text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def load_savefile(input_file, layers=0, verbose=False, lazy=False): """ Parse a savefile as a pcap_savefile instance. Returns the savefile on success and None on failure. Verbose mode prints additional information about the file's processing. layers defines how many layers to descend and decode the ...
[ "def", "load_savefile", "(", "input_file", ",", "layers", "=", "0", ",", "verbose", "=", "False", ",", "lazy", "=", "False", ")", ":", "global", "VERBOSE", "old_verbose", "=", "VERBOSE", "VERBOSE", "=", "verbose", "__TRACE__", "(", "'[+] attempting to load {:s...
36.966667
20.633333
def true_negatives(links_true, links_pred, total): """Count the number of True Negatives. Returns the number of correctly predicted non-links, also called the number of True Negatives (TN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (o...
[ "def", "true_negatives", "(", "links_true", ",", "links_pred", ",", "total", ")", ":", "links_true", "=", "_get_multiindex", "(", "links_true", ")", "links_pred", "=", "_get_multiindex", "(", "links_pred", ")", "if", "isinstance", "(", "total", ",", "pandas", ...
29.966667
22.133333
def call_rpc(self, rpc_id, payload=bytes()): """Call an RPC by its ID. Args: rpc_id (int): The number of the RPC payload (bytes): A byte string of payload parameters up to 20 bytes Returns: str: The response payload from the RPC """ # If we ...
[ "def", "call_rpc", "(", "self", ",", "rpc_id", ",", "payload", "=", "bytes", "(", ")", ")", ":", "# If we define the RPC locally, call that one. We use this for reporting", "# our status", "if", "super", "(", "ServiceDelegateTile", ",", "self", ")", ".", "has_rpc", ...
49.761905
29.238095
def get_effective_member_count(self, group_id): """ Returns a count of effective members for the group identified by the passed group ID. """ self._valid_group_id(group_id) url = "{}/group/{}/effective_member?view=count".format(self.API, ...
[ "def", "get_effective_member_count", "(", "self", ",", "group_id", ")", ":", "self", ".", "_valid_group_id", "(", "group_id", ")", "url", "=", "\"{}/group/{}/effective_member?view=count\"", ".", "format", "(", "self", ".", "API", ",", "group_id", ")", "data", "=...
32.785714
19.071429
def getFullFMAtIndex(self, index): ''' This function creates a complete FM-index for a specific position in the BWT. Example using the above example: BWT Full FM-index $ A C G T C 0 1 2 4 4 $ 0 1 3 4 4 C 1 1 3 4 4 A ...
[ "def", "getFullFMAtIndex", "(", "self", ",", "index", ")", ":", "#get the bin we occupy", "binID", "=", "index", ">>", "self", ".", "bitPower", "if", "binID", "<<", "self", ".", "bitPower", "==", "index", ":", "ret", "=", "self", ".", "partialFM", "[", "...
40.421053
23.789474
def _is_physical_entity(pe): """Return True if the element is a physical entity""" val = isinstance(pe, _bp('PhysicalEntity')) or \ isinstance(pe, _bpimpl('PhysicalEntity')) return val
[ "def", "_is_physical_entity", "(", "pe", ")", ":", "val", "=", "isinstance", "(", "pe", ",", "_bp", "(", "'PhysicalEntity'", ")", ")", "or", "isinstance", "(", "pe", ",", "_bpimpl", "(", "'PhysicalEntity'", ")", ")", "return", "val" ]
40.8
12.6
def parse_s2bs(s2bs): """ convert s2b files to dictionary """ s2b = {} for s in s2bs: for line in open(s): line = line.strip().split('\t') s, b = line[0], line[1] s2b[s] = b return s2b
[ "def", "parse_s2bs", "(", "s2bs", ")", ":", "s2b", "=", "{", "}", "for", "s", "in", "s2bs", ":", "for", "line", "in", "open", "(", "s", ")", ":", "line", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "'\\t'", ")", "s", ",", "b", "...
22
12.545455
def unpackStruct(self, data, def_buf): """ Wrapper for struct.unpack with SerialBlock buffer definitionns. Args: data (str): Implicit cast bytes to str, serial port return. def_buf (SerialBlock): Block object holding field lengths. Returns: tuple: parsed res...
[ "def", "unpackStruct", "(", "self", ",", "data", ",", "def_buf", ")", ":", "struct_str", "=", "\"=\"", "for", "fld", "in", "def_buf", ":", "if", "not", "def_buf", "[", "fld", "]", "[", "MeterData", ".", "CalculatedFlag", "]", ":", "struct_str", "=", "s...
39.45
22.45
def setup(self, middleware): """ Setup middleware :param middleware: :return: """ if not isinstance(middleware, BaseMiddleware): raise TypeError(f"`middleware` must be an instance of BaseMiddleware, not {type(middleware)}") if middleware.is_configured...
[ "def", "setup", "(", "self", ",", "middleware", ")", ":", "if", "not", "isinstance", "(", "middleware", ",", "BaseMiddleware", ")", ":", "raise", "TypeError", "(", "f\"`middleware` must be an instance of BaseMiddleware, not {type(middleware)}\"", ")", "if", "middleware"...
34.375
19.625
def _set_clear_mpls_auto_bandwidth_sample_history_lsp(self, v, load=False): """ Setter method for clear_mpls_auto_bandwidth_sample_history_lsp, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_auto_bandwidth_sample_history_lsp (rpc) If this variable is read-only (config: false) in the source YANG ...
[ "def", "_set_clear_mpls_auto_bandwidth_sample_history_lsp", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynC...
95.318182
47.727273
def childAtPath(self, path): """ Get a child at I{path} where I{path} is a (/) separated list of element names that are expected to be children. @param path: A (/) separated list of element names. @type path: basestring @return: The leaf node at the end of I{path} ...
[ "def", "childAtPath", "(", "self", ",", "path", ")", ":", "if", "self", ".", "__root", "is", "None", ":", "return", "None", "if", "path", "[", "0", "]", "==", "'/'", ":", "path", "=", "path", "[", "1", ":", "]", "path", "=", "path", ".", "split...
33.3
12.8
def every_other(iterable): """ Yield every other item from the iterable >>> ' '.join(every_other('abcdefg')) 'a c e g' """ items = iter(iterable) while True: try: yield next(items) next(items) except StopIteration: return
[ "def", "every_other", "(", "iterable", ")", ":", "items", "=", "iter", "(", "iterable", ")", "while", "True", ":", "try", ":", "yield", "next", "(", "items", ")", "next", "(", "items", ")", "except", "StopIteration", ":", "return" ]
16.357143
18.642857
def _insert_layer_between(self, src, snk, new_layer, new_keras_layer): """ Insert the new_layer before layer, whose position is layer_idx. The new layer's parameter is stored in a Keras layer called new_keras_layer """ if snk is None: insert_pos = self.layer_list.inde...
[ "def", "_insert_layer_between", "(", "self", ",", "src", ",", "snk", ",", "new_layer", ",", "new_keras_layer", ")", ":", "if", "snk", "is", "None", ":", "insert_pos", "=", "self", ".", "layer_list", ".", "index", "(", "src", ")", "+", "1", "else", ":",...
43.894737
14.526316
def _set_rstp(self, v, load=False): """ Setter method for rstp, mapped from YANG variable /protocol/spanning_tree/rstp (container) If this variable is read-only (config: false) in the source YANG file, then _set_rstp is considered as a private method. Backends looking to populate this variable shoul...
[ "def", "_set_rstp", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
89.772727
42.5
def shutdown(self, msg, args): """Causes the bot to gracefully shutdown.""" self.log.info("Received shutdown from %s", msg.user.username) self._bot.runnable = False return "Shutting down..."
[ "def", "shutdown", "(", "self", ",", "msg", ",", "args", ")", ":", "self", ".", "log", ".", "info", "(", "\"Received shutdown from %s\"", ",", "msg", ".", "user", ".", "username", ")", "self", ".", "_bot", ".", "runnable", "=", "False", "return", "\"Sh...
43.6
10.4
def expected_magz(RAW_IMU, ATTITUDE, inclination, declination): '''estimate from mag''' v = expected_mag(RAW_IMU, ATTITUDE, inclination, declination) return v.z
[ "def", "expected_magz", "(", "RAW_IMU", ",", "ATTITUDE", ",", "inclination", ",", "declination", ")", ":", "v", "=", "expected_mag", "(", "RAW_IMU", ",", "ATTITUDE", ",", "inclination", ",", "declination", ")", "return", "v", ".", "z" ]
42.5
21.5
def _collect_conflicts_between( context, # type: ValidationContext conflicts, # type: List[Tuple[Tuple[str, str], List[Node], List[Node]]] cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], ...
[ "def", "_collect_conflicts_between", "(", "context", ",", "# type: ValidationContext", "conflicts", ",", "# type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]", "cached_fields_and_fragment_names", ",", "# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, G...
53.076923
27.025641
def fit_image(self, sma0=None, minsma=0., maxsma=None, step=0.1, conver=DEFAULT_CONVERGENCE, minit=DEFAULT_MINIT, maxit=DEFAULT_MAXIT, fflag=DEFAULT_FFLAG, maxgerr=DEFAULT_MAXGERR, sclip=3., nclip=0, integrmode=BILINEAR, linear=False, maxrit=None):...
[ "def", "fit_image", "(", "self", ",", "sma0", "=", "None", ",", "minsma", "=", "0.", ",", "maxsma", "=", "None", ",", "step", "=", "0.1", ",", "conver", "=", "DEFAULT_CONVERGENCE", ",", "minit", "=", "DEFAULT_MINIT", ",", "maxit", "=", "DEFAULT_MAXIT", ...
50.677291
23.266932
def enable_fundamental_type_wrappers(self): """ If a type is a int128, a long_double_t or a void, some placeholders need to be in the generated code to be valid. """ # 2015-01 reactivating header templates #log.warning('enable_fundamental_type_wrappers deprecated - replac...
[ "def", "enable_fundamental_type_wrappers", "(", "self", ")", ":", "# 2015-01 reactivating header templates", "#log.warning('enable_fundamental_type_wrappers deprecated - replaced by generate_headers')", "# return # FIXME ignore", "self", ".", "enable_fundamental_type_wrappers", "=", "lambd...
44.222222
15.666667
def check_parent_object_permissions(self, request, obj): """ Check if the request should be permitted for a given parent object. Raises an appropriate exception if the request is not permitted. """ for permission in self.get_parent_permissions(): if not permission.has...
[ "def", "check_parent_object_permissions", "(", "self", ",", "request", ",", "obj", ")", ":", "for", "permission", "in", "self", ".", "get_parent_permissions", "(", ")", ":", "if", "not", "permission", ".", "has_object_permission", "(", "request", ",", "self", ...
50
17.25
def __read(self): """ Reads packets from the socket """ # Set the socket as non-blocking self._socket.setblocking(0) while not self._stop_event.is_set(): # Watch for content ready = select.select([self._socket], [], [], 1) if ready[0]:...
[ "def", "__read", "(", "self", ")", ":", "# Set the socket as non-blocking", "self", ".", "_socket", ".", "setblocking", "(", "0", ")", "while", "not", "self", ".", "_stop_event", ".", "is_set", "(", ")", ":", "# Watch for content", "ready", "=", "select", "....
34.941176
12.941176
def is_changed(): """ Checks if current project has any noncommited changes. """ executed, changed_lines = execute_git('status --porcelain', output=False) merge_not_finished = mod_path.exists('.git/MERGE_HEAD') return changed_lines.strip() or merge_not_finished
[ "def", "is_changed", "(", ")", ":", "executed", ",", "changed_lines", "=", "execute_git", "(", "'status --porcelain'", ",", "output", "=", "False", ")", "merge_not_finished", "=", "mod_path", ".", "exists", "(", "'.git/MERGE_HEAD'", ")", "return", "changed_lines",...
54.6
18.6
def run_winexe_command(cmd, args, host, username, password, port=445): ''' Run a command remotly via the winexe executable ''' creds = "-U '{0}%{1}' //{2}".format( username, password, host ) logging_creds = "-U '{0}%XXX-REDACTED-XXX' //{1}".format( username, ...
[ "def", "run_winexe_command", "(", "cmd", ",", "args", ",", "host", ",", "username", ",", "password", ",", "port", "=", "445", ")", ":", "creds", "=", "\"-U '{0}%{1}' //{2}\"", ".", "format", "(", "username", ",", "password", ",", "host", ")", "logging_cred...
31.1875
23.8125
def from_string(string): """ Reads a string representation to a Cssr object. Args: string (str): A string representation of a CSSR. Returns: Cssr object. """ lines = string.split("\n") toks = lines[0].split() lengths = [float(i) f...
[ "def", "from_string", "(", "string", ")", ":", "lines", "=", "string", ".", "split", "(", "\"\\n\"", ")", "toks", "=", "lines", "[", "0", "]", ".", "split", "(", ")", "lengths", "=", "[", "float", "(", "i", ")", "for", "i", "in", "toks", "]", "...
31.615385
17
def infix_filename(self, name, default, infix, ext=None): """Unless *name* is provided, insert *infix* before the extension *ext* of *default*.""" if name is None: p, oldext = os.path.splitext(default) if ext is None: ext = oldext if ext.startswith(os....
[ "def", "infix_filename", "(", "self", ",", "name", ",", "default", ",", "infix", ",", "ext", "=", "None", ")", ":", "if", "name", "is", "None", ":", "p", ",", "oldext", "=", "os", ".", "path", ".", "splitext", "(", "default", ")", "if", "ext", "i...
42
11
def has_vary_header(response, header_query): """ Checks to see if the response has a given header name in its Vary header. """ if not response.has_header('Vary'): return False vary_headers = cc_delim_re.split(response['Vary']) existing_headers = set([header.lower() for header in vary_hea...
[ "def", "has_vary_header", "(", "response", ",", "header_query", ")", ":", "if", "not", "response", ".", "has_header", "(", "'Vary'", ")", ":", "return", "False", "vary_headers", "=", "cc_delim_re", ".", "split", "(", "response", "[", "'Vary'", "]", ")", "e...
41.111111
13.111111
def _add_row(self, index): """ Add a new row to the DataFrame :param index: index of the new row :return: nothing """ self._index.append(index) for c, _ in enumerate(self._columns): self._data[c].append(None)
[ "def", "_add_row", "(", "self", ",", "index", ")", ":", "self", ".", "_index", ".", "append", "(", "index", ")", "for", "c", ",", "_", "in", "enumerate", "(", "self", ".", "_columns", ")", ":", "self", ".", "_data", "[", "c", "]", ".", "append", ...
26.8
8.8
def get_signatures(self, limit=100, offset=0, conditions={}): """ Get all signatures """ url = self.SIGNS_URL + "?limit=%s&offset=%s" % (limit, offset) for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += ...
[ "def", "get_signatures", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "conditions", "=", "{", "}", ")", ":", "url", "=", "self", ".", "SIGNS_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "for", "...
28.9375
16.0625
def exists(zpool): ''' Check if a ZFS storage pool is active zpool : string Name of storage pool CLI Example: .. code-block:: bash salt '*' zpool.exists myzpool ''' # list for zpool # NOTE: retcode > 0 if zpool does not exists res = __salt__['cmd.run_all']( ...
[ "def", "exists", "(", "zpool", ")", ":", "# list for zpool", "# NOTE: retcode > 0 if zpool does not exists", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "__utils__", "[", "'zfs.zpool_command'", "]", "(", "command", "=", "'list'", ",", "target", "=", "z...
18.807692
21.884615
def create_port(context, port): """Create a port Create a port which is a connection point of a device (e.g., a VM NIC) to attach to a L2 Neutron network. : param context: neutron api request context : param port: dictionary describing the port, with keys as listed in the RESOURCE_ATTRIBUTE...
[ "def", "create_port", "(", "context", ",", "port", ")", ":", "LOG", ".", "info", "(", "\"create_port for tenant %s\"", "%", "context", ".", "tenant_id", ")", "port_attrs", "=", "port", "[", "\"port\"", "]", "admin_only", "=", "[", "\"mac_address\"", ",", "\"...
41.936364
19.85
def persist(self: T, **kwargs) -> T: """ Trigger computation, keeping data as dask arrays This operation can be used to trigger computation on underlying dask arrays, similar to ``.compute()``. However this operation keeps the data as dask arrays. This is particularly useful when usin...
[ "def", "persist", "(", "self", ":", "T", ",", "*", "*", "kwargs", ")", "->", "T", ":", "new", "=", "self", ".", "copy", "(", "deep", "=", "False", ")", "return", "new", ".", "_persist_inplace", "(", "*", "*", "kwargs", ")" ]
35.15
22.2
def merge_and_fit(self, segment): """ Merges another segment with this one, ordering the points based on a distance heuristic Args: segment (:obj:`Segment`): Segment to merge with Returns: :obj:`Segment`: self """ self.points = sort_segment_po...
[ "def", "merge_and_fit", "(", "self", ",", "segment", ")", ":", "self", ".", "points", "=", "sort_segment_points", "(", "self", ".", "points", ",", "segment", ".", "points", ")", "return", "self" ]
33
16.909091
def _group_similar(items: List[T], comparer: Callable[[T, T], bool]) -> List[List[T]]: """Combines similar items into groups. Args: items: The list of items to group. comparer: Determines if two items are similar. Returns: A list of groups of items. """ groups = [] # type...
[ "def", "_group_similar", "(", "items", ":", "List", "[", "T", "]", ",", "comparer", ":", "Callable", "[", "[", "T", ",", "T", "]", ",", "bool", "]", ")", "->", "List", "[", "List", "[", "T", "]", "]", ":", "groups", "=", "[", "]", "# type: List...
30.818182
14.409091
def validate_yaml(yaml_in, yaml_fn): """Check with yamllint the yaml syntaxes Looking for duplicate keys.""" try: import yamllint.linter as linter from yamllint.config import YamlLintConfig except ImportError: return conf = """{"extends": "relaxed", "rules": {"...
[ "def", "validate_yaml", "(", "yaml_in", ",", "yaml_fn", ")", ":", "try", ":", "import", "yamllint", ".", "linter", "as", "linter", "from", "yamllint", ".", "config", "import", "YamlLintConfig", "except", "ImportError", ":", "return", "conf", "=", "\"\"\"{\"ext...
46.56
17.72
def snapshot_present(name, recursive=False, properties=None): ''' ensure snapshot exists and has properties set name : string name of snapshot recursive : boolean recursively create snapshots of all descendent datasets properties : dict additional zfs properties (-o) .....
[ "def", "snapshot_present", "(", "name", ",", "recursive", "=", "False", ",", "properties", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}",...
31.915254
20.79661
def add(self, child, min_occurs=1): """Add a child node. @param child: The schema for the child node. @param min_occurs: The minimum number of times the child node must occur, if C{None} is given the default is 1. """ if not min_occurs in (0, 1): raise Ru...
[ "def", "add", "(", "self", ",", "child", ",", "min_occurs", "=", "1", ")", ":", "if", "not", "min_occurs", "in", "(", "0", ",", "1", ")", ":", "raise", "RuntimeError", "(", "\"Unexpected min bound for node schema\"", ")", "self", ".", "children", "[", "c...
39.833333
14.75
def beforeContext(self): """Copy sys.modules onto my mod stack """ mods = sys.modules.copy() self._mod_stack.append(mods)
[ "def", "beforeContext", "(", "self", ")", ":", "mods", "=", "sys", ".", "modules", ".", "copy", "(", ")", "self", ".", "_mod_stack", ".", "append", "(", "mods", ")" ]
29.8
5.4
def get_instance(self, payload): """ Build an instance of TaskQueueStatisticsInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsInstance :rtype: twilio.rest.taskrouter.v1....
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "TaskQueueStatisticsInstance", "(", "self", ".", "_version", ",", "payload", ",", "workspace_sid", "=", "self", ".", "_solution", "[", "'workspace_sid'", "]", ",", "task_queue_sid", "=", "...
40.666667
24.933333
def get_account_by_b58_address(self, b58_address: str, password: str) -> Account: """ :param b58_address: a base58 encode address. :param password: a password which is used to decrypt the encrypted private key. :return: """ acct = self.get_account_data_by_b58_address(b58_...
[ "def", "get_account_by_b58_address", "(", "self", ",", "b58_address", ":", "str", ",", "password", ":", "str", ")", "->", "Account", ":", "acct", "=", "self", ".", "get_account_data_by_b58_address", "(", "b58_address", ")", "n", "=", "self", ".", "wallet_in_me...
51.181818
21
def fit_overlays(self, text, run_matchers=None, **kw): """ First all matchers will run and then I will try to combine them. Use run_matchers to force running(True) or not running(False) the matchers. See ListMatcher for arguments. """ self._maybe_run_matchers(tex...
[ "def", "fit_overlays", "(", "self", ",", "text", ",", "run_matchers", "=", "None", ",", "*", "*", "kw", ")", ":", "self", ".", "_maybe_run_matchers", "(", "text", ",", "run_matchers", ")", "for", "i", "in", "self", ".", "_list_match", ".", "fit_overlay",...
36.818182
14.272727
def connect_autoscale(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.ec2.autosc...
[ "def", "connect_autoscale", "(", "aws_access_key_id", "=", "None", ",", "aws_secret_access_key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "boto", ".", "ec2", ".", "autoscale", "import", "AutoScaleConnection", "return", "AutoScaleConnection", "(", ...
41.307692
19.615385
def smart_clip(layer_to_clip, mask_layer): """Smart clip a vector layer with another. Issue https://github.com/inasafe/inasafe/issues/3186 :param layer_to_clip: The vector layer to clip. :type layer_to_clip: QgsVectorLayer :param mask_layer: The vector layer to use for clipping. :type mask_la...
[ "def", "smart_clip", "(", "layer_to_clip", ",", "mask_layer", ")", ":", "output_layer_name", "=", "smart_clip_steps", "[", "'output_layer_name'", "]", "writer", "=", "create_memory_layer", "(", "output_layer_name", ",", "layer_to_clip", ".", "geometryType", "(", ")", ...
30.075472
19.037736
def _execute(self, native, command, data=None, returning=True, mapper=dict): """ Executes the inputted command into the current \ connection cursor. :param command | <str> ...
[ "def", "_execute", "(", "self", ",", "native", ",", "command", ",", "data", "=", "None", ",", "returning", "=", "True", ",", "mapper", "=", "dict", ")", ":", "if", "data", "is", "None", ":", "data", "=", "{", "}", "# check to make sure the connection has...
35.036036
18.963964
def next_frame_savp_vae(): """SAVP - VAE only model.""" hparams = next_frame_savp() hparams.use_vae = True hparams.use_gan = False hparams.latent_loss_multiplier = 1e-3 hparams.latent_loss_multiplier_schedule = "linear_anneal" return hparams
[ "def", "next_frame_savp_vae", "(", ")", ":", "hparams", "=", "next_frame_savp", "(", ")", "hparams", ".", "use_vae", "=", "True", "hparams", ".", "use_gan", "=", "False", "hparams", ".", "latent_loss_multiplier", "=", "1e-3", "hparams", ".", "latent_loss_multipl...
31
12.5
def set_status(self, status, origin=None, force=False): """ Compatibility to actuator class. Also :class:`~automate.callables.builtin_callables.SetStatus` callable can be used for sensors too, if so desired. """ if status != self.default: self._se...
[ "def", "set_status", "(", "self", ",", "status", ",", "origin", "=", "None", ",", "force", "=", "False", ")", ":", "if", "status", "!=", "self", ".", "default", ":", "self", ".", "_setup_reset_delay", "(", ")", "if", "self", ".", "status_filter", ":", ...
32.714286
16.714286
def load_airpassengers(as_series=False): """Monthly airline passengers. The classic Box & Jenkins airline data. Monthly totals of international airline passengers, 1949 to 1960. Parameters ---------- as_series : bool, optional (default=False) Whether to return a Pandas series. If False...
[ "def", "load_airpassengers", "(", "as_series", "=", "False", ")", ":", "rslt", "=", "np", ".", "array", "(", "[", "112", ",", "118", ",", "132", ",", "129", ",", "121", ",", "135", ",", "148", ",", "148", ",", "136", ",", "119", ",", "104", ","...
38.055556
24.680556
def compress(string, mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0): """Compress a byte string. Args: string (bytes): The input data. mode (int, optional): The compression mode can be MODE_GENERIC (default), MODE_TEXT (for UTF-8 format text input) or MODE_FONT (for WOFF 2.0). qua...
[ "def", "compress", "(", "string", ",", "mode", "=", "MODE_GENERIC", ",", "quality", "=", "11", ",", "lgwin", "=", "22", ",", "lgblock", "=", "0", ")", ":", "compressor", "=", "Compressor", "(", "mode", "=", "mode", ",", "quality", "=", "quality", ","...
43.96
24.16
def syncdb(args): """Update the database with model schema. Shorthand for `paver manage syncdb`. """ cmd = args and 'syncdb %s' % ' '.join(options.args) or 'syncdb --noinput' call_manage(cmd) for fixture in options.paved.django.syncdb.fixtures: call_manage("loaddata %s" % fixture)
[ "def", "syncdb", "(", "args", ")", ":", "cmd", "=", "args", "and", "'syncdb %s'", "%", "' '", ".", "join", "(", "options", ".", "args", ")", "or", "'syncdb --noinput'", "call_manage", "(", "cmd", ")", "for", "fixture", "in", "options", ".", "paved", "....
43.285714
14.285714
def check_name(name): """ Verify the name is well-formed >>> check_name(123) False >>> check_name('') False >>> check_name('abc') False >>> check_name('abc.def') True >>> check_name('abc.def.ghi') False >>> check_name('abc.d-ef') True >>> check_name('abc.d+ef...
[ "def", "check_name", "(", "name", ")", ":", "if", "type", "(", "name", ")", "not", "in", "[", "str", ",", "unicode", "]", ":", "return", "False", "if", "not", "is_name_valid", "(", "name", ")", ":", "return", "False", "return", "True" ]
19.558824
21.441176
def indexFromCoordinates(coordinates, dimensions): """ Translate coordinates into an index, using the given coordinate system. Similar to ``numpy.ravel_multi_index``. :param coordinates: (list of ints) A list of coordinates of length ``dimensions.size()``. :param dimensions: (list of ints) The co...
[ "def", "indexFromCoordinates", "(", "coordinates", ",", "dimensions", ")", ":", "index", "=", "0", "for", "i", ",", "dimension", "in", "enumerate", "(", "dimensions", ")", ":", "index", "*=", "dimension", "index", "+=", "coordinates", "[", "i", "]", "retur...
32.181818
23
def auth_approle(self, role_id, secret_id=None, mount_point='approle', use_token=True): """POST /auth/<mount_point>/login :param role_id: :type role_id: :param secret_id: :type secret_id: :param mount_point: :type mount_point: :param use_token: :t...
[ "def", "auth_approle", "(", "self", ",", "role_id", ",", "secret_id", "=", "None", ",", "mount_point", "=", "'approle'", ",", "use_token", "=", "True", ")", ":", "params", "=", "{", "'role_id'", ":", "role_id", "}", "if", "secret_id", "is", "not", "None"...
28.571429
20.666667
def _ensure_package_loaded(path, component): """Ensure that the given module is loaded as a submodule. Returns: str: The name that the module should be imported as. """ logger = logging.getLogger(__name__) packages = component.find_products('support_package') if len(packages) == 0: ...
[ "def", "_ensure_package_loaded", "(", "path", ",", "component", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "packages", "=", "component", ".", "find_products", "(", "'support_package'", ")", "if", "len", "(", "packages", ")", ...
42.102564
25.74359
def set_output(self, state): """Sets whether the function generator is outputting a voltage.""" if state: self.instr.write('OUTP ON') else: self.instr.write('OUTP OFF')
[ "def", "set_output", "(", "self", ",", "state", ")", ":", "if", "state", ":", "self", ".", "instr", ".", "write", "(", "'OUTP ON'", ")", "else", ":", "self", ".", "instr", ".", "write", "(", "'OUTP OFF'", ")" ]
35.166667
10.5
def new_user(yaml_path): ''' Return the consumer and oauth tokens with three-legged OAuth process and save in a yaml file in the user's home directory. ''' print 'Retrieve API Key from https://www.shirts.io/accounts/api_console/' api_key = raw_input('Shirts.io API Key: ') tokens = { ...
[ "def", "new_user", "(", "yaml_path", ")", ":", "print", "'Retrieve API Key from https://www.shirts.io/accounts/api_console/'", "api_key", "=", "raw_input", "(", "'Shirts.io API Key: '", ")", "tokens", "=", "{", "'api_key'", ":", "api_key", ",", "}", "yaml_file", "=", ...
25.166667
25.277778
def path_iter(self, include_self=True): """Yields back the path from this node to the root node.""" if include_self: node = self else: node = self.parent while node is not None: yield node node = node.parent
[ "def", "path_iter", "(", "self", ",", "include_self", "=", "True", ")", ":", "if", "include_self", ":", "node", "=", "self", "else", ":", "node", "=", "self", ".", "parent", "while", "node", "is", "not", "None", ":", "yield", "node", "node", "=", "no...
31
12
def _check_states_enum(cls): """Check if states enum exists and is proper one.""" states_enum_name = cls.context.get_config('states_enum_name') try: cls.context['states_enum'] = getattr( cls.context.new_class, states_enum_name) except AttributeError: ...
[ "def", "_check_states_enum", "(", "cls", ")", ":", "states_enum_name", "=", "cls", ".", "context", ".", "get_config", "(", "'states_enum_name'", ")", "try", ":", "cls", ".", "context", "[", "'states_enum'", "]", "=", "getattr", "(", "cls", ".", "context", ...
34.631579
19.368421
def extract_user_id(self, request): """ Extract a user id from a request object. """ payload = self.extract_payload(request) user_id_attribute = self.config.user_id() return payload.get(user_id_attribute, None)
[ "def", "extract_user_id", "(", "self", ",", "request", ")", ":", "payload", "=", "self", ".", "extract_payload", "(", "request", ")", "user_id_attribute", "=", "self", ".", "config", ".", "user_id", "(", ")", "return", "payload", ".", "get", "(", "user_id_...
36
5.714286
def ParseMessagesRow(self, parser_mediator, query, row, **unused_kwargs): """Parses an Messages row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.R...
[ "def", "ParseMessagesRow", "(", "self", ",", "parser_mediator", ",", "query", ",", "row", ",", "*", "*", "unused_kwargs", ")", ":", "query_hash", "=", "hash", "(", "query", ")", "event_data", "=", "HangoutsMessageData", "(", ")", "event_data", ".", "sender",...
41.884615
22
def eval_objfn(self): r"""Compute components of objective function as well as total contribution to objective function. The objective function is :math:`\| \mathbf{x} \|_1` and the constraint violation measure is :math:`P(\mathbf{x}) - \mathbf{x}` where :math:`P(\mathbf{x})` is ...
[ "def", "eval_objfn", "(", "self", ")", ":", "obj", "=", "np", ".", "linalg", ".", "norm", "(", "(", "self", ".", "wl1", "*", "self", ".", "obfn_g0var", "(", ")", ")", ".", "ravel", "(", ")", ",", "1", ")", "cns", "=", "np", ".", "linalg", "."...
43.142857
19.142857
def convert_python_regex_to_ecma(value, flags=[]): """Convert Python regex to ECMA 262 regex. If given value is already ECMA regex it will be returned unchanged. :param string value: Python regex. :param list flags: List of flags (allowed flags: `re.I`, `re.M`) :return: ECMA 262 regex :rtype: ...
[ "def", "convert_python_regex_to_ecma", "(", "value", ",", "flags", "=", "[", "]", ")", ":", "if", "is_ecma_regex", "(", "value", ")", ":", "return", "value", "result_flags", "=", "[", "PYTHON_TO_ECMA_FLAGS", "[", "f", "]", "for", "f", "in", "flags", "]", ...
29.888889
21.611111
def _get_actual_reset_type(self, reset_type): """! @brief Determine the reset type to use given defaults and passed in type.""" # Default to reset_type session option if reset_type parameter is None. If the session # option isn't set, then use the core's default reset type. if r...
[ "def", "_get_actual_reset_type", "(", "self", ",", "reset_type", ")", ":", "# Default to reset_type session option if reset_type parameter is None. If the session", "# option isn't set, then use the core's default reset type.", "if", "reset_type", "is", "None", ":", "if", "'reset_typ...
49.354839
23.83871
def _get_things(self, method, thing, thing_type, params=None, cacheable=True): """Returns a list of the most played thing_types by this thing.""" limit = params.get("limit", 1) seq = [] for node in _collect_nodes( limit, self, self.ws_prefix + "." + method, cacheable, params...
[ "def", "_get_things", "(", "self", ",", "method", ",", "thing", ",", "thing_type", ",", "params", "=", "None", ",", "cacheable", "=", "True", ")", ":", "limit", "=", "params", ".", "get", "(", "\"limit\"", ",", "1", ")", "seq", "=", "[", "]", "for"...
38.2
23
def whitelisted(argument=None): """Decorates a method requiring that the requesting IP address is whitelisted. Requires a whitelist value as a list in the Application.settings dictionary. IP addresses can be an individual IP address or a subnet. Examples: ['10.0.0.0/8','192.168.1.0/24', '1....
[ "def", "whitelisted", "(", "argument", "=", "None", ")", ":", "def", "is_whitelisted", "(", "remote_ip", ",", "whitelist", ")", ":", "\"\"\"Check to see if an IP address is whitelisted.\n\n :param str ip_address: The IP address to check\n :param list whitelist: The whit...
32.535354
20.232323
def delete_if_exists(self, **kwargs): """ Deletes an object if it exists in database according to given query parameters and returns True otherwise does nothing and returns False. Args: **kwargs: query parameters Returns(bool): True or False """ ...
[ "def", "delete_if_exists", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "get", "(", "*", "*", "kwargs", ")", ".", "blocking_delete", "(", ")", "return", "True", "except", "ObjectDoesNotExist", ":", "return", "False" ]
28.0625
18.4375
def import_model(self, source): """Import and return model instance.""" source = self._resolve_source(source) self._context = FilePathContext(source) with self._context.open() as f: self._reader = self._open_reader(f) return self._reader.create_model()
[ "def", "import_model", "(", "self", ",", "source", ")", ":", "source", "=", "self", ".", "_resolve_source", "(", "source", ")", "self", ".", "_context", "=", "FilePathContext", "(", "source", ")", "with", "self", ".", "_context", ".", "open", "(", ")", ...
37.25
8.875
def post_commit_hook(argv): """Hook: for checking commit message.""" _, stdout, _ = run("git log -1 --format=%B HEAD") message = "\n".join(stdout) options = {"allow_empty": True} if not _check_message(message, options): click.echo( "Commit message errors (fix with 'git commit --...
[ "def", "post_commit_hook", "(", "argv", ")", ":", "_", ",", "stdout", ",", "_", "=", "run", "(", "\"git log -1 --format=%B HEAD\"", ")", "message", "=", "\"\\n\"", ".", "join", "(", "stdout", ")", "options", "=", "{", "\"allow_empty\"", ":", "True", "}", ...
34.166667
15.166667
def get_manager_state(drop_defaults=False, widgets=None): """Returns the full state for a widget manager for embedding :param drop_defaults: when True, it will not include default value :param widgets: list with widgets to include in the state (or all widgets when None) :return: ...
[ "def", "get_manager_state", "(", "drop_defaults", "=", "False", ",", "widgets", "=", "None", ")", ":", "state", "=", "{", "}", "if", "widgets", "is", "None", ":", "widgets", "=", "Widget", ".", "widgets", ".", "values", "(", ")", "for", "widget", "in",...
46
22.846154
def start_workflow_execution(domain=None, workflowId=None, workflowType=None, taskList=None, taskPriority=None, input=None, executionStartToCloseTimeout=None, tagList=None, taskStartToCloseTimeout=None, childPolicy=None, lambdaRole=None): """ Starts an execution of the workflow type in the specified domain usin...
[ "def", "start_workflow_execution", "(", "domain", "=", "None", ",", "workflowId", "=", "None", ",", "workflowType", "=", "None", ",", "taskList", "=", "None", ",", "taskPriority", "=", "None", ",", "input", "=", "None", ",", "executionStartToCloseTimeout", "="...
72.910995
68.041885
def rmR(kls, path): """`rm -R path`. Deletes, but does not recurse into, symlinks. If the path does not exist, silently return.""" if os.path.islink(path) or os.path.isfile(path): os.unlink(path) elif os.path.isdir(path): walker = os.walk(path, topdown=False, followlinks=False) for dirpath, dirnames,...
[ "def", "rmR", "(", "kls", ",", "path", ")", ":", "if", "os", ".", "path", ".", "islink", "(", "path", ")", "or", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "os", ".", "unlink", "(", "path", ")", "elif", "os", ".", "path", ".", ...
36.615385
11.615385
def checkpoint(self, tasks=None): """Checkpoint the dfk incrementally to a checkpoint file. When called, every task that has been completed yet not checkpointed is checkpointed to a file. Kwargs: - tasks (List of task ids) : List of task ids to checkpoint. Default=None ...
[ "def", "checkpoint", "(", "self", ",", "tasks", "=", "None", ")", ":", "with", "self", ".", "checkpoint_lock", ":", "checkpoint_queue", "=", "None", "if", "tasks", ":", "checkpoint_queue", "=", "tasks", "else", ":", "checkpoint_queue", "=", "self", ".", "t...
41.207317
21.304878
def load_async(self, source, mode='create', source_format='csv', csv_options=None, ignore_unknown_values=False, max_bad_records=0): """ Starts importing a table from GCS and return a Future. Args: source: the URL of the source objects(s). Can include a wildcard '*' at the end of the item...
[ "def", "load_async", "(", "self", ",", "source", ",", "mode", "=", "'create'", ",", "source_format", "=", "'csv'", ",", "csv_options", "=", "None", ",", "ignore_unknown_values", "=", "False", ",", "max_bad_records", "=", "0", ")", ":", "if", "source_format",...
54.557692
31.5
def gpg_profile_get_key( blockchain_id, keyname, key_id=None, proxy=None, wallet_keys=None, config_dir=None, gpghome=None ): """ Get the profile key Return {'status': True, 'key_data': ..., 'key_id': ...} on success Return {'error': ...} on error """ assert is_valid_keyname( keyname ) i...
[ "def", "gpg_profile_get_key", "(", "blockchain_id", ",", "keyname", ",", "key_id", "=", "None", ",", "proxy", "=", "None", ",", "wallet_keys", "=", "None", ",", "config_dir", "=", "None", ",", "gpghome", "=", "None", ")", ":", "assert", "is_valid_keyname", ...
33.040816
25.367347
def delete_volume(self, datacenter_id, volume_id): """ Removes a volume from the data center. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param volume_id: The unique ID of the volume. :type volume_id: ``str...
[ "def", "delete_volume", "(", "self", ",", "datacenter_id", ",", "volume_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/volumes/%s'", "%", "(", "datacenter_id", ",", "volume_id", ")", ",", "method", "=", "'DE...
31
17
def __convert(root, tag, values, func): """Converts the tag type found in the root and converts them using the func and appends them to the values. """ elements = root.getElementsByTagName(tag) for element in elements: converted = func(element) # Append to the list __append...
[ "def", "__convert", "(", "root", ",", "tag", ",", "values", ",", "func", ")", ":", "elements", "=", "root", ".", "getElementsByTagName", "(", "tag", ")", "for", "element", "in", "elements", ":", "converted", "=", "func", "(", "element", ")", "# Append to...
30.363636
11.090909
def filter(objects, Type=None, min=-1, max=-1): #PYCHOK muppy filter """Filter objects. The filter can be by type, minimum size, and/or maximum size. Keyword arguments: Type -- object type to filter by min -- minimum object size max -- maximum object size """ res = [] if min > max...
[ "def", "filter", "(", "objects", ",", "Type", "=", "None", ",", "min", "=", "-", "1", ",", "max", "=", "-", "1", ")", ":", "#PYCHOK muppy filter", "res", "=", "[", "]", "if", "min", ">", "max", ":", "raise", "ValueError", "(", "\"minimum must be smal...
28.857143
20.142857
def mlt2mlon(self, mlt, datetime, ssheight=50*6371): """Computes the magnetic longitude at the specified magnetic local time and UT. Parameters ========== mlt : array_like Magnetic local time datetime : :class:`datetime.datetime` Date and time ...
[ "def", "mlt2mlon", "(", "self", ",", "mlt", ",", "datetime", ",", "ssheight", "=", "50", "*", "6371", ")", ":", "ssglat", ",", "ssglon", "=", "helpers", ".", "subsol", "(", "datetime", ")", "ssalat", ",", "ssalon", "=", "self", ".", "geo2apex", "(", ...
38.6
23.628571
def from_corpus(cls, corpus): """ Create a new modifiable corpus from any other CorpusView. This for example can be used to create a independent modifiable corpus from a subview. Args: corpus (CorpusView): The corpus to create a copy from. Returns: Corpu...
[ "def", "from_corpus", "(", "cls", ",", "corpus", ")", ":", "ds", "=", "Corpus", "(", ")", "# Tracks", "tracks", "=", "copy", ".", "deepcopy", "(", "list", "(", "corpus", ".", "tracks", ".", "values", "(", ")", ")", ")", "track_mapping", "=", "ds", ...
33.761905
25.238095
def get_patient_bams(job, patient_dict, sample_type, univ_options, bwa_options, mutect_options): """ Convenience function to return the bam and its index in the correct format for a sample type. :param dict patient_dict: dict of patient info :param str sample_type: 'tumor_rna', 'tumor_dna', 'normal_dna...
[ "def", "get_patient_bams", "(", "job", ",", "patient_dict", ",", "sample_type", ",", "univ_options", ",", "bwa_options", ",", "mutect_options", ")", ":", "output_dict", "=", "{", "}", "if", "'dna'", "in", "sample_type", ":", "sample_info", "=", "'fix_pg_sorted'"...
51
23.47619
def build_full_toctree(builder, docname, prune, collapse): """Return a single toctree starting from docname containing all sub-document doctrees. """ env = builder.env doctree = env.get_doctree(env.config.master_doc) toctrees = [] for toctreenode in doctree.traverse(addnodes.toctree): ...
[ "def", "build_full_toctree", "(", "builder", ",", "docname", ",", "prune", ",", "collapse", ")", ":", "env", "=", "builder", ".", "env", "doctree", "=", "env", ".", "get_doctree", "(", "env", ".", "config", ".", "master_doc", ")", "toctrees", "=", "[", ...
37
13.857143
def merge_dicts(src, patch): """Merge contents of dict `patch` into `src`.""" for key in patch: if key in src: if isinstance(src[key], dict) and isinstance(patch[key], dict): merge_dicts(src[key], patch[key]) else: src[key] = merge_values(src[key],...
[ "def", "merge_dicts", "(", "src", ",", "patch", ")", ":", "for", "key", "in", "patch", ":", "if", "key", "in", "src", ":", "if", "isinstance", "(", "src", "[", "key", "]", ",", "dict", ")", "and", "isinstance", "(", "patch", "[", "key", "]", ",",...
32.083333
19.75
def get_config(self, code_dir, project_dir): """ Finds a configuration by looking for a manifest in the given directories. Returns ------- samcli.lib.build.workflow_config.CONFIG A supported configuration if one is found Raises ------ ValueEr...
[ "def", "get_config", "(", "self", ",", "code_dir", ",", "project_dir", ")", ":", "# Search for manifest first in code directory and then in the project directory.", "# Search order is important here because we want to prefer the manifest present within the code directory over", "# a manifest...
40.103448
28.448276
def run(self): """Starts cleaning cache in infinite loop. """ logger.info("Starting daemon.") while True: try: self._scan_disk() do_cleaning, delete_from_index = self._analyze_file_index() if do_cleaning: sel...
[ "def", "run", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Starting daemon.\"", ")", "while", "True", ":", "try", ":", "self", ".", "_scan_disk", "(", ")", "do_cleaning", ",", "delete_from_index", "=", "self", ".", "_analyze_file_index", "(", ")",...
42.666667
17.133333
def _load_metadata(self): """Load metadata from the archive file""" logger.debug("Loading metadata infomation of archive %s", self.archive_path) cursor = self._db.cursor() select_stmt = "SELECT origin, backend_name, backend_version, " \ "category, backend_params, ...
[ "def", "_load_metadata", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Loading metadata infomation of archive %s\"", ",", "self", ".", "archive_path", ")", "cursor", "=", "self", ".", "_db", ".", "cursor", "(", ")", "select_stmt", "=", "\"SELECT origin,...
37.44
20.28
def _resize_image_if_necessary(image_fobj, target_pixels=None): """Resize an image to have (roughly) the given number of target pixels. Args: image_fobj: File object containing the original image. target_pixels: If given, number of pixels that the image must have. Returns: A file object. """ if ...
[ "def", "_resize_image_if_necessary", "(", "image_fobj", ",", "target_pixels", "=", "None", ")", ":", "if", "target_pixels", "is", "None", ":", "return", "image_fobj", "cv2", "=", "tfds", ".", "core", ".", "lazy_imports", ".", "cv2", "# Decode image using OpenCV2."...
35.807692
19.192308
def _parse_fields(self, *args, **kwargs): """ Deprecated. This will be removed in a future release. """ from warnings import warn warn('Whois._parse_fields() has been deprecated and will be ' 'removed. You should now use Whois.parse_fields().') return self.p...
[ "def", "_parse_fields", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "warnings", "import", "warn", "warn", "(", "'Whois._parse_fields() has been deprecated and will be '", "'removed. You should now use Whois.parse_fields().'", ")", "return", ...
37.777778
14.666667
def delete(self): """Remove this resource or collection (recursive). See DAVResource.delete() """ if self.provider.readonly: raise DAVError(HTTP_FORBIDDEN) os.unlink(self._file_path) self.remove_all_properties(True) self.remove_all_locks(True)
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "provider", ".", "readonly", ":", "raise", "DAVError", "(", "HTTP_FORBIDDEN", ")", "os", ".", "unlink", "(", "self", ".", "_file_path", ")", "self", ".", "remove_all_properties", "(", "True", ")"...
30.3
9
def update_configs(self, config): """ Gather configuration requirements of all plugins """ for what in self.plugins: # backend, repo etc. for key in self.plugins[what]: # s3, filesystem etc. # print("Updating configuration of", what, key) self...
[ "def", "update_configs", "(", "self", ",", "config", ")", ":", "for", "what", "in", "self", ".", "plugins", ":", "# backend, repo etc.", "for", "key", "in", "self", ".", "plugins", "[", "what", "]", ":", "# s3, filesystem etc.", "# print(\"Updating configuration...
42.222222
16
def triangulate_polygon(polygon, triangle_args='pq30', engine='auto', **kwargs): """ Given a shapely polygon create a triangulation using one of the python interfaces to triangle.c: > pip install meshpy > pip install triangle ...
[ "def", "triangulate_polygon", "(", "polygon", ",", "triangle_args", "=", "'pq30'", ",", "engine", "=", "'auto'", ",", "*", "*", "kwargs", ")", ":", "# turn the polygon in to vertices, segments, and hole points", "arg", "=", "_polygon_to_kwargs", "(", "polygon", ")", ...
34.103896
13.74026
def _initialize_tensor_name_to_ids(self): """Initializer for _tensor_name_to_ids. Returns: a {string: (int, int)}, mapping the name of tensor T to the index of T's operation in _operations and T's index in T's operation's outputs. """ tensor_name_to_ids = {} for i, operation in enum...
[ "def", "_initialize_tensor_name_to_ids", "(", "self", ")", ":", "tensor_name_to_ids", "=", "{", "}", "for", "i", ",", "operation", "in", "enumerate", "(", "self", ".", "_operations", ")", ":", "for", "j", ",", "tensor", "in", "enumerate", "(", "operation", ...
38.75
16.583333
def set_body_states(self, states): '''Set the states of some bodies in the world. Parameters ---------- states : sequence of states A complete state tuple for one or more bodies in the world. See :func:`get_body_states`. ''' for state in states: ...
[ "def", "set_body_states", "(", "self", ",", "states", ")", ":", "for", "state", "in", "states", ":", "self", ".", "get_body", "(", "state", ".", "name", ")", ".", "state", "=", "state" ]
32.727273
18.181818
def get_person_by_employee_id(self, employee_id): """ Returns a restclients.Person object for the given employee id. If the employee id isn't found, or if there is an error communicating with the PWS, a DataFailureException will be thrown. """ if not self.valid_employee_...
[ "def", "get_person_by_employee_id", "(", "self", ",", "employee_id", ")", ":", "if", "not", "self", ".", "valid_employee_id", "(", "employee_id", ")", ":", "raise", "InvalidEmployeeID", "(", "employee_id", ")", "url", "=", "\"{}.json?{}\"", ".", "format", "(", ...
41.565217
19.391304
def get_url(self, environ): """Return the base URL.""" if self.override_url: url = self.override_url else: # PEP333: wsgi.url_scheme, HTTP_HOST, SERVER_NAME, and SERVER_PORT # can be used to reconstruct a request's complete URL # Much of the follo...
[ "def", "get_url", "(", "self", ",", "environ", ")", ":", "if", "self", ".", "override_url", ":", "url", "=", "self", ".", "override_url", "else", ":", "# PEP333: wsgi.url_scheme, HTTP_HOST, SERVER_NAME, and SERVER_PORT", "# can be used to reconstruct a request's complete UR...
43.909091
17.818182
def probe_image(self, labels, instance, column_name=None, num_scaled_images=50, top_percent=10): """ Get pixel importance of the image. It performs pixel sensitivity analysis by showing only the most important pixels to a certain label in the image. It uses integrated gradie...
[ "def", "probe_image", "(", "self", ",", "labels", ",", "instance", ",", "column_name", "=", "None", ",", "num_scaled_images", "=", "50", ",", "top_percent", "=", "10", ")", ":", "if", "len", "(", "self", ".", "_image_columns", ")", ">", "1", "and", "no...
47.481481
25.345679
def _preprocess_data(self, X, Y=None, idxs=None, train=False): """ Preprocess the data: 1. Make sentence with mention into sequence data for LSTM. 2. Select subset of the input if idxs exists. :param X: The input data of the model. :type X: pair with candidates and corre...
[ "def", "_preprocess_data", "(", "self", ",", "X", ",", "Y", "=", "None", ",", "idxs", "=", "None", ",", "train", "=", "False", ")", ":", "C", ",", "F", "=", "X", "if", "Y", "is", "not", "None", ":", "Y", "=", "np", ".", "array", "(", "Y", "...
34.913978
17.903226
def on_table_row_click(self, row, item): ''' Highlight selected row(s) and put the result of a muti_row selection in the list "self.selected_row_list". ''' if not self.multi_selection_enabled: self.remove_selection() if row not in self.selected_row_lis...
[ "def", "on_table_row_click", "(", "self", ",", "row", ",", "item", ")", ":", "if", "not", "self", ".", "multi_selection_enabled", ":", "self", ".", "remove_selection", "(", ")", "if", "row", "not", "in", "self", ".", "selected_row_list", ":", "self", ".", ...
39.909091
9.181818
def load_figure(self, fig, fmt): """Set a new figure in the figure canvas.""" self.figcanvas.load_figure(fig, fmt) self.scale_image() self.figcanvas.repaint()
[ "def", "load_figure", "(", "self", ",", "fig", ",", "fmt", ")", ":", "self", ".", "figcanvas", ".", "load_figure", "(", "fig", ",", "fmt", ")", "self", ".", "scale_image", "(", ")", "self", ".", "figcanvas", ".", "repaint", "(", ")" ]
37.2
6.8
def package_repositories(self): """ Property for accessing :class:`PackageRepositoryManager` instance, which is used to manage package repos. :rtype: yagocd.resources.package_repository.PackageRepositoryManager """ if self._package_repository_manager is None: self._p...
[ "def", "package_repositories", "(", "self", ")", ":", "if", "self", ".", "_package_repository_manager", "is", "None", ":", "self", ".", "_package_repository_manager", "=", "PackageRepositoryManager", "(", "session", "=", "self", ".", "_session", ")", "return", "se...
48.333333
25.666667
def tofile(self, f): """Serialize this ScalableBloomFilter into the file-object `f'.""" f.write(pack(self.FILE_FMT, self.scale, self.ratio, self.initial_capacity, self.error_rate)) # Write #-of-filters f.write(pack(b'<l', len(self.filters))) if len(...
[ "def", "tofile", "(", "self", ",", "f", ")", ":", "f", ".", "write", "(", "pack", "(", "self", ".", "FILE_FMT", ",", "self", ".", "scale", ",", "self", ".", "ratio", ",", "self", ".", "initial_capacity", ",", "self", ".", "error_rate", ")", ")", ...
35.695652
14.608696
def interp(x, dx, dy, left=None, right=None): '''One-dimensional linear interpolation routine inspired/ reimplemented from NumPy for extra speed for scalar values (and also numpy). Returns the one-dimensional piecewise linear interpolant to a function with a given value at discrete data-points....
[ "def", "interp", "(", "x", ",", "dx", ",", "dy", ",", "left", "=", "None", ",", "right", "=", "None", ")", ":", "lendx", "=", "len", "(", "dx", ")", "j", "=", "binary_search", "(", "x", ",", "dx", ",", "lendx", ")", "if", "(", "j", "==", "-...
28.872727
22.763636
def _is_at_ref_start(self, nucmer_hit): '''Returns True iff the hit is "close enough" to the start of the reference sequence''' hit_coords = nucmer_hit.ref_coords() return hit_coords.start < self.ref_end_tolerance
[ "def", "_is_at_ref_start", "(", "self", ",", "nucmer_hit", ")", ":", "hit_coords", "=", "nucmer_hit", ".", "ref_coords", "(", ")", "return", "hit_coords", ".", "start", "<", "self", ".", "ref_end_tolerance" ]
58.5
19