text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _validate(self, val): """ val must be None or one of the objects in self.objects. """ if not self.check_on_set: self._ensure_value_is_in_objects(val) return if not (val in self.objects or (self.allow_None and val is None)): # CEBALERT: can...
[ "def", "_validate", "(", "self", ",", "val", ")", ":", "if", "not", "self", ".", "check_on_set", ":", "self", ".", "_ensure_value_is_in_objects", "(", "val", ")", "return", "if", "not", "(", "val", "in", "self", ".", "objects", "or", "(", "self", ".", ...
36.2
16.133333
def ip_allocate(self, linode, public=True): """ Allocates an IP to a Instance you own. Additional IPs must be requested by opening a support ticket first. :param linode: The Instance to allocate the new IP for. :type linode: Instance or int :param public: If True, alloc...
[ "def", "ip_allocate", "(", "self", ",", "linode", ",", "public", "=", "True", ")", ":", "result", "=", "self", ".", "client", ".", "post", "(", "'/networking/ipv4/'", ",", "data", "=", "{", "\"linode_id\"", ":", "linode", ".", "id", "if", "isinstance", ...
35.64
20.92
def _execute_request(self, request): """Helper method to execute a request, since a lock should be used to not fire up multiple requests at the same time. :return: Result of `request.execute` """ with GoogleCloudProvider.__gce_lock: return request.execute(http=self._...
[ "def", "_execute_request", "(", "self", ",", "request", ")", ":", "with", "GoogleCloudProvider", ".", "__gce_lock", ":", "return", "request", ".", "execute", "(", "http", "=", "self", ".", "_auth_http", ")" ]
40.375
10.75
def daOnes(shap, dtype=numpy.float): """ One constructor for numpy distributed array @param shap the shape of the array @param dtype the numpy data type """ res = DistArray(shap, dtype) res[:] = 1 return res
[ "def", "daOnes", "(", "shap", ",", "dtype", "=", "numpy", ".", "float", ")", ":", "res", "=", "DistArray", "(", "shap", ",", "dtype", ")", "res", "[", ":", "]", "=", "1", "return", "res" ]
25.666667
8.555556
def get_result(self, course_grade): """ Get result for the statement. Arguments: course_grade (CourseGrade): Course grade. """ return Result( score=Score( scaled=course_grade.percent, raw=course_grade.percent * 100, ...
[ "def", "get_result", "(", "self", ",", "course_grade", ")", ":", "return", "Result", "(", "score", "=", "Score", "(", "scaled", "=", "course_grade", ".", "percent", ",", "raw", "=", "course_grade", ".", "percent", "*", "100", ",", "min", "=", "MIN_SCORE"...
27.470588
12.176471
def _is_dir(fs, path): """ Check that the given path is a directory. Note that unlike `os.path.isdir`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bubble up. """ try: ...
[ "def", "_is_dir", "(", "fs", ",", "path", ")", ":", "try", ":", "return", "stat", ".", "S_ISDIR", "(", "fs", ".", "stat", "(", "path", ")", ".", "st_mode", ")", "except", "exceptions", ".", "FileNotFound", ":", "return", "False" ]
29.285714
21.857143
def autopep8(self, **kwargs): # pragma: no cover """ Auto convert your python code in a directory to pep8 styled code. :param kwargs: arguments for ``autopep8.fix_code`` method. **中文文档** 将目录下的所有Python文件用pep8风格格式化。增加其可读性和规范性。 """ self.assert_is_dir_and_exists()...
[ "def", "autopep8", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "self", ".", "assert_is_dir_and_exists", "(", ")", "for", "p", "in", "self", ".", "select_by_ext", "(", "\".py\"", ")", ":", "with", "open", "(", "p", ".", "abspath"...
30.25
19.65
def create_error_handlers(blueprint, error_handlers_registry=None): """Create error handlers on blueprint. :params blueprint: Records API blueprint. :params error_handlers_registry: Configuration of error handlers per exception or HTTP status code and view name. The dictionary has the foll...
[ "def", "create_error_handlers", "(", "blueprint", ",", "error_handlers_registry", "=", "None", ")", ":", "error_handlers_registry", "=", "error_handlers_registry", "or", "{", "}", "# Catch record validation errors", "@", "blueprint", ".", "errorhandler", "(", "ValidationE...
38.285714
20.619048
def run(X_train, X_test, y_train, y_test, PARAMS): '''Train model and predict result''' model.fit(X_train, y_train) predict_y = model.predict(X_test) score = r2_score(y_test, predict_y) LOG.debug('r2 score: %s' % score) nni.report_final_result(score)
[ "def", "run", "(", "X_train", ",", "X_test", ",", "y_train", ",", "y_test", ",", "PARAMS", ")", ":", "model", ".", "fit", "(", "X_train", ",", "y_train", ")", "predict_y", "=", "model", ".", "predict", "(", "X_test", ")", "score", "=", "r2_score", "(...
38.285714
4.571429
def add_imports(): """Add Imports""" text, ok = QtGui.QInputDialog.getText(None, 'Add Import', 'Enter an import line to add (example: from os import path or os.path):') if ok: sort_kate_imports(add_imports=text.split...
[ "def", "add_imports", "(", ")", ":", "text", ",", "ok", "=", "QtGui", ".", "QInputDialog", ".", "getText", "(", "None", ",", "'Add Import'", ",", "'Enter an import line to add (example: from os import path or os.path):'", ")", "if", "ok", ":", "sort_kate_imports", "...
45.714286
23.285714
def coord(self, func:CoordFunc, *args, **kwargs)->'Image': "Equivalent to `image.flow = func(image.flow, image.size)`." self.flow = func(self.flow, *args, **kwargs) return self
[ "def", "coord", "(", "self", ",", "func", ":", "CoordFunc", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "'Image'", ":", "self", ".", "flow", "=", "func", "(", "self", ".", "flow", ",", "*", "args", ",", "*", "*", "kwargs", ")", "retur...
49.25
19.75
def main(): ''' set things up ''' configs = setup(argparse.ArgumentParser()) harvester = GreyHarvester( test_domain=configs['test_domain'], test_sleeptime=TEST_SLEEPTIME, https_only=configs['https_only'], allowed_countries=configs['allowed_countries'], denied_countr...
[ "def", "main", "(", ")", ":", "configs", "=", "setup", "(", "argparse", ".", "ArgumentParser", "(", ")", ")", "harvester", "=", "GreyHarvester", "(", "test_domain", "=", "configs", "[", "'test_domain'", "]", ",", "test_sleeptime", "=", "TEST_SLEEPTIME", ",",...
29.904762
16.47619
def build_body(cls: Type[AN], body: List[ast.stmt]) -> List: """ Note: Return type is probably ``-> List[AN]``, but can't get it to pass. """ act_nodes = [] # type: List[ActNode] for child_node in body: act_nodes += ActNode.build(child_node) retur...
[ "def", "build_body", "(", "cls", ":", "Type", "[", "AN", "]", ",", "body", ":", "List", "[", "ast", ".", "stmt", "]", ")", "->", "List", ":", "act_nodes", "=", "[", "]", "# type: List[ActNode]", "for", "child_node", "in", "body", ":", "act_nodes", "+...
35.888889
13.888889
def run_simple( hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, reloader_type="auto", threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, s...
[ "def", "run_simple", "(", "hostname", ",", "port", ",", "application", ",", "use_reloader", "=", "False", ",", "use_debugger", "=", "False", ",", "use_evalex", "=", "True", ",", "extra_files", "=", "None", ",", "reloader_interval", "=", "1", ",", "reloader_t...
39.80226
21.977401
def capability(self, data: ['SASdata', str] = None, by: str = None, cdfplot: str = None, comphist: str = None, freq: str = None, histogram: str = None, id: str = None, inset: str = None, ...
[ "def", "capability", "(", "self", ",", "data", ":", "[", "'SASdata'", ",", "str", "]", "=", "None", ",", "by", ":", "str", "=", "None", ",", "cdfplot", ":", "str", "=", "None", ",", "comphist", ":", "str", "=", "None", ",", "freq", ":", "str", ...
54.813953
22.162791
def get(self, href): """Fetch a single item.""" if self.is_fake: return uid = _trim_suffix(href, ('.ics', '.ical', '.vcf')) etesync_item = self.collection.get(uid) if etesync_item is None: return None try: item = vobject.readOne(etesy...
[ "def", "get", "(", "self", ",", "href", ")", ":", "if", "self", ".", "is_fake", ":", "return", "uid", "=", "_trim_suffix", "(", "href", ",", "(", "'.ics'", ",", "'.ical'", ",", "'.vcf'", ")", ")", "etesync_item", "=", "self", ".", "collection", ".", ...
36.25
17.65
def get_version(self): """Fetches the current version number of the Graph API being used.""" args = {"access_token": self.access_token} try: response = self.session.request( "GET", FACEBOOK_GRAPH_URL + self.version + "/me", params=args,...
[ "def", "get_version", "(", "self", ")", ":", "args", "=", "{", "\"access_token\"", ":", "self", ".", "access_token", "}", "try", ":", "response", "=", "self", ".", "session", ".", "request", "(", "\"GET\"", ",", "FACEBOOK_GRAPH_URL", "+", "self", ".", "v...
36.47619
14.142857
def __createHTMNetwork(self, sensorParams, spEnable, spParams, tmEnable, tmParams, clEnable, clParams, anomalyParams): """ Create a CLA network and return it. description: HTMPredictionModel description dictionary (TODO: define schema) Returns: NetworkInfo instance; """ ...
[ "def", "__createHTMNetwork", "(", "self", ",", "sensorParams", ",", "spEnable", ",", "spParams", ",", "tmEnable", ",", "tmParams", ",", "clEnable", ",", "clParams", ",", "anomalyParams", ")", ":", "#--------------------------------------------------", "# Create the netw...
38.604839
22.459677
def set_symbol(self, symbol): """(symbol, bondorder) -> set the bondsymbol of the molecule""" raise "Deprecated" self.symbol, self.bondtype, bondorder, self.equiv_class = \ BONDLOOKUP[symbol] if self.bondtype == 4: self.aromatic = 1 else: ...
[ "def", "set_symbol", "(", "self", ",", "symbol", ")", ":", "raise", "\"Deprecated\"", "self", ".", "symbol", ",", "self", ".", "bondtype", ",", "bondorder", ",", "self", ".", "equiv_class", "=", "BONDLOOKUP", "[", "symbol", "]", "if", "self", ".", "bondt...
34
11.2
def set_memory_cache(self, results, key=None): """Store result in memory cache with key matching model state.""" key = self.model.hash if key is None else key self.memory_cache[key] = results
[ "def", "set_memory_cache", "(", "self", ",", "results", ",", "key", "=", "None", ")", ":", "key", "=", "self", ".", "model", ".", "hash", "if", "key", "is", "None", "else", "key", "self", ".", "memory_cache", "[", "key", "]", "=", "results" ]
53
4.75
def close(self): """End the report.""" endpoint = self.endpoint.replace("/api/v1/spans", "") logger.debug("Zipkin trace may be located at this URL {}/traces/{}".format(endpoint, self.trace_id))
[ "def", "close", "(", "self", ")", ":", "endpoint", "=", "self", ".", "endpoint", ".", "replace", "(", "\"/api/v1/spans\"", ",", "\"\"", ")", "logger", ".", "debug", "(", "\"Zipkin trace may be located at this URL {}/traces/{}\"", ".", "format", "(", "endpoint", ...
40.4
29
def decorate_cls_with_validation(cls, field_name, # type: str *validation_func, # type: ValidationFuncs **kwargs): # type: (...) -> Type[Any] """ This method is equivalent to decorating a class with th...
[ "def", "decorate_cls_with_validation", "(", "cls", ",", "field_name", ",", "# type: str", "*", "validation_func", ",", "# type: ValidationFuncs", "*", "*", "kwargs", ")", ":", "# type: (...) -> Type[Any]", "error_type", ",", "help_msg", ",", "none_policy", "=", "pop_k...
57.129496
35.143885
def write_inquiry_scan_activity(sock, interval, window): """returns 0 on success, -1 on failure""" # save current filter old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # Setup socket filter to receive only events related to the # write_inquiry_mode command flt = bluez.hci_fi...
[ "def", "write_inquiry_scan_activity", "(", "sock", ",", "interval", ",", "window", ")", ":", "# save current filter", "old_filter", "=", "sock", ".", "getsockopt", "(", "bluez", ".", "SOL_HCI", ",", "bluez", ".", "HCI_FILTER", ",", "14", ")", "# Setup socket fil...
35.892857
18.857143
def _ParseNoHeaderSingleLine(self, parser_mediator, structure): """Parse an isolated header line and store appropriate attributes. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. structure (pyparsing.ParseResul...
[ "def", "_ParseNoHeaderSingleLine", "(", "self", ",", "parser_mediator", ",", "structure", ")", ":", "if", "not", "self", ".", "_last_event_data", ":", "logger", ".", "debug", "(", "'SkyDrive, found isolated line with no previous events'", ")", "return", "event_data", ...
39.333333
20.708333
def colorscale(mag, cmin, cmax): """ Return a tuple of floats between 0 and 1 for R, G, and B. From Python Cookbook (9.11?) """ # Normalize to 0-1 try: x = float(mag-cmin)/(cmax-cmin) except ZeroDivisionError: x = 0.5 # cmax == cmin blue = min((max((4*(0.75-x), 0.)), 1.)...
[ "def", "colorscale", "(", "mag", ",", "cmin", ",", "cmax", ")", ":", "# Normalize to 0-1", "try", ":", "x", "=", "float", "(", "mag", "-", "cmin", ")", "/", "(", "cmax", "-", "cmin", ")", "except", "ZeroDivisionError", ":", "x", "=", "0.5", "# cmax =...
30.642857
9.642857
def abspath(path, ref=None): """ Create an absolute path. Parameters ---------- path : str absolute or relative path with respect to `ref` ref : str or None reference path if `path` is relative Returns ------- path : str absolute path Raises ------ ...
[ "def", "abspath", "(", "path", ",", "ref", "=", "None", ")", ":", "if", "ref", ":", "path", "=", "os", ".", "path", ".", "join", "(", "ref", ",", "path", ")", "if", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "raise", "Valu...
20.807692
21.423077
def get_long_query(self, base_object_query, limit_to=100, max_calls=None, start_record=0, verbose=False): """ Takes a base query for all objects and recursively requests them :param str base_object_query: the base query to be executed :param int limit_to: how many...
[ "def", "get_long_query", "(", "self", ",", "base_object_query", ",", "limit_to", "=", "100", ",", "max_calls", "=", "None", ",", "start_record", "=", "0", ",", "verbose", "=", "False", ")", ":", "if", "verbose", ":", "print", "(", "base_object_query", ")",...
37.770492
22.163934
def remove_decorator(source: str): """Remove decorators from function definition""" lines = source.splitlines() atok = asttokens.ASTTokens(source, parse=True) for node in ast.walk(atok.tree): if isinstance(node, ast.FunctionDef): break if node.decorator_list: deco_first...
[ "def", "remove_decorator", "(", "source", ":", "str", ")", ":", "lines", "=", "source", ".", "splitlines", "(", ")", "atok", "=", "asttokens", ".", "ASTTokens", "(", "source", ",", "parse", "=", "True", ")", "for", "node", "in", "ast", ".", "walk", "...
34.277778
18.166667
def exceptions_log_path(cls, for_pid=None, in_dir=None): """Get the path to either the shared or pid-specific fatal errors log file.""" if for_pid is None: intermediate_filename_component = '' else: assert(isinstance(for_pid, IntegerForPid)) intermediate_filename_component = '.{}'.format(f...
[ "def", "exceptions_log_path", "(", "cls", ",", "for_pid", "=", "None", ",", "in_dir", "=", "None", ")", ":", "if", "for_pid", "is", "None", ":", "intermediate_filename_component", "=", "''", "else", ":", "assert", "(", "isinstance", "(", "for_pid", ",", "I...
39.25
16.25
def alpha(self, theta_x, theta_y, kwargs_lens, k=None): """ reduced deflection angle :param theta_x: angle in x-direction :param theta_y: angle in y-direction :param kwargs_lens: lens model kwargs :return: """ beta_x, beta_y = self.ray_shooting(theta_x, t...
[ "def", "alpha", "(", "self", ",", "theta_x", ",", "theta_y", ",", "kwargs_lens", ",", "k", "=", "None", ")", ":", "beta_x", ",", "beta_y", "=", "self", ".", "ray_shooting", "(", "theta_x", ",", "theta_y", ",", "kwargs_lens", ")", "alpha_x", "=", "theta...
33.076923
11.846154
def _Backward2_T_Ph(P, h): """Backward equation for region 2, T=f(P,h) Parameters ---------- P : float Pressure, [MPa] h : float Specific enthalpy, [kJ/kg] Returns ------- T : float Temperature, [K] """ if P <= 4: T = _Backward2a_T_Ph(P, h) e...
[ "def", "_Backward2_T_Ph", "(", "P", ",", "h", ")", ":", "if", "P", "<=", "4", ":", "T", "=", "_Backward2a_T_Ph", "(", "P", ",", "h", ")", "elif", "4", "<", "P", "<=", "6.546699678", ":", "T", "=", "_Backward2b_T_Ph", "(", "P", ",", "h", ")", "e...
19.366667
19.766667
def _write(self, s, s_length=None, flush=False, ignore_overflow=False, err_msg=None): """Write ``s`` :type s: str|unicode :param s: String to write :param s_length: Custom length of ``s`` :param flush: Set this to flush the terminal stream after writing :...
[ "def", "_write", "(", "self", ",", "s", ",", "s_length", "=", "None", ",", "flush", "=", "False", ",", "ignore_overflow", "=", "False", ",", "err_msg", "=", "None", ")", ":", "if", "not", "ignore_overflow", ":", "s_length", "=", "len", "(", "s", ")",...
40.28
16.96
def visit_FunctionCall(self, node): """Visitor for `FunctionCall` AST node.""" function_name = node.identifier.name call = self.table[function_name] if call is None: raise SementicError(f"Function `{function_name}` not declared.") else: call = call._node ...
[ "def", "visit_FunctionCall", "(", "self", ",", "node", ")", ":", "function_name", "=", "node", ".", "identifier", ".", "name", "call", "=", "self", ".", "table", "[", "function_name", "]", "if", "call", "is", "None", ":", "raise", "SementicError", "(", "...
35.551724
17.482759
def _next(self, request, application, roles, next_config): """ Continue the state machine at given state. """ # we only support state changes for POST requests if request.method == "POST": key = None # If next state is a transition, process it while True: ...
[ "def", "_next", "(", "self", ",", "request", ",", "application", ",", "roles", ",", "next_config", ")", ":", "# we only support state changes for POST requests", "if", "request", ".", "method", "==", "\"POST\"", ":", "key", "=", "None", "# If next state is a transit...
35.435897
20.820513
def _message_received(self, message): """Notify the observers about the received message.""" with self.lock: self._state.receive_message(message) for callable in chain(self._on_message_received, self._on_message): callable(message)
[ "def", "_message_received", "(", "self", ",", "message", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "_state", ".", "receive_message", "(", "message", ")", "for", "callable", "in", "chain", "(", "self", ".", "_on_message_received", ",", "self"...
47
12.333333
def add_root_vault(self, vault_id): """Adds a root vault. arg: vault_id (osid.id.Id): the ``Id`` of a vault raise: AlreadyExists - ``vault_id`` is already in hierarchy raise: NotFound - ``vault_id`` not found raise: NullArgument - ``vault_id`` is ``null`` raise: O...
[ "def", "add_root_vault", "(", "self", ",", "vault_id", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchyDesignSession.add_root_bin_template", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog_session",...
46.117647
18.588235
def _req_lixian_torrent(self, u): """ :param u: uploaded torrent file """ self._load_signatures() url = 'http://115.com/lixian/' params = { 'ct': 'lixian', 'ac': 'torrent', } data = { 'pickcode': u.pickcode, ...
[ "def", "_req_lixian_torrent", "(", "self", ",", "u", ")", ":", "self", ".", "_load_signatures", "(", ")", "url", "=", "'http://115.com/lixian/'", "params", "=", "{", "'ct'", ":", "'lixian'", ",", "'ac'", ":", "'torrent'", ",", "}", "data", "=", "{", "'pi...
29.5
13.884615
def parse_bug_activity(raw_html): """Parse a Bugzilla bug activity HTML stream. This method extracts the information about activity from the given HTML stream. The bug activity is stored into a HTML table. Each parsed activity event is returned into a dictionary. If the given H...
[ "def", "parse_bug_activity", "(", "raw_html", ")", ":", "def", "is_activity_empty", "(", "bs", ")", ":", "EMPTY_ACTIVITY", "=", "\"No changes have been made to this (?:bug|issue) yet.\"", "tag", "=", "bs", ".", "find", "(", "text", "=", "re", ".", "compile", "(", ...
35.6
18.96
def proj_simplex(x, diameter=1, out=None): r"""Projection onto simplex. Projection onto:: ``{ x \in X | x_i \geq 0, \sum_i x_i = r}`` with :math:`r` being the diameter. It is computed by the formula proposed in [D+2008]. Parameters ---------- space : `LinearSpace` Space /...
[ "def", "proj_simplex", "(", "x", ",", "diameter", "=", "1", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "out", "=", "x", ".", "space", ".", "element", "(", ")", "# sort values in descending order", "x_sor", "=", "x", ".", "asar...
25.854545
22.818182
def reset(cls, *args, **kwargs): """Undo call to prepare, useful for testing.""" cls.local.tchannel = None cls.args = None cls.kwargs = None cls.prepared = False
[ "def", "reset", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cls", ".", "local", ".", "tchannel", "=", "None", "cls", ".", "args", "=", "None", "cls", ".", "kwargs", "=", "None", "cls", ".", "prepared", "=", "False" ]
32.666667
9.833333
def upgrade_plan_list(self, subid, params=None): ''' /v1/server/upgrade_plan_list GET - account Retrieve a list of the VPSPLANIDs for which a virtual machine can be upgraded. An empty response array means that there are currently no upgrades available. Link: https://www....
[ "def", "upgrade_plan_list", "(", "self", ",", "subid", ",", "params", "=", "None", ")", ":", "params", "=", "update_params", "(", "params", ",", "{", "'SUBID'", ":", "subid", "}", ")", "return", "self", ".", "request", "(", "'/v1/server/upgrade_plan_list'", ...
44.818182
20.818182
def request_data(key, url, file, string_content, start, end, fix_apple): """ Request data, update local data cache and remove this Thread form queue. :param key: key for data source to get result later :param url: iCal URL :param file: iCal file path :param string_content: iCal content as strin...
[ "def", "request_data", "(", "key", ",", "url", ",", "file", ",", "string_content", ",", "start", ",", "end", ",", "fix_apple", ")", ":", "data", "=", "[", "]", "try", ":", "data", "+=", "events", "(", "url", "=", "url", ",", "file", "=", "file", ...
32.7
19.9
def _get_ensemble_bed_files(items): """ get all ensemble structural BED file calls, skipping any normal samples from tumor/normal calls """ bed_files = [] for data in items: for sv in data.get("sv", []): if sv["variantcaller"] == "sv-ensemble": if ("vrn_file" ...
[ "def", "_get_ensemble_bed_files", "(", "items", ")", ":", "bed_files", "=", "[", "]", "for", "data", "in", "items", ":", "for", "sv", "in", "data", ".", "get", "(", "\"sv\"", ",", "[", "]", ")", ":", "if", "sv", "[", "\"variantcaller\"", "]", "==", ...
38.384615
16.692308
def authenticationReject(): """AUTHENTICATION REJECT Section 9.2.1""" a = TpPd(pd=0x5) b = MessageType(mesType=0x11) # 00010001 packet = a / b return packet
[ "def", "authenticationReject", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x5", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x11", ")", "# 00010001", "packet", "=", "a", "/", "b", "return", "packet" ]
28.666667
13.833333
def fetch(self, rebuild=False, cache=True): """Fetches the table and applies all post processors. Args: rebuild (bool): Rebuild the table and ignore cache. Default: False cache (bool): Cache the finished table for faster future loading. Default: True """ ...
[ "def", "fetch", "(", "self", ",", "rebuild", "=", "False", ",", "cache", "=", "True", ")", ":", "if", "rebuild", ":", "return", "self", ".", "_process_table", "(", "cache", ")", "try", ":", "return", "self", ".", "read_cache", "(", ")", "except", "Fi...
38.615385
14.307692
def _get_var_decl_init_value(self, _ctype, children): """ Gathers initialisation values by parsing children nodes of a VAR_DECL. """ # FIXME TU for INIT_LIST_EXPR # FIXME: always return [(child.kind,child.value),...] # FIXME: simplify this redondant code. init_va...
[ "def", "_get_var_decl_init_value", "(", "self", ",", "_ctype", ",", "children", ")", ":", "# FIXME TU for INIT_LIST_EXPR", "# FIXME: always return [(child.kind,child.value),...]", "# FIXME: simplify this redondant code.", "init_value", "=", "[", "]", "children", "=", "list", ...
39.208333
16.958333
def unregister(self, id): ''' Remove the service with id `id` from the service registry. ''' result = self.rr.table(self.table).get(id).delete().run() if result != { 'deleted':1, 'errors':0,'inserted':0, 'replaced':0,'skipped':0,'unchanged':0}: ...
[ "def", "unregister", "(", "self", ",", "id", ")", ":", "result", "=", "self", ".", "rr", ".", "table", "(", "self", ".", "table", ")", ".", "get", "(", "id", ")", ".", "delete", "(", ")", ".", "run", "(", ")", "if", "result", "!=", "{", "'del...
43
21.545455
def tupleize(element, ignore_types=(str, bytes)): """Cast a single element to a tuple.""" if hasattr(element, '__iter__') and not isinstance(element, ignore_types): return element else: return tuple((element,))
[ "def", "tupleize", "(", "element", ",", "ignore_types", "=", "(", "str", ",", "bytes", ")", ")", ":", "if", "hasattr", "(", "element", ",", "'__iter__'", ")", "and", "not", "isinstance", "(", "element", ",", "ignore_types", ")", ":", "return", "element",...
38.833333
17.333333
def od_reorder_keys(od, keys_in_new_order): # not used ''' Reorder the keys in an OrderedDict ``od`` in-place. ''' if set(od.keys()) != set(keys_in_new_order): raise KeyError('Keys in the new order do not match existing keys') for key in keys_in_new_order: od[key] = od.pop(key) r...
[ "def", "od_reorder_keys", "(", "od", ",", "keys_in_new_order", ")", ":", "# not used", "if", "set", "(", "od", ".", "keys", "(", ")", ")", "!=", "set", "(", "keys_in_new_order", ")", ":", "raise", "KeyError", "(", "'Keys in the new order do not match existing ke...
35.555556
20.222222
def get_unit(a): """Extract the time unit from array's dtype""" typestr = a.dtype.str i = typestr.find('[') if i == -1: raise TypeError("Expected a datetime64 array, not %s", a.dtype) return typestr[i + 1: -1]
[ "def", "get_unit", "(", "a", ")", ":", "typestr", "=", "a", ".", "dtype", ".", "str", "i", "=", "typestr", ".", "find", "(", "'['", ")", "if", "i", "==", "-", "1", ":", "raise", "TypeError", "(", "\"Expected a datetime64 array, not %s\"", ",", "a", "...
33
17.285714
def read_cz_lsm_time_stamps(fd, byte_order): """Read LSM time stamps from file and return as list.""" size, count = struct.unpack(byte_order+'II', fd.read(8)) if size != (8 + 8 * count): raise ValueError("lsm_time_stamps block is too short") return struct.unpack(('%s%dd' % (byte_order, count)), ...
[ "def", "read_cz_lsm_time_stamps", "(", "fd", ",", "byte_order", ")", ":", "size", ",", "count", "=", "struct", ".", "unpack", "(", "byte_order", "+", "'II'", ",", "fd", ".", "read", "(", "8", ")", ")", "if", "size", "!=", "(", "8", "+", "8", "*", ...
50.857143
10.571429
def get_context_data(self, **kwargs): """ Returns the context data to provide to the template. """ context = kwargs if 'view' not in context: context['view'] = self # Insert the considered forum, topic and post into the context context['forum'] = self.get_forum() ...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "kwargs", "if", "'view'", "not", "in", "context", ":", "context", "[", "'view'", "]", "=", "self", "# Insert the considered forum, topic and post into the context", "context...
43.676471
19.147059
def add_virtual_columns_cartesian_velocities_to_polar(self, x="x", y="y", vx="vx", radius_polar=None, vy="vy", vr_out="vr_polar", vazimuth_out="vphi_polar", propagate_uncertainties=False,): """Convert cartesian to polar velocities. :param x: ...
[ "def", "add_virtual_columns_cartesian_velocities_to_polar", "(", "self", ",", "x", "=", "\"x\"", ",", "y", "=", "\"y\"", ",", "vx", "=", "\"vx\"", ",", "radius_polar", "=", "None", ",", "vy", "=", "\"vy\"", ",", "vr_out", "=", "\"vr_polar\"", ",", "vazimuth_...
42.84
23.88
def _set_bd_vc_peer_counter(self, v, load=False): """ Setter method for bd_vc_peer_counter, mapped from YANG variable /bd_vc_peer_state/bd_vc_peer_counter (container) If this variable is read-only (config: false) in the source YANG file, then _set_bd_vc_peer_counter is considered as a private method...
[ "def", "_set_bd_vc_peer_counter", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ","...
77.833333
37.375
def rollback(self): """ Netmiko is being used to commit the rollback configuration because it takes a better care of results compared to pan-python. """ if self.changed: rollback_cmd = '<load><config><from>{0}</from></config></load>'.format(self.backup_file) ...
[ "def", "rollback", "(", "self", ")", ":", "if", "self", ".", "changed", ":", "rollback_cmd", "=", "'<load><config><from>{0}</from></config></load>'", ".", "format", "(", "self", ".", "backup_file", ")", "self", ".", "device", ".", "op", "(", "cmd", "=", "rol...
37.947368
16.157895
def validate(self, corpus, catalogue): """Returns True if all of the files labelled in `catalogue` are up-to-date in the database. :param corpus: corpus of works :type corpus: `Corpus` :param catalogue: catalogue matching filenames to labels :type catalogue: `Catalogue` ...
[ "def", "validate", "(", "self", ",", "corpus", ",", "catalogue", ")", ":", "is_valid", "=", "True", "for", "name", "in", "catalogue", ":", "count", "=", "0", "# It is unfortunate that this creates WitnessText objects", "# for each work, since that involves reading the fil...
42.081081
14.837838
def _is_impossible_by_count(self, state): """Disallow any board that has insufficient tile count to solve.""" # count all the tile types and name them for readability counts = {tile_type: 0 for tile_type in base.Tile._all_types} standard_wildcard_type = '2' for p, tile in state.b...
[ "def", "_is_impossible_by_count", "(", "self", ",", "state", ")", ":", "# count all the tile types and name them for readability", "counts", "=", "{", "tile_type", ":", "0", "for", "tile_type", "in", "base", ".", "Tile", ".", "_all_types", "}", "standard_wildcard_type...
40.722222
13.361111
def do_set_hub_connection(self, args): """Set Hub connection parameters. Usage: set_hub_connection username password host [port] Arguments: username: Hub username password: Hub password host: host name or IP address port: IP port [def...
[ "def", "do_set_hub_connection", "(", "self", ",", "args", ")", ":", "params", "=", "args", ".", "split", "(", ")", "username", "=", "None", "password", "=", "None", "host", "=", "None", "port", "=", "None", "try", ":", "username", "=", "params", "[", ...
27.472222
15.027778
def listar_por_nome(self, nome): """Obtém um equipamento a partir do seu nome. :param nome: Nome do equipamento. :return: Dicionário com a seguinte estrutura: :: {'equipamento': {'id': < id_equipamento >, 'nome': < nome_equipamento >, 'id_tipo_equi...
[ "def", "listar_por_nome", "(", "self", ",", "nome", ")", ":", "if", "nome", "==", "''", "or", "nome", "is", "None", ":", "raise", "InvalidParameterError", "(", "u'O nome do equipamento não foi informado.')", "", "url", "=", "'equipamento/nome/'", "+", "urllib", ...
35.029412
19.323529
def _process(self, name): """Process the current token.""" if self.token.nature == name: self.token = self.lexer.next_token() else: self._error()
[ "def", "_process", "(", "self", ",", "name", ")", ":", "if", "self", ".", "token", ".", "nature", "==", "name", ":", "self", ".", "token", "=", "self", ".", "lexer", ".", "next_token", "(", ")", "else", ":", "self", ".", "_error", "(", ")" ]
31.333333
11.333333
def cas2tas(cas, h): """ cas2tas conversion both m/s h in m """ p, rho, T = atmos(h) qdyn = p0*((1.+rho0*cas*cas/(7.*p0))**3.5-1.) tas = np.sqrt(7.*p/rho*((1.+qdyn/p)**(2./7.)-1.)) tas = -1 * tas if cas < 0 else tas return tas
[ "def", "cas2tas", "(", "cas", ",", "h", ")", ":", "p", ",", "rho", ",", "T", "=", "atmos", "(", "h", ")", "qdyn", "=", "p0", "*", "(", "(", "1.", "+", "rho0", "*", "cas", "*", "cas", "/", "(", "7.", "*", "p0", ")", ")", "**", "3.5", "-"...
34.857143
12.285714
def view_creatr(filename): """Name of the View File to be created""" if not check(): click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:view command') return path = os.path.abspath('.') + '/public/templates' if not os.path.exists(path): os.makedirs(path...
[ "def", "view_creatr", "(", "filename", ")", ":", "if", "not", "check", "(", ")", ":", "click", ".", "echo", "(", "Fore", ".", "RED", "+", "'ERROR: Ensure you are in a bast app to run the create:view command'", ")", "return", "path", "=", "os", ".", "path", "."...
36.333333
22.666667
def leave_transaction_management(using=None): """ Leaves transaction management for a running thread. A dirty flag is carried over to the surrounding block, as a commit will commit all changes, even those from outside. (Commits are on connection level.) """ if using is None: for using in...
[ "def", "leave_transaction_management", "(", "using", "=", "None", ")", ":", "if", "using", "is", "None", ":", "for", "using", "in", "tldap", ".", "backend", ".", "connections", ":", "connection", "=", "tldap", ".", "backend", ".", "connections", "[", "usin...
42.923077
14.923077
def has_key(self, key): """ Ensures :attr:`subject` is a :class:`collections.Mapping` and contains *key*. """ self.is_a(Mapping) self.contains(key) return KeyInspector(self._subject[key])
[ "def", "has_key", "(", "self", ",", "key", ")", ":", "self", ".", "is_a", "(", "Mapping", ")", "self", ".", "contains", "(", "key", ")", "return", "KeyInspector", "(", "self", ".", "_subject", "[", "key", "]", ")" ]
32.714286
13.857143
def fit(self, X, y=None): """Fit the grid Parameters ---------- X : array-like, shape = [n_samples, n_features] Data points Returns ------- self """ X = array2d(X) self.n_features = X.shape[1] self.n_bins = self.n_bins...
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "X", "=", "array2d", "(", "X", ")", "self", ".", "n_features", "=", "X", ".", "shape", "[", "1", "]", "self", ".", "n_bins", "=", "self", ".", "n_bins_per_feature", "**", "se...
29.487179
18.358974
def list_all_variants(cls, **kwargs): """List Variants Return a list of Variants This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_variants(async=True) >>> result = thread.get()...
[ "def", "list_all_variants", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_list_all_variants_with_http_info", "(", "*",...
36.173913
14.652174
def get_column(self, X, column): """Return a column of the given matrix. Args: X: `numpy.ndarray` or `pandas.DataFrame`. column: `int` or `str`. Returns: np.ndarray: Selected column. """ if isinstance(X, pd.DataFrame): return X[co...
[ "def", "get_column", "(", "self", ",", "X", ",", "column", ")", ":", "if", "isinstance", "(", "X", ",", "pd", ".", "DataFrame", ")", ":", "return", "X", "[", "column", "]", ".", "values", "return", "X", "[", ":", ",", "column", "]" ]
24.857143
15.428571
def is_member(self, ldap_user, group_dn): """ Returns True if the group is the user's primary group or if the user is listed in the group's memberUid attribute. """ try: user_uid = ldap_user.attrs["uid"][0] try: is_member = ldap_user.conne...
[ "def", "is_member", "(", "self", ",", "ldap_user", ",", "group_dn", ")", ":", "try", ":", "user_uid", "=", "ldap_user", ".", "attrs", "[", "\"uid\"", "]", "[", "0", "]", "try", ":", "is_member", "=", "ldap_user", ".", "connection", ".", "compare_s", "(...
35.481481
18.666667
def check_power_redundancy(): """ Check if the power supplies are redundant The check is skipped if --noPowerRedundancy is set """ # skip the check if --noPowerRedundancy is set if power_redundancy_flag: # walk the data ps_redundant_data = walk_data(sess, oid_ps_redundant...
[ "def", "check_power_redundancy", "(", ")", ":", "# skip the check if --noPowerRedundancy is set", "if", "power_redundancy_flag", ":", "# walk the data ", "ps_redundant_data", "=", "walk_data", "(", "sess", ",", "oid_ps_redundant", ",", "helper", ")", "[", "0", "]",...
46.3
17.1
def route_to_route_network(gtfs, walking_threshold, start_time, end_time): """ Creates networkx graph where the nodes are bus routes and a edge indicates that there is a possibility to transfer between the routes :param gtfs: :param walking_threshold: :param start_time: :param end_time: ...
[ "def", "route_to_route_network", "(", "gtfs", ",", "walking_threshold", ",", "start_time", ",", "end_time", ")", ":", "graph", "=", "networkx", ".", "Graph", "(", ")", "routes", "=", "gtfs", ".", "get_table", "(", "\"routes\"", ")", "for", "i", "in", "rout...
49.470588
26.794118
def refresh_win(self, set_encoding=True): """ set_encoding is False when resizing """ self._fix_geometry() self.init_window(set_encoding) self._win.bkgdset(' ', curses.color_pair(3)) self._win.erase() self._win.box() self._win.addstr(0, int((self.maxX ...
[ "def", "refresh_win", "(", "self", ",", "set_encoding", "=", "True", ")", ":", "self", ".", "_fix_geometry", "(", ")", "self", ".", "init_window", "(", "set_encoding", ")", "self", ".", "_win", ".", "bkgdset", "(", "' '", ",", "curses", ".", "color_pair"...
44.346154
22.384615
def add(self, ngram): """Count 1 for P[(w1, ..., wn)] and for P(wn | (w1, ..., wn-1)""" CountingProbDist.add(self, ngram) self.cond_prob[ngram[:-1]].add(ngram[-1])
[ "def", "add", "(", "self", ",", "ngram", ")", ":", "CountingProbDist", ".", "add", "(", "self", ",", "ngram", ")", "self", ".", "cond_prob", "[", "ngram", "[", ":", "-", "1", "]", "]", ".", "add", "(", "ngram", "[", "-", "1", "]", ")" ]
46
7.25
def maximum(self): """Maximum value of the object.""" value = self._schema.get("maximum", None) if value is None: return if not isinstance(value, NUMERIC_TYPES): raise SchemaError( "maximum value {0!r} is not a numeric type".format( ...
[ "def", "maximum", "(", "self", ")", ":", "value", "=", "self", ".", "_schema", ".", "get", "(", "\"maximum\"", ",", "None", ")", "if", "value", "is", "None", ":", "return", "if", "not", "isinstance", "(", "value", ",", "NUMERIC_TYPES", ")", ":", "rai...
34.4
14.6
def load(self, data): """This is the entrance method for all data which is used to store the raw data and start parsing the data. :param data: The raw untouched bytearray as recieved by the RFXtrx :type data: bytearray :return: The parsed data represented in a dictionary ...
[ "def", "load", "(", "self", ",", "data", ")", ":", "self", ".", "loaded_at", "=", "datetime", ".", "utcnow", "(", ")", "self", ".", "raw", "=", "data", "self", ".", "data", "=", "self", ".", "parse", "(", "data", ")", "return", "self", ".", "data...
33
16.214286
def deterministic_from_funcs( name, eval, jacobians={}, jacobian_formats={}, dtype=np.float, mv=False): """ Return a Stochastic subclass made from a particular distribution. :Parameters: name : string The name of the new class. jacobians : function The log-probability fu...
[ "def", "deterministic_from_funcs", "(", "name", ",", "eval", ",", "jacobians", "=", "{", "}", ",", "jacobian_formats", "=", "{", "}", ",", "dtype", "=", "np", ".", "float", ",", "mv", "=", "False", ")", ":", "(", "args", ",", "defaults", ")", "=", ...
33.472222
19.305556
async def load_cache(self, archive: bool = False) -> int: """ Load caches and archive enough to go offline and be able to generate proof on all credentials in wallet. Return timestamp (epoch seconds) of cache load event, also used as subdirectory for cache archives. :re...
[ "async", "def", "load_cache", "(", "self", ",", "archive", ":", "bool", "=", "False", ")", "->", "int", ":", "LOGGER", ".", "debug", "(", "'HolderProver.load_cache >>> archive: %s'", ",", "archive", ")", "rv", "=", "int", "(", "time", "(", ")", ")", "box...
39.95
17.85
def render_cvmfs_sc(cvmfs_volume): """Render REANA_CVMFS_SC_TEMPLATE.""" name = CVMFS_REPOSITORIES[cvmfs_volume] rendered_template = dict(REANA_CVMFS_SC_TEMPLATE) rendered_template['metadata']['name'] = "csi-cvmfs-{}".format(name) rendered_template['parameters']['repository'] = cvmfs_volume retu...
[ "def", "render_cvmfs_sc", "(", "cvmfs_volume", ")", ":", "name", "=", "CVMFS_REPOSITORIES", "[", "cvmfs_volume", "]", "rendered_template", "=", "dict", "(", "REANA_CVMFS_SC_TEMPLATE", ")", "rendered_template", "[", "'metadata'", "]", "[", "'name'", "]", "=", "\"cs...
47.714286
12.714286
def topLevelWindows(self): """ Returns a list of the top level windows for this application. :return [<QtGui.QMainWindow>, ..] """ out = [] clean = [] for ref in self._topLevelWindows: window = ref() if window is not ...
[ "def", "topLevelWindows", "(", "self", ")", ":", "out", "=", "[", "]", "clean", "=", "[", "]", "for", "ref", "in", "self", ".", "_topLevelWindows", ":", "window", "=", "ref", "(", ")", "if", "window", "is", "not", "None", ":", "clean", ".", "append...
27.625
13.625
def changed_fields(self, from_db=False): """ Args: from_db (bool): Check changes against actual db data Returns: list: List of fields names which their values changed. """ if self.exist: current_dict = self.clean_value() # `from_db`...
[ "def", "changed_fields", "(", "self", ",", "from_db", "=", "False", ")", ":", "if", "self", ".", "exist", ":", "current_dict", "=", "self", ".", "clean_value", "(", ")", "# `from_db` attr is set False as default, when a `ListNode` is", "# initialized just after above `c...
45.428571
24
def import_setting(self): """Import setting to a file.""" LOGGER.debug('Import button clicked') home_directory = os.path.expanduser('~') file_path, __ = QFileDialog.getOpenFileName( self, self.tr('Import InaSAFE settings'), home_directory, ...
[ "def", "import_setting", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'Import button clicked'", ")", "home_directory", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "file_path", ",", "__", "=", "QFileDialog", ".", "getOpenFileName", "("...
45.25
13.7
def merge_entities(doc): """Merge entities into a single token. doc (Doc): The Doc object. RETURNS (Doc): The Doc object with merged entities. DOCS: https://spacy.io/api/pipeline-functions#merge_entities """ with doc.retokenize() as retokenizer: for ent in doc.ents: attrs =...
[ "def", "merge_entities", "(", "doc", ")", ":", "with", "doc", ".", "retokenize", "(", ")", "as", "retokenizer", ":", "for", "ent", "in", "doc", ".", "ents", ":", "attrs", "=", "{", "\"tag\"", ":", "ent", ".", "root", ".", "tag", ",", "\"dep\"", ":"...
33.615385
18.153846
def averaging(grid, numGrid, numPix): """ resize 2d pixel grid with numGrid to numPix and averages over the pixels :param grid: higher resolution pixel grid :param numGrid: number of pixels per axis in the high resolution input image :param numPix: lower number of pixels per axis in the output image...
[ "def", "averaging", "(", "grid", ",", "numGrid", ",", "numPix", ")", ":", "Nbig", "=", "numGrid", "Nsmall", "=", "numPix", "small", "=", "grid", ".", "reshape", "(", "[", "int", "(", "Nsmall", ")", ",", "int", "(", "Nbig", "/", "Nsmall", ")", ",", ...
40.461538
26.769231
def run(*extractor_list, **kwargs): """Parse arguments provided on the commandline and execute extractors.""" args = _get_args(kwargs.get('args')) n_extractors = len(extractor_list) log.info('Going to run list of {} FeatureExtractors'.format(n_extractors)) collection = fex.Collection(cache_path=args...
[ "def", "run", "(", "*", "extractor_list", ",", "*", "*", "kwargs", ")", ":", "args", "=", "_get_args", "(", "kwargs", ".", "get", "(", "'args'", ")", ")", "n_extractors", "=", "len", "(", "extractor_list", ")", "log", ".", "info", "(", "'Going to run l...
40.769231
13.307692
def ready_argument_list(self, arguments): """ready argument list to be passed to the kernel, allocates gpu mem :param arguments: List of arguments to be passed to the kernel. The order should match the argument list on the CUDA kernel. Allowed values are numpy.ndarray, and/or nu...
[ "def", "ready_argument_list", "(", "self", ",", "arguments", ")", ":", "gpu_args", "=", "[", "]", "for", "arg", "in", "arguments", ":", "# if arg i is a numpy array copy to device", "if", "isinstance", "(", "arg", ",", "numpy", ".", "ndarray", ")", ":", "alloc...
45.727273
17.5
def current_url_name(context): """ Returns the name of the current URL, namespaced, or False. Example usage: {% current_url_name as url_name %} <a href="#"{% if url_name == 'myapp:home' %} class="active"{% endif %}">Home</a> """ url_name = False if context.request.resolver_ma...
[ "def", "current_url_name", "(", "context", ")", ":", "url_name", "=", "False", "if", "context", ".", "request", ".", "resolver_match", ":", "url_name", "=", "\"{}:{}\"", ".", "format", "(", "context", ".", "request", ".", "resolver_match", ".", "namespace", ...
29.888889
21.555556
def _onMessageNotification(self, client, userdata, pahoMessage): """ Internal callback for gateway notification messages, parses source device from topic string and passes the information on to the registered device command callback """ try: note = Notification(pahoMe...
[ "def", "_onMessageNotification", "(", "self", ",", "client", ",", "userdata", ",", "pahoMessage", ")", ":", "try", ":", "note", "=", "Notification", "(", "pahoMessage", ",", "self", ".", "_messageCodecs", ")", "except", "InvalidEventException", "as", "e", ":",...
44.461538
17.384615
def unpack_archive(*components, **kwargs) -> str: """ Unpack a compressed archive. Arguments: *components (str[]): Absolute path. **kwargs (dict, optional): Set "compression" to compression type. Default: bz2. Set "dir" to destination directory. Defaults to the direc...
[ "def", "unpack_archive", "(", "*", "components", ",", "*", "*", "kwargs", ")", "->", "str", ":", "path", "=", "fs", ".", "abspath", "(", "*", "components", ")", "compression", "=", "kwargs", ".", "get", "(", "\"compression\"", ",", "\"bz2\"", ")", "dir...
26.5
19.5
def import_json(file_name, **kwargs): """ Imports curves and surfaces from files in JSON format. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details. :param file_name: name of the input file :type file_name: str :return: a list of rational spli...
[ "def", "import_json", "(", "file_name", ",", "*", "*", "kwargs", ")", ":", "def", "callback", "(", "data", ")", ":", "return", "json", ".", "loads", "(", "data", ")", "# Get keyword arguments", "delta", "=", "kwargs", ".", "get", "(", "'delta'", ",", "...
32.565217
22
def nlmsg_alloc(len_=default_msg_size): """Allocate a new Netlink message with maximum payload size specified. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L299 Allocates a new Netlink message without any further payload. The maximum payload size defaults to resource.getpagesize() or as...
[ "def", "nlmsg_alloc", "(", "len_", "=", "default_msg_size", ")", ":", "len_", "=", "max", "(", "libnl", ".", "linux_private", ".", "netlink", ".", "nlmsghdr", ".", "SIZEOF", ",", "len_", ")", "nm", "=", "nl_msg", "(", ")", "nm", ".", "nm_refcnt", "=", ...
40.1
25.55
def create_partition(self, partition_spec, if_not_exists=False, async_=False, **kw): """ Create a partition within the table. :param partition_spec: specification of the partition. :param if_not_exists: :param async_: :return: partition object :rtype: odps.models...
[ "def", "create_partition", "(", "self", ",", "partition_spec", ",", "if_not_exists", "=", "False", ",", "async_", "=", "False", ",", "*", "*", "kw", ")", ":", "async_", "=", "kw", ".", "get", "(", "'async'", ",", "async_", ")", "return", "self", ".", ...
40
17.5
def _nat_rules_for_internet_access(self, acl_no, network, netmask, inner_itfc, outer_itfc, vrf_name): """Configure the NAT rules for an internal network. Configuring NAT rules in the ASR1k is a three step process. First create an ACL for the IP range of th...
[ "def", "_nat_rules_for_internet_access", "(", "self", ",", "acl_no", ",", "network", ",", "netmask", ",", "inner_itfc", ",", "outer_itfc", ",", "vrf_name", ")", ":", "acl_present", "=", "self", ".", "_check_acl", "(", "acl_no", ",", "network", ",", "netmask", ...
49.880952
24.642857
def list(self): """ List the existing stacks in the indicated region Args: None Returns: True if True Todo: Figure out what could go wrong and take steps to hanlde problems. """ self._initialize_list() int...
[ "def", "list", "(", "self", ")", ":", "self", ".", "_initialize_list", "(", ")", "interested", "=", "True", "response", "=", "self", ".", "_cloudFormation", ".", "list_stacks", "(", ")", "print", "(", "'Stack(s):'", ")", "while", "interested", ":", "if", ...
29.181818
21.787879
def get(self, nick): '''taobao.sellercats.list.get 获取前台展示的店铺内卖家自定义商品类目 此API添加卖家店铺内自定义类目 父类目parent_cid值等于0:表示此类目为店铺下的一级类目,值不等于0:表示此类目有父类目 注:因为缓存的关系,添加的新类目需8个小时后才可以在淘宝页面上正常显示,但是不影响在该类目下商品发布''' request = TOPRequest('taobao.sellercats.list.get') request['nick'] = nick self.c...
[ "def", "get", "(", "self", ",", "nick", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.sellercats.list.get'", ")", "request", "[", "'nick'", "]", "=", "nick", "self", ".", "create", "(", "self", ".", "execute", "(", "request", ")", ")", "return", ...
46.625
24.375
def from_text(textring): """Convert a dictionary containing (textual DNS name, base64 secret) pairs into a binary keyring which has (dns.name.Name, binary secret) pairs. @rtype: dict""" keyring = {} for keytext in textring: keyname = dns.name.from_text(keytext) secret = base64.decod...
[ "def", "from_text", "(", "textring", ")", ":", "keyring", "=", "{", "}", "for", "keytext", "in", "textring", ":", "keyname", "=", "dns", ".", "name", ".", "from_text", "(", "keytext", ")", "secret", "=", "base64", ".", "decodestring", "(", "textring", ...
35.363636
15.818182
def _calculate_hash(self, filename, **kwargs): """ Calculates the hash of the file and the hash of the file + metadata (passed in ``kwargs``). Args: filename (str): Name of the file testnet (bool): testnet flag. Defaults to False **kwargs: Additional ...
[ "def", "_calculate_hash", "(", "self", ",", "filename", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "file_hash", "=", "hashlib", ".", "md5", "(", "f", ".", "read", "(", ")", ")", ".", "hex...
39.514286
23.228571
def main_loop(): '''main processing loop, display graphs and maps''' global grui, last_xlim while True: if mestate is None or mestate.exit: return while not mestate.input_queue.empty(): line = mestate.input_queue.get() cmds = line.split(';') fo...
[ "def", "main_loop", "(", ")", ":", "global", "grui", ",", "last_xlim", "while", "True", ":", "if", "mestate", "is", "None", "or", "mestate", ".", "exit", ":", "return", "while", "not", "mestate", ".", "input_queue", ".", "empty", "(", ")", ":", "line",...
34.870968
12.16129
def pull(i): """ Input: { (path) - repo UOA (where to create entry) (type) - type (url) - URL or (data_uoa) - repo UOA (clone) - if 'yes', clone repo instead of update (current_repos) - if r...
[ "def", "pull", "(", "i", ")", ":", "o", "=", "i", ".", "get", "(", "'out'", ",", "''", ")", "xrecache", "=", "False", "pp", "=", "[", "]", "px", "=", "i", ".", "get", "(", "'path'", ",", "''", ")", "t", "=", "i", ".", "get", "(", "'type'"...
28.333333
21.257028
def filter_classified_data(self, item): """Remove classified or confidential data from an item. It removes those fields that contain data considered as classified. Classified fields are defined in `CLASSIFIED_FIELDS` class attribute. :param item: fields will be removed from this item ...
[ "def", "filter_classified_data", "(", "self", ",", "item", ")", ":", "item_uuid", "=", "uuid", "(", "self", ".", "origin", ",", "self", ".", "metadata_id", "(", "item", ")", ")", "logger", ".", "debug", "(", "\"Filtering classified data for item %s\"", ",", ...
37.291667
25.708333
def _handle(self, msg): """ Pass a received message to the registered handlers. :param msg: received message :type msg: :class:`fatbotslim.irc.Message` """ def handler_yielder(): for handler in self.handlers: yield handler def handle...
[ "def", "_handle", "(", "self", ",", "msg", ")", ":", "def", "handler_yielder", "(", ")", ":", "for", "handler", "in", "self", ".", "handlers", ":", "yield", "handler", "def", "handler_callback", "(", "_", ")", ":", "if", "msg", ".", "propagate", ":", ...
29.647059
14.470588
def key_absent(name, use_32bit_registry=False): r''' .. versionadded:: 2015.5.4 Ensure a registry key is removed. This will remove the key, subkeys, and all value entries. Args: name (str): A string representing the full path to the key to be removed to include the...
[ "def", "key_absent", "(", "name", ",", "use_32bit_registry", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", "}", "hive", ",", "key", "=", "...
30.858974
24.679487