code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
reconstruction_flags = {} # reconstruction_key_flags = {} for key, item in dic.items(): if type(key) is not str: # import pickle # key = pickle.dumps(key).decode("ascii") import json key = json.dumps(key) reconstruction_flags[path + k...
def recursively_save_dict_contents_to_group(h5file, path, dic)
....
2.035542
2.025768
1.004825
rf = h5file["_reconstruction_flags"] # rkf = h5file["_reconstruction_key_flags"] ans = {} for key, item in h5file[path].items(): dest_key = key # if key in ("_reconstruction_flags", "_reconstruction_key_flags"): if key in "_reconstruction_flags": continue ...
def recursively_load_dict_contents_from_group(h5file, path)
....
2.187544
2.179302
1.003782
parser = argparse.ArgumentParser( description="Send push notifications for a feed") parser.add_argument('--version', action='version', version="%(prog)s " + __version__.__version__) parser.add_argument('feeds', type=str, nargs='*', metavar='feed_url', ...
def parse_args(*args)
Parse the arguments for the command
2.330983
2.31819
1.005518
args = parse_args() logging.basicConfig(level=LOG_LEVELS[min( args.verbosity, len(LOG_LEVELS) - 1)]) loop = asyncio.get_event_loop() loop.run_until_complete(_run(args))
def main()
main entry point
2.867687
2.672987
1.07284
try: resp = self.client.get_project(project_key) except launchdarkly_api.rest.ApiException as ex: msg = "Unable to get environments." resp = "API response was {0} {1}.".format(ex.status, ex.reason) LOG.error("%s %s", msg, resp) sys.exi...
def get_environments(self, project_key: str) -> dict
Retrieve all environments for a given project. Includes name, key, and mobile key. :param project_key: Key for project. :returns: dictionary of environments.
3.357703
3.522883
0.953112
build_env = "/environments/" + self.environment_key + "/on" patch_comment = [{"op": "replace", "path": build_env, "value": state}] try: resp = self.feature.patch_feature_flag( self.project_key, feature_key, patch_comment) except launchdarkly_api.rest...
def update_flag(self, state: str, feature_key: str) \ -> launchdarkly_api.FeatureFlag
Update the flag status for the specified feature flag. :param state: New feature flag state :param featureKey: Feature flag key :returns: FeatureFlag object.
4.209104
4.565925
0.921851
self._write_line('ret = {}') self._write_execute_rows(routine) self._write_line('for row in rows:') num_of_dict = len(routine['columns']) i = 0 while i < num_of_dict: value = "row['{0!s}']".format(routine['columns'][i]) stack = '' ...
def _write_result_handler(self, routine)
Generates code for calling the stored routine in the wrapper method.
2.508128
2.465757
1.017184
query = query.strip() if os.linesep in query: # Query is a multi line query MetadataDataLayer.io.log_very_verbose('Executing query:') MetadataDataLayer.io.log_very_verbose('<sql>{0}</sql>'.format(query)) else: # Query is a single line que...
def _log_query(query)
Logs the query on the console. :param str query: The query.
4.361134
4.32923
1.007369
'''send a public key to request a token. When we call this function, we already have an RSA key at self.key board: the discourse board to post to ''' nonce = str(uuid.uuid4()) data = {'scopes': 'write', 'client_id': self.client_id, 'application_name': 'HelpMe', ...
def request_token(self, board)
send a public key to request a token. When we call this function, we already have an RSA key at self.key board: the discourse board to post to
5.577344
4.642427
1.201385
'''create a Discourse post, given a title, body, board, and token. Parameters ========== title: the issue title body: the issue body board: the discourse board to post to ''' category_url = "%s/categories.json" % board response = requests.get(category_url) if r...
def create_post(self, title, body, board, category, username)
create a Discourse post, given a title, body, board, and token. Parameters ========== title: the issue title body: the issue body board: the discourse board to post to
3.16826
2.729644
1.160686
self._io.title('Loader') if file_names: self.__load_list(config_filename, file_names) else: self.__load_all(config_filename) if self.error_file_names: self.__log_overview_errors() return 1 else: return 0
def main(self, config_filename, file_names=None)
Loads stored routines into the current schema. :param str config_filename: The name of the configuration file of the current project :param list[str] file_names: The sources that must be loaded. If empty all sources (if required) will loaded. :rtype: int The status of exit.
4.950257
4.824435
1.02608
if self.error_file_names: self._io.warning('Routines in the files below are not loaded:') self._io.listing(sorted(self.error_file_names))
def __log_overview_errors(self)
Show info about sources files of stored routines that were not loaded successfully.
10.305415
6.535454
1.576848
key = '@' + name + '@' key = key.lower() class_name = value.__class__.__name__ if class_name in ['int', 'float']: value = str(value) elif class_name in ['bool']: value = '1' if value else '0' elif class_name in ['str']: if qu...
def _add_replace_pair(self, name, value, quote)
Adds a replace part to the map of replace pairs. :param name: The name of the replace pair. :param value: The value of value of the replace pair.
3.489187
3.529738
0.988511
self._read_configuration_file(config_filename) self.connect() self.find_source_files_from_list(file_names) self._get_column_type() self.__read_stored_routine_metadata() self.__get_constants() self._get_old_stored_routine_info() self._get_correct_s...
def __load_list(self, config_filename, file_names)
Loads all stored routines in a list into the RDBMS instance. :param str config_filename: The filename of the configuration file. :param list[str] file_names: The list of files to be loaded.
6.015711
4.99319
1.204783
self._read_configuration_file(config_filename) self.connect() self.__find_source_files() self._get_column_type() self.__read_stored_routine_metadata() self.__get_constants() self._get_old_stored_routine_info() self._get_correct_sql_mode() ...
def __load_all(self, config_filename)
Loads all stored routines into the RDBMS instance. :param str config_filename: string The filename of the configuration file.
5.640845
4.733337
1.191727
config = configparser.ConfigParser() config.read(config_filename) self._source_directory = config.get('loader', 'source_directory') self._source_file_extension = config.get('loader', 'extension') self._source_file_encoding = config.get('loader', 'encoding') self...
def _read_configuration_file(self, config_filename)
Reads parameters from the configuration file. :param str config_filename: The name of the configuration file.
3.47488
3.709075
0.936859
for dir_path, _, files in os.walk(self._source_directory): for name in files: if name.lower().endswith(self._source_file_extension): basename = os.path.splitext(os.path.basename(name))[0] relative_path = os.path.relpath(os.path.join(di...
def __find_source_files(self)
Searches recursively for all source files in a directory.
2.491228
2.374919
1.048974
if os.path.isfile(self._pystratum_metadata_filename): with open(self._pystratum_metadata_filename, 'r') as file: self._pystratum_metadata = json.load(file)
def __read_stored_routine_metadata(self)
Reads the metadata of stored routines from the metadata file.
3.104628
2.745837
1.130667
self._io.writeln('') for routine_name in sorted(self._source_file_names): if routine_name in self._pystratum_metadata: old_metadata = self._pystratum_metadata[routine_name] else: old_metadata = None if routine_name in self._r...
def __load_stored_routines(self)
Loads all stored routines into the RDBMS instance.
2.939759
2.813677
1.044811
clean = {} for key, _ in self._source_file_names.items(): if key in self._pystratum_metadata: clean[key] = self._pystratum_metadata[key] self._pystratum_metadata = clean
def __remove_obsolete_metadata(self)
Removes obsolete entries from the metadata of all stored routines.
4.714932
4.623377
1.019803
with open(self._pystratum_metadata_filename, 'w') as stream: json.dump(self._pystratum_metadata, stream, indent=4, sort_keys=True)
def __write_stored_routine_metadata(self)
Writes the metadata of all stored routines to the metadata file.
3.666055
3.336759
1.098688
for file_name in file_names: if os.path.exists(file_name): routine_name = os.path.splitext(os.path.basename(file_name))[0] if routine_name not in self._source_file_names: self._source_file_names[routine_name] = file_name el...
def find_source_files_from_list(self, file_names)
Finds all source files that actually exists from a list of file names. :param list[str] file_names: The list of file names.
2.209862
2.291227
0.964489
helper = ConstantClass(self._constants_class_name, self._io) helper.reload() constants = helper.constants() for name, value in constants.items(): self._add_replace_pair(name, value, True) self._io.text('Read {0} constants for substitution from <fso>{1}</fso...
def __get_constants(self)
Gets the constants from the class that acts like a namespace for constants and adds them to the replace pairs.
9.228872
7.107918
1.298393
logging.debug('Terminate: %s', self) self.state = VmState.TERMINATED return await self.manager.terminate_vm(self.id)
async def terminate(self)
Terminate vm.
6.791463
4.884809
1.390323
levels = { "NOTSET": logging.NOTSET, "DEBUG": logging.DEBUG, "INFO": logging.INFO, "WARNING": logging.WARNING, "ERROR": logging.ERROR, "CRITICAL": logging.CRITICAL, } if not formatter: if formatter_str: formatter_str = formatter_str ...
def init_logger( name="", handler_path_levels=None, level=logging.INFO, formatter=None, formatter_str=None, datefmt="%Y-%m-%d %H:%M:%S", )
Add a default handler for logger. Args: name = '' or logger obj. handler_path_levels = [['loggerfile.log',13],['','DEBUG'],['','info'],['','notSet']] # [[path,level]] level = the least level for the logger. formatter = logging.Formatter( '%(levelname)-7s %(asctime)s %(name)s (%(file...
1.919343
1.95948
0.979517
sep = kwargs.pop("sep", " ") frame = sys._getframe(1) ln = frame.f_lineno _file = frame.f_globals.get("__file__", "") fn = os.path.split(_file)[-1] return print_logger.info( sep.join(map(unicode, messages)), extra={"ln": ln, "fn": fn} )
def print_info(*messages, **kwargs)
Simple print use logger, print with time / file / line_no. :param sep: sep of messages, " " by default. Basic Usage:: print_info(1, 2, 3) print_info(1, 2, 3) print_info(1, 2, 3) # [2018-10-24 19:12:16] temp_code.py(7): 1 2 3 # [2018-10-24 19:12:16] temp_code.py(8):...
3.775226
4.419569
0.854207
try: if hasattr(model, "knockout_fields"): fields = model.knockout_fields() else: try: fields = model_to_dict(model).keys() except Exception as e: fields = model._meta.get_fields() return fields # Crash proofing ...
def get_fields(model)
Returns a Model's knockout_fields, or the default set of field names.
3.772742
3.2075
1.176225
temp_dict = dict() for field in fields: try: attribute = getattr(obj, str(field)) if isinstance(attribute, list) and all([isinstance(item, models.Model) for item in attribute]): temp_dict[field] = [] for item in attribute: ...
def get_object_data(obj, fields, safe)
Given an object and a list of fields, recursively build an object for serialization. Returns a dictionary.
2.442011
2.375523
1.027989
try: if isinstance(model, str): modelName = model else: modelName = model.__class__.__name__ if field_names: fields = field_names else: fields = get_fields(model) if hasattr(model, "comparator"): comparator =...
def ko_model(model, field_names=None, data=None)
Given a model, returns the Knockout Model and the Knockout ViewModel. Takes optional field names and data.
3.026365
2.873232
1.053296
try: if isinstance(model, str): modelName = model else: modelName = model.__class__.__name__ modelBindingsString = "ko.applyBindings(new " + modelName + "ViewModel(), $('#" + modelName.lower() + "s')[0]);" return modelBindingsString except Exceptio...
def ko_bindings(model)
Given a model, returns the Knockout data bindings.
3.728423
3.605146
1.034195
return ko_data(queryset, field_names, name, safe, return_json=True)
def ko_json(queryset, field_names=None, name=None, safe=False)
Given a QuerySet, return just the serialized representation based on the knockout_fields. Useful for middleware/APIs. Convenience method around ko_data.
4.745715
4.66494
1.017315
try: try: # Get an inital instance of the QS. queryset_instance = queryset[0] except TypeError as e: # We are being passed an object rather than a QuerySet. # That's naughty, but we'll survive. queryset_instance = queryset ...
def ko_data(queryset, field_names=None, name=None, safe=False, return_json=False)
Given a QuerySet, return just the serialized representation based on the knockout_fields as JavaScript.
3.242869
3.130672
1.035838
try: koDataString = ko_data(queryset, field_names) koModelString = ko_model(queryset[0].__class__.__name__, field_names, data=True) koBindingsString = ko_bindings(queryset[0]) koString = koDataString + '\n' + koModelString + '\n' + koBindingsString return koString ...
def ko(queryset, field_names=None)
Converts a Django QuerySet into a complete Knockout implementation.
4.053125
3.572398
1.134567
'''load a keypair from a keypair file. We add attributes key (the raw key) and public_key (the url prepared public key) to the client. Parameters ========== keypair_file: the pem file to load. ''' from Crypto.PublicKey import RSA # Load key with open(keypair_file, 'rb')...
def load_keypair(keypair_file)
load a keypair from a keypair file. We add attributes key (the raw key) and public_key (the url prepared public key) to the client. Parameters ========== keypair_file: the pem file to load.
6.037376
2.384024
2.532431
'''generate_keypair is used by some of the helpers that need a keypair. The function should be used if the client doesn't have the attribute self.key. We generate the key and return it. We use pycryptodome (3.7.2) Parameters ========= keypair_file: fullpath to whe...
def generate_keypair(keypair_file)
generate_keypair is used by some of the helpers that need a keypair. The function should be used if the client doesn't have the attribute self.key. We generate the key and return it. We use pycryptodome (3.7.2) Parameters ========= keypair_file: fullpath to where to s...
5.159082
1.849018
2.790174
query = query.strip() message = 'Wrong number of rows selected' message += os.linesep message += 'Expected number of rows: {}'.format(expected_row_count) message += os.linesep message += 'Actual number of rows: {}'.format(actual_row_count) message += os....
def __message(expected_row_count, actual_row_count, query)
Composes the exception message. :param str expected_row_count: The expected row count. :param int actual_row_count: The actual row count. :param str query: The query. :rtype: str
2.289649
2.560519
0.894213
'''submit the issue to github. When we get here we should have: {'user_prompt_issue': 'I want to do the thing.', 'user_prompt_repo': 'vsoch/hello-world', 'user_prompt_title': 'Error with this thing', 'record_asciinema': '/tmp/helpme.93o__nt5.json', ...
def _submit(self)
submit the issue to github. When we get here we should have: {'user_prompt_issue': 'I want to do the thing.', 'user_prompt_repo': 'vsoch/hello-world', 'user_prompt_title': 'Error with this thing', 'record_asciinema': '/tmp/helpme.93o__nt5.json', '...
7.192987
2.650163
2.714168
resolver = jsonschema.RefResolver(uri, spec) def _do_resolve(node): if isinstance(node, collections.Mapping) and '$ref' in node: with resolver.resolving(node['$ref']) as resolved: result = deepcopy(resolved) for key in resolved: if ke...
def resolve_refs(uri, spec)
Resolve JSON references in a given dictionary. OpenAPI spec may contain JSON references to its nodes or external sources, so any attempt to rely that there's some expected attribute in the spec may fail. So we need to resolve JSON references before we use it (i.e. replace with referenced object). For d...
2.007642
2.159086
0.929857
'''This is the actual driver for the helper. ''' from helpme.main import get_helper name = args.command if name in HELPME_HELPERS: # Get the helper, do the recording, submit helper = get_helper(name=name) if args.asciinema is not None: if os.path.exists(args....
def main(args, extras)
This is the actual driver for the helper.
8.305089
7.12178
1.166153
# Clean HTML html_extractor = self.html_extractor( html_contents, self._xpaths_to_keep, self._xpaths_to_discard) has_matches = html_extractor.parse() if has_matches: # Relative to absolute URLs if base_url is not None: html_e...
def extract(self, html_contents, css_contents=None, base_url=None)
Extracts the cleaned html tree as a string and only css rules matching the cleaned html tree :param html_contents: The HTML contents to parse :type html_contents: str :param css_contents: The CSS contents to parse :type css_contents: str :param base_url: The base page UR...
2.549251
2.569776
0.992013
assert isinstance(xpath, string_types) dest.append(xpath)
def __add(self, dest, xpath)
Adds a Xpath expression to the dest list :param dest: The destination list to add the Xpath :type dest: list :param xpath: The Xpath expression to add :type xpath: str
8.713001
8.087366
1.07736
if line is None: self._write("\n") if self.__indent_level > 1: self.__indent_level -= 1 elif line == '': self._write("\n") else: line = (' ' * 4 * self.__indent_level) + line if line[-1:] == ':': ...
def _write_line(self, line=None)
Appends a line of code to the generated code and adjust the indent level of the generated code. :param line: The line of code (with out LF) that must be appended.
2.831627
2.87537
0.984787
tmp = self._page_width - ((4 * self.__indent_level) + 2) self._write_line('# ' + ('-' * tmp))
def _write_separator(self)
Inserts a horizontal (commented) line tot the generated code.
12.116748
9.701166
1.248999
if self._lob_as_string_flag: return self._write_routine_method_without_lob(routine) else: if self.is_lob_parameter(routine['parameters']): return self._write_routine_method_with_lob(routine) else: return self._write_routine_met...
def write_routine_method(self, routine)
Returns a complete wrapper method. :param dict[str,*] routine: The routine metadata. :rtype: str
3.48679
3.491386
0.998684
if routine['pydoc']['parameters']: self._write_line('') for param in routine['pydoc']['parameters']: lines = param['description'].split(os.linesep) self._write_line(':param {0} {1}: {2}'.format(param['python_type'], ...
def _write_docstring_parameters(self, routine)
Writes the parameters part of the docstring for the wrapper method of a stored routine. :param dict routine: The metadata of the stored routine.
3.044513
3.106808
0.979949
rtype = self._get_docstring_return_type() if rtype: self._write_line('') self._write_line(':rtype: {0}'.format(rtype))
def __write_docstring_return_type(self)
Writes the return type part of the docstring for the wrapper method of a stored routine.
3.607216
3.424374
1.053394
self._write_line('')
def __write_docstring(self, routine)
Writes the docstring for the wrapper method of a stored routine. :param dict routine: The metadata of the stored routine.
51.023911
93.861565
0.543608
ret = '' for parameter_info in routine['parameters']: if ret: ret += ', ' ret += parameter_info['name'] return ret
def _get_wrapper_args(routine)
Returns code for the parameters of the wrapper method for the stored routine. :param dict[str,*] routine: The routine metadata. :rtype: str
5.894637
4.940191
1.1932
template = self.env.get_template('ld-relay.conf.jinja') with open('ld-relay.conf', 'w') as ld_relay_config: template = template.render( envs=environments ) ld_relay_config.write(template)
def generate_relay_config(self, environments: list) -> None
Generate ld-relay.conf file. Given a list of environments of a project, this will generate a ``ld-relay.conf`` file in the current working directory. The conf file follows the specification that is documented in the main `ld-relay`_ documentation. .. _ld-relay: https://github.c...
3.745524
3.125797
1.198262
parts = self.__class_name.split('.') module_name = ".".join(parts[:-1]) module = __import__(module_name) modules = [] for comp in parts[1:]: module = getattr(module, comp) modules.append(module) self.__module = modules[-2]
def __load(self)
Loads dynamically the class that acts like a namespace for constants.
3.020241
2.758874
1.094737
ret = {} name = self.__class_name.split('.')[-1] constant_class = getattr(self.__module, name) for name, value in constant_class.__dict__.items(): if re.match(r'^[A-Z][A-Z0-9_]*$', name): ret[name] = value return ret
def constants(self)
Gets the constants from the class that acts like a namespace for constants. :rtype: dict<str,*>
3.377106
3.19076
1.058402
ret = {'start_line': 0, 'last_line': 0, 'indent': ''} mode = 1 count = 0 for line in lines: if mode == 1: if line.strip() == self.__annotation: ret['start_line'] = count + 1 r...
def __extract_info(self, lines)
Extracts the following info from the source of the module with the class that acts like a namespace for constants: * Start line with constants * Last line with constants * Indent for constants :param list[str] lines: The source of the module with the class that acts like a names...
2.863928
2.831107
1.011593
old_lines = self.source().split("\n") info = self.__extract_info(old_lines) new_lines = old_lines[0:info['start_line']] for constant, value in sorted(constants.items()): new_lines.append("{0}{1} = {2}".format(info['indent'], str(constant), str(value))) new...
def source_with_constants(self, constants)
Returns the source of the module with the class that acts like a namespace for constants with new constants. :param dict[str,int] constants: The new constants. :rtype: str
3.026628
2.980103
1.015612
'''return the full path for the user configuration file. If doesn't exist, create it for the user. ''' from helpme.defaults import HELPME_CLIENT_SECRETS # The inital file has a funny username if not os.path.exists(HELPME_CLIENT_SECRETS): bot.debug('Generating settings file at %s' % ...
def get_configfile_user()
return the full path for the user configuration file. If doesn't exist, create it for the user.
5.730742
4.931616
1.162041
'''remove a setting from the global config ''' removed = False config = _load_config(configfile) if section in config: if name.lower() in config[section]: removed = config.remove_option(section, name) # Does the user want to save the file? if removed and save: wr...
def _remove_setting(section, name, configfile, save=False)
remove a setting from the global config
3.555872
3.429862
1.036739
'''remove a setting from the global config ''' configfile = get_configfile() return _remove_setting(section, name, configfile, save)
def remove_setting(self, section, name, save=False)
remove a setting from the global config
6.189877
5.986066
1.034048
'''remove a setting from the user config ''' configfile = get_configfile_user() return _remove_setting(section, name, configfile, save)
def remove_user_setting(self, section, name, save=False)
remove a setting from the user config
6.401444
6.680067
0.958291
'''general function to load and return a configuration given a helper name. This function is used for both the user config and global help me config files. ''' if os.path.exists(configfile): config = read_config(configfile) if section is not None: if section in conf...
def _load_config(configfile, section=None)
general function to load and return a configuration given a helper name. This function is used for both the user config and global help me config files.
6.974555
2.589403
2.693499
'''load a tuple of environment variables, to add to the user settings Example: items = [('HELPME_DISCOURSE_BOARD', 'user_prompt_board'), ('HELPME_DISCOURSE_CATEGORY', 'user_prompt_category')] # Note that it's added to the client with an underscore: self._load...
def load_envars(self, items)
load a tuple of environment variables, to add to the user settings Example: items = [('HELPME_DISCOURSE_BOARD', 'user_prompt_board'), ('HELPME_DISCOURSE_CATEGORY', 'user_prompt_category')] # Note that it's added to the client with an underscore: self._load_envars...
8.710684
2.370024
3.675357
'''return a setting from the environment (first priority) and then secrets (second priority) if one can be found. If not, return None. Parameters ========== section: the section in the config, defaults to self.name name: they key (index) of the setting to look up default: ...
def get_setting(self, name, section=None, default=None, user=True)
return a setting from the environment (first priority) and then secrets (second priority) if one can be found. If not, return None. Parameters ========== section: the section in the config, defaults to self.name name: they key (index) of the setting to look up default: (option...
6.369966
2.865871
2.222698
'''get all settings for a client, if defined in config. ''' config = self._load_config_user() if self.name in config: return config[self.name]
def get_settings(self)
get all settings for a client, if defined in config.
10.095793
5.256933
1.920472
'''update client secrets will update the data structure for a particular authentication. This should only be used for a (quasi permanent) token or similar. The secrets file, if found, is updated and saved by default. Parameters ========== helper: the name of the helper to look up...
def update_settings(self, updates, config=None)
update client secrets will update the data structure for a particular authentication. This should only be used for a (quasi permanent) token or similar. The secrets file, if found, is updated and saved by default. Parameters ========== helper: the name of the helper to look up in the...
8.682496
2.107502
4.119805
'''Look for a setting in the environment (first priority) and then the settings file (second). If something is found, the settings file is updated. The order of operations works as follows: 1. The user config file is used as a cache for the variable 2. the environment variable always ta...
def get_and_update_setting(self, name, default=None, user=True)
Look for a setting in the environment (first priority) and then the settings file (second). If something is found, the settings file is updated. The order of operations works as follows: 1. The user config file is used as a cache for the variable 2. the environment variable always takes pri...
8.412589
1.754715
4.794277
if app not in argv[:2]: # app is automatically added if not present argv.insert(1, app) if len(argv) < 3 and 'test' not in argv[:2]: # test argument is given if not argument is passed argv.insert(2, 'test') if extra_args: argv.extend(extra_args) return runner...
def run(app, argv=sys.argv, extra_args=None)
Run commands in a plain django environment :param app: application :param argv: arguments (default to sys.argv) :param extra_args: list of extra arguments
4.853858
5.165517
0.939665
try: import cms # NOQA # nopyflakes except ImportError: print('runner.cms is available only if django CMS is installed') raise if app not in argv[:2]: # app is automatically added if not present argv.insert(1, app) if len(argv) < 3 and 'test' not in argv[:2...
def cms(app, argv=sys.argv, extra_args=None)
Run commands in a django cMS environment :param app: application :param argv: arguments (default to sys.argv) :param extra_args: list of extra arguments
4.842338
4.984498
0.971479
helper = helper_module.__file__ argv = [os.path.basename(helper), app, 'setup', '--extra-settings={0}'.format(helper)] if use_cms: argv.append('--cms') if extra_args: argv.extend(extra_args) return runner(argv)
def setup(app, helper_module, extra_args=None, use_cms=False)
Setup the Django / django CMS environment and return the environment settings. :param app: application :param helper_module: helper module :param extra_args: list of extra arguments :param use_cms: setup a django CMS environemtn :return: Django settings module
3.781158
3.872945
0.976301
# Create the element tree self.tree = self._build_tree(self.html_contents) # Get explicits elements to keep and discard self.elts_to_keep = self._get_elements_to_keep() self.elts_to_discard = self._get_elements_to_discard() # Init an empty list of Elements to r...
def parse(self)
Returns a cleaned lxml ElementTree :returns: Whether the cleaned HTML has matches or not :rtype: bool
4.537522
4.078918
1.112433
# Delete target attributes strip_attributes(self.tree, 'target') # Absolute links self.tree.rewrite_links( lambda link: urljoin(base_url, link) if not link.startswith(self.rel_to_abs_excluded_prefixes) else link) # Extra attributes oncli...
def rel_to_abs(self, base_url)
Converts relative links from html contents to absolute links
4.838955
4.613654
1.048833
return list(chain(*[self.tree.xpath(xpath) for xpath in source]))
def _get_elements(self, source)
Returns the list of HtmlElements for the source :param source: The source list to parse :type source: list :returns: A list of HtmlElements :rtype: list
7.900809
11.081531
0.712971
for e in elt.iterchildren(): is_discard_element = self._is_discard(e) is_keep_element = self._is_keep(e) # Element is an explicit one to discard, flag it and continue if is_discard_element and not is_keep_element: self.elts_to_remove.app...
def _parse_element(self, elt, parent_is_keep=False)
Parses an Element recursively :param elt: HtmlElement to parse :type elt: lxml.html.HtmlElement :param parent_is_keep: Whether the element is inside a keep element or not :type parent_is_keep: bool
3.386459
3.409296
0.993302
# iterdescendants is a generator, don't cast it as a list to avoid # parsing the whole descendants tree if not necessary for d in elt.iterdescendants(): if d in self.elts_to_keep: return True return False
def _has_keep_elt_in_descendants(self, elt)
Returns whether the element has a descendant to keep or not :param elt: The HtmlElement to check :type elt: lxml.html.HtmlElement :returns: True if the element has a keep element in its descendants :rtype: bool
8.145969
8.550468
0.952693
for e in elts_to_remove: # Get the element parent parent = e.getparent() # lxml also remove the element tail, preserve it if e.tail and e.tail.strip(): parent_text = parent.text or '' parent.text = parent_text + e.tail ...
def _remove_elements(self, elts_to_remove)
Removes flagged elements from the ElementTree
4.25232
4.240867
1.002701
namespace = System.getServiceType("getSystemInfo") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return SystemInfo(results)
def getSystemInfo(self, timeout=1)
Execute GetInfo action to get information's about the System on the device. :return: information's about the System on the device. :rtype: SystemInfo
14.026791
10.55747
1.328613
namespace = System.getServiceType("reboot") uri = self.getControlURL(namespace) self.execute(uri, namespace, "Reboot", timeout=timeout)
def reboot(self, timeout=1)
Reboot the device
20.29789
18.574314
1.092793
namespace = System.getServiceType("getTimeInfo") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return TimeInfo(results)
def getTimeInfo(self, timeout=1)
Execute GetInfo action to get information's about the time on the device. :return: information's about the time on the device. :rtype: TimeInfo
15.795179
12.984035
1.216508
namespace = System.getServiceType("softwareUpdateAvailable") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return bool(int(results["NewUpgradeAvailable"]))
def softwareUpdateAvailable(self, timeout=1)
Returns if a software update is available :return: if a software update is available :rtype: bool
16.159628
17.068502
0.946751
out = {} if 'etag' in headers: out['if-none-match'] = headers['etag'] if 'last-modified' in headers: out['if-modified-since'] = headers['last-modified'] return out
def make_headers(headers)
Make the cache control headers based on a previous request's response headers
2.266882
2.030581
1.116371
if not self.cache_dir: return None filename = self._get_cache_file(prefix, url) try: with open(filename, 'rb') as file: item = pickle.load(file) if schema_version and schema_version != item.schema: LOGGER.debug("Cache...
def get(self, prefix, url, schema_version=None)
Get the cached object
2.951381
2.831578
1.04231
if not self.cache_dir: return filename = self._get_cache_file(prefix, url) try: os.makedirs(os.path.join(self.cache_dir, prefix)) except OSError: pass with open(filename, 'wb') as file: pickle.dump(obj, file)
def set(self, prefix, url, obj)
Add an object into the cache
2.374953
2.31326
1.026669
if "get_root" in kwargs: get_root = kwargs["get_root"] else: # default value get_root = False sdp = dataset_path(get_root=get_root) pth = os.path.join(sdp, *path_to_join) logger.debug("sample_data_path" + str(sdp)) logger.debug("path " + str(pth)) return pth
def join_path(*path_to_join, **kwargs)
Join input path to sample data path (usually in ~/lisa_data) :param path_to_join: one or more paths :param get_root: return dataset root path. If false, the path would be into "medical/orig" :return: joined path
3.881356
3.129646
1.24019
if cachefile is not None: cache = cachef.CacheFile(cachefile) cache.update("local_dataset_dir", path)
def set_dataset_path(path, cache=None, cachefile="~/.io3d_cache.yaml")
Sets path to dataset. Warning: function with side effects! :param path: path you want to store dataset :param cache: CacheFile object :param cachefile: default '~/.io3d_cache.yaml'
8.434862
8.419966
1.001769
local_data_dir = local_dir if cachefile is not None: cache = cachef.CacheFile(cachefile) # cache.update('local_dataset_dir', head) if cache is not None: local_data_dir = cache.get_or_save_default("local_dataset_dir", local_dir) if get_root: local_data_dir else:...
def dataset_path(cache=None, cachefile="~/.io3d_cache.yaml", get_root=False)
Get dataset path. :param cache: CacheFile object :param cachefile: cachefile path, default '~/.io3d_cache.yaml' :return: path to dataset
4.830505
5.109081
0.945474
data_url = data_urls[label] if type(data_url) == str: # back compatibility data_url = [data_url] if type(data_url) == list: data_url.extend([None, None, None, None]) data_url = data_url[:4] url, expected_hash, hash_path, relative_donwload_dir = data_url i...
def get_dataset_meta(label)
Gives you metadata for dataset chosen via 'label' param :param label: label = key in data_url dict (that big dict containing all possible datasets) :return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir) relative_download_dir says where will be downloaded the file from url and event...
3.611974
2.62876
1.374022
new_dataset_label_dict = [] for label in dataset_label_dict: dataset_metadata = data_urls[label] if type(dataset_metadata) == dict and "package" in dataset_metadata: new_dataset_label_dict.extend(dataset_metadata["package"]) else: new_dataset_label_dict.appen...
def _expand_dataset_packages(dataset_label_dict)
Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'. In case the param is not pointing to multidataset returns only that label in a list. :param str dataset_label_dict: label of multi dataset :return: list of labels
2.44645
2.708772
0.903158
if destination_dir is None: destination_dir = op.join(dataset_path(get_root=True), "medical", "orig") destination_dir = op.expanduser(destination_dir) logger.info("destination dir: {}".format(destination_dir)) if dataset_label is None: dataset_label = data_urls.keys() if type...
def download(dataset_label=None, destination_dir=None, dry_run=False)
Download sample data by data label. Warning: function with side effect! Labels can be listed by sample_data.data_urls.keys(). Returns downloaded files. :param dataset_label: label of data. If it is set to None, all data are downloaded :param destination_dir: output dir for data :param dry_run: runs fu...
2.647283
2.660317
0.9951
# TODO implement if destination_dir is None: destination_dir = op.join(dataset_path(get_root=True), "medical", "orig") destination_dir = op.expanduser(destination_dir) data_url, url, expected_hash, hash_path, relative_output_path = get_dataset_meta( dataset_label ) paths = ...
def get_old(dataset_label, data_id, destination_dir=None)
Get the 3D data from specified dataset with specified id. Download data if necessary. :param dataset_label: :param data_id: integer or wildcards file pattern :param destination_dir: :return:
5.409882
5.219469
1.036481
import checksumdir hash_func = checksumdir.HASH_FUNCS.get(hashfunc) if not hash_func: raise NotImplementedError("{} not implemented.".format(hashfunc)) if os.path.isdir(path): return checksumdir.dirhash(path, hashfunc=hashfunc) hashvalues = [] path_list = list(sorted(glob...
def checksum(path, hashfunc="md5")
Return checksum of files given by path. Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'. :param path: path of files to get hash from :param hashfunc: function used to get hash, default 'md5' :return: (str) hash of the file/files given by path
2.558073
2.534621
1.009253
segmentation = np.zeros([20, 30, 40]) # generate test data segmentation[6:10, 7:24, 10:37] = 1 segmentation[6:10, 7, 10] = 0 segmentation[6:10, 23, 10] = 0 segmentation[6:10, 7, 36] = 0 segmentation[6:10, 23, 36] = 0 segmentation[2:18, 12:19, 18:28] = 2 data3d = segmentation * ...
def generate_donut()
Generate donut like shape with stick inside :return: dict {'data3d': '', 'segmentation': '', 'voxelsize_mm': ''}
3.039278
2.644797
1.149153
import scipy.ndimage # seedsz= int(sz/10) space = 2 seeds = np.zeros([sz, sz + 1, sz + 2], dtype=np.int8) xmin = radius + seedsz + offset + 2 ymin = radius + seedsz + offset + 6 seeds[offset + 12, xmin + 3 : xmin + 7 + seedsz, ymin : ymin + 2] = 1 seeds[offset + 20, xmin + 7 : xmi...
def generate_round_data( sz=32, offset=0, radius=7, seedsz=3, add_object_without_seeds=False )
Generate data with two sphere objects. :param sz: output data shape is [sz, sz+1, sz+2] :param offset: :param radius: :param seedsz: :param add_object_without_seeds: Add also one cube-like object in the corner. :return:
3.477057
3.356777
1.035832
# data slab = {"none": 0, "liver": 1, "porta": 2} voxelsize_mm = np.array([1.0, 1.0, 1.2]) segm = np.zeros([80, 256, 250], dtype=np.int16) # liver segm[30:60, 70:180, 40:190] = slab["liver"] # porta segm[40:45, 120:130, 70:190] = slab["porta"] segm[41:44, 122:127, 68:70] = sl...
def generate_synthetic_liver(return_dataplus=False)
Create synthetic data. There is some liver and porta -like object. :return data3d, segmentation, voxelsize_mm, slab, seeds_liver, seeds_porta:
2.374689
2.160983
1.098893
# data3d = np.zeros([1,7,7], dtype=np.int16) if shape is None: shape = [32, 32] center = (np.asarray(shape) - 1) / 2.0 r = np.min(center) * face_r # np.min(np.asarray(shape) / 2.0) # shape = data3d.shape[1:] # data3d[center[0], center[1], center[2]] = 1 x, y = np.meshgrid...
def _get_face2(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2)
Create 2D binar face :param shape: :param face_r: :param smile_r1: :param smile_r2: :param eye_r: :return:
2.3271
2.328441
0.999424
# TODO add axis (ax=0) if shape is None: shape = [32, 32] nd = len(shape) if nd == 2: sh2 = shape else: sh2 = shape[1:] fc2 = _get_face2( sh2, face_r=face_r, smile_r1=smile_r1, smile_r2=smile_r2, eye_r=eye_r ) if nd == 2: return fc2 else:...
def generate_face(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2)
Create 2D or 3D binar data with smile face. :param shape: 2D or 3D shape of data :param face_r: :param smile_r1: :param smile_r2: :param eye_r: :return: binar ndarray
2.790615
2.654101
1.051435
try: os.remove(local_file_name) except Exception as e: print( "Cannot remove file '" + local_file_name + "'. Please remove it manually." ) print(e)
def remove(local_file_name)
Function attempts to remove file, if failure occures -> print exception :param local_file_name: name of file to remove
2.890063
3.139261
0.920619
# url = "http://147.228.240.61/queetech/sample-data/jatra_06mm_jenjatra.zip" logmsg = "downloading from '" + url + "' to '" + destination + "'" print(logmsg) logger.info(logmsg) tmp_filename = url[url.rfind("/") + 1 :] # tmp_filename = "tmp.zip" # urllibr.urlretrieve(url, zip_file_name...
def downzip(url, destination="./sample_data/")
Download, unzip and delete. Warning: function with strong side effects! Returns downloaded data. :param str url: url from which data should be donloaded :param destination: destination to which data should be downloaded
5.430923
5.753888
0.94387
local_file_name = op.expanduser(local_file_name) destination = op.dirname(local_file_name) datafile = zipfile.ZipFile(local_file_name) namelist = datafile.namelist() datafile.extractall(destination) datafile.close() remove(local_file_name) fullnamelist = [] for fn in namelist: ...
def unzip_one(local_file_name)
Unzips one file and deletes it. Warning: function with side effects! :param str local_file_name: file name of zip file :return: list of archive members by name.
2.50223
2.906572
0.860887
logger.debug("unzipping " + zip_file_name) fnlist = unzip_one(zip_file_name) for fn in fnlist: if zipfile.is_zipfile(fn): local_fnlist = unzip_recursive(fn) fnlist.extend(local_fnlist) return fnlist
def unzip_recursive(zip_file_name)
Unzip file with all recursive zip files inside and delete zip files after that. :param zip_file_name: file name of zip file :return: list of archive members by name.
2.737062
2.926274
0.93534
'''a wrapper around generation of an asciinema.api.Api to call the upload command given an already existing asciinema file. Parameters ========== filename: the asciinema file to upload, can be generated with function record_asciinema in record.py ''' if os.p...
def upload_asciinema(filename)
a wrapper around generation of an asciinema.api.Api to call the upload command given an already existing asciinema file. Parameters ========== filename: the asciinema file to upload, can be generated with function record_asciinema in record.py
8.030174
4.624721
1.736359
if not app_config['DOCKER_TLS']: return False cert_path = app_config['DOCKER_TLS_CERT_PATH'] if cert_path: client_cert = '{0}:{1}'.format( os.path.join(cert_path, 'cert.pem'), os.path.join(cert_path, 'key.pem')) ca_cert = os.path.join(cert_path, 'ca.pem...
def make_tls_config(app_config)
Creates TLS configuration object.
1.877184
1.836172
1.022336
if not config_value: return client_cert = config_value.split(':') if len(client_cert) != 2: tips = ('client_cert should be formatted like ' '"/path/to/cert.pem:/path/to/key.pem"') raise ValueError('{0!r} is invalid.\n{1}'.format(config_value, tips)) return tu...
def parse_client_cert_pair(config_value)
Parses the client cert pair from config item. :param config_value: the string value of config item. :returns: tuple or none.
3.173428
3.309977
0.958746
app.extensions = getattr(app, 'extensions', {}) app.extensions['docker.client'] = None app.config.setdefault('DOCKER_URL', None) app.config.setdefault('DOCKER_VERSION', '1.16') app.config.setdefault('DOCKER_TIMEOUT', 30) app.config.setdefault('DOCKER_TLS', False...
def init_app(self, app)
Initializes an application for using :class:`docker.Client`. :param app: an instance of :class:`~flask.Flask`.
1.957435
1.976251
0.990479