text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def apply(self, func, num_splits=None, other_axis_partition=None, **kwargs): """Applies func to the object in the plasma store. See notes in Parent class about this method. Args: func: The function to apply. num_splits: The number of times to split the result object. ...
[ "def", "apply", "(", "self", ",", "func", ",", "num_splits", "=", "None", ",", "other_axis_partition", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "num_splits", "is", "None", ":", "num_splits", "=", "len", "(", "self", ".", "list_of_blocks", ...
38.848485
0.004566
def _get_at_from_session(self): """ Get the saved access token for private resources from the session. """ try: return self.request.session['oauth_%s_access_token' % get_token_prefix( self.req...
[ "def", "_get_at_from_session", "(", "self", ")", ":", "try", ":", "return", "self", ".", "request", ".", "session", "[", "'oauth_%s_access_token'", "%", "get_token_prefix", "(", "self", ".", "request_token_url", ")", "]", "except", "KeyError", ":", "raise", "O...
41.083333
0.003968
def superkey(self): """Returns a set of column names that together constitute the superkey.""" sorted_list = [] for header in self.header: if header in self._keys: sorted_list.append(header) return sorted_list
[ "def", "superkey", "(", "self", ")", ":", "sorted_list", "=", "[", "]", "for", "header", "in", "self", ".", "header", ":", "if", "header", "in", "self", ".", "_keys", ":", "sorted_list", ".", "append", "(", "header", ")", "return", "sorted_list" ]
37.571429
0.011152
def _find_longest_parent_path(path_set, path): """Finds the longest "parent-path" of 'path' in 'path_set'. This function takes and returns "path-like" strings which are strings made of strings separated by os.sep. No file access is performed here, so these strings need not correspond to actual files in some fi...
[ "def", "_find_longest_parent_path", "(", "path_set", ",", "path", ")", ":", "# This could likely be more efficiently implemented with a trie", "# data-structure, but we don't want to add an extra dependency for that.", "while", "path", "not", "in", "path_set", ":", "if", "not", "...
40
0.006573
def get_pg_core(connection_string, *, cursor_factory=None, edit_connection=None): """Creates a simple PostgreSQL core. Requires the psycopg2 library.""" import psycopg2 as pq from psycopg2.extras import NamedTupleCursor def opener(): """Opens a single PostgreSQL connection with the scope-captured connectio...
[ "def", "get_pg_core", "(", "connection_string", ",", "*", ",", "cursor_factory", "=", "None", ",", "edit_connection", "=", "None", ")", ":", "import", "psycopg2", "as", "pq", "from", "psycopg2", ".", "extras", "import", "NamedTupleCursor", "def", "opener", "("...
34.045455
0.011688
def decode_from_dataset(estimator, problem_name, hparams, decode_hp, decode_to_file=None, dataset_split=None, checkpoint_path=None): """Perform decoding from dataset.""" tf...
[ "def", "decode_from_dataset", "(", "estimator", ",", "problem_name", ",", "hparams", ",", "decode_hp", ",", "decode_to_file", "=", "None", ",", "dataset_split", "=", "None", ",", "checkpoint_path", "=", "None", ")", ":", "tf", ".", "logging", ".", "info", "(...
34.3
0.009717
def to_mime_message(self): """Returns the envelope as :py:class:`email.mime.multipart.MIMEMultipart`.""" msg = MIMEMultipart('alternative') msg['Subject'] = self._header(self._subject or '') msg['From'] = self._encoded(self._addrs_to_header([self._from])) msg['To'] = sel...
[ "def", "to_mime_message", "(", "self", ")", ":", "msg", "=", "MIMEMultipart", "(", "'alternative'", ")", "msg", "[", "'Subject'", "]", "=", "self", ".", "_header", "(", "self", ".", "_subject", "or", "''", ")", "msg", "[", "'From'", "]", "=", "self", ...
35.208333
0.002304
def remove_tab(self, tab=0): """ Removes the tab by index. """ # pop it from the list t = self.tabs.pop(tab) # remove it from the gui self._widget.removeTab(tab) # return it in case someone cares return t
[ "def", "remove_tab", "(", "self", ",", "tab", "=", "0", ")", ":", "# pop it from the list", "t", "=", "self", ".", "tabs", ".", "pop", "(", "tab", ")", "# remove it from the gui", "self", ".", "_widget", ".", "removeTab", "(", "tab", ")", "# return it in c...
20.538462
0.007168
def purge(datasets, reuses, organizations): ''' Permanently remove data flagged as deleted. If no model flag is given, all models are purged. ''' purge_all = not any((datasets, reuses, organizations)) if purge_all or datasets: log.info('Purging datasets') purge_datasets() ...
[ "def", "purge", "(", "datasets", ",", "reuses", ",", "organizations", ")", ":", "purge_all", "=", "not", "any", "(", "(", "datasets", ",", "reuses", ",", "organizations", ")", ")", "if", "purge_all", "or", "datasets", ":", "log", ".", "info", "(", "'Pu...
24.285714
0.001887
def get_summary(result): """ get summary from test result Args: result (instance): HtmlTestResult() instance Returns: dict: summary extracted from result. { "success": True, "stat": {}, "time": {}, "records": [] ...
[ "def", "get_summary", "(", "result", ")", ":", "summary", "=", "{", "\"success\"", ":", "result", ".", "wasSuccessful", "(", ")", ",", "\"stat\"", ":", "{", "'total'", ":", "result", ".", "testsRun", ",", "'failures'", ":", "len", "(", "result", ".", "...
26.952381
0.000853
def get_code_breakpoint(self, dwProcessId, address): """ Returns the internally used breakpoint object, for the code breakpoint defined at the given address. @warning: It's usually best to call the L{Debug} methods instead of accessing the breakpoint objects directly. ...
[ "def", "get_code_breakpoint", "(", "self", ",", "dwProcessId", ",", "address", ")", ":", "key", "=", "(", "dwProcessId", ",", "address", ")", "if", "key", "not", "in", "self", ".", "__codeBP", ":", "msg", "=", "\"No breakpoint at process %d, address %s\"", "ad...
34.935484
0.001797
def rpc_get_subdomains_owned_by_address(self, address, **con_info): """ Get the list of subdomains owned by an address. Return {'status': True, 'subdomains': ...} on success Return {'error': ...} on error """ if not check_address(address): return {'error': 'In...
[ "def", "rpc_get_subdomains_owned_by_address", "(", "self", ",", "address", ",", "*", "*", "con_info", ")", ":", "if", "not", "check_address", "(", "address", ")", ":", "return", "{", "'error'", ":", "'Invalid address'", ",", "'http_status'", ":", "400", "}", ...
41.727273
0.004264
def get_dem_mosaic_cmd(fn_list, o, fn_list_txt=None, tr=None, t_srs=None, t_projwin=None, georef_tile_size=None, threads=None, tile=None, stat=None): """ Create ASP dem_mosaic command Useful for spawning many single-threaded mosaicing processes """ cmd = ['dem_mosaic',] if o is None: o ...
[ "def", "get_dem_mosaic_cmd", "(", "fn_list", ",", "o", ",", "fn_list_txt", "=", "None", ",", "tr", "=", "None", ",", "t_srs", "=", "None", ",", "t_projwin", "=", "None", ",", "georef_tile_size", "=", "None", ",", "threads", "=", "None", ",", "tile", "=...
38.2
0.008817
def get_gravatar(email, size=80, default='identicon'): """ Get's a Gravatar for a email address. :param size: The size in pixels of one side of the Gravatar's square image. Optional, if not supplied will default to ``80``. :param default: Defines what should be displayed if no imag...
[ "def", "get_gravatar", "(", "email", ",", "size", "=", "80", ",", "default", "=", "'identicon'", ")", ":", "if", "userena_settings", ".", "USERENA_MUGSHOT_GRAVATAR_SECURE", ":", "base_url", "=", "'https://secure.gravatar.com/avatar/'", "else", ":", "base_url", "=", ...
34.288889
0.00189
def from_known_inputs(cls, logs=None, metric_names=None, label_names=None): """An alternate constructor that assumes known metrics and labels. This differs from the default constructor in that the metrics and labels are iterables of names of 'known' metrics and labels respectively. The ...
[ "def", "from_known_inputs", "(", "cls", ",", "logs", "=", "None", ",", "metric_names", "=", "None", ",", "label_names", "=", "None", ")", ":", "if", "not", "metric_names", ":", "metric_names", "=", "(", ")", "if", "not", "label_names", ":", "label_names", ...
47.189189
0.003367
def _set_mpls_traffic_bypass(self, v, load=False): """ Setter method for mpls_traffic_bypass, mapped from YANG variable /telemetry/profile/mpls_traffic_bypass (list) If this variable is read-only (config: false) in the source YANG file, then _set_mpls_traffic_bypass is considered as a private method...
[ "def", "_set_mpls_traffic_bypass", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",...
116.909091
0.004242
def tagAttributes(fdef_master_list,node,depth=0): '''recursively tag objects with sizes, depths and path names ''' if type(node)==list: for i in node: depth+=1 tagAttributes(fdef_master_list,i,depth) if type(node)==dict: for x in fdef_master_list: if jsNam...
[ "def", "tagAttributes", "(", "fdef_master_list", ",", "node", ",", "depth", "=", "0", ")", ":", "if", "type", "(", "node", ")", "==", "list", ":", "for", "i", "in", "node", ":", "depth", "+=", "1", "tagAttributes", "(", "fdef_master_list", ",", "i", ...
36.058824
0.025437
def parse_input_file(resource): """ Parse input file into remote packages and excluded data. In addition to garbage, excluded data includes directory indexes for the time being. This will be revisited after basic functionality has been fully implemented. """ input_resource = open(resource, ...
[ "def", "parse_input_file", "(", "resource", ")", ":", "input_resource", "=", "open", "(", "resource", ",", "'r'", ")", ".", "read", "(", ")", "remotes_list", "=", "[", "url", "for", "url", "in", "input_resource", ".", "split", "(", ")", "]", "juicer", ...
45.782609
0.007442
def get_llur(self): """ Get lower-left and upper-right coordinates of the bounding box of this compound object. Returns ------- x1, y1, x2, y2: a 4-tuple of the lower-left and upper-right coords """ points = np.array([obj.get_llur() for obj in self.object...
[ "def", "get_llur", "(", "self", ")", ":", "points", "=", "np", ".", "array", "(", "[", "obj", ".", "get_llur", "(", ")", "for", "obj", "in", "self", ".", "objects", "]", ")", "t_", "=", "points", ".", "T", "x1", ",", "y1", "=", "t_", "[", "0"...
32
0.004338
def deleteMultiple(self, objs): ''' deleteMultiple - Delete multiple objects @param objs - List of objects @return - Number of objects deleted ''' conn = self._get_connection() pipeline = conn.pipeline() numDeleted = 0 for obj in objs: numDeleted += self.deleteOne(obj, pipeline) pipeline....
[ "def", "deleteMultiple", "(", "self", ",", "objs", ")", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "pipeline", "=", "conn", ".", "pipeline", "(", ")", "numDeleted", "=", "0", "for", "obj", "in", "objs", ":", "numDeleted", "+=", "self",...
17.473684
0.04
def get_output_data_port_m(self, data_port_id): """Returns the output data port model for the given data port id :param data_port_id: The data port id to search for :return: The model of the data port with the given id """ for data_port_m in self.output_data_ports: i...
[ "def", "get_output_data_port_m", "(", "self", ",", "data_port_id", ")", ":", "for", "data_port_m", "in", "self", ".", "output_data_ports", ":", "if", "data_port_m", ".", "data_port", ".", "data_port_id", "==", "data_port_id", ":", "return", "data_port_m", "return"...
41.9
0.004673
def alias_assessment_offered(self, assessment_offered_id, alias_id): """Adds an ``Id`` to an ``AssessmentOffered`` for the purpose of creating compatibility. The primary ``Id`` of the ``AssessmentOffered`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. ...
[ "def", "alias_assessment_offered", "(", "self", ",", "assessment_offered_id", ",", "alias_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceAdminSession.alias_resources_template", "self", ".", "_alias_id", "(", "primary_id", "=", "assessment_offered_id", ...
51.5
0.003177
def datastruct_formater( data, frequence=FREQUENCE.DAY, market_type=MARKET_TYPE.STOCK_CN, default_header=[] ): """一个任意格式转化为DataStruct的方法 Arguments: data {[type]} -- [description] Keyword Arguments: frequence {[type]} -- [description] (default: {FREQU...
[ "def", "datastruct_formater", "(", "data", ",", "frequence", "=", "FREQUENCE", ".", "DAY", ",", "market_type", "=", "MARKET_TYPE", ".", "STOCK_CN", ",", "default_header", "=", "[", "]", ")", ":", "if", "isinstance", "(", "data", ",", "list", ")", ":", "t...
39.168675
0.003
def cmd(send, msg, args): """Summons a user Syntax: {command} <nick> """ if args['type'] == 'privmsg': send("Note-passing should be done in public.") return arguments = msg.split() if len(arguments) > 1: send("Sorry, I can only perform the summoning ritual for one person ...
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "args", "[", "'type'", "]", "==", "'privmsg'", ":", "send", "(", "\"Note-passing should be done in public.\"", ")", "return", "arguments", "=", "msg", ".", "split", "(", ")", "if", "len"...
33
0.004651
def attention_lm_small(): """Cheap model. on lm1b_32k: 45M params 2 steps/sec on [GeForce GTX TITAN X] Returns: an hparams object. """ hparams = attention_lm_base() hparams.num_hidden_layers = 4 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.layer_prepostprocess_dropout ...
[ "def", "attention_lm_small", "(", ")", ":", "hparams", "=", "attention_lm_base", "(", ")", "hparams", ".", "num_hidden_layers", "=", "4", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "filter_size", "=", "2048", "hparams", ".", "layer_prepostprocess...
20.4375
0.023392
def variance(data, xbar=None): """Return the sample variance of data. data should be an iterable of Real-valued numbers, with at least two values. The optional argument xbar, if given, should be the mean of the data. If it is missing or None, the mean is automatically calculated. Use this function...
[ "def", "variance", "(", "data", ",", "xbar", "=", "None", ")", ":", "if", "iter", "(", "data", ")", "is", "data", ":", "data", "=", "list", "(", "data", ")", "n", "=", "len", "(", "data", ")", "if", "n", "<", "2", ":", "raise", "StatisticsError...
36.851852
0.000979
def Sensitivity(self): """Sensitivity spectrum to convert flux in :math:`erg \\; cm^{-2} \\; s^{-1} \\; \\AA^{-1}` to :math:`count s^{-1} \\AA^{-1}`. Calculation is done by combining the throughput curves with :math:`\\frac{h \\; c}{\\lambda}` . Returns ------- ...
[ "def", "Sensitivity", "(", "self", ")", ":", "sensitivity", "=", "spectrum", ".", "TabularSpectralElement", "(", ")", "product", "=", "self", ".", "_multiplyThroughputs", "(", ")", "sensitivity", ".", "_wavetable", "=", "product", ".", "GetWaveSet", "(", ")", ...
34.142857
0.004071
def release_hosting_device_slots(self, context, hosting_device, resource, num): """Free <num> slots in <hosting_device> from logical resource <id>. Returns True if deallocation was successful. False otherwise. """ with context.session.begin(subtransa...
[ "def", "release_hosting_device_slots", "(", "self", ",", "context", ",", "hosting_device", ",", "resource", ",", "num", ")", ":", "with", "context", ".", "session", ".", "begin", "(", "subtransactions", "=", "True", ")", ":", "num_str", "=", "str", "(", "n...
54.904762
0.000852
def associate_eip_address(instance_id=None, instance_name=None, public_ip=None, allocation_id=None, network_interface_id=None, network_interface_name=None, private_ip_address=None, allow_reassociation=False, region=None, key=None, ...
[ "def", "associate_eip_address", "(", "instance_id", "=", "None", ",", "instance_name", "=", "None", ",", "public_ip", "=", "None", ",", "allocation_id", "=", "None", ",", "network_interface_id", "=", "None", ",", "network_interface_name", "=", "None", ",", "priv...
43.642857
0.002401
def prune_creds_json(creds: dict, cred_ids: set) -> str: """ Strip all creds out of the input json structure that do not match any of the input credential identifiers. :param creds: indy-sdk creds structure :param cred_ids: the set of credential identifiers of interest :return: the reduced creds js...
[ "def", "prune_creds_json", "(", "creds", ":", "dict", ",", "cred_ids", ":", "set", ")", "->", "str", ":", "rv", "=", "deepcopy", "(", "creds", ")", "for", "key", "in", "(", "'attrs'", ",", "'predicates'", ")", ":", "for", "attr_uuid", ",", "creds_by_uu...
38.105263
0.005391
def extract_attribute_grid(self, model_grid, potential=False, future=False): """ Extracts the data from a ModelOutput or ModelGrid object within the bounding box region of the STObject. Args: model_grid: A ModelGrid or ModelOutput Object potential: Extracts from ...
[ "def", "extract_attribute_grid", "(", "self", ",", "model_grid", ",", "potential", "=", "False", ",", "future", "=", "False", ")", ":", "if", "potential", ":", "var_name", "=", "model_grid", ".", "variable", "+", "\"-potential\"", "timesteps", "=", "np", "."...
45.681818
0.005848
def commit(self): """ Insert the text at the current cursor position. """ # Backup and remove the currently selected text (may be none). tc = self.qteWidget.textCursor() self.selText = tc.selection().toHtml() self.selStart = tc.selectionStart() self.selEn...
[ "def", "commit", "(", "self", ")", ":", "# Backup and remove the currently selected text (may be none).", "tc", "=", "self", ".", "qteWidget", ".", "textCursor", "(", ")", "self", ".", "selText", "=", "tc", ".", "selection", "(", ")", ".", "toHtml", "(", ")", ...
39.21875
0.001555
def earthsun_distance(unixtime, delta_t, numthreads): """ Calculates the distance from the earth to the sun using the NREL SPA algorithm described in [1]. Parameters ---------- unixtime : numpy array Array of unix/epoch timestamps to calculate solar position for. Unixtime is the...
[ "def", "earthsun_distance", "(", "unixtime", ",", "delta_t", ",", "numthreads", ")", ":", "R", "=", "solar_position", "(", "unixtime", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "delta_t", ",", "0", ",", "numthreads", ",", "esd", "=", "...
31.5
0.001925
def shared_parameters(self): """ :return: bool, indicating if parameters are shared between the vector components of this model. """ if len(self) == 1: # Not a vector return False else: params_thusfar = [] for component in self.val...
[ "def", "shared_parameters", "(", "self", ")", ":", "if", "len", "(", "self", ")", "==", "1", ":", "# Not a vector", "return", "False", "else", ":", "params_thusfar", "=", "[", "]", "for", "component", "in", "self", ".", "values", "(", ")", ":", "vars",...
34.176471
0.00335
def tournament_name2number(self, name): """Translate tournament name to tournament number. Args: name (str): tournament name to translate Returns: number (int): number of the tournament or `None` if unknown. Examples: >>> NumerAPI().tournament_name2...
[ "def", "tournament_name2number", "(", "self", ",", "name", ")", ":", "tournaments", "=", "self", ".", "get_tournaments", "(", ")", "d", "=", "{", "t", "[", "'name'", "]", ":", "t", "[", "'tournament'", "]", "for", "t", "in", "tournaments", "}", "return...
31
0.003478
def restore_default_values_page(self): """Setup UI for default values setting.""" # Clear parameters so it doesn't add parameters when # restore from changes. if self.default_value_parameters: self.default_value_parameters = [] if self.default_value_parameter_containe...
[ "def", "restore_default_values_page", "(", "self", ")", ":", "# Clear parameters so it doesn't add parameters when", "# restore from changes.", "if", "self", ".", "default_value_parameters", ":", "self", ".", "default_value_parameters", "=", "[", "]", "if", "self", ".", "...
42.726027
0.000627
def get_library_config(name): """Get distutils-compatible extension extras for the given library. This requires ``pkg-config``. """ try: proc = Popen(['pkg-config', '--cflags', '--libs', name], stdout=PIPE, stderr=PIPE) except OSError: print('pkg-config is required for building PyA...
[ "def", "get_library_config", "(", "name", ")", ":", "try", ":", "proc", "=", "Popen", "(", "[", "'pkg-config'", ",", "'--cflags'", ",", "'--libs'", ",", "name", "]", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "except", "OSError", ":",...
26.818182
0.00491
def editProfile(self, profile): """ Prompts the user to edit the given profile. :param profile | <projexui.widgets.xviewwidget.XViewProfile> """ mod = XViewProfileDialog.edit(self.window(), profile) if not mod: return False ...
[ "def", "editProfile", "(", "self", ",", "profile", ")", ":", "mod", "=", "XViewProfileDialog", ".", "edit", "(", "self", ".", "window", "(", ")", ",", "profile", ")", "if", "not", "mod", ":", "return", "False", "# update the action interface\r", "for", "ac...
31.181818
0.008487
def find(self, key, perfect=False): """ Find a key path in the tree, matching wildcards. Return value for key, along with index path through subtree lists to the result. Throw ``KeyError`` if the key path doesn't exist in the tree. """ return find_in_tree(self.root, ke...
[ "def", "find", "(", "self", ",", "key", ",", "perfect", "=", "False", ")", ":", "return", "find_in_tree", "(", "self", ".", "root", ",", "key", ",", "perfect", ")" ]
40.5
0.006042
def bandnames(self, names): """ set the names of the raster bands Parameters ---------- names: list of str the names to be set; must be of same length as the number of bands Returns ------- """ if not isinstance(names, list): ...
[ "def", "bandnames", "(", "self", ",", "names", ")", ":", "if", "not", "isinstance", "(", "names", ",", "list", ")", ":", "raise", "TypeError", "(", "'the names to be set must be of type list'", ")", "if", "len", "(", "names", ")", "!=", "self", ".", "bands...
30.578947
0.005008
def validate_response(self, resp): """ Validates resp against expected return type for this function. Raises RpcException if the response is invalid. """ ok, msg = self.contract.validate(self.returns, self.returns.is_array, resp) ...
[ "def", "validate_response", "(", "self", ",", "resp", ")", ":", "ok", ",", "msg", "=", "self", ".", "contract", ".", "validate", "(", "self", ".", "returns", ",", "self", ".", "returns", ".", "is_array", ",", "resp", ")", "if", "not", "ok", ":", "v...
45.090909
0.007905
def sendall(self, data, **kws): """Send data to the socket. The socket must be connected to a remote socket. All the data is guaranteed to be sent.""" return SendAll(self, data, timeout=self._timeout, **kws)
[ "def", "sendall", "(", "self", ",", "data", ",", "*", "*", "kws", ")", ":", "return", "SendAll", "(", "self", ",", "data", ",", "timeout", "=", "self", ".", "_timeout", ",", "*", "*", "kws", ")" ]
57.75
0.008547
def _log_board_numbers(self, numbers): """ Numbers are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param numbers: list of catan.board.HexNumber objects. """ self._logln('numbers: {0...
[ "def", "_log_board_numbers", "(", "self", ",", "numbers", ")", ":", "self", ".", "_logln", "(", "'numbers: {0}'", ".", "format", "(", "' '", ".", "join", "(", "str", "(", "n", ".", "value", ")", "for", "n", "in", "numbers", ")", ")", ")" ]
45.5
0.010782
def _set_network_adapter_mapping(domain, gateway, ip_addr, subnet_mask, mac): ''' Returns a vim.vm.customization.AdapterMapping object containing the IP properties of a network adapter card domain Domain of the host gateway Gateway address ip_addr IP address subne...
[ "def", "_set_network_adapter_mapping", "(", "domain", ",", "gateway", ",", "ip_addr", ",", "subnet_mask", ",", "mac", ")", ":", "adapter_mapping", "=", "vim", ".", "vm", ".", "customization", ".", "AdapterMapping", "(", ")", "adapter_mapping", ".", "macAddress",...
27.676471
0.001027
def main_executable_region_limbos_contain(self, addr): """ Sometimes there exists a pointer that points to a few bytes before the beginning of a section, or a few bytes after the beginning of the section. We take care of that here. :param int addr: The address to check. :return:...
[ "def", "main_executable_region_limbos_contain", "(", "self", ",", "addr", ")", ":", "TOLERANCE", "=", "64", "closest_region", "=", "None", "least_limbo", "=", "None", "for", "start", ",", "end", "in", "self", ".", "main_executable_regions", ":", "if", "start", ...
37.178571
0.002809
def add_aggregated_lv_components(network, components): """ Aggregates LV load and generation at LV stations Use this function if you aim for MV calculation only. The according DataFrames of `components` are extended by load and generators representing these aggregated respecting the technology type...
[ "def", "add_aggregated_lv_components", "(", "network", ",", "components", ")", ":", "generators", "=", "{", "}", "loads", "=", "{", "}", "# collect aggregated generation capacity by type and subtype", "# collect aggregated load grouped by sector", "for", "lv_grid", "in", "n...
38.851852
0.00031
def get_cands_uri(field, ccd, version='p', ext='measure3.cands.astrom', prefix=None, block=None): """ return the nominal URI for a candidate file. @param field: the OSSOS field name @param ccd: which CCD are the candidates on @param version: either the 'p', or 's' (scrambled) ...
[ "def", "get_cands_uri", "(", "field", ",", "ccd", ",", "version", "=", "'p'", ",", "ext", "=", "'measure3.cands.astrom'", ",", "prefix", "=", "None", ",", "block", "=", "None", ")", ":", "if", "prefix", "is", "None", ":", "prefix", "=", "\"\"", "if", ...
31.1
0.003119
def create_node_rating_counts_settings(sender, **kwargs): """ create node rating count and settings""" created = kwargs['created'] node = kwargs['instance'] if created: # create node_rating_count and settings # task will be executed in background unless settings.CELERY_ALWAYS_EAGER is Tr...
[ "def", "create_node_rating_counts_settings", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "created", "=", "kwargs", "[", "'created'", "]", "node", "=", "kwargs", "[", "'instance'", "]", "if", "created", ":", "# create node_rating_count and settings", "# task ...
56.6
0.005217
def process_data_for_mean(data, direction_type_key): """ takes list of dicts with dec and inc as well as direction_type if possible or method_codes and sorts the data into lines and planes and process it for fisher means @param: data - list of dicts with dec inc and some manner of PCA type info @param:...
[ "def", "process_data_for_mean", "(", "data", ",", "direction_type_key", ")", ":", "dec_key", ",", "inc_key", ",", "meth_key", "=", "'dec'", ",", "'inc'", ",", "'magic_method_codes'", "# data model 2.5", "if", "'dir_dec'", "in", "data", "[", "0", "]", ".", "key...
45.485294
0.001899
def getIndex(self, indexName, indexClass): """Retrieves an index with a given index name and class @params indexName: The index name @params indexClass: vertex or edge @return The Index object or None""" if indexClass == "vertex": try: return Index(in...
[ "def", "getIndex", "(", "self", ",", "indexName", ",", "indexClass", ")", ":", "if", "indexClass", "==", "\"vertex\"", ":", "try", ":", "return", "Index", "(", "indexName", ",", "indexClass", ",", "\"manual\"", ",", "self", ".", "neograph", ".", "nodes", ...
40.428571
0.006904
def _permute_two_sample_iscs(iscs, group_parameters, i, pairwise=False, summary_statistic='median', exact_permutations=None, prng=None): """Applies two-sample permutations to ISC data Input ISCs should be n_subjects (leave-one-out approach) or n_pa...
[ "def", "_permute_two_sample_iscs", "(", "iscs", ",", "group_parameters", ",", "i", ",", "pairwise", "=", "False", ",", "summary_statistic", "=", "'median'", ",", "exact_permutations", "=", "None", ",", "prng", "=", "None", ")", ":", "# Shuffle the group assignment...
35.390805
0.000316
def fit(self, X, y=None): """ Compute the min, max and median for all columns in the DataFrame. For more information, please see the :func:`~tsfresh.utilities.dataframe_functions.get_range_values_per_column` function. :param X: DataFrame to calculate min, max and median ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "if", "not", "isinstance", "(", "X", ",", "pd", ".", "DataFrame", ")", ":", "X", "=", "pd", ".", "DataFrame", "(", "X", ")", "col_to_max", ",", "col_to_min", ",", "col_to_media...
49.25
0.005475
def remove_model(self, model_uuid: str) -> dict: """Delete the model from the registry. Call `upload()` to update the remote side.""" model_type = None for key, val in self.models.items(): if model_uuid in val: self._log.info("Found %s among %s models.", model_uuid, k...
[ "def", "remove_model", "(", "self", ",", "model_uuid", ":", "str", ")", "->", "dict", ":", "model_type", "=", "None", "for", "key", ",", "val", "in", "self", ".", "models", ".", "items", "(", ")", ":", "if", "model_uuid", "in", "val", ":", "self", ...
47.653846
0.003956
def scroll_to_horizontally(self, obj, *args,**selectors): """ Scroll(horizontally) on the object: obj to specific UI object which has *selectors* attributes appears. Return true if the UI object, else return false. See `Scroll To Vertically` for more details. """ return...
[ "def", "scroll_to_horizontally", "(", "self", ",", "obj", ",", "*", "args", ",", "*", "*", "selectors", ")", ":", "return", "obj", ".", "scroll", ".", "horiz", ".", "to", "(", "*", "*", "selectors", ")" ]
38.333333
0.011331
def log_request(handler): """ Logging request is opposite to response, sometime its necessary, feel free to enable it. """ block = 'Request Infomations:\n' + _format_headers_log(handler.request.headers) if handler.request.arguments: block += '+----Arguments----+\n' for k, v in h...
[ "def", "log_request", "(", "handler", ")", ":", "block", "=", "'Request Infomations:\\n'", "+", "_format_headers_log", "(", "handler", ".", "request", ".", "headers", ")", "if", "handler", ".", "request", ".", "arguments", ":", "block", "+=", "'+----Arguments---...
33.615385
0.004454
def _change_state_for_executable_task_instances(self, task_instances, acceptable_states, session=None): """ Changes the state of task instances in the list with one of the given states to QUEUED atomically, and returns the TIs changed in Simple...
[ "def", "_change_state_for_executable_task_instances", "(", "self", ",", "task_instances", ",", "acceptable_states", ",", "session", "=", "None", ")", ":", "if", "len", "(", "task_instances", ")", "==", "0", ":", "session", ".", "commit", "(", ")", "return", "[...
40.1875
0.003036
def to_meta(self, md5=None, file=None): """Return a dictionary of metadata, for use in the Remote api.""" # from collections import OrderedDict if not md5: if not file: raise ValueError('Must specify either file or md5') md5 = md5_for_file(file) ...
[ "def", "to_meta", "(", "self", ",", "md5", "=", "None", ",", "file", "=", "None", ")", ":", "# from collections import OrderedDict", "if", "not", "md5", ":", "if", "not", "file", ":", "raise", "ValueError", "(", "'Must specify either file or md5'", ")", "md5",...
29.818182
0.002954
def get_or_add_image_part(self, image_descriptor): """Return |ImagePart| object containing image identified by *image_descriptor*. The image-part is newly created if a matching one is not present in the collection. """ image = Image.from_file(image_descriptor) matching_i...
[ "def", "get_or_add_image_part", "(", "self", ",", "image_descriptor", ")", ":", "image", "=", "Image", ".", "from_file", "(", "image_descriptor", ")", "matching_image_part", "=", "self", ".", "_get_by_sha1", "(", "image", ".", "sha1", ")", "if", "matching_image_...
43.363636
0.00616
def update_one(self, filter, update, upsert=False, bypass_document_validation=False, collation=None, array_filters=None, session=None): """Update a single document matching the filter. >>> for doc in db.test.find(): ... print(doc) ... ...
[ "def", "update_one", "(", "self", ",", "filter", ",", "update", ",", "upsert", "=", "False", ",", "bypass_document_validation", "=", "False", ",", "collation", "=", "None", ",", "array_filters", "=", "None", ",", "session", "=", "None", ")", ":", "common",...
37.507246
0.001883
def hdate(self): """Return the hebrew date.""" if self._last_updated == "hdate": return self._hdate return conv.jdn_to_hdate(self._jdn)
[ "def", "hdate", "(", "self", ")", ":", "if", "self", ".", "_last_updated", "==", "\"hdate\"", ":", "return", "self", ".", "_hdate", "return", "conv", ".", "jdn_to_hdate", "(", "self", ".", "_jdn", ")" ]
33.4
0.011696
def from_env_vars(self) -> None: """Load values from environment variables. Keys must start with `KUYRUK_`.""" for key, value in os.environ.items(): if key.startswith('KUYRUK_'): key = key[7:] if hasattr(Config, key): try: ...
[ "def", "from_env_vars", "(", "self", ")", "->", "None", ":", "for", "key", ",", "value", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "'KUYRUK_'", ")", ":", "key", "=", "key", "[", "7", ":", "]", ...
37.230769
0.004032
def nsmallest(n, iterable, key=None): """Find the n smallest elements in a dataset. Equivalent to: sorted(iterable, key=key)[:n] """ # Short-cut for n==1 is to use min() if n == 1: it = iter(iterable) sentinel = object() if key is None: result = min(it, default...
[ "def", "nsmallest", "(", "n", ",", "iterable", ",", "key", "=", "None", ")", ":", "# Short-cut for n==1 is to use min()", "if", "n", "==", "1", ":", "it", "=", "iter", "(", "iterable", ")", "sentinel", "=", "object", "(", ")", "if", "key", "is", "None"...
28.387097
0.000549
def as_dictionary(self): """ Return the parameter as a dictionary. :return: dict """ return { "name": self.name, "type": self.type, "value": remove_0x_prefix(self.value) if self.type == 'bytes32' else self.value }
[ "def", "as_dictionary", "(", "self", ")", ":", "return", "{", "\"name\"", ":", "self", ".", "name", ",", "\"type\"", ":", "self", ".", "type", ",", "\"value\"", ":", "remove_0x_prefix", "(", "self", ".", "value", ")", "if", "self", ".", "type", "==", ...
26.181818
0.010067
def _flatten_file_with_secondary(input, out_dir): """Flatten file representation with secondary indices (CWL-like) """ out = [] orig_dir = os.path.dirname(input["base"]) for finfo in [input["base"]] + input.get("secondary", []): cur_dir = os.path.dirname(finfo) if cur_dir != orig_dir...
[ "def", "_flatten_file_with_secondary", "(", "input", ",", "out_dir", ")", ":", "out", "=", "[", "]", "orig_dir", "=", "os", ".", "path", ".", "dirname", "(", "input", "[", "\"base\"", "]", ")", "for", "finfo", "in", "[", "input", "[", "\"base\"", "]", ...
42
0.003584
def get_states(self, merge_multi_context=True): """Gets states from all devices. If `merge_multi_context` is ``True``, it is like ``[out1, out2]``. Otherwise, it is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output elements are `NDArray`. Parameters ...
[ "def", "get_states", "(", "self", ",", "merge_multi_context", "=", "True", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "return", "self", ".", "_exec_group", ".", "get_states", "(", "merge_multi_context", "=", "merge_multi...
40.090909
0.008859
def lookup_signame(num): """Find the corresponding signal name for 'num'. Return None if 'num' is invalid.""" signames = signal.__dict__ num = abs(num) for signame in list(signames.keys()): if signame.startswith('SIG') and signames[signame] == num: return signame pass ...
[ "def", "lookup_signame", "(", "num", ")", ":", "signames", "=", "signal", ".", "__dict__", "num", "=", "abs", "(", "num", ")", "for", "signame", "in", "list", "(", "signames", ".", "keys", "(", ")", ")", ":", "if", "signame", ".", "startswith", "(", ...
34.272727
0.002584
def set_longitude_grid(self, degrees): """ Set the number of degrees between each longitude grid. """ number = (360.0 / degrees) + 1 locs = np.linspace(-np.pi, np.pi, number, True)[1:] locs[-1] -= 0.01 # Workaround for "back" gridlines showing. self.xaxis.set_majo...
[ "def", "set_longitude_grid", "(", "self", ",", "degrees", ")", ":", "number", "=", "(", "360.0", "/", "degrees", ")", "+", "1", "locs", "=", "np", ".", "linspace", "(", "-", "np", ".", "pi", ",", "np", ".", "pi", ",", "number", ",", "True", ")", ...
45
0.006536
def list_databases(self, like=None): """ List databases in the Impala cluster. Like the SHOW DATABASES command in the impala-shell. Parameters ---------- like : string, default None e.g. 'foo*' to match all tables starting with 'foo' Returns --...
[ "def", "list_databases", "(", "self", ",", "like", "=", "None", ")", ":", "statement", "=", "'SHOW DATABASES'", "if", "like", ":", "statement", "+=", "\" LIKE '{0}'\"", ".", "format", "(", "like", ")", "with", "self", ".", "_execute", "(", "statement", ","...
26.590909
0.0033
def _resolve_items_to_service_uids(items): """ Returns a list of service uids without duplicates based on the items :param items: A list (or one object) of service-related info items. The list can be heterogeneous and each item can be: - Analysis Service instance - Analysis insta...
[ "def", "_resolve_items_to_service_uids", "(", "items", ")", ":", "def", "resolve_to_uid", "(", "item", ")", ":", "if", "api", ".", "is_uid", "(", "item", ")", ":", "return", "item", "elif", "IAnalysisService", ".", "providedBy", "(", "item", ")", ":", "ret...
37.945946
0.000694
def _get_token_type(self, char): """ Returns a 2-tuple (behaviour, type). behaviours: 0 - join 1 - split 2 - ignore """ if char in '()': return self.SPLIT, 0 elif char == ',': return self.SPLIT, 1 elif char in '<>': ...
[ "def", "_get_token_type", "(", "self", ",", "char", ")", ":", "if", "char", "in", "'()'", ":", "return", "self", ".", "SPLIT", ",", "0", "elif", "char", "==", "','", ":", "return", "self", ".", "SPLIT", ",", "1", "elif", "char", "in", "'<>'", ":", ...
29.36
0.003958
def rand_poisson(nnodes, ncontacts, lam=1, nettype='bu', netinfo=None, netrep='graphlet'): """ Generate a random network where intervals between contacts are distributed by a poisson distribution Parameters ---------- nnodes : int Number of nodes in networks ncontacts : int or list ...
[ "def", "rand_poisson", "(", "nnodes", ",", "ncontacts", ",", "lam", "=", "1", ",", "nettype", "=", "'bu'", ",", "netinfo", "=", "None", ",", "netrep", "=", "'graphlet'", ")", ":", "if", "isinstance", "(", "ncontacts", ",", "list", ")", ":", "if", "le...
32.761905
0.003175
def GetArtifactParserDependencies(rdf_artifact): """Return the set of knowledgebase path dependencies required by the parser. Args: rdf_artifact: RDF artifact object. Returns: A set of strings for the required kb objects e.g. ["users.appdata", "systemroot"] """ deps = set() processors = parser...
[ "def", "GetArtifactParserDependencies", "(", "rdf_artifact", ")", ":", "deps", "=", "set", "(", ")", "processors", "=", "parser", ".", "Parser", ".", "GetClassesByArtifact", "(", "rdf_artifact", ".", "name", ")", "for", "p", "in", "processors", ":", "deps", ...
29.066667
0.013333
def set_policy(vhost, name, pattern, definition, priority=None, runas=None, apply_to=None): ''' Set a policy based on rabbitmqctl set_policy. Reference: http://www.rabbitmq.com/ha.html CLI Example: .. code-b...
[ "def", "set_policy", "(", "vhost", ",", "name", ",", "pattern", ",", "definition", ",", "priority", "=", "None", ",", "runas", "=", "None", ",", "apply_to", "=", "None", ")", ":", "if", "runas", "is", "None", "and", "not", "salt", ".", "utils", ".", ...
32.914286
0.001686
def verify_document(self, document: Document) -> bool: """ Check specified document :param duniterpy.documents.Document document: :return: """ signature = base64.b64decode(document.signatures[0]) prepended = signature + bytes(document.raw(), 'ascii') try:...
[ "def", "verify_document", "(", "self", ",", "document", ":", "Document", ")", "->", "bool", ":", "signature", "=", "base64", ".", "b64decode", "(", "document", ".", "signatures", "[", "0", "]", ")", "prepended", "=", "signature", "+", "bytes", "(", "docu...
29.857143
0.00464
def _create_latent_variables(self): """ Creates model latent variables Returns ---------- None (changes model attributes) """ for parm in range(self.z_no): self.latent_variables.add_z('Scale ' + self.X_names[parm], fam.Flat(transform='exp'), fam.Normal(0, 3)...
[ "def", "_create_latent_variables", "(", "self", ")", ":", "for", "parm", "in", "range", "(", "self", ".", "z_no", ")", ":", "self", ".", "latent_variables", ".", "add_z", "(", "'Scale '", "+", "self", ".", "X_names", "[", "parm", "]", ",", "fam", ".", ...
35.333333
0.006897
def dataset_docs_str(datasets=None): """Create dataset documentation string for given datasets. Args: datasets: list of datasets for which to create documentation. If None, then all available datasets will be used. Returns: string describing the datasets (in the MarkDown format). """ m...
[ "def", "dataset_docs_str", "(", "datasets", "=", "None", ")", ":", "module_to_builder", "=", "make_module_to_builder_dict", "(", "datasets", ")", "sections", "=", "sorted", "(", "list", "(", "module_to_builder", ".", "keys", "(", ")", ")", ")", "section_tocs", ...
34.233333
0.00947
def federation(self): """returns the class that controls federation""" url = self._url + "/federation" return _Federation(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._p...
[ "def", "federation", "(", "self", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/federation\"", "return", "_Federation", "(", "url", "=", "url", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_...
46.285714
0.006061
def _fill(self): """Fills bucket with accrued tokens since last fill.""" right_now = time.time() time_diff = right_now - self._last_fill if time_diff < 0: return self._count = min( self._count + self._fill_rate * time_diff, self._capacity, ...
[ "def", "_fill", "(", "self", ")", ":", "right_now", "=", "time", ".", "time", "(", ")", "time_diff", "=", "right_now", "-", "self", ".", "_last_fill", "if", "time_diff", "<", "0", ":", "return", "self", ".", "_count", "=", "min", "(", "self", ".", ...
27
0.00551
def processFlat(self): """Main process. Returns ------- est_idx : np.array(N) Estimated indeces for the segment boundaries in frames. est_labels : np.array(N-1) Estimated labels for the segments. """ # Preprocess to obtain features, times, ...
[ "def", "processFlat", "(", "self", ")", ":", "# Preprocess to obtain features, times, and input boundary indeces", "F", "=", "self", ".", "_preprocess", "(", ")", "# Normalize", "F", "=", "U", ".", "normalize", "(", "F", ",", "norm_type", "=", "self", ".", "conf...
40.931034
0.001646
def split_by_commas(maybe_s: str) -> Tuple[str, ...]: """Split a string by commas, but allow escaped commas. - If maybe_s is falsey, returns an empty tuple - Ignore backslashed commas """ if not maybe_s: return () parts: List[str] = [] split_by_backslash = maybe_s.split(r'\,') fo...
[ "def", "split_by_commas", "(", "maybe_s", ":", "str", ")", "->", "Tuple", "[", "str", ",", "...", "]", ":", "if", "not", "maybe_s", ":", "return", "(", ")", "parts", ":", "List", "[", "str", "]", "=", "[", "]", "split_by_backslash", "=", "maybe_s", ...
35.176471
0.001629
def iter_dialogs( self, offset_date: int = 0, limit: int = 0 ) -> Generator["pyrogram.Dialog", None, None]: """Use this method to iterate through a user's dialogs sequentially. This convenience method does the same as repeatedly calling :meth:`get_dialogs` in a loop, thus sa...
[ "def", "iter_dialogs", "(", "self", ",", "offset_date", ":", "int", "=", "0", ",", "limit", ":", "int", "=", "0", ")", "->", "Generator", "[", "\"pyrogram.Dialog\"", ",", "None", ",", "None", "]", ":", "current", "=", "0", "total", "=", "limit", "or"...
29.20339
0.00393
def redirect_stds(self): """Redirects stds""" if not self.debug: sys.stdout = self.stdout_write sys.stderr = self.stderr_write sys.stdin = self.stdin_read
[ "def", "redirect_stds", "(", "self", ")", ":", "if", "not", "self", ".", "debug", ":", "sys", ".", "stdout", "=", "self", ".", "stdout_write", "sys", ".", "stderr", "=", "self", ".", "stderr_write", "sys", ".", "stdin", "=", "self", ".", "stdin_read" ]
34.333333
0.009479
def is_into_check(self, move: Move) -> bool: """ Checks if the given move would leave the king in check or put it into check. The move must be at least pseudo legal. """ king = self.king(self.turn) if king is None: return False checkers = self.attacke...
[ "def", "is_into_check", "(", "self", ",", "move", ":", "Move", ")", "->", "bool", ":", "king", "=", "self", ".", "king", "(", "self", ".", "turn", ")", "if", "king", "is", "None", ":", "return", "False", "checkers", "=", "self", ".", "attackers_mask"...
40.25
0.004552
def rvir(self,H=70.,Om=0.3,overdens=200.,wrtcrit=False,ro=None,vo=None, use_physical=False): # use_physical necessary bc of pop=False, does nothing inside """ NAME: rvir PURPOSE: calculate the virial radius for this density distribution INPUT: ...
[ "def", "rvir", "(", "self", ",", "H", "=", "70.", ",", "Om", "=", "0.3", ",", "overdens", "=", "200.", ",", "wrtcrit", "=", "False", ",", "ro", "=", "None", ",", "vo", "=", "None", ",", "use_physical", "=", "False", ")", ":", "# use_physical necess...
32.222222
0.022088
def _tls_add_pad(p, block_size): """ Provided with cipher block size parameter and current TLSCompressed packet p (after MAC addition), the function adds required, deterministic padding to p.data before encryption step, as it is defined for TLS (i.e. not SSL and its allowed random padding). The func...
[ "def", "_tls_add_pad", "(", "p", ",", "block_size", ")", ":", "padlen", "=", "-", "p", ".", "len", "%", "block_size", "padding", "=", "chb", "(", "padlen", ")", "*", "(", "padlen", "+", "1", ")", "p", ".", "len", "+=", "len", "(", "padding", ")",...
42.272727
0.002105
def _add_months(self, date, months): """ Add ``months`` months to ``date``. Unfortunately we can't use timedeltas to add months because timedelta counts in days and there's no foolproof way to add N months in days without counting the number of days per month. """ ...
[ "def", "_add_months", "(", "self", ",", "date", ",", "months", ")", ":", "year", "=", "date", ".", "year", "+", "(", "date", ".", "month", "+", "months", "-", "1", ")", "//", "12", "month", "=", "(", "date", ".", "month", "+", "months", "-", "1...
43
0.008282
def is_std_wostream(type_): """ Returns True, if type represents C++ std::wostream, False otherwise. """ if utils.is_str(type_): return type_ in wostream_equivalences type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string ...
[ "def", "is_std_wostream", "(", "type_", ")", ":", "if", "utils", ".", "is_str", "(", "type_", ")", ":", "return", "type_", "in", "wostream_equivalences", "type_", "=", "remove_alias", "(", "type_", ")", "type_", "=", "remove_reference", "(", "type_", ")", ...
25.538462
0.002907
def get_image(self, float_key="floats", to_chw=True): """ get image list from ImageFrame """ tensors = callBigDlFunc(self.bigdl_type, "localImageFrameToImageTensor", self.value, float_key, to_chw) return map(lambda tensor: tensor.to_ndarray(), t...
[ "def", "get_image", "(", "self", ",", "float_key", "=", "\"floats\"", ",", "to_chw", "=", "True", ")", ":", "tensors", "=", "callBigDlFunc", "(", "self", ".", "bigdl_type", ",", "\"localImageFrameToImageTensor\"", ",", "self", ".", "value", ",", "float_key", ...
45.857143
0.012232
def trim_common_suffixes(strs, min_len=0): """ trim common suffixes >>> trim_common_suffixes('A', 1) (0, 'A') """ if len(strs) < 2: return 0, strs rev_strs = [s[::-1] for s in strs] trimmed, rev_strs = trim_common_prefixes(rev_strs, min_len) if trimmed: strs = [...
[ "def", "trim_common_suffixes", "(", "strs", ",", "min_len", "=", "0", ")", ":", "if", "len", "(", "strs", ")", "<", "2", ":", "return", "0", ",", "strs", "rev_strs", "=", "[", "s", "[", ":", ":", "-", "1", "]", "for", "s", "in", "strs", "]", ...
17.65
0.002688
def createNetwork(self, data, headers=None, query_params=None, content_type="application/json"): """ Create a new network It is method for POST /network """ uri = self.client.base_url + "/network" return self.client.post(uri, data, headers, query_params, content_type)
[ "def", "createNetwork", "(", "self", ",", "data", ",", "headers", "=", "None", ",", "query_params", "=", "None", ",", "content_type", "=", "\"application/json\"", ")", ":", "uri", "=", "self", ".", "client", ".", "base_url", "+", "\"/network\"", "return", ...
44.285714
0.009494
def show_repo(self, repo_names=[], envs=[], query='/repositories/'): """ `repo_names` - Name of repository(s) to show Show repositories in specified environments """ juicer.utils.Log.log_debug("Show Repo(s): %s", str(repo_names)) repo_objects = {} for env in env...
[ "def", "show_repo", "(", "self", ",", "repo_names", "=", "[", "]", ",", "envs", "=", "[", "]", ",", "query", "=", "'/repositories/'", ")", ":", "juicer", ".", "utils", ".", "Log", ".", "log_debug", "(", "\"Show Repo(s): %s\"", ",", "str", "(", "repo_na...
46.129032
0.00274
def ParseOptions(cls, options, analysis_plugin): """Parses and validates options. Args: options (argparse.Namespace): parser options. analysis_plugin (VirusTotalAnalysisPlugin): analysis plugin to configure. Raises: BadConfigObject: when the output module object is of the wrong type. ...
[ "def", "ParseOptions", "(", "cls", ",", "options", ",", "analysis_plugin", ")", ":", "if", "not", "isinstance", "(", "analysis_plugin", ",", "virustotal", ".", "VirusTotalAnalysisPlugin", ")", ":", "raise", "errors", ".", "BadConfigObject", "(", "'Analysis plugin ...
37.714286
0.003693
def _get_config_file(conf, atom): ''' Parse the given atom, allowing access to its parts Success does not mean that the atom exists, just that it is in the correct format. Returns none if the atom is invalid. ''' if '*' in atom: parts = portage.dep.Atom(atom, allow_wildcard=True) ...
[ "def", "_get_config_file", "(", "conf", ",", "atom", ")", ":", "if", "'*'", "in", "atom", ":", "parts", "=", "portage", ".", "dep", ".", "Atom", "(", "atom", ",", "allow_wildcard", "=", "True", ")", "if", "not", "parts", ":", "return", "if", "parts",...
34.923077
0.002144
def edited(self, scope, name, lastSavedVal, newVal, action): """ This is the callback function invoked when an item is edited. This is only called for those items which were previously specified to use this mechanism. We do not turn this on for all items because the performa...
[ "def", "edited", "(", "self", ",", "scope", ",", "name", ",", "lastSavedVal", ",", "newVal", ",", "action", ")", ":", "# Get name(s) of any triggers that this par triggers", "triggerNamesTup", "=", "self", ".", "_taskParsObj", ".", "getTriggerStrings", "(", "scope",...
57.728155
0.004795
def define_grid(self, matrix): """Populates the Table with a list of tuples of strings. Args: matrix (list): list of iterables of strings (lists or something else). Items in the matrix have to correspond to a key for the children. """ self.style['grid-templa...
[ "def", "define_grid", "(", "self", ",", "matrix", ")", ":", "self", ".", "style", "[", "'grid-template-areas'", "]", "=", "''", ".", "join", "(", "\"'%s'\"", "%", "(", "' '", ".", "join", "(", "x", ")", ")", "for", "x", "in", "matrix", ")" ]
46.375
0.018519
def create_temp(node, namer): """Create a temporary variable. Args: node: Create a temporary variable to store this variable in. namer: A naming object that guarantees the names are unique. Returns: node: See `create_grad`. Returns a temporary variable, which is always a simple variable anno...
[ "def", "create_temp", "(", "node", ",", "namer", ")", ":", "if", "isinstance", "(", "node", ",", "gast", ".", "Name", ")", ":", "name", "=", "node", ".", "id", "elif", "isinstance", "(", "node", ",", "(", "gast", ".", "Attribute", ",", "gast", ".",...
31.45
0.012346
def isCollinear(self, b, c): ''' :b: Point or point equivalent :c: Point or point equivalent :return: boolean True if 'self' is collinear with 'b' and 'c', otherwise False. ''' return all(self.ccw(b, c, axis) == 0 for axis in self._keys)
[ "def", "isCollinear", "(", "self", ",", "b", ",", "c", ")", ":", "return", "all", "(", "self", ".", "ccw", "(", "b", ",", "c", ",", "axis", ")", "==", "0", "for", "axis", "in", "self", ".", "_keys", ")" ]
28.6
0.00678
def correlate(self): """ Associates various constructs with each other. """ print("Correlating information from different parts of your project...") non_local_mods = INTRINSIC_MODS for item in self.settings['extra_mods']: i = ...
[ "def", "correlate", "(", "self", ")", ":", "print", "(", "\"Correlating information from different parts of your project...\"", ")", "non_local_mods", "=", "INTRINSIC_MODS", "for", "item", "in", "self", ".", "settings", "[", "'extra_mods'", "]", ":", "i", "=", "item...
45.230263
0.004128
def send_publish(self, mid, topic, payload, qos, retain, dup): """Send PUBLISH.""" self.logger.debug("Send PUBLISH") if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN #NOTE: payload may be any kind of data # yet if it is a unicode string we utf8-encode it...
[ "def", "send_publish", "(", "self", ",", "mid", ",", "topic", ",", "payload", ",", "qos", ",", "retain", ",", "dup", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Send PUBLISH\"", ")", "if", "self", ".", "sock", "==", "NC", ".", "INVALID_SOC...
47.444444
0.009195
def main(): """Run newer stuffs.""" logging.basicConfig(format=LOGGING_FORMAT) log = logging.getLogger(__name__) parser = argparse.ArgumentParser() add_debug(parser) add_app(parser) add_env(parser) add_region(parser) add_properties(parser) parser.add_argument("--elb-subnet", hel...
[ "def", "main", "(", ")", ":", "logging", ".", "basicConfig", "(", "format", "=", "LOGGING_FORMAT", ")", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "add_debug", "(", "parser", ...
32.714286
0.004243