code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def __get_response_element_data(self, key1, key2): if not self.dict_response[key1][key2]: l = self.response for i, orig in enumerate(self.origins): self.dict_response[key1][key2][orig] = {} for j, dest in enumerate(self.destinations): ...
For each origin an elements object is created in the ouput. For each destination, an object is created inside elements object. For example, if there are 2 origins and 1 destination, 2 element objects with 1 object each are created. If there are 2 origins and 2 destinations, 2 element objects wit...
def get_closest_points(self, max_distance=None, origin_index=0, origin_raw=None): if not self.dict_response['distance']['value']: self.get_distance_values() if origin_raw: origin = copy.deepcopy(self.dict_response['distance']['value'][origin_raw]) else: ...
Get closest points to a given origin. Returns a list of 2 element tuples where first element is the destination and the second is the distance.
def rename_node(self, prefix): node_map_dict = {} # map each node to its new name (e.g. "a1") for i in range(0, len(self.nodes)): node_map_dict[self.nodes[i]] = prefix + str(i) # update node name for i, v in enumerate(self.nodes): self.nodes[i] = ...
Rename AMR graph nodes to prefix + node_index to avoid nodes with the same name in two different AMRs.
def get_triples(self): instance_triple = [] relation_triple = [] attribute_triple = [] for i in range(len(self.nodes)): instance_triple.append(("instance", self.nodes[i], self.node_values[i])) # l[0] is relation name # l[1] is the other node t...
Get the triples in three lists. instance_triple: a triple representing an instance. E.g. instance(w, want-01) attribute triple: relation of attributes, e.g. polarity(w, - ) and relation triple, e.g. arg0 (w, b)
def get_amr_line(input_f): cur_amr = [] has_content = False for line in input_f: line = line.strip() if line == "": if not has_content: # empty lines before current AMR continue else: ...
Read the file containing AMRs. AMRs are separated by a blank line. Each call of get_amr_line() returns the next available AMR (in one-line form). Note: this function does not verify if the AMR is valid
def __get_config(self, data_sources=None): if not data_sources: # For testing data_sources = ["gerrit", "git", "github_issues", "mls"] # In new_config a dict with all the metrics for all data sources is created new_config = {} for ds in data_sources: ...
Build a dictionary with the Report configuration with the data sources and metrics to be included in each section of the report :param data_sources: list of data sources to be included in the report :return: a dict with the data sources and metrics to be included in the report
def __convert_none_to_zero(self, ts): if not ts: return ts ts_clean = [val if val else 0 for val in ts] return ts_clean
Convert None values to 0 so the data works with Matplotlib :param ts: :return: a list with 0s where Nones existed
def bar3_chart(self, title, labels, data1, file_name, data2, data3, legend=["", ""]): colors = ["orange", "grey"] data1 = self.__convert_none_to_zero(data1) data2 = self.__convert_none_to_zero(data2) data3 = self.__convert_none_to_zero(data3) fig, ax = plt.subplots(1)...
Generate a bar plot with three columns in each x position and save it to file_name :param title: title to be used in the chart :param labels: list of labels for the x axis :param data1: values for the first columns :param file_name: name of the file in which to save the chart :p...
def get_metric_index(self, metric_cls): ds = self.class2ds[metric_cls.ds] if self.index_dict[ds]: index_name = self.index_dict[ds] else: index_name = self.ds2index[metric_cls.ds] return index_name
Get the index name with the data for a metric class :param metric_cls: a metric class :return: the name of the index with the data for the metric
def sec_com_channels(self): metrics = self.config['com_channels']['activity_metrics'] metrics += self.config['com_channels']['author_metrics'] for metric in metrics: csv_labels = 'labels,' + metric.id file_label = metric.ds.name + "_" + metric.id tit...
Generate the data for the Communication Channels section in the report :return:
def sec_project_activity(self, project=None): def create_data(metrics, project): csv_labels = "labels" + ',' + metrics[0].id + "," + metrics[1].id file_label = metrics[0].ds.name + "_" + metrics[0].id + "_" file_label += metrics[1].ds.name + "_" + metrics[1].id ...
Generate the data for the Activity section in the report :return:
def sec_projects(self): """ This activity is displayed at the general level, aggregating all of the projects, with the name 'general' and per project using the name of each project. This activity is divided into three main sections: activity, community and process. ...
Generate the report projects related sections: the general project is included always and add to the global report, and an specific report for each project is generated if configured. :return:
def sections(self): secs = OrderedDict() secs['Overview'] = self.sec_overview secs['Communication Channels'] = self.sec_com_channels secs['Detailed Activity by Project'] = self.sec_projects return secs
Get the sections of the report and howto build them. :return: a dict with the method to be called to fill each section of the report
def create_data_figs(self): logger.info("Generating the report data and figs from %s to %s", self.start, self.end) for section in self.sections(): logger.info("Generating %s", section) self.sections()[section]() logger.info("Data and figs d...
Generate the data and figs files for the report :return:
def build_period_name(cls, pdate, interval='quarter', offset=None, start_date=False): if interval not in ['quarter']: raise RuntimeError("Interval not support in build_period_name", interval) name = pdate.strftime('%Y-%m-%d') + ' ' + interval months_in_quarter = 3 ...
Build the period name for humans (eg, 18-Q2) to be used in the reports. Just supporting quarters right now. The name is built using the last month for the quarter. :param pdate: the date (datetime) which defines the period :param interval: the time interval (string) used in the report ...
def replace_text(filepath, to_replace, replacement): with open(filepath) as file: s = file.read() s = s.replace(to_replace, replacement) with open(filepath, 'w') as file: file.write(s)
Replaces a string in a given file with another string :param file: the file in which the string has to be replaced :param to_replace: the string to be replaced in the file :param replacement: the string which replaces 'to_replace' in the file
def replace_text_dir(self, directory, to_replace, replacement, file_type=None): if not file_type: file_type = "*.tex" for file in glob.iglob(os.path.join(directory, file_type)): self.replace_text(file, to_replace, replacement)
Replaces a string with its replacement in all the files in the directory :param directory: the directory in which the files have to be modified :param to_replace: the string to be replaced in the files :param replacement: the string which replaces 'to_replace' in the files :param file_t...
def create(self): logger.info("Generating the report from %s to %s", self.start, self.end) self.create_data_figs() self.create_pdf() logger.info("Report completed")
Generate the data and figs for the report and fill the LaTeX templates with them to generate a PDF file with the report. :return:
def get_names(file_dir, files): # for each user, check if they have files available # return user name list total_list = [] name_list = [] get_sub = False for path, subdir, dir_files in os.walk(file_dir): if not get_sub: total_list = subdir[:] get_sub = True ...
Get the annotator name list based on a list of files Args: file_dir: AMR file folder files: a list of AMR names, e.g. nw_wsj_0001_1 Returns: a list of user names who annotate all the files
def pprint_table(table): col_paddings = [] for i in range(len(table[0])): col_paddings.append(get_max_width(table,i)) for row in table: print(row[0].ljust(col_paddings[0] + 1), end="") for i in range(1, len(row)): col = str(row[i]).rjust(col_paddings[i]+2) ...
Print a table in pretty format
def build_arg_parser(): parser = argparse.ArgumentParser(description="Smatch table calculator -- arguments") parser.add_argument("--fl", type=argparse.FileType('r'), help='AMR ID list file') parser.add_argument('-f', nargs='+', help='AMR IDs (at least one)') parser.add_argument("-p", nargs='*', hel...
Build an argument parser using argparse. Use it when python version is 2.7 or later.
def build_arg_parser2(): usage_str = "Smatch table calculator -- arguments" parser = optparse.OptionParser(usage=usage_str) parser.add_option("--fl", dest="fl", type="string", help='AMR ID list file') parser.add_option("-f", dest="f", type="string", action="callback", callback=cb, help="AMR IDs (at...
Build an argument parser using optparse. Use it when python version is 2.5 or 2.6.
def cb(option, value, parser): arguments = [value] for arg in parser.rargs: if arg[0] != "-": arguments.append(arg) else: del parser.rargs[:len(arguments)] break if getattr(parser.values, option.dest): arguments.extend(getattr(parser.values, o...
Callback function to handle variable number of arguments in optparse
def create_csv(filename, csv_data, mode="w"): with open(filename, mode) as f: csv_data.replace("_", r"\_") f.write(csv_data)
Create a CSV file with the given data and store it in the file with the given name. :param filename: name of the file to store the data in :pram csv_data: the data to be stored in the file :param mode: the mode in which we have to open the file. It can be 'w', 'a', etc. Default is 'w'
def get_metric_index(self, data_source): if data_source in self.index_dict: index = self.index_dict[data_source] else: index = self.class2index[self.ds2class[data_source]] return Index(index_name=index)
This function will return the elasticsearch index for a corresponding data source. It chooses in between the default and the user inputed es indices and returns the user inputed one if it is available. :param data_source: the data source for which the index has to be returned :returns: ...
def get_sec_project_activity(self): logger.debug("Calculating Project Activity metrics.") data_path = os.path.join(self.data_dir, "activity") if not os.path.exists(data_path): os.makedirs(data_path) for ds in self.data_sources: metric_file = self.ds2cl...
Generate the "project activity" section of the report.
def create_data_figs(self): logger.info("Generating the report data and figs from %s to %s", self.start_date, self.end_date) self.get_sec_overview() self.get_sec_project_activity() self.get_sec_project_community() self.get_sec_project_process() ...
Generate the data and figs files for the report :return:
def create(self): logger.info("Generating the report from %s to %s", self.start_date, self.end_date) self.create_data_figs() self.create_pdf() logger.info("Report completed")
Generate the data and figs for the report and fill the LaTeX templates with them to generate a PDF file with the report. :return:
def set_var_slice(self, name, start, count, var): tmp = self.get_var(name).copy() # sometimes we want to slice in 1 dimension, sometimes in more # always slice in arrays start = np.atleast_1d(start) count = np.atleast_1d(count) slices = [np.s_[i:(i+n)] for i,n in...
Overwrite the values in variable name with data from var, in the range (start:start+count). Start, count can be integers for rank 1, and can be tuples of integers for higher ranks. For some implementations it can be equivalent and more efficient to do: `get_var(name)[start[0]:sta...
def set_var_index(self, name, index, var): tmp = self.get_var(name).copy() tmp.flat[index] = var self.set_var(name, tmp)
Overwrite the values in variable "name" with data from var, at the flattened (C-contiguous style) indices. Indices is a vector of 0-based integers, of the same length as the vector var. For some implementations it can be equivalent and more efficient to do: `get_var(name)...
def create_tables(database): '''Create all tables in the given database''' logging.getLogger(__name__).debug("Creating missing database tables") database.connect() database.create_tables([User, Group, UserToGroup, GroupT...
Create all tables in the given database
def populate_with_defaults(): '''Create user admin and grant him all permission If the admin user already exists the function will simply return ''' logging.getLogger(__name__).debug("Populating with default users") if not User.select().where(User.name == 'admin').exists(): admin = User.cre...
Create user admin and grant him all permission If the admin user already exists the function will simply return
def init_db(dbURL, pwd_salt_size=None, pwd_rounds=None): '''Initialize users database initialize database and create necessary tables to handle users oprations. :param dbURL: database url, as described in :func:`init_proxy` ''' if not dbURL: dbURL = 'sqlite:///:memory:' logging.get...
Initialize users database initialize database and create necessary tables to handle users oprations. :param dbURL: database url, as described in :func:`init_proxy`
def normalize(s, replace_spaces=True): whitelist = (' -' + string.ascii_letters + string.digits) if type(s) == six.binary_type: s = six.text_type(s, 'utf-8', 'ignore') table = {} for ch in [ch for ch in s if ch not in whitelist]: if ch not in table: try: ...
Normalize non-ascii characters to their closest ascii counterparts
def get_robot_variables(): prefix = 'ROBOT_' variables = [] def safe_str(s): if isinstance(s, six.text_type): return s else: return six.text_type(s, 'utf-8', 'ignore') for key in os.environ: if key.startswith(prefix) and len(key) > len(prefix): ...
Return list of Robot Framework -compatible cli-variables parsed from ROBOT_-prefixed environment variable
def configure(self): logger.debug('Configuring ' + hex(self.get_address()) + ' ch: ' + str(self.get_channel()) + ' res: ' + str(self.get_resolution()) + ' gain: ' + str(self.get_gain())) self.bus.write_byte(self.address, self.config...
Configure the device. Send the device configuration saved inside the MCP342x object to the target device.
def convert(self): c = self.config c &= (~MCP342x._continuous_mode_mask & 0x7f) # Force one-shot c |= MCP342x._not_ready_mask # Convert logger.debug('Convert ' + hex(self.address) + ' config: ' + bin(c)) self.bus.write_byte(self.address, c)
Initiate one-shot conversion. The current settings are used, with the exception of continuous mode.
def get_first_date_of_index(elastic_url, index): es = Elasticsearch(elastic_url) search = Search(using=es, index=index) agg = A("min", field="grimoire_creation_date") search.aggs.bucket("1", agg) search = search.extra(size=0) response = search.execute() start_date = response.to_dict()['...
Get the first/min date present in the index
def __get_query_filters(cls, filters={}, inverse=False): query_filters = [] for name in filters: if name[0] == '*' and not inverse: # An inverse filter and not inverse mode continue if name[0] != '*' and inverse: # A direc...
Convert a dict with the filters to be applied ({"name1":"value1", "name2":"value2"}) to a list of query objects which can be used together in a query using boolean combination logic. :param filters: dict with the filters to be applied :param inverse: if True include all the inverse filt...
def __get_query_range(cls, date_field, start=None, end=None): if not start and not end: return '' start_end = {} if start: start_end["gte"] = "%s" % start.isoformat() if end: start_end["lte"] = "%s" % end.isoformat() query_range = {d...
Create a filter dict with date_field from start to end dates. :param date_field: field with the date value :param start: date with the from value. Should be a datetime.datetime object of the form: datetime.datetime(2018, 5, 25, 15, 17, 39) :param end: date with the to valu...
def __get_query_basic(cls, date_field=None, start=None, end=None, filters={}): query_basic = Search() query_filters = cls.__get_query_filters(filters) for f in query_filters: query_basic = query_basic.query(f) query_filters_inverse = cls._...
Create a es_dsl query object with the date range and filters. :param date_field: field with the date value :param start: date with the from value, should be a datetime.datetime object :param end: date with the to value, should be a datetime.datetime object :param filters: dict with the ...
def __get_query_agg_terms(cls, field, agg_id=None): if not agg_id: agg_id = cls.AGGREGATION_ID query_agg = A("terms", field=field, size=cls.AGG_SIZE, order={"_count": "desc"}) return (agg_id, query_agg)
Create a es_dsl aggregation object based on a term. :param field: field to be used to aggregate :return: a tuple with the aggregation id and es_dsl aggregation object. Ex: { "terms": { "field": <field>, "size:": <size>,...
def __get_query_agg_max(cls, field, agg_id=None): if not agg_id: agg_id = cls.AGGREGATION_ID query_agg = A("max", field=field) return (agg_id, query_agg)
Create an es_dsl aggregation object for getting the max value of a field. :param field: field from which the get the max value :return: a tuple with the aggregation id and es_dsl aggregation object. Ex: { "max": { "field": <field> ...
def __get_query_agg_percentiles(cls, field, agg_id=None): if not agg_id: agg_id = cls.AGGREGATION_ID query_agg = A("percentiles", field=field) return (agg_id, query_agg)
Create an es_dsl aggregation object for getting the percentiles value of a field. In general this is used to get the median (0.5) percentile. :param field: field from which the get the percentiles values :return: a tuple with the aggregation id and es_dsl aggregation object. Ex: ...
def __get_query_agg_avg(cls, field, agg_id=None): if not agg_id: agg_id = cls.AGGREGATION_ID query_agg = A("avg", field=field) return (agg_id, query_agg)
Create an es_dsl aggregation object for getting the average value of a field. :param field: field from which the get the average value :return: a tuple with the aggregation id and es_dsl aggregation object. Ex: { "avg": { "field": <field> ...
def __get_query_agg_cardinality(cls, field, agg_id=None): if not agg_id: agg_id = cls.AGGREGATION_ID query_agg = A("cardinality", field=field, precision_threshold=cls.ES_PRECISION) return (agg_id, query_agg)
Create an es_dsl aggregation object for getting the approximate count of distinct values of a field. :param field: field from which the get count of distinct values :return: a tuple with the aggregation id and es_dsl aggregation object. Ex: { "cardinality": { ...
def __get_bounds(cls, start=None, end=None): bounds = {} if start or end: # Extend bounds so we have data until start and end start_ts = None end_ts = None if start: # elasticsearch is unable to convert date with microseconds into ...
Return a dict with the bounds for a date_histogram agg. :param start: date from for the date_histogram agg, should be a datetime.datetime object :param end: date to for the date_histogram agg, should be a datetime.datetime object :return: a dict with the DSL bounds for a date_histogram aggregat...
def get_count(cls, date_field=None, start=None, end=None, filters={}): """ Total number of items """ query_basic = cls.__get_query_basic(date_field=date_field, start=start, end=end, filters=filters) ...
Build the DSL query for counting the number of items. :param date_field: field with the date :param start: date from which to start counting, should be a datetime.datetime object :param end: date until which to count items, should be a datetime.datetime object :param filters: dict with ...
def _flatten_fetched_fields(fields_arg): if fields_arg is None: return None if isinstance(fields_arg, dict): return tuple(sorted([k for k in list(fields_arg.keys()) if fields_arg[k]])) else: return tuple(sorted(fields_arg))
this method takes either a kwargs 'fields', which can be a dict : {"_id": False, "store": 1, "url": 1} or a list : ["store", "flag", "url"] and returns a tuple : ("store", "flag"). it HAS to be a tuple, so that it is not updated by the different instances
def ensure_fields(self, fields, force_refetch=False): # We fetched with fields=None, we should have fetched them all if self._fetched_fields is None or self._initialized_with_doc: return if force_refetch: missing_fields = fields else: missin...
Makes sure we fetched the fields, and populate them if not.
def refetch_fields(self, missing_fields): db_fields = self.mongokat_collection.find_one({"_id": self["_id"]}, fields={k: 1 for k in missing_fields}) self._fetched_fields += tuple(missing_fields) if not db_fields: return for k, v in db_fields.items(): s...
Refetches a list of fields from the DB
def unset_fields(self, fields): self.mongokat_collection.update_one({"_id": self["_id"]}, {"$unset": { f: 1 for f in fields }}) for f in fields: if f in self: del self[f]
Removes this list of fields from both the local object and the DB.
def reload(self): old_doc = self.mongokat_collection.find_one({"_id": self['_id']}, read_use="primary") if not old_doc: raise OperationFailure('Can not reload an unsaved document.' ' %s is not found in the database. Maybe _id was a string and not...
allow to refresh the document, so after using update(), it could reload its value from the database. Be carreful : reload() will erase all unsaved values. If no _id is set in the document, a KeyError is raised.
def save(self, force=False, uuid=False, **kwargs): if not self._initialized_with_doc and not force: raise Exception("Cannot save a document not initialized from a Python dict. This might remove fields from the DB!") self._initialized_with_doc = False if '_id' not in self:...
REPLACES the object in DB. This is forbidden with objects from find() methods unless force=True is given.
def save_partial(self, data=None, allow_protected_fields=False, **kwargs): # Backwards compat, deprecated argument if "dotnotation" in kwargs: del kwargs["dotnotation"] if data is None: data = dotdict(self) if "_id" not in data: rai...
Saves just the currently set fields in the database.
def read_default_args(tool_name): global opinel_arg_dir profile_name = 'default' # h4ck to have an early read of the profile name for i, arg in enumerate(sys.argv): if arg == '--profile' and len(sys.argv) >= i + 1: profile_name = sys.argv[i + 1] #if not os.path.isdir(op...
Read default argument values for a given tool :param tool_name: Name of the script to read the default arguments for :return: Dictionary of default arguments (shared + tool-specific)
def prompt(test_input = None): if test_input != None: if type(test_input) == list and len(test_input): choice = test_input.pop(0) elif type(test_input) == list: choice = '' else: choice = test_input else: # Coverage: 4 missed statements ...
Prompt function that works for Python2 and Python3 :param test_input: Value to be returned when testing :return: Value typed by user (or passed in argument when testing)
def prompt_4_mfa_code(activate = False, input = None): while True: if activate: prompt_string = 'Enter the next value: ' else: prompt_string = 'Enter your MFA code (or \'q\' to abort): ' mfa_code = prompt_4_value(prompt_string, no_confirm = True, input = input) ...
Prompt for an MFA code :param activate: Set to true when prompting for the 2nd code when activating a new MFA device :param input: Used for unit testing :return: The MFA code
def prompt_4_mfa_serial(input = None): return prompt_4_value('Enter your MFA serial:', required = False, regex = re_mfa_serial_format, regex_format = mfa_serial_format, input = input)
Prompt for an MFA serial number :param input: Used for unit testing :return: The MFA serial number
def prompt_4_overwrite(filename, force_write, input = None): if not os.path.exists(filename) or force_write: return True return prompt_4_yes_no('File \'{}\' already exists. Do you want to overwrite it'.format(filename), input = input)
Prompt whether the file should be overwritten :param filename: Name of the file about to be written :param force_write: Skip confirmation prompt if this flag is set :param input: Used for unit testing :return: Boolean ...
def prompt_4_yes_no(question, input = None): count = 0 while True: printError(question + ' (y/n)? ') choice = prompt(input).lower() if choice == 'yes' or choice == 'y': return True elif choice == 'no' or choice == 'n': return False else: ...
Prompt for a yes/no or y/n answer . :param question: Question to be asked :param input: Used for unit testing :return: True for yes/y, False for no/n
def safe_import_module(path, default=None): if path is None: return default dot = path.rindex('.') module_name = path[:dot] class_name = path[dot + 1:] try: _class = getattr(import_module(module_name), class_name) return _class except (ImportError, AttributeErro...
Try to import the specified module from the given Python path @path is a string containing a Python path to the wanted module, @default is an object to return if import fails, it can be None, a callable or whatever you need. Return a object or None
def get_feed_renderer(engines, name): if name not in engines: raise FeedparserError("Given feed name '{}' does not exists in 'settings.FEED_RENDER_ENGINES'".format(name)) renderer = safe_import_module(engines[name]) return renderer
From engine name, load the engine path and return the renderer class Raise 'FeedparserError' if any loading error
def clear_line(mode=2): ''' Clear the current line. Arguments: mode: | 0 | 'forward' | 'right' - Clear cursor to end of line. | 1 | 'backward' | 'left' - Clear cursor to beginning of line. | 2 | 'full' - Clear entire line. Note: ...
Clear the current line. Arguments: mode: | 0 | 'forward' | 'right' - Clear cursor to end of line. | 1 | 'backward' | 'left' - Clear cursor to beginning of line. | 2 | 'full' - Clear entire line. Note: Cursor position does ...
def clear_screen(mode=2): ''' Clear the terminal/console screen. (Also aliased to clear.) Arguments: mode: | 0 | 'forward' - Clear cursor to end of screen, cursor stays. | 1 | 'backward' - Clear cursor to beginning of screen, "" | 2 | 'full' - Cle...
Clear the terminal/console screen. (Also aliased to clear.) Arguments: mode: | 0 | 'forward' - Clear cursor to end of screen, cursor stays. | 1 | 'backward' - Clear cursor to beginning of screen, "" | 2 | 'full' - Clear entire visible screen, cursor t...
def reset_terminal(): ''' Reset the terminal/console screen. (Also aliased to cls.) Greater than a fullscreen terminal clear, also clears the scrollback buffer. May expose bugs in dumb terminals. ''' if os.name == 'nt': from .windows import cls cls() else: text ...
Reset the terminal/console screen. (Also aliased to cls.) Greater than a fullscreen terminal clear, also clears the scrollback buffer. May expose bugs in dumb terminals.
def set_title(title, mode=0): ''' Set the title of the terminal window/tab/icon. Arguments: title: str mode: | 0 | 'both' - Set icon/taskbar and window/tab title | 1 | 'icon' - Set only icon/taskbar title | 2 | 'title' - Set only window/t...
Set the title of the terminal window/tab/icon. Arguments: title: str mode: | 0 | 'both' - Set icon/taskbar and window/tab title | 1 | 'icon' - Set only icon/taskbar title | 2 | 'title' - Set only window/tab title
def wait_key(keys=None): ''' Waits for a keypress at the console and returns it. "Where's the any key?" Arguments: keys - if passed, wait for this specific key, e.g. ESC. may be a tuple. Returns: char or ESC - depending on key hit. None...
Waits for a keypress at the console and returns it. "Where's the any key?" Arguments: keys - if passed, wait for this specific key, e.g. ESC. may be a tuple. Returns: char or ESC - depending on key hit. None - immediately under i/o redirect...
def pause(message='Press any key to continue…'): ''' Analogous to the ancient `DOS pause <https://en.wikipedia.org/wiki/List_of_DOS_commands#PAUSE>`_ command, with a modifiable message. Arguments: message: str Returns: str, None: One character or ESC - dep...
Analogous to the ancient `DOS pause <https://en.wikipedia.org/wiki/List_of_DOS_commands#PAUSE>`_ command, with a modifiable message. Arguments: message: str Returns: str, None: One character or ESC - depending on key hit. None - immediately under i...
def build_query_fragment(query): root = etree.Element('query', nsmap={None: 'http://basex.org/rest'}) text = etree.SubElement(root, 'text') text.text = etree.CDATA(query.strip()) return root
<query xmlns="http://basex.org/rest"> <text><![CDATA[ (//city/name)[position() <= 5] ]]></text> </query>
def feedparser_render(url, *args, **kwargs): renderer_name = kwargs.get('renderer', settings.FEED_DEFAULT_RENDERER_ENGINE) renderer_template = kwargs.get('template', None) expiration = kwargs.get('expiration', 0) renderer = get_feed_renderer(settings.FEED_RENDER_ENGINES, renderer_name) ret...
Render a feed and return its builded html Usage: :: {% feedparser_render 'http://localhost/sample.xml' %} Or with all accepted arguments: :: {% feedparser_render 'http://localhost/sample.xml' renderer='CustomRenderer' template='foo/custom.html' expiration=3600 %}
def build_region_list(service, chosen_regions = [], partition_name = 'aws'): service = 'ec2containerservice' if service == 'ecs' else service # Of course things aren't that easy... # Get list of regions from botocore regions = Session().get_available_regions(service, partition_name = partition_name) ...
Build the list of target region names :param service: :param chosen_regions: :param partition_name: :return:
def connect_service(service, credentials, region_name = None, config = None, silent = False): api_client = None try: client_params = {} client_params['service_name'] = service.lower() session_params = {} session_params['aws_access_key_id'] = credentials['AccessKeyId'] ...
Instantiates an AWS API client :param service: :param credentials: :param region_name: :param config: :param silent: :return:
def handle_truncated_response(callback, params, entities): results = {} for entity in entities: results[entity] = [] while True: try: marker_found = False response = callback(**params) for entity in entities: if entity in response: ...
Handle truncated responses :param callback: :param params: :param entities: :return:
def pdftojpg(filehandle, meta): resolution = meta.get('resolution', 300) width = meta.get('width', 1080) bgcolor = Color(meta.get('bgcolor', 'white')) stream = BytesIO() with Image(blob=filehandle.stream, resolution=resolution) as img: img.background_color = bgcolor img.alpha_c...
Converts a PDF to a JPG and places it back onto the FileStorage instance passed to it as a BytesIO object. Optional meta arguments are: * resolution: int or (int, int) used for wand to determine resolution, defaults to 300. * width: new width of the image for resizing, defaults to 1080 ...
def change_filename(filehandle, meta): filename = secure_filename(meta.get('filename', filehandle.filename)) basename, _ = os.path.splitext(filename) meta['original_filename'] = filehandle.filename filehandle.filename = filename + '.jpg' return filehandle
Changes the filename to reflect the conversion from PDF to JPG. This method will preserve the original filename in the meta dictionary.
def avoid_name_collisions(filehandle, meta): if meta.get('avoid_name_collision', True): filename = filehandle.filename original, ext = os.path.splitext(filehandle.filename) counter = count() while os.path.exists(get_save_path(filename)): fixer = str(next(counter)) ...
Manipulates a filename until it's unique. This can be disabled by setting meta['avoid_name_collision'] to any falsey value.
def pdf_saver(filehandle, *args, **kwargs): "Uses werkzeug.FileStorage instance to save the converted image." fullpath = get_save_path(filehandle.filename) filehandle.save(fullpath, buffer_size=kwargs.get('buffer_size', 16384)f pdf_saver(filehandle, *args, **kwargs): "Uses werkzeug.FileStorage instance ...
Uses werkzeug.FileStorage instance to save the converted image.
def load_data(data_file, key_name = None, local_file = False, format = 'json'): if local_file: if data_file.startswith('/'): src_file = data_file else: src_dir = os.getcwd() src_file = os.path.join(src_dir, data_file) else: src_dir = os.path.join(...
Load a JSON data file :param data_file: :param key_name: :param local_file: :return:
def read_ip_ranges(filename, local_file = True, ip_only = False, conditions = []): targets = [] data = load_data(filename, local_file = local_file) if 'source' in data: # Filtered IP ranges conditions = data['conditions'] local_file = data['local_file'] if 'local_file' in data e...
Returns the list of IP prefixes from an ip-ranges file :param filename: :param local_file: :param conditions: :param ip_only: :return:
def read_file(file_path, mode = 'rt'): contents = '' with open(file_path, mode) as f: contents = f.read() return contents
Read the contents of a file :param file_path: Path of the file to be read :return: Contents of the file
def save_blob_as_json(filename, blob, force_write, debug): try: if prompt_4_overwrite(filename, force_write): with open(filename, 'wt') as f: print('%s' % json.dumps(blob, indent=4 if debug else None, separators=(',', ': '), sort_keys=True, cls=CustomJSONEncoder), file=f) ...
Creates/Modifies file and saves python object as JSON :param filename: :param blob: :param force_write: :param debug: :return:
def save_ip_ranges(profile_name, prefixes, force_write, debug, output_format = 'json'): filename = 'ip-ranges-%s.json' % profile_name ip_ranges = {} ip_ranges['createDate'] = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') # Unique prefixes unique_prefixes = {} for prefix in prefixes:...
Creates/Modifies an ip-range-XXX.json file :param profile_name: :param prefixes: :param force_write: :param debug: :return:
def check_requirements(script_path, requirements_file = None): script_dir = os.path.dirname(script_path) opinel_min_version = opinel_max_version = boto3_min_version = boto3_max_version = None # Requirements file is either next to the script or in data/requirements if not requirements_file: ...
Check versions of opinel and boto3 :param script_path: :return:
def init_app(self, app): assert 'zodb' not in app.extensions, \ 'app already initiated for zodb' app.extensions['zodb'] = _ZODBState(self, app) app.teardown_request(self.close_db)
Configure a Flask application to use this ZODB extension.
def close_db(self, exception): if self.is_connected: if exception is None and not transaction.isDoomed(): transaction.commit() else: transaction.abort() self.connection.close()
Added as a `~flask.Flask.teardown_request` to applications to commit the transaction and disconnect ZODB if it was used during the request.
def create_db(self, app): assert 'ZODB_STORAGE' in app.config, \ 'ZODB_STORAGE not configured' storage = app.config['ZODB_STORAGE'] if isinstance(storage, basestring): factory, dbargs = zodburi.resolve_uri(storage) elif isinstance(storage, tuple): ...
Create a ZODB connection pool from the *app* configuration.
def connection(self): assert flask.has_request_context(), \ 'tried to connect zodb outside request' if not self.is_connected: connector = flask.current_app.extensions['zodb'] flask._request_ctx_stack.top.zodb_connection = connector.db.open() tr...
Request-bound database connection.
def add_user_to_group(iam_client, user, group, quiet = False): if not quiet: printInfo('Adding user to group %s...' % group) iam_client.add_user_to_group(GroupName = group, UserName = user)
Add an IAM user to an IAM group :param iam_client: :param group: :param user: :param user_info: :param dry_run: :return:
def create_groups(iam_client, groups): groups_data = [] if type(groups) != list: groups = [ groups ] for group in groups: errors = [] try: printInfo('Creating group %s...' % group) iam_client.create_group(GroupName = group) except Exception as e:...
Create a number of IAM group, silently handling exceptions when entity already exists . :param iam_client: AWS API client for IAM :param groups: Name of IAM groups to be created. :return: None
def delete_virtual_mfa_device(iam_client, mfa_serial): try: printInfo('Deleting MFA device %s...' % mfa_serial) iam_client.delete_virtual_mfa_device(SerialNumber = mfa_serial) except Exception as e: printException(e) printError('Failed to delete MFA device %s' % mfa_serial) ...
Delete a vritual MFA device given its serial number :param iam_client: :param mfa_serial: :return:
def init_group_category_regex(category_groups, category_regex_args): category_regex = [] authorized_empty_regex = 1 if len(category_regex_args) and len(category_groups) != len(category_regex_args): printError('Error: you must provide as many regex as category groups.') return None f...
Initialize and compile regular expression for category groups :param category_regex_args: List of string regex :return: List of compiled regex
def _index_to_ansi_values(self, index): ''' Converts an palette index to the corresponding ANSI color. Arguments: index - an int (from 0-15) Returns: index as str in a list for compatibility with values. ''' if self.__class__.__name__[0]...
Converts an palette index to the corresponding ANSI color. Arguments: index - an int (from 0-15) Returns: index as str in a list for compatibility with values.
def _create_entry(self, name, values, fbterm=False): ''' Render first values as string and place as first code, save, and return attr. ''' if fbterm: attr = _PaletteEntryFBTerm(self, name.upper(), ';'.join(values)) else: attr = _PaletteEntry(self, name...
Render first values as string and place as first code, save, and return attr.
def write(self, data): ''' This could be a bit less clumsy. ''' if data == '\n': # print does this return self.stream.write(data) else: bytes_ = 0 for line in data.splitlines(True): nl = '' if line.endswith('\n'): # mv nl to e...
This could be a bit less clumsy.
def set_output(self, outfile): ''' Set's the output file, currently only useful with context-managers. Note: This function is experimental and may not last. ''' if self._orig_stdout: # restore Usted sys.stdout = self._orig_stdout self._stream = ...
Set's the output file, currently only useful with context-managers. Note: This function is experimental and may not last.
def _render(self): ''' Standard rendering of bar graph. ''' cm_chars = self._comp_style(self.icons[_ic] * self._num_complete_chars) em_chars = self._empt_style(self.icons[_ie] * self._num_empty_chars) return f'{self._first}{cm_chars}{em_chars}{self._last} {self._lbl}f _render(self): ...
Standard rendering of bar graph.
def _render_internal_label(self): ''' Render with a label inside the bar graph. ''' ncc = self._num_complete_chars bar = self._lbl.center(self.iwidth) cm_chars = self._comp_style(bar[:ncc]) em_chars = self._empt_style(bar[ncc:]) return f'{self._first}{cm_chars}{em_chars}{...
Render with a label inside the bar graph.
def _get_ncc(self, width, ratio): ''' Get the number of complete chars. This one figures the remainder for the partial char as well. ''' sub_chars = round(width * ratio * self.partial_chars_len) ncc, self.remainder = divmod(sub_chars, self.partial_chars_len) return n...
Get the number of complete chars. This one figures the remainder for the partial char as well.
def _render(self): ''' figure partial character ''' p_char = '' if not self.done and self.remainder: p_style = self._comp_style if self.partial_char_extra_style: if p_style is str: p_style = self.partial_char_extra_style ...
figure partial character