text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def wait_until_alert_is_present(self, timeout=None): """ Waits for an alert to be present @type timeout: int @param timeout: the maximum number of seconds the driver will wait before timing out @rtype: webdriverwrapper.WebElementWrapper ...
[ "def", "wait_until_alert_is_present", "(", "self", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "locator", "=", "None", "def", "wait", "(", ")", ":", "'''\n ...
36.857143
23.809524
def settings(**kwargs): """ Generally, this will automatically be added to a newly initialized :class:`phoebe.frontend.bundle.Bundle` :parameter **kwargs: defaults for the values of any of the parameters :return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly created :cla...
[ "def", "settings", "(", "*", "*", "kwargs", ")", ":", "params", "=", "[", "]", "params", "+=", "[", "StringParameter", "(", "qualifier", "=", "'phoebe_version'", ",", "value", "=", "kwargs", ".", "get", "(", "'phoebe_version'", ",", "__version__", ")", "...
78.115385
66.115385
def _which_ip_protocol(element): """ Validate the protocol addresses for the element. Most elements can have an IPv4 or IPv6 address assigned on the same element. This allows elements to be validated and placed on the right network. :return: boolean tuple :rtype: tuple(ipv4, ipv6) """ ...
[ "def", "_which_ip_protocol", "(", "element", ")", ":", "try", ":", "if", "element", ".", "typeof", "in", "(", "'host'", ",", "'router'", ")", ":", "return", "getattr", "(", "element", ",", "'address'", ",", "False", ")", ",", "getattr", "(", "element", ...
45.48
21.32
def generate(self): """generate tar file ..Usage:: >>> tarfile = b"".join(data for data in tg.generate()) """ if self._tar_buffer.tell(): self._tar_buffer.seek(0, 0) yield self._tar_buffer.read() for fname in self._files_to_add: ...
[ "def", "generate", "(", "self", ")", ":", "if", "self", ".", "_tar_buffer", ".", "tell", "(", ")", ":", "self", ".", "_tar_buffer", ".", "seek", "(", "0", ",", "0", ")", "yield", "self", ".", "_tar_buffer", ".", "read", "(", ")", "for", "fname", ...
30.214286
14.107143
def _parse_args(args): """ Interpret command line arguments. :param args: `sys.argv` :return: The populated argparse namespace. """ parser = argparse.ArgumentParser(prog='nibble', description='Speed, distance and time ' ...
[ "def", "_parse_args", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "'nibble'", ",", "description", "=", "'Speed, distance and time '", "'calculations around '", "'quantities of digital '", "'information.'", ")", "parser", ...
40.76
13.96
def allocate_tcp_port(): """Return an (integer) available TCP port on localhost. This briefly listens on the port in question, then closes it right away.""" # We want to bind() the socket but not listen(). Twisted (in # tcp.Port.createInternetSocket) would do several other things: # non-blocking, cl...
[ "def", "allocate_tcp_port", "(", ")", ":", "# We want to bind() the socket but not listen(). Twisted (in", "# tcp.Port.createInternetSocket) would do several other things:", "# non-blocking, close-on-exec, and SO_REUSEADDR. We don't need", "# non-blocking because we never listen on it, and we don't ...
51.2
19.466667
def list_all_table_rate_rules(cls, **kwargs): """List TableRateRules Return a list of TableRateRules This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_table_rate_rules(async=True) ...
[ "def", "list_all_table_rate_rules", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_list_all_table_rate_rules_with_http_info...
38.347826
15.26087
def xtob(data, sep=''): """Interpret the hex encoding of a blob (string).""" # remove the non-hex characters data = re.sub("[^0-9a-fA-F]", '', data) # interpret the hex return binascii.unhexlify(data)
[ "def", "xtob", "(", "data", ",", "sep", "=", "''", ")", ":", "# remove the non-hex characters", "data", "=", "re", ".", "sub", "(", "\"[^0-9a-fA-F]\"", ",", "''", ",", "data", ")", "# interpret the hex", "return", "binascii", ".", "unhexlify", "(", "data", ...
30.714286
12.428571
def decodeGsm7(encodedText): """ GSM-7 text decoding algorithm Decodes the specified GSM-7-encoded string into a plaintext string. :param encodedText: the text string to encode :type encodedText: bytearray or str :return: A string containing the decoded text :rtype: str """ ...
[ "def", "decodeGsm7", "(", "encodedText", ")", ":", "result", "=", "[", "]", "if", "type", "(", "encodedText", ")", "==", "str", ":", "encodedText", "=", "rawStrToByteArray", "(", "encodedText", ")", "#bytearray(encodedText)", "iterEncoded", "=", "iter", "(", ...
32.6
15.48
def check_lon_extents(self, ds): ''' Check that the values of geospatial_lon_min/geospatial_lon_max approximately match the data. :param netCDF4.Dataset ds: An open netCDF dataset ''' if not (hasattr(ds, 'geospatial_lon_min') and hasattr(ds, 'geospatial_lon_max')): ...
[ "def", "check_lon_extents", "(", "self", ",", "ds", ")", ":", "if", "not", "(", "hasattr", "(", "ds", ",", "'geospatial_lon_min'", ")", "and", "hasattr", "(", "ds", ",", "'geospatial_lon_max'", ")", ")", ":", "return", "Result", "(", "BaseCheck", ".", "M...
40.421053
26.368421
def make_diff(current, revision): """Create the difference between the current revision and a previous version""" the_diff = [] dmp = diff_match_patch() for field in (set(current.field_dict.keys()) | set(revision.field_dict.keys())): # These exclusions really should be configurable if f...
[ "def", "make_diff", "(", "current", ",", "revision", ")", ":", "the_diff", "=", "[", "]", "dmp", "=", "diff_match_patch", "(", ")", "for", "field", "in", "(", "set", "(", "current", ".", "field_dict", ".", "keys", "(", ")", ")", "|", "set", "(", "r...
40.702128
17.106383
def contextMenuEvent(self, event): """ Handles the default menu options for the orb widget. :param event | <QContextMenuEvent> """ if self.contextMenuPolicy() == Qt.DefaultContextMenu: self.showMenu(event.pos()) else: super(X...
[ "def", "contextMenuEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "contextMenuPolicy", "(", ")", "==", "Qt", ".", "DefaultContextMenu", ":", "self", ".", "showMenu", "(", "event", ".", "pos", "(", ")", ")", "else", ":", "super", "(", ...
35.5
13.7
def _build_resolver(cls, session: AppSession): '''Build resolver.''' args = session.args dns_timeout = args.dns_timeout if args.timeout: dns_timeout = args.timeout if args.inet_family == 'IPv4': family = IPFamilyPreference.ipv4_only elif args.ine...
[ "def", "_build_resolver", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "args", "=", "session", ".", "args", "dns_timeout", "=", "args", ".", "dns_timeout", "if", "args", ".", "timeout", ":", "dns_timeout", "=", "args", ".", "timeout", "if", "...
33.692308
14.692308
def _zip(self) -> ObjectValue: """Zip the receiver into an object and return it.""" res = ObjectValue(self.siblings.copy(), self.timestamp) res[self.name] = self.value return res
[ "def", "_zip", "(", "self", ")", "->", "ObjectValue", ":", "res", "=", "ObjectValue", "(", "self", ".", "siblings", ".", "copy", "(", ")", ",", "self", ".", "timestamp", ")", "res", "[", "self", ".", "name", "]", "=", "self", ".", "value", "return"...
41.2
12
def save(self) -> None: """ Save the training trace to :py:attr:`CXF_TRACE_FILE` file under the specified directory. :raise ValueError: if no output directory was specified """ if self._output_dir is None: raise ValueError('Can not save TrainingTrace without output d...
[ "def", "save", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_output_dir", "is", "None", ":", "raise", "ValueError", "(", "'Can not save TrainingTrace without output dir.'", ")", "yaml_to_file", "(", "self", ".", "_trace", ",", "self", ".", "_output...
42.777778
22.777778
def update_cluster_admin_password(self, username, new_password): """Update cluster admin password.""" url = "cluster_admins/{0}".format(username) data = { 'password': new_password } self.request( url=url, method='POST', data=data,...
[ "def", "update_cluster_admin_password", "(", "self", ",", "username", ",", "new_password", ")", ":", "url", "=", "\"cluster_admins/{0}\"", ".", "format", "(", "username", ")", "data", "=", "{", "'password'", ":", "new_password", "}", "self", ".", "request", "(...
23.4375
21.1875
def get_optimization_coordinates(self): """Return the coordinates of the geometries at each point in the optimization""" coor_array = self.fields.get("Opt point 1 Geometries") if coor_array is None: return [] else: return np.reshape(coor_array, (-1, len(self...
[ "def", "get_optimization_coordinates", "(", "self", ")", ":", "coor_array", "=", "self", ".", "fields", ".", "get", "(", "\"Opt point 1 Geometries\"", ")", "if", "coor_array", "is", "None", ":", "return", "[", "]", "else", ":", "return", "np", ".", "re...
48.142857
17.571429
def fetchmany(self, size=None): """Fetch many""" self._check_executed() if size is None: size = self.arraysize rows = [] for i in range_type(size): row = self.read_next() if row is None: break rows.append(row) ...
[ "def", "fetchmany", "(", "self", ",", "size", "=", "None", ")", ":", "self", ".", "_check_executed", "(", ")", "if", "size", "is", "None", ":", "size", "=", "self", ".", "arraysize", "rows", "=", "[", "]", "for", "i", "in", "range_type", "(", "size...
25.214286
13.642857
def get_polarization_change_norm(self, convert_to_muC_per_cm2=True, all_in_polar=True): """ Get magnitude of difference between nonpolar and polar same branch polarization. """ polar = self.structures[-1] a, b, c = polar.lattice.matrix a, b, c = a / np.linalg.norm...
[ "def", "get_polarization_change_norm", "(", "self", ",", "convert_to_muC_per_cm2", "=", "True", ",", "all_in_polar", "=", "True", ")", ":", "polar", "=", "self", ".", "structures", "[", "-", "1", "]", "a", ",", "b", ",", "c", "=", "polar", ".", "lattice"...
47.692308
19.538462
def plot_connectivity_surrogate(self, measure_name, repeats=100, fig=None): """ Plot spectral connectivity measure under the assumption of no actual connectivity. Repeatedly samples connectivity from phase-randomized data. This provides estimates of the connectivity distribution if there was no...
[ "def", "plot_connectivity_surrogate", "(", "self", ",", "measure_name", ",", "repeats", "=", "100", ",", "fig", "=", "None", ")", ":", "cb", "=", "self", ".", "get_surrogate_connectivity", "(", "measure_name", ",", "repeats", ")", "self", ".", "_prepare_plots"...
39.266667
28.166667
def set_dict_item(dct, name_string, set_to): """Sets dictionary item identified by name_string to set_to. name_string is the indentifier generated using flatten_dict. Maintains the type of the orginal object in dct and tries to convert set_to to that type. """ key_strings = str(name_string).sp...
[ "def", "set_dict_item", "(", "dct", ",", "name_string", ",", "set_to", ")", ":", "key_strings", "=", "str", "(", "name_string", ")", ".", "split", "(", "'-->'", ")", "d", "=", "dct", "for", "ks", "in", "key_strings", "[", ":", "-", "1", "]", ":", "...
33.071429
17.142857
def magic_fields(self): """the magic fields for the schema""" return {f:v for f, v in self.fields.items() if f.startswith('_')}
[ "def", "magic_fields", "(", "self", ")", ":", "return", "{", "f", ":", "v", "for", "f", ",", "v", "in", "self", ".", "fields", ".", "items", "(", ")", "if", "f", ".", "startswith", "(", "'_'", ")", "}" ]
47
16.666667
def avl_join_dir_recursive(t1, t2, node, direction): """ Recursive version of join_left and join_right TODO: make this iterative using a stack """ other_side = 1 - direction if _DEBUG_JOIN_DIR: print('--JOIN DIR (dir=%r) --' % (direction,)) ascii_tree(t1, 't1') ascii_tree...
[ "def", "avl_join_dir_recursive", "(", "t1", ",", "t2", ",", "node", ",", "direction", ")", ":", "other_side", "=", "1", "-", "direction", "if", "_DEBUG_JOIN_DIR", ":", "print", "(", "'--JOIN DIR (dir=%r) --'", "%", "(", "direction", ",", ")", ")", "ascii_tre...
34.333333
14.641026
def sanitize(self): ''' Check if the current settings conform to the RFC and fix where possible ''' # Check ports if not isinstance(self.source_port, numbers.Integral) \ or self.source_port < 0 \ or self.source_port >= 2 ** 16: raise ValueError('Invali...
[ "def", "sanitize", "(", "self", ")", ":", "# Check ports", "if", "not", "isinstance", "(", "self", ".", "source_port", ",", "numbers", ".", "Integral", ")", "or", "self", ".", "source_port", "<", "0", "or", "self", ".", "source_port", ">=", "2", "**", ...
38.071429
19.214286
def check_unknown_attachment_in_space(confluence, space_key): """ Detect errors in space :param confluence: :param space_key: :return: """ page_ids = get_all_pages_ids(confluence, space_key) print("Start review pages {} in {}".format(len(page_ids), space_key)) for page_id in...
[ "def", "check_unknown_attachment_in_space", "(", "confluence", ",", "space_key", ")", ":", "page_ids", "=", "get_all_pages_ids", "(", "confluence", ",", "space_key", ")", "print", "(", "\"Start review pages {} in {}\"", ".", "format", "(", "len", "(", "page_ids", ")...
33.461538
16.384615
def save_base_map(filename, grouped_by_text): """Dump a list of agents along with groundings and counts into a csv file Parameters ---------- filename : str Filepath for output file grouped_by_text : list of tuple List of tuples of the form output by agent_texts_with_grounding "...
[ "def", "save_base_map", "(", "filename", ",", "grouped_by_text", ")", ":", "rows", "=", "[", "]", "for", "group", "in", "grouped_by_text", ":", "text_string", "=", "group", "[", "0", "]", "for", "db", ",", "db_id", ",", "count", "in", "group", "[", "1"...
33.73913
17.478261
def get_joined_filters(self, filters): """ Creates a new filters class with active filters joined """ retfilters = Filters(self.filter_converter, self.datamodel) retfilters.filters = self.filters + filters.filters retfilters.values = self.values + filters.values ...
[ "def", "get_joined_filters", "(", "self", ",", "filters", ")", ":", "retfilters", "=", "Filters", "(", "self", ".", "filter_converter", ",", "self", ".", "datamodel", ")", "retfilters", ".", "filters", "=", "self", ".", "filters", "+", "filters", ".", "fil...
41.625
13.125
def resolve_topic(topic): """Return class described by given topic. Args: topic: A string describing a class. Returns: A class. Raises: TopicResolutionError: If there is no such class. """ try: module_name, _, class_name = topic.partition('#') module = ...
[ "def", "resolve_topic", "(", "topic", ")", ":", "try", ":", "module_name", ",", "_", ",", "class_name", "=", "topic", ".", "partition", "(", "'#'", ")", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "except", "ImportError", "as...
26.863636
20.681818
def api_payload(self): """ Generates a payload ready for submission to the API, guided by `_api_payload` """ if not self._api_payload: raise NotImplementedError() payload = {} for attr_name in self._api_payload: value = getattr(self, attr_name, None) i...
[ "def", "api_payload", "(", "self", ")", ":", "if", "not", "self", ".", "_api_payload", ":", "raise", "NotImplementedError", "(", ")", "payload", "=", "{", "}", "for", "attr_name", "in", "self", ".", "_api_payload", ":", "value", "=", "getattr", "(", "sel...
39.7
8.6
def assertNoTMDiffs(tms): """ Check for diffs among the TM instances in the passed in tms dict and raise an assert if any are detected Parameters: --------------------------------------------------------------------- tms: dict of TM instances """ if len(tms) == 1: return if len(...
[ "def", "assertNoTMDiffs", "(", "tms", ")", ":", "if", "len", "(", "tms", ")", "==", "1", ":", "return", "if", "len", "(", "tms", ")", ">", "2", ":", "raise", "\"Not implemented for more than 2 TMs\"", "same", "=", "fdrutils", ".", "tmDiff2", "(", "tms", ...
24.777778
21.555556
def osCopy(self): """ Triggers the OS "copy" keyboard shortcut """ k = Keyboard() k.keyDown("{CTRL}") k.type("c") k.keyUp("{CTRL}")
[ "def", "osCopy", "(", "self", ")", ":", "k", "=", "Keyboard", "(", ")", "k", ".", "keyDown", "(", "\"{CTRL}\"", ")", "k", ".", "type", "(", "\"c\"", ")", "k", ".", "keyUp", "(", "\"{CTRL}\"", ")" ]
27.666667
15
def patch(self, client=None): """Sends all changed properties in a PATCH request. Updates the ``_properties`` with the response from the backend. If :attr:`user_project` is set, bills the API request to that project. :type client: :class:`~google.cloud.storage.client.Client` or ...
[ "def", "patch", "(", "self", ",", "client", "=", "None", ")", ":", "client", "=", "self", ".", "_require_client", "(", "client", ")", "query_params", "=", "self", ".", "_query_params", "# Pass '?projection=full' here because 'PATCH' documented not", "# to work properl...
39.214286
18.357143
def jobs(self): """ Method for getting jobs from stage instance. :return: arrays of jobs. :rtype: list of yagocd.resources.job.JobInstance """ jobs = list() for data in self.data.jobs: jobs.append(JobInstance(session=self._session, data=data, stage=se...
[ "def", "jobs", "(", "self", ")", ":", "jobs", "=", "list", "(", ")", "for", "data", "in", "self", ".", "data", ".", "jobs", ":", "jobs", ".", "append", "(", "JobInstance", "(", "session", "=", "self", ".", "_session", ",", "data", "=", "data", ",...
27.833333
19
def refine_MIDDLEWARE_CLASSES(original): """ Django docs say that the LocaleMiddleware should come after the SessionMiddleware. Here, we make sure that the SessionMiddleware is enabled and then place the LocaleMiddleware at the correct position. Be careful with the order when refining the Middleware...
[ "def", "refine_MIDDLEWARE_CLASSES", "(", "original", ")", ":", "try", ":", "session_middleware_index", "=", "original", ".", "index", "(", "'django.contrib.sessions.middleware.SessionMiddleware'", ")", "original", ".", "insert", "(", "session_middleware_index", "+", "1", ...
52.375
30.875
def new( name: str, arity: Arity, class_name: str=None, *, associative: bool=False, commutative: bool=False, one_identity: bool=False, infix: bool=False ) -> Type['Operation']: """Utility method to create a new o...
[ "def", "new", "(", "name", ":", "str", ",", "arity", ":", "Arity", ",", "class_name", ":", "str", "=", "None", ",", "*", ",", "associative", ":", "bool", "=", "False", ",", "commutative", ":", "bool", "=", "False", ",", "one_identity", ":", "bool", ...
35.315789
21.982456
def _help_workbench(self): """ Help on Workbench """ help = '%sWelcome to Workbench Help:%s' % (color.Yellow, color.Normal) help += '\n\t%s- workbench.help(\'basic\') %s for getting started help' % (color.Green, color.LightBlue) help += '\n\t%s- workbench.help(\'workers\') %s for help on...
[ "def", "_help_workbench", "(", "self", ")", ":", "help", "=", "'%sWelcome to Workbench Help:%s'", "%", "(", "color", ".", "Yellow", ",", "color", ".", "Normal", ")", "help", "+=", "'\\n\\t%s- workbench.help(\\'basic\\') %s for getting started help'", "%", "(", "color"...
84.666667
53.222222
def Shape(docs, drop=0.0): """Get word shapes.""" ids = numpy.zeros((sum(len(doc) for doc in docs),), dtype="i") i = 0 for doc in docs: for token in doc: ids[i] = token.shape i += 1 return ids, None
[ "def", "Shape", "(", "docs", ",", "drop", "=", "0.0", ")", ":", "ids", "=", "numpy", ".", "zeros", "(", "(", "sum", "(", "len", "(", "doc", ")", "for", "doc", "in", "docs", ")", ",", ")", ",", "dtype", "=", "\"i\"", ")", "i", "=", "0", "for...
26.888889
17.333333
def run_sync(self, func, timeout=None): """Starts the `IOLoop`, runs the given function, and stops the loop. The function must return either a yieldable object or ``None``. If the function returns a yieldable object, the `IOLoop` will run until the yieldable is resolved (and `ru...
[ "def", "run_sync", "(", "self", ",", "func", ",", "timeout", "=", "None", ")", ":", "future_cell", "=", "[", "None", "]", "def", "run", "(", ")", ":", "try", ":", "result", "=", "func", "(", ")", "if", "result", "is", "not", "None", ":", "from", ...
39.462963
18.592593
def get_reqs(which="main"): """Gets requirements from all_reqs with versions.""" reqs = [] for req in all_reqs[which]: req_str = req + ">=" + ver_tuple_to_str(min_versions[req]) if req in version_strictly: req_str += ",<" + ver_tuple_to_str(min_versions[req][:-1]) + "." + str(min...
[ "def", "get_reqs", "(", "which", "=", "\"main\"", ")", ":", "reqs", "=", "[", "]", "for", "req", "in", "all_reqs", "[", "which", "]", ":", "req_str", "=", "req", "+", "\">=\"", "+", "ver_tuple_to_str", "(", "min_versions", "[", "req", "]", ")", "if",...
42.222222
20.666667
def show_matrix(es, fs, t, a): ''' print matrix according to viterbi alignment like fs ------------- e|x| | | | s| |x| | | | | | |x| | | |x| | ------------- ''' max_a = viterbi_alignment(es, fs, t, a).items() m = len(es) n = len(fs) retur...
[ "def", "show_matrix", "(", "es", ",", "fs", ",", "t", ",", "a", ")", ":", "max_a", "=", "viterbi_alignment", "(", "es", ",", "fs", ",", "t", ",", "a", ")", ".", "items", "(", ")", "m", "=", "len", "(", "es", ")", "n", "=", "len", "(", "fs",...
20.875
22.25
def get_transformation(self, server_hardware_type_uri, enclosure_group_uri): """ Transforms an existing profile template by supplying a new server hardware type and enclosure group or both. A profile template will be returned with a new configuration based on the capabilities of the supplied ...
[ "def", "get_transformation", "(", "self", ",", "server_hardware_type_uri", ",", "enclosure_group_uri", ")", ":", "query_params", "=", "self", ".", "TRANSFORMATION_PATH", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "uri", "=", "\"{}{}\"", ".", "forma...
52.545455
34.909091
def _rule_block(self): """ Parses the production rule:: block : NAME '{' option* '}' Returns tuple (name, options_list). """ name = self._get_token(self.RE_NAME) self._expect_token('{') # consume additional options if available options =...
[ "def", "_rule_block", "(", "self", ")", ":", "name", "=", "self", ".", "_get_token", "(", "self", ".", "RE_NAME", ")", "self", ".", "_expect_token", "(", "'{'", ")", "# consume additional options if available", "options", "=", "[", "]", "while", "self", ".",...
27.352941
15.411765
def setMLPrefix(self, sMeshLocalPrefix): """set mesh local prefix""" print '%s call setMLPrefix' % self.port try: cmd = 'dataset meshlocalprefix %s' % sMeshLocalPrefix self.hasActiveDatasetToCommit = True return self.__sendCommand(cmd)[0] == 'Done' exc...
[ "def", "setMLPrefix", "(", "self", ",", "sMeshLocalPrefix", ")", ":", "print", "'%s call setMLPrefix'", "%", "self", ".", "port", "try", ":", "cmd", "=", "'dataset meshlocalprefix %s'", "%", "sMeshLocalPrefix", "self", ".", "hasActiveDatasetToCommit", "=", "True", ...
45.444444
14.888889
def _allocate_ids_async(cls, size=None, max=None, parent=None, **ctx_options): """Allocates a range of key IDs for this model class. This is the asynchronous version of Model._allocate_ids(). """ from . import tasklets ctx = tasklets.get_context() cls._pre_allocate_ids...
[ "def", "_allocate_ids_async", "(", "cls", ",", "size", "=", "None", ",", "max", "=", "None", ",", "parent", "=", "None", ",", "*", "*", "ctx_options", ")", ":", "from", ".", "import", "tasklets", "ctx", "=", "tasklets", ".", "get_context", "(", ")", ...
43.125
15.125
def detect_registry_url(client, auto_login=True): """Return a URL of the Docker registry.""" repo = client.repo config = repo.config_reader() # Find registry URL in .git/config remote_url = None try: registry_url = config.get_value('renku', 'registry', None) except NoSectionError: ...
[ "def", "detect_registry_url", "(", "client", ",", "auto_login", "=", "True", ")", ":", "repo", "=", "client", ".", "repo", "config", "=", "repo", ".", "config_reader", "(", ")", "# Find registry URL in .git/config", "remote_url", "=", "None", "try", ":", "regi...
32.650794
18.555556
def relation_get(attribute=None, unit=None, rid=None): """Attempt to use leader-get if supported in the current version of Juju, otherwise falls back on relation-get. Note that we only attempt to use leader-get if the provided rid is a peer relation id or no relation id is provided (in which case we as...
[ "def", "relation_get", "(", "attribute", "=", "None", ",", "unit", "=", "None", ",", "rid", "=", "None", ")", ":", "try", ":", "if", "rid", "in", "relation_ids", "(", "'cluster'", ")", ":", "return", "leader_get", "(", "attribute", ",", "rid", ")", "...
41.066667
15.866667
def simple_in_memory_settings(cls): """ Decorator that returns a class that "persists" data in-memory. Mostly useful for testing :param cls: the class whose features should be persisted in-memory :return: A new class that will persist features in memory """ class Settings(ff.PersistenceSe...
[ "def", "simple_in_memory_settings", "(", "cls", ")", ":", "class", "Settings", "(", "ff", ".", "PersistenceSettings", ")", ":", "id_provider", "=", "ff", ".", "UuidProvider", "(", ")", "key_builder", "=", "ff", ".", "StringDelimitedKeyBuilder", "(", ")", "data...
31.736842
17.736842
def _filter_child_model_fields(cls, fields): """ Keep only related model fields. Example: Inherited models: A -> B -> C B has one-to-many relationship to BMany. after inspection BMany would have links to B and C. Keep only B. Parent model A could not be used (It would not be in ...
[ "def", "_filter_child_model_fields", "(", "cls", ",", "fields", ")", ":", "indexes_to_remove", "=", "set", "(", "[", "]", ")", "for", "index1", ",", "field1", "in", "enumerate", "(", "fields", ")", ":", "for", "index2", ",", "field2", "in", "enumerate", ...
40
20.518519
def get_float(self, key, is_list=False, is_optional=False, is_secret=False, is_local=False, default=None, options=None): """ Get a the value corresponding to the key and converts...
[ "def", "get_float", "(", "self", ",", "key", ",", "is_list", "=", "False", ",", "is_optional", "=", "False", ",", "is_secret", "=", "False", ",", "is_local", "=", "False", ",", "default", "=", "None", ",", "options", "=", "None", ")", ":", "if", "is_...
43.926829
19.146341
def _renorm(args: Dict[str, Any]): """Renormalizes the state using the norm arg.""" state = _state_shard(args) # If our gate is so bad that we have norm of zero, we have bigger problems. state /= np.sqrt(args['norm_squared'])
[ "def", "_renorm", "(", "args", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "state", "=", "_state_shard", "(", "args", ")", "# If our gate is so bad that we have norm of zero, we have bigger problems.", "state", "/=", "np", ".", "sqrt", "(", "args", "[", ...
47.4
11.4
def create_api_gateway_routes( self, lambda_arn, api_name=None, api_key_required=False, authorization_type='NONE', authorizer=None, ...
[ "def", "create_api_gateway_routes", "(", "self", ",", "lambda_arn", ",", "api_name", "=", "None", ",", "api_key_required", "=", "False", ",", "authorization_type", "=", "'NONE'", ",", "authorizer", "=", "None", ",", "cors_options", "=", "None", ",", "description...
45.369565
19.23913
def read_numeric(fmt, buff, byteorder='big'): """Read a numeric value from a file-like object.""" try: fmt = fmt[byteorder] return fmt.unpack(buff.read(fmt.size))[0] except StructError: return 0 except KeyError as exc: raise ValueError('Invalid byte order') from e...
[ "def", "read_numeric", "(", "fmt", ",", "buff", ",", "byteorder", "=", "'big'", ")", ":", "try", ":", "fmt", "=", "fmt", "[", "byteorder", "]", "return", "fmt", ".", "unpack", "(", "buff", ".", "read", "(", "fmt", ".", "size", ")", ")", "[", "0",...
34.888889
13.777778
def _parse_out_variable(self): """Internal method to parse the tc_playbook_out_variable arg. **Example Variable Format**:: #App:1234:status!String,#App:1234:status_code!String """ self._out_variables = {} self._out_variables_type = {} if self.tcex.default_ar...
[ "def", "_parse_out_variable", "(", "self", ")", ":", "self", ".", "_out_variables", "=", "{", "}", "self", ".", "_out_variables_type", "=", "{", "}", "if", "self", ".", "tcex", ".", "default_args", ".", "tc_playbook_out_variables", ":", "variables", "=", "se...
49.333333
19.238095
def cont(self, event = None): """ Resumes execution after processing a debug event. @see: dispatch(), loop(), wait() @type event: L{Event} @param event: (Optional) Event object returned by L{wait}. @raise WindowsError: Raises an exception on error. """ ...
[ "def", "cont", "(", "self", ",", "event", "=", "None", ")", ":", "# If no event object was given, use the last event.", "if", "event", "is", "None", ":", "event", "=", "self", ".", "lastEvent", "# Ignore dummy events.", "if", "not", "event", ":", "return", "# Ge...
34.890909
20.963636
def Then5(self, f, arg1, arg2, arg3, arg4, *args, **kwargs): """ `Then5(f, ...)` is equivalent to `ThenAt(5, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. """ args = (arg1, arg2, arg3, arg4) + args return self.ThenAt(5, f, *args, **kwargs)
[ "def", "Then5", "(", "self", ",", "f", ",", "arg1", ",", "arg2", ",", "arg3", ",", "arg4", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "(", "arg1", ",", "arg2", ",", "arg3", ",", "arg4", ")", "+", "args", "return", "self...
48.333333
18
def K2onSilicon_main(args=None): """Function called when `K2onSilicon` is executed on the command line.""" import argparse parser = argparse.ArgumentParser( description="Run K2onSilicon to find which targets in a " "list call on active silicon for a given K2 campaign.") parse...
[ "def", "K2onSilicon_main", "(", "args", "=", "None", ")", ":", "import", "argparse", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Run K2onSilicon to find which targets in a \"", "\"list call on active silicon for a given K2 campaign.\"", ")", ...
53.583333
16.833333
def add_rule(self, name, callable_): """Makes rule 'name' available to all subsequently loaded Jamfiles. Calling that rule wil relay to 'callable'.""" assert isinstance(name, basestring) assert callable(callable_) self.project_rules_.add_rule(name, callable_)
[ "def", "add_rule", "(", "self", ",", "name", ",", "callable_", ")", ":", "assert", "isinstance", "(", "name", ",", "basestring", ")", "assert", "callable", "(", "callable_", ")", "self", ".", "project_rules_", ".", "add_rule", "(", "name", ",", "callable_"...
42
9.428571
def find_template(repo_dir): """Determine which child directory of `repo_dir` is the project template. :param repo_dir: Local directory of newly cloned repo. :returns project_template: Relative path to project template. """ logger.debug('Searching {} for the project template.'.format(repo_dir)) ...
[ "def", "find_template", "(", "repo_dir", ")", ":", "logger", ".", "debug", "(", "'Searching {} for the project template.'", ".", "format", "(", "repo_dir", ")", ")", "repo_dir_contents", "=", "os", ".", "listdir", "(", "repo_dir", ")", "project_template", "=", "...
33.958333
20.875
def create(self, **kwargs): """Custom _create method to accommodate for issue 11.5.4 and 12.1.1, Where creation of an object would return 404, despite the object being created. """ tmos_v = self._meta_data['bigip']._meta_data['tmos_version'] if LooseVersion(tmos_v) == Lo...
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "tmos_v", "=", "self", ".", "_meta_data", "[", "'bigip'", "]", ".", "_meta_data", "[", "'tmos_version'", "]", "if", "LooseVersion", "(", "tmos_v", ")", "==", "LooseVersion", "(", "'11.5.4'"...
47.071429
21.857143
def hexdump(x, dump=False): """Build a tcpdump like hexadecimal view :param x: a Packet :param dump: define if the result must be printed or returned in a variable :returns: a String only when dump=True """ s = "" x = bytes_encode(x) x_len = len(x) i = 0 while i < x_len: ...
[ "def", "hexdump", "(", "x", ",", "dump", "=", "False", ")", ":", "s", "=", "\"\"", "x", "=", "bytes_encode", "(", "x", ")", "x_len", "=", "len", "(", "x", ")", "i", "=", "0", "while", "i", "<", "x_len", ":", "s", "+=", "\"%04x \"", "%", "i",...
24.923077
17.961538
def get_drill_bits_d_imperial(): """Return array of possible drill diameters in imperial.""" step_32nd = np.arange(0.03125, 0.25, 0.03125) step_8th = np.arange(0.25, 1.0, 0.125) step_4th = np.arange(1.0, 2.0, 0.25) maximum = [2.0] return np.concatenate((step_32nd, ste...
[ "def", "get_drill_bits_d_imperial", "(", ")", ":", "step_32nd", "=", "np", ".", "arange", "(", "0.03125", ",", "0.25", ",", "0.03125", ")", "step_8th", "=", "np", ".", "arange", "(", "0.25", ",", "1.0", ",", "0.125", ")", "step_4th", "=", "np", ".", ...
36.272727
8.727273
def load_page(self, payload): """ Parses the collection of records out of a list payload. :param dict payload: The JSON-loaded content. :return list: The list of records. """ if 'meta' in payload and 'key' in payload['meta']: return payload[payload['meta']['k...
[ "def", "load_page", "(", "self", ",", "payload", ")", ":", "if", "'meta'", "in", "payload", "and", "'key'", "in", "payload", "[", "'meta'", "]", ":", "return", "payload", "[", "payload", "[", "'meta'", "]", "[", "'key'", "]", "]", "else", ":", "keys"...
34.125
14.25
def run_model(self, model_run, run_url): """Execute the given model run. Throws a ValueError if the given run specifies an unknown model or if the model connector is invalid. An EngineException is thrown if running the model (i.e., communication with the backend) fails. Paramet...
[ "def", "run_model", "(", "self", ",", "model_run", ",", "run_url", ")", ":", "# Get model to verify that it exists and to get connector information", "model", "=", "self", ".", "get_model", "(", "model_run", ".", "model_id", ")", "if", "model", "is", "None", ":", ...
42.190476
19.809524
def one_hot(x, size, dtype=np.float32): """Make a n+1 dim one-hot array from n dim int-categorical array.""" return np.array(x[..., np.newaxis] == np.arange(size), dtype)
[ "def", "one_hot", "(", "x", ",", "size", ",", "dtype", "=", "np", ".", "float32", ")", ":", "return", "np", ".", "array", "(", "x", "[", "...", ",", "np", ".", "newaxis", "]", "==", "np", ".", "arange", "(", "size", ")", ",", "dtype", ")" ]
57.333333
8
def validate_submission(self, filename): """Validates submission. Args: filename: submission filename Returns: submission metadata or None if submission is invalid """ self._prepare_temp_dir() # Convert filename to be absolute path, relative path might cause problems # with mou...
[ "def", "validate_submission", "(", "self", ",", "filename", ")", ":", "self", ".", "_prepare_temp_dir", "(", ")", "# Convert filename to be absolute path, relative path might cause problems", "# with mounting directory in Docker", "filename", "=", "os", ".", "path", ".", "a...
34.702703
15.918919
def setCol(self, x, l): """set the x-th column, starting at 0""" for i in xrange(0, self.__size): self.setCell(x, i, l[i])
[ "def", "setCol", "(", "self", ",", "x", ",", "l", ")", ":", "for", "i", "in", "xrange", "(", "0", ",", "self", ".", "__size", ")", ":", "self", ".", "setCell", "(", "x", ",", "i", ",", "l", "[", "i", "]", ")" ]
36.75
5.25
def fit(self, y, **kwargs): """ Sets up y for the histogram and checks to ensure that ``y`` is of the correct data type. Fit calls draw. Parameters ---------- y : an array of one dimension or a pandas Series kwargs : dict keyword arguments pa...
[ "def", "fit", "(", "self", ",", "y", ",", "*", "*", "kwargs", ")", ":", "#throw an error if y has more than 1 column", "if", "y", ".", "ndim", ">", "1", ":", "raise", "YellowbrickValueError", "(", "\"y needs to be an array or Series with one dimension\"", ")", "# Ha...
26.68
21.32
def identify(self, text, **kwargs): """ Identify language. Identifies the language of the input text. :param str text: Input text in UTF-8 format. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers a...
[ "def", "identify", "(", "self", ",", "text", ",", "*", "*", "kwargs", ")", ":", "if", "text", "is", "None", ":", "raise", "ValueError", "(", "'text must be provided'", ")", "headers", "=", "{", "}", "if", "'headers'", "in", "kwargs", ":", "headers", "....
28.742857
19.2
def update_aliases(self): """Get aliases information from room state. Returns: boolean: True if the aliases changed, False if not """ try: response = self.client.api.get_room_state(self.room_id) for chunk in response: if "content" in c...
[ "def", "update_aliases", "(", "self", ")", ":", "try", ":", "response", "=", "self", ".", "client", ".", "api", ".", "get_room_state", "(", "self", ".", "room_id", ")", "for", "chunk", "in", "response", ":", "if", "\"content\"", "in", "chunk", "and", "...
37.470588
17.235294
def relaxation_as_linear_operator(method, A, b): """Create a linear operator that applies a relaxation method for the given right-hand-side. Parameters ---------- methods : {tuple or string} Relaxation descriptor: Each tuple must be of the form ('method','opts') where 'method' is the na...
[ "def", "relaxation_as_linear_operator", "(", "method", ",", "A", ",", "b", ")", ":", "from", "pyamg", "import", "relaxation", "from", "scipy", ".", "sparse", ".", "linalg", ".", "interface", "import", "LinearOperator", "import", "pyamg", ".", "multilevel", "de...
35.191781
23.465753
def create_projection(self, fov: float = 75.0, near: float = 1.0, far: float = 100.0, aspect_ratio: float = None): """ Create a projection matrix with the following parameters. When ``aspect_ratio`` is not provided the configured aspect ratio for the window will be used. Args: ...
[ "def", "create_projection", "(", "self", ",", "fov", ":", "float", "=", "75.0", ",", "near", ":", "float", "=", "1.0", ",", "far", ":", "float", "=", "100.0", ",", "aspect_ratio", ":", "float", "=", "None", ")", ":", "return", "matrix44", ".", "creat...
34.041667
22.208333
def add_to_submission(self, submission_id, submission_objects): """Adds submission_objects to clinvar collection and update the coresponding submission object with their id Args: submission_id(str) : id of the submission to be updated submission_objects(tuple): a tup...
[ "def", "add_to_submission", "(", "self", ",", "submission_id", ",", "submission_objects", ")", ":", "LOG", ".", "info", "(", "\"Adding new variants and case data to clinvar submission '%s'\"", ",", "submission_id", ")", "# Insert variant submission_objects into clinvar collection...
58
37.5
def scan_aggs(search, source_aggs, inner_aggs={}, size=10): """ Helper function used to iterate over all possible bucket combinations of ``source_aggs``, returning results of ``inner_aggs`` for each. Uses the ``composite`` aggregation under the hood to perform this. """ def run_search(**kwargs):...
[ "def", "scan_aggs", "(", "search", ",", "source_aggs", ",", "inner_aggs", "=", "{", "}", ",", "size", "=", "10", ")", ":", "def", "run_search", "(", "*", "*", "kwargs", ")", ":", "s", "=", "search", "[", ":", "0", "]", "s", ".", "aggs", ".", "b...
41.090909
17.181818
def _randomize_single_subject(data, seed=None): """Randomly permute the voxels of the subject. The subject is organized as Voxel x TR, this method shuffles the voxel dimension in place. Parameters ---------- data: 2D array in shape [nVoxels, nTRs] Activity image data to be shuffled. ...
[ "def", "_randomize_single_subject", "(", "data", ",", "seed", "=", "None", ")", ":", "if", "seed", "is", "not", "None", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "np", ".", "random", ".", "shuffle", "(", "data", ")" ]
25.5
18.55
def gen_batches(data, batch_size): """Divide input data into batches. :param data: input data :param batch_size: size of each batch :return: data divided into batches """ data = np.array(data) for i in range(0, data.shape[0], batch_size): yield data[i:i + batch_size]
[ "def", "gen_batches", "(", "data", ",", "batch_size", ")", ":", "data", "=", "np", ".", "array", "(", "data", ")", "for", "i", "in", "range", "(", "0", ",", "data", ".", "shape", "[", "0", "]", ",", "batch_size", ")", ":", "yield", "data", "[", ...
26.818182
11.818182
def get_historical_orders(self, symbol=None, side=None, start=None, end=None, page=None, limit=None): """List of KuCoin V1 historical orders. https://docs.kucoin.com/#get-v1-historical-orders-list :param symbol: (optional) Name of symbol e.g. KCS-BTC :type...
[ "def", "get_historical_orders", "(", "self", ",", "symbol", "=", "None", ",", "side", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "page", "=", "None", ",", "limit", "=", "None", ")", ":", "data", "=", "{", "}", "if", "sy...
28.338462
18.830769
def get_known_name(s: str) -> Optional[Tuple[str, ColorArg]]: """ Reverse translate a terminal code to a known color name, if possible. Returns a tuple of (codetype, knownname) on success. Returns None on failure. """ if not s.endswith('m'): # All codes end with 'm', so... r...
[ "def", "get_known_name", "(", "s", ":", "str", ")", "->", "Optional", "[", "Tuple", "[", "str", ",", "ColorArg", "]", "]", ":", "if", "not", "s", ".", "endswith", "(", "'m'", ")", ":", "# All codes end with 'm', so...", "return", "None", "if", "s", "."...
32.779661
12.610169
def commit_to(self, db: BaseDB) -> None: """ Trying to commit changes when nothing has been written will raise a ValidationError """ self.logger.debug2('persist storage root to data store') if self._trie_nodes_batch is None: raise ValidationError( ...
[ "def", "commit_to", "(", "self", ",", "db", ":", "BaseDB", ")", "->", "None", ":", "self", ".", "logger", ".", "debug2", "(", "'persist storage root to data store'", ")", "if", "self", ".", "_trie_nodes_batch", "is", "None", ":", "raise", "ValidationError", ...
45.846154
18.923077
def set_controller_value(self, index_or_name, value): """ Sets controller value :param index_or_name integer index or string name :param value float """ if not isinstance(index_or_name, int): index = self.get_controller_index(index_or_name) else: ...
[ "def", "set_controller_value", "(", "self", ",", "index_or_name", ",", "value", ")", ":", "if", "not", "isinstance", "(", "index_or_name", ",", "int", ")", ":", "index", "=", "self", ".", "get_controller_index", "(", "index_or_name", ")", "else", ":", "index...
33.666667
15
def connect_model(self, model): """Link the Database to the Model instance. In case a new database is created from scratch, ``connect_model`` creates Trace objects for all tallyable pymc objects defined in `model`. If the database is being loaded from an existing file, ``connec...
[ "def", "connect_model", "(", "self", ",", "model", ")", ":", "# Changed this to allow non-Model models. -AP", "# We could also remove it altogether. -DH", "if", "isinstance", "(", "model", ",", "pymc", ".", "Model", ")", ":", "self", ".", "model", "=", "model", "els...
40.456522
17.326087
def is_ip_addr(value): """ Check that the supplied value is an Internet Protocol address, v.4, represented by a dotted-quad string, i.e. '1.2.3.4'. >>> vtor = Validator() >>> vtor.check('ip_addr', '1 ') '1' >>> vtor.check('ip_addr', ' 1.2') '1.2' >>> vtor.check('ip_addr', ' 1.2.3 ')...
[ "def", "is_ip_addr", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", "raise", "VdtTypeError", "(", "value", ")", "value", "=", "value", ".", "strip", "(", ")", "try", ":", "dottedQuadToNum", "(", "value", ...
32.694444
14.75
def _b64encode_to_str(data): """ Wrapper around b64encode which takes and returns same-named types on both Python 2 and Python 3. :type data: bytes :return: str """ ret = b64encode(data) if not isinstance(ret, str): # Python3 return ret.decode('ascii') else: return r...
[ "def", "_b64encode_to_str", "(", "data", ")", ":", "ret", "=", "b64encode", "(", "data", ")", "if", "not", "isinstance", "(", "ret", ",", "str", ")", ":", "# Python3", "return", "ret", ".", "decode", "(", "'ascii'", ")", "else", ":", "return", "ret" ]
25.916667
13.916667
def get_atext(value): """atext = <matches _atext_matcher> We allow any non-ATOM_ENDS in atext, but add an InvalidATextDefect to the token's defects list if we find non-atext characters. """ m = _non_atom_end_matcher(value) if not m: raise errors.HeaderParseError( "expected a...
[ "def", "get_atext", "(", "value", ")", ":", "m", "=", "_non_atom_end_matcher", "(", "value", ")", "if", "not", "m", ":", "raise", "errors", ".", "HeaderParseError", "(", "\"expected atext but found '{}'\"", ".", "format", "(", "value", ")", ")", "atext", "="...
32.466667
15
def remover(self, id_tipo_acesso): """Removes access type by its identifier. :param id_tipo_acesso: Access type identifier. :return: None :raise TipoAcessoError: Access type associated with equipment, cannot be removed. :raise InvalidParameterError: Protocol value is invalid o...
[ "def", "remover", "(", "self", ",", "id_tipo_acesso", ")", ":", "if", "not", "is_valid_int_param", "(", "id_tipo_acesso", ")", ":", "raise", "InvalidParameterError", "(", "u'Access type id is invalid or was not informed.'", ")", "url", "=", "'tipoacesso/'", "+", "str"...
38.272727
23.363636
def getBranch(self, name, **context): """Return a branch of this tree where the 'name' OID may reside""" for keyLen in self._vars.getKeysLens(): subName = name[:keyLen] if subName in self._vars: return self._vars[subName] raise error.NoSuchObjectError(nam...
[ "def", "getBranch", "(", "self", ",", "name", ",", "*", "*", "context", ")", ":", "for", "keyLen", "in", "self", ".", "_vars", ".", "getKeysLens", "(", ")", ":", "subName", "=", "name", "[", ":", "keyLen", "]", "if", "subName", "in", "self", ".", ...
43
11.5
def _modules_to_main(modList): """Force every module in modList to be placed into main""" if not modList: return main = sys.modules['__main__'] for modname in modList: if isinstance(modname, str): try: mod = __import__(modname) except Exception: sys.stderr.write( ...
[ "def", "_modules_to_main", "(", "modList", ")", ":", "if", "not", "modList", ":", "return", "main", "=", "sys", ".", "modules", "[", "'__main__'", "]", "for", "modname", "in", "modList", ":", "if", "isinstance", "(", "modname", ",", "str", ")", ":", "t...
32.222222
18
def iter_trees(self, *args, **kwargs): """:return: Iterator yielding Tree objects :note: Takes all arguments known to iter_commits method""" return (c.tree for c in self.iter_commits(*args, **kwargs))
[ "def", "iter_trees", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "(", "c", ".", "tree", "for", "c", "in", "self", ".", "iter_commits", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
55.25
7.25
def hook(reverse=False, align=False, strip_path=False, enable_on_envvar_only=False, on_tty=False, conservative=False, styles=None, tb=None, tpe=None, value=None): """Hook the current excepthook to the backtrace. If `align` is True...
[ "def", "hook", "(", "reverse", "=", "False", ",", "align", "=", "False", ",", "strip_path", "=", "False", ",", "enable_on_envvar_only", "=", "False", ",", "on_tty", "=", "False", ",", "conservative", "=", "False", ",", "styles", "=", "None", ",", "tb", ...
32.873418
23.291139
def _commit(self): """Transactionally commit the changes accumulated. Returns: List[google.cloud.proto.firestore.v1beta1.\ write_pb2.WriteResult, ...]: The write results corresponding to the changes committed, returned in the same order as the changes...
[ "def", "_commit", "(", "self", ")", ":", "if", "not", "self", ".", "in_progress", ":", "raise", "ValueError", "(", "_CANT_COMMIT", ")", "commit_response", "=", "_commit_with_retry", "(", "self", ".", "_client", ",", "self", ".", "_write_pbs", ",", "self", ...
36.2
22.55
def _align_header(header, alignment, width, visible_width, is_multiline=False, width_fn=None): "Pad string header to width chars given known visible_width of the header." if is_multiline: header_lines = re.split(_multiline_codes, header) padded_lines = [_align_header(h, alignme...
[ "def", "_align_header", "(", "header", ",", "alignment", ",", "width", ",", "visible_width", ",", "is_multiline", "=", "False", ",", "width_fn", "=", "None", ")", ":", "if", "is_multiline", ":", "header_lines", "=", "re", ".", "split", "(", "_multiline_codes...
39.684211
14.526316
def tour(self, action='start', channel=0, start=True, tour_path_number=1): """ Params: action - start or stop channel - channel number start - True (StartTour) or False (StopTour) tour_path_number - tour path numbe...
[ "def", "tour", "(", "self", ",", "action", "=", "'start'", ",", "channel", "=", "0", ",", "start", "=", "True", ",", "tour_path_number", "=", "1", ")", ":", "ret", "=", "self", ".", "command", "(", "'ptz.cgi?action={0}&channel={1}&code={2}Tour&arg1={3}'", "'...
40.533333
14.533333
async def get_blueprint_params(request, left: int, right: int) -> str: """ API Description: Multiply, left * right. This will show in the swagger page (localhost:8000/api/v1/). """ res = left * right return "{left}*{right}={res}".format(left=left, right=right, res=res)
[ "async", "def", "get_blueprint_params", "(", "request", ",", "left", ":", "int", ",", "right", ":", "int", ")", "->", "str", ":", "res", "=", "left", "*", "right", "return", "\"{left}*{right}={res}\"", ".", "format", "(", "left", "=", "left", ",", "right...
47.333333
24.333333
def replace(self, match, content): """Replace all occurences of the regex in all matches from a file with a specific value. """ new_string = self.replace_expression.sub(self.replace_with, match) logger.info('Replacing: [ %s ] --> [ %s ]', match, new_string) new_content = ...
[ "def", "replace", "(", "self", ",", "match", ",", "content", ")", ":", "new_string", "=", "self", ".", "replace_expression", ".", "sub", "(", "self", ".", "replace_with", ",", "match", ")", "logger", ".", "info", "(", "'Replacing: [ %s ] --> [ %s ]'", ",", ...
46.75
12.75
def my_glob(pattern): """ get a listing matching pattern @param pattern: @return: """ result = [] if pattern[0:4] == 'vos:': dirname = os.path.dirname(pattern) flist = listdir(dirname) for fname in flist: fname = '/'.join([dirname, fname]) if ...
[ "def", "my_glob", "(", "pattern", ")", ":", "result", "=", "[", "]", "if", "pattern", "[", "0", ":", "4", "]", "==", "'vos:'", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "pattern", ")", "flist", "=", "listdir", "(", "dirname", "...
23.944444
14.055556
def wait_until_complete(self, timeout=None): """Wait until sequencer is finished. This method blocks your application until the sequencer has completed its operation. It returns once the sequencer has finished. Arguments: timeout -- Optional. Seconds to wait for sequencer to ...
[ "def", "wait_until_complete", "(", "self", ",", "timeout", "=", "None", ")", ":", "timeout_at", "=", "None", "if", "timeout", ":", "timeout_at", "=", "time", ".", "time", "(", ")", "+", "int", "(", "timeout", ")", "sequencer", "=", "self", ".", "get", ...
35.448276
22.793103
def _on_channel_open(self, channel): """ Callback used when a channel is opened. This registers all the channel callbacks. Args: channel (pika.channel.Channel): The channel that successfully opened. """ channel.add_on_close_callback(self._on_channel_close) ...
[ "def", "_on_channel_open", "(", "self", ",", "channel", ")", ":", "channel", ".", "add_on_close_callback", "(", "self", ".", "_on_channel_close", ")", "channel", ".", "add_on_cancel_callback", "(", "self", ".", "_on_cancel", ")", "channel", ".", "basic_qos", "("...
33.538462
21.230769
def shape(self): """Returns a tuple of row, column, (band count if multidimensional).""" shp = (self.ds.RasterYSize, self.ds.RasterXSize, self.ds.RasterCount) return shp[:2] if shp[2] <= 1 else shp
[ "def", "shape", "(", "self", ")", ":", "shp", "=", "(", "self", ".", "ds", ".", "RasterYSize", ",", "self", ".", "ds", ".", "RasterXSize", ",", "self", ".", "ds", ".", "RasterCount", ")", "return", "shp", "[", ":", "2", "]", "if", "shp", "[", "...
54.5
16.75
def mkdir(self, remote_path): """Makes new directory on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MKCOL :param remote_path: path to directory :return: True if request executed with code 200 or 201 and False otherwise. """ ...
[ "def", "mkdir", "(", "self", ",", "remote_path", ")", ":", "directory_urn", "=", "Urn", "(", "remote_path", ",", "directory", "=", "True", ")", "try", ":", "response", "=", "self", ".", "execute_request", "(", "action", "=", "'mkdir'", ",", "path", "=", ...
33.157895
24.578947
def unquote_redirection_tokens(args: List[str]) -> None: """ Unquote redirection tokens in a list of command-line arguments This is used when redirection tokens have to be passed to another command :param args: the command line args """ for i, arg in enumerate(args): unquoted_arg = strip...
[ "def", "unquote_redirection_tokens", "(", "args", ":", "List", "[", "str", "]", ")", "->", "None", ":", "for", "i", ",", "arg", "in", "enumerate", "(", "args", ")", ":", "unquoted_arg", "=", "strip_quotes", "(", "arg", ")", "if", "unquoted_arg", "in", ...
41.5
10.9
def check_settings(required_settings): """ Checks all settings required by a module have been set. If a setting is required and it could not be found a NotImplementedError will be raised informing which settings are missing. :param required_settings: List of settings names (as strings) that ...
[ "def", "check_settings", "(", "required_settings", ")", ":", "defined_settings", "=", "[", "setting", "if", "hasattr", "(", "settings", ",", "setting", ")", "else", "None", "for", "setting", "in", "required_settings", "]", "if", "not", "all", "(", "defined_set...
32.818182
22.545455