code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def init_checker_state(self, name, argument_names): if 'checker_state' in argument_names: self.checker_state = self._checker_states.setdefault(name, {})
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier dictionary
Prepare custom state for the specific checker plugin.
def _set_client_id(self, client_id): with self.lock: if self.client_id is None: self.client_id = client_id
module function_definition identifier parameters identifier identifier block with_statement with_clause with_item attribute identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier identifier
Method for tracer to set client ID of throttler.
def _write_config(self): param_dict = { 'url': self._params.url, 'snapshot_paths': self._params.snapshot_paths, 'wait_time': self._params.wait_time, 'num_scrolls': self._params.num_scrolls, 'smart_scroll': self._params.smart_scroll, 'snapshot': self._params.snapshot, 'viewport_width': self._params.viewport_size[0], 'viewport_height': self._params.viewport_size[1], 'paper_width': self._params.paper_size[0], 'paper_height': self._params.paper_size[1], 'custom_headers': self._params.custom_headers, 'page_settings': self._params.page_settings, } if self._params.event_log_filename: param_dict['event_log_filename'] = \ os.path.abspath(self._params.event_log_filename) if self._params.action_log_filename: param_dict['action_log_filename'] = \ os.path.abspath(self._params.action_log_filename) config_text = json.dumps(param_dict) self._config_file.write(config_text.encode('utf-8')) self._config_file.close()
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end subscript attribute attribute identifier identifier identifier integer pair string string_start string_content string_end subscript attribute attribute identifier identifier identifier integer pair string string_start string_content string_end subscript attribute attribute identifier identifier identifier integer pair string string_start string_content string_end subscript attribute attribute identifier identifier identifier integer pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute attribute identifier identifier identifier if_statement attribute attribute identifier identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end line_continuation call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier if_statement attribute attribute identifier identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end line_continuation call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list
Write the parameters to a file for PhantomJS to read.
def remove_args(parser): arguments = [] for action in list(parser._get_optional_actions()): if '--help' not in action.option_strings: arguments += action.option_strings for arg in arguments: if arg in sys.argv: sys.argv.remove(arg)
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement augmented_assignment identifier attribute identifier identifier for_statement identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Remove custom arguments from the parser
def analyze(self, webpage): detected_apps = set() for app_name, app in self.apps.items(): if self._has_app(app, webpage): detected_apps.add(app_name) detected_apps |= self._get_implied_apps(detected_apps) return detected_apps
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement call attribute identifier identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier
Return a list of applications that can be detected on the web page.
def parse_timestr(timestr): timedelta_secs = parse_timedelta(timestr) sync_start = datetime.now() if timedelta_secs: target = datetime.now() + timedelta(seconds=timedelta_secs) elif timestr.isdigit(): target = datetime.now() + timedelta(seconds=int(timestr)) else: try: target = parse(timestr) except: raise ValueError("Unable to parse '{}'".format(timestr)) sync_start = sync_start.replace(microsecond=0) try: target = target.astimezone(tz=tz.tzlocal()).replace(tzinfo=None) except ValueError: pass return (sync_start, target)
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier identifier elif_clause call attribute identifier identifier argument_list block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier call identifier argument_list identifier else_clause block try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier integer try_statement block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list identifier argument_list keyword_argument identifier none except_clause identifier block pass_statement return_statement tuple identifier identifier
Parse a string describing a point in time.
def const_shuffle(arr, seed=23980): old_seed = np.random.seed() np.random.seed(seed) np.random.shuffle(arr) np.random.seed(old_seed)
module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Shuffle an array in-place with a fixed seed.
def buffer_leave(self, filename): self.log.debug('buffer_leave: %s', filename) self.editor.clean_errors()
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list
User is changing of buffer.
def digest(self): total = 0 if self.count == 3: total = 1 elif self.count == 4: total = 4 elif self.count > 4: total = 8 * self.count - 28 threshold = total / 256 code = [0]*32 for i in range(256): if self.acc[i] > threshold: code[i >> 3] += 1 << (i&7) return code[::-1]
module function_definition identifier parameters identifier block expression_statement assignment identifier integer if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier integer elif_clause comparison_operator attribute identifier identifier integer block expression_statement assignment identifier integer elif_clause comparison_operator attribute identifier identifier integer block expression_statement assignment identifier binary_operator binary_operator integer attribute identifier identifier integer expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator list integer integer for_statement identifier call identifier argument_list integer block if_statement comparison_operator subscript attribute identifier identifier identifier identifier block expression_statement augmented_assignment subscript identifier binary_operator identifier integer binary_operator integer parenthesized_expression binary_operator identifier integer return_statement subscript identifier slice unary_operator integer
Get digest of data seen thus far as a list of bytes.
def generated_key(key): key_name = key['name'] if key['method'] == 'uuid': LOG.debug("Setting %s to a uuid", key_name) return str(uuid4()) elif key['method'] == 'words': LOG.debug("Setting %s to random words", key_name) return random_word() elif key['method'] == 'static': if 'value' not in key.keys(): raise aomi.exceptions.AomiData("Missing static value") LOG.debug("Setting %s to a static value", key_name) return key['value'] else: raise aomi.exceptions.AomiData("Unexpected generated secret method %s" % key['method'])
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement call identifier argument_list call identifier argument_list elif_clause comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement call identifier argument_list elif_clause comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block if_statement comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block raise_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement subscript identifier string string_start string_content string_end else_clause block raise_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end
Create the proper generated key value
def _save(self): fname = self.filename() def _write_file(fname): if PY2: with codecs.open(fname, 'w', encoding='utf-8') as configfile: self._write(configfile) else: with open(fname, 'w', encoding='utf-8') as configfile: self.write(configfile) try: _write_file(fname) except EnvironmentError: try: if osp.isfile(fname): os.remove(fname) time.sleep(0.05) _write_file(fname) except Exception as e: print("Failed to write user configuration file to disk, with " "the exception shown below") print(e)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list function_definition identifier parameters identifier block if_statement identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier try_statement block expression_statement call identifier argument_list identifier except_clause identifier block try_statement block if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list float expression_statement call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list identifier
Save config into the associated .ini file
def surface(self, tag): if tag.cfrom is not None and tag.cto is not None and tag.cfrom >= 0 and tag.cto >= 0: return self.text[tag.cfrom:tag.cto] else: return ''
module function_definition identifier parameters identifier identifier block if_statement boolean_operator boolean_operator boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier integer comparison_operator attribute identifier identifier integer block return_statement subscript attribute identifier identifier slice attribute identifier identifier attribute identifier identifier else_clause block return_statement string string_start string_end
Get surface string that is associated with a tag object
def getFlags (self, ifname): try: result = self._ioctl(self.SIOCGIFFLAGS, self._getifreq(ifname)) except IOError as msg: log.warn(LOG_CHECK, "error getting flags for interface %r: %s", ifname, msg) return 0 flags, = struct.unpack('H', result[16:18]) return flags
module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier identifier return_statement integer expression_statement assignment pattern_list identifier call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier slice integer integer return_statement identifier
Get the flags for an interface
def list_to_tree(cls, files): def attach(branch, trunk): parts = branch.split('/', 1) if len(parts) == 1: trunk[FILE_MARKER].append(parts[0]) else: node, others = parts if node not in trunk: trunk[node] = defaultdict(dict, ((FILE_MARKER, []), )) attach(others, trunk[node]) tree = defaultdict(dict, ((FILE_MARKER, []), )) for line in files: attach(line, tree) return tree
module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call attribute subscript identifier identifier identifier argument_list subscript identifier integer else_clause block expression_statement assignment pattern_list identifier identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier tuple tuple identifier list expression_statement call identifier argument_list identifier subscript identifier identifier expression_statement assignment identifier call identifier argument_list identifier tuple tuple identifier list for_statement identifier identifier block expression_statement call identifier argument_list identifier identifier return_statement identifier
Converts a list of filenames into a directory tree structure.
def compare_variants_label_plot(data): keys = OrderedDict() keys['total_called_variants_known'] = {'name': 'Known Variants'} keys['total_called_variants_novel'] = {'name': 'Novel Variants'} pconfig = { 'id': 'picard_variantCallingMetrics_variant_label', 'title': 'Picard: Variants Called', 'ylab': 'Counts of Variants', } return bargraph.plot(data, cats=keys, pconfig=pconfig)
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier
Return HTML for the Compare variants plot
def make_important(bulk): return ";".join( "%s !important" % p if not p.endswith("!important") else p for p in bulk.split(";") )
module function_definition identifier parameters identifier block return_statement call attribute string string_start string_content string_end identifier generator_expression conditional_expression binary_operator string string_start string_content string_end identifier not_operator call attribute identifier identifier argument_list string string_start string_content string_end identifier for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content string_end
makes every property in a string !important.
def download_tar(self, url, untar=True, delete_after_untar=False, destination_dir='.'): try: floyd_logger.info("Downloading the tar file to the current directory ...") filename = self.download(url=url, filename='output.tar') if filename and untar: floyd_logger.info("Untarring the contents of the file ...") tar = tarfile.open(filename) tar.extractall(path=destination_dir) tar.close() if delete_after_untar: floyd_logger.info("Cleaning up the tar file ...") os.remove(filename) return filename except FloydException as e: floyd_logger.info("Download URL ERROR! {}".format(e.message)) return False
module function_definition identifier parameters identifier identifier default_parameter identifier true default_parameter identifier false default_parameter identifier string string_start string_content string_end block try_statement block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end if_statement boolean_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier return_statement false
Download and optionally untar the tar file from the given url
def head_values(self): values = set() for head in self._heads: values.add(head.value) return values
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier
Return set of the head values
def language_model_learner(data:DataBunch, arch, config:dict=None, drop_mult:float=1., pretrained:bool=True, pretrained_fnames:OptStrTuple=None, **learn_kwargs) -> 'LanguageLearner': "Create a `Learner` with a language model from `data` and `arch`." model = get_language_model(arch, len(data.vocab.itos), config=config, drop_mult=drop_mult) meta = _model_meta[arch] learn = LanguageLearner(data, model, split_func=meta['split_lm'], **learn_kwargs) if pretrained: if 'url' not in meta: warn("There are no pretrained weights for that architecture yet!") return learn model_path = untar_data(meta['url'], data=False) fnames = [list(model_path.glob(f'*.{ext}'))[0] for ext in ['pth', 'pkl']] learn.load_pretrained(*fnames) learn.freeze() if pretrained_fnames is not None: fnames = [learn.path/learn.model_dir/f'{fn}.{ext}' for fn,ext in zip(pretrained_fnames, ['pth', 'pkl'])] learn.load_pretrained(*fnames) learn.freeze() return learn
module function_definition identifier parameters typed_parameter identifier type identifier identifier typed_default_parameter identifier type identifier none typed_default_parameter identifier type identifier float typed_default_parameter identifier type identifier true typed_default_parameter identifier type identifier none dictionary_splat_pattern identifier type string string_start string_content string_end block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier keyword_argument identifier subscript identifier string string_start string_content string_end dictionary_splat identifier if_statement identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call identifier argument_list string string_start string_content string_end return_statement identifier expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end keyword_argument identifier false expression_statement assignment identifier list_comprehension subscript call identifier argument_list call attribute identifier identifier argument_list string string_start string_content interpolation identifier string_end integer for_in_clause identifier list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list list_splat identifier expression_statement call attribute identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier list_comprehension binary_operator binary_operator attribute identifier identifier attribute identifier identifier string string_start interpolation identifier string_content interpolation identifier string_end for_in_clause pattern_list identifier identifier call identifier argument_list identifier list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list list_splat identifier expression_statement call attribute identifier identifier argument_list return_statement identifier
Create a `Learner` with a language model from `data` and `arch`.
def convert_tokens_to_ids(self, tokens): ids = [] for token in tokens: ids.append(self.vocab[token]) if len(ids) > self.max_len: logger.warning( "Token indices sequence length is longer than the specified maximum " " sequence length for this BERT model ({} > {}). Running this" " sequence through BERT will result in indexing errors".format(len(ids), self.max_len) ) return ids
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier identifier if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier argument_list call identifier argument_list identifier attribute identifier identifier return_statement identifier
Converts a sequence of tokens into ids using the vocab.
def main(args, extras): from helpme.main import get_helper name = args.command if name in HELPME_HELPERS: helper = get_helper(name=name) if args.asciinema is not None: if os.path.exists(args.asciinema): helper.data['record_asciinema'] = args.asciinema helper.run(positionals=extras)
module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier none block if_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier
This is the actual driver for the helper.
def execute_notebook(self, name): warnings.filterwarnings("ignore", category=DeprecationWarning) nb,f = self.load_notebook(name) self.run_notebook(nb,f) self.assertTrue(True)
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list true
Loads and then runs a notebook file.
def state_size(self) -> Sequence[Shape]: return self._sizes(self._compiler.rddl.state_size)
module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block return_statement call attribute identifier identifier argument_list attribute attribute attribute identifier identifier identifier identifier
Returns the MDP state size.
def delete_resource_scenario(scenario_id, resource_attr_id, quiet=False, **kwargs): _check_can_edit_scenario(scenario_id, kwargs['user_id']) _delete_resourcescenario(scenario_id, resource_attr_id, suppress_error=quiet)
module function_definition identifier parameters identifier identifier default_parameter identifier false dictionary_splat_pattern identifier block expression_statement call identifier argument_list identifier subscript identifier string string_start string_content string_end expression_statement call identifier argument_list identifier identifier keyword_argument identifier identifier
Remove the data associated with a resource in a scenario.
def _get_mscoco(directory): for url in _MSCOCO_URLS: filename = os.path.basename(url) download_url = os.path.join(_MSCOCO_ROOT_URL, url) path = generator_utils.maybe_download(directory, filename, download_url) unzip_dir = os.path.join(directory, filename.strip(".zip")) if not tf.gfile.Exists(unzip_dir): zipfile.ZipFile(path, "r").extractall(directory)
module function_definition identifier parameters identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier argument_list identifier
Download and extract MSCOCO datasets to directory unless it is there.
def visit(self, node): try: method = getattr(self, 'visit_%s' % node.expr_name.lower()) except AttributeError: return try: return method(node, [self.visit(n) for n in node]) except (VisitationError, UndefinedLabel): raise except self.unwrapped_exceptions: raise except Exception: exc_class, exc, trace = sys.exc_info() raise VisitationError(exc, exc_class, node).with_traceback(trace)
module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list except_clause identifier block return_statement try_statement block return_statement call identifier argument_list identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier except_clause tuple identifier identifier block raise_statement except_clause attribute identifier identifier block raise_statement except_clause identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list raise_statement call attribute call identifier argument_list identifier identifier identifier identifier argument_list identifier
Rewrite original method to use lower-case method, and not "generic" function.
def home_abbreviation(self): abbr = re.sub(r'.*/teams/', '', str(self._home_name)) abbr = re.sub(r'/.*', '', abbr) return abbr
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier return_statement identifier
Returns a ``string`` of the home team's abbreviation, such as 'KAN'.
def to_header(self, timestamp=None): rv = [("sentry_key", self.public_key), ("sentry_version", self.version)] if timestamp is not None: rv.append(("sentry_timestamp", str(to_timestamp(timestamp)))) if self.client is not None: rv.append(("sentry_client", self.client)) if self.secret_key is not None: rv.append(("sentry_secret", self.secret_key)) return u"Sentry " + u", ".join("%s=%s" % (key, value) for key, value in rv)
module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier list tuple string string_start string_content string_end attribute identifier identifier tuple string string_start string_content string_end attribute identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list tuple string string_start string_content string_end call identifier argument_list call identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list tuple string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list tuple string string_start string_content string_end attribute identifier identifier return_statement binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier generator_expression binary_operator string string_start string_content string_end tuple identifier identifier for_in_clause pattern_list identifier identifier identifier
Returns the auth header a string.
def _get_background_color(self): color = self.cell_attributes[self.key]["bgcolor"] return tuple(c / 255.0 for c in color_pack2rgb(color))
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript subscript attribute identifier identifier attribute identifier identifier string string_start string_content string_end return_statement call identifier generator_expression binary_operator identifier float for_in_clause identifier call identifier argument_list identifier
Returns background color rgb tuple of right line
def form_invalid(self, form): messages.error(self.request, form.errors[NON_FIELD_ERRORS]) return redirect( reverse( 'forum_conversation:topic', kwargs={ 'forum_slug': self.object.topic.forum.slug, 'forum_pk': self.object.topic.forum.pk, 'slug': self.object.topic.slug, 'pk': self.object.topic.pk }, ), )
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier subscript attribute identifier identifier identifier return_statement call identifier argument_list call identifier argument_list string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end attribute attribute attribute attribute identifier identifier identifier identifier identifier pair string string_start string_content string_end attribute attribute attribute attribute identifier identifier identifier identifier identifier pair string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier pair string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier
Handles an invalid form.
def restore_placeholders(msgid, translation): placehoders = re.findall(r'(\s*)(%(?:\(\w+\))?[sd])(\s*)', msgid) return re.sub( r'(\s*)(__[\w]+?__)(\s*)', lambda matches: '{0}{1}{2}'.format(placehoders[0][0], placehoders[0][1], placehoders.pop(0)[2]), translation)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list string string_start string_content string_end lambda lambda_parameters identifier call attribute string string_start string_content string_end identifier argument_list subscript subscript identifier integer integer subscript subscript identifier integer integer subscript call attribute identifier identifier argument_list integer integer identifier
Restore placeholders in the translated message.
def load(cls, serialized_index): from lunr import __TARGET_JS_VERSION__ if isinstance(serialized_index, basestring): serialized_index = json.loads(serialized_index) if serialized_index["version"] != __TARGET_JS_VERSION__: logger.warning( "Version mismatch when loading serialized index. " "Current version of lunr {} does not match that of serialized " "index {}".format(__TARGET_JS_VERSION__, serialized_index["version"]) ) field_vectors = { ref: Vector(elements) for ref, elements in serialized_index["fieldVectors"] } tokenset_builder = TokenSetBuilder() inverted_index = {} for term, posting in serialized_index["invertedIndex"]: tokenset_builder.insert(term) inverted_index[term] = posting tokenset_builder.finish() return Index( fields=serialized_index["fields"], field_vectors=field_vectors, inverted_index=inverted_index, token_set=tokenset_builder.root, pipeline=Pipeline.load(serialized_index["pipeline"]), )
module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier dotted_name identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator subscript identifier string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier dictionary_comprehension pair identifier call identifier argument_list identifier for_in_clause pattern_list identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier identifier expression_statement call attribute identifier identifier argument_list return_statement call identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end
Load a serialized index
def find_and_fire_hook(event_name, instance, user_override=None): try: from django.contrib.auth import get_user_model User = get_user_model() except ImportError: from django.contrib.auth.models import User from rest_hooks.models import HOOK_EVENTS if not event_name in HOOK_EVENTS.keys(): raise Exception( '"{}" does not exist in `settings.HOOK_EVENTS`.'.format(event_name) ) filters = {'event': event_name} if user_override is not False: if user_override: filters['user'] = user_override elif hasattr(instance, 'user'): filters['user'] = instance.user elif isinstance(instance, User): filters['user'] = instance else: raise Exception( '{} has no `user` property. REST Hooks needs this.'.format(repr(instance)) ) HookModel = get_hook_model() hooks = HookModel.objects.filter(**filters) for hook in hooks: hook.deliver_hook(instance)
module function_definition identifier parameters identifier identifier default_parameter identifier none block try_statement block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list except_clause identifier block import_from_statement dotted_name identifier identifier identifier identifier dotted_name identifier import_from_statement dotted_name identifier identifier dotted_name identifier if_statement not_operator comparison_operator identifier call attribute identifier identifier argument_list block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier if_statement comparison_operator identifier false block if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier elif_clause call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list dictionary_splat identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier
Look up Hooks that apply
def git_hash(): if git_repo() is None: return "unknown" git_hash = subprocess.check_output( ["git", "rev-parse", "HEAD"]) git_hash = git_hash.decode("utf-8") git_hash = git_hash.strip() return git_hash
module function_definition identifier parameters block if_statement comparison_operator call identifier argument_list none block return_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier
returns the current git hash or unknown if not in git repo
def whispers(self, peer, format, *args): return lib.zyre_whispers(self._as_parameter_, peer, format, *args)
module function_definition identifier parameters identifier identifier identifier list_splat_pattern identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier list_splat identifier
Send formatted string to a single peer specified as UUID string
def _domain_event_device_removed_cb(conn, domain, dev, opaque): _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev })
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call identifier argument_list identifier identifier identifier subscript identifier string string_start string_content string_end dictionary pair string string_start string_content string_end identifier
Domain device removal events handler
def explode(self, obj): if obj in self._done: return False result = False for item in self._explode: if hasattr(item, '_moId'): if obj._moId == item._moId: result = True else: if obj.__class__.__name__ == item.__name__: result = True if result: self._done.add(obj) return result
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement false expression_statement assignment identifier false for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier true else_clause block if_statement comparison_operator attribute attribute identifier identifier identifier attribute identifier identifier block expression_statement assignment identifier true if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier
Determine if the object should be exploded.
def filter_lines(input_file, output_file, translate=lambda line: line): filepath, lines = get_lines([input_file])[0] return filepath, [(tag, translate(line=line, tag=tag)) for (tag, line) in lines]
module function_definition identifier parameters identifier identifier default_parameter identifier lambda lambda_parameters identifier identifier block expression_statement assignment pattern_list identifier identifier subscript call identifier argument_list list identifier integer return_statement expression_list identifier list_comprehension tuple identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier for_in_clause tuple_pattern identifier identifier identifier
Translate all the lines of a single file
def draw_scores(self): x1, y1 = self.WIDTH - self.BORDER - 200 - 2 * self.BORDER, self.BORDER width, height = 100, 60 self.screen.fill((255, 255, 255), (x1, 0, self.WIDTH - x1, height + y1)) self._draw_score_box(self.score_label, self.score, (x1, y1), (width, height)) x2 = x1 + width + self.BORDER self._draw_score_box(self.best_label, self.manager.score, (x2, y1), (width, height)) return (x1, y1), (x2, y1), width, height
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier expression_list binary_operator binary_operator binary_operator attribute identifier identifier attribute identifier identifier integer binary_operator integer attribute identifier identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier expression_list integer integer expression_statement call attribute attribute identifier identifier identifier argument_list tuple integer integer integer tuple identifier integer binary_operator attribute identifier identifier identifier binary_operator identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier tuple identifier identifier tuple identifier identifier expression_statement assignment identifier binary_operator binary_operator identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier tuple identifier identifier tuple identifier identifier return_statement expression_list tuple identifier identifier tuple identifier identifier identifier identifier
Draw the current and best score
def ctx(self): if six.PY2: return contextlib.nested( self.functions.context_dict.clone(), self.returners.context_dict.clone(), self.executors.context_dict.clone(), ) else: exitstack = contextlib.ExitStack() exitstack.enter_context(self.functions.context_dict.clone()) exitstack.enter_context(self.returners.context_dict.clone()) exitstack.enter_context(self.executors.context_dict.clone()) return exitstack
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement call attribute identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list return_statement identifier
Return a single context manager for the minion's data
def _qt_export_vtkjs(self, show=True): return FileDialog(self.app_window, filefilter=['VTK JS File(*.vtkjs)'], show=show, directory=os.getcwd(), callback=self.export_vtkjs)
module function_definition identifier parameters identifier default_parameter identifier true block return_statement call identifier argument_list attribute identifier identifier keyword_argument identifier list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier
Spawn an save file dialog to export a vtkjs file.
def validate_program(self): terminals = [0] for node in self.program: if isinstance(node, _Function): terminals.append(node.arity) else: terminals[-1] -= 1 while terminals[-1] == 0: terminals.pop() terminals[-1] -= 1 return terminals == [-1]
module function_definition identifier parameters identifier block expression_statement assignment identifier list integer for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier else_clause block expression_statement augmented_assignment subscript identifier unary_operator integer integer while_statement comparison_operator subscript identifier unary_operator integer integer block expression_statement call attribute identifier identifier argument_list expression_statement augmented_assignment subscript identifier unary_operator integer integer return_statement comparison_operator identifier list unary_operator integer
Rough check that the embedded program in the object is valid.
def __PrintAdditionalImports(self, imports): google_imports = [x for x in imports if 'google' in x] other_imports = [x for x in imports if 'google' not in x] if other_imports: for import_ in sorted(other_imports): self.__printer(import_) self.__printer() if google_imports: for import_ in sorted(google_imports): self.__printer(import_) self.__printer()
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator string string_start string_content string_end identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator string string_start string_content string_end identifier if_statement identifier block for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list if_statement identifier block for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list
Print additional imports needed for protorpc.
def _check_input_names(symbol, names, typename, throw): args = symbol.list_arguments() for name in names: if name in args: continue candidates = [arg for arg in args if not arg.endswith('_weight') and not arg.endswith('_bias') and not arg.endswith('_gamma') and not arg.endswith('_beta')] msg = "\033[91mYou created Module with Module(..., %s_names=%s) but " \ "input with name '%s' is not found in symbol.list_arguments(). " \ "Did you mean one of:\n\t%s\033[0m"%( typename, str(names), name, '\n\t'.join(candidates)) if throw: raise ValueError(msg) else: warnings.warn(msg)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier identifier block if_statement comparison_operator identifier identifier block continue_statement expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause boolean_operator boolean_operator boolean_operator not_operator call attribute identifier identifier argument_list string string_start string_content string_end not_operator call attribute identifier identifier argument_list string string_start string_content string_end not_operator call attribute identifier identifier argument_list string string_start string_content string_end not_operator call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator concatenated_string string string_start string_content escape_sequence string_end string string_start string_content string_end string string_start string_content escape_sequence escape_sequence escape_sequence string_end tuple identifier call identifier argument_list identifier identifier call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier if_statement identifier block raise_statement call identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier
Check that all input names are in symbol's arguments.
def reverse(self, url, args=None, kwargs=None): return reverse("%s:%s" % (self.instance_name, url,), args=args, kwargs=kwargs, current_app = self.app_name)
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block return_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier
Reverse an url taking self.app_name in account
def decode_vlqs(s): ints = [] i = 0 shift = 0 for c in s: raw = B64_INT[c] cont = VLQ_CONT & raw i = ((VLQ_BASE_MASK & raw) << shift) | i shift += VLQ_SHIFT if not cont: sign = -1 if 1 & i else 1 ints.append((i >> 1) * sign) i = 0 shift = 0 return tuple(ints)
module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier integer expression_statement assignment identifier integer for_statement identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator identifier identifier identifier identifier expression_statement augmented_assignment identifier identifier if_statement not_operator identifier block expression_statement assignment identifier conditional_expression unary_operator integer binary_operator integer identifier integer expression_statement call attribute identifier identifier argument_list binary_operator parenthesized_expression binary_operator identifier integer identifier expression_statement assignment identifier integer expression_statement assignment identifier integer return_statement call identifier argument_list identifier
Decode str `s` into a list of integers.
def ensure(user, action, subject): ability = Ability(user, get_authorization_method()) if ability.cannot(action, subject): raise AccessDenied()
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list if_statement call attribute identifier identifier argument_list identifier identifier block raise_statement call identifier argument_list
Similar to ``can`` but will raise a AccessDenied Exception if does not have access
def execute ( self, conn, dataset, dataset_access_type, transaction=False ): if not conn: dbsExceptionHandler("dbsException-failed-connect2host", "Oracle/Dataset/UpdateType. Expects db connection from upper layer.", self.logger.exception) binds = { "dataset" : dataset , "dataset_access_type" : dataset_access_type ,"myuser": dbsUtils().getCreateBy(), "mydate": dbsUtils().getTime() } result = self.dbi.processData(self.sql, binds, conn, transaction)
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier false block if_statement not_operator identifier block expression_statement call identifier argument_list string string_start string_content string_end string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute call identifier argument_list identifier argument_list pair string string_start string_content string_end call attribute call identifier argument_list identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier identifier identifier
for a given file
def OnText(self, event): if not self.ignore_changes: post_command_event(self, self.CodeEntryMsg, code=event.GetString()) self.main_window.grid.grid_renderer.cell_cache.clear() event.Skip()
module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement call identifier argument_list identifier attribute identifier identifier keyword_argument identifier call attribute identifier identifier argument_list expression_statement call attribute attribute attribute attribute attribute identifier identifier identifier identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list
Text event method evals the cell and updates the grid
def getAllFeatureSets(self): for dataset in self.getAllDatasets(): iterator = self._client.search_feature_sets( dataset_id=dataset.id) for featureSet in iterator: yield featureSet
module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier for_statement identifier identifier block expression_statement yield identifier
Returns all feature sets on the server.
def prev_window(self, widget, data=None): self.path_window.hide() self.parent.open_window(widget, self.data)
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier
Function returns to Main Window
def _release_all(self): for i in self.inputs: i.call_release(True) self.available_lock.release()
module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list true expression_statement call attribute attribute identifier identifier identifier argument_list
Releases all locks to kill all threads
def isempty(result): if isinstance(result, list): for element in result: if isinstance(element, list): if not isempty(element): return False else: if element is not None: return False else: if result is not None: return False return True
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block for_statement identifier identifier block if_statement call identifier argument_list identifier identifier block if_statement not_operator call identifier argument_list identifier block return_statement false else_clause block if_statement comparison_operator identifier none block return_statement false else_clause block if_statement comparison_operator identifier none block return_statement false return_statement true
Finds out if a scraping result should be considered empty.
def build_standard_field(self, field_name, model_field): field_mapping = ClassLookupDict(self.serializer_field_mapping) field_class = field_mapping[model_field] field_kwargs = get_field_kwargs(field_name, model_field) if 'choices' in field_kwargs: field_class = self.serializer_choice_field valid_kwargs = set(( 'read_only', 'write_only', 'required', 'default', 'initial', 'source', 'label', 'help_text', 'style', 'error_messages', 'validators', 'allow_null', 'allow_blank', 'choices' )) for key in list(field_kwargs.keys()): if key not in valid_kwargs: field_kwargs.pop(key) if not issubclass(field_class, ModelField): field_kwargs.pop('model_field', None) if not issubclass(field_class, CharField) and not issubclass(field_class, ChoiceField): field_kwargs.pop('allow_blank', None) if postgres_fields and isinstance(model_field, postgres_fields.ArrayField): child_model_field = model_field.base_field child_field_class, child_field_kwargs = self.build_standard_field( 'child', child_model_field ) field_kwargs['child'] = child_field_class(**child_field_kwargs) return field_class, field_kwargs
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement not_operator call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end none if_statement boolean_operator not_operator call identifier argument_list identifier identifier not_operator call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end none if_statement boolean_operator identifier call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list dictionary_splat identifier return_statement expression_list identifier identifier
Create regular model fields.
def declalltypes(self): for f in self.body: if (hasattr(f, '_ctype') and f._ctype._storage == Storages.TYPEDEF): yield f
module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block if_statement parenthesized_expression boolean_operator call identifier argument_list identifier string string_start string_content string_end comparison_operator attribute attribute identifier identifier identifier attribute identifier identifier block expression_statement yield identifier
generator on all declaration of type
def request_token(self): client = OAuth1( client_key=self._server_cache[self.client.server].key, client_secret=self._server_cache[self.client.server].secret, callback_uri=self.callback, ) request = {"auth": client} response = self._requester( requests.post, "oauth/request_token", **request ) data = parse.parse_qs(response.text) data = { 'token': data[self.PARAM_TOKEN][0], 'token_secret': data[self.PARAM_TOKEN_SECRET][0] } return data
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute subscript attribute identifier identifier attribute attribute identifier identifier identifier identifier keyword_argument identifier attribute subscript attribute identifier identifier attribute attribute identifier identifier identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end dictionary_splat identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end subscript subscript identifier attribute identifier identifier integer pair string string_start string_content string_end subscript subscript identifier attribute identifier identifier integer return_statement identifier
Gets OAuth request token
def build_loss(model_logits, sparse_targets): time_major_shape = [FLAGS.unroll_steps, FLAGS.batch_size] flat_batch_shape = [FLAGS.unroll_steps * FLAGS.batch_size, -1] xent = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=tf.reshape(model_logits, flat_batch_shape), labels=tf.reshape(sparse_targets, flat_batch_shape[:-1])) xent = tf.reshape(xent, time_major_shape) sequence_neg_log_prob = tf.reduce_sum(xent, axis=0) return tf.reduce_mean(sequence_neg_log_prob, axis=0)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier list binary_operator attribute identifier identifier attribute identifier identifier unary_operator integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier call attribute identifier identifier argument_list identifier subscript identifier slice unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier integer return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier integer
Compute the log loss given predictions and targets.
def render(self): release_notes = [] for parser in self.parsers: parser_content = parser.render() if parser_content is not None: release_notes.append(parser_content) return u"\r\n\r\n".join(release_notes)
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence string_end identifier argument_list identifier
Returns the rendered release notes from all parsers as a string
def pop_float(self, key: str, default: Any = DEFAULT) -> float: value = self.pop(key, default) if value is None: return None else: return float(value)
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier none block return_statement none else_clause block return_statement call identifier argument_list identifier
Performs a pop and coerces to a float.
def _load_lsm_data(self, data_var, conversion_factor=1, calc_4d_method=None, calc_4d_dim=None, time_step=None): data = self.xd.lsm.getvar(data_var, yslice=self.yslice, xslice=self.xslice, calc_4d_method=calc_4d_method, calc_4d_dim=calc_4d_dim) if isinstance(time_step, datetime): data = data.loc[{self.lsm_time_dim: [pd.to_datetime(time_step)]}] elif time_step is not None: data = data[{self.lsm_time_dim: [time_step]}] data = data.fillna(0) data.values *= conversion_factor return data
module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier dictionary pair attribute identifier identifier list call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier none block expression_statement assignment identifier subscript identifier dictionary pair attribute identifier identifier list identifier expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement augmented_assignment attribute identifier identifier identifier return_statement identifier
This extracts the LSM data from a folder of netcdf files
def _visitor_impl(self, arg): if (_qualname(type(self)), type(arg)) in _methods: method = _methods[(_qualname(type(self)), type(arg))] return method(self, arg) else: arg_parent_type = arg.__class__.__bases__[0] while arg_parent_type != object: if (_qualname(type(self)), arg_parent_type) in _methods: method = _methods[(_qualname(type(self)), arg_parent_type)] return method(self, arg) else: arg_parent_type = arg_parent_type.__bases__[0] raise VisitorException('No visitor found for class ' + str(type(arg)))
module function_definition identifier parameters identifier identifier block if_statement comparison_operator tuple call identifier argument_list call identifier argument_list identifier call identifier argument_list identifier identifier block expression_statement assignment identifier subscript identifier tuple call identifier argument_list call identifier argument_list identifier call identifier argument_list identifier return_statement call identifier argument_list identifier identifier else_clause block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier integer while_statement comparison_operator identifier identifier block if_statement comparison_operator tuple call identifier argument_list call identifier argument_list identifier identifier identifier block expression_statement assignment identifier subscript identifier tuple call identifier argument_list call identifier argument_list identifier identifier return_statement call identifier argument_list identifier identifier else_clause block expression_statement assignment identifier subscript attribute identifier identifier integer raise_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list call identifier argument_list identifier
Actual visitor method implementation.
def bbox_to_poly(north, south, east, west): return Polygon([(west, south), (east, south), (east, north), (west, north)])
module function_definition identifier parameters identifier identifier identifier identifier block return_statement call identifier argument_list list tuple identifier identifier tuple identifier identifier tuple identifier identifier tuple identifier identifier
Convenience function to parse bbox -> poly
def _pool_event_refresh_cb(conn, pool, opaque): _salt_send_event(opaque, conn, { 'pool': { 'name': pool.name(), 'uuid': pool.UUIDString() }, 'event': opaque['event'] })
module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list identifier identifier dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end subscript identifier string string_start string_content string_end
Storage pool refresh events handler
def _gen_packet_setpower(self, sequence, power, fade): level = pack("<H", Power.BULB_OFF if power == 0 else Power.BULB_ON) duration = pack("<I", fade) payload = bytearray(level) payload.extend(duration) return self._gen_packet(sequence, PayloadType.SETPOWER2, payload)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end conditional_expression attribute identifier identifier comparison_operator identifier integer attribute identifier identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier attribute identifier identifier identifier
Generate "setpower" packet payload.
def _deduplicate_items(cls, items): "Deduplicates assigned paths by incrementing numbering" counter = Counter([path[:i] for path, _ in items for i in range(1, len(path)+1)]) if sum(counter.values()) == len(counter): return items new_items = [] counts = defaultdict(lambda: 0) for i, (path, item) in enumerate(items): if counter[path] > 1: path = path + (util.int_to_roman(counts[path]+1),) elif counts[path]: path = path[:-1] + (util.int_to_roman(counts[path]+1),) new_items.append((path, item)) counts[path] += 1 return new_items
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list list_comprehension subscript identifier slice identifier for_in_clause pattern_list identifier identifier identifier for_in_clause identifier call identifier argument_list integer binary_operator call identifier argument_list identifier integer if_statement comparison_operator call identifier argument_list call attribute identifier identifier argument_list call identifier argument_list identifier block return_statement identifier expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list lambda integer for_statement pattern_list identifier tuple_pattern identifier identifier call identifier argument_list identifier block if_statement comparison_operator subscript identifier identifier integer block expression_statement assignment identifier binary_operator identifier tuple call attribute identifier identifier argument_list binary_operator subscript identifier identifier integer elif_clause subscript identifier identifier block expression_statement assignment identifier binary_operator subscript identifier slice unary_operator integer tuple call attribute identifier identifier argument_list binary_operator subscript identifier identifier integer expression_statement call attribute identifier identifier argument_list tuple identifier identifier expression_statement augmented_assignment subscript identifier identifier integer return_statement identifier
Deduplicates assigned paths by incrementing numbering
def validate_backup_window(window): hour = r'[01]?[0-9]|2[0-3]' minute = r'[0-5][0-9]' r = ("(?P<start_hour>%s):(?P<start_minute>%s)-" "(?P<end_hour>%s):(?P<end_minute>%s)") % (hour, minute, hour, minute) range_regex = re.compile(r) m = range_regex.match(window) if not m: raise ValueError("DBInstance PreferredBackupWindow must be in the " "format: hh24:mi-hh24:mi") start_ts = (int(m.group('start_hour')) * 60) + int(m.group('start_minute')) end_ts = (int(m.group('end_hour')) * 60) + int(m.group('end_minute')) if abs(end_ts - start_ts) < 30: raise ValueError("DBInstance PreferredBackupWindow must be at least " "30 minutes long.") return window
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier binary_operator parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end tuple identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier binary_operator parenthesized_expression binary_operator call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end integer call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator parenthesized_expression binary_operator call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end integer call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list binary_operator identifier identifier integer block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end return_statement identifier
Validate PreferredBackupWindow for DBInstance
def _reset_build(self, sources): from ambry.orm.exc import NotFoundError for p in self.dataset.partitions: if p.type == p.TYPE.SEGMENT: self.log("Removing old segment partition: {}".format(p.identity.name)) try: self.wrap_partition(p).local_datafile.remove() self.session.delete(p) except NotFoundError: pass for s in sources: if s.reftype == 'partition': continue p = s.partition if p: try: self.wrap_partition(p).local_datafile.remove() self.session.delete(p) except NotFoundError: pass if s.state in (self.STATES.BUILDING, self.STATES.BUILT): s.state = self.STATES.INGESTED self.commit()
module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier for_statement identifier attribute attribute identifier identifier identifier block if_statement comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier try_statement block expression_statement call attribute attribute call attribute identifier identifier argument_list identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier except_clause identifier block pass_statement for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block continue_statement expression_statement assignment identifier attribute identifier identifier if_statement identifier block try_statement block expression_statement call attribute attribute call attribute identifier identifier argument_list identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier except_clause identifier block pass_statement if_statement comparison_operator attribute identifier identifier tuple attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list
Remove partition datafiles and reset the datafiles to the INGESTED state
def interfaces(self): self._ifaces = [] wifi_ctrl = wifiutil.WifiUtil() for interface in wifi_ctrl.interfaces(): iface = Interface(interface) self._ifaces.append(iface) self._logger.info("Get interface: %s", iface.name()) if not self._ifaces: self._logger.error("Can't get wifi interface") return self._ifaces
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier list expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list if_statement not_operator attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement attribute identifier identifier
Collect the available wlan interfaces.
def save_migration(connection, basename): sql = "INSERT INTO migrations_applied (name, date) VALUES (%s, NOW())" with connection.cursor() as cursor: cursor.execute(sql, (basename,)) connection.commit() return True
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content string_end with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier tuple identifier expression_statement call attribute identifier identifier argument_list return_statement true
Save a migration in `migrations_applied` table
def handle_device_json(self, data): self._device_json.insert(0, data) self._device_json.pop()
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list integer identifier expression_statement call attribute attribute identifier identifier identifier argument_list
Manage the device json list.
def describe_token_expr(expr): if ':' in expr: type, value = expr.split(':', 1) if type == 'name': return value else: type = expr return _describe_token_type(type)
module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer if_statement comparison_operator identifier string string_start string_content string_end block return_statement identifier else_clause block expression_statement assignment identifier identifier return_statement call identifier argument_list identifier
Like `describe_token` but for token expressions.
def hook_drag(self): widget = self.widget widget.mousePressEvent = self.mousePressEvent widget.mouseMoveEvent = self.mouseMoveEvent widget.mouseReleaseEvent = self.mouseReleaseEvent
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier
Install the hooks for drag operations.
def generate_shard_args(outfiles, num_examples): num_shards = len(outfiles) num_examples_per_shard = num_examples // num_shards start_idxs = [i * num_examples_per_shard for i in range(num_shards)] end_idxs = list(start_idxs) end_idxs.pop(0) end_idxs.append(num_examples) return zip(start_idxs, end_idxs, outfiles)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier list_comprehension binary_operator identifier identifier for_in_clause identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier identifier identifier
Generate start and end indices per outfile.
def delete(self): if not self._created: return try: node1 = self._nodes[0]["node"] adapter_number1 = self._nodes[0]["adapter_number"] port_number1 = self._nodes[0]["port_number"] except IndexError: return try: yield from node1.delete("/adapters/{adapter_number}/ports/{port_number}/nio".format(adapter_number=adapter_number1, port_number=port_number1), timeout=120) except aiohttp.web.HTTPNotFound: pass try: node2 = self._nodes[1]["node"] adapter_number2 = self._nodes[1]["adapter_number"] port_number2 = self._nodes[1]["port_number"] except IndexError: return try: yield from node2.delete("/adapters/{adapter_number}/ports/{port_number}/nio".format(adapter_number=adapter_number2, port_number=port_number2), timeout=120) except aiohttp.web.HTTPNotFound: pass yield from super().delete()
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement try_statement block expression_statement assignment identifier subscript subscript attribute identifier identifier integer string string_start string_content string_end expression_statement assignment identifier subscript subscript attribute identifier identifier integer string string_start string_content string_end expression_statement assignment identifier subscript subscript attribute identifier identifier integer string string_start string_content string_end except_clause identifier block return_statement try_statement block expression_statement yield call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier integer except_clause attribute attribute identifier identifier identifier block pass_statement try_statement block expression_statement assignment identifier subscript subscript attribute identifier identifier integer string string_start string_content string_end expression_statement assignment identifier subscript subscript attribute identifier identifier integer string string_start string_content string_end expression_statement assignment identifier subscript subscript attribute identifier identifier integer string string_start string_content string_end except_clause identifier block return_statement try_statement block expression_statement yield call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier integer except_clause attribute attribute identifier identifier identifier block pass_statement expression_statement yield call attribute call identifier argument_list identifier argument_list
Delete the link and free the resources
def build_expression_values(dynamizer, expr_values, kwargs): if expr_values: values = expr_values return dynamizer.encode_keys(values) elif kwargs: values = dict(((':' + k, v) for k, v in six.iteritems(kwargs))) return dynamizer.encode_keys(values)
module function_definition identifier parameters identifier identifier identifier block if_statement identifier block expression_statement assignment identifier identifier return_statement call attribute identifier identifier argument_list identifier elif_clause identifier block expression_statement assignment identifier call identifier argument_list generator_expression tuple binary_operator string string_start string_content string_end identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier
Build ExpresionAttributeValues from a value or kwargs
def iter_ruptures(self): assert self.orig, '%s is not fully initialized' % self for ridx in range(self.start, self.stop): if self.orig.rate[ridx]: rup = self.get_ucerf_rupture(ridx, self.src_filter) if rup: yield rup
module function_definition identifier parameters identifier block assert_statement attribute identifier identifier binary_operator string string_start string_content string_end identifier for_statement identifier call identifier argument_list attribute identifier identifier attribute identifier identifier block if_statement subscript attribute attribute identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier if_statement identifier block expression_statement yield identifier
Yield ruptures for the current set of indices
def store_pulse_jobs(pulse_job, exchange, routing_key): newrelic.agent.add_custom_parameter("exchange", exchange) newrelic.agent.add_custom_parameter("routing_key", routing_key) JobLoader().process_job(pulse_job)
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute call identifier argument_list identifier argument_list identifier
Fetches the jobs pending from pulse exchanges and loads them.
def safe_values(self, value): string_val = "" if isinstance(value, datetime.date): try: string_val = value.strftime('{0}{1}{2}'.format( current_app.config['DATETIME']['DATE_FORMAT'], current_app.config['DATETIME']['SEPARATOR'], current_app.config['DATETIME']['TIME_FORMAT'])) except RuntimeError as error: string_val = value.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(value, bytes): string_val = value.decode('utf-8') elif isinstance(value, decimal.Decimal): string_val = float(value) else: string_val = value return string_val
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_end if_statement call identifier argument_list identifier attribute identifier identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end elif_clause call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier identifier return_statement identifier
Parse non-string values that will not serialize
def html_entity_decode_codepoint(self, m, defs=htmlentities.codepoint2name): try: char = defs[m.group(1)] return "&{char};".format(char=char) except ValueError: return m.group(0) except KeyError: return m.group(0)
module function_definition identifier parameters identifier identifier default_parameter identifier attribute identifier identifier block try_statement block expression_statement assignment identifier subscript identifier call attribute identifier identifier argument_list integer return_statement call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier except_clause identifier block return_statement call attribute identifier identifier argument_list integer except_clause identifier block return_statement call attribute identifier identifier argument_list integer
decode html entity into one of the codepoint2name
def parse_int_literal(ast, _variables=None): if isinstance(ast, IntValueNode): num = int(ast.value) if MIN_INT <= num <= MAX_INT: return num return INVALID
module function_definition identifier parameters identifier default_parameter identifier none block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement comparison_operator identifier identifier identifier block return_statement identifier return_statement identifier
Parse an integer value node in the AST.
def _handle_parens(self, children, start, formats): opens, closes = self._count_needed_parens(formats) old_end = self.source.offset new_end = None for i in range(closes): new_end = self.source.consume(')')[1] if new_end is not None: if self.children: children.append(self.source[old_end:new_end]) new_start = start for i in range(opens): new_start = self.source.rfind_token('(', 0, new_start) if new_start != start: if self.children: children.appendleft(self.source[new_start:start]) start = new_start return start
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier none for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer if_statement comparison_operator identifier none block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier slice identifier identifier expression_statement assignment identifier identifier for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer identifier if_statement comparison_operator identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier slice identifier identifier expression_statement assignment identifier identifier return_statement identifier
Changes `children` and returns new start
def clear_waiting_coordinators(self, cancel=False): with self._lockw: if cancel: for _coordinator in self._waiting_transfer_coordinators: _coordinator.notify_cancelled("Clear Waiting Queue", False) self._waiting_transfer_coordinators.clear()
module function_definition identifier parameters identifier default_parameter identifier false block with_statement with_clause with_item attribute identifier identifier block if_statement identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end false expression_statement call attribute attribute identifier identifier identifier argument_list
remove all entries from waiting queue or cancell all in waiting queue
def show(data, negate=False): from PIL import Image as pil data = np.array((data - data.min()) * 255.0 / (data.max() - data.min()), np.uint8) if negate: data = 255 - data img = pil.fromarray(data) img.show()
module function_definition identifier parameters identifier default_parameter identifier false block import_from_statement dotted_name identifier aliased_import dotted_name identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator binary_operator parenthesized_expression binary_operator identifier call attribute identifier identifier argument_list float parenthesized_expression binary_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier if_statement identifier block expression_statement assignment identifier binary_operator integer identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list
Show the stretched data.
def text(self): try: return self._text except AttributeError: if IS_PYTHON_3: encoding = self._response.headers.get_content_charset("utf-8") else: encoding = self._response.headers.getparam("charset") self._text = self._response.read().decode(encoding or "utf-8") return self._text
module function_definition identifier parameters identifier block try_statement block return_statement attribute identifier identifier except_clause identifier block if_statement identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list boolean_operator identifier string string_start string_content string_end return_statement attribute identifier identifier
Get the raw text for the response
def run(self): try: self._connect() self._register() while True: try: body = self.command_queue.get(block=True, timeout=1 * SECOND) except queue.Empty: body = None if body is not None: result = self._send(body) if result: self.command_queue.task_done() else: self._disconnect() self._connect() self._register() if self._stop_event.is_set(): logger.debug("CoreAgentSocket thread stopping.") break except Exception: logger.debug("CoreAgentSocket thread exception.") finally: self._started_event.clear() self._stop_event.clear() self._stopped_event.set() logger.debug("CoreAgentSocket thread stopped.")
module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list while_statement true block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier true keyword_argument identifier binary_operator integer identifier except_clause attribute identifier identifier block expression_statement assignment identifier none if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list if_statement call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end break_statement except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end finally_clause block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end
Called by the threading system
def delete(context, sequence): uri = '%s/%s/%s' % (context.dci_cs_api, RESOURCE, sequence) return context.session.delete(uri)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier
Delete jobs events from a given sequence
def _build_toctree_node(parent=None, entries=None, includefiles=None, caption=None): subnode = sphinx.addnodes.toctree() subnode['parent'] = parent subnode['entries'] = entries subnode['includefiles'] = includefiles subnode['caption'] = caption subnode['maxdepth'] = 1 subnode['hidden'] = False subnode['glob'] = None subnode['hidden'] = False subnode['includehidden'] = False subnode['numbered'] = 0 subnode['titlesonly'] = False return subnode
module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end integer expression_statement assignment subscript identifier string string_start string_content string_end false expression_statement assignment subscript identifier string string_start string_content string_end none expression_statement assignment subscript identifier string string_start string_content string_end false expression_statement assignment subscript identifier string string_start string_content string_end false expression_statement assignment subscript identifier string string_start string_content string_end integer expression_statement assignment subscript identifier string string_start string_content string_end false return_statement identifier
Factory for a toctree node.
def com_google_fonts_check_fontv(ttFont): from fontv.libfv import FontVersion fv = FontVersion(ttFont) if fv.version and (fv.is_development or fv.is_release): yield PASS, "Font version string looks GREAT!" else: yield INFO, ("Version string is: \"{}\"\n" "The version string must ideally include a git commit hash" " and either a 'dev' or a 'release' suffix such as in the" " example below:\n" "\"Version 1.3; git-0d08353-release\"" "").format(fv.get_name_id5_version_string())
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator attribute identifier identifier parenthesized_expression boolean_operator attribute identifier identifier attribute identifier identifier block expression_statement yield expression_list identifier string string_start string_content string_end else_clause block expression_statement yield expression_list identifier call attribute parenthesized_expression concatenated_string string string_start string_content escape_sequence escape_sequence escape_sequence string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content escape_sequence string_end string string_start string_content escape_sequence escape_sequence string_end string string_start string_end identifier argument_list call attribute identifier identifier argument_list
Check for font-v versioning
def create_initial_review_history(brain_or_object): obj = api.get_object(brain_or_object) review_history = list() wf_tool = api.get_tool("portal_workflow") for wf_id in api.get_workflows_for(obj): wf = wf_tool.getWorkflowById(wf_id) if not hasattr(wf, "initial_state"): logger.warn("No initial_state attr for workflow '{}': {}'" .format(wf_id, repr(obj))) initial_state = getattr(wf, "initial_state", "registered") initial_review_history = { 'action': None, 'actor': obj.Creator(), 'comments': 'Default review_history (by 1.3 upgrade step)', 'review_state': initial_state, 'time': obj.created(), } if hasattr(wf, "state_variable"): initial_review_history[wf.state_variable] = initial_state else: logger.warn("No state_variable attr for workflow '{}': {}" .format(wf_id, repr(obj))) review_history.append(initial_review_history) return sorted(review_history, key=lambda st: st.get("time"))
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end none pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute identifier identifier argument_list if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment subscript identifier attribute identifier identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier keyword_argument identifier lambda lambda_parameters identifier call attribute identifier identifier argument_list string string_start string_content string_end
Creates a new review history for the given object
def initialize_from_ckpt(ckpt_dir, hparams): model_dir = hparams.get("model_dir", None) already_has_ckpt = ( model_dir and tf.train.latest_checkpoint(model_dir) is not None) if already_has_ckpt: return tf.logging.info("Checkpoint dir: %s", ckpt_dir) reader = tf.contrib.framework.load_checkpoint(ckpt_dir) variable_map = {} for var in tf.contrib.framework.get_trainable_variables(): var_name = var.name.split(":")[0] if reader.has_tensor(var_name): tf.logging.info("Loading variable from checkpoint: %s", var_name) variable_map[var_name] = var else: tf.logging.info("Cannot find variable in checkpoint, skipping: %s", var_name) tf.train.init_from_checkpoint(ckpt_dir, variable_map)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment identifier parenthesized_expression boolean_operator identifier comparison_operator call attribute attribute identifier identifier identifier argument_list identifier none if_statement identifier block return_statement expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier expression_statement assignment identifier dictionary for_statement identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment subscript identifier identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier
Initialize variables from given directory.
def OnRangeSelected(self, event): if not self.grid.IsEditable(): selection = self.grid.selection row, col, __ = self.grid.sel_mode_cursor if (row, col) in selection: self.grid.ClearSelection() else: self.grid.SetGridCursor(row, col) post_command_event(self.grid, self.grid.SelectionMsg, selection=selection)
module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment pattern_list identifier identifier identifier attribute attribute identifier identifier identifier if_statement comparison_operator tuple identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier keyword_argument identifier identifier
Event handler for grid selection
def cmd_reverse_lookup(command_name): for key, value in miss_cmds.items(): if (value.upper() == command_name.upper()): return key return 0
module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement parenthesized_expression comparison_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list block return_statement identifier return_statement integer
returns 0 if key not found
def clean(self): if not self.priorDays and not self.startDate: raise ValidationError(_( 'Either a start date or an "up to __ days in the past" limit is required ' + 'for repeated expense rules that are not associated with a venue or a staff member.' )) super(GenericRepeatedExpense,self).clean()
module function_definition identifier parameters identifier block if_statement boolean_operator not_operator attribute identifier identifier not_operator attribute identifier identifier block raise_statement call identifier argument_list call identifier argument_list binary_operator string string_start string_content string_end string string_start string_content string_end expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list
priorDays is required for Generic Repeated Expenses to avoid infinite loops
def validate_value(self, value): if value not in (None, self._unset): super(ReferenceField, self).validate_value(value) if value.app != self.target_app: raise ValidationError( self.record, "Reference field '{}' has target app '{}', cannot reference record '{}' from app '{}'".format( self.name, self.target_app, value, value.app ) )
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier tuple none attribute identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier identifier attribute identifier identifier
Validate provided record is a part of the appropriate target app for the field
def _buildItem(self, elem, cls=None, initpath=None): initpath = initpath or self._initpath if cls is not None: return cls(self._server, elem, initpath) etype = elem.attrib.get('type', elem.attrib.get('streamType')) ehash = '%s.%s' % (elem.tag, etype) if etype else elem.tag ecls = utils.PLEXOBJECTS.get(ehash, utils.PLEXOBJECTS.get(elem.tag)) if ecls is not None: return ecls(self._server, elem, initpath) raise UnknownType("Unknown library type <%s type='%s'../>" % (elem.tag, etype))
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier attribute identifier identifier if_statement comparison_operator identifier none block return_statement call identifier argument_list attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier conditional_expression binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier none block return_statement call identifier argument_list attribute identifier identifier identifier identifier raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier
Factory function to build objects based on registered PLEXOBJECTS.
def hla_choices(orig_hla, min_parts=2): yield orig_hla try: int(orig_hla[-1]) except ValueError: yield orig_hla[:-1] hla_parts = orig_hla.split(":") for sub_i in range(len(hla_parts) - min_parts + 1): yield ":".join(hla_parts[:len(hla_parts) - sub_i])
module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement yield identifier try_statement block expression_statement call identifier argument_list subscript identifier unary_operator integer except_clause identifier block expression_statement yield subscript identifier slice unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call identifier argument_list binary_operator binary_operator call identifier argument_list identifier identifier integer block expression_statement yield call attribute string string_start string_content string_end identifier argument_list subscript identifier slice binary_operator call identifier argument_list identifier identifier
Provide a range of options for HLA type, with decreasing resolution.
def ensure_netmiko_conn(func): def wrap_function(self, filename=None, config=None): try: netmiko_object = self._netmiko_device if netmiko_object is None: raise AttributeError() except AttributeError: device_type = c.NETMIKO_MAP[self.platform] netmiko_optional_args = self.netmiko_optional_args if "port" in netmiko_optional_args: netmiko_optional_args["port"] = 22 self._netmiko_open( device_type=device_type, netmiko_optional_args=netmiko_optional_args ) func(self, filename=filename, config=config) return wrap_function
module function_definition identifier parameters identifier block function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block try_statement block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list except_clause identifier block expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier
Decorator that ensures Netmiko connection exists.
def remove(self, idx): data = {} for k in self.data: data[k] = np.delete(self.data[k], idx) return self._return(data=data)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement identifier attribute identifier identifier block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list subscript attribute identifier identifier identifier identifier return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier
Return a new DictArray that does not contain the indexed values
def cast_to_swimlane(self, value): if value is None: return value if self.input_type == self._type_interval: return value.in_seconds() * 1000 return self.format_datetime(value)
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block return_statement identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement binary_operator call attribute identifier identifier argument_list integer return_statement call attribute identifier identifier argument_list identifier
Return datetimes formatted as expected by API and timespans as millisecond epochs
def write(self, *string): self._output.write(' '.join([six.text_type(s) for s in string])) return self
module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier return_statement identifier
Writes to the output