text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def load_user_catalog(): """Return a catalog for the platform-specific user Intake directory""" cat_dir = user_data_dir() if not os.path.isdir(cat_dir): return Catalog() else: return YAMLFilesCatalog(cat_dir)
[ "def", "load_user_catalog", "(", ")", ":", "cat_dir", "=", "user_data_dir", "(", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "cat_dir", ")", ":", "return", "Catalog", "(", ")", "else", ":", "return", "YAMLFilesCatalog", "(", "cat_dir", ")" ]
33.428571
11.428571
def verify(self, windowSize=None): """Checks the stimulus, including expanded parameters for invalidating conditions :param windowSize: acquistion (recording) window size (seconds) :type windowSize: float :returns: str -- error message, if any, 0 otherwise""" if self.samplerate(...
[ "def", "verify", "(", "self", ",", "windowSize", "=", "None", ")", ":", "if", "self", ".", "samplerate", "(", ")", "is", "None", ":", "return", "\"Multiple recording files with conflicting samplerates\"", "msg", "=", "self", ".", "_autoParams", ".", "verify", ...
45.185185
16.481481
def get_roles(self): """Get the roles associated with the hosts. Returns dict of role -> [host] """ machines = self.c_resources["machines"] result = {} for desc in machines: roles = utils.get_roles_as_list(desc) hosts = self._denormal...
[ "def", "get_roles", "(", "self", ")", ":", "machines", "=", "self", ".", "c_resources", "[", "\"machines\"", "]", "result", "=", "{", "}", "for", "desc", "in", "machines", ":", "roles", "=", "utils", ".", "get_roles_as_list", "(", "desc", ")", "hosts", ...
28.375
13.5
def _write_line(self, indent_string, entry, this_entry, comment): """Write an individual line, for the write method""" # NOTE: the calls to self._quote here handles non-StringType values. if not self.unrepr: val = self._decode_element(self._quote(this_entry)) else: ...
[ "def", "_write_line", "(", "self", ",", "indent_string", ",", "entry", ",", "this_entry", ",", "comment", ")", ":", "# NOTE: the calls to self._quote here handles non-StringType values.", "if", "not", "self", ".", "unrepr", ":", "val", "=", "self", ".", "_decode_ele...
51.583333
18.416667
async def certify(client: Client, certification_signed_raw: str) -> ClientResponse: """ POST certification raw document :param client: Client to connect to the api :param certification_signed_raw: Certification raw document :return: """ return await client.post(MODULE + '/certify', {'cert':...
[ "async", "def", "certify", "(", "client", ":", "Client", ",", "certification_signed_raw", ":", "str", ")", "->", "ClientResponse", ":", "return", "await", "client", ".", "post", "(", "MODULE", "+", "'/certify'", ",", "{", "'cert'", ":", "certification_signed_r...
40.333333
23.888889
def send(evt): "Process an outgoing communication" # get the text written by the user (input textbox control) msg = ctrl_input.value # send the message (replace with socket/queue/etc.) gui.alert(msg, "Message") # record the message (update the UI) log(msg) ctrl_input.value = "" ctrl_...
[ "def", "send", "(", "evt", ")", ":", "# get the text written by the user (input textbox control)", "msg", "=", "ctrl_input", ".", "value", "# send the message (replace with socket/queue/etc.)", "gui", ".", "alert", "(", "msg", ",", "\"Message\"", ")", "# record the message ...
32.8
14.6
def create_usage(self, sub_add_on, usage): """Record the usage on the given subscription add on and update the usage object with returned xml""" url = urljoin(self._url, '/add_ons/%s/usage' % (sub_add_on.add_on_code,)) return usage.post(url)
[ "def", "create_usage", "(", "self", ",", "sub_add_on", ",", "usage", ")", ":", "url", "=", "urljoin", "(", "self", ".", "_url", ",", "'/add_ons/%s/usage'", "%", "(", "sub_add_on", ".", "add_on_code", ",", ")", ")", "return", "usage", ".", "post", "(", ...
53.8
10.6
def name(self, name): """ Set the name of this object. Tell the parent if the name has changed. """ from_name = self.name assert isinstance(name, str) self._name = name if self.has_parent(): self._parent_._name_changed(self, from_name)
[ "def", "name", "(", "self", ",", "name", ")", ":", "from_name", "=", "self", ".", "name", "assert", "isinstance", "(", "name", ",", "str", ")", "self", ".", "_name", "=", "name", "if", "self", ".", "has_parent", "(", ")", ":", "self", ".", "_parent...
30.2
8.8
def open(filename, frame='unspecified'): """ Opens a segmentation image """ data = Image.load_data(filename) return SegmentationImage(data, frame)
[ "def", "open", "(", "filename", ",", "frame", "=", "'unspecified'", ")", ":", "data", "=", "Image", ".", "load_data", "(", "filename", ")", "return", "SegmentationImage", "(", "data", ",", "frame", ")" ]
41.75
1.25
def parse_rule(tokens, variables, neighbors, parents, is_merc): """ Parse a rule set, return a list of declarations. Requires a dictionary of declared variables. Selectors in the neighbors list are simply grouped, and are generated from comma-delimited lists of selectors in the styl...
[ "def", "parse_rule", "(", "tokens", ",", "variables", ",", "neighbors", ",", "parents", ",", "is_merc", ")", ":", "#", "# Local helper function", "#", "def", "validate_selector_elements", "(", "elements", ",", "line", ",", "col", ")", ":", "if", "len", "(", ...
38.59434
22.90566
def handle_msg(self, payload): """ Handle message for network plugin protocol :param payload: Received message :type payload: dict :return: Response to send (if set) :rtype: None | dict """ self.debug(u"\n{}".format(pformat(payload))) msg = payloa...
[ "def", "handle_msg", "(", "self", ",", "payload", ")", ":", "self", ".", "debug", "(", "u\"\\n{}\"", ".", "format", "(", "pformat", "(", "payload", ")", ")", ")", "msg", "=", "payload", "[", "'msg'", "]", "res", "=", "{", "'msg'", ":", "msg", ",", ...
38.119403
13.41791
def send_cmd_recv_rsp(self, cmd_code, cmd_data, timeout, send_idm=True, check_status=True): """Send a command and receive a response. This low level method sends an arbitrary command with the 8-bit integer *cmd_code*, followed by the captured tag identifier (ID...
[ "def", "send_cmd_recv_rsp", "(", "self", ",", "cmd_code", ",", "cmd_data", ",", "timeout", ",", "send_idm", "=", "True", ",", "check_status", "=", "True", ")", ":", "idm", "=", "self", ".", "idm", "if", "send_idm", "else", "bytearray", "(", ")", "cmd", ...
48.507937
20.857143
def _set_annotation_to_str(annotation_data: Mapping[str, Mapping[str, bool]], key: str) -> str: """Return a set annotation string.""" value = annotation_data[key] if len(value) == 1: return 'SET {} = "{}"'.format(key, list(value)[0]) x = ('"{}"'.format(v) for v in sorted(value)) return 'S...
[ "def", "_set_annotation_to_str", "(", "annotation_data", ":", "Mapping", "[", "str", ",", "Mapping", "[", "str", ",", "bool", "]", "]", ",", "key", ":", "str", ")", "->", "str", ":", "value", "=", "annotation_data", "[", "key", "]", "if", "len", "(", ...
35.2
24.1
def read(self, entity=None, attrs=None, ignore=None, params=None): """Fetch an attribute missing from the server's response. For more information, see `Bugzilla #1237257 <https://bugzilla.redhat.com/show_bug.cgi?id=1237257>`_. Add content_view_component to the response if needed, as ...
[ "def", "read", "(", "self", ",", "entity", "=", "None", ",", "attrs", "=", "None", ",", "ignore", "=", "None", ",", "params", "=", "None", ")", ":", "if", "attrs", "is", "None", ":", "attrs", "=", "self", ".", "read_json", "(", ")", "if", "_get_v...
43.133333
19.8
def remove(self, doc_type, doc_ids, **kwargs): """ Implements call to remove the documents from the index """ try: # ignore is flagged as an unexpected-keyword-arg; ES python client documents that it can be used # pylint: disable=unexpected-keyword-arg actions = [] ...
[ "def", "remove", "(", "self", ",", "doc_type", ",", "doc_ids", ",", "*", "*", "kwargs", ")", ":", "try", ":", "# ignore is flagged as an unexpected-keyword-arg; ES python client documents that it can be used", "# pylint: disable=unexpected-keyword-arg", "actions", "=", "[", ...
42.913043
20.130435
def get_checkpoint_files(self): """ Return a list of checkpoint files for this DAG node and its job. """ checkpoint_files = list(self.__checkpoint_files) if isinstance(self.job(), CondorDAGJob): checkpoint_files = checkpoint_files + self.job().get_checkpoint_files() return checkpoint_fil...
[ "def", "get_checkpoint_files", "(", "self", ")", ":", "checkpoint_files", "=", "list", "(", "self", ".", "__checkpoint_files", ")", "if", "isinstance", "(", "self", ".", "job", "(", ")", ",", "CondorDAGJob", ")", ":", "checkpoint_files", "=", "checkpoint_files...
39.375
13.125
def curve_fit(self): """ Fits `scipy_data_fitting.Fit.function` to the data and returns the output from the specified curve fit function. See `scipy_data_fitting.Fit.options` for details on how to control or override the the curve fitting algorithm. """ if not ha...
[ "def", "curve_fit", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_curve_fit'", ")", ":", "options", "=", "self", ".", "options", ".", "copy", "(", ")", "fit_function", "=", "options", ".", "pop", "(", "'fit_function'", ")", "indep...
43.916667
20.833333
def read(self, section, option): """Read from file. Parameters ---------- section : string Section. option : string Option. Returns ------- string Value. """ self.config.read(self.filepath) raw ...
[ "def", "read", "(", "self", ",", "section", ",", "option", ")", ":", "self", ".", "config", ".", "read", "(", "self", ".", "filepath", ")", "raw", "=", "self", ".", "config", ".", "get", "(", "section", ",", "option", ")", "out", "=", "tidy_headers...
22.157895
18.842105
def get_sub_balance(self, sub_id, _async=False): """ 查询子账户各币种账户余额 :param sub_uid: 子账户id :param _async: :return: """ params = {} params['sub-uid'] = sub_id path = '/v1/account/accounts/{sub-uid}' return api_key_get(params, path, _async=_asy...
[ "def", "get_sub_balance", "(", "self", ",", "sub_id", ",", "_async", "=", "False", ")", ":", "params", "=", "{", "}", "params", "[", "'sub-uid'", "]", "=", "sub_id", "path", "=", "'/v1/account/accounts/{sub-uid}'", "return", "api_key_get", "(", "params", ","...
26
14.166667
def amounts(masses): """ Calculate the amounts from the specified compound masses. :param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5} :returns: [kmol] dictionary """ return {compound: amount(compound, masses[compound]) for compound in masses.keys()}
[ "def", "amounts", "(", "masses", ")", ":", "return", "{", "compound", ":", "amount", "(", "compound", ",", "masses", "[", "compound", "]", ")", "for", "compound", "in", "masses", ".", "keys", "(", ")", "}" ]
26.363636
19.454545
def _get_encoder_method(stream_type): """A function to get the python type to device cloud type converter function. :param stream_type: The streams data type :return: A function that when called with the python object will return the serializable type for sending to the cloud. If there is no function f...
[ "def", "_get_encoder_method", "(", "stream_type", ")", ":", "if", "stream_type", "is", "not", "None", ":", "return", "DSTREAM_TYPE_MAP", ".", "get", "(", "stream_type", ".", "upper", "(", ")", ",", "(", "lambda", "x", ":", "x", ",", "lambda", "x", ":", ...
49.166667
24.666667
def cumulative_returns(returns, period, freq=None): """ Builds cumulative returns from 'period' returns. This function simulates the cumulative effect that a series of gains or losses (the 'returns') have on an original amount of capital over a period of time. if F is the frequency at which returns...
[ "def", "cumulative_returns", "(", "returns", ",", "period", ",", "freq", "=", "None", ")", ":", "if", "not", "isinstance", "(", "period", ",", "pd", ".", "Timedelta", ")", ":", "period", "=", "pd", ".", "Timedelta", "(", "period", ")", "if", "freq", ...
40.276074
24.95092
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. """ # Opening a file by inode number is faster than opening a file by location. ...
[ "def", "FileEntryExistsByPathSpec", "(", "self", ",", "path_spec", ")", ":", "# Opening a file by inode number is faster than opening a file by location.", "tsk_file", "=", "None", "inode", "=", "getattr", "(", "path_spec", ",", "'inode'", ",", "None", ")", "location", ...
27.875
20.916667
def _close_rpc_interface(self, connection_id, callback): """Disable RPC interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, ad...
[ "def", "_close_rpc_interface", "(", "self", ",", "connection_id", ",", "callback", ")", ":", "try", ":", "context", "=", "self", ".", "connections", ".", "get_context", "(", "connection_id", ")", "except", "ArgumentError", ":", "callback", "(", "connection_id", ...
42.0625
28.75
def error(self, i: int=None) -> str: """ Returns an error message """ head = "[" + colors.red("error") + "]" if i is not None: head = str(i) + " " + head return head
[ "def", "error", "(", "self", ",", "i", ":", "int", "=", "None", ")", "->", "str", ":", "head", "=", "\"[\"", "+", "colors", ".", "red", "(", "\"error\"", ")", "+", "\"]\"", "if", "i", "is", "not", "None", ":", "head", "=", "str", "(", "i", ")...
27.25
7
def _get_dest_file_and_url(self, filepath, page_meta={}): """ Return tuple of the file destination and url """ filename = filepath.split("/")[-1] filepath_base = filepath.replace(filename, "").rstrip("/") slug = page_meta.get("slug") fname = slugify(slug) if slug else filename \...
[ "def", "_get_dest_file_and_url", "(", "self", ",", "filepath", ",", "page_meta", "=", "{", "}", ")", ":", "filename", "=", "filepath", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "filepath_base", "=", "filepath", ".", "replace", "(", "filename",...
40.904762
17.571429
def _varFindLimitSpace(basedir, vars, space, part, lookup_fatal, depth): ''' limits the search space of space to part basically does space.get(part, None), but with templating for part and a few more things ''' # Previous part couldn't be found, nothing to limit to if space is None: ...
[ "def", "_varFindLimitSpace", "(", "basedir", ",", "vars", ",", "space", ",", "part", ",", "lookup_fatal", ",", "depth", ")", ":", "# Previous part couldn't be found, nothing to limit to", "if", "space", "is", "None", ":", "return", "space", "# A part with escaped .s i...
31.555556
22
def _incr_decr(self, command, key, value, default, time): """ Function which increments and decrements. :param key: Key's name :type key: six.string_types :param value: Number to be (de|in)cremented :type value: int :param default: Default value if key does not e...
[ "def", "_incr_decr", "(", "self", ",", "command", ",", "key", ",", "value", ",", "default", ",", "time", ")", ":", "time", "=", "time", "if", "time", ">=", "0", "else", "self", ".", "MAXIMUM_EXPIRE_TIME", "self", ".", "_send", "(", "struct", ".", "pa...
42.69697
20.393939
def request_load_source(self, py_db, seq, filename): ''' :param str filename: Note: must be already translated for the server. ''' try: assert filename.__class__ == str # i.e.: bytes on py2 and str on py3 with open(filename, 'r') as stream: ...
[ "def", "request_load_source", "(", "self", ",", "py_db", ",", "seq", ",", "filename", ")", ":", "try", ":", "assert", "filename", ".", "__class__", "==", "str", "# i.e.: bytes on py2 and str on py3", "with", "open", "(", "filename", ",", "'r'", ")", "as", "s...
37
24.733333
def status(cls): """Retrieve global status from status.gandi.net.""" return cls.json_get('%s/status' % cls.api_url, empty_key=True, send_key=False)
[ "def", "status", "(", "cls", ")", ":", "return", "cls", ".", "json_get", "(", "'%s/status'", "%", "cls", ".", "api_url", ",", "empty_key", "=", "True", ",", "send_key", "=", "False", ")" ]
47
14.25
def get_all(self): """Returns the cache stats as a list of dicts.""" ret = [] for cache_name, stat in self.stats_per_cache.items(): ret.append({ 'cache_name': cache_name, 'num_hits': len(stat.hit_targets), 'num_misses': len(stat.miss_targets), 'hits': stat.hit_targets, ...
[ "def", "get_all", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "cache_name", ",", "stat", "in", "self", ".", "stats_per_cache", ".", "items", "(", ")", ":", "ret", ".", "append", "(", "{", "'cache_name'", ":", "cache_name", ",", "'num_hits'", ...
30.666667
14.416667
def keys(self, index=None): """Returns a list of keys in the database """ if index is not None and index not in self._indexes: raise ValueError('Index {} does not exist'.format(index)) db = self._indexes[index][0] if index else self._main_db with self._lmdb.begin(db=...
[ "def", "keys", "(", "self", ",", "index", "=", "None", ")", ":", "if", "index", "is", "not", "None", "and", "index", "not", "in", "self", ".", "_indexes", ":", "raise", "ValueError", "(", "'Index {} does not exist'", ".", "format", "(", "index", ")", "...
38.166667
18.5
def CrearLiquidacion(self, tipo_cbte, pto_vta, nro_cbte, fecha, cod_deposito_acopio, tipo_compra, variedad_tabaco, cod_provincia_origen_tabaco, puerta=None, nro_tarjeta=None, horas=None, control=None, nro_interno=None, iibb_emisor=None, fecha_inicio_actividad=None, ...
[ "def", "CrearLiquidacion", "(", "self", ",", "tipo_cbte", ",", "pto_vta", ",", "nro_cbte", ",", "fecha", ",", "cod_deposito_acopio", ",", "tipo_compra", ",", "variedad_tabaco", ",", "cod_provincia_origen_tabaco", ",", "puerta", "=", "None", ",", "nro_tarjeta", "="...
46.545455
12
def conversations_read(self, id): """ Marks a single conversation as read. Returns the updated `conversation dict`_. WARNING: This method is currently not documented in the official API and might therefore be unstable. """ id = self.__unpack_id(i...
[ "def", "conversations_read", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/conversations/{0}/read'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", ...
35.083333
13.583333
def send_object(bucket, obj, expected_chksum=None, logger_data=None, restricted=True, as_attachment=False): """Send an object for a given bucket. :param bucket: The bucket (instance or id) to get the object from. :param obj: A :class:`invenio_files_rest.models.ObjectVersion`...
[ "def", "send_object", "(", "bucket", ",", "obj", ",", "expected_chksum", "=", "None", ",", "logger_data", "=", "None", ",", "restricted", "=", "True", ",", "as_attachment", "=", "False", ")", ":", "if", "not", "obj", ".", "is_head", ":", "check_permission"...
43.08
20.68
def _del_cached_value(self, xblock): """Remove a value from the xblock's cache, if the cache exists.""" # pylint: disable=protected-access if hasattr(xblock, '_field_data_cache') and self.name in xblock._field_data_cache: del xblock._field_data_cache[self.name]
[ "def", "_del_cached_value", "(", "self", ",", "xblock", ")", ":", "# pylint: disable=protected-access", "if", "hasattr", "(", "xblock", ",", "'_field_data_cache'", ")", "and", "self", ".", "name", "in", "xblock", ".", "_field_data_cache", ":", "del", "xblock", "...
58.6
13.4
def schema_file(self): """ Gets the full path to the file in which to load configuration schema. """ path = os.getcwd() + '/' + self.lazy_folder return path + self.schema_filename
[ "def", "schema_file", "(", "self", ")", ":", "path", "=", "os", ".", "getcwd", "(", ")", "+", "'/'", "+", "self", ".", "lazy_folder", "return", "path", "+", "self", ".", "schema_filename" ]
50
7.75
def to_table(components, topo_info): """ normalize raw logical plan info to table """ inputs, outputs = defaultdict(list), defaultdict(list) for ctype, component in components.items(): if ctype == 'bolts': for component_name, component_info in component.items(): for input_stream in component_inf...
[ "def", "to_table", "(", "components", ",", "topo_info", ")", ":", "inputs", ",", "outputs", "=", "defaultdict", "(", "list", ")", ",", "defaultdict", "(", "list", ")", "for", "ctype", ",", "component", "in", "components", ".", "items", "(", ")", ":", "...
42.821429
14.821429
def remove_quotes_around_tz(cls, timestr): """Remove quotes (single and double) around timezone otherwise `dateutil.parser.parse` raises """ quoted = cls.QUOTED_TIMEZONE.match(timestr) if quoted is not None: return quoted.group(1) + quoted.group(2)
[ "def", "remove_quotes_around_tz", "(", "cls", ",", "timestr", ")", ":", "quoted", "=", "cls", ".", "QUOTED_TIMEZONE", ".", "match", "(", "timestr", ")", "if", "quoted", "is", "not", "None", ":", "return", "quoted", ".", "group", "(", "1", ")", "+", "qu...
42
5.285714
def similarity(self, d, d_): """ Compute a similarity score for two documents. Optionally pass in a `term_sim_ref` dict-like, which should be able to take `term1, term2` as args and return their similarity. """ es = set([e.name for e in d.entities]) es_ = set([e....
[ "def", "similarity", "(", "self", ",", "d", ",", "d_", ")", ":", "es", "=", "set", "(", "[", "e", ".", "name", "for", "e", "in", "d", ".", "entities", "]", ")", "es_", "=", "set", "(", "[", "e", ".", "name", "for", "e", "in", "d_", ".", "...
38.587302
18.047619
async def async_set_operation_mode( self, operation_mode: OperationMode, password: str = '') -> None: """ Set the operation mode on the base unit. :param operation_mode: the operation mode to change to :param password: if specified, will be used instead of the password ...
[ "async", "def", "async_set_operation_mode", "(", "self", ",", "operation_mode", ":", "OperationMode", ",", "password", ":", "str", "=", "''", ")", "->", "None", ":", "await", "self", ".", "_protocol", ".", "async_execute", "(", "SetOpModeCommand", "(", "operat...
38.076923
17.153846
def _get_index_urls_locations(self, project_name): """Returns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations """ def mkurl_pypi_url(url): loc = posixpath.join(url, proj...
[ "def", "_get_index_urls_locations", "(", "self", ",", "project_name", ")", ":", "def", "mkurl_pypi_url", "(", "url", ")", ":", "loc", "=", "posixpath", ".", "join", "(", "url", ",", "project_url_name", ")", "# For maximum compatibility with easy_install, ensure the pa...
39.434783
21.152174
def stopEventLoop(): """ Stop the current event loop if possible returns True if it expects that it was successful, False otherwise """ stopper = PyObjCAppHelperRunLoopStopper_wrap.currentRunLoopStopper() if stopper is None: if NSApp() is not None: NSApp().terminate_(None) ...
[ "def", "stopEventLoop", "(", ")", ":", "stopper", "=", "PyObjCAppHelperRunLoopStopper_wrap", ".", "currentRunLoopStopper", "(", ")", "if", "stopper", "is", "None", ":", "if", "NSApp", "(", ")", "is", "not", "None", ":", "NSApp", "(", ")", ".", "terminate_", ...
29
18.666667
def grid_model_params_ria(lvgd): """Determine grid model parameters for LV grids of sectors retail/industrial and agricultural Parameters ---------- lvgd : LVGridDistrictDing0 Low-voltage grid district object Returns ------- :obj:`dict` Structural description of (pa...
[ "def", "grid_model_params_ria", "(", "lvgd", ")", ":", "# Choose retail/industrial and agricultural grid model", "model_params_ria", "=", "{", "}", "if", "(", "(", "lvgd", ".", "sector_count_retail", "+", "lvgd", ".", "sector_count_industrial", ">", "0", ")", "or", ...
31.970588
18.882353
def _get_distance_scaling_term(self, C, rjb, mag): """ Returns the distance scaling component of the model Equation 10, Page 63 """ # Depth adjusted distance, equation 11 (Page 63) rval = np.sqrt(rjb ** 2.0 + C["c11"] ** 2.0) f_0, f_1, f_2 = self._get_distance_seg...
[ "def", "_get_distance_scaling_term", "(", "self", ",", "C", ",", "rjb", ",", "mag", ")", ":", "# Depth adjusted distance, equation 11 (Page 63)", "rval", "=", "np", ".", "sqrt", "(", "rjb", "**", "2.0", "+", "C", "[", "\"c11\"", "]", "**", "2.0", ")", "f_0...
43.083333
10.916667
def write_struct_field(self, struct_name, field_name, values, x, y, p=0): """Write a value into a struct. This method is particularly useful for writing values into the ``sv`` struct which contains some configuration data. See ``sark.h`` for details. Parameters -------...
[ "def", "write_struct_field", "(", "self", ",", "struct_name", ",", "field_name", ",", "values", ",", "x", ",", "y", ",", "p", "=", "0", ")", ":", "# Look up the struct and field", "field", ",", "address", ",", "pack_chars", "=", "self", ".", "_get_struct_fie...
33.59375
20.21875
def list(cls, zone_id, options=None): """List zone records for a zone.""" options = options if options else {} return cls.call('domain.zone.record.list', zone_id, 0, options)
[ "def", "list", "(", "cls", ",", "zone_id", ",", "options", "=", "None", ")", ":", "options", "=", "options", "if", "options", "else", "{", "}", "return", "cls", ".", "call", "(", "'domain.zone.record.list'", ",", "zone_id", ",", "0", ",", "options", ")...
48.75
9.5
def sendCommand(self, command): """Sends a command through the web interface of the charger and parses the response""" data = { 'rapi' : command } full_url = self.url + urllib.parse.urlencode(data) data = urllib.request.urlopen(full_url) response = re.search('\<p>&gt;\$(.+)\<script', data.read().dec...
[ "def", "sendCommand", "(", "self", ",", "command", ")", ":", "data", "=", "{", "'rapi'", ":", "command", "}", "full_url", "=", "self", ".", "url", "+", "urllib", ".", "parse", ".", "urlencode", "(", "data", ")", "data", "=", "urllib", ".", "request",...
64.777778
24.111111
def get_close_matches(word, possibilities, n=3, cutoff=0.6): """Use SequenceMatcher to return list of the best "good enough" matches. word is a sequence for which close matches are desired (typically a string). possibilities is a list of sequences against which to match word (typically a list of s...
[ "def", "get_close_matches", "(", "word", ",", "possibilities", ",", "n", "=", "3", ",", "cutoff", "=", "0.6", ")", ":", "if", "not", "n", ">", "0", ":", "raise", "ValueError", "(", "\"n must be > 0: %r\"", "%", "(", "n", ",", ")", ")", "if", "not", ...
34.319149
20.468085
def _find_link_internal(self, link, args, kwargs): """Wrapper around find_link that deals with convenience special-cases: * If ``link`` has an *href*-attribute, then return it. If not, consider it as a ``url_regex`` argument. * If searching for the link fails and debug is active, lau...
[ "def", "_find_link_internal", "(", "self", ",", "link", ",", "args", ",", "kwargs", ")", ":", "if", "hasattr", "(", "link", ",", "'attrs'", ")", "and", "'href'", "in", "link", ".", "attrs", ":", "return", "link", "# Check if \"link\" parameter should be treate...
38.310345
18.482759
def delete_user_by_email(self, id, email): """Deletes a specified connection user by its email. Args: id (str): The id of the connection (must be a database connection). email (str): The email of the user to delete. See: https://auth0.com/docs/api/management/v2#!/Connect...
[ "def", "delete_user_by_email", "(", "self", ",", "id", ",", "email", ")", ":", "return", "self", ".", "client", ".", "delete", "(", "self", ".", "_url", "(", "id", ")", "+", "'/users'", ",", "params", "=", "{", "'email'", ":", "email", "}", ")" ]
33.928571
26.714286
def create_option(cls, option, **kwargs): """Create Option Create a new Option This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_option(option, async=True) >>> result = thread.get...
[ "def", "create_option", "(", "cls", ",", "option", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_create_option_with_http_info", ...
38.142857
17.904762
def query_helper(request,namespace, docid, configuration=None): """Does the actual query, called by query() or pub_query(), not directly""" flatargs = { 'customslicesize': request.POST.get('customslicesize',settings.CONFIGURATIONS[configuration].get('customslicesize','50')), #for pagination of search re...
[ "def", "query_helper", "(", "request", ",", "namespace", ",", "docid", ",", "configuration", "=", "None", ")", ":", "flatargs", "=", "{", "'customslicesize'", ":", "request", ".", "POST", ".", "get", "(", "'customslicesize'", ",", "settings", ".", "CONFIGURA...
57.090909
35.545455
def add_end_event_to_diagram(self, process_id, end_event_name="", end_event_definition=None, node_id=None): """ Adds an EndEvent element to BPMN diagram. User-defined attributes: - name - event definition (creates a special type of end event). Supported event definitions ...
[ "def", "add_end_event_to_diagram", "(", "self", ",", "process_id", ",", "end_event_name", "=", "\"\"", ",", "end_event_definition", "=", "None", ",", "node_id", "=", "None", ")", ":", "end_event_id", ",", "end_event", "=", "self", ".", "add_flow_node_to_diagram", ...
63.097561
32.756098
def horizontal_random_walk(size): """ Generates random walks that start at the left side of the image and move towards the right :param size: The size of the image :return: An iterator of paths, each an iterator of (x,y) coordinates """ _, height = size distribution = {(1, dy): 1 / 3.0 for d...
[ "def", "horizontal_random_walk", "(", "size", ")", ":", "_", ",", "height", "=", "size", "distribution", "=", "{", "(", "1", ",", "dy", ")", ":", "1", "/", "3.0", "for", "dy", "in", "[", "-", "1", ",", "0", ",", "1", "]", "}", "start_points", "...
44
16.4
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ if self.storagehandler is None: return "No storage handler available!" sname = str(self.resolve_option("storage_name")) ...
[ "def", "do_execute", "(", "self", ")", ":", "if", "self", ".", "storagehandler", "is", "None", ":", "return", "\"No storage handler available!\"", "sname", "=", "str", "(", "self", ".", "resolve_option", "(", "\"storage_name\"", ")", ")", "if", "sname", "not",...
37
15.714286
def wavg(groupe, var): ''' Fonction qui calcule la moyenne pondérée par groupe d'une variable ''' d = groupe[var] w = groupe['pondmen'] return (d * w).sum() / w.sum()
[ "def", "wavg", "(", "groupe", ",", "var", ")", ":", "d", "=", "groupe", "[", "var", "]", "w", "=", "groupe", "[", "'pondmen'", "]", "return", "(", "d", "*", "w", ")", ".", "sum", "(", ")", "/", "w", ".", "sum", "(", ")" ]
26.285714
22.285714
def program_rtr_nwk_next_hop(self, rout_id, next_hop, cidr): """Program the next hop for all networks of a tenant. """ namespace = self.find_rtr_namespace(rout_id) if namespace is None: LOG.error("Unable to find namespace for router %s", rout_id) return False arg...
[ "def", "program_rtr_nwk_next_hop", "(", "self", ",", "rout_id", ",", "next_hop", ",", "cidr", ")", ":", "namespace", "=", "self", ".", "find_rtr_namespace", "(", "rout_id", ")", "if", "namespace", "is", "None", ":", "LOG", ".", "error", "(", "\"Unable to fin...
43.153846
20.461538
def p_if_then_part(p): """ if_then_part : IF expr then """ if is_number(p[2]): api.errmsg.warning_condition_is_always(p.lineno(1), bool(p[2].value)) p[0] = p[2]
[ "def", "p_if_then_part", "(", "p", ")", ":", "if", "is_number", "(", "p", "[", "2", "]", ")", ":", "api", ".", "errmsg", ".", "warning_condition_is_always", "(", "p", ".", "lineno", "(", "1", ")", ",", "bool", "(", "p", "[", "2", "]", ".", "value...
29.333333
22.833333
def check_errors(self, response): " Check some common errors." # Read content. content = response.content if 'status' not in content: raise self.GeneralError('We expect a status field.') # Return the decoded content if status is success. if content['status'...
[ "def", "check_errors", "(", "self", ",", "response", ")", ":", "# Read content.", "content", "=", "response", ".", "content", "if", "'status'", "not", "in", "content", ":", "raise", "self", ".", "GeneralError", "(", "'We expect a status field.'", ")", "# Return ...
31.512195
20.878049
def uvindex_around_coords(self, lat, lon): """ Queries the OWM Weather API for Ultra Violet value sampled in the surroundings of the provided geocoordinates and in the specified time interval. A *UVIndex* object instance is returned, encapsulating a *Location* object and the UV i...
[ "def", "uvindex_around_coords", "(", "self", ",", "lat", ",", "lon", ")", ":", "geo", ".", "assert_is_lon", "(", "lon", ")", "geo", ".", "assert_is_lat", "(", "lat", ")", "params", "=", "{", "'lon'", ":", "lon", ",", "'lat'", ":", "lat", "}", "json_d...
48.727273
20.636364
def get_undo_redo_list_from_active_trail_history_item_to_version_id(self, version_id): """Perform fast search from currently active branch to specific version_id and collect all recovery steps. """ all_trail_action = [a.version_id for a in self.single_trail_history() if a is not None] al...
[ "def", "get_undo_redo_list_from_active_trail_history_item_to_version_id", "(", "self", ",", "version_id", ")", ":", "all_trail_action", "=", "[", "a", ".", "version_id", "for", "a", "in", "self", ".", "single_trail_history", "(", ")", "if", "a", "is", "not", "None...
60.040816
32.591837
def PSHUFD(cpu, op0, op1, op3): """ Packed shuffle doublewords. Copies doublewords from source operand (second operand) and inserts them in the destination operand (first operand) at locations selected with the order operand (third operand). :param cpu: current CPU. :pa...
[ "def", "PSHUFD", "(", "cpu", ",", "op0", ",", "op1", ",", "op3", ")", ":", "size", "=", "op0", ".", "size", "arg0", "=", "op0", ".", "read", "(", ")", "arg1", "=", "op1", ".", "read", "(", ")", "order", "=", "Operators", ".", "ZEXTEND", "(", ...
39.125
22.916667
def flux_minimization(model, fixed, solver, weights={}): """Minimize flux of all reactions while keeping certain fluxes fixed. The fixed reactions are given in a dictionary as reaction id to value mapping. The weighted L1-norm of the fluxes is minimized. Args: model: MetabolicModel to solve. ...
[ "def", "flux_minimization", "(", "model", ",", "fixed", ",", "solver", ",", "weights", "=", "{", "}", ")", ":", "fba", "=", "FluxBalanceProblem", "(", "model", ",", "solver", ")", "for", "reaction_id", ",", "value", "in", "iteritems", "(", "fixed", ")", ...
33.038462
20.653846
def getCurrentItem(self): # TODO: rename? getCurrentItemAndIndex? getCurrentTuple? getCurrent? """ Find the current tree item (and the current index while we're at it) Returns a tuple with the current item, and its index. The item may be None. See also the notes at the top of this module...
[ "def", "getCurrentItem", "(", "self", ")", ":", "# TODO: rename? getCurrentItemAndIndex? getCurrentTuple? getCurrent?", "currentIndex", "=", "self", ".", "getRowCurrentIndex", "(", ")", "currentItem", "=", "self", ".", "model", "(", ")", ".", "getItem", "(", "currentI...
63.625
22.25
def get_vertical_orientation_property(value, is_bytes=False): """Get `VO` property.""" obj = unidata.ascii_vertical_orientation if is_bytes else unidata.unicode_vertical_orientation if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['verticalorientation'].get...
[ "def", "get_vertical_orientation_property", "(", "value", ",", "is_bytes", "=", "False", ")", ":", "obj", "=", "unidata", ".", "ascii_vertical_orientation", "if", "is_bytes", "else", "unidata", ".", "unicode_vertical_orientation", "if", "value", ".", "startswith", "...
36.583333
29.916667
def search_queryset(self): """Get search query set""" queryset = self.get_model_class().objects.get_queryset() if self.get_model_config().list_select_related: queryset = queryset.select_related(*self.get_model_config().list_select_related) return watson.filter(queryset, sel...
[ "def", "search_queryset", "(", "self", ")", ":", "queryset", "=", "self", ".", "get_model_class", "(", ")", ".", "objects", ".", "get_queryset", "(", ")", "if", "self", ".", "get_model_config", "(", ")", ".", "list_select_related", ":", "queryset", "=", "q...
42.875
27.125
def save(self): """Store config back to file.""" try: os.makedirs(os.path.dirname(self._configfile)) except: pass with open(self._configfile, 'w') as f: self._config.write(f)
[ "def", "save", "(", "self", ")", ":", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "_configfile", ")", ")", "except", ":", "pass", "with", "open", "(", "self", ".", "_configfile", ",", "'w'", ")", "...
26.111111
19.222222
def gofwrapper(f, loss_function='squared'): """ Goodness-of-fit decorator function for likelihoods ================================================== Generates goodness-of-fit points for data likelihoods. Wrap function f(*args, **kwds) where f is a likelihood. Assume args = (x, parameter1, par...
[ "def", "gofwrapper", "(", "f", ",", "loss_function", "=", "'squared'", ")", ":", "name", "=", "f", ".", "__name__", "[", ":", "-", "5", "]", "# Take a snapshot of the main namespace.", "# Find the functions needed to compute the gof points.", "expval_func", "=", "eval...
28.377778
18.022222
def add_inverse_query(self, key_val={}): """ Add an es_dsl inverse query object to the es_dsl Search object :param key_val: a key-value pair(dict) containing the query to be added to the search object :returns: self, which allows the method to be chainable with the other methods ...
[ "def", "add_inverse_query", "(", "self", ",", "key_val", "=", "{", "}", ")", ":", "q", "=", "Q", "(", "\"match\"", ",", "*", "*", "key_val", ")", "self", ".", "search", "=", "self", ".", "search", ".", "query", "(", "~", "q", ")", "return", "self...
37.545455
22.454545
def is_correct(self): # pylint: disable=too-many-branches """ Check if this object configuration is correct :: * Check our own specific properties * Call our parent class is_correct checker :return: True if the configuration is correct, otherwise False :rtype: b...
[ "def", "is_correct", "(", "self", ")", ":", "# pylint: disable=too-many-branches", "state", "=", "True", "if", "hasattr", "(", "self", ",", "'trigger'", ")", "and", "getattr", "(", "self", ",", "'trigger'", ",", "None", ")", ":", "self", ".", "add_warning", ...
50.253521
27.267606
def get_client_index_from_id(self, client_id): """Return client index from id""" for index, client in enumerate(self.clients): if id(client) == client_id: return index
[ "def", "get_client_index_from_id", "(", "self", ",", "client_id", ")", ":", "for", "index", ",", "client", "in", "enumerate", "(", "self", ".", "clients", ")", ":", "if", "id", "(", "client", ")", "==", "client_id", ":", "return", "index" ]
42.2
6.6
async def get_top_clans(self): '''Get a list of top clans, info is only brief, call get_clan() on each of the ClanInfo objects to get full clan info''' url = self.BASE + '/top/clans' data = await self.request(url) return [ClanInfo(self, c) for c in data.get('clans')]
[ "async", "def", "get_top_clans", "(", "self", ")", ":", "url", "=", "self", ".", "BASE", "+", "'/top/clans'", "data", "=", "await", "self", ".", "request", "(", "url", ")", "return", "[", "ClanInfo", "(", "self", ",", "c", ")", "for", "c", "in", "d...
34.555556
17.222222
def write_data(self, command, data, timeout=None): """Shortcut for writing specifically a DataMessage.""" self.write_message(FilesyncMessageTypes.DataMessage(command, data), timeout)
[ "def", "write_data", "(", "self", ",", "command", ",", "data", ",", "timeout", "=", "None", ")", ":", "self", ".", "write_message", "(", "FilesyncMessageTypes", ".", "DataMessage", "(", "command", ",", "data", ")", ",", "timeout", ")" ]
62.666667
16.666667
def deactivate_mfa_device(self, user_name, serial_number): """ Deactivates the specified MFA device and removes it from association with the user. :type user_name: string :param user_name: The username of the user :type serial_number: string :param seria...
[ "def", "deactivate_mfa_device", "(", "self", ",", "user_name", ",", "serial_number", ")", ":", "params", "=", "{", "'UserName'", ":", "user_name", ",", "'SerialNumber'", ":", "serial_number", "}", "return", "self", ".", "get_response", "(", "'DeactivateMFADevice'"...
35.9375
16.0625
def _remove_duplicate_points(points, groups): ''' Removes the duplicate points from the beginning of a section, if they are present in points-groups representation. Returns: points, groups with unique points. ''' group_initial_ids = groups[:, GPFIRST] to_be_reduced = np.zeros(len(gro...
[ "def", "_remove_duplicate_points", "(", "points", ",", "groups", ")", ":", "group_initial_ids", "=", "groups", "[", ":", ",", "GPFIRST", "]", "to_be_reduced", "=", "np", ".", "zeros", "(", "len", "(", "group_initial_ids", ")", ")", "to_be_removed", "=", "[",...
33.241379
19.655172
def _add_point_scalar(self, scalars, name, set_active=False, deep=True): """ Adds point scalars to the mesh Parameters ---------- scalars : numpy.ndarray Numpy array of scalars. Must match number of points. name : str Name of point scalars to ad...
[ "def", "_add_point_scalar", "(", "self", ",", "scalars", ",", "name", ",", "set_active", "=", "False", ",", "deep", "=", "True", ")", ":", "if", "not", "isinstance", "(", "scalars", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "'Inpu...
35.627907
19.255814
def _build_ex_tree(self): """Construct exception tree from trace.""" # Load exception data into tree structure sep = self._exh_obj.callables_separator data = self._exh_obj.exceptions_db if not data: raise RuntimeError("Exceptions database is empty") # Add root...
[ "def", "_build_ex_tree", "(", "self", ")", ":", "# Load exception data into tree structure", "sep", "=", "self", ".", "_exh_obj", ".", "callables_separator", "data", "=", "self", ".", "_exh_obj", ".", "exceptions_db", "if", "not", "data", ":", "raise", "RuntimeErr...
45.83871
15.903226
def _parse_binary(v, header_d): """ Parses binary string. Note: <str> for py2 and <binary> for py3. """ # This is often a no-op, but it ocassionally converts numbers into strings v = nullify(v) if v is None: return None if six.PY2: try: return six.bi...
[ "def", "_parse_binary", "(", "v", ",", "header_d", ")", ":", "# This is often a no-op, but it ocassionally converts numbers into strings", "v", "=", "nullify", "(", "v", ")", "if", "v", "is", "None", ":", "return", "None", "if", "six", ".", "PY2", ":", "try", ...
21.730769
21.653846
def iter_descendants_labels(self, ontology, iri, size=None, sleep=None): """Iterates over the labels for the descendants of a given term :param str ontology: The name of the ontology :param str iri: The IRI of a term :param int size: The size of each page. Defaults to 500, which is the ...
[ "def", "iter_descendants_labels", "(", "self", ",", "ontology", ",", "iri", ",", "size", "=", "None", ",", "sleep", "=", "None", ")", ":", "for", "label", "in", "_help_iterate_labels", "(", "self", ".", "iter_descendants", "(", "ontology", ",", "iri", ",",...
54.181818
27.090909
def _date(val, offset=None): """ A special pseudo-type for pipeline arguments. This allows us to parse dates as Python datetimes, including special values like 'now' and 'today', as well as apply offsets to the datetime. Args: val: a string containing the value for the datetime. This can be 'now', 'today'...
[ "def", "_date", "(", "val", ",", "offset", "=", "None", ")", ":", "if", "val", "is", "None", ":", "return", "val", "if", "val", "==", "''", "or", "val", "==", "'now'", ":", "when", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "elif"...
40.576271
21.762712
def bech32_decode(bech): """Validate a Bech32 string, and determine HRP and data.""" if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or (bech.lower() != bech and bech.upper() != bech)): return None, None bech = bech.lower() pos = bech.rfind('1') if pos < 1 or pos + 7 > len(b...
[ "def", "bech32_decode", "(", "bech", ")", ":", "if", "(", "(", "any", "(", "ord", "(", "x", ")", "<", "33", "or", "ord", "(", "x", ")", ">", "126", "for", "x", "in", "bech", ")", ")", "or", "(", "bech", ".", "lower", "(", ")", "!=", "bech",...
37.625
14.0625
def setTabURLs(tabs, webTranslator): """ Sets the C{linkURL} attribute on each L{Tab} instance in C{tabs} that does not already have it set @param tabs: sequence of L{Tab} instances @param webTranslator: L{xmantissa.ixmantissa.IWebTranslator} implementor @return: None...
[ "def", "setTabURLs", "(", "tabs", ",", "webTranslator", ")", ":", "for", "tab", "in", "tabs", ":", "if", "not", "tab", ".", "linkURL", ":", "tab", ".", "linkURL", "=", "webTranslator", ".", "linkTo", "(", "tab", ".", "storeID", ")", "setTabURLs", "(", ...
29.4375
16.4375
def configure(ctx, integration, args, show_args, editable): """Configure an integration with default parameters. You can still provide one-off integration arguments to :func:`honeycomb.commands.service.run` if required. """ home = ctx.obj["HOME"] integration_path = plugin_utils.get_plugin_path(home...
[ "def", "configure", "(", "ctx", ",", "integration", ",", "args", ",", "show_args", ",", "editable", ")", ":", "home", "=", "ctx", ".", "obj", "[", "\"HOME\"", "]", "integration_path", "=", "plugin_utils", ".", "get_plugin_path", "(", "home", ",", "defs", ...
44.857143
28.464286
def update(self, labels, preds, masks=None): # pylint: disable=arguments-differ """Updates the internal evaluation result. Parameters ---------- labels : list of `NDArray` The labels of the data with class indices as values, one per sample. preds : list of `N...
[ "def", "update", "(", "self", ",", "labels", ",", "preds", ",", "masks", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "labels", ",", "preds", "=", "check_label_shapes", "(", "labels", ",", "preds", ",", "True", ")", "masks", "=", "[", "None...
50.045455
22.022727
def ScanForFileSystem(self, source_path_spec): """Scans the path specification for a supported file system format. Args: source_path_spec (PathSpec): source path specification. Returns: PathSpec: file system path specification or None if no supported file system type was found. ...
[ "def", "ScanForFileSystem", "(", "self", ",", "source_path_spec", ")", ":", "if", "source_path_spec", ".", "type_indicator", "==", "(", "definitions", ".", "TYPE_INDICATOR_APFS_CONTAINER", ")", ":", "# TODO: consider changes this when upstream changes have been made.", "# Cur...
37.548387
22.387097
def haversine_distance(origin, destination): """ Calculate the Haversine distance. Parameters ---------- origin : tuple of float (lat, long) destination : tuple of float (lat, long) Returns ------- distance_in_km : float Examples -------- >>> munich = (...
[ "def", "haversine_distance", "(", "origin", ",", "destination", ")", ":", "lat1", ",", "lon1", "=", "origin", "lat2", ",", "lon2", "=", "destination", "if", "not", "(", "-", "90.0", "<=", "lat1", "<=", "90", ")", ":", "raise", "ValueError", "(", "'lat1...
30.46
18.94
def date_created(self): """Date the Scopus record was created.""" date_created = self.xml.find('institution-profile/date-created') if date_created is not None: date_created = (int(date_created.attrib['year']), int(date_created.attrib['month']), ...
[ "def", "date_created", "(", "self", ")", ":", "date_created", "=", "self", ".", "xml", ".", "find", "(", "'institution-profile/date-created'", ")", "if", "date_created", "is", "not", "None", ":", "date_created", "=", "(", "int", "(", "date_created", ".", "at...
44.8
16.1
def verts_str(verts, pad=1): r""" makes a string from a list of integer verticies """ if verts is None: return 'None' fmtstr = ', '.join(['%' + six.text_type(pad) + 'd' + ', %' + six.text_type(pad) + 'd'] * 1) return ', '.join(['(' + fmtstr % vert + ')' for vert in verts]...
[ "def", "verts_str", "(", "verts", ",", "pad", "=", "1", ")", ":", "if", "verts", "is", "None", ":", "return", "'None'", "fmtstr", "=", "', '", ".", "join", "(", "[", "'%'", "+", "six", ".", "text_type", "(", "pad", ")", "+", "'d'", "+", "', %'", ...
45
16.428571
def data_integrity(components, components_data): """ Check grid data for integrity Parameters ---------- components: dict Grid components components_data: dict Grid component data (such as p,q and v set points) Returns ------- """ data_check = {} for comp ...
[ "def", "data_integrity", "(", "components", ",", "components_data", ")", ":", "data_check", "=", "{", "}", "for", "comp", "in", "[", "'Bus'", ",", "'Load'", "]", ":", "# list(components_data.keys()):", "data_check", "[", "comp", "]", "=", "{", "}", "data_che...
32.870968
22.354839
def branches(config, **kwargs): """ Show current branch points. """ with alembic_lock( config.registry["sqlalchemy.engine"], config.alembic_config() ) as alembic_config: alembic.command.branches(alembic_config, **kwargs)
[ "def", "branches", "(", "config", ",", "*", "*", "kwargs", ")", ":", "with", "alembic_lock", "(", "config", ".", "registry", "[", "\"sqlalchemy.engine\"", "]", ",", "config", ".", "alembic_config", "(", ")", ")", "as", "alembic_config", ":", "alembic", "."...
31.125
12.375
def get_largest_schedule_within_budget(self, budget, proportion_discard): """ Gets the largest hyperband schedule within target_budget. This is required since the original hyperband algorithm uses R, the maximum number of resources per configuration. TODO(maxlam): Possibly binary...
[ "def", "get_largest_schedule_within_budget", "(", "self", ",", "budget", ",", "proportion_discard", ")", ":", "# Exhaustively generate schedules and check if", "# they're within budget, adding to a list.", "valid_schedules_and_costs", "=", "[", "]", "for", "R", "in", "range", ...
46.4
21.92
def subalignment(alnfle, subtype, alntype="fasta"): """ Subset synonymous or fourfold degenerate sites from an alignment input should be a codon alignment """ aln = AlignIO.read(alnfle, alntype) alnlen = aln.get_alignment_length() nseq = len(aln) subaln = None subalnfile = alnfle.rs...
[ "def", "subalignment", "(", "alnfle", ",", "subtype", ",", "alntype", "=", "\"fasta\"", ")", ":", "aln", "=", "AlignIO", ".", "read", "(", "alnfle", ",", "alntype", ")", "alnlen", "=", "aln", ".", "get_alignment_length", "(", ")", "nseq", "=", "len", "...
31.787234
15.191489
def report_messages_stats(sect, stats, _): """make messages type report""" if not stats["by_msg"]: # don't print this report when we didn't detected any errors raise exceptions.EmptyReportError() in_order = sorted( [ (value, msg_id) for msg_id, value in stats[...
[ "def", "report_messages_stats", "(", "sect", ",", "stats", ",", "_", ")", ":", "if", "not", "stats", "[", "\"by_msg\"", "]", ":", "# don't print this report when we didn't detected any errors", "raise", "exceptions", ".", "EmptyReportError", "(", ")", "in_order", "=...
34.647059
14.705882
def ConvertStringToFilename(name): """Converts an unicode string to a filesystem safe filename. For maximum compatibility we escape all chars which are not alphanumeric (in the unicode sense). Args: name: a unicode string that is part of a subject. Returns: A safe filename with escaped special chars...
[ "def", "ConvertStringToFilename", "(", "name", ")", ":", "return", "re", ".", "sub", "(", "r\"\\W\"", ",", "lambda", "x", ":", "\"%%%02X\"", "%", "ord", "(", "x", ".", "group", "(", "0", ")", ")", ",", "name", ",", "flags", "=", "re", ".", "UNICODE...
28.2
20.666667
def set_execution_state(self, execution_state): """ set exectuion state """ if not execution_state: self.execution_state = None self.cluster = None self.environ = None else: self.execution_state = execution_state cluster, environ = self.get_execution_state_dc_environ(execution_...
[ "def", "set_execution_state", "(", "self", ",", "execution_state", ")", ":", "if", "not", "execution_state", ":", "self", ".", "execution_state", "=", "None", "self", ".", "cluster", "=", "None", "self", ".", "environ", "=", "None", "else", ":", "self", "....
32.692308
14
def store_dummy_router_net(self, net_id, subnet_id, rtr_id): """Storing the router attributes. """ self.dummy_net_id = net_id self.dummy_subnet_id = subnet_id self.dummy_router_id = rtr_id
[ "def", "store_dummy_router_net", "(", "self", ",", "net_id", ",", "subnet_id", ",", "rtr_id", ")", ":", "self", ".", "dummy_net_id", "=", "net_id", "self", ".", "dummy_subnet_id", "=", "subnet_id", "self", ".", "dummy_router_id", "=", "rtr_id" ]
43.2
5.8
def datapoint(self, ind, field_names=None): """ Loads a tensor datapoint for a given global index. Parameters ---------- ind : int global index in the tensor field_names : :obj:`list` of str field names to load Returns ------- :ob...
[ "def", "datapoint", "(", "self", ",", "ind", ",", "field_names", "=", "None", ")", ":", "# flush if necessary", "if", "self", ".", "_has_unsaved_data", ":", "self", ".", "flush", "(", ")", "# check valid input", "if", "ind", ">=", "self", ".", "_num_datapoin...
32.342857
16.828571
def GetSyncMoConfig(ConfigDoc): """ Internal support method for SyncManagedObject. """ moConfigMap = {} configList = ConfigDoc.getElementsByTagName("mo") for moConfigNode in configList: classId = None noun = None version = None actionVersion = None action = None ignoreReason = None status ...
[ "def", "GetSyncMoConfig", "(", "ConfigDoc", ")", ":", "moConfigMap", "=", "{", "}", "configList", "=", "ConfigDoc", ".", "getElementsByTagName", "(", "\"mo\"", ")", "for", "moConfigNode", "in", "configList", ":", "classId", "=", "None", "noun", "=", "None", ...
27.072727
20.527273
def rels_xml_for(self, source_uri): """ Return rels item XML for source with *source_uri* or None if no rels item is present. """ try: rels_xml = self.blob_for(source_uri.rels_uri) except KeyError: rels_xml = None return rels_xml
[ "def", "rels_xml_for", "(", "self", ",", "source_uri", ")", ":", "try", ":", "rels_xml", "=", "self", ".", "blob_for", "(", "source_uri", ".", "rels_uri", ")", "except", "KeyError", ":", "rels_xml", "=", "None", "return", "rels_xml" ]
30
14.8