text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def downloaded(name, artifact, target_dir='/tmp', target_file=None): ''' Ensures that the artifact from nexus exists at given location. If it doesn't exist, then it will be downloaded. If it already exists then the checksum of existing file is checked against checksum in nexus. If it is different then t...
[ "def", "downloaded", "(", "name", ",", "artifact", ",", "target_dir", "=", "'/tmp'", ",", "target_file", "=", "None", ")", ":", "log", ".", "debug", "(", "\" ======================== STATE: nexus.downloaded (name: %s) \"", ",", "name", ")", "ret", "=", "{", "'na...
33.892857
22.440476
def plot_i(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the dimensionless quantity I of Pedersen and Rasmussen (1990) I = -(I2/2)**2 / (I1/3)**3 that is bounded by 0 and 1. Usage --...
[ "def", "plot_i", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if"...
38.55
19.65
def nn_dims(self, x, y, dims_x, dims_y, k=1, radius=np.inf, eps=0.0, p=2): """Find the k nearest neighbors of a subset of dims of x and y in the observed output data @see Databag.nn() for argument description @return distance and indexes of found nearest neighbors. """ if self.s...
[ "def", "nn_dims", "(", "self", ",", "x", ",", "y", ",", "dims_x", ",", "dims_y", ",", "k", "=", "1", ",", "radius", "=", "np", ".", "inf", ",", "eps", "=", "0.0", ",", "p", "=", "2", ")", ":", "if", "self", ".", "size", ">", "0", ":", "di...
54.368421
22.210526
def key_exists(hive, key, use_32bit_registry=False): ''' Check that the key is found in the registry. This refers to keys and not value/data pairs. To check value/data pairs, use ``value_exists`` Args: hive (str): The hive to connect to key (str): The key to check use_32bit_r...
[ "def", "key_exists", "(", "hive", ",", "key", ",", "use_32bit_registry", "=", "False", ")", ":", "local_hive", "=", "_to_unicode", "(", "hive", ")", "local_key", "=", "_to_unicode", "(", "key", ")", "registry", "=", "Registry", "(", ")", "try", ":", "hke...
26.340909
24.340909
def add_proof(self, text, publisher_account, keeper): """Add a proof to the DDO, based on the public_key id/index and signed with the private key add a static proof to the DDO, based on one of the public keys.""" # just incase clear out the current static proof property self._proof = No...
[ "def", "add_proof", "(", "self", ",", "text", ",", "publisher_account", ",", "keeper", ")", ":", "# just incase clear out the current static proof property", "self", ".", "_proof", "=", "None", "self", ".", "_proof", "=", "{", "'type'", ":", "PROOF_TYPE", ",", "...
45.416667
16.166667
def _post_run_hook(self, runtime): ''' generates a report showing nine slices, three per axis, of an arbitrary volume of `in_files`, with the resulting segmentation overlaid ''' outputs = self.aggregate_outputs(runtime=runtime) self._melodic_dir = outputs.out_dir NIWORKF...
[ "def", "_post_run_hook", "(", "self", ",", "runtime", ")", ":", "outputs", "=", "self", ".", "aggregate_outputs", "(", "runtime", "=", "runtime", ")", "self", ".", "_melodic_dir", "=", "outputs", ".", "out_dir", "NIWORKFLOWS_LOG", ".", "info", "(", "'Generat...
42.1
23.3
def source_start(base='', book_id='book'): """ chooses a starting source file in the 'base' directory for id = book_id """ repo_htm_path = "{book_id}-h/{book_id}-h.htm".format(book_id=book_id) possible_paths = ["book.asciidoc", repo_htm_path, "{}-0.tx...
[ "def", "source_start", "(", "base", "=", "''", ",", "book_id", "=", "'book'", ")", ":", "repo_htm_path", "=", "\"{book_id}-h/{book_id}-h.htm\"", ".", "format", "(", "book_id", "=", "book_id", ")", "possible_paths", "=", "[", "\"book.asciidoc\"", ",", "repo_htm_p...
30.727273
16.181818
def filter_by_meta(data, df, join_meta=False, **kwargs): """Filter by and join meta columns from an IamDataFrame to a pd.DataFrame Parameters ---------- data: pd.DataFrame instance DataFrame to which meta columns are to be joined, index or columns must include `['model', 'scenario']` ...
[ "def", "filter_by_meta", "(", "data", ",", "df", ",", "join_meta", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "set", "(", "META_IDX", ")", ".", "issubset", "(", "data", ".", "index", ".", "names", "+", "list", "(", "data", ".", ...
40.075472
20.037736
def check_recursion_depth(self): """Check recursion depth, raise AsyncRecursionError if too deep.""" from furious.async import MAX_DEPTH recursion_options = self._options.get('_recursion', {}) max_depth = recursion_options.get('max', MAX_DEPTH) # Check if recursion check has be...
[ "def", "check_recursion_depth", "(", "self", ")", ":", "from", "furious", ".", "async", "import", "MAX_DEPTH", "recursion_options", "=", "self", ".", "_options", ".", "get", "(", "'_recursion'", ",", "{", "}", ")", "max_depth", "=", "recursion_options", ".", ...
47.363636
20.181818
def _get_specified_sub_menu_template_name(self, level): """ Called by get_sub_menu_template(). Iterates through the various ways in which developers can specify potential sub menu templates for a menu, and returns the name of the most suitable template for the ``current_level``. ...
[ "def", "_get_specified_sub_menu_template_name", "(", "self", ",", "level", ")", ":", "ideal_index", "=", "level", "-", "2", "return", "self", ".", "_option_vals", ".", "sub_menu_template_name", "or", "get_item_by_index_or_last_item", "(", "self", ".", "_option_vals", ...
45.861111
24.583333
def convert_radian(coord, *variables): """Convert the given coordinate from radian to degree Parameters ---------- coord: xr.Variable The variable to transform ``*variables`` The variables that are on the same unit. Returns ------- xr.Variable The transformed va...
[ "def", "convert_radian", "(", "coord", ",", "*", "variables", ")", ":", "if", "any", "(", "v", ".", "attrs", ".", "get", "(", "'units'", ")", "==", "'radian'", "for", "v", "in", "variables", ")", ":", "return", "coord", "*", "180.", "/", "np", ".",...
27.222222
20.111111
def eventFilter(self, targetObj, event_qt): """ Intercept keyboard events and pass them on to the key parser and/or applet and/or widget. The handler only intercepts keyboard events and lets Qt handle the remaining ones (eg. mouse clicks) as usual. |Args| * ``t...
[ "def", "eventFilter", "(", "self", ",", "targetObj", ",", "event_qt", ")", ":", "# Return immediately if Qtmacs is not interested in it.", "if", "event_qt", ".", "type", "(", ")", "not", "in", "self", ".", "qteEventList", ":", "return", "False", "# Determine if the ...
40.153153
22.855856
def violations(self, src_path): """ Return a list of Violations recorded in `src_path`. """ if not any(src_path.endswith(ext) for ext in self.driver.supported_extensions): return [] if src_path not in self.violations_dict: if self.reports: ...
[ "def", "violations", "(", "self", ",", "src_path", ")", ":", "if", "not", "any", "(", "src_path", ".", "endswith", "(", "ext", ")", "for", "ext", "in", "self", ".", "driver", ".", "supported_extensions", ")", ":", "return", "[", "]", "if", "src_path", ...
48.782609
20.956522
def vra(self,*args,**kwargs): """ NAME: vra PURPOSE: return velocity in right ascension (km/s) INPUT: t - (optional) time at which to get vra (can be Quantity) obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer ...
[ "def", "vra", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", ".", "OrbitTop", "import", "_check_roSet", ",", "_check_voSet", "_check_roSet", "(", "self", ",", "kwargs", ",", "'vra'", ")", "_check_voSet", "(", "self", ",", "kw...
32.978723
25.829787
def pull_session(session_id=None, url='default', io_loop=None, arguments=None): ''' Create a session by loading the current server-side document. ``session.document`` will be a fresh document loaded from the server. While the connection to the server is open, changes made on the server side will be app...
[ "def", "pull_session", "(", "session_id", "=", "None", ",", "url", "=", "'default'", ",", "io_loop", "=", "None", ",", "arguments", "=", "None", ")", ":", "coords", "=", "_SessionCoordinates", "(", "session_id", "=", "session_id", ",", "url", "=", "url", ...
41.87931
28.637931
def clone(self, callable=None, **overrides): """Clones the Callable optionally with new settings Args: callable: New callable function to wrap **overrides: Parameter overrides to apply Returns: Cloned Callable object """ old = {k: v for k, v ...
[ "def", "clone", "(", "self", ",", "callable", "=", "None", ",", "*", "*", "overrides", ")", ":", "old", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "get_param_values", "(", ")", "if", "k", "not", "in", "[", "'callable'", "...
35.866667
14.933333
def process_tx_receipt(tx_hash, event, event_name): """ Wait until the tx receipt is processed. :param tx_hash: hash of the transaction :param event: AttributeDict with the event data. :param event_name: name of the event to subscribe, str :return: """ web3 = Web3Provider.get_web3() ...
[ "def", "process_tx_receipt", "(", "tx_hash", ",", "event", ",", "event_name", ")", ":", "web3", "=", "Web3Provider", ".", "get_web3", "(", ")", "try", ":", "web3", ".", "eth", ".", "waitForTransactionReceipt", "(", "tx_hash", ",", "timeout", "=", "20", ")"...
40.551724
25.448276
def _request_exc_message(exc): """ Return a reasonable exception message from a :exc:`request.exceptions.RequestException` exception. The approach is to dig deep to the original reason, if the original exception is present, skipping irrelevant exceptions such as `urllib3.exceptions.MaxRetryErro...
[ "def", "_request_exc_message", "(", "exc", ")", ":", "if", "exc", ".", "args", ":", "if", "isinstance", "(", "exc", ".", "args", "[", "0", "]", ",", "Exception", ")", ":", "org_exc", "=", "exc", ".", "args", "[", "0", "]", "if", "isinstance", "(", ...
35.028571
20.114286
def get_query_rows(self, job_id, offset=None, limit=None, timeout=0): """Retrieve a list of rows from a query table by job id. This method will append results from multiple pages together. If you want to manually page through results, you can use `get_query_results` method directly. ...
[ "def", "get_query_rows", "(", "self", ",", "job_id", ",", "offset", "=", "None", ",", "limit", "=", "None", ",", "timeout", "=", "0", ")", ":", "# Get query results", "query_reply", "=", "self", ".", "get_query_results", "(", "job_id", ",", "offset", "=", ...
41.613636
20.636364
def get(self): """ Retrieve the current configured SharedStorages entries :return: [list] List containing the current SharedStorages entries """ request = self._call(GetSharedStorages) response = request.commit() return response['Value']
[ "def", "get", "(", "self", ")", ":", "request", "=", "self", ".", "_call", "(", "GetSharedStorages", ")", "response", "=", "request", ".", "commit", "(", ")", "return", "response", "[", "'Value'", "]" ]
35.75
12.75
def setup(self, builder: Builder): """Performs this component's simulation setup. The ``setup`` method is automatically called by the simulation framework. The framework passes in a ``builder`` object which provides access to a variety of framework subsystems and metadata. Para...
[ "def", "setup", "(", "self", ",", "builder", ":", "Builder", ")", ":", "self", ".", "config", "=", "builder", ".", "configuration", "self", ".", "with_common_random_numbers", "=", "bool", "(", "self", ".", "config", ".", "randomness", ".", "key_columns", "...
48
30.53125
def to_csv(data, field_names=None, filename='data.csv', overwrite=True, write_headers=True, append=False, flat=True, primary_fields=None, sort_fields=True): """ DEPRECATED Write a list of dicts to a csv file :param data: List of dicts :param field_names: The ...
[ "def", "to_csv", "(", "data", ",", "field_names", "=", "None", ",", "filename", "=", "'data.csv'", ",", "overwrite", "=", "True", ",", "write_headers", "=", "True", ",", "append", "=", "False", ",", "flat", "=", "True", ",", "primary_fields", "=", "None"...
35.968254
17.873016
def type_description_from_node(gi_node): ''' Parse a typed node, returns a usable description ''' ctype_name, gi_name, array_nesting = unnest_type (gi_node) cur_ns = get_namespace(gi_node) if ctype_name is not None: type_tokens = __type_tokens_from_cdecl (ctype_name) else: ...
[ "def", "type_description_from_node", "(", "gi_node", ")", ":", "ctype_name", ",", "gi_name", ",", "array_nesting", "=", "unnest_type", "(", "gi_node", ")", "cur_ns", "=", "get_namespace", "(", "gi_node", ")", "if", "ctype_name", "is", "not", "None", ":", "type...
30.333333
22.555556
def modify_fw_device(self, tenant_id, fw_id, data): """Modifies the firewall cfg. """ drvr_dict, mgmt_ip = self.sched_obj.get_fw_dev_map(fw_id) return drvr_dict.get('drvr_obj').modify_fw(tenant_id, data)
[ "def", "modify_fw_device", "(", "self", ",", "tenant_id", ",", "fw_id", ",", "data", ")", ":", "drvr_dict", ",", "mgmt_ip", "=", "self", ".", "sched_obj", ".", "get_fw_dev_map", "(", "fw_id", ")", "return", "drvr_dict", ".", "get", "(", "'drvr_obj'", ")", ...
56
15.75
def _buffer(self, event: Message): """ Buffers an event, if applicable. """ if isinstance(event, BytesMessage): self._byte_buffer.write(event.data) elif isinstance(event, TextMessage): self._string_buffer.write(event.data)
[ "def", "_buffer", "(", "self", ",", "event", ":", "Message", ")", ":", "if", "isinstance", "(", "event", ",", "BytesMessage", ")", ":", "self", ".", "_byte_buffer", ".", "write", "(", "event", ".", "data", ")", "elif", "isinstance", "(", "event", ",", ...
34.875
3.625
def membership_in(self, organization): """Retrieve the user's membership in the specified organization.""" url = self._build_url('user', 'memberships', 'orgs', str(organization)) json = self._json(self._get(url), 200) return Membership(json, self)
[ "def", "membership_in", "(", "self", ",", "organization", ")", ":", "url", "=", "self", ".", "_build_url", "(", "'user'", ",", "'memberships'", ",", "'orgs'", ",", "str", "(", "organization", ")", ")", "json", "=", "self", ".", "_json", "(", "self", "....
50.666667
6.5
def generic_commit_and_try_merge2master_wf(git_action, file_content, doc_id, auth_info, parent_sha, commi...
[ "def", "generic_commit_and_try_merge2master_wf", "(", "git_action", ",", "file_content", ",", "doc_id", ",", "auth_info", ",", "parent_sha", ",", "commit_msg", "=", "''", ",", "merged_sha", "=", "None", ",", "doctype_display_name", "=", "\"document\"", ")", ":", "...
50.421053
22.552632
def create_dispatcher(self): """ Return a dispatcher for configured channels. """ before_context = max(self.args.before_context, self.args.context) after_context = max(self.args.after_context, self.args.context) if self.args.files_with_match is not None or self.args.coun...
[ "def", "create_dispatcher", "(", "self", ")", ":", "before_context", "=", "max", "(", "self", ".", "args", ".", "before_context", ",", "self", ".", "args", ".", "context", ")", "after_context", "=", "max", "(", "self", ".", "args", ".", "after_context", ...
49.117647
23.117647
def l2n(l, c): "host to network long" c = [] c.append(int((l >> 24) & U32(0xFF))) c.append(int((l >> 16) & U32(0xFF))) c.append(int((l >> 8) & U32(0xFF))) c.append(int((l ) & U32(0xFF))) return c
[ "def", "l2n", "(", "l", ",", "c", ")", ":", "c", "=", "[", "]", "c", ".", "append", "(", "int", "(", "(", "l", ">>", "24", ")", "&", "U32", "(", "0xFF", ")", ")", ")", "c", ".", "append", "(", "int", "(", "(", "l", ">>", "16", ")", "&...
27.75
12.25
def modification_changed(self, state=None, index=None, editor_id=None): """ Current editor's modification state has changed --> change tab title depending on new modification state --> enable/disable save/save all actions """ if editor_id is not None: f...
[ "def", "modification_changed", "(", "self", ",", "state", "=", "None", ",", "index", "=", "None", ",", "editor_id", "=", "None", ")", ":", "if", "editor_id", "is", "not", "None", ":", "for", "index", ",", "_finfo", "in", "enumerate", "(", "self", ".", ...
41.896552
13
def get_random_ontology(TOP_RANGE=10, pattern=""): """for testing purposes. Returns a random ontology/graph""" choices = get_localontologies(pattern=pattern) try: ontouri = choices[random.randint(0, TOP_RANGE)] # [0] except: ontouri = choices[0] print("Testing with URI: %s" % ontour...
[ "def", "get_random_ontology", "(", "TOP_RANGE", "=", "10", ",", "pattern", "=", "\"\"", ")", ":", "choices", "=", "get_localontologies", "(", "pattern", "=", "pattern", ")", "try", ":", "ontouri", "=", "choices", "[", "random", ".", "randint", "(", "0", ...
35.416667
14
def histogram(self, key, **dims): """Adds histogram with dimensions to the registry""" return super(RegexRegistry, self).histogram(self._get_key(key), **dims)
[ "def", "histogram", "(", "self", ",", "key", ",", "*", "*", "dims", ")", ":", "return", "super", "(", "RegexRegistry", ",", "self", ")", ".", "histogram", "(", "self", ".", "_get_key", "(", "key", ")", ",", "*", "*", "dims", ")" ]
57.333333
15.333333
def fetchJobStoreFiles(jobStore, options): """ Takes a list of file names as glob patterns, searches for these within a given directory, and attempts to take all of the files found and copy them into options.localFilePath. :param jobStore: A fileJobStore object. :param options.fetch: List of fi...
[ "def", "fetchJobStoreFiles", "(", "jobStore", ",", "options", ")", ":", "for", "jobStoreFile", "in", "options", ".", "fetch", ":", "jobStoreHits", "=", "recursiveGlob", "(", "directoryname", "=", "options", ".", "jobStore", ",", "glob_pattern", "=", "jobStoreFil...
49.478261
16.869565
def setup_toolbar(self): """Setup the toolbar.""" self.savefig_btn = create_toolbutton( self, icon=ima.icon('filesave'), tip=_("Save Image As..."), triggered=self.emit_save_figure) self.delfig_btn = create_toolbutton( self, icon=ima.icon('editclear...
[ "def", "setup_toolbar", "(", "self", ")", ":", "self", ".", "savefig_btn", "=", "create_toolbutton", "(", "self", ",", "icon", "=", "ima", ".", "icon", "(", "'filesave'", ")", ",", "tip", "=", "_", "(", "\"Save Image As...\"", ")", ",", "triggered", "=",...
33.578947
10.105263
def build_multiple_tocs(filenames: list, ordered: bool = False, no_links: bool = False, no_indentation: bool = False, no_list_coherence: bool = False, keep_header_levels: int = 3, ...
[ "def", "build_multiple_tocs", "(", "filenames", ":", "list", ",", "ordered", ":", "bool", "=", "False", ",", "no_links", ":", "bool", "=", "False", ",", "no_indentation", ":", "bool", "=", "False", ",", "no_list_coherence", ":", "bool", "=", "False", ",", ...
37.489796
16.55102
def make_clean_visible_from_raw(_html, tag_replacement_char=' '): '''Takes an HTML-like Unicode (or UTF-8 encoded) string as input and returns a Unicode string with all tags replaced by whitespace. In particular, all Unicode characters inside HTML are replaced with a single whitespace character. Th...
[ "def", "make_clean_visible_from_raw", "(", "_html", ",", "tag_replacement_char", "=", "' '", ")", ":", "if", "not", "isinstance", "(", "_html", ",", "unicode", ")", ":", "_html", "=", "unicode", "(", "_html", ",", "'utf-8'", ")", "#Strip tags with logic above", ...
37.37037
24.851852
def isValid(self) -> bool: '''Determine if the statement, expression or directive is valid. Otherwise the parser will continue until a valid multi-line expression or statement can be found.''' if not self.values: return True try: if self.category() == 'dir...
[ "def", "isValid", "(", "self", ")", "->", "bool", ":", "if", "not", "self", ".", "values", ":", "return", "True", "try", ":", "if", "self", ".", "category", "(", ")", "==", "'directive'", ":", "# we add func() because the expression can be multi-line and", "# ...
40.288136
18.966102
def choice_info(self): """View .info file """ info = ReadSBo(self.sbo_url).info(self.name, ".info") fill = self.fill_pager(info) self.pager(info + fill)
[ "def", "choice_info", "(", "self", ")", ":", "info", "=", "ReadSBo", "(", "self", ".", "sbo_url", ")", ".", "info", "(", "self", ".", "name", ",", "\".info\"", ")", "fill", "=", "self", ".", "fill_pager", "(", "info", ")", "self", ".", "pager", "("...
31.166667
8.666667
def connection_lost(self, exc): ''' override asyncio.Protocol ''' self._connected = False logging.debug( 'Connection lost (address: {} port: {})' .format(self.remote_ip, self.port)) for pid, (future, task) in self._requests.items(): t...
[ "def", "connection_lost", "(", "self", ",", "exc", ")", ":", "self", ".", "_connected", "=", "False", "logging", ".", "debug", "(", "'Connection lost (address: {} port: {})'", ".", "format", "(", "self", ".", "remote_ip", ",", "self", ".", "port", ")", ")", ...
30.157895
18.789474
def _generate_union_tag_property(self, union): """Emits union instance property representing union state.""" self.emit_wrapped_text( 'Represents the union\'s current tag state.', prefix=comment_prefix) self.emit( fmt_property_str( prop='tag', t...
[ "def", "_generate_union_tag_property", "(", "self", ",", "union", ")", ":", "self", ".", "emit_wrapped_text", "(", "'Represents the union\\'s current tag state.'", ",", "prefix", "=", "comment_prefix", ")", "self", ".", "emit", "(", "fmt_property_str", "(", "prop", ...
41.888889
14
def plot_report(report, success_name, fail_names, label=None, is_max_confidence=True, linewidth=LINEWIDTH, plot_upper_bound=True): """ Plot a success fail curve from a confidence report :param report: A confidence report (the type of object saved by make_confide...
[ "def", "plot_report", "(", "report", ",", "success_name", ",", "fail_names", ",", "label", "=", "None", ",", "is_max_confidence", "=", "True", ",", "linewidth", "=", "LINEWIDTH", ",", "plot_upper_bound", "=", "True", ")", ":", "(", "fail_optimal", ",", "succ...
41.926829
14.853659
def _parse(self, test_spec_str): """Parses a test specification string into an object that can yield corresponding tests. Tests can be specified in one of four forms: * [classname] * [classname]#[methodname] * [fully qualified classname]#[methodname] * [fully qualified classname]#[methodname] ...
[ "def", "_parse", "(", "self", ",", "test_spec_str", ")", ":", "components", "=", "test_spec_str", ".", "split", "(", "'#'", ",", "2", ")", "classname", "=", "components", "[", "0", "]", "methodname", "=", "components", "[", "1", "]", "if", "len", "(", ...
32.473684
16.631579
def level3_initialize(self): """Load abspath, dirname, basename, fname, ext, atime, ctime, mtime, size_on_disk attributes in initialization. **中文文档** 比较全面但稍慢的WinFile对象初始化方法, 从绝对路径中取得: - 绝对路径 - 父目录路径 - 文件全名 - 纯文件名 - 文件扩展名 ...
[ "def", "level3_initialize", "(", "self", ")", ":", "self", ".", "dirname", ",", "self", ".", "basename", "=", "os", ".", "path", ".", "split", "(", "self", ".", "abspath", ")", "# 目录名, 文件名", "self", ".", "fname", ",", "self", ".", "ext", "=", "os", ...
32.428571
20.75
def shuffle(self, func, num_splits=None, **kwargs): """Shuffle the order of the data in this axis based on the `func`. Extends `BaseFrameAxisPartition.shuffle`. :param func: :param num_splits: :param kwargs: :return: """ if num_splits is None: ...
[ "def", "shuffle", "(", "self", ",", "func", ",", "num_splits", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "num_splits", "is", "None", ":", "num_splits", "=", "len", "(", "self", ".", "list_of_blocks", ")", "args", "=", "[", "self", ".", ...
31.210526
18.421053
def parse_elements(elements): """Parse essential fix's data elements. Args: elements (list): Data values for fix Returns: Fix: Fix object representing data """ if not len(elements) in (14, 15): raise ValueError('Invalid GGA fix data') ...
[ "def", "parse_elements", "(", "elements", ")", ":", "if", "not", "len", "(", "elements", ")", "in", "(", "14", ",", "15", ")", ":", "raise", "ValueError", "(", "'Invalid GGA fix data'", ")", "time", "=", "datetime", ".", "time", "(", "*", "[", "int", ...
44.511111
15.933333
def remove_environment(self, name=None, path=None, **kwargs): """ Remove an environment entirely. See ``remove``. """ return self.remove(name=name, path=path, all=True, **kwargs)
[ "def", "remove_environment", "(", "self", ",", "name", "=", "None", ",", "path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "remove", "(", "name", "=", "name", ",", "path", "=", "path", ",", "all", "=", "True", ",", "*...
30.428571
15.285714
def import_events(self, source='wonambi'): """action: import events from text file (Wonambi or RemLogic).""" if self.annot is None: # remove if buttons are disabled self.parent.statusBar().showMessage('No score file loaded') return if 'wonambi' == source: fo...
[ "def", "import_events", "(", "self", ",", "source", "=", "'wonambi'", ")", ":", "if", "self", ".", "annot", "is", "None", ":", "# remove if buttons are disabled", "self", ".", "parent", ".", "statusBar", "(", ")", ".", "showMessage", "(", "'No score file loade...
34.961538
20.461538
def inspect(source: dict): """ Inspects the data and structure of the source dictionary object and adds the results to the display for viewing. :param source: A dictionary object to be inspected. :return: """ r = _get_report() r.append_body(render.inspect(source))
[ "def", "inspect", "(", "source", ":", "dict", ")", ":", "r", "=", "_get_report", "(", ")", "r", ".", "append_body", "(", "render", ".", "inspect", "(", "source", ")", ")" ]
26.818182
15.181818
def _delAccountRights(sidObject, user_right): ''' helper function to remove an account right from a user ''' try: _polHandle = win32security.LsaOpenPolicy(None, win32security.POLICY_ALL_ACCESS) user_rights_list = [user_right] _ret = win32security.LsaRemoveAccountRights(_polHandle...
[ "def", "_delAccountRights", "(", "sidObject", ",", "user_right", ")", ":", "try", ":", "_polHandle", "=", "win32security", ".", "LsaOpenPolicy", "(", "None", ",", "win32security", ".", "POLICY_ALL_ACCESS", ")", "user_rights_list", "=", "[", "user_right", "]", "_...
40
25.666667
def configure(self, options, config): """Configures the xunit plugin.""" Plugin.configure(self, options, config) self.config = config if self.enabled: self.jinja = Environment( loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')), ...
[ "def", "configure", "(", "self", ",", "options", ",", "config", ")", ":", "Plugin", ".", "configure", "(", "self", ",", "options", ",", "config", ")", "self", ".", "config", "=", "config", "if", "self", ".", "enabled", ":", "self", ".", "jinja", "=",...
46.923077
18.153846
def _replace_fun_unescape(m): """ Decode single hex/unicode escapes found in regex matches. Supports single hex/unicode escapes of the form ``'\\xYY'``, ``'\\uYYYY'``, and ``'\\UYYYYYYYY'`` where Y is a hex digit. Only decodes if there is an odd number of backslashes. .. versionadded:: 0.2 Pa...
[ "def", "_replace_fun_unescape", "(", "m", ")", ":", "slsh", "=", "b'\\\\'", ".", "decode", "(", "'ascii'", ")", "s", "=", "m", ".", "group", "(", "0", ")", "count", "=", "s", ".", "count", "(", "slsh", ")", "if", "count", "%", "2", "==", "0", "...
24.633333
21.033333
def area_top_orifice(self): """Estimate the orifice area corresponding to the top row of orifices. Another solution method is to use integration to solve this problem. Here we use the width of the stout weir in the center of the top row to estimate the area of the top orifice """...
[ "def", "area_top_orifice", "(", "self", ")", ":", "# Calculate the center of the top row:", "z", "=", "self", ".", "hl", "-", "0.5", "*", "self", ".", "b_rows", "# Multiply the stout weir width by the height of one row.", "return", "self", ".", "stout_w_per_flow", "(", ...
52.7
14.6
def result_report_parameters(self): """Report metric parameters Returns ------- str result report in string format """ output = self.ui.data(field='Evaluated length', value=self.evaluated_length_seconds, unit='sec') + '\n' output += self.ui.data(fie...
[ "def", "result_report_parameters", "(", "self", ")", ":", "output", "=", "self", ".", "ui", ".", "data", "(", "field", "=", "'Evaluated length'", ",", "value", "=", "self", ".", "evaluated_length_seconds", ",", "unit", "=", "'sec'", ")", "+", "'\\n'", "out...
32.55
31.65
def imm_params(imm): ''' imm_params(imm) yields a dictionary of the parameters of the immutable object imm. ''' return {p: getattr(imm, p) for p in six.iterkeys(_imm_param_data(imm))}
[ "def", "imm_params", "(", "imm", ")", ":", "return", "{", "p", ":", "getattr", "(", "imm", ",", "p", ")", "for", "p", "in", "six", ".", "iterkeys", "(", "_imm_param_data", "(", "imm", ")", ")", "}" ]
39
33.4
def output(id, url): """ View the files from a job. """ try: experiment = ExperimentClient().get(normalize_job_name(id)) except FloydException: experiment = ExperimentClient().get(id) output_dir_url = "%s/%s/files" % (floyd.floyd_web_host, experiment.name) if url: fl...
[ "def", "output", "(", "id", ",", "url", ")", ":", "try", ":", "experiment", "=", "ExperimentClient", "(", ")", ".", "get", "(", "normalize_job_name", "(", "id", ")", ")", "except", "FloydException", ":", "experiment", "=", "ExperimentClient", "(", ")", "...
30.4
18.4
def addMibSource(self, *mibSources): """Adds path to repository to search PySNMP MIB files. Parameters ---------- *mibSources : one or more paths to search or Python package names to import and search for PySNMP MIB modules. Returns ------- ...
[ "def", "addMibSource", "(", "self", ",", "*", "mibSources", ")", ":", "if", "self", ".", "_mibSourcesToAdd", "is", "None", ":", "self", ".", "_mibSourcesToAdd", "=", "mibSources", "else", ":", "self", ".", "_mibSourcesToAdd", "+=", "mibSources", "return", "s...
30.285714
23.171429
def char_spacing(self, dots): '''Specifes character spacing in dots. Args: dots: the character spacing you desire, in dots Returns: None Raises: RuntimeError: Invalid dot amount. ''' if dots in range(0,127): self.se...
[ "def", "char_spacing", "(", "self", ",", "dots", ")", ":", "if", "dots", "in", "range", "(", "0", ",", "127", ")", ":", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "chr", "(", "32", ")", "+", "chr", "(", "dots", ")", ")", "else", ...
30.5
20.071429
def _check_subject_identifier_matches_requested(self, authentication_request, sub): # type (oic.message.AuthorizationRequest, str) -> None """ Verifies the subject identifier against any requested subject identifier using the claims request parameter. :param authentication_request: authe...
[ "def", "_check_subject_identifier_matches_requested", "(", "self", ",", "authentication_request", ",", "sub", ")", ":", "# type (oic.message.AuthorizationRequest, str) -> None", "if", "'claims'", "in", "authentication_request", ":", "requested_id_token_sub", "=", "authentication_...
70.789474
38.263158
def get(self): """Return the computed statistics over the gathered data""" values = self.reservoir.sorted_values def safe(f, *args): try: return f(values, *args) except exceptions.StatisticsError: return 0.0 plevels = [50, 75, 90...
[ "def", "get", "(", "self", ")", ":", "values", "=", "self", ".", "reservoir", ".", "sorted_values", "def", "safe", "(", "f", ",", "*", "args", ")", ":", "try", ":", "return", "f", "(", "values", ",", "*", "args", ")", "except", "exceptions", ".", ...
34.542857
16.057143
def year(past=False, min_delta=0, max_delta=20): """Return a random year.""" return dt.date.today().year + _delta(past, min_delta, max_delta)
[ "def", "year", "(", "past", "=", "False", ",", "min_delta", "=", "0", ",", "max_delta", "=", "20", ")", ":", "return", "dt", ".", "date", ".", "today", "(", ")", ".", "year", "+", "_delta", "(", "past", ",", "min_delta", ",", "max_delta", ")" ]
49
12
def _create_window_function(name, doc=''): """ Create a window function by name """ def _(): sc = SparkContext._active_spark_context jc = getattr(sc._jvm.functions, name)() return Column(jc) _.__name__ = name _.__doc__ = 'Window function: ' + doc return _
[ "def", "_create_window_function", "(", "name", ",", "doc", "=", "''", ")", ":", "def", "_", "(", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "jc", "=", "getattr", "(", "sc", ".", "_jvm", ".", "functions", ",", "name", ")", "(", ...
32.333333
11.888889
def limits(table, field): """ Find minimum and maximum values under the given field. E.g.:: >>> import petl as etl >>> table = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]] >>> minv, maxv = etl.limits(table, 'bar') >>> minv 1 >>> maxv 3 The `field` ...
[ "def", "limits", "(", "table", ",", "field", ")", ":", "vals", "=", "iter", "(", "values", "(", "table", ",", "field", ")", ")", "try", ":", "minv", "=", "maxv", "=", "next", "(", "vals", ")", "except", "StopIteration", ":", "return", "None", ",", ...
23.321429
21.107143
def enter_node(self, ir_node): """ Enter the given element; keeps track of `cdata`; subclasses may extend by overriding """ this_is_cdata = (isinstance(ir_node, Element) and ir_node.name in self.cdata_elements) self.state['is_cdata'] = bool(self.s...
[ "def", "enter_node", "(", "self", ",", "ir_node", ")", ":", "this_is_cdata", "=", "(", "isinstance", "(", "ir_node", ",", "Element", ")", "and", "ir_node", ".", "name", "in", "self", ".", "cdata_elements", ")", "self", ".", "state", "[", "'is_cdata'", "]...
43.875
13.625
def to_rectified(self, x, y): """ Convert the input (x, y) positions from the original (unrectified) image to the rectified image. Parameters ---------- x, y: float or array-like of float The zero-index pixel coordinates in the original (unrectif...
[ "def", "to_rectified", "(", "self", ",", "x", ",", "y", ")", ":", "return", "self", ".", "_reproject", "(", "self", ".", "wcs_original", ",", "self", ".", "wcs_rectified", ")", "(", "x", ",", "y", ")" ]
30
18.210526
def match_member_id(self, member_conf, current_member_confs): """ Attempts to find an id for member_conf where fom current members confs there exists a element. Returns the id of an element of current confs WHERE member_conf.host and element.host are EQUAL or map to same host ...
[ "def", "match_member_id", "(", "self", ",", "member_conf", ",", "current_member_confs", ")", ":", "if", "current_member_confs", "is", "None", ":", "return", "None", "for", "curr_mem_conf", "in", "current_member_confs", ":", "if", "is_same_address", "(", "member_conf...
38.133333
18.933333
def get_start_time_metadata(self): """Gets the metadata for the assessment start time. return: (osid.Metadata) - metadata for the start time *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_meta...
[ "def", "get_start_time_metadata", "(", "self", ")", ":", "# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template", "metadata", "=", "dict", "(", "self", ".", "_mdata", "[", "'start_time'", "]", ")", "metadata", ".", "update", "(", "{", "'...
44.727273
22.181818
def split(self, split_on): """ Splits the AST if its operation is `split_on` (i.e., return all the arguments). Otherwise, return a list with just the AST. """ if self.op in split_on: return list(self.args) else: return [ self ]
[ "def", "split", "(", "self", ",", "split_on", ")", ":", "if", "self", ".", "op", "in", "split_on", ":", "return", "list", "(", "self", ".", "args", ")", "else", ":", "return", "[", "self", "]" ]
38.428571
19.285714
def textrank(self, sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'), withFlag=False): """ Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, re...
[ "def", "textrank", "(", "self", ",", "sentence", ",", "topK", "=", "20", ",", "withWeight", "=", "False", ",", "allowPOS", "=", "(", "'ns'", ",", "'n'", ",", "'vn'", ",", "'v'", ")", ",", "withFlag", "=", "False", ")", ":", "self", ".", "pos_filt",...
42.55
18.95
def sample(self, n=1): """ Returns one or more samples from this probability distribution. :param int n: Number of samples to return. :return numpy.ndarray: An array containing samples from the distribution of shape ``(n, d)``, where ``d`` is the number of random...
[ "def", "sample", "(", "self", ",", "n", "=", "1", ")", ":", "samples", "=", "np", ".", "empty", "(", "(", "n", ",", "self", ".", "n_rvs", ")", ")", "idxs_to_sample", "=", "np", ".", "arange", "(", "n", ")", "iters", "=", "0", "while", "idxs_to_...
33.851852
25.777778
def plot_energy( data, kind="kde", bfmi=True, figsize=None, legend=True, fill_alpha=(1, 0.75), fill_color=("C0", "C5"), bw=4.5, textsize=None, fill_kwargs=None, plot_kwargs=None, ax=None, ): """Plot energy transition distribution and marginal energy distribution in HM...
[ "def", "plot_energy", "(", "data", ",", "kind", "=", "\"kde\"", ",", "bfmi", "=", "True", ",", "figsize", "=", "None", ",", "legend", "=", "True", ",", "fill_alpha", "=", "(", "1", ",", "0.75", ")", ",", "fill_color", "=", "(", "\"C0\"", ",", "\"C5...
29.264706
23.875
def s_to_ev(offset_us, source_to_detector_m, array): """convert time (s) to energy (eV) Parameters: =========== numpy array of time in s offset_us: float. Delay of detector in us source_to_detector_m: float. Distance source to detector in m Returns: ======== numpy array of energy in...
[ "def", "s_to_ev", "(", "offset_us", ",", "source_to_detector_m", ",", "array", ")", ":", "lambda_a", "=", "3956.", "*", "(", "array", "+", "offset_us", "*", "1e-6", ")", "/", "source_to_detector_m", "return", "(", "81.787", "/", "pow", "(", "lambda_a", ","...
31.285714
17.642857
def portfolio_byvalue( weights, steps, min_values, max_values=1e9, total_portfolio_value=10000 ): """ For a long only portfolio, convert the continuous weights to a discrete allocation using Mixed Integer Linear Programming. This function assumes that we buy some asset based on value instead of shar...
[ "def", "portfolio_byvalue", "(", "weights", ",", "steps", ",", "min_values", ",", "max_values", "=", "1e9", ",", "total_portfolio_value", "=", "10000", ")", ":", "import", "pulp", "if", "not", "isinstance", "(", "weights", ",", "dict", ")", ":", "raise", "...
42.359375
19.515625
def convert_linalg_gemm2(node, **kwargs): """Map MXNet's _linalg_gemm2 operator attributes to onnx's MatMul and Transpose operators based on the values set for transpose_a, transpose_b attributes. Return multiple nodes created. """ name, input_nodes, attrs = get_inputs(node, kwargs) # Getti...
[ "def", "convert_linalg_gemm2", "(", "node", ",", "*", "*", "kwargs", ")", ":", "name", ",", "input_nodes", ",", "attrs", "=", "get_inputs", "(", "node", ",", "kwargs", ")", "# Getting the attributes and assigning default values.", "alpha", "=", "float", "(", "at...
29.108434
15.674699
def _parse_wikiheadlines(path): """Generates examples from Wikiheadlines dataset file.""" lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])$", path) assert lang_match is not None, "Invalid Wikiheadlines filename: %s" % path l1, l2 = lang_match.groups() with tf.io.gfile.GFile(path) as f: for line in f:...
[ "def", "_parse_wikiheadlines", "(", "path", ")", ":", "lang_match", "=", "re", ".", "match", "(", "r\".*\\.([a-z][a-z])-([a-z][a-z])$\"", ",", "path", ")", "assert", "lang_match", "is", "not", "None", ",", "\"Invalid Wikiheadlines filename: %s\"", "%", "path", "l1",...
34.583333
17
def detect(abf,sweep=None,threshold_upslope=50,dT=.1,saveToo=True): """ An AP will be detected by a upslope that exceeds 50V/s. Analyzed too. if type(sweep) is int, graph int(sweep) if sweep==None, process all sweeps sweep. """ if type(sweep) is int: sweeps=[sweep] else: ...
[ "def", "detect", "(", "abf", ",", "sweep", "=", "None", ",", "threshold_upslope", "=", "50", ",", "dT", "=", ".1", ",", "saveToo", "=", "True", ")", ":", "if", "type", "(", "sweep", ")", "is", "int", ":", "sweeps", "=", "[", "sweep", "]", "else",...
44.325581
18.27907
def remove_temporary_source(self): """Remove the source files from this requirement, if they are marked for deletion""" if self.is_bundle or os.path.exists(self.delete_marker_filename): logger.info('Removing source in %s' % self.source_dir) if self.source_dir: ...
[ "def", "remove_temporary_source", "(", "self", ")", ":", "if", "self", ".", "is_bundle", "or", "os", ".", "path", ".", "exists", "(", "self", ".", "delete_marker_filename", ")", ":", "logger", ".", "info", "(", "'Removing source in %s'", "%", "self", ".", ...
47.636364
10.818182
def add_to_session(request, template_name="index.html", **kwargs): 'Add some info to a session in a place that django-plotly-dash can pass to a callback' django_plotly_dash = request.session.get("django_plotly_dash", dict()) session_add_count = django_plotly_dash.get('add_counter', 0) django_plotly_da...
[ "def", "add_to_session", "(", "request", ",", "template_name", "=", "\"index.html\"", ",", "*", "*", "kwargs", ")", ":", "django_plotly_dash", "=", "request", ".", "session", ".", "get", "(", "\"django_plotly_dash\"", ",", "dict", "(", ")", ")", "session_add_c...
47.2
31.2
def send_markdown(self, agent_id, user_ids, content, party_ids='', tag_ids=''): """markdown消息 https://work.weixin.qq.com/api/doc#90000/90135/90236/markdown%E6%B6%88%E6%81%AF > 目前仅支持markdown语法的子集 > 微工作台(原企业号)不支持展示markdown消息 :param agent_id: 企业应用的id,整型。可在应用的设置页面查看 :type ...
[ "def", "send_markdown", "(", "self", ",", "agent_id", ",", "user_ids", ",", "content", ",", "party_ids", "=", "''", ",", "tag_ids", "=", "''", ")", ":", "msg", "=", "{", "\"msgtype\"", ":", "\"markdown\"", ",", "\"markdown\"", ":", "{", "\"content\"", ":...
33.69697
16.666667
def reverse(viewname, subdomain=None, scheme=None, args=None, kwargs=None, current_app=None): """ Reverses a URL from the given parameters, in a similar fashion to :meth:`django.core.urlresolvers.reverse`. :param viewname: the name of URL :param subdomain: the subdomain to use for URL rever...
[ "def", "reverse", "(", "viewname", ",", "subdomain", "=", "None", ",", "scheme", "=", "None", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "current_app", "=", "None", ")", ":", "urlconf", "=", "settings", ".", "SUBDOMAIN_URLCONFS", ".", "...
41.363636
20
def t_less_variable(self, t): r'@@?[\w-]+|@\{[^@\}]+\}' v = t.value.lower() if v in reserved.tokens: t.type = reserved.tokens[v] if t.type == "css_media": t.lexer.push_state("mediaquery") elif t.type == "css_import": t.lexer.pus...
[ "def", "t_less_variable", "(", "self", ",", "t", ")", ":", "v", "=", "t", ".", "value", ".", "lower", "(", ")", "if", "v", "in", "reserved", ".", "tokens", ":", "t", ".", "type", "=", "reserved", ".", "tokens", "[", "v", "]", "if", "t", ".", ...
34.5
7.9
def get_bundle_imported_services(self, bundle): """ Returns this bundle's ServiceReference list for all services it is using or returns None if this bundle is not using any services. A bundle is considered to be using a service if its use count for that service is greater than ze...
[ "def", "get_bundle_imported_services", "(", "self", ",", "bundle", ")", ":", "with", "self", ".", "__svc_lock", ":", "return", "sorted", "(", "self", ".", "__bundle_imports", ".", "get", "(", "bundle", ",", "[", "]", ")", ")" ]
45.3125
21.1875
def loadTargetPatterns(self, filename, cols = None, everyNrows = 1, delim = ' ', checkEven = 1): """ Loads targets as patterns from file. """ self.loadTargetPatternssFromFile(filename, cols, everyNrows, delim, checkEven...
[ "def", "loadTargetPatterns", "(", "self", ",", "filename", ",", "cols", "=", "None", ",", "everyNrows", "=", "1", ",", "delim", "=", "' '", ",", "checkEven", "=", "1", ")", ":", "self", ".", "loadTargetPatternssFromFile", "(", "filename", ",", "cols", ",...
45
13.285714
def parse_gpr(str_expr): """parse gpr into AST Parameters ---------- str_expr : string string with the gene reaction rule to parse Returns ------- tuple elements ast_tree and gene_ids as a set """ str_expr = str_expr.strip() if len(str_expr) == 0: return...
[ "def", "parse_gpr", "(", "str_expr", ")", ":", "str_expr", "=", "str_expr", ".", "strip", "(", ")", "if", "len", "(", "str_expr", ")", "==", "0", ":", "return", "None", ",", "set", "(", ")", "for", "char", ",", "escaped", "in", "replacements", ":", ...
29.423077
17.807692
def mine_sub_trees(self, threshold): """ Generate subtrees and mine them for patterns. """ patterns = {} mining_order = sorted(self.frequent.keys(), key=lambda x: self.frequent[x]) # Get items in tree in reverse order of occurrences. ...
[ "def", "mine_sub_trees", "(", "self", ",", "threshold", ")", ":", "patterns", "=", "{", "}", "mining_order", "=", "sorted", "(", "self", ".", "frequent", ".", "keys", "(", ")", ",", "key", "=", "lambda", "x", ":", "self", ".", "frequent", "[", "x", ...
35.875
15.583333
def add_input_variable(self, var): """Adds the argument variable as one of the input variable""" assert(isinstance(var, Variable)) self.input_variable_list.append(var)
[ "def", "add_input_variable", "(", "self", ",", "var", ")", ":", "assert", "(", "isinstance", "(", "var", ",", "Variable", ")", ")", "self", ".", "input_variable_list", ".", "append", "(", "var", ")" ]
47
2.75
def atlas_peer_get_health( peer_hostport, peer_table=None ): """ Get the health score for a peer. Health is: (number of responses received / number of requests sent) """ with AtlasPeerTableLocked(peer_table) as ptbl: # availability score: number of responses / number of requests num...
[ "def", "atlas_peer_get_health", "(", "peer_hostport", ",", "peer_table", "=", "None", ")", ":", "with", "AtlasPeerTableLocked", "(", "peer_table", ")", "as", "ptbl", ":", "# availability score: number of responses / number of requests", "num_responses", "=", "0", "num_req...
35
15.8
def receivables_account(self) -> Account: """ Returns receivables account. Receivables account is assumed to be the one were invoice rows were recorded. :return: Account or None """ row = AccountEntry.objects.filter(source_invoice=self).order_by('id').first() return row.a...
[ "def", "receivables_account", "(", "self", ")", "->", "Account", ":", "row", "=", "AccountEntry", ".", "objects", ".", "filter", "(", "source_invoice", "=", "self", ")", ".", "order_by", "(", "'id'", ")", ".", "first", "(", ")", "return", "row", ".", "...
48.142857
18.714286
def replace(iterable, pred, substitutes, count=None, window_size=1): """Yield the items from *iterable*, replacing the items for which *pred* returns ``True`` with the items from the iterable *substitutes*. >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1] >>> pred = lambda x: x == 0 >>> substitu...
[ "def", "replace", "(", "iterable", ",", "pred", ",", "substitutes", ",", "count", "=", "None", ",", "window_size", "=", "1", ")", ":", "if", "window_size", "<", "1", ":", "raise", "ValueError", "(", "'window_size must be at least 1'", ")", "# Save the substitu...
40.152542
21.389831
def get_index(self, label): """ Find the index of the input ``label``. Parameters ---------- labels : int The label numbers to find. Returns ------- index : int The array index. Raises ------ ValueError ...
[ "def", "get_index", "(", "self", ",", "label", ")", ":", "self", ".", "check_labels", "(", "label", ")", "return", "np", ".", "searchsorted", "(", "self", ".", "labels", ",", "label", ")" ]
19.545455
19.272727
def _represent_ordereddict(dump, tag, mapping, flow_style=None): """PyYAML representer function for OrderedDict. This is needed for yaml.safe_dump() to support OrderedDict. Courtesy: https://blog.elsdoerfer.name/2012/07/26/make-pyyaml-output-an-ordereddict/ """ value = [] node = yaml.Mappin...
[ "def", "_represent_ordereddict", "(", "dump", ",", "tag", ",", "mapping", ",", "flow_style", "=", "None", ")", ":", "value", "=", "[", "]", "node", "=", "yaml", ".", "MappingNode", "(", "tag", ",", "value", ",", "flow_style", "=", "flow_style", ")", "i...
41
15.333333
def keys(self): """Get all the block names in the dataset""" names = [] for i in range(self.n_blocks): names.append(self.get_block_name(i)) return names
[ "def", "keys", "(", "self", ")", ":", "names", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "n_blocks", ")", ":", "names", ".", "append", "(", "self", ".", "get_block_name", "(", "i", ")", ")", "return", "names" ]
31.833333
12.833333
def parse_field(data, field_cfg, target, is_optional=False): """ Recursively parses response according to configuration :param data: response or its part :param field_cfg: field configuration :param target: target object for parsed data :param is_optional: optional sign ...
[ "def", "parse_field", "(", "data", ",", "field_cfg", ",", "target", ",", "is_optional", "=", "False", ")", ":", "field_type", "=", "field_cfg", "[", "Field", ".", "FIELD_TYPE", "]", "field_key", "=", "field_cfg", "[", "Field", ".", "FIELD_KEY", "]", "if", ...
49.532258
18.854839
def create_network(self, tenant_name, network, subnet, dhcp_range=True): """Create network on the DCNM. :param tenant_name: name of tenant the network belongs to :param network: network parameters :param subnet: subnet parameters of the network """ ...
[ "def", "create_network", "(", "self", ",", "tenant_name", ",", "network", ",", "subnet", ",", "dhcp_range", "=", "True", ")", ":", "seg_id", "=", "str", "(", "network", ".", "segmentation_id", ")", "subnet_ip_mask", "=", "subnet", ".", "cidr", ".", "split"...
41.5
16.548387
def item_enclosure_url(self, item): """ Return an image for enclosure. """ try: url = item.image.url except (AttributeError, ValueError): img = BeautifulSoup(item.html_content, 'html.parser').find('img') url = img.get('src') if img else None ...
[ "def", "item_enclosure_url", "(", "self", ",", "item", ")", ":", "try", ":", "url", "=", "item", ".", "image", ".", "url", "except", "(", "AttributeError", ",", "ValueError", ")", ":", "img", "=", "BeautifulSoup", "(", "item", ".", "html_content", ",", ...
34.866667
10.866667
def _spectrum(self, photon_energy): """Compute intrinsic synchrotron differential spectrum for energies in ``photon_energy`` Compute synchrotron for random magnetic field according to approximation of Aharonian, Kelner, and Prosekin 2010, PhysRev D 82, 3002 (`arXiv:1006.1045 <ht...
[ "def", "_spectrum", "(", "self", ",", "photon_energy", ")", ":", "outspecene", "=", "_validate_ene", "(", "photon_energy", ")", "from", "scipy", ".", "special", "import", "cbrt", "def", "Gtilde", "(", "x", ")", ":", "\"\"\"\n AKP10 Eq. D7\n\n ...
30.724638
20.623188
def update_checksum(self, progress_callback=None, chunk_size=None, checksum_kwargs=None, **kwargs): """Update checksum based on file.""" self.checksum = self.storage(**kwargs).checksum( progress_callback=progress_callback, chunk_size=chunk_size, **(checksu...
[ "def", "update_checksum", "(", "self", ",", "progress_callback", "=", "None", ",", "chunk_size", "=", "None", ",", "checksum_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "checksum", "=", "self", ".", "storage", "(", "*", "*", "...
55.166667
15.166667
def plotSkymapCatalog(lon,lat,**kwargs): """ Plot a catalog of coordinates on a full-sky map. """ fig = plt.figure() ax = plt.subplot(111,projection=projection) drawSkymapCatalog(ax,lon,lat,**kwargs)
[ "def", "plotSkymapCatalog", "(", "lon", ",", "lat", ",", "*", "*", "kwargs", ")", ":", "fig", "=", "plt", ".", "figure", "(", ")", "ax", "=", "plt", ".", "subplot", "(", "111", ",", "projection", "=", "projection", ")", "drawSkymapCatalog", "(", "ax"...
31
5.571429
def create_placeholder(self, slot="blog_contents", role='m', title=None): """ Create a placeholder on this blog entry. To fill the content items, use :func:`ContentItemModel.objects.create_for_placeholder() <fluent_contents.models.managers.ContentItemManager.create_for_placeholder>`. ...
[ "def", "create_placeholder", "(", "self", ",", "slot", "=", "\"blog_contents\"", ",", "role", "=", "'m'", ",", "title", "=", "None", ")", ":", "return", "Placeholder", ".", "objects", ".", "create_for_object", "(", "self", ",", "slot", ",", "role", "=", ...
47.1
29.3
def get_label(self, function = None, offset = None): """ Retrieves the label for the given function of this module or the module base address if no function name is given. @type function: str @param function: (Optional) Exported function name. @type offset: int ...
[ "def", "get_label", "(", "self", ",", "function", "=", "None", ",", "offset", "=", "None", ")", ":", "return", "_ModuleContainer", ".", "parse_label", "(", "self", ".", "get_name", "(", ")", ",", "function", ",", "offset", ")" ]
37.4
23.4
def bismark_alignment_chart (self): """ Make the alignment plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['aligned_reads'] = { 'color': '#2f7ed8', 'name': 'Aligned Uniquely' } keys['ambig_reads'] = { 'color': '#492970', 'name': ...
[ "def", "bismark_alignment_chart", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "keys", "[", "'aligned_reads'", "]", "=", "{", "'color'", ":", "'#2f7ed8'", ",", "'name'", ":", "'Aligned Uniquel...
40.130435
22.869565