text
stringlengths
81
112k
minify response html to decrease traffic def response_minify(self, response): """ minify response html to decrease traffic """ if response.content_type == u'text/html; charset=utf-8': endpoint = request.endpoint or '' view_func = current_app.view_functions.get(e...
decorator to mark a view as exempt from htmlmin. def exempt(self, obj): """ decorator to mark a view as exempt from htmlmin. """ name = '%s.%s' % (obj.__module__, obj.__name__) @wraps(obj) def __inner(*a, **k): return obj(*a, **k) self._exempt_route...
Client supplied raw DMQL, ensure quote wrap. def dmql(query): """Client supplied raw DMQL, ensure quote wrap.""" if isinstance(query, dict): raise ValueError("You supplied a dictionary to the dmql_query parameter, but a string is required." " Did you mean to ...
Converts the filter dictionary into DMQL def filter_to_dmql(filter_dict): """Converts the filter dictionary into DMQL""" if not isinstance(filter_dict, (dict, collections.OrderedDict)): raise TypeError('Expected a dictionary type buy got {} instead.'.format(type(filter_dict))) def...
Get attributes of xml tags in input_dict and creates a dictionary with the attribute name as the key and the attribute value as the value :param input_dict: The xml tag with the attributes and values :return: dict def get_attributes(input_dict): """ Get attributes of xml tags in...
Turns column names in a single string into a dictionary with the key being the column name and the value being the value in that column for each row :param columns_string: A string of column names :param dict_string: A string of values :param delimiter: The delimiter to use to split the ...
Checks the RETS Response Code and handles non-zero answers. :param xml_response_dict: :return: None def analyze_reply_code(self, xml_response_dict): """ Checks the RETS Response Code and handles non-zero answers. :param xml_response_dict: :return: None """ ...
Appends the content and object ids how RETS expects them def ids(self, content_ids, object_ids): """Appends the content and object ids how RETS expects them""" result = [] content_ids = self.split(content_ids, False) object_ids = self.split(object_ids) for cid in content_ids: ...
Splits def split(value, dash_ranges=True): """Splits """ if isinstance(value, list): value = [str(v) for v in value] else: str_value = str(value) dash_matches = re.match(pattern='(\d+)\-(\d+)', string=str_value) if ':' in str_value or ',' in str_...
Set key value to the file. The fuction will be make the key and value to dictinary formate. If its exist then it will update the current new key value to the file. Arg: key : cache key value : cache value def set_value(self, key, value): """ Set key valu...
Delete the key if the token is expired. Arg: key : cache key def delete_value(self, key): """ Delete the key if the token is expired. Arg: key : cache key """ response = {} response['status'] = False response['msg'] = "key does not exist...
Open the file and assiging the permission to read/write and return the content in json formate. Return : json data def read_file(self): """ Open the file and assiging the permission to read/write and return the content in json formate. Return : json data """ ...
It will convert json content to json string and update into file. Return: Boolean True/False def update_file(self, content): """ It will convert json content to json string and update into file. Return: Boolean True/False """ updated_content = json.dump...
Parses RETS metadata using the COMPACT-DECODED format :param response: :param metadata_type: :return: def parse(self, response, metadata_type): """ Parses RETS metadata using the COMPACT-DECODED format :param response: :param metadata_type: :return: ...
Parses RETS metadata using the STANDARD-XML format :param response: requests Response object :param metadata_type: string :return parsed: list def parse(self, response, metadata_type): """ Parses RETS metadata using the STANDARD-XML format :param response: requests Respo...
From this 'multipart/parallel; boundary="874e43d27ec6d83f30f37841bdaf90c7"; charset=utf-8' get this --874e43d27ec6d83f30f37841bdaf90c7 def _get_multiparts(response): """ From this 'multipart/parallel; boundary="874e43d27ec6d83f30f37841bdaf90c7"; charset=utf-8' ge...
Parse multiple objects from the RETS feed. A lot of string methods are used to handle the response before encoding it back into bytes for the object. :param response: The response from the feed :return: list of SingleObjectParser def parse_image_response(self, response): """ Par...
Parse a single object from the RETS feed :param response: The response from the RETS server :return: Object def parse_image_response(self, response): """ Parse a single object from the RETS feed :param response: The response from the RETS server :return: Object "...
Auth is used to call the AUTH API of CricketAPI. Access token required for every request call to CricketAPI. Auth functional will post user Cricket API app details to server and return the access token. Return: Access token def auth(self): """ Auth i...
It will return json response based on given url, params and methods. Arg: params: 'dictionary' url: 'url' format method: default 'get', support method 'post' Return: json data def get_response(self, url, params={}, method="get"): """ ...
Getting the valid access token. Access token expires every 24 hours, It will expires then it will generate a new token. Return: active access token def get_active_token(self): """ Getting the valid access token. Access token expires every 24 hours, ...
Calling the Match API. Arg: match_key: key of the match card_type: optional, default to full_card. Accepted values are micro_card, summary_card & full_card. Return: json data def get_match(self, match_key, card_type="full_card"): """ Cal...
Calling the Recent Matches API. Arg: card_type: optional, default to micro_card. Accepted values are micro_card & summary_card. Return: json data def get_recent_matches(self, card_type="micro_card"): """ Calling the Recent Matches API. Arg: ...
Calling the Player Stats API Args: player_key: Key of the player board_key: key of the board Return: json data def get_player_stats(self, player_key, board_key): """ Calling the Player Stats API Args: player_key: Key of the player ...
match_key: key of the match over_key : key of the over Return: json data: def get_ball_by_ball(self, match_key, over_key=None): """ match_key: key of the match over_key : key of the over Return: json data: """ if over_...
Calling specific season recent matches. Arg: season_key: key of the season. Return: json date def get_recent_season_matches(self, season_key): """ Calling specific season recent matches. Arg: season_key: key of the season. Return: ...
Calling the Recent Season API. Return: json data def get_recent_seasons(self): """ Calling the Recent Season API. Return: json data """ recent_seasons_url = self.api_path + "recent_seasons/" response = self.get_response(recent_seasons_url...
Calling the Schedule API. Return: json data def get_schedule(self, date=None): """ Calling the Schedule API. Return: json data """ schedule_url = self.api_path + "schedule/" params = {} if date: params['date'] = date ...
Calling specific season schedule Arg: season_key: key of the season Return: json data def get_season_schedule(self, season_key): """ Calling specific season schedule Arg: season_key: key of the season Return: json data ...
Calling Season API. Arg: season_key: key of the season card_type: optional, default to micro_card. Accepted values are micro_card & summary_card Return: json data def get_season(self, season_key, card_type="micro_card"): """ Calling Season ...
Calling Season Stats API. Arg: season_key: key of the season Return: json data def get_season_stats(self, season_key): """ Calling Season Stats API. Arg: season_key: key of the season Return: json data """ se...
Calling Season teams API Arg: season_key: key of the season Return: json data def get_season_team(self, season_key, season_team_key,stats_type=None): """ Calling Season teams API Arg: season_key: key of the season Return: ...
Calling Season Points API. Arg: season_key: key of the season Return: json data def get_season_points(self, season_key): """ Calling Season Points API. Arg: season_key: key of the season Return: json data """ ...
Calling Season Player Stats API. Arg: season_key: key of the season player_key: key of the player Return: json data def get_season_player_stats(self, season_key, player_key): """ Calling Season Player Stats API. Arg: season_key: key ...
Calling Overs Summary API Arg: match_key: key of the match Return: json data def get_overs_summary(self, match_key): """ Calling Overs Summary API Arg: match_key: key of the match Return: json data """ overs_s...
Calling News Aggregation API Return: json data def get_news_aggregation(self): """ Calling News Aggregation API Return: json data """ news_aggregation_url = self.api_path + "news_aggregation" + "/" response = self.get_response(news_aggreg...
Calling Fantasy Credit API Arg: match_key: key of the match Return: json data def get_fantasy_credits(self, match_key): """ Calling Fantasy Credit API Arg: match_key: key of the match Return: json data """ ...
Calling Fantasy Points API Arg: match_key: key of the match Return: json data def get_fantasy_points(self, match_key): """ Calling Fantasy Points API Arg: match_key: key of the match Return: json data """ ...
Generates an output string by replacing the keywords in the format string with the corresponding values from a submission dictionary. def main(self): """ Generates an output string by replacing the keywords in the format string with the corresponding values from a submission dictionary....
Logs into Reddit in order to display a personalised front page. def login(self): """ Logs into Reddit in order to display a personalised front page. """ data = {'user': self.options['username'], 'passwd': self.options['password'], 'api_type': 'json'} response = s...
If there are no or only one submissions left, get new submissions. This function manages URL creation and the specifics for front page or subreddit mode. def manage_submissions(self): """ If there are no or only one submissions left, get new submissions. This function manages UR...
Connects to Reddit and gets a JSON representation of submissions. This JSON data is then processed and returned. url: A url that requests for submissions should be sent to. def get_submissions(self, url): """ Connects to Reddit and gets a JSON representation of submissions. Thi...
A compulsary function that gets the output of the cmus-remote -Q command and converts it to unicode in order for it to be processed and finally output. def main(self): """ A compulsary function that gets the output of the cmus-remote -Q command and converts it to unicode in orde...
Change the newline separated string of output data into a dictionary which can then be used to replace the strings in the config format. cmus_output: A string with information about cmus that is newline seperated. Running cmus-remote -Q in a terminal will show you what you're de...
A helper function to convert seconds into hh:mm:ss for better readability. time: A string representing time in seconds. def convert_time(self, time): """ A helper function to convert seconds into hh:mm:ss for better readability. time: A string representing time in seco...
Output all of the options and data for a segment. full_text: A string representing the data that should be output to i3bar. short_text: A more concise version of full_text, in case there is minimal room on the i3bar. def output(self, full_text, short_text): """ Output all of th...
A function that should be overwritten by a plugin that wishes to react to events, if it wants to perform any action other than running the supplied command related to a button. event: A dictionary passed from i3bar (after being decoded from JSON) that has the folowing format: e...
Reverse the requested URL (passed via GET / POST as `url_name` parameter) :param request: Request object :return: The reversed path def url_reverse(request): """ Reverse the requested URL (passed via GET / POST as `url_name` parameter) :param request: Request object :return: The reversed path...
Converts a filer image ID in a complete path :param request: Request object :param image_id: Filer image ID :param thumb_options: ThumbnailOption ID :param width: user-provided width :param height: user-provided height :return: JSON serialized URL components ('url', 'width', 'height') def url_...
Returns the requested ThumbnailOption as JSON :param request: Request object :return: JSON serialized ThumbnailOption def thumbnail_options(request): """ Returns the requested ThumbnailOption as JSON :param request: Request object :return: JSON serialized ThumbnailOption """ response_...
returns the content of an image sized according to the parameters :param request: Request object :param image_id: Filer image ID :param thumb_options: ThumbnailOption ID :param width: user-provided width :param height: user-provided height :return: JSON serialized URL components ('url', 'width'...
A helper function to create a directory if it doesn't exist. path: A string containing a full path to the directory to be created. def _touch_dir(self, path): """ A helper function to create a directory if it doesn't exist. path: A string containing a full path to the directory to be ...
Reload the configuration from the file. This is in its own function so that it can be called at any time by another class. def reload(self): """ Reload the configuration from the file. This is in its own function so that it can be called at any time by another class. """ ...
Replaces strings with appropriate data types (int, boolean). Also replaces the human readable logging levels with the integer form. dictionary: A dictionary returned from the config file. def _replace_data_types(dictionary): """ Replaces strings with appropriate data types (int, boolea...
Command line interface for the ``rotate-backups`` program. def main(): """Command line interface for the ``rotate-backups`` program.""" coloredlogs.install(syslog=True) # Command line option defaults. rotation_scheme = {} kw = dict(include_list=[], exclude_list=[]) parallel = False use_sudo...
Return the first line from the file located at battery_path/prop as a string. def get_battery_state(self, prop): """ Return the first line from the file located at battery_path/prop as a string. """ with open(os.path.join(self.options['battery_path'], prop), 'r') as f: ...
Coerce a string to a :class:`Location` object. :param value: The value to coerce (a string or :class:`Location` object). :param options: Any keyword arguments are passed on to :func:`~executor.contexts.create_context()`. :returns: A :class:`Location` object. def coerce_location(value, ...
Coerce a retention period to a Python value. :param value: A string containing the text 'always', a number or an expression that can be evaluated to a number. :returns: A number or the string 'always'. :raises: :exc:`~exceptions.ValueError` when the string can't be coerced. def coerce_re...
Load a configuration file with backup directories and rotation schemes. :param configuration_file: Override the pathname of the configuration file to load (a string or :data:`None`). :param expand: :data:`True` to expand filename patterns to their matches, :dat...
Rotate the backups in a directory according to a flexible rotation scheme. .. note:: This function exists to preserve backwards compatibility with older versions of the `rotate-backups` package where all of the logic was exposed as a single function. Please refer to the do...
Rotate the backups in the given locations concurrently. :param locations: One or more values accepted by :func:`coerce_location()`. :param kw: Any keyword arguments are passed on to :func:`rotate_backups()`. This function uses :func:`rotate_backups()` to prepare rotation commands for t...
Rotate the backups in a directory according to a flexible rotation scheme. :param location: Any value accepted by :func:`coerce_location()`. :param load_config: If :data:`True` (so by default) the rotation scheme and other options can be customized by the user in ...
Load a rotation scheme and other options from a configuration file. :param location: Any value accepted by :func:`coerce_location()`. :returns: The configured or given :class:`Location` object. def load_config_file(self, location): """ Load a rotation scheme and other options from a co...
Collect the backups at the given location. :param location: Any value accepted by :func:`coerce_location()`. :returns: A sorted :class:`list` of :class:`Backup` objects (the backups are sorted by their date). :raises: :exc:`~exceptions.ValueError` when the given directory does...
Group backups collected by :func:`collect_backups()` by rotation frequencies. :param backups: A :class:`set` of :class:`Backup` objects. :returns: A :class:`dict` whose keys are the names of rotation frequencies ('hourly', 'daily', etc.) and whose values are dictiona...
Apply the user defined rotation scheme to the result of :func:`group_backups()`. :param backups_by_frequency: A :class:`dict` in the format generated by :func:`group_backups()`. :param most_recent_backup: The :class:`~datetime.datetime` of the most ...
Collect the criteria used to decide which backups to preserve. :param backups_by_frequency: A :class:`dict` in the format generated by :func:`group_backups()` which has been processed by :func:`apply_rotation_scheme()`. :returns:...
The pathname of the mount point of :attr:`directory` (a string or :data:`None`). If the ``stat --format=%m ...`` command that is used to determine the mount point fails, the value of this property defaults to :data:`None`. This enables graceful degradation on e.g. Mac OS X whose ``stat`` ...
Make sure the location exists. def ensure_exists(self): """Make sure the location exists.""" if not self.context.is_directory(self.directory): # This can also happen when we don't have permission to one of the # parent directories so we'll point that out in the error message ...
Make sure the location exists and is readable. def ensure_readable(self): """Make sure the location exists and is readable.""" self.ensure_exists() if not self.context.is_readable(self.directory): if self.context.have_superuser_privileges: msg = "The directory %s isn...
Make sure the directory exists and is writable. def ensure_writable(self): """Make sure the directory exists and is writable.""" self.ensure_exists() if not self.context.is_writable(self.directory): if self.context.have_superuser_privileges: msg = "The directory %s i...
Check if the given location "matches". :param location: The :class:`Location` object to try to match. :returns: :data:`True` if the two locations are on the same system and the :attr:`directory` can be matched as a filename pattern or a literal match on the normalize...
A helper function for creating a file logger. Accepts arguments, as it is used in Status and LoggingWriter. def setup_file_logger(filename, formatting, log_level): """ A helper function for creating a file logger. Accepts arguments, as it is used in Status and LoggingWriter. """ logger = loggin...
Outputs data to stdout, without buffering. message: A string containing the data to be output. comma: Whether or not a comma should be placed at the end of the output. def output_to_bar(self, message, comma=True): """ Outputs data to stdout, without buffering. message: A strin...
Reload the installed plugins and the configuration file. This is called when either the plugins or config get updated. def reload(self): """ Reload the installed plugins and the configuration file. This is called when either the plugins or config get updated. """ logging...
Creates a thread for each plugin and lets the thread_manager handle it. def run_plugins(self): """ Creates a thread for each plugin and lets the thread_manager handle it. """ for obj in self.loader.objects: # Reserve a slot in the output_dict in order to ensure that the ...
Monitors if the config file or plugins are updated. Also outputs the JSON data generated by the plugins, without needing to poll the threads. def run(self): """ Monitors if the config file or plugins are updated. Also outputs the JSON data generated by the plugins, without needing to po...
If plugins haven't been initialised and therefore not sending output or their output is None, there is no reason to take up extra room on the bar. def _remove_empty_output(self): """ If plugins haven't been initialised and therefore not sending output or their output is None, th...
An event handler that processes events from stdin and calls the on_click function of the respective object. This function is run in another thread, so as to not stall the main thread. def handle_events(self): """ An event handler that processes events from stdin and calls the on_click ...
Helper function that returns a dictionary of all fields in the given model. If self.field_filter is set, it only includes the fields that match the filter. def field_dict(self, model): """ Helper function that returns a dictionary of all fields in the given model. If self.field_...
Calls the main function of a plugin and mutates the output dict with its return value. Provides an easy way to change the output whilst not needing to constantly poll a queue in another thread and allowing plugin's to manage their own intervals. def run(self): """ Calls the main...
Creates a thread, starts it and then adds it to the thread pool. Func: Same as in the Thread class. Interval: Same as in the Thread class. def add_thread(self, func, interval): """ Creates a thread, starts it and then adds it to the thread pool. Func: Same as in the Thread cla...
Compiles python plugin files in order to be processed by the loader. It compiles the plugins if they have been updated or haven't yet been compiled. def _compile_files(self): """ Compiles python plugin files in order to be processed by the loader. It compiles the plugins if they...
Accepts a path to a compiled plugin and returns a module object. file_path: A string that represents a complete file path to a compiled plugin. def _load_compiled(self, file_path): """ Accepts a path to a compiled plugin and returns a module object. file_path: A string that re...
Matches the plugins that have been specified in the config file with the available plugins. Returns instantiated objects based upon the classes defined in the plugins. def load_objects(self): """ Matches the plugins that have been specified in the config file with the available ...
Discovers the available plugins and turns each into a module object. This is a seperate function to allow plugins to be updated dynamically by other parts of the application. def refresh_files(self): """ Discovers the available plugins and turns each into a module object. This i...
Handles main URL routing for the databrowse app. `url` is the remainder of the URL -- e.g. 'objects/3'. def root(self, request, url): """ Handles main URL routing for the databrowse app. `url` is the remainder of the URL -- e.g. 'objects/3'. """ # Delegate to the appro...
Registers the given model(s) with the given databrowse site. The model(s) should be Model classes, not instances. If a databrowse class isn't given, it will use DefaultModelDatabrowse (the default databrowse options). If a model is already registered, this will raise AlreadyRegistered...
Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered. def unregister(self, *model_list): """ Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered. """ for model in model_list: ...
Handles main URL routing for the databrowse app. `url` is the remainder of the URL -- e.g. 'comments/comment/'. def root(self, request, url): """ Handles main URL routing for the databrowse app. `url` is the remainder of the URL -- e.g. 'comments/comment/'. """ self.ro...
Handles the model-specific functionality of the databrowse site, delegating<to the appropriate ModelDatabrowse class. def model_page(self, request, app_label, model_name, rest_of_url=None): """ Handles the model-specific functionality of the databrowse site, delegating<to the appropriat...
Returns a list of values for this field for this instance. It's a list so we can accomodate many-to-many fields. def values(self): """ Returns a list of values for this field for this instance. It's a list so we can accomodate many-to-many fields. """ # This import is de...
Returns a list of (value, URL) tuples. def urls(self): "Returns a list of (value, URL) tuples." # First, check the urls() method for each plugin. plugin_urls = [] for plugin_name, plugin in \ self.model.model_databrowse().plugins.items(): urls...
Helper function that returns a dictionary of all DateFields or DateTimeFields in the given model. If self.field_names is set, it takes that into account when building the dictionary. def field_dict(self, model): """ Helper function that returns a dictionary of all DateFields or ...
Optionally launches a Spark cluster and then runs ADAM to count k-mers on an input file. :param job: Toil job :param input_file: URL/path to input file to count k-mers on :param output_path: URL/path to save k-mer counts at :param kmer_length: The length of k-mer substrings to count. :param spa...
Runs k-mer counting. 1. If the input file is located in S3, the file is copied into HDFS. 2. If the input file is not in Parquet format, the file is converted into Parquet. 3. The k-mers are counted and saved as text. 4. If the output path is an S3 URL, the file is copied back to S3. :param job: T...
Sets up command line parser for Toil/ADAM based k-mer counter, and launches k-mer counter with optional Spark cluster. def main(): ''' Sets up command line parser for Toil/ADAM based k-mer counter, and launches k-mer counter with optional Spark cluster. ''' parser = argparse.ArgumentParser() ...
Downloads shared files and calls the GATK best practices germline pipeline for a cohort of samples :param JobFunctionWrappingJob job: passed automatically by Toil :param list[GermlineSample] samples: List of GermlineSample namedtuples :param Namespace config: Configuration options for pipeline Requ...
Runs the GATK best practices pipeline for germline SNP and INDEL discovery. Steps in Pipeline 0: Generate and preprocess BAM - Uploads processed BAM to output directory 1: Call Variants using HaplotypeCaller - Uploads GVCF 2: Genotype VCF - Uploads VCF 3: Filter Variants usi...
Checks for enough disk space for joint genotyping, then calls the genotype and filter pipeline function. :param JobFunctionWrappingJob job: passed automatically by Toil :param dict gvcfs: Dictionary of GVCFs {Sample ID: FileStoreID} :param Namespace config: Input parameters and reference FileStoreIDs ...