text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
async def build_hardware_controller( cls, config: robot_configs.robot_config = None, port: str = None, loop: asyncio.AbstractEventLoop = None, force: bool = False) -> 'API': """ Build a hardware controller that will actually talk to hardware. This method ...
[ "async", "def", "build_hardware_controller", "(", "cls", ",", "config", ":", "robot_configs", ".", "robot_config", "=", "None", ",", "port", ":", "str", "=", "None", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", "=", "None", ",", "force", ":", "bo...
49.807692
20.769231
def prefer_master(nodes: List[DiscoveredNode]) -> Optional[DiscoveredNode]: """ Select the master if available, otherwise fall back to a replica. """ return max(nodes, key=attrgetter("state"))
[ "def", "prefer_master", "(", "nodes", ":", "List", "[", "DiscoveredNode", "]", ")", "->", "Optional", "[", "DiscoveredNode", "]", ":", "return", "max", "(", "nodes", ",", "key", "=", "attrgetter", "(", "\"state\"", ")", ")" ]
40.8
14
def validate_trail_settings(self, ct, aws_region, trail): """Validates logging, SNS and S3 settings for the global trail. Has the capability to: - start logging for the trail - create SNS topics & queues - configure or modify a S3 bucket for logging """ self.lo...
[ "def", "validate_trail_settings", "(", "self", ",", "ct", ",", "aws_region", ",", "trail", ")", ":", "self", ".", "log", ".", "debug", "(", "'Validating trail {}/{}/{}'", ".", "format", "(", "self", ".", "account", ".", "account_name", ",", "aws_region", ","...
38.258621
20.017241
def FileEntryExistsByPathSpec(self, path_spec): """Determines if a file entry for a path specification exists. Args: path_spec (PathSpec): path specification. Returns: bool: True if the file entry exists. """ # All checks for correct path spec is done in SQLiteBlobFile. # Therefore...
[ "def", "FileEntryExistsByPathSpec", "(", "self", ",", "path_spec", ")", ":", "# All checks for correct path spec is done in SQLiteBlobFile.", "# Therefore, attempt to open the path specification and", "# check if errors occurred.", "try", ":", "file_object", "=", "resolver", ".", "...
31.9
20.65
def get_alexa_rankings(self, domains): """Retrieves the most recent VT info for a set of domains. Args: domains: list of string domains. Returns: A dict with the domain as key and the VT report as value. """ api_name = 'alexa_rankings' (all_respo...
[ "def", "get_alexa_rankings", "(", "self", ",", "domains", ")", ":", "api_name", "=", "'alexa_rankings'", "(", "all_responses", ",", "domains", ")", "=", "self", ".", "_bulk_cache_lookup", "(", "api_name", ",", "domains", ")", "responses", "=", "self", ".", "...
35.8
20.25
def prepare_prop_defs(prop_defs, prop_name, cls_names): """ Examines and adds any missing defs to the prop_defs dictionary for use with the RdfPropertyMeta.__prepare__ method Args: ----- prop_defs: the defintions from the rdf vocabulary defintion prop_name: the property name ...
[ "def", "prepare_prop_defs", "(", "prop_defs", ",", "prop_name", ",", "cls_names", ")", ":", "def", "get_def", "(", "prop_defs", ",", "def_fields", ",", "default_val", "=", "None", ")", ":", "\"\"\" returns the cross corelated fields for delealing with mutiple\n ...
37.505747
15.850575
def Crowl_Louvar_LFL(atoms): r'''Calculates lower flammability limit, using the Crowl-Louvar [1]_ correlation. Uses molecular formula only. The lower flammability limit of a gas is air is: .. math:: C_mH_xO_y + zO_2 \to mCO_2 + \frac{x}{2}H_2O \text{LFL} = \frac{0.55}{4.76m + 1.19x - ...
[ "def", "Crowl_Louvar_LFL", "(", "atoms", ")", ":", "nC", ",", "nH", ",", "nO", "=", "0", ",", "0", ",", "0", "if", "'C'", "in", "atoms", "and", "atoms", "[", "'C'", "]", ":", "nC", "=", "atoms", "[", "'C'", "]", "else", ":", "return", "None", ...
26.137255
23.588235
def compare(self, buf, offset=0, length=1, ignore=""): """Compare buffer""" for i in range(offset, offset + length): if isinstance(self.m_types, (type(Union), type(Structure))): if compare(self.m_buf[i], buf[i], ignore=ignore): return 1 elif s...
[ "def", "compare", "(", "self", ",", "buf", ",", "offset", "=", "0", ",", "length", "=", "1", ",", "ignore", "=", "\"\"", ")", ":", "for", "i", "in", "range", "(", "offset", ",", "offset", "+", "length", ")", ":", "if", "isinstance", "(", "self", ...
34.181818
19.272727
def get_election_votes(self, election): """Get all votes for this candidate in an election.""" candidate_election = CandidateElection.objects.get( candidate=self, election=election ) return candidate_election.votes.all()
[ "def", "get_election_votes", "(", "self", ",", "election", ")", ":", "candidate_election", "=", "CandidateElection", ".", "objects", ".", "get", "(", "candidate", "=", "self", ",", "election", "=", "election", ")", "return", "candidate_election", ".", "votes", ...
37
14.428571
def to_dict(self) -> dict: '''vote info as dict''' return { "version": self.version, "description": self.description, "count_mode": self.count_mode, "start_block": self.start_block, "end_block": self.end_block, "choices": self.choi...
[ "def", "to_dict", "(", "self", ")", "->", "dict", ":", "return", "{", "\"version\"", ":", "self", ".", "version", ",", "\"description\"", ":", "self", ".", "description", ",", "\"count_mode\"", ":", "self", ".", "count_mode", ",", "\"start_block\"", ":", "...
30.916667
11.916667
def onConnect(self, client, userdata, flags, rc): """! The callback for when the client receives a CONNACK response from the server. @param client @param userdata @param flags @param rc """ for sub in self.subsciption: (result, mid) = self.cli...
[ "def", "onConnect", "(", "self", ",", "client", ",", "userdata", ",", "flags", ",", "rc", ")", ":", "for", "sub", "in", "self", ".", "subsciption", ":", "(", "result", ",", "mid", ")", "=", "self", ".", "client", ".", "subscribe", "(", "sub", ")" ]
29.818182
17.363636
def memoize(fun): """A decorator for memoizing functions. Only works on functions that take simple arguments - arguments that take list-like or dict-like arguments will not be memoized, and this function will raise a TypeError. """ @funcutils.wraps(fun) def wrapper(*args, **kwargs): ...
[ "def", "memoize", "(", "fun", ")", ":", "@", "funcutils", ".", "wraps", "(", "fun", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "do_memoization", "=", "sportsref", ".", "get_option", "(", "'memoize'", ")", "if", "not",...
28.5
18.447368
def sign(self, message): """ >>> authlen = OmapiHMACMD5Authenticator.authlen >>> len(OmapiHMACMD5Authenticator(b"foo", 16*b"x").sign(b"baz")) == authlen True @type message: bytes @rtype: bytes @returns: a signature of length self.authlen """ return hmac.HMAC(self.key, message, digestmod=hashlib.md5)....
[ "def", "sign", "(", "self", ",", "message", ")", ":", "return", "hmac", ".", "HMAC", "(", "self", ".", "key", ",", "message", ",", "digestmod", "=", "hashlib", ".", "md5", ")", ".", "digest", "(", ")" ]
28.909091
19.454545
def split_scoped_hparams(scopes, merged_hparams): """Split single HParams with scoped keys into multiple.""" split_values = {scope: {} for scope in scopes} merged_values = merged_hparams.values() for scoped_key, value in six.iteritems(merged_values): scope = scoped_key.split(".")[0] key = scoped_key[len...
[ "def", "split_scoped_hparams", "(", "scopes", ",", "merged_hparams", ")", ":", "split_values", "=", "{", "scope", ":", "{", "}", "for", "scope", "in", "scopes", "}", "merged_values", "=", "merged_hparams", ".", "values", "(", ")", "for", "scoped_key", ",", ...
36.583333
14.583333
def SSTORE(self, offset, value): """Save word to storage""" storage_address = self.address self._publish('will_evm_write_storage', storage_address, offset, value) #refund = Operators.ITEBV(256, # previous_value != 0, # Opera...
[ "def", "SSTORE", "(", "self", ",", "offset", ",", "value", ")", ":", "storage_address", "=", "self", ".", "address", "self", ".", "_publish", "(", "'will_evm_write_storage'", ",", "storage_address", ",", "offset", ",", "value", ")", "#refund = Operators.ITEBV(25...
47.5
17.357143
def delete(self) : "deletes the document from the database" if self.URL is None : raise DeletionError("Can't delete a document that was not saved") r = self.connection.session.delete(self.URL) data = r.json() if (r.status_code != 200 and r.status_code != 202) or 'err...
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "URL", "is", "None", ":", "raise", "DeletionError", "(", "\"Can't delete a document that was not saved\"", ")", "r", "=", "self", ".", "connection", ".", "session", ".", "delete", "(", "self", ".", ...
37.333333
21.833333
def to_internal_value(self, data): """ List of dicts of native values <- List of dicts of primitive datatypes. """ if html.is_html_input(data): data = html.parse_html_list(data) if isinstance(data, type('')) or isinstance(data, collections.Mapping) or not hasattr(data...
[ "def", "to_internal_value", "(", "self", ",", "data", ")", ":", "if", "html", ".", "is_html_input", "(", "data", ")", ":", "data", "=", "html", ".", "parse_html_list", "(", "data", ")", "if", "isinstance", "(", "data", ",", "type", "(", "''", ")", ")...
49.181818
18.090909
def __ConstructRelativePath(self, method_config, request, relative_path=None): """Determine the relative path for request.""" python_param_names = util.MapParamNames( method_config.path_params, type(request)) params = dict([(param, getattr(request, par...
[ "def", "__ConstructRelativePath", "(", "self", ",", "method_config", ",", "request", ",", "relative_path", "=", "None", ")", ":", "python_param_names", "=", "util", ".", "MapParamNames", "(", "method_config", ".", "path_params", ",", "type", "(", "request", ")",...
57
15.6
def ensure_workspace(self, name, layout, workspace_id): """Looks for a workspace with workspace_id. If none is found, create a new one, add it, and change to it. """ workspace = next((workspace for workspace in self.document_model.workspaces if workspace.workspace_id == workspace_id), N...
[ "def", "ensure_workspace", "(", "self", ",", "name", ",", "layout", ",", "workspace_id", ")", ":", "workspace", "=", "next", "(", "(", "workspace", "for", "workspace", "in", "self", ".", "document_model", ".", "workspaces", "if", "workspace", ".", "workspace...
53.333333
27.555556
def set_meta(mcs, bases, attr): """ Get all of the ``Meta`` classes from bases and combine them with this class. Pops or creates ``Meta`` from attributes, combines all bases, adds ``_meta`` to attributes with all meta :param bases: bases of this class :param att...
[ "def", "set_meta", "(", "mcs", ",", "bases", ",", "attr", ")", ":", "# pop the meta class from the attributes", "meta", "=", "attr", ".", "pop", "(", "mcs", ".", "_meta_cls", ",", "types", ".", "ClassType", "(", "mcs", ".", "_meta_cls", ",", "(", ")", ",...
40.483871
15.774194
def qindex2index(index): """ from a QIndex (row/column coordinate system), get the buffer index of the byte """ r = index.row() c = index.column() if c > 0x10: return (0x10 * r) + c - 0x11 else: return (0x10 * r) + c
[ "def", "qindex2index", "(", "index", ")", ":", "r", "=", "index", ".", "row", "(", ")", "c", "=", "index", ".", "column", "(", ")", "if", "c", ">", "0x10", ":", "return", "(", "0x10", "*", "r", ")", "+", "c", "-", "0x11", "else", ":", "return...
34.125
12.625
def iMath_propagate_labels_through_mask(image, labels, stopping_value=100, propagation_method=0): """ >>> import ants >>> wms = ants.image_read('~/desktop/wms.nii.gz') >>> thal = ants.image_read('~/desktop/thal.nii.gz') >>> img2 = ants.iMath_propagate_labels_through_mask(wms, thal, 500, 0) """ ...
[ "def", "iMath_propagate_labels_through_mask", "(", "image", ",", "labels", ",", "stopping_value", "=", "100", ",", "propagation_method", "=", "0", ")", ":", "return", "iMath", "(", "image", ",", "'PropagateLabelsThroughMask'", ",", "labels", ",", "stopping_value", ...
51.125
24.625
def substitute_namespace_into_graph(self, graph): """ Creates a graph from the local namespace of the code (to be used after the execution of the code) :param graph: The graph to use as a recipient of the namespace :return: the updated graph """ for key, value in self.na...
[ "def", "substitute_namespace_into_graph", "(", "self", ",", "graph", ")", ":", "for", "key", ",", "value", "in", "self", ".", "namespace", ".", "items", "(", ")", ":", "try", ":", "nodes", "=", "graph", ".", "vs", ".", "select", "(", "name", "=", "ke...
34.217391
15.695652
def grab_server(self, onerror = None): """Disable processing of requests on all other client connections until the server is ungrabbed. Server grabbing should be avoided as much as possible.""" request.GrabServer(display = self.display, onerror = onerror)
[ "def", "grab_server", "(", "self", ",", "onerror", "=", "None", ")", ":", "request", ".", "GrabServer", "(", "display", "=", "self", ".", "display", ",", "onerror", "=", "onerror", ")" ]
51.5
8.166667
def _build_static_table_mapping(): """ Build static table mapping from header name to tuple with next structure: (<minimal index of header>, <mapping from header value to it index>). static_table_mapping used for hash searching. """ static_table_mapping = {} for index, (name, value) in enum...
[ "def", "_build_static_table_mapping", "(", ")", ":", "static_table_mapping", "=", "{", "}", "for", "index", ",", "(", "name", ",", "value", ")", "in", "enumerate", "(", "CocaineHeaders", ".", "STATIC_TABLE", ",", "1", ")", ":", "header_name_search_result", "="...
43.166667
19.666667
def process_event(self, event, client, args, force_dispatch=False): """Process an incoming event. Offers it to each module according to self.module_ordering, continuing to the next unless the module inhibits propagation. Returns True if a module inhibited propagation, otherwise False. ...
[ "def", "process_event", "(", "self", ",", "event", ",", "client", ",", "args", ",", "force_dispatch", "=", "False", ")", ":", "if", "not", "self", ".", "running", ":", "_log", ".", "debug", "(", "\"Ignoring '%s' event - controller not running.\"", ",", "event"...
47.193548
25.451613
def add_property(attribute, type): """Add a property to a class """ def decorator(cls): """Decorator """ private = "_" + attribute def getAttr(self): """Property getter """ if getattr(self, private) is None: setattr(self, p...
[ "def", "add_property", "(", "attribute", ",", "type", ")", ":", "def", "decorator", "(", "cls", ")", ":", "\"\"\"Decorator\n \"\"\"", "private", "=", "\"_\"", "+", "attribute", "def", "getAttr", "(", "self", ")", ":", "\"\"\"Property getter\n \"\...
24.6
11.64
def remove_perm(self, subj_str, perm_str): """Remove permission from a subject. Args: subj_str : str Subject for which to remove permission(s) perm_str : str Permission to remove. Implicitly removes all higher permissions. E.g., ``write`` will al...
[ "def", "remove_perm", "(", "self", ",", "subj_str", ",", "perm_str", ")", ":", "self", ".", "_assert_valid_permission", "(", "perm_str", ")", "for", "perm_str", "in", "self", ".", "_equal_or_higher_perm", "(", "perm_str", ")", ":", "self", ".", "_perm_dict", ...
37.066667
22.6
def shutdown(message=None, timeout=5, force_close=True, reboot=False, # pylint: disable=redefined-outer-name in_seconds=False, only_on_pending_reboot=False): ''' Shutdown a running system. Args: message (str): The message to display to the user before shutting down. ...
[ "def", "shutdown", "(", "message", "=", "None", ",", "timeout", "=", "5", ",", "force_close", "=", "True", ",", "reboot", "=", "False", ",", "# pylint: disable=redefined-outer-name", "in_seconds", "=", "False", ",", "only_on_pending_reboot", "=", "False", ")", ...
38.529412
27.023529
def _serialize_item(item): """Internal function: serialize native types.""" # Recursively serialize lists, tuples, and dicts. if isinstance(item, (list, tuple)): return [_serialize_item(subitem) for subitem in item] elif isinstance(item, dict): return dict([(key, _serialize_item(value)) ...
[ "def", "_serialize_item", "(", "item", ")", ":", "# Recursively serialize lists, tuples, and dicts.", "if", "isinstance", "(", "item", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "_serialize_item", "(", "subitem", ")", "for", "subitem", "in", ...
35.074074
18.555556
def _parse_typed_parameter_typed_value(values): ''' Creates Arguments in a TypedParametervalue. ''' type_, value = _expand_one_key_dictionary(values) _current_parameter_value.type = type_ if _is_simple_type(value): arg = Argument(value) _current_parameter_value.add_argument(arg)...
[ "def", "_parse_typed_parameter_typed_value", "(", "values", ")", ":", "type_", ",", "value", "=", "_expand_one_key_dictionary", "(", "values", ")", "_current_parameter_value", ".", "type", "=", "type_", "if", "_is_simple_type", "(", "value", ")", ":", "arg", "=", ...
32.428571
15
def poll_integration_alert_data(integration_alert): """Poll for updates on waiting IntegrationAlerts.""" logger.info("Polling information for integration alert %s", integration_alert) try: configured_integration = integration_alert.configured_integration integration_actions_instance = config...
[ "def", "poll_integration_alert_data", "(", "integration_alert", ")", ":", "logger", ".", "info", "(", "\"Polling information for integration alert %s\"", ",", "integration_alert", ")", "try", ":", "configured_integration", "=", "integration_alert", ".", "configured_integratio...
47.333333
33.636364
def logical_chassis_fwdl_sanity_output_fwdl_cmd_status(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logical_chassis_fwdl_sanity = ET.Element("logical_chassis_fwdl_sanity") config = logical_chassis_fwdl_sanity output = ET.SubElement(logical_cha...
[ "def", "logical_chassis_fwdl_sanity_output_fwdl_cmd_status", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "logical_chassis_fwdl_sanity", "=", "ET", ".", "Element", "(", "\"logical_chassis_fwdl_sanity\"", ...
46.25
18.166667
def build_paste(uid, shortid, type, nick, time, fmt, code, filename, mime): "Build a 'paste' object" return locals()
[ "def", "build_paste", "(", "uid", ",", "shortid", ",", "type", ",", "nick", ",", "time", ",", "fmt", ",", "code", ",", "filename", ",", "mime", ")", ":", "return", "locals", "(", ")" ]
43.333333
20
def loading(self): """Context manager for when you need to instantiate entities upon unpacking""" if getattr(self, '_initialized', False): raise ValueError("Already loading") self._initialized = False yield self._initialized = True
[ "def", "loading", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'_initialized'", ",", "False", ")", ":", "raise", "ValueError", "(", "\"Already loading\"", ")", "self", ".", "_initialized", "=", "False", "yield", "self", ".", "_initialized", "...
39.571429
11.285714
def get_popular_subreddits(self, *args, **kwargs): """Return a get_content generator for the most active subreddits. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. """ url = self.config['popular_subreddits']...
[ "def", "get_popular_subreddits", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "url", "=", "self", ".", "config", "[", "'popular_subreddits'", "]", "return", "self", ".", "get_content", "(", "url", ",", "*", "args", ",", "*", "*", ...
40.666667
18
def format_image_iter( data_fetch, x_start=0, y_start=0, width=32, height=32, frame=0, columns=1, downsample=1 ): """Return the ANSI escape sequence to render a bitmap image. data_fetch Function that takes three arguments (x position, y position, and frame) and returns a Colour corresponding to...
[ "def", "format_image_iter", "(", "data_fetch", ",", "x_start", "=", "0", ",", "y_start", "=", "0", ",", "width", "=", "32", ",", "height", "=", "32", ",", "frame", "=", "0", ",", "columns", "=", "1", ",", "downsample", "=", "1", ")", ":", "frames",...
36.894737
25.403509
def cli(env, context_id, include): """List IPSEC VPN tunnel context details. Additional resources can be joined using multiple instances of the include option, for which the following choices are available. \b at: address translations is: internal subnets rs: remote subnets sr: statica...
[ "def", "cli", "(", "env", ",", "context_id", ",", "include", ")", ":", "mask", "=", "_get_tunnel_context_mask", "(", "(", "'at'", "in", "include", ")", ",", "(", "'is'", "in", "include", ")", ",", "(", "'rs'", "in", "include", ")", ",", "(", "'sr'", ...
39.04878
16.707317
def save_index(self, filename): ''' Save the current Layout's index to a .json file. Args: filename (str): Filename to write to. Note: At the moment, this won't serialize directory-specific config files. This means reconstructed indexes will only work properly in ca...
[ "def", "save_index", "(", "self", ",", "filename", ")", ":", "data", "=", "{", "}", "for", "f", "in", "self", ".", "files", ".", "values", "(", ")", ":", "entities", "=", "{", "v", ".", "entity", ".", "id", ":", "v", ".", "value", "for", "k", ...
41.375
23.25
def flush(self, meta=None): '''Flush all model keys from the database''' pattern = self.basekey(meta) if meta else self.namespace return self.client.delpattern('%s*' % pattern)
[ "def", "flush", "(", "self", ",", "meta", "=", "None", ")", ":", "pattern", "=", "self", ".", "basekey", "(", "meta", ")", "if", "meta", "else", "self", ".", "namespace", "return", "self", ".", "client", ".", "delpattern", "(", "'%s*'", "%", "pattern...
50
16
def trigger(self, event: str, **kwargs: Any) -> None: """Trigger all handlers for an event to (asynchronously) execute""" event = event.upper() for func in self._event_handlers[event]: self.loop.create_task(func(**kwargs)) # This will unblock anyone that is awaiting on the ne...
[ "def", "trigger", "(", "self", ",", "event", ":", "str", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "event", "=", "event", ".", "upper", "(", ")", "for", "func", "in", "self", ".", "_event_handlers", "[", "event", "]", ":", "sel...
47.636364
13.909091
def version(self): """Get the version of MongoDB that this Server runs as a tuple.""" if not self.__version: command = (self.name, '--version') logger.debug(command) stdout, _ = subprocess.Popen( command, stdout=subprocess.PIPE).communicate() ...
[ "def", "version", "(", "self", ")", ":", "if", "not", "self", ".", "__version", ":", "command", "=", "(", "self", ".", "name", ",", "'--version'", ")", "logger", ".", "debug", "(", "command", ")", "stdout", ",", "_", "=", "subprocess", ".", "Popen", ...
46.5
12.625
def get(self, filename): """ returns subtitles as string """ params = { "v": 'dreambox', "kolejka": "false", "nick": "", "pass": "", "napios": sys.platform, "l": self.language.upper(), "f": self.prepareHash(filename),...
[ "def", "get", "(", "self", ",", "filename", ")", ":", "params", "=", "{", "\"v\"", ":", "'dreambox'", ",", "\"kolejka\"", ":", "\"false\"", ",", "\"nick\"", ":", "\"\"", ",", "\"pass\"", ":", "\"\"", ",", "\"napios\"", ":", "sys", ".", "platform", ",",...
28.290323
18.645161
def _dict_to_fields(d, jsonify=True): """ Convert dict to tuple, for faster sqlite3 import """ x = [] for k in constants._keys: v = d[k] if jsonify and (k in ('attributes', 'extra')): x.append(_jsonify(v)) else: x.append(v) return tuple(x)
[ "def", "_dict_to_fields", "(", "d", ",", "jsonify", "=", "True", ")", ":", "x", "=", "[", "]", "for", "k", "in", "constants", ".", "_keys", ":", "v", "=", "d", "[", "k", "]", "if", "jsonify", "and", "(", "k", "in", "(", "'attributes'", ",", "'e...
25
13.833333
def get_groups(self, condition=None, page_size=1000): """Return an iterator over all groups in this device cloud account Optionally, a condition can be specified to limit the number of groups returned. Examples:: # Get all groups and print information about them ...
[ "def", "get_groups", "(", "self", ",", "condition", "=", "None", ",", "page_size", "=", "1000", ")", ":", "query_kwargs", "=", "{", "}", "if", "condition", "is", "not", "None", ":", "query_kwargs", "[", "\"condition\"", "]", "=", "condition", ".", "compi...
43.59375
24.5625
def fit_predict(self, data, labels, unkown=None): """\ Fit and classify data efficiently. :param data: sparse input matrix (ideal dtype is `numpy.float32`) :type data: :class:`scipy.sparse.csr_matrix` :param labels: the labels associated with data :type labels: iterable ...
[ "def", "fit_predict", "(", "self", ",", "data", ",", "labels", ",", "unkown", "=", "None", ")", ":", "self", ".", "fit", "(", "data", ",", "labels", ")", "return", "self", ".", "_predict_from_bmus", "(", "self", ".", "_bmus", ",", "unkown", ")" ]
39.357143
13.571429
def _check_optimization_errors(self): """ Parses three potential optimization errors: failing to converge within the allowed number of optimization cycles, failure to determine the lamda needed to continue, and inconsistent size of MO files due to a linear dependence in the AO basis. ...
[ "def", "_check_optimization_errors", "(", "self", ")", ":", "if", "read_pattern", "(", "self", ".", "text", ",", "{", "\"key\"", ":", "r\"MAXIMUM OPTIMIZATION CYCLES REACHED\"", "}", ",", "terminate_on_match", "=", "True", ")", ".", "get", "(", "'key'", ")", "...
45.916667
20.75
def _pred(aclass): """ :param aclass :return: boolean """ isaclass = inspect.isclass(aclass) return isaclass and aclass.__module__ == _pred.__module__
[ "def", "_pred", "(", "aclass", ")", ":", "isaclass", "=", "inspect", ".", "isclass", "(", "aclass", ")", "return", "isaclass", "and", "aclass", ".", "__module__", "==", "_pred", ".", "__module__" ]
24
12.571429
def get_sequence_rule_lookup_session_for_bank(self, bank_id, proxy): """Gets the ``OsidSession`` associated with the sequence rule lookup service for the given bank. arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank`` arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessme...
[ "def", "get_sequence_rule_lookup_session_for_bank", "(", "self", ",", "bank_id", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_sequence_rule_lookup", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "##", "# Also include check to see i...
50.833333
21.458333
def update_cluster_topology(self, assignment): """Modify the cluster-topology with given assignment. Change the replica set of partitions as in given assignment. :param assignment: dict representing actions to be used to update the current cluster-topology :raises: InvalidBroke...
[ "def", "update_cluster_topology", "(", "self", ",", "assignment", ")", ":", "try", ":", "for", "partition_name", ",", "replica_ids", "in", "six", ".", "iteritems", "(", "assignment", ")", ":", "try", ":", "new_replicas", "=", "[", "self", ".", "brokers", "...
43.732143
19.839286
def accept_vpc_peering_connection(name=None, conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Accept a VPC pending requested peering connection between two VPCs. name Name of this state conn_id The connection ID to ac...
[ "def", "accept_vpc_peering_connection", "(", "name", "=", "None", ",", "conn_id", "=", "None", ",", "conn_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "log", ...
28.74026
26.324675
def get_typeof(self, name): """Get the GType of a GObject property. This function returns 0 if the property does not exist. """ # logger.debug('VipsObject.get_typeof: self = %s, name = %s', # str(self), name) pspec = self._get_pspec(name) if pspec...
[ "def", "get_typeof", "(", "self", ",", "name", ")", ":", "# logger.debug('VipsObject.get_typeof: self = %s, name = %s',", "# str(self), name)", "pspec", "=", "self", ".", "_get_pspec", "(", "name", ")", "if", "pspec", "is", "None", ":", "# need to clear any...
26.176471
20.411765
def add_context(self, name, indices, level=None): """ Add a new context level to the hierarchy. By default, new contexts are added to the lowest level of the hierarchy. To insert the context elsewhere in the hierarchy, use the ``level`` argument. For example, ``level=0`` would i...
[ "def", "add_context", "(", "self", ",", "name", ",", "indices", ",", "level", "=", "None", ")", ":", "self", ".", "_validate_context", "(", "(", "name", ",", "indices", ")", ")", "if", "level", "is", "None", ":", "level", "=", "len", "(", "self", "...
34.423077
21.576923
def decipher_atom_keys(self, forcefield='DLF', dict_key='atom_ids'): """ Decipher force field atom ids. This takes all values in :attr:`MolecularSystem.system['atom_ids']` that match force field type criteria and creates :attr:`MolecularSystem.system['elements']` with the corres...
[ "def", "decipher_atom_keys", "(", "self", ",", "forcefield", "=", "'DLF'", ",", "dict_key", "=", "'atom_ids'", ")", ":", "# In case there is no 'atom_ids' key we try 'elements'. This is for", "# XYZ and MOL files mostly. But, we keep the dict_key keyword for", "# someone who would wa...
40.957447
22.234043
def set(self, value): """ Sets the value of the object :param value: A unicode string containing an IPv4 address, IPv4 address with CIDR, an IPv6 address or IPv6 address with CIDR """ if not isinstance(value, str_cls): raise TypeError(unwrap(...
[ "def", "set", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str_cls", ")", ":", "raise", "TypeError", "(", "unwrap", "(", "'''\n %s value must be a unicode string, not %s\n '''", ",", "type_name", "...
30.928571
16.328571
def pivot(self, index, column, value): """ Pivot the frame designated by the three columns: index, column, and value. Index and column should be of type enum, int, or time. For cases of multiple indexes for a column label, the aggregation method is to pick the first occurrence in the dat...
[ "def", "pivot", "(", "self", ",", "index", ",", "column", ",", "value", ")", ":", "assert_is_type", "(", "index", ",", "str", ")", "assert_is_type", "(", "column", ",", "str", ")", "assert_is_type", "(", "value", ",", "str", ")", "col_names", "=", "sel...
51.269231
22.269231
def get_sms_connection(backend=None, fail_silently=False, **kwds): """Load an sms backend and return an instance of it. If backend is None (default) settings.SMS_BACKEND is used. Both fail_silently and other keyword arguments are used in the constructor of the backend. https://github.com/django/django/blob/mast...
[ "def", "get_sms_connection", "(", "backend", "=", "None", ",", "fail_silently", "=", "False", ",", "*", "*", "kwds", ")", ":", "klass", "=", "import_string", "(", "backend", "or", "settings", ".", "SMS_BACKEND", ")", "return", "klass", "(", "fail_silently", ...
38
21.916667
def assert_valid_rule_class(clazz): """ Asserts that a given rule clazz is valid by checking a number of its properties: - Rules must extend from LineRule or CommitRule - Rule classes must have id and name string attributes. The options_spec is optional, but if set, it must be a list of gitlin...
[ "def", "assert_valid_rule_class", "(", "clazz", ")", ":", "# Rules must extend from LineRule or CommitRule", "if", "not", "(", "issubclass", "(", "clazz", ",", "rules", ".", "LineRule", ")", "or", "issubclass", "(", "clazz", ",", "rules", ".", "CommitRule", ")", ...
63.472727
36.927273
def filename_matches_glob(filename: str, globtext: str) -> bool: """ The ``glob.glob`` function doesn't do exclusion very well. We don't want to have to specify root directories for exclusion patterns. We don't want to have to trawl a massive set of files to find exclusion files....
[ "def", "filename_matches_glob", "(", "filename", ":", "str", ",", "globtext", ":", "str", ")", "->", "bool", ":", "# Quick check on basename-only matching", "if", "fnmatch", "(", "filename", ",", "globtext", ")", ":", "log", ".", "debug", "(", "\"{!r} matches {!...
33.9
21.366667
def _inject_target(self, target_adaptor): """Inject a target, respecting all sources of dependencies.""" target_cls = self._target_types[target_adaptor.type_alias] declared_deps = target_adaptor.dependencies implicit_deps = (Address.parse(s, relative_to=target_adaptor...
[ "def", "_inject_target", "(", "self", ",", "target_adaptor", ")", ":", "target_cls", "=", "self", ".", "_target_types", "[", "target_adaptor", ".", "type_alias", "]", "declared_deps", "=", "target_adaptor", ".", "dependencies", "implicit_deps", "=", "(", "Address"...
55.384615
23.384615
def normal(self, t, i): """Handle normal chars.""" current = [] if t == "\\": try: t = next(i) current.extend(self.reference(t, i)) except StopIteration: current.append(t) elif t == "(": current.extend(...
[ "def", "normal", "(", "self", ",", "t", ",", "i", ")", ":", "current", "=", "[", "]", "if", "t", "==", "\"\\\\\"", ":", "try", ":", "t", "=", "next", "(", "i", ")", "current", ".", "extend", "(", "self", ".", "reference", "(", "t", ",", "i", ...
27.85
16.15
def allele_counts_dataframe(variant_and_allele_reads_generator): """ Creates a DataFrame containing number of reads supporting the ref vs. alt alleles for each variant. """ df_builder = DataFrameBuilder( AlleleCount, extra_column_fns={ "gene": lambda variant, _: ";".join(...
[ "def", "allele_counts_dataframe", "(", "variant_and_allele_reads_generator", ")", ":", "df_builder", "=", "DataFrameBuilder", "(", "AlleleCount", ",", "extra_column_fns", "=", "{", "\"gene\"", ":", "lambda", "variant", ",", "_", ":", "\";\"", ".", "join", "(", "va...
39.642857
15.071429
def scandir(path, app=None): ''' Config-aware scandir. Currently, only aware of ``exclude_fnc``. :param path: absolute path :type path: str :param app: flask application :type app: flask.Flask or None :returns: filtered scandir entries :rtype: iterator ''' exclude = app and app....
[ "def", "scandir", "(", "path", ",", "app", "=", "None", ")", ":", "exclude", "=", "app", "and", "app", ".", "config", ".", "get", "(", "'exclude_fnc'", ")", "if", "exclude", ":", "return", "(", "item", "for", "item", "in", "compat", ".", "scandir", ...
26.631579
17.789474
def put_meta(request): """MNStorage.updateSystemMetadata(session, pid, sysmeta) → boolean. TODO: Currently, this call allows making breaking changes to SysMeta. We need to clarify what can be modified and what the behavior should be when working with SIDs and chains. """ if django.conf.setting...
[ "def", "put_meta", "(", "request", ")", ":", "if", "django", ".", "conf", ".", "settings", ".", "REQUIRE_WHITELIST_FOR_UPDATE", ":", "d1_gmn", ".", "app", ".", "auth", ".", "assert_create_update_delete_permission", "(", "request", ")", "d1_gmn", ".", "app", "....
42.366667
23.833333
def snmp_server_agtconfig_location(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") agtconfig = ET.SubElement(snmp_server, "agtconfig") location = ET.Sub...
[ "def", "snmp_server_agtconfig_location", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "snmp_server", "=", "ET", ".", "SubElement", "(", "config", ",", "\"snmp-server\"", ",", "xmlns", "=", "\"...
43.454545
16.454545
def get_public_key_info(self): """ Analyze the public key information we have in our scriptSig. Returns {'status': true, 'type': 'singlesig' | 'multisig', 'public_keys': [...], 'num_sigs': ...} on success Returns {'error': ...} on error """ script_parts = virtualchain.btc...
[ "def", "get_public_key_info", "(", "self", ")", ":", "script_parts", "=", "virtualchain", ".", "btc_script_deserialize", "(", "base64", ".", "b64decode", "(", "self", ".", "sig", ")", ")", "if", "len", "(", "script_parts", ")", "<", "2", ":", "return", "{"...
49.078947
33.342105
def failure(path, downloader): """Display warning message via stderr or GUI.""" base = os.path.basename(path) if sys.stdin.isatty(): print('INFO [{}]: Failed to download {!r}'.format(downloader, base)) else: notify_failure(base, downloader)
[ "def", "failure", "(", "path", ",", "downloader", ")", ":", "base", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "sys", ".", "stdin", ".", "isatty", "(", ")", ":", "print", "(", "'INFO [{}]: Failed to download {!r}'", ".", "format", ...
38
14
def json(self): """Produce a JSON representation for the web interface""" d = { 'id': self.id, 'format': self.formatclass.__name__,'label': self.label, 'mimetype': self.formatclass.mimetype, 'schema': self.formatclass.schema } if self.unique: d['unique'] = True if self.filen...
[ "def", "json", "(", "self", ")", ":", "d", "=", "{", "'id'", ":", "self", ".", "id", ",", "'format'", ":", "self", ".", "formatclass", ".", "__name__", ",", "'label'", ":", "self", ".", "label", ",", "'mimetype'", ":", "self", ".", "formatclass", "...
49.590909
27.363636
def get_service_location_info(self, service_location_id): """ Request service location info Parameters ---------- service_location_id : int Returns ------- dict """ url = urljoin(URLS['servicelocation'], service_location_id, "info") ...
[ "def", "get_service_location_info", "(", "self", ",", "service_location_id", ")", ":", "url", "=", "urljoin", "(", "URLS", "[", "'servicelocation'", "]", ",", "service_location_id", ",", "\"info\"", ")", "headers", "=", "{", "\"Authorization\"", ":", "\"Bearer {}\...
27.823529
19.588235
def timeout(seconds, err_msg="xtls: function run too long."): """ 超时检测 :param seconds: 函数最长运行时间 :param err_msg: 超时提示 """ def decorator(function): def _on_timeout(signum, frame): raise TimeoutError(err_msg) @wraps(function) def wrapper(*args, **kwargs): ...
[ "def", "timeout", "(", "seconds", ",", "err_msg", "=", "\"xtls: function run too long.\"", ")", ":", "def", "decorator", "(", "function", ")", ":", "def", "_on_timeout", "(", "signum", ",", "frame", ")", ":", "raise", "TimeoutError", "(", "err_msg", ")", "@"...
23.875
17.125
def unwrap_or(self, default: U) -> Union[T, U]: """ Returns the contained value or ``default``. Args: default: The default value. Returns: The contained value if the :py:class:`Option` is ``Some``, otherwise ``default``. Notes: I...
[ "def", "unwrap_or", "(", "self", ",", "default", ":", "U", ")", "->", "Union", "[", "T", ",", "U", "]", ":", "return", "self", ".", "unwrap_or_else", "(", "lambda", ":", "default", ")" ]
27.863636
20.681818
def init_app(self, app): """ Initialize the captcha extension to the given app object. """ self.enabled = app.config.get("CAPTCHA_ENABLE", True) self.digits = app.config.get("CAPTCHA_LENGTH", 4) self.max = 10**self.digits self.image_generator = ImageCaptcha() ...
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "self", ".", "enabled", "=", "app", ".", "config", ".", "get", "(", "\"CAPTCHA_ENABLE\"", ",", "True", ")", "self", ".", "digits", "=", "app", ".", "config", ".", "get", "(", "\"CAPTCHA_LENGTH\"", ...
52
27.407407
def construct_xblock(self, block_type, scope_ids, field_data=None, *args, **kwargs): r""" Construct a new xblock of the type identified by block_type, passing \*args and \*\*kwargs into `__init__`. """ return self.construct_xblock_from_class( cls=self.load_block_type(...
[ "def", "construct_xblock", "(", "self", ",", "block_type", ",", "scope_ids", ",", "field_data", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "construct_xblock_from_class", "(", "cls", "=", "self", ".", "load_bloc...
38.909091
14.636364
def single_node_env(args): """Sets up environment for a single-node TF session. Args: :args: command line arguments as either argparse args or argv list """ # setup ARGV for the TF process if isinstance(args, list): sys.argv = args elif args.argv: sys.argv = args.argv # setup ENV for Had...
[ "def", "single_node_env", "(", "args", ")", ":", "# setup ARGV for the TF process", "if", "isinstance", "(", "args", ",", "list", ")", ":", "sys", ".", "argv", "=", "args", "elif", "args", ".", "argv", ":", "sys", ".", "argv", "=", "args", ".", "argv", ...
28.933333
18.333333
def Point2HexColor(a, lfrac, tfrac): """ Return web-safe hex triplets. """ [H,S,V] = [math.floor(360 * a), lfrac, tfrac] RGB = hsvToRGB(H, S, V) H = [hex(int(math.floor(255 * x))) for x in RGB] HEX = [a[a.find('x') + 1:] for a in H] HEX = ['0' + h if len(h) == 1 else h for h in HEX]...
[ "def", "Point2HexColor", "(", "a", ",", "lfrac", ",", "tfrac", ")", ":", "[", "H", ",", "S", ",", "V", "]", "=", "[", "math", ".", "floor", "(", "360", "*", "a", ")", ",", "lfrac", ",", "tfrac", "]", "RGB", "=", "hsvToRGB", "(", "H", ",", "...
21
19.5
def get_installed_version(dist_name, working_set=None): """Get the installed version of dist_name avoiding pkg_resources cache""" # Create a requirement that we'll look for inside of setuptools. req = pkg_resources.Requirement.parse(dist_name) if working_set is None: # We want to avoid having t...
[ "def", "get_installed_version", "(", "dist_name", ",", "working_set", "=", "None", ")", ":", "# Create a requirement that we'll look for inside of setuptools.", "req", "=", "pkg_resources", ".", "Requirement", ".", "parse", "(", "dist_name", ")", "if", "working_set", "i...
42.125
18.8125
def addmags(*mags): """ mags is either list of magnitudes or list of (mag, err) pairs """ tot = 0 uncs = [] for mag in mags: try: tot += 10**(-0.4*mag) except: m, dm = mag f = 10**(-0.4*m) tot += f unc = f * (1 - 10**(-0...
[ "def", "addmags", "(", "*", "mags", ")", ":", "tot", "=", "0", "uncs", "=", "[", "]", "for", "mag", "in", "mags", ":", "try", ":", "tot", "+=", "10", "**", "(", "-", "0.4", "*", "mag", ")", "except", ":", "m", ",", "dm", "=", "mag", "f", ...
24.363636
17.909091
def on_start(self): """ start the service """ LOGGER.debug("natsd.Service.on_start") self.service = threading.Thread(target=self.run_event_loop, name=self.serviceQ + " service thread") self.service.start() while not self.is_started: time.sleep(0.01)
[ "def", "on_start", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"natsd.Service.on_start\"", ")", "self", ".", "service", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "run_event_loop", ",", "name", "=", "self", ".", "serviceQ",...
34.333333
15.444444
def SNM0(T, Tc, Vc, omega, delta_SRK=None): r'''Calculates saturated liquid density using the Mchaweh, Moshfeghian model [1]_. Designed for simple calculations. .. math:: V_s = V_c/(1+1.169\tau^{1/3}+1.818\tau^{2/3}-2.658\tau+2.161\tau^{4/3} \tau = 1-\frac{(T/T_c)}{\alpha_{SRK}} \...
[ "def", "SNM0", "(", "T", ",", "Tc", ",", "Vc", ",", "omega", ",", "delta_SRK", "=", "None", ")", ":", "Tr", "=", "T", "/", "Tc", "m", "=", "0.480", "+", "1.574", "*", "omega", "-", "0.176", "*", "omega", "*", "omega", "alpha_SRK", "=", "(", "...
28.628571
24.342857
def write_branch_data(self, file): """ Writes branch data to file. """ branch_attr = ["r", "x", "b", "rate_a", "rate_b", "rate_c", "ratio", "phase_shift", "online", "ang_min", "ang_max", "p_from", "q_from", "p_to", "q_to", "mu_s_from", "mu_s_to", "mu_angmin", ...
[ "def", "write_branch_data", "(", "self", ",", "file", ")", ":", "branch_attr", "=", "[", "\"r\"", ",", "\"x\"", ",", "\"b\"", ",", "\"rate_a\"", ",", "\"rate_b\"", ",", "\"rate_c\"", ",", "\"ratio\"", ",", "\"phase_shift\"", ",", "\"online\"", ",", "\"ang_mi...
40.481481
17.296296
def update_presubscriptions(self, presubscriptions): """Update pre-subscription data. Pre-subscription data will be removed for empty list. :param presubscriptions: list of `Presubscription` objects (Required) :returns: None """ api = self._get_api(mds.SubscriptionsApi) ...
[ "def", "update_presubscriptions", "(", "self", ",", "presubscriptions", ")", ":", "api", "=", "self", ".", "_get_api", "(", "mds", ".", "SubscriptionsApi", ")", "presubscriptions_list", "=", "[", "]", "for", "presubscription", "in", "presubscriptions", ":", "if"...
50.666667
20.388889
def getPrimaryRole(store, primaryRoleName, createIfNotFound=False): """ Get Role object corresponding to an identifier name. If the role name passed is the empty string, it is assumed that the user is not authenticated, and the 'Everybody' role is primary. If the role name passed is non-empty, but...
[ "def", "getPrimaryRole", "(", "store", ",", "primaryRoleName", ",", "createIfNotFound", "=", "False", ")", ":", "if", "not", "primaryRoleName", ":", "return", "getEveryoneRole", "(", "store", ")", "ff", "=", "store", ".", "findUnique", "(", "Role", ",", "Rol...
44.787879
24
def update_aliases( cr, registry, model_name, set_parent_thread_id, alias_defaults=None, defaults_id_key=False): """ Update a model's aliases according to how they are configured in the model's create() method. :param model_name: The name of the model whose aliases are to be updated. \ ...
[ "def", "update_aliases", "(", "cr", ",", "registry", ",", "model_name", ",", "set_parent_thread_id", ",", "alias_defaults", "=", "None", ",", "defaults_id_key", "=", "False", ")", ":", "model_id", "=", "registry", "[", "'ir.model'", "]", ".", "search", "(", ...
44.15625
15.15625
def validate(self, raw_data, **kwargs): """Convert the raw_data to a float. """ try: converted_data = float(raw_data) super(FloatField, self).validate(converted_data, **kwargs) return raw_data except ValueError: raise ValidationException(s...
[ "def", "validate", "(", "self", ",", "raw_data", ",", "*", "*", "kwargs", ")", ":", "try", ":", "converted_data", "=", "float", "(", "raw_data", ")", "super", "(", "FloatField", ",", "self", ")", ".", "validate", "(", "converted_data", ",", "*", "*", ...
35.1
16.9
def main(): """Main function. Mostly parsing the command line arguments. """ parser = argparse.ArgumentParser() parser.add_argument('--backend', choices=['gatttool', 'bluepy', 'pygatt'], default='gatttool') parser.add_argument('-v', '--verbose', action='store_const', const=True) subparsers ...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'--backend'", ",", "choices", "=", "[", "'gatttool'", ",", "'bluepy'", ",", "'pygatt'", "]", ",", "default", "=", "'gatttool'", ...
32.7
24.1
def is_base_form(self, univ_pos, morphology=None): """ Check whether we're dealing with an uninflected paradigm, so we can avoid lemmatization entirely. """ morphology = {} if morphology is None else morphology others = [key for key in morphology if key ...
[ "def", "is_base_form", "(", "self", ",", "univ_pos", ",", "morphology", "=", "None", ")", ":", "morphology", "=", "{", "}", "if", "morphology", "is", "None", "else", "morphology", "others", "=", "[", "key", "for", "key", "in", "morphology", "if", "key", ...
42.419355
17.516129
def _put_input(self, input_source: str) -> None: """Put input string to ffmpeg command.""" input_cmd = shlex.split(str(input_source)) if len(input_cmd) > 1: self._argv.extend(input_cmd) else: self._argv.extend(["-i", input_source])
[ "def", "_put_input", "(", "self", ",", "input_source", ":", "str", ")", "->", "None", ":", "input_cmd", "=", "shlex", ".", "split", "(", "str", "(", "input_source", ")", ")", "if", "len", "(", "input_cmd", ")", ">", "1", ":", "self", ".", "_argv", ...
40.142857
9.428571
def add_mag_drifts(inst): """Adds ion drifts in magnetic coordinates using ion drifts in S/C coordinates along with pre-calculated unit vectors for magnetic coordinates. Note ---- Requires ion drifts under labels 'iv_*' where * = (x,y,z) along with unit vectors labels 'unit_zonal_*'...
[ "def", "add_mag_drifts", "(", "inst", ")", ":", "inst", "[", "'iv_zon'", "]", "=", "{", "'data'", ":", "inst", "[", "'unit_zon_x'", "]", "*", "inst", "[", "'iv_x'", "]", "+", "inst", "[", "'unit_zon_y'", "]", "*", "inst", "[", "'iv_y'", "]", "+", "...
51.492958
26.887324
def on(self, image): """ Project polygons from one image to a new one. Parameters ---------- image : ndarray or tuple of int New image onto which the polygons are to be projected. May also simply be that new image's shape tuple. Returns -...
[ "def", "on", "(", "self", ",", "image", ")", ":", "shape", "=", "normalize_shape", "(", "image", ")", "if", "shape", "[", "0", ":", "2", "]", "==", "self", ".", "shape", "[", "0", ":", "2", "]", ":", "return", "self", ".", "deepcopy", "(", ")",...
30.954545
17.136364
def sleep(self): """Sleep""" try: self.send_command("SLEEP") return True except requests.exceptions.RequestException: _LOGGER.error("Connection error: sleep command not sent.") return False
[ "def", "sleep", "(", "self", ")", ":", "try", ":", "self", ".", "send_command", "(", "\"SLEEP\"", ")", "return", "True", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "_LOGGER", ".", "error", "(", "\"Connection error: sleep command not s...
31.75
16.125
def to_bytes(s, encoding=None, errors='strict'): """Returns a bytestring version of 's', encoded as specified in 'encoding'.""" encoding = encoding or 'utf-8' if isinstance(s, bytes): if encoding != 'utf-8': return s.decode('utf-8', errors).encode(encoding, errors) else: ...
[ "def", "to_bytes", "(", "s", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ")", ":", "encoding", "=", "encoding", "or", "'utf-8'", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "if", "encoding", "!=", "'utf-8'", ":", "return", ...
35.166667
11.583333
def cnst_AT(self, X): r"""Compute :math:`A^T \mathbf{x}` where :math:`A \mathbf{x}` is a component of ADMM problem constraint. In this case :math:`A^T \mathbf{x} = (G_r^T \;\; G_c^T) \mathbf{x}`. """ return np.sum(np.concatenate( [sl.GTax(X[..., ax], ax)[..., np.newa...
[ "def", "cnst_AT", "(", "self", ",", "X", ")", ":", "return", "np", ".", "sum", "(", "np", ".", "concatenate", "(", "[", "sl", ".", "GTax", "(", "X", "[", "...", ",", "ax", "]", ",", "ax", ")", "[", "...", ",", "np", ".", "newaxis", "]", "fo...
42.333333
15.777778
def remove_unique_identifiers(identifiers_to_tags, pipeline_links): """Removes unique identifiers and add the original process names to the already parsed pipelines Parameters ---------- identifiers_to_tags : dict Match between unique process identifiers and process names pipeline_links...
[ "def", "remove_unique_identifiers", "(", "identifiers_to_tags", ",", "pipeline_links", ")", ":", "# Replaces the unique identifiers by the original process names", "for", "index", ",", "val", "in", "enumerate", "(", "pipeline_links", ")", ":", "if", "val", "[", "\"input\"...
33
19.222222
def flush(self) -> None: """ To act as a file. """ self.underlying_stream.flush() self.file.flush() os.fsync(self.file.fileno())
[ "def", "flush", "(", "self", ")", "->", "None", ":", "self", ".", "underlying_stream", ".", "flush", "(", ")", "self", ".", "file", ".", "flush", "(", ")", "os", ".", "fsync", "(", "self", ".", "file", ".", "fileno", "(", ")", ")" ]
24.285714
7.428571
def category_structure(category, site): """ A category structure. """ return {'description': category.title, 'htmlUrl': '%s://%s%s' % ( PROTOCOL, site.domain, category.get_absolute_url()), 'rssUrl': '%s://%s%s' % ( PROTOCOL, site.do...
[ "def", "category_structure", "(", "category", ",", "site", ")", ":", "return", "{", "'description'", ":", "category", ".", "title", ",", "'htmlUrl'", ":", "'%s://%s%s'", "%", "(", "PROTOCOL", ",", "site", ".", "domain", ",", "category", ".", "get_absolute_ur...
39.875
7.375
def root(self, value): """Set new XML tree""" self._xml = t2s(value) self._root = value
[ "def", "root", "(", "self", ",", "value", ")", ":", "self", ".", "_xml", "=", "t2s", "(", "value", ")", "self", ".", "_root", "=", "value" ]
21.6
16.4
def _compile_iterable(self, schema): """ Compile iterable: iterable of schemas treated as allowed values """ # Compile each member as a schema schema_type = type(schema) schema_subs = tuple(map(self.sub_compile, schema)) # When the schema is an iterable with a single item (e.g. ...
[ "def", "_compile_iterable", "(", "self", ",", "schema", ")", ":", "# Compile each member as a schema", "schema_type", "=", "type", "(", "schema", ")", "schema_subs", "=", "tuple", "(", "map", "(", "self", ".", "sub_compile", ",", "schema", ")", ")", "# When th...
42.138462
21.353846
def select_features(self, *args, **kwargs): """ Select one or more fields as feature fields. :rtype: DataFrame """ if not args: raise ValueError("Field list cannot be empty.") # generate selected set from args augment = kwargs.get('add', False) ...
[ "def", "select_features", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "args", ":", "raise", "ValueError", "(", "\"Field list cannot be empty.\"", ")", "# generate selected set from args", "augment", "=", "kwargs", ".", "get", ...
35.769231
11.769231
def load_jamfile(self, dir, jamfile_module): """Load a Jamfile at the given directory. Returns nothing. Will attempt to load the file as indicated by the JAMFILE patterns. Effect of calling this rule twice with the same 'dir' is underfined.""" assert isinstance(dir, basestring) a...
[ "def", "load_jamfile", "(", "self", ",", "dir", ",", "jamfile_module", ")", ":", "assert", "isinstance", "(", "dir", ",", "basestring", ")", "assert", "isinstance", "(", "jamfile_module", ",", "basestring", ")", "# See if the Jamfile is where it should be.", "is_jam...
45.55
20.6125
def generate_data_with_shared_vocab(self, data_dir, tmp_dir, task_id=-1): """Generates TF-Records for problems using a global vocabulary file.""" global_vocab_filename = os.path.join(data_dir, self.vocab_filename) if not tf.gfile.Exists(global_vocab_filename): raise ValueError( 'Global vocab...
[ "def", "generate_data_with_shared_vocab", "(", "self", ",", "data_dir", ",", "tmp_dir", ",", "task_id", "=", "-", "1", ")", ":", "global_vocab_filename", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "self", ".", "vocab_filename", ")", "if", "...
59.666667
21.333333