INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return a list of parts related to this one via reltype.
def related(self, reltype): """Return a list of parts related to this one via reltype.""" parts = [] package = getattr(self, 'package', None) or self for rel in self.relationships.types.get(reltype, []): parts.append(package[posixpath.join(self.base, rel.target)]) return parts
Load relationships from source XML.
def _load_rels(self, source): """Load relationships from source XML.""" # don't get confused here - the original source is string data; # the parameter source below is a Part object self.relationships.load(source=self, data=source)
Add a part to the package.
def add(self, part, override=True): """Add a part to the package. It will also add a content-type - by default an override. If override is False then it will add a content-type for the extension if one isn't already present. """ ct_add_method = [ self.content_types.add_default, self.content_types.ad...
Load a part into this package based on its relationship type
def _load_part(self, rel_type, name, data): """ Load a part into this package based on its relationship type """ if self.content_types.find_for(name) is None: log.warning('no content type found for part %(name)s' % vars()) return cls = Part.classes_by_rel_type[rel_type] part = cls(self, name) part.l...
Return all parts of this package that are instances of cls ( where cls is passed directly to isinstance so can be a class or sequence of classes ).
def get_parts_by_class(self, cls): """ Return all parts of this package that are instances of cls (where cls is passed directly to isinstance, so can be a class or sequence of classes). """ return (part for part in self.parts.values() if isinstance(part, cls))
Get the correct content type for a given name
def find_for(self, name): """ Get the correct content type for a given name """ map = self.items # first search the overrides (by name) # then fall back to the defaults (by extension) # finally, return None if unmatched return map.get(name, None) or map.get(get_ext(name) or None, None)
given an element parse out the proper ContentType
def from_element(cls, element): "given an element, parse out the proper ContentType" # disambiguate the subclass ns, class_name = parse_tag(element.tag) class_ = getattr(ContentType, class_name) if not class_: msg = 'Invalid Types child element: %(class_name)s' % vars() raise ValueError(msg) # constru...
Parses the given DSL string and returns parsed results.
def parse(input_string, prefix=''): """Parses the given DSL string and returns parsed results. Args: input_string (str): DSL string prefix (str): Optional prefix to add to every element name, useful to namespace things Returns: dict: Parsed content """ tree = parser.parse(input_string) visit...
Builds a final copy of the token using the given secret key.
def build(self, secret_key): """Builds a final copy of the token using the given secret key. :param secret_key(string): The secret key that corresponds to this builder's access key. """ key = jwk.JWK( kty='oct', k=base64url_encode(uuid.UUID(secret_key).bytes), ...
Assigns force field parameters to Atoms in the AMPAL object.
def assign_force_field(ampal_obj, ff): """Assigns force field parameters to Atoms in the AMPAL object. Parameters ---------- ampal_obj : AMPAL Object Any AMPAL object with a `get_atoms` method. ff: BuffForceField The force field to be used for scoring. """ if hasattr(ampal_o...
Finds the maximum radius and npnp in the force field.
def find_max_rad_npnp(self): """Finds the maximum radius and npnp in the force field. Returns ------- (max_rad, max_npnp): (float, float) Maximum radius and npnp distance in the loaded force field. """ max_rad = 0 max_npnp = 0 for res, _ in se...
Makes a dictionary containing PyAtomData for the force field.
def _make_ff_params_dict(self): """Makes a dictionary containing PyAtomData for the force field. Returns ------- ff_params_struct_dict: dict Dictionary containing PyAtomData structs for the force field parameters for each atom in the force field. """ ...
Save this package to target which should be a filename or open file stream. If target is not supplied and this package has a filename attribute ( such as when this package was created from an existing file ) it will be used.
def save(self, target=None): """ Save this package to target, which should be a filename or open file stream. If target is not supplied, and this package has a filename attribute (such as when this package was created from an existing file), it will be used. """ target = target or getattr(self, 'filename'...
Return a zipped package as a readable stream
def as_stream(self): """ Return a zipped package as a readable stream """ stream = io.BytesIO() self._store(stream) stream.seek(0) return stream
Return a generator yielding each of the segments who s names match name.
def _get_matching_segments(self, zf, name): """ Return a generator yielding each of the segments who's names match name. """ for n in zf.namelist(): if n.startswith(name): yield zf.read(n)
Copy objects from one directory in a bucket to another directory in the same bucket.
def copy_dir(bucket_name, src_path, dest_path, aws_access_key_id=None, aws_secret_access_key=None, aws_profile=None, surrogate_key=None, cache_control=None, surrogate_control=None, create_directory_redirect_object=True): """Copy objects from one direc...
Open an S3 Bucket resource.
def open_bucket(bucket_name, aws_access_key_id=None, aws_secret_access_key=None, aws_profile=None): """Open an S3 Bucket resource. Parameters ---------- bucket_name : `str` Name of the S3 bucket. aws_access_key_id : `str`, optional The access key for ...
Upload a directory of files to S3.
def upload_dir(bucket_name, path_prefix, source_dir, upload_dir_redirect_objects=True, surrogate_key=None, surrogate_control=None, cache_control=None, acl=None, aws_access_key_id=None, aws_secret_access_key=None, aws_profile=None)...
Upload a file to the S3 bucket.
def upload_file(local_path, bucket_path, bucket, metadata=None, acl=None, cache_control=None): """Upload a file to the S3 bucket. This function uses the mimetypes module to guess and then set the Content-Type and Encoding-Type headers. Parameters ---------- local_path : `str` ...
Upload an arbitrary object to an S3 bucket.
def upload_object(bucket_path, bucket, content='', metadata=None, acl=None, cache_control=None, content_type=None): """Upload an arbitrary object to an S3 bucket. Parameters ---------- bucket_path : `str` Destination path (also known as the key name) of the f...
Create an S3 object representing a directory that s designed to redirect a browser ( via Fastly ) to the index. html contained inside that directory.
def create_dir_redirect_object(bucket_dir_path, bucket, metadata=None, acl=None, cache_control=None): """Create an S3 object representing a directory that's designed to redirect a browser (via Fastly) to the ``index.html`` contained inside that directory. Parameters -...
List all file - type object names that exist at the root of this bucket directory.
def list_filenames_in_directory(self, dirname): """List all file-type object names that exist at the root of this bucket directory. Parameters ---------- dirname : `str` Directory name in the bucket relative to ``bucket_root/``. Returns ------- ...
List all names of directories that exist at the root of this bucket directory.
def list_dirnames_in_directory(self, dirname): """List all names of directories that exist at the root of this bucket directory. Note that *directories* don't exist in S3; rather directories are inferred from path names. Parameters ---------- dirname : `str` ...
Make an absolute directory path in the bucker for dirname which is is assumed relative to the self. _bucket_root prefix directory.
def _create_prefix(self, dirname): """Make an absolute directory path in the bucker for dirname, which is is assumed relative to the self._bucket_root prefix directory. """ if dirname in ('.', '/'): dirname = '' # Strips trailing slash from dir prefix for comparisons ...
Delete a file from the bucket.
def delete_file(self, filename): """Delete a file from the bucket. Parameters ---------- filename : `str` Name of the file, relative to ``bucket_root/``. """ key = os.path.join(self._bucket_root, filename) objects = list(self._bucket.objects.filter(Pr...
Delete a directory ( and contents ) from the bucket.
def delete_directory(self, dirname): """Delete a directory (and contents) from the bucket. Parameters ---------- dirname : `str` Name of the directory, relative to ``bucket_root/``. Raises ------ RuntimeError Raised when there are no obje...
Ensure a token is in the Click context object or authenticate and obtain the token from LTD Keeper.
def ensure_login(ctx): """Ensure a token is in the Click context object or authenticate and obtain the token from LTD Keeper. Parameters ---------- ctx : `click.Context` The Click context. ``ctx.obj`` must be a `dict` that contains keys: ``keeper_hostname``, ``username``, ``password...
Speak loudly! FIVE! Use upper case!
def loud(self, lang='englist'): """Speak loudly! FIVE! Use upper case!""" lang_method = getattr(self, lang, None) if lang_method: return lang_method().upper() else: return self.english().upper()
Replaced by a letter 5 right shift. e. g. a - > f b - > g. - >.
def rotate(self, word): """Replaced by a letter 5 right shift. e.g. a->f, b->g, . -> .""" before = string.printable[:62] after = ''.join([i[5:] + i[:5] for i in [string.digits, string.ascii_lowercase, ...
Delete all objects in the S3 bucket named bucket_name that are found in the root_path directory.
def delete_dir(bucket_name, root_path, aws_access_key_id=None, aws_secret_access_key=None, aws_profile=None): """Delete all objects in the S3 bucket named ``bucket_name`` that are found in the ``root_path`` directory. Parameters ---------- bucket_name : `str` N...
Get project s home URL based on settings. PROJECT_HOME_NAMESPACE.
def home_url(): """Get project's home URL based on settings.PROJECT_HOME_NAMESPACE. Returns None if PROJECT_HOME_NAMESPACE is not defined in settings. """ try: return reverse(home_namespace) except Exception: url = home_namespace try: validate_url = URLValidator(...
Decorator to silence template tags if PROJECT_HOME_NAMESPACE is not defined in settings.
def silence_without_namespace(f): """Decorator to silence template tags if 'PROJECT_HOME_NAMESPACE' is not defined in settings. Usage Example: from django import template register = template.Library() @register.simple_tag @silence_without_namespace def a_template_...
A template tag to return the project s home URL and label formatted as a Bootstrap 3 breadcrumb.
def project_home_breadcrumb_bs3(label): """A template tag to return the project's home URL and label formatted as a Bootstrap 3 breadcrumb. PROJECT_HOME_NAMESPACE must be defined in settings, for example: PROJECT_HOME_NAMESPACE = 'project_name:index_view' Usage Example: {% load project...
A template tag to return the project s home URL and label formatted as a Bootstrap 4 breadcrumb.
def project_home_breadcrumb_bs4(label): """A template tag to return the project's home URL and label formatted as a Bootstrap 4 breadcrumb. PROJECT_HOME_NAMESPACE must be defined in settings, for example: PROJECT_HOME_NAMESPACE = 'project_name:index_view' Usage Example: {% load project...
Arggh matey
def pm(client, event, channel, nick, rest): 'Arggh matey' if rest: rest = rest.strip() Karma.store.change(rest, 2) rcpt = rest else: rcpt = channel if random.random() > 0.95: return f"Arrggh ye be doin' great, grand work, {rcpt}!" return f"Arrggh ye be doin' ...
Rico Suave
def lm(client, event, channel, nick, rest): 'Rico Suave' if rest: rest = rest.strip() Karma.store.change(rest, 2) rcpt = rest else: rcpt = channel return f'¡Estás haciendo un buen trabajo, {rcpt}!'
pmxbot parle français
def fm(client, event, channel, nick, rest): 'pmxbot parle français' if rest: rest = rest.strip() Karma.store.change(rest, 2) rcpt = rest else: rcpt = channel return f'Vous bossez bien, {rcpt}!'
Zor supas! — !زۆر سوپاس
def zorsupas(client, event, channel, nick, rest): 'Zor supas! — !زۆر سوپاس' if rest: rest = rest.strip() Karma.store.change(rest, 1) rcpt = rest else: rcpt = channel return ( f'Zor supas {rcpt}, to zor zor barezi! —' ' زۆر سوپاس، تۆ زۆر زۆر به‌ره‌زی' )
Danke schön!
def danke(client, event, channel, nick, rest): 'Danke schön!' if rest: rest = rest.strip() Karma.store.change(rest, 1) rcpt = rest else: rcpt = channel return f'Danke schön, {rcpt}! Danke schön!'
schneier facts
def schneier(client, event, channel, nick, rest): 'schneier "facts"' rcpt = rest.strip() or channel if rest.strip(): Karma.store.change(rcpt, 2) url = 'https://www.schneierfacts.com/' d = requests.get(url).text start_tag = re.escape('<p class="fact">') end_tag = re.escape('</p>') ...
Calculates the interaction energy between AMPAL objects.
def get_interaction_energy(ampal_objs, ff=None, assign_ff=True): """Calculates the interaction energy between AMPAL objects. Parameters ---------- ampal_objs: [AMPAL Object] A list of any AMPAL objects with `get_atoms` methods. ff: BuffForceField, optional The force field to be used...
Calculates the internal energy of the AMPAL object.
def get_internal_energy(ampal_obj, ff=None, assign_ff=True): """Calculates the internal energy of the AMPAL object. Parameters ---------- ampal_obj: AMPAL Object Any AMPAL object with a `get_atoms` method. ff: BuffForceField, optional The force field to be used for scoring. If no fo...
Get sample counts by file and root thread function. ( Useful for answering quesitons like what modules are hot? )
def rooted_samples_by_file(self): ''' Get sample counts by file, and root thread function. (Useful for answering quesitons like "what modules are hot?") ''' rooted_leaf_samples, _ = self.live_data_copy() rooted_file_samples = {} for root, counts in rooted_leaf_sam...
Get sample counts by line and root thread function. ( For one file specified as a parameter. ) This is useful for generating side - by - side views of source code and samples.
def rooted_samples_by_line(self, filename): ''' Get sample counts by line, and root thread function. (For one file, specified as a parameter.) This is useful for generating "side-by-side" views of source code and samples. ''' rooted_leaf_samples, _ = self.live_dat...
Get lines sampled accross all threads in order from most to least sampled.
def hotspots(self): ''' Get lines sampled accross all threads, in order from most to least sampled. ''' rooted_leaf_samples, _ = self.live_data_copy() line_samples = {} for _, counts in rooted_leaf_samples.items(): for key, count in counts.items(): ...
return sampled stacks in form suitable for inclusion in a flame graph ( https:// github. com/ brendangregg/ FlameGraph )
def flame_map(self): ''' return sampled stacks in form suitable for inclusion in a flame graph (https://github.com/brendangregg/FlameGraph) ''' flame_map = {} _, stack_counts = self.live_data_copy() for stack, count in stack_counts.items(): root = stac...
Get a temporary auth token from LTD Keeper.
def get_keeper_token(host, username, password): """Get a temporary auth token from LTD Keeper. Parameters ---------- host : `str` Hostname of the LTD Keeper API (e.g., ``'https://keeper.lsst.codes'``). username : `str` Username. password : `str` Password. Returns ...
Upload a new site build to LSST the Docs.
def upload(ctx, product, git_ref, dirname, aws_id, aws_secret, ci_env, on_travis_push, on_travis_pr, on_travis_api, on_travis_cron, skip_upload): """Upload a new site build to LSST the Docs. """ logger = logging.getLogger(__name__) if skip_upload: click.echo('Skipping ltd ...
Detect if the upload should be skipped based on the TRAVIS_EVENT_TYPE environment variable.
def _should_skip_travis_event(on_travis_push, on_travis_pr, on_travis_api, on_travis_cron): """Detect if the upload should be skipped based on the ``TRAVIS_EVENT_TYPE`` environment variable. Returns ------- should_skip : `bool` True if the upload should be skip...
Instant purge URLs with a given surrogate key from the Fastly caches.
def purge_key(surrogate_key, service_id, api_key): """Instant purge URLs with a given surrogate key from the Fastly caches. Parameters ---------- surrogate_key : `str` Surrogate key header (``x-amz-meta-surrogate-key``) value of objects to purge from the Fastly cache. service_id : `...
Register a new build for a product on LSST the Docs.
def register_build(host, keeper_token, product, git_refs): """Register a new build for a product on LSST the Docs. Wraps ``POST /products/{product}/builds/``. Parameters ---------- host : `str` Hostname of LTD Keeper API server. keeper_token : `str` Auth token (`ltdconveyor.kee...
Confirm a build upload is complete.
def confirm_build(build_url, keeper_token): """Confirm a build upload is complete. Wraps ``PATCH /builds/{build}``. Parameters ---------- build_url : `str` URL of the build resource. Given a build resource, this URL is available from the ``self_url`` field. keeper_token : `str`...
Deeply updates a dictionary. List values are concatenated.
def deep_update(d, u): """Deeply updates a dictionary. List values are concatenated. Args: d (dict): First dictionary which will be updated u (dict): Second dictionary use to extend the first one Returns: dict: The merge dictionary """ for k, v in u.items(): if isinstance(v, Mapping): ...
ltd is a command - line client for LSST the Docs.
def main(ctx, log_level, keeper_hostname, username, password): """ltd is a command-line client for LSST the Docs. Use ltd to upload new site builds, and to work with the LTD Keeper API. """ ch = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s %(levelname)8s %(name)s | %(...
Edit a part from an OOXML Package without unzipping it
def part_edit_cmd(): 'Edit a part from an OOXML Package without unzipping it' parser = argparse.ArgumentParser(description=inspect.getdoc(part_edit_cmd)) parser.add_argument( 'path', help='Path to part (including path to zip file, i.e. ./file.zipx/part)', ) parser.add_argument( '--reformat-xml', action='st...
List the contents of a subdirectory of a zipfile
def pack_dir_cmd(): 'List the contents of a subdirectory of a zipfile' parser = argparse.ArgumentParser(description=inspect.getdoc(part_edit_cmd)) parser.add_argument( 'path', help=( 'Path to list (including path to zip file, ' 'i.e. ./file.zipx or ./file.zipx/subdir)' ), ) args = parser.parse_args() ...
recursively call os. path. split until we have all of the components of a pathname suitable for passing back to os. path. join.
def split_all(path): """ recursively call os.path.split until we have all of the components of a pathname suitable for passing back to os.path.join. """ drive, path = os.path.splitdrive(path) head, tail = os.path.split(path) terminators = [os.path.sep, os.path.altsep, ''] parts = split_all(head) if head not in ...
Given a path to a part in a zip file return a path to the file and the path to the part.
def find_file(path): """ Given a path to a part in a zip file, return a path to the file and the path to the part. Assuming /foo.zipx exists as a file, >>> find_file('/foo.zipx/dir/part') # doctest: +SKIP ('/foo.zipx', '/dir/part') >>> find_file('/foo.zipx') # doctest: +SKIP ('/foo.zipx', '') """ path_comp...
Give preference to an XML_EDITOR or EDITOR defined in the environment. Otherwise use notepad on Windows and edit on other platforms.
def get_editor(filepath): """ Give preference to an XML_EDITOR or EDITOR defined in the environment. Otherwise use notepad on Windows and edit on other platforms. """ default_editor = ['edit', 'notepad'][sys.platform.startswith('win32')] return os.environ.get( 'XML_EDITOR', os.environ.get('EDITOR', ...
return ( user seckey ) if url end point is in allowed entry point list
def permission_check(apikey, endpoint): """ return (user, seckey) if url end point is in allowed entry point list """ try: ak = APIKeys.objects.get(apikey=apikey) apitree = cPickle.loads(ak.apitree.encode("ascii")) if apitree.match(endpoint): ...
Process the astroid node stream.
def process_module(self, node): """Process the astroid node stream.""" if self.config.file_header: if sys.version_info[0] < 3: pattern = re.compile( '\A' + self.config.file_header, re.LOCALE | re.MULTILINE) else: # The use of re...
Generates an html chart from either a pandas dataframe a dictionnary a list or an Altair Data object and optionally write it to a file
def gen(self, slug, name, dataobj, xfield, yfield, time_unit=None, chart_type="line", width=800, height=300, color=Color(), size=Size(), scale=Scale(zero=False), shape=Shape(), filepath=None, html_before="", html_after=""): """ Generates an html chart from...
Generate html from an Altair chart object and optionally write it to a file
def html(self, slug, name, chart_obj, filepath=None, html_before="", html_after=""): """ Generate html from an Altair chart object and optionally write it to a file """ try: html = "" if name: html = "<h3>" + name + "</h3>" ...
Serialize to an Altair chart object from either a pandas dataframe a dictionnary a list or an Altair Data object
def serialize(self, dataobj, xfield, yfield, time_unit=None, chart_type="line", width=800, height=300, color=None, size=None, scale=Scale(zero=False), shape=None, options={}): """ Serialize to an Altair chart object from either a pandas dataframe, a ...
Patch the Altair generated json to the newest Vega Lite spec
def _patch_json(self, json_data): """ Patch the Altair generated json to the newest Vega Lite spec """ json_data = json.loads(json_data) # add schema json_data["$schema"] = "https://vega.github.io/schema/vega-lite/2.0.0-beta.15.json" # add top level width and heig...
Generates html from Vega lite data
def _json_to_html(self, slug, json_data): """ Generates html from Vega lite data """ html = '<div id="chart-' + slug + '"></div>' html += '<script>' html += 'var s' + slug + ' = ' + json_data + ';' html += 'vega.embed("#chart-' + slug + '", s' + slug + ');' ...
Converts a dictionnary to a pandas dataframe
def _dict_to_df(self, dictobj, xfield, yfield): """ Converts a dictionnary to a pandas dataframe """ x = [] y = [] for datapoint in dictobj: x.append(datapoint) y.append(dictobj[datapoint]) df = pd.DataFrame({xfield[0]: x, yfield[0]: y}) ...
Writes a chart s html to a file
def _write_file(self, slug, folderpath, html): """ Writes a chart's html to a file """ # check directories if not os.path.isdir(folderpath): try: os.makedirs(folderpath) except Exception as e: tr.err(e) # construct ...
Get the right chart class from a string
def _chart_class(self, df, chart_type, **kwargs): """ Get the right chart class from a string """ if chart_type == "bar": return Chart(df).mark_bar(**kwargs) elif chart_type == "circle": return Chart(df).mark_circle(**kwargs) elif chart_type == "li...
Encode the fields in Altair format
def _encode_fields(self, xfield, yfield, time_unit=None, scale=Scale(zero=False)): """ Encode the fields in Altair format """ if scale is None: scale = Scale() xfieldtype = xfield[1] yfieldtype = yfield[1] x_options = None ...
Link to a GitHub user.
def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to a GitHub user. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :param name: The role name used in the document. :par...
Returns the tarball URL inferred from an app. json if present.
def _infer_tarball_url(): """Returns the tarball URL inferred from an app.json, if present.""" try: with click.open_file('app.json', 'r') as f: contents = f.read() app_json = json.loads(contents) except IOError: return None repository = app_json.get('repository') ...
Brings up a Heroku app.
def up(tarball_url, auth_token, env, app_name): """Brings up a Heroku app.""" tarball_url = tarball_url or _infer_tarball_url() if not tarball_url: click.echo('No tarball URL found.') sys.exit(1) if env: # Split ["KEY=value", ...] into {"KEY": "value", ...} env = { ...
Brings down a Heroku app.
def down(auth_token, force, app_name): """Brings down a Heroku app.""" if not app_name: click.echo( 'WARNING: Inferring the app name when deleting is deprecated. ' 'Starting with happy 2.0, the app_name parameter will be required.' ) app_name = app_name or _read_app_...
Decorator implementing Iterator interface with nicer manner.
def iter_attribute(iterable_name) -> Union[Iterable, Callable]: """Decorator implementing Iterator interface with nicer manner. Example ------- @iter_attribute('my_attr'): class DecoratedClass: ... Warning: ======== When using PyCharm or MYPY you'll probably see issues with d...
check: 1 timestamp in reasonable range 2 api key exists 3 entry point allowed for this api key 4 signature correctness
def api_auth(function=None): """ check: 1, timestamp in reasonable range 2, api key exists 3, entry point allowed for this api key 4, signature correctness effect: - add user object in request if the api key is binding with an user """ def real_decorator(func): def wrapp...
returns a random ( fixed length ) string
def text(length, choices=string.ascii_letters): """ returns a random (fixed length) string :param length: string length :param choices: string containing all the chars can be used to build the string .. seealso:: :py:func:`rtext` """ return ''.join(choice(choices) for x in range(length)...
returns a random ( variable length ) string.
def rtext(maxlength, minlength=1, choices=string.ascii_letters): """ returns a random (variable length) string. :param maxlength: maximum string length :param minlength: minimum string length :param choices: string containing all the chars can be used to build the string .. seealso...
returns a a random string that represent a binary representation
def binary(length): """ returns a a random string that represent a binary representation :param length: number of bits """ num = randint(1, 999999) mask = '0' * length return (mask + ''.join([str(num >> i & 1) for i in range(7, -1, -1)]))[-length:]
returns a string representing a random ip address
def ipaddress(not_valid=None): """ returns a string representing a random ip address :param not_valid: if passed must be a list of integers representing valid class A netoworks that must be ignored """ not_valid_class_A = not_valid or [] class_a = [r for r in range(1, 256) if r not in not_...
returns a: class: netaddr. IPAddress instance with a random value
def ip(private=True, public=True, max_attempts=10000): """ returns a :class:`netaddr.IPAddress` instance with a random value :param private: if False does not return private networks :param public: if False does not return public networks :param max_attempts: """ if not (private or pub...
Get a random date between two dates
def date(start, end): """Get a random date between two dates""" stime = date_to_timestamp(start) etime = date_to_timestamp(end) ptime = stime + random.random() * (etime - stime) return datetime.date.fromtimestamp(ptime)
Returns a prepared Session instance.
def _get_session(self): """Returns a prepared ``Session`` instance.""" session = Session() session.headers = { 'Content-type': 'application/json', 'Accept': 'application/vnd.heroku+json; version=3', } if self._auth_token: session.trust_env = ...
Sends an API request to Heroku.
def api_request(self, method, endpoint, data=None, *args, **kwargs): """Sends an API request to Heroku. :param method: HTTP method. :param endpoint: API endpoint, e.g. ``/apps``. :param data: A dict sent as JSON in the body of the request. :returns: A dict represntation of the J...
Creates an app - setups build. Returns response data as a dict.
def create_build(self, tarball_url, env=None, app_name=None): """Creates an app-setups build. Returns response data as a dict. :param tarball_url: URL of a tarball containing an ``app.json``. :param env: Dict containing environment variable overrides. :param app_name: Name of the Heroku...
Checks the status of an app - setups build.
def check_build_status(self, build_id): """Checks the status of an app-setups build. :param build_id: ID of the build to check. :returns: ``True`` if succeeded, ``False`` if pending. """ data = self.api_request('GET', '/app-setups/%s' % build_id) status = data.get('stat...
generator that returns an unique string
def sequence(prefix, cache=None): """ generator that returns an unique string :param prefix: prefix of string :param cache: cache used to store the last used number >>> next(sequence('abc')) 'abc-0' >>> next(sequence('abc')) 'abc-1' """ if cache is None: cache = _sequen...
Used internally by memoize decorator to get/ store function results
def _get_memoized_value(func, args, kwargs): """Used internally by memoize decorator to get/store function results""" key = (repr(args), repr(kwargs)) if not key in func._cache_dict: ret = func(*args, **kwargs) func._cache_dict[key] = ret return func._cache_dict[key]
Decorator that stores function results in a dictionary to be used on the next time that the same arguments were informed.
def memoize(func): """Decorator that stores function results in a dictionary to be used on the next time that the same arguments were informed.""" func._cache_dict = {} @wraps(func) def _inner(*args, **kwargs): return _get_memoized_value(func, args, kwargs) return _inner
wraps a function so that produce unique results
def unique(func, num_args=0, max_attempts=100, cache=None): """ wraps a function so that produce unique results :param func: :param num_args: >>> import random >>> choices = [1,2] >>> a = unique(random.choice, 1) >>> a,b = a(choices), a(choices) >>> a == b False """ if ...
Add any sub commands to the argument parser.
def register_sub_commands(self, parser): """ Add any sub commands to the argument parser. :param parser: The argument parser object """ sub_commands = self.get_sub_commands() if sub_commands: sub_parsers = parser.add_subparsers(dest=self.sub_parser_dest_name)...
Gets the root argument parser object.
def get_root_argparser(self): """ Gets the root argument parser object. """ return self.arg_parse_class(description=self.get_help(), formatter_class=self.get_formatter_class())
Gets the description of the command. If its not supplied the first sentence of the doc string is used.
def get_description(self): """ Gets the description of the command. If its not supplied the first sentence of the doc string is used. """ if self.description: return self.description elif self.__doc__ and self.__doc__.strip(): return self.__doc__.strip().s...
Gets the help text for the command. If its not supplied the doc string is used.
def get_help(self): """ Gets the help text for the command. If its not supplied the doc string is used. """ if self.help: return self.help elif self.__doc__ and self.__doc__.strip(): return self.__doc__.strip() else: return ''
Runs the command passing in the parsed arguments.
def run(self, args=None): """ Runs the command passing in the parsed arguments. :param args: The arguments to run the command with. If ``None`` the arguments are gathered from the argument parser. This is automatically set when calling sub commands and in most cases shou...
userfileter: when binding api key with user filter some users if necessary
def get_api_key_form(userfilter={}): """ userfileter: when binding api key with user, filter some users if necessary """ class APIKeyForm(ModelForm): class Meta: model = APIKeys exclude = ("apitree",) user = forms.ModelChoiceField(queryset=get_user_model().objects...
Encode wrapper for a dataset with maximum value
def encode(self, *args, **kwargs): """Encode wrapper for a dataset with maximum value Datasets can be one or two dimensional Strings are ignored as ordinal encoding""" if isinstance(args[0], str): return self.encode([args[0]],**kwargs) elif isinstance(args[0], int) ...
Get all available athletes This method is cached to prevent unnecessary calls to GC.
def get_athletes(self): """Get all available athletes This method is cached to prevent unnecessary calls to GC. """ response = self._get_request(self.host) response_buffer = StringIO(response.text) return pd.read_csv(response_buffer)
Get all activity data for the last activity
def get_last_activities(self, n): """Get all activity data for the last activity Keyword arguments: """ filenames = self.get_activity_list().iloc[-n:].filename.tolist() last_activities = [self.get_activity(f) for f in filenames] return last_activities
Actually do the request for activity list This call is slow and therefore this method is memory cached.
def _request_activity_list(self, athlete): """Actually do the request for activity list This call is slow and therefore this method is memory cached. Keyword arguments: athlete -- Full name of athlete """ response = self._get_request(self._athlete_endpoint(athlete)) ...