text
stringlengths
81
112k
Get the status for a package. def _get_package_status(package): """Get the status for a package.""" status = package["status_str"] or "Unknown" stage = package["stage_str"] or "Unknown" if stage == "Fully Synchronised": return status return "%(status)s / %(stage)s" % {"status": status, "sta...
Convert a number, string, or sequence type into a pure boolean. Args: value (number, string, sequence): pretty much anything Returns: bool: boolean representation of the given value Examples: >>> [boolify(x) for x in ('yes', 'no')] [True, False] >>> [boolify(x) for...
Take a primitive value, usually a string, and try to make a more relevant type out of it. An optional type_hint will try to coerce the value to that type. Args: value (Any): Usually a string, not a sequence type_hint (type or Tuple[type]): Examples: >>> typify('32') 32 ...
Examples: >>> listify('abc', return_type=list) ['abc'] >>> listify(None) () >>> listify(False) (False,) >>> listify(('a', 'b', 'c'), return_type=list) ['a', 'b', 'c'] def listify(val, return_type=tuple): """ Examples: >>> listify('abc', re...
open(rootdir, mode='a') Open a disk-based carray/ctable. This function could be used to open bcolz objects as bquery objects to perform queries on them. Parameters ---------- rootdir : pathname (string) The directory hosting the carray/ctable object. mode : the open mode (string) ...
Delete a package from a repository. - OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the REPO name where the package is stored, and the PACKAGE name (slug) of the package itself. All separated by a slash. Example: 'your-org/awesome-repo/better-pkg'. def delete(ctx, opts, owner_...
Ensure that owner/repo/identifier is formatted correctly. def validate_owner_repo_identifier(ctx, param, value): """Ensure that owner/repo/identifier is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO/IDENTIFIER" return validators.validate_slashes(param, value, minimum=3, m...
Add common options for entitlement commands. def common_entitlements_options(f): """Add common options for entitlement commands.""" @click.option( "--show-tokens", default=False, is_flag=True, help="Show entitlement token string contents in output.", ) @click.pass_conte...
Options for list entitlements subcommand. def list_entitlements_options(f): """Options for list entitlements subcommand.""" @common_entitlements_options @decorators.common_cli_config_options @decorators.common_cli_list_options @decorators.common_cli_output_options @decorators.common_api_auth_o...
List entitlements for a repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to list entitlements for. All separated by a slash. Example: 'your-org/your-repo' Full CLI example: $ cloudsmith ents list your-org/your-repo def list_entit...
Print entitlements as a table or output in another format. def print_entitlements(opts, data, page_info=None, show_list_info=True): """Print entitlements as a table or output in another format.""" if utils.maybe_print_as_json(opts, data, page_info): return headers = ["Name", "Token", "Created / Up...
Create a new entitlement in a repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to create an entitlement. All separated by a slash. Example: 'your-org/your-repo' Full CLI example: $ cloudsmith ents create your-org/your-repo --name ...
Delete an entitlement from a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ...
Update (set) a entitlement in a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmi...
Refresh an entitlement in a repository. Note that this changes the token associated with the entitlement. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-o...
Sync entitlements from another repository. ***WARNING*** This will DELETE ALL of the existing entitlements in the repository and replace them with entitlements from the source repository. - OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO name where you want to sync entitleme...
Counts the time spent in some context def ctime(message=None): "Counts the time spent in some context" t = time.time() yield if message: print message + ":\t", print round(time.time() - t, 4), "sec"
Optionally pause the process based on suggested rate interval. def maybe_rate_limit(client, headers, atexit=False): """Optionally pause the process based on suggested rate interval.""" # pylint: disable=fixme # pylint: disable=global-statement # FIXME: Yes, I know this is not great. We'll fix it later....
Pause the process based on suggested rate interval. def rate_limit(client, headers, atexit=False): """Pause the process based on suggested rate interval.""" if not client or not headers: return False if not getattr(client.config, "rate_limit", False): return False rate_info = RateLimi...
Retrieve status (and optionally) version from the API. def get_status(with_version=False): """Retrieve status (and optionally) version from the API.""" client = get_status_api() with catch_raise_api_exception(): data, _, headers = client.status_check_basic_with_http_info() ratelimits.maybe_ra...
Give the first value that satisfies the key test. Args: seq (iterable): key (callable): test for each element of iterable default: returned when all elements fail test apply (callable): applied to element before return, but not to default value Returns: first element in seq tha...
Calls each element of sequence to invoke the side effect. Args: seq: Returns: None def call_each(seq): """Calls each element of sequence to invoke the side effect. Args: seq: Returns: None """ try: reduce(lambda _, y: y(), seq) except TypeError as e: ...
Transform a username:password value into a base64 string. def transform_api_header_authorization(param, value): """Transform a username:password value into a base64 string.""" try: username, password = value.split(":", 1) except ValueError: raise click.BadParameter( "Authorizati...
Validate that API headers is a CSV of k=v pairs. def validate_api_headers(param, value): """Validate that API headers is a CSV of k=v pairs.""" # pylint: disable=unused-argument if not value: return None headers = {} for kv in value.split(","): try: k, v = kv.split("=",...
Ensure that parameter has slashes and minimum parts. def validate_slashes(param, value, minimum=2, maximum=None, form=None): """Ensure that parameter has slashes and minimum parts.""" try: value = value.split("/") except ValueError: value = None if value: if len(value) < minimu...
Ensure that owner/repo is formatted correctly. def validate_owner_repo(ctx, param, value): """Ensure that owner/repo is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO" return validate_slashes(param, value, minimum=2, maximum=2, form=form)
Ensure that owner/repo/package is formatted correctly. def validate_owner_repo_package(ctx, param, value): """Ensure that owner/repo/package is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO/PACKAGE" return validate_slashes(param, value, minimum=3, maximum=3, form=form)
Ensure that owner/repo/distro/version is formatted correctly. def validate_owner_repo_distro(ctx, param, value): """Ensure that owner/repo/distro/version is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO/DISTRO[/RELEASE]" return validate_slashes(param, value, minimum=3, ma...
Ensure that a valid value for page is chosen. def validate_page(ctx, param, value): """Ensure that a valid value for page is chosen.""" # pylint: disable=unused-argument if value == 0: raise click.BadParameter( "Page is not zero-based, please set a value to 1 or higher.", param=param ...
Ensure that a valid value for page size is chosen. def validate_page_size(ctx, param, value): """Ensure that a valid value for page size is chosen.""" # pylint: disable=unused-argument if value == 0: raise click.BadParameter("Page size must be non-zero or unset.", param=param) return value
Get Account Asset Balance API Type -------- HTTP Private API Docs ---- https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance def getbalance(self, **params): """Get Account Asset Balance API Type -------- HTTP Private API ...
removes all overridden and inherited variables from hosts and groups def tidy_all_the_variables(host, inventory_mgr): ''' removes all overridden and inherited variables from hosts and groups ''' global _vars _vars = dict() _vars[host] = inventory_mgr.inventory.get_host_vars(host) fo...
merges all entities by inventory source def _plugins_inventory(self, entities): import os from ansible.plugins.loader import vars_loader from ansible.utils.vars import combine_vars ''' merges all entities by inventory source ''' data = {} for inventory_dir in self.variab...
gets data from WordPress site def handle(self, *args, **options): """gets data from WordPress site""" # TODO: refactor these with .get if 'username' in options: self.username = options['username'] else: self.username = None if 'password' in options: ...
create Image objects and transfer image files to media root def create_images_from_urls_in_content(self, body): """create Image objects and transfer image files to media root""" soup = BeautifulSoup(body, "html5lib") for img in soup.findAll('img'): old_url = img['src'] i...
Returns Django comment object with this wordpress id def lookup_comment_by_wordpress_id(self, comment_id, comments): """ Returns Django comment object with this wordpress id """ for comment in comments: if comment.wordpress_id == comment_id: return comment
create Blog post entries from wordpress data def create_blog_pages(self, posts, blog_index, *args, **options): """create Blog post entries from wordpress data""" for post in posts: post_id = post.get('ID') title = post.get('title') if title: new_title...
Calculates and stores a unique slug of ``value`` for an instance. ``slug_field_name`` should be a string matching the name of the field to store the slug in (and the field to check against for uniqueness). ``queryset`` usually doesn't need to be explicitly provided - it'll default to using the ``.all(...
Cleans up a slug by removing slug separator characters that occur at the beginning or end of a slug. If an alternate separator is used, it will also replace any instances of the default '-' separator with the new separator. def _slug_strip(value, separator='-'): """ Cleans up a slug by removing sl...
Limit choices in blog author field based on config settings def limit_author_choices(): """ Limit choices in blog author field based on config settings """ LIMIT_AUTHOR_CHOICES = getattr(settings, 'BLOG_LIMIT_AUTHOR_CHOICES_GROUP', None) if LIMIT_AUTHOR_CHOICES: if isinstance(LIMIT_AUTHOR_CHOICES, ...
Get context data useful on all blog related pages def get_blog_context(context): """ Get context data useful on all blog related pages """ context['authors'] = get_user_model().objects.filter( owned_pages__live=True, owned_pages__content_type__model='blogpage' ).annotate(Count('owned_pages'...
changes the xmlns (XML namespace) so that values are replaced with the string representation of their key this makes the import process for portable >>> xp = XML_parser >>> test_xmlns = r'<rss version="2.0" xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/">' >>> xp.remove...
create a default dict of values, including category and tag lookup def item_dict(self, item): """ create a default dict of values, including category and tag lookup """ # mocking wierd JSON structure ret_dict = {"terms":{"category":[],"post_tag":[]}} for ...
for whatever reason, sometimes WP XML has unintelligible datetime strings for pubDate. In this case default to custom_date_string or today Use fallback in case a secondary date string is available. Incidentally, somehow the string 'Mon, 30 Nov -0001 00:00:00 +0000' shows up. ...
cleanup item keys to match API json format def translate_item(self, item_dict): """cleanup item keys to match API json format""" if not item_dict.get('title'): return None # Skip attachments if item_dict.get('{wp}post_type', None) == 'attachment': return None ...
<wp:comment> <wp:comment_id>1234</wp:comment_id> <wp:comment_author><![CDATA[John Doe]]></wp:comment_author> <wp:comment_author_email><![CDATA[info@adsasd.com]]></wp:comment_author_email> <wp:comment_author_url>http://myhomepage.com/</wp:comment_author_url> <wp:comment_author_IP><![CD...
given a WordPress xml export file, will return list of dictionaries with keys that match the expected json keys of a wordpress API call >>> xp = XML_parser('example_export.xml') >>> json_vals = {"slug","ID", "title","description", "content", "author", "terms", "date", } >>> data ...
Returns a flat list of all comments in XML dump. Formatted as the JSON output from Wordpress API. Keys: ('content', 'slug', 'date', 'status', 'author', 'ID', 'parent') date format: '%Y-%m-%dT%H:%M:%S' author: {'username': 'Name', 'URL': ''} def get_com...
Returns `content` with consecutive spaces converted to non-break spaces, and linebreak converted into HTML br elements. :param content: text to format :type content: `str` :rtype: `str` def _format_content(self, content): """Returns `content` with consecutive spaces converted t...
Returns `text` with each consituent token wrapped in HTML markup for later match annotation. :param text: text to be marked up :type text: `str` :rtype: `str` def _prepare_text(self, text): """Returns `text` with each consituent token wrapped in HTML markup for later ma...
Generates HTML reports for each witness to `work`, showing its text with the n-grams in `ngrams` highlighted. Any n-grams in `minus_ngrams` have any highlighting of them (or subsets of them) removed. :param output_dir: directory to write report to :type output_dir: `str` ...
Returns `content` with its n-grams from `ngrams` highlighted (if `add_class` is True) or unhighlighted. :param content: text to be modified :type content: `str` :param ngrams: n-grams to modify :type ngrams: `list` of `str` :param highlight: whether to highlight or unhig...
Generates HTML reports showing the text of each witness to `work` with its matches in `matches` highlighted. :param output_dir: directory to write report to :type output_dir: `str` :param work: name of work to highlight :type text_name: `str` :param matches_filename: fil...
Pull out the metadata about each packet from the input_stream Args: None Returns: generator (dictionary): a generator that contains packet meta data in the form of a dictionary def packet_meta_data(self): """Pull out the metadata about each packet from the in...
Print a summary of the flow information def print_flow_info(flow): """Print a summary of the flow information""" print('Flow %s (%s)-- Packets:%d Bytes:%d Payload: %s...' % (flow['flow_id'], flow['direction'], len(flow['packet_list']), len(flow['pay...
Combine packets into flows def packets_to_flows(self): """Combine packets into flows""" # For each packet, place it into either an existing flow or a new flow for packet in self.input_stream: # Compute flow tuple and add the packet to the flow flow_id = flow_utils.flow...
Copy assets for the report to `output_dir`. :param output_dir: directory to output assets to :type output_dir: `str` def _copy_static_assets(self, output_dir): """Copy assets for the report to `output_dir`. :param output_dir: directory to output assets to :type output_dir: `st...
Returns a template for this report. :rtype: `jinja2.Template` def _get_template(self): """Returns a template for this report. :rtype: `jinja2.Template` """ loader = PackageLoader(self._package_name, 'assets/templates') env = Environment(extensions=['jinja2.ext.with_']...
Writes the data in `context` in the report's template to `report_name` in `report_dir`. If `assets_dir` is supplied, copies all assets for this report to the specified directory. If `template` is supplied, uses that template instead of automatically finding it. This is useful i...
Print out summary information about each packet from the input_stream def pull(self): """Print out summary information about each packet from the input_stream""" # For each packet in the pcap process the contents for item in self.input_stream: # Print out the timestamp in UTC ...
Print out information about each packet from the input_stream def pull(self): """Print out information about each packet from the input_stream""" # For each packet in the pcap process the contents for item in self.input_stream: # Print out the timestamp in UTC print('T...
Load the client adaptor module of django_peeringdb Assumes config is valid. def load_backend(**orm_config): """ Load the client adaptor module of django_peeringdb Assumes config is valid. """ settings = {} settings['SECRET_KEY'] = orm_config.get('secret_key', '') db_config = orm_config...
Adds to each result row a count of the number of occurrences of that n-gram across all works within the label. This count uses the highest witness count for each work. def add_label_count(self): """Adds to each result row a count of the number of occurrences of that n-gram across all w...
Adds to each result row a count of the number of works within the label contain that n-gram. This counts works that have at least one witness carrying the n-gram. This correctly handles cases where an n-gram has only zero counts for a given work (possible with zero-fill followe...
Returns `row` annotated with whether it should be deleted or not. An n-gram is marked for deletion if: * its label count is 1 and its constituent (n-1)-grams also have a label count of 1; or * there is a containing (n+1)-gram that has the same label count. :param ...
Replaces the results with those n-grams that contain any of the original n-grams, and that represent points at which an n-gram is a constituent of multiple larger n-grams with a lower label count. :param corpus: corpus of works to which results belong :type corpus: `Corpus` ...
Groups together witnesses for the same n-gram and work that has the same count, and outputs a single row for each group. This output replaces the siglum field with a sigla field that provides a comma separated list of the witness sigla. Due to this, it is not necessarily possible to run...
Writes the results data to `fh` in CSV format and returns `fh`. :param fh: file to write data to :type fh: file object :rtype: file object def csv(self, fh): """Writes the results data to `fh` in CSV format and returns `fh`. :param fh: file to write data to :type fh: f...
Removes all rows whose n-gram contains `ngram`. This operation uses simple string containment matching. For tokens that consist of multiple characters, this means that `ngram` may be part of one or two tokens; eg, "he m" would match on "she may". :param ngram: n-gram to remove ...
Adds rows for all longer forms of n-grams in the results that are present in the witnesses. This works with both diff and intersect results. :param corpus: corpus of works to which results belong :type corpus: `Corpus` def extend(self, corpus): """Adds rows for all longer form...
Returns extended match data derived from `extended_ngrams`. This extended match data are the counts for all intermediate n-grams within each extended n-gram. :param extended_ngrams: extended n-grams :type extended_ngrams: `list` of `str` :param highest_n: the highest degree of ...
Returns the n-grams of the largest size that exist in `siglum` witness to `work` under `label`, generated from adding together overlapping n-grams in `matches`. :param matches: n-gram matches :type matches: `pandas.DataFrame` :param work: name of work whose results are being pro...
Returns the n-grams in `data` that do not contain any other n-gram in `data`. :param data: n-gram results data :type data: `pandas.DataFrame` :param min_size: minimum n-gram size in `data` :type min_size: `int` :rtype: `list` of `str` def _generate_filter_ngrams(self, d...
Returns a list of all substrings of `ngram`. :param ngram: n-gram to generate substrings of :type ngram: `str` :param size: size of `ngram` :type size: `int` :rtype: `list` def _generate_substrings(self, ngram, size): """Returns a list of all substrings of `ngram`. ...
Groups result rows by n-gram and label, providing a single summary field giving the range of occurrences across each work's witnesses. Results are sorted by n-gram then by label (in the order given in `labels`). :param labels: labels to order on :type labels: `list` of `str` de...
Groups results by witness, providing a single summary field giving the n-grams found in it, a count of their number, and the count of their combined occurrences. def group_by_witness(self): """Groups results by witness, providing a single summary field giving the n-grams found in it, a ...
Returns False if `results` has an n-gram that exists in only one label, True otherwise. :param results: results to analyze :type results: `pandas.DataFrame` :rtype: `bool` def _is_intersect_results(results): """Returns False if `results` has an n-gram that exists in only one ...
Removes results rows whose n-gram is in `ngrams`. :param ngrams: n-grams to remove :type ngrams: `list` of `str` def prune_by_ngram(self, ngrams): """Removes results rows whose n-gram is in `ngrams`. :param ngrams: n-grams to remove :type ngrams: `list` of `str` """ ...
Removes results rows whose total n-gram count (across all works bearing this n-gram) is outside the range specified by `minimum` and `maximum`. For each text, the count used as part of the sum across all works is the maximum count across the witnesses for that work. If `label` ...
Removes results rows if the n-gram count for all works bearing that n-gram is outside the range specified by `minimum` and `maximum`. That is, if a single witness of a single work has an n-gram count that falls within the specified range, all result rows for that n-gram are kept...
Removes results rows whose n-gram size is outside the range specified by `minimum` and `maximum`. :param minimum: minimum n-gram size :type minimum: `int` :param maximum: maximum n-gram size :type maximum: `int` def prune_by_ngram_size(self, minimum=None, maximum=None): ...
Removes results rows for n-grams that are not attested in a number of works in the range specified by `minimum` and `maximum`. Work here encompasses all witnesses, so that the same n-gram appearing in multiple witnesses of the same work are counted as a single work. If ...
Removes results rows for which the n-gram is not present in at least one text in each labelled set of texts. def reciprocal_remove(self): """Removes results rows for which the n-gram is not present in at least one text in each labelled set of texts.""" self._logger.info( 'Re...
Removes results rows whose n-grams are contained in larger n-grams. def reduce(self): """Removes results rows whose n-grams are contained in larger n-grams.""" self._logger.info('Reducing the n-grams') # This does not make use of any pandas functionality; it # probably c...
Lowers the counts of all n-grams in `data` that are substrings of `ngram` by `ngram`\'s count. Modifies `data` in place. :param data: row data dictionary for the current text :type data: `dict` :param ngram: n-gram being reduced :type ngram: `str` def _reduce_by_ngram(...
Relabels results rows according to `catalogue`. A row whose work is labelled in the catalogue will have its label set to the label in the catalogue. Rows whose works are not labelled in the catalogue will be unchanged. :param catalogue: mapping of work names to labels :type cat...
Removes all results rows associated with `label`. :param label: label to filter results on :type label: `str` def remove_label(self, label): """Removes all results rows associated with `label`. :param label: label to filter results on :type label: `str` """ se...
Sorts all results rows. Sorts by: size (descending), n-gram, count (descending), label, text name, siglum. def sort(self): """Sorts all results rows. Sorts by: size (descending), n-gram, count (descending), label, text name, siglum. """ self._matches.sort_valu...
Adds rows to the results to ensure that, for every n-gram that is attested in at least one witness, every witness for that text has a row, with added rows having a count of zero. :param corpus: corpus containing the texts appearing in the results :type corpus: `Corpus` def zero_fill(se...
Setup logging output defaults def get_logger(): """Setup logging output defaults""" # Grab the logger if not hasattr(get_logger, 'logger'): # Setup the default logging config get_logger.logger = logging.getLogger('chains') format_str = '%(asctime)s [%(levelname)s] - %(module)s: %(...
Read Packets from the packet capture interface def read_interface(self): """Read Packets from the packet capture interface""" # Spin up the packet capture if self._iface_is_file(): self.pcap = pcapy.open_offline(self.iface_name) else: try: # self...
Returns a parser configured with sub-commands and arguments. def generate_parser(): """Returns a parser configured with sub-commands and arguments.""" parser = argparse.ArgumentParser( description=constants.TACL_DESCRIPTION, formatter_class=ParagraphFormatter) subparsers = parser.add_subpar...
Adds a sub-command parser to `subparsers` to generate aligned sequences from a set of results. def generate_align_subparser(subparsers): """Adds a sub-command parser to `subparsers` to generate aligned sequences from a set of results.""" parser = subparsers.add_parser( 'align', description=cons...
Generates and saves a catalogue file. def generate_catalogue(args, parser): """Generates and saves a catalogue file.""" catalogue = tacl.Catalogue() catalogue.generate(args.corpus, args.label) catalogue.save(args.catalogue)
Adds a sub-command parser to `subparsers` to generate and save a catalogue file. def generate_catalogue_subparser(subparsers): """Adds a sub-command parser to `subparsers` to generate and save a catalogue file.""" parser = subparsers.add_parser( 'catalogue', description=constants.CATALOGUE_DESC...
Adds a sub-command parser to `subparsers` to make a counts query. def generate_counts_subparser(subparsers): """Adds a sub-command parser to `subparsers` to make a counts query.""" parser = subparsers.add_parser( 'counts', description=constants.COUNTS_DESCRIPTION, epilog=constants.COUNT...
Adds a sub-command parser to `subparsers` to make a diff query. def generate_diff_subparser(subparsers): """Adds a sub-command parser to `subparsers` to make a diff query.""" parser = subparsers.add_parser( 'diff', description=constants.DIFF_DESCRIPTION, epilog=constants.DIFF_EPILOG, fo...
Adds a sub-command parser to `subparsers` to excise n-grams from witnesses. def generate_excise_subparser(subparsers): """Adds a sub-command parser to `subparsers` to excise n-grams from witnesses.""" parser = subparsers.add_parser( 'excise', description=constants.EXCISE_DESCRIPTION, he...
Adds a sub-command parser to `subparsers` to highlight a witness' text with its matches in a result. def generate_highlight_subparser(subparsers): """Adds a sub-command parser to `subparsers` to highlight a witness' text with its matches in a result.""" parser = subparsers.add_parser( 'highligh...
Adds a sub-command parser to `subparsers` to make an intersection query. def generate_intersect_subparser(subparsers): """Adds a sub-command parser to `subparsers` to make an intersection query.""" parser = subparsers.add_parser( 'intersect', description=constants.INTERSECT_DESCRIPTION, ...