text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def add_instruction(self, specification): """Add an instruction specification :param specification: a specification with a key :data:`knittingpattern.Instruction.TYPE` .. seealso:: :meth:`as_instruction` """ instruction = self.as_instruction(specification) sel...
[ "def", "add_instruction", "(", "self", ",", "specification", ")", ":", "instruction", "=", "self", ".", "as_instruction", "(", "specification", ")", "self", ".", "_type_to_instruction", "[", "instruction", ".", "type", "]", "=", "instruction" ]
36.5
15.1
def regroup_if_changed(group, op_list, name=None): """Creates a new group for op_list if it has changed. Args: group: The current group. It is returned if op_list is unchanged. op_list: The list of operations to check. name: The name to use if a new group is created. Returns: Either group or a ne...
[ "def", "regroup_if_changed", "(", "group", ",", "op_list", ",", "name", "=", "None", ")", ":", "has_deltas", "=", "isinstance", "(", "op_list", ",", "sequence_with_deltas", ".", "SequenceWithDeltas", ")", "if", "(", "group", "is", "None", "or", "len", "(", ...
33.714286
20
def today(self) -> datetime: """ Returns today (date only) as datetime """ self.value = datetime.combine(datetime.today().date(), time.min) return self.value
[ "def", "today", "(", "self", ")", "->", "datetime", ":", "self", ".", "value", "=", "datetime", ".", "combine", "(", "datetime", ".", "today", "(", ")", ".", "date", "(", ")", ",", "time", ".", "min", ")", "return", "self", ".", "value" ]
44.5
14.75
def _append(self, target, value): """Replace PHP's []= idiom """ return self.__p(target) + '[] = ' + self.__p(value) + ';'
[ "def", "_append", "(", "self", ",", "target", ",", "value", ")", ":", "return", "self", ".", "__p", "(", "target", ")", "+", "'[] = '", "+", "self", ".", "__p", "(", "value", ")", "+", "';'" ]
28.6
14.4
def do_index_command(self, index, **options): """Delete search index.""" if options["interactive"]: logger.warning("This will permanently delete the index '%s'.", index) if not self._confirm_action(): logger.warning( "Aborting deletion of index...
[ "def", "do_index_command", "(", "self", ",", "index", ",", "*", "*", "options", ")", ":", "if", "options", "[", "\"interactive\"", "]", ":", "logger", ".", "warning", "(", "\"This will permanently delete the index '%s'.\"", ",", "index", ")", "if", "not", "sel...
41.9
14.9
def create_update(): """ Create the grammar for the 'update' statement """ update = upkey("update").setResultsName("action") returns, none, all_, updated, old, new = map( upkey, ["returns", "none", "all", "updated", "old", "new"] ) return_ = returns + Group( none | (all_ + old) | (al...
[ "def", "create_update", "(", ")", ":", "update", "=", "upkey", "(", "\"update\"", ")", ".", "setResultsName", "(", "\"action\"", ")", "returns", ",", "none", ",", "all_", ",", "updated", ",", "old", ",", "new", "=", "map", "(", "upkey", ",", "[", "\"...
30.947368
19
def does_database_exist(self, database_name): """ Checks if a database exists in CosmosDB. """ if database_name is None: raise AirflowBadRequest("Database name cannot be None.") existing_database = list(self.get_conn().QueryDatabases({ "query": "SELECT * ...
[ "def", "does_database_exist", "(", "self", ",", "database_name", ")", ":", "if", "database_name", "is", "None", ":", "raise", "AirflowBadRequest", "(", "\"Database name cannot be None.\"", ")", "existing_database", "=", "list", "(", "self", ".", "get_conn", "(", "...
30.764706
17
def to_record(self): """Create a CertStore record from this TLSFileBundle""" tf_list = [getattr(self, k, None) for k in [_.value for _ in TLSFileType]] # If a cert isn't defined in this bundle, remove it tf_list = filter(lambda x: x, tf_list) files = {tf.file_...
[ "def", "to_record", "(", "self", ")", ":", "tf_list", "=", "[", "getattr", "(", "self", ",", "k", ",", "None", ")", "for", "k", "in", "[", "_", ".", "value", "for", "_", "in", "TLSFileType", "]", "]", "# If a cert isn't defined in this bundle, remove it", ...
41.8
15.1
def period_break(dates, period): """ Returns the indices where the given period changes. Parameters ---------- dates : PeriodIndex Array of intervals to monitor. period : string Name of the period to monitor. """ current = getattr(dates, period) previous = getattr(da...
[ "def", "period_break", "(", "dates", ",", "period", ")", ":", "current", "=", "getattr", "(", "dates", ",", "period", ")", "previous", "=", "getattr", "(", "dates", "-", "1", "*", "dates", ".", "freq", ",", "period", ")", "return", "np", ".", "nonzer...
27.214286
12.785714
def from_pb(cls, cell_pb): """Create a new cell from a Cell protobuf. :type cell_pb: :class:`._generated.data_pb2.Cell` :param cell_pb: The protobuf to convert. :rtype: :class:`Cell` :returns: The cell corresponding to the protobuf. """ if cell_pb.labels: ...
[ "def", "from_pb", "(", "cls", ",", "cell_pb", ")", ":", "if", "cell_pb", ".", "labels", ":", "return", "cls", "(", "cell_pb", ".", "value", ",", "cell_pb", ".", "timestamp_micros", ",", "labels", "=", "cell_pb", ".", "labels", ")", "else", ":", "return...
35.846154
19.769231
def _sanitize(cls, message): """ Sanitize the given message, dealing with multiple arguments and/or string formatting. :param message: the log message to be sanitized :type message: string or list of strings :rtype: string """ if isinstance(messa...
[ "def", "_sanitize", "(", "cls", ",", "message", ")", ":", "if", "isinstance", "(", "message", ",", "list", ")", ":", "if", "len", "(", "message", ")", "==", "0", ":", "sanitized", "=", "u\"Empty log message\"", "elif", "len", "(", "message", ")", "==",...
33.363636
11.909091
async def _seed2did(self) -> str: """ Derive DID, as per indy-sdk, from seed. :return: DID """ rv = None dids_with_meta = json.loads(await did.list_my_dids_with_meta(self.handle)) # list if dids_with_meta: for did_with_meta in dids_with_meta: # di...
[ "async", "def", "_seed2did", "(", "self", ")", "->", "str", ":", "rv", "=", "None", "dids_with_meta", "=", "json", ".", "loads", "(", "await", "did", ".", "list_my_dids_with_meta", "(", "self", ".", "handle", ")", ")", "# list", "if", "dids_with_meta", "...
34.387097
21.16129
def process_hashes(self, body, allow_create=False): """Process any hashes mentioned and push them to related topics. :arg body: Body of the comment to check for hashes and push out. :arg allow_create=False: Whether to allow creating new topics from hash ta...
[ "def", "process_hashes", "(", "self", ",", "body", ",", "allow_create", "=", "False", ")", ":", "hash_re", "=", "re", ".", "compile", "(", "self", ".", "hashtag_re", ")", "hashes", "=", "hash_re", ".", "findall", "(", "body", ")", "done", "=", "{", "...
43.482759
18.413793
def external_account_cmd_by_name(self, command_name): """ Executes a command on the external account specified by name. @param command_name: The name of the command. @return: Reference to the submitted command. @since: API v16 """ return self._cmd(command_name, data=self.name, api_versi...
[ "def", "external_account_cmd_by_name", "(", "self", ",", "command_name", ")", ":", "return", "self", ".", "_cmd", "(", "command_name", ",", "data", "=", "self", ".", "name", ",", "api_version", "=", "16", ")" ]
31.7
16.1
async def close(self, wait_for_completion=True): """Close window. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=Position(position_percent=100), ...
[ "async", "def", "close", "(", "self", ",", "wait_for_completion", "=", "True", ")", ":", "await", "self", ".", "set_position", "(", "position", "=", "Position", "(", "position_percent", "=", "100", ")", ",", "wait_for_completion", "=", "wait_for_completion", "...
32.545455
16.454545
def send(self, str, end='\n'): """Sends a line to std_in.""" return self._process.stdin.write(str+end)
[ "def", "send", "(", "self", ",", "str", ",", "end", "=", "'\\n'", ")", ":", "return", "self", ".", "_process", ".", "stdin", ".", "write", "(", "str", "+", "end", ")" ]
38.666667
6.333333
def aggregate(l): """Aggregate a `list` of prefixes. Keyword arguments: l -- a python list of prefixes Example use: >>> aggregate(["10.0.0.0/8", "10.0.0.0/24"]) ['10.0.0.0/8'] """ tree = radix.Radix() for item in l: try: tree.add(item) except (ValueError...
[ "def", "aggregate", "(", "l", ")", ":", "tree", "=", "radix", ".", "Radix", "(", ")", "for", "item", "in", "l", ":", "try", ":", "tree", ".", "add", "(", "item", ")", "except", "(", "ValueError", ")", "as", "err", ":", "raise", "Exception", "(", ...
23.833333
18.888889
def to_value(self, variables_mapping=None): """ parse lazy data with evaluated variables mapping. Notice: variables_mapping should not contain any variable or function. """ variables_mapping = variables_mapping or {} args = [] for arg in self._args: if is...
[ "def", "to_value", "(", "self", ",", "variables_mapping", "=", "None", ")", ":", "variables_mapping", "=", "variables_mapping", "or", "{", "}", "args", "=", "[", "]", "for", "arg", "in", "self", ".", "_args", ":", "if", "isinstance", "(", "arg", ",", "...
39.666667
18.833333
def remove_terms_by_indices(self, idx_to_delete_list): ''' Parameters ---------- idx_to_delete_list, list Returns ------- TermDocMatrix ''' new_X, new_term_idx_store = self._get_X_after_delete_terms(idx_to_delete_list) return self._make_n...
[ "def", "remove_terms_by_indices", "(", "self", ",", "idx_to_delete_list", ")", ":", "new_X", ",", "new_term_idx_store", "=", "self", ".", "_get_X_after_delete_terms", "(", "idx_to_delete_list", ")", "return", "self", ".", "_make_new_term_doc_matrix", "(", "new_X", "="...
42.473684
29.736842
def delay(self, gain_in=0.8, gain_out=0.5, delays=list((1000, 1800)), decays=list((0.3, 0.25)), parallel=False): """delay takes 4 parameters: input gain (max 1), output gain and then two lists, delays and decays. Each list i...
[ "def", "delay", "(", "self", ",", "gain_in", "=", "0.8", ",", "gain_out", "=", "0.5", ",", "delays", "=", "list", "(", "(", "1000", ",", "1800", ")", ")", ",", "decays", "=", "list", "(", "(", "0.3", ",", "0.25", ")", ")", ",", "parallel", "=",...
35.352941
13.117647
def from_dict(data, ctx): """ Instantiate a new LimitOrder from a dict (generally from loading a JSON response). The data used to instantiate the LimitOrder is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. """ data...
[ "def", "from_dict", "(", "data", ",", "ctx", ")", ":", "data", "=", "data", ".", "copy", "(", ")", "if", "data", ".", "get", "(", "'clientExtensions'", ")", "is", "not", "None", ":", "data", "[", "'clientExtensions'", "]", "=", "ctx", ".", "transacti...
33.884615
19.576923
def build(self): """ Build package from source and create log file in path /var/log/slpkg/sbo/build_logs/. Also check md5sum calculates. """ try: self._delete_dir() try: tar = tarfile.open(self.script) except Exception a...
[ "def", "build", "(", "self", ")", ":", "try", ":", "self", ".", "_delete_dir", "(", ")", "try", ":", "tar", "=", "tarfile", ".", "open", "(", "self", ".", "script", ")", "except", "Exception", "as", "err", ":", "print", "err", "raise", "SystemExit", ...
45.5
15.425926
def setTau(self, vehID, tau): """setTau(string, double) -> None Sets the driver's tau-parameter (reaction time or anticipation time depending on the car-following model) in s for this vehicle. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_TAU, vehI...
[ "def", "setTau", "(", "self", ",", "vehID", ",", "tau", ")", ":", "self", ".", "_connection", ".", "_sendDoubleCmd", "(", "tc", ".", "CMD_SET_VEHICLE_VARIABLE", ",", "tc", ".", "VAR_TAU", ",", "vehID", ",", "tau", ")" ]
45.857143
24.428571
def connect_by_uri(uri): """General URI syntax: postgresql://user:passwd@host:port/db NOTE: the authority and the path parts of the URI have precedence over the query part, if an argument is given in both. conv,quote_conv,cursorclass are not (yet?) allowed as complex Python objects are ne...
[ "def", "connect_by_uri", "(", "uri", ")", ":", "puri", "=", "urisup", ".", "uri_help_split", "(", "uri", ")", "#params = __dict_from_query(puri[QUERY])", "params", "=", "{", "}", "if", "puri", "[", "AUTHORITY", "]", ":", "user", ",", "passwd", ",", "host", ...
28.882353
17.441176
def finish_build(verbose=True): '''finish_build will finish the build by way of sending the log to the same bucket. the params are loaded from the previous function that built the image, expected in $HOME/params.pkl :: note: this function is currently configured to work with Google Compute Engine me...
[ "def", "finish_build", "(", "verbose", "=", "True", ")", ":", "# If we are building the image, this will not be set", "go", "=", "get_build_metadata", "(", "key", "=", "'dobuild'", ")", "if", "go", "==", "None", ":", "sys", ".", "exit", "(", "0", ")", "# Load ...
40.222222
20.833333
def write_results(filename,config,srcfile,samples): """ Package everything nicely """ results = createResults(config,srcfile,samples=samples) results.write(filename)
[ "def", "write_results", "(", "filename", ",", "config", ",", "srcfile", ",", "samples", ")", ":", "results", "=", "createResults", "(", "config", ",", "srcfile", ",", "samples", "=", "samples", ")", "results", ".", "write", "(", "filename", ")" ]
43.75
10.75
def get_short_name(self): """ Returns the short type name of this X.509 extension. The result is a byte string such as :py:const:`b"basicConstraints"`. :return: The short type name. :rtype: :py:data:`bytes` .. versionadded:: 0.12 """ obj = _lib.X509_EXT...
[ "def", "get_short_name", "(", "self", ")", ":", "obj", "=", "_lib", ".", "X509_EXTENSION_get_object", "(", "self", ".", "_extension", ")", "nid", "=", "_lib", ".", "OBJ_obj2nid", "(", "obj", ")", "return", "_ffi", ".", "string", "(", "_lib", ".", "OBJ_ni...
30.428571
17.571429
def write_close(self, code=None): '''Write a close ``frame`` with ``code``. ''' return self.write(self.parser.close(code), opcode=0x8, encode=False)
[ "def", "write_close", "(", "self", ",", "code", "=", "None", ")", ":", "return", "self", ".", "write", "(", "self", ".", "parser", ".", "close", "(", "code", ")", ",", "opcode", "=", "0x8", ",", "encode", "=", "False", ")" ]
42.25
20.25
def kelly_kapowski(s, g, w, its=50, r=0.025, m=1.5, **kwargs): """ Compute cortical thickness using the DiReCT algorithm. Diffeomorphic registration-based cortical thickness based on probabilistic segmentation of an image. This is an optimization algorithm. Arguments --------- s : AN...
[ "def", "kelly_kapowski", "(", "s", ",", "g", ",", "w", ",", "its", "=", "50", ",", "r", "=", "0.025", ",", "m", "=", "1.5", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "s", ",", "iio", ".", "ANTsImage", ")", ":", "s", "=", "...
26.268657
21.910448
def MTF50(self, MTFx,MTFy): ''' return object resolution as [line pairs/mm] where MTF=50% see http://www.imatest.com/docs/sharpness/ ''' if self.mtf_x is None: self.MTF() f = UnivariateSpline(self.mtf_x, self.mtf_y-0.5) r...
[ "def", "MTF50", "(", "self", ",", "MTFx", ",", "MTFy", ")", ":", "if", "self", ".", "mtf_x", "is", "None", ":", "self", ".", "MTF", "(", ")", "f", "=", "UnivariateSpline", "(", "self", ".", "mtf_x", ",", "self", ".", "mtf_y", "-", "0.5", ")", "...
32.9
16.5
def UpdateBudget(self, client_customer_id, budget_id, micro_amount, delivery_method): """Update a Budget with the given budgetId. Args: client_customer_id: str Client Customer Id used to update Budget. budget_id: str Id of the budget to be updated. micro_amount: str New val...
[ "def", "UpdateBudget", "(", "self", ",", "client_customer_id", ",", "budget_id", ",", "micro_amount", ",", "delivery_method", ")", ":", "self", ".", "client", ".", "SetClientCustomerId", "(", "client_customer_id", ")", "operations", "=", "[", "{", "'operator'", ...
35.045455
18.409091
def compileGSUB(featureFile, glyphOrder): """ Compile and return a GSUB table from `featureFile` (feaLib FeatureFile), using the given `glyphOrder` (list of glyph names). """ font = ttLib.TTFont() font.setGlyphOrder(glyphOrder) addOpenTypeFeatures(font, featureFile, tables={"GSUB"}) return f...
[ "def", "compileGSUB", "(", "featureFile", ",", "glyphOrder", ")", ":", "font", "=", "ttLib", ".", "TTFont", "(", ")", "font", ".", "setGlyphOrder", "(", "glyphOrder", ")", "addOpenTypeFeatures", "(", "font", ",", "featureFile", ",", "tables", "=", "{", "\"...
41
10.375
def atlas_zonefile_push_enqueue( zonefile_hash, name, txid, zonefile_data, zonefile_queue=None, con=None, path=None ): """ Enqueue the given zonefile into our "push" queue, from which it will be replicated to storage and sent out to other peers who don't have it. Return True if we enqueued it R...
[ "def", "atlas_zonefile_push_enqueue", "(", "zonefile_hash", ",", "name", ",", "txid", ",", "zonefile_data", ",", "zonefile_queue", "=", "None", ",", "con", "=", "None", ",", "path", "=", "None", ")", ":", "res", "=", "False", "bits", "=", "atlasdb_get_zonefi...
27.933333
21.266667
def make_ring_dicts(**kwargs): """Build and return the information about the Galprop rings """ library_yamlfile = kwargs.get('library', 'models/library.yaml') gmm = kwargs.get('GalpropMapManager', GalpropMapManager(**kwargs)) if library_yamlfile is None or library_yamlfile == 'None': return ...
[ "def", "make_ring_dicts", "(", "*", "*", "kwargs", ")", ":", "library_yamlfile", "=", "kwargs", ".", "get", "(", "'library'", ",", "'models/library.yaml'", ")", "gmm", "=", "kwargs", ".", "get", "(", "'GalpropMapManager'", ",", "GalpropMapManager", "(", "*", ...
41.764706
15.764706
def compile(self, name, migrate='', rollback='', num=None): """Create a migration.""" if num is None: num = len(self.todo) name = '{:03}_'.format(num + 1) + name filename = name + '.py' path = os.path.join(self.migrate_dir, filename) with open(path, 'w') as f...
[ "def", "compile", "(", "self", ",", "name", ",", "migrate", "=", "''", ",", "rollback", "=", "''", ",", "num", "=", "None", ")", ":", "if", "num", "is", "None", ":", "num", "=", "len", "(", "self", ".", "todo", ")", "name", "=", "'{:03}_'", "."...
35.583333
19.666667
def long_to_bytes(lnum, padmultiple=1): """Packs the lnum (which must be convertable to a long) into a byte string 0 padded to a multiple of padmultiple bytes in size. 0 means no padding whatsoever, so that packing 0 result in an empty string. The resulting byte string is the big-endian two's ...
[ "def", "long_to_bytes", "(", "lnum", ",", "padmultiple", "=", "1", ")", ":", "# source: http://stackoverflow.com/a/14527004/1231454", "if", "lnum", "==", "0", ":", "return", "b'\\0'", "*", "padmultiple", "elif", "lnum", "<", "0", ":", "raise", "ValueError", "(",...
37.608696
18.478261
def search(cls, session, queries, out_type): """Search for a record given a domain. Args: session (requests.sessions.Session): Authenticated session. queries (helpscout.models.Domain or iter): The queries for the domain. If a ``Domain`` object is provided, it wil...
[ "def", "search", "(", "cls", ",", "session", ",", "queries", ",", "out_type", ")", ":", "cls", ".", "_check_implements", "(", "'search'", ")", "domain", "=", "cls", ".", "get_search_domain", "(", "queries", ")", "return", "cls", "(", "'/search/%s.json'", "...
43.923077
20.653846
def Y(self, value): """ sets the Y coordinate """ if isinstance(value, (int, float, long, types.NoneType)): self._y = value
[ "def", "Y", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "int", ",", "float", ",", "long", ",", "types", ".", "NoneType", ")", ")", ":", "self", ".", "_y", "=", "value" ]
35.4
9.6
def add_resourcegroupitems(scenario_id, items, scenario=None, **kwargs): """ Get all the items in a group, in a scenario. """ user_id = int(kwargs.get('user_id')) if scenario is None: scenario = _get_scenario(scenario_id, user_id) _check_network_ownership(scenario.network_id, user...
[ "def", "add_resourcegroupitems", "(", "scenario_id", ",", "items", ",", "scenario", "=", "None", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "int", "(", "kwargs", ".", "get", "(", "'user_id'", ")", ")", "if", "scenario", "is", "None", ":", "scen...
25.45
21.85
def _adjusted_rand_index(reference_indices, estimated_indices): """Compute the Rand index, adjusted for change. Parameters ---------- reference_indices : np.ndarray Array of reference indices estimated_indices : np.ndarray Array of estimated indices Returns ------- ari ...
[ "def", "_adjusted_rand_index", "(", "reference_indices", ",", "estimated_indices", ")", ":", "n_samples", "=", "len", "(", "reference_indices", ")", "ref_classes", "=", "np", ".", "unique", "(", "reference_indices", ")", "est_classes", "=", "np", ".", "unique", ...
38.045455
20.454545
def participants(self): """agents + computers (i.e. all non-observers)""" ret = [] for p in self.players: try: if p.isComputer: ret.append(p) if not p.isObserver: ret.append(p) # could cause an exception if player isn't a PlayerPreGame ...
[ "def", "participants", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "p", "in", "self", ".", "players", ":", "try", ":", "if", "p", ".", "isComputer", ":", "ret", ".", "append", "(", "p", ")", "if", "not", "p", ".", "isObserver", ":", "re...
39.777778
19.666667
def writerow(self, row): """Write a single row.""" json_text = json.dumps(row) if isinstance(json_text, bytes): json_text = json_text.decode('utf-8') self._out.write(json_text) self._out.write(u'\n')
[ "def", "writerow", "(", "self", ",", "row", ")", ":", "json_text", "=", "json", ".", "dumps", "(", "row", ")", "if", "isinstance", "(", "json_text", ",", "bytes", ")", ":", "json_text", "=", "json_text", ".", "decode", "(", "'utf-8'", ")", "self", "....
35
6.571429
def find_module(self, fullname, path=None): """ Tell if the module to load can be loaded by the load_module function, ie: if it is a ``pygal.maps.*`` module. """ if fullname.startswith('pygal.maps.') and hasattr( maps, fullname.split('.')[2]): ...
[ "def", "find_module", "(", "self", ",", "fullname", ",", "path", "=", "None", ")", ":", "if", "fullname", ".", "startswith", "(", "'pygal.maps.'", ")", "and", "hasattr", "(", "maps", ",", "fullname", ".", "split", "(", "'.'", ")", "[", "2", "]", ")",...
34.2
12.6
def _se_all(self): """Standard errors (SE) for all parameters, including the intercept.""" x = np.atleast_2d(self.x) err = np.atleast_1d(self.ms_err) se = np.sqrt(np.diagonal(np.linalg.inv(x.T @ x)) * err[:, None]) return np.squeeze(se)
[ "def", "_se_all", "(", "self", ")", ":", "x", "=", "np", ".", "atleast_2d", "(", "self", ".", "x", ")", "err", "=", "np", ".", "atleast_1d", "(", "self", ".", "ms_err", ")", "se", "=", "np", ".", "sqrt", "(", "np", ".", "diagonal", "(", "np", ...
46
12
def satellite(self,stellar_mass,distance_modulus,mc_source_id=1,seed=None,**kwargs): """ Create a simulated satellite. Returns a catalog object. """ if seed is not None: np.random.seed(seed) isochrone = kwargs.pop('isochrone',self.isochrone) kernel = kwargs.pop('kerne...
[ "def", "satellite", "(", "self", ",", "stellar_mass", ",", "distance_modulus", ",", "mc_source_id", "=", "1", ",", "seed", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "seed", "is", "not", "None", ":", "np", ".", "random", ".", "seed", "(", ...
48.6
29.96
def request_sensor_list(self, req, msg): """Sensor list""" if msg.arguments: name = (msg.arguments[0],) keys = (name, ) if name not in self.fake_sensor_infos: return ("fail", "Unknown sensor name.") else: keys = self.fake_sensor_inf...
[ "def", "request_sensor_list", "(", "self", ",", "req", ",", "msg", ")", ":", "if", "msg", ".", "arguments", ":", "name", "=", "(", "msg", ".", "arguments", "[", "0", "]", ",", ")", "keys", "=", "(", "name", ",", ")", "if", "name", "not", "in", ...
31.529412
13.588235
def get_nowait(self, name, default=_MISSING, autoremove=False): """Get the value of a key if it is already set. This method allows you to check if a key has already been set without blocking. If the key has not been set you will get the default value you pass in or KeyError() if no def...
[ "def", "get_nowait", "(", "self", ",", "name", ",", "default", "=", "_MISSING", ",", "autoremove", "=", "False", ")", ":", "self", ".", "_ensure_declared", "(", "name", ")", "try", ":", "future", "=", "self", ".", "_data", "[", "name", "]", "if", "fu...
35.105263
23.052632
def start_environment( self, user_name, environment_id, custom_headers=None, raw=False, polling=True, **operation_config): """Starts an environment by starting all resources inside the environment. This operation can take a while to complete. :param user_name: The name of the user. ...
[ "def", "start_environment", "(", "self", ",", "user_name", ",", "environment_id", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "polling", "=", "True", ",", "*", "*", "operation_config", ")", ":", "raw_result", "=", "self", ".", "_star...
49.1
21.175
def _findJobStoreForUrl(self, url, export=False): """ Returns the AbstractJobStore subclass that supports the given URL. :param urlparse.ParseResult url: The given URL :param bool export: The URL for :rtype: toil.jobStore.AbstractJobStore """ for jobStoreCls in s...
[ "def", "_findJobStoreForUrl", "(", "self", ",", "url", ",", "export", "=", "False", ")", ":", "for", "jobStoreCls", "in", "self", ".", "_jobStoreClasses", ":", "if", "jobStoreCls", ".", "_supportsUrl", "(", "url", ",", "export", ")", ":", "return", "jobSto...
44.461538
16.153846
def make_coord_dict(coord): """helper function to make a dict from a coordinate for logging""" return dict( z=int_if_exact(coord.zoom), x=int_if_exact(coord.column), y=int_if_exact(coord.row), )
[ "def", "make_coord_dict", "(", "coord", ")", ":", "return", "dict", "(", "z", "=", "int_if_exact", "(", "coord", ".", "zoom", ")", ",", "x", "=", "int_if_exact", "(", "coord", ".", "column", ")", ",", "y", "=", "int_if_exact", "(", "coord", ".", "row...
32
12.285714
def url_to_filename(url): """ Safely translate url to relative filename Args: url (str): A target url string Returns: str """ # remove leading/trailing slash if url.startswith('/'): url = url[1:] if url.endswith('/'): url = url[:-1] # remove pardir s...
[ "def", "url_to_filename", "(", "url", ")", ":", "# remove leading/trailing slash", "if", "url", ".", "startswith", "(", "'/'", ")", ":", "url", "=", "url", "[", "1", ":", "]", "if", "url", ".", "endswith", "(", "'/'", ")", ":", "url", "=", "url", "["...
24.95
16.75
def after_output(command_status): """ Shell sequence to be run after the command output. The ``command_status`` should be in the range 0-255. """ if command_status not in range(256): raise ValueError("command_status must be an integer in the range 0-255") sys.stdout.write(AFTER_OUTPUT.f...
[ "def", "after_output", "(", "command_status", ")", ":", "if", "command_status", "not", "in", "range", "(", "256", ")", ":", "raise", "ValueError", "(", "\"command_status must be an integer in the range 0-255\"", ")", "sys", ".", "stdout", ".", "write", "(", "AFTER...
39.666667
17.166667
def get_idp_choices(): """ Get a list of identity providers choices for enterprise customer. Return: A list of choices of all identity providers, None if it can not get any available identity provider. """ try: from third_party_auth.provider import Registry # pylint: disable=redef...
[ "def", "get_idp_choices", "(", ")", ":", "try", ":", "from", "third_party_auth", ".", "provider", "import", "Registry", "# pylint: disable=redefined-outer-name", "except", "ImportError", "as", "exception", ":", "LOGGER", ".", "warning", "(", "\"Could not import Registry...
37.833333
27.277778
def cleanup(self): """ Stops any running entities in the prefix and uninitializes it, usually you want to do this if you are going to remove the prefix afterwards Returns: None """ with LogTask('Stop prefix'): self.stop() with LogTask("Tag...
[ "def", "cleanup", "(", "self", ")", ":", "with", "LogTask", "(", "'Stop prefix'", ")", ":", "self", ".", "stop", "(", ")", "with", "LogTask", "(", "\"Tag prefix as uninitialized\"", ")", ":", "os", ".", "unlink", "(", "self", ".", "paths", ".", "prefix_l...
32.333333
19
def disk_cache(basename, directory, method=False): """ Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If 'method', skip the first argument, usually being self or cls. The cache filepath is 'directory/basename-hash.p...
[ "def", "disk_cache", "(", "basename", ",", "directory", ",", "method", "=", "False", ")", ":", "directory", "=", "os", ".", "path", ".", "expanduser", "(", "directory", ")", "ensure_directory", "(", "directory", ")", "def", "wrapper", "(", "func", ")", "...
38.827586
14.827586
def rot3(theta): """ Args: theta (float): Angle in radians Return: Rotation matrix of angle theta around the Z-axis """ return np.array([ [np.cos(theta), np.sin(theta), 0], [-np.sin(theta), np.cos(theta), 0], [0, 0, 1] ])
[ "def", "rot3", "(", "theta", ")", ":", "return", "np", ".", "array", "(", "[", "[", "np", ".", "cos", "(", "theta", ")", ",", "np", ".", "sin", "(", "theta", ")", ",", "0", "]", ",", "[", "-", "np", ".", "sin", "(", "theta", ")", ",", "np...
22.833333
15.166667
def save(self, out, kind=None, **kw): """\ Saves the sequence of QR Code to `out`. If `out` is a filename, this method modifies the filename and adds ``<Number of QR Codes>-<Current QR Code>`` to it. ``structured-append.svg`` becomes (if the sequence contains two QR Codes): ...
[ "def", "save", "(", "self", ",", "out", ",", "kind", "=", "None", ",", "*", "*", "kw", ")", ":", "m", "=", "len", "(", "self", ")", "def", "prepare_fn_noop", "(", "o", ",", "n", ")", ":", "\"\"\"\\\n Function to enumerate file names, does nothin...
36.027027
18.864865
def Parse(self, stat, file_object, knowledge_base): """Parse the History file.""" _, _ = stat, knowledge_base # TODO(user): Convert this to use the far more intelligent plaso parser. ff = Firefox3History(file_object) for timestamp, unused_entry_type, url, title in ff.Parse(): yield rdf_webhist...
[ "def", "Parse", "(", "self", ",", "stat", ",", "file_object", ",", "knowledge_base", ")", ":", "_", ",", "_", "=", "stat", ",", "knowledge_base", "# TODO(user): Convert this to use the far more intelligent plaso parser.", "ff", "=", "Firefox3History", "(", "file_objec...
40.769231
11.615385
def is_nan(self): """Asserts that val is real number and NaN (not a number).""" self._validate_number() self._validate_real() if not math.isnan(self.val): self._err('Expected <%s> to be <NaN>, but was not.' % self.val) return self
[ "def", "is_nan", "(", "self", ")", ":", "self", ".", "_validate_number", "(", ")", "self", ".", "_validate_real", "(", ")", "if", "not", "math", ".", "isnan", "(", "self", ".", "val", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to be <NaN>, but w...
39.428571
14.714286
def _hijack_gtk(self): """Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt ...
[ "def", "_hijack_gtk", "(", "self", ")", ":", "def", "dummy", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "pass", "# save and trap main and main_quit from gtk", "orig_main", ",", "gtk", ".", "main", "=", "gtk", ".", "main", ",", "dummy", "orig_main_qui...
35.9
19.8
def encode_scaled(data, size, version=0, level=QR_ECLEVEL_L, hint=QR_MODE_8, case_sensitive=True): """Creates a QR-code from string data, resized to the specified dimensions. Args: data: string: The data to encode in a QR-code. If a unicode string is supplied, it will be encod...
[ "def", "encode_scaled", "(", "data", ",", "size", ",", "version", "=", "0", ",", "level", "=", "QR_ECLEVEL_L", ",", "hint", "=", "QR_MODE_8", ",", "case_sensitive", "=", "True", ")", ":", "version", ",", "src_size", ",", "im", "=", "encode", "(", "data...
45.965517
21.206897
def all_consumed_offsets(self): """Returns consumed offsets as {TopicPartition: OffsetAndMetadata}""" all_consumed = {} for partition, state in six.iteritems(self.assignment): if state.has_valid_position: all_consumed[partition] = OffsetAndMetadata(state.position, '')...
[ "def", "all_consumed_offsets", "(", "self", ")", ":", "all_consumed", "=", "{", "}", "for", "partition", ",", "state", "in", "six", ".", "iteritems", "(", "self", ".", "assignment", ")", ":", "if", "state", ".", "has_valid_position", ":", "all_consumed", "...
48.857143
14.142857
def _init(self, parser): """Initialize/Build the ``argparse.ArgumentParser`` and subparsers. This internal version of ``init`` is used to ensure that all subcommands have a properly initialized parser. Args ---- parser : argparse.ArgumentParser The parser fo...
[ "def", "_init", "(", "self", ",", "parser", ")", ":", "assert", "isinstance", "(", "parser", ",", "argparse", ".", "ArgumentParser", ")", "self", ".", "_init_parser", "(", "parser", ")", "self", ".", "_attach_arguments", "(", ")", "self", ".", "_attach_sub...
29.166667
17.944444
def posterior_predictive_to_xarray(self): """Convert posterior_predictive samples to xarray.""" posterior = self.posterior posterior_predictive = self.posterior_predictive data = get_draws(posterior, variables=posterior_predictive) return dict_to_dataset(data, library=self.p...
[ "def", "posterior_predictive_to_xarray", "(", "self", ")", ":", "posterior", "=", "self", ".", "posterior", "posterior_predictive", "=", "self", ".", "posterior_predictive", "data", "=", "get_draws", "(", "posterior", ",", "variables", "=", "posterior_predictive", "...
59.5
17.5
def get(self, txn_id): """Returns the TransactionReceipt Args: txn_id (str): the id of the transaction for which the receipt should be retrieved. Returns: TransactionReceipt: The receipt for the given transaction id. Raises: KeyError...
[ "def", "get", "(", "self", ",", "txn_id", ")", ":", "if", "txn_id", "not", "in", "self", ".", "_receipt_db", ":", "raise", "KeyError", "(", "'Unknown transaction id {}'", ".", "format", "(", "txn_id", ")", ")", "txn_receipt_bytes", "=", "self", ".", "_rece...
32.05
20.65
def get_log_records_access(f): """Access to getLogRecords() controlled by settings.PUBLIC_LOG_RECORDS.""" @functools.wraps(f) def wrapper(request, *args, **kwargs): if not django.conf.settings.PUBLIC_LOG_RECORDS: trusted(request) return f(request, *args, **kwargs) return wr...
[ "def", "get_log_records_access", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "django", ".", "conf", ".", "settings", ".", "PU...
31.6
16
def record(self): # type: () -> bytes ''' A method to generate the string representing this Volume Descriptor. Parameters: None. Returns: A string representing this Volume Descriptor. ''' if not self._initialized: raise pycdlibexcept...
[ "def", "record", "(", "self", ")", ":", "# type: () -> bytes", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'This Volume Descriptor is not yet initialized'", ")", "vol_mod_date", "=", "dates", ".", "Vol...
46.245283
18.207547
def open_url_in_browser(url, browsername=None, fallback=False): r""" Opens a url in the specified or default browser Args: url (str): web url CommandLine: python -m utool.util_grabdata --test-open_url_in_browser Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >...
[ "def", "open_url_in_browser", "(", "url", ",", "browsername", "=", "None", ",", "fallback", "=", "False", ")", ":", "import", "webbrowser", "print", "(", "'[utool] Opening url=%r in browser'", "%", "(", "url", ",", ")", ")", "if", "browsername", "is", "None", ...
29.916667
19.708333
def strip_and_uncomment(asm_lines): """Strip whitespaces and comments from asm lines.""" asm_stripped = [] for line in asm_lines: # Strip comments and whitespaces asm_stripped.append(line.split('#')[0].strip()) return asm_stripped
[ "def", "strip_and_uncomment", "(", "asm_lines", ")", ":", "asm_stripped", "=", "[", "]", "for", "line", "in", "asm_lines", ":", "# Strip comments and whitespaces", "asm_stripped", ".", "append", "(", "line", ".", "split", "(", "'#'", ")", "[", "0", "]", ".",...
36.571429
10
def login(self, **kwargs): """登录""" payload = { 'username': self.username, 'password': self.password, } headers = kwargs.setdefault('headers', {}) headers.setdefault( 'Referer', 'https://www.shanbay.com/web/account/login' ) ...
[ "def", "login", "(", "self", ",", "*", "*", "kwargs", ")", ":", "payload", "=", "{", "'username'", ":", "self", ".", "username", ",", "'password'", ":", "self", ".", "password", ",", "}", "headers", "=", "kwargs", ".", "setdefault", "(", "'headers'", ...
34.266667
14.533333
def _has_valid_type_annotation(self, tokens, i): """Extended check of PEP-484 type hint presence""" if not self._inside_brackets("("): return False # token_info # type string start end line # 0 1 2 3 4 bracket_level = 0 for token in tok...
[ "def", "_has_valid_type_annotation", "(", "self", ",", "tokens", ",", "i", ")", ":", "if", "not", "self", ".", "_inside_brackets", "(", "\"(\"", ")", ":", "return", "False", "# token_info", "# type string start end line", "# 0 1 2 3 4", "bracket_level"...
34.92
9.96
def _api_key_patch_replace(conn, apiKey, path, value): ''' the replace patch operation on an ApiKey resource ''' response = conn.update_api_key(apiKey=apiKey, patchOperations=[{'op': 'replace', 'path': path, 'value': value}]) return response
[ "def", "_api_key_patch_replace", "(", "conn", ",", "apiKey", ",", "path", ",", "value", ")", ":", "response", "=", "conn", ".", "update_api_key", "(", "apiKey", "=", "apiKey", ",", "patchOperations", "=", "[", "{", "'op'", ":", "'replace'", ",", "'path'", ...
41.428571
26.285714
def run(self, files, working_area): """ Run checks concurrently. Returns a list of CheckResults ordered by declaration order of the checks in the imported module """ # Ensure that dictionary is ordered by check declaration order (via self.check_names) # NOTE: Requires CP...
[ "def", "run", "(", "self", ",", "files", ",", "working_area", ")", ":", "# Ensure that dictionary is ordered by check declaration order (via self.check_names)", "# NOTE: Requires CPython 3.6. If we need to support older versions of Python, replace with OrderedDict.", "results", "=", "{",...
45.514286
23.171429
def ping(self, *args, **kwargs): """ Ping Server Respond without doing anything. This endpoint is used to check that the service is up. This method is ``stable`` """ return self._makeApiCall(self.funcinfo["ping"], *args, **kwargs)
[ "def", "ping", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"ping\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
25.363636
19.181818
def _check_import(module_names): """Import the specified modules and provide status.""" diagnostics = {} for module_name in module_names: try: __import__(module_name) res = 'ok' except ImportError as err: res = str(err) diagnostics[module_name] = r...
[ "def", "_check_import", "(", "module_names", ")", ":", "diagnostics", "=", "{", "}", "for", "module_name", "in", "module_names", ":", "try", ":", "__import__", "(", "module_name", ")", "res", "=", "'ok'", "except", "ImportError", "as", "err", ":", "res", "...
30.454545
11.181818
def _build_netengine_arguments(self): """ returns a python dictionary representing arguments that will be passed to a netengine backend for internal use only """ arguments = { "host": self.host } if self.config is not None: for key...
[ "def", "_build_netengine_arguments", "(", "self", ")", ":", "arguments", "=", "{", "\"host\"", ":", "self", ".", "host", "}", "if", "self", ".", "config", "is", "not", "None", ":", "for", "key", ",", "value", "in", "self", ".", "config", ".", "iteritem...
26
15.555556
def create_token(user): """ Create token. """ payload = jwt_payload_handler(user) if api_settings.JWT_ALLOW_REFRESH: payload['orig_iat'] = timegm( datetime.utcnow().utctimetuple() ) # Return values token = jwt_encode_handler(payload) return token
[ "def", "create_token", "(", "user", ")", ":", "payload", "=", "jwt_payload_handler", "(", "user", ")", "if", "api_settings", ".", "JWT_ALLOW_REFRESH", ":", "payload", "[", "'orig_iat'", "]", "=", "timegm", "(", "datetime", ".", "utcnow", "(", ")", ".", "ut...
22.692308
12.846154
def tagged(self, *tag_slugs): """ Return the items which are tagged with a specific tag. When multiple tags are provided, they operate as "OR" query. """ if getattr(self.model, 'tags', None) is None: raise AttributeError("The {0} does not include TagsEntryMixin".forma...
[ "def", "tagged", "(", "self", ",", "*", "tag_slugs", ")", ":", "if", "getattr", "(", "self", ".", "model", ",", "'tags'", ",", "None", ")", "is", "None", ":", "raise", "AttributeError", "(", "\"The {0} does not include TagsEntryMixin\"", ".", "format", "(", ...
41.916667
21.25
def do_windowed(self, line): """ Un-fullscreen the current window """ self.bot.canvas.sink.trigger_fullscreen_action(False) print(self.response_prompt, file=self.stdout)
[ "def", "do_windowed", "(", "self", ",", "line", ")", ":", "self", ".", "bot", ".", "canvas", ".", "sink", ".", "trigger_fullscreen_action", "(", "False", ")", "print", "(", "self", ".", "response_prompt", ",", "file", "=", "self", ".", "stdout", ")" ]
34
7.666667
def _get_xml(xml_str): ''' Intrepret the data coming from opennebula and raise if it's not XML. ''' try: xml_data = etree.XML(xml_str) # XMLSyntaxError seems to be only available from lxml, but that is the xml # library loaded by this module except etree.XMLSyntaxError as err: ...
[ "def", "_get_xml", "(", "xml_str", ")", ":", "try", ":", "xml_data", "=", "etree", ".", "XML", "(", "xml_str", ")", "# XMLSyntaxError seems to be only available from lxml, but that is the xml", "# library loaded by this module", "except", "etree", ".", "XMLSyntaxError", "...
38.076923
24.230769
def terminate_session(self, token): """Terminates the session token, effectively logging out the user from all crowd-enabled services. Args: token: The session token. Returns: True: If session terminated None: If session termination failed "...
[ "def", "terminate_session", "(", "self", ",", "token", ")", ":", "url", "=", "self", ".", "rest_url", "+", "\"/session/%s\"", "%", "token", "response", "=", "self", ".", "_delete", "(", "url", ")", "# For consistency between methods use None rather than False", "#...
27.347826
18.826087
def dqueries2queriessam(cfg,dqueries): """ Aligns queries to genome and gets SAM file step#1 :param cfg: configuration dict :param dqueries: dataframe of queries """ datatmpd=cfg['datatmpd'] dqueries=set_index(dqueries,'query id') queryls=dqueries.loc[:,'query sequence'].apply(l...
[ "def", "dqueries2queriessam", "(", "cfg", ",", "dqueries", ")", ":", "datatmpd", "=", "cfg", "[", "'datatmpd'", "]", "dqueries", "=", "set_index", "(", "dqueries", ",", "'query id'", ")", "queryls", "=", "dqueries", ".", "loc", "[", ":", ",", "'query seque...
46.104167
22.4375
def _register_service_type(cls, subclass): """Registers subclass handlers of various service-type-specific service implementations. Look for classes decorated with @Folder._register_service_type for hints on how this works.""" if hasattr(subclass, '__service_type__'): c...
[ "def", "_register_service_type", "(", "cls", ",", "subclass", ")", ":", "if", "hasattr", "(", "subclass", ",", "'__service_type__'", ")", ":", "cls", ".", "_service_type_mapping", "[", "subclass", ".", "__service_type__", "]", "=", "subclass", "if", "subclass", ...
51.818182
9.636364
def findLabel(self, query, create=False): """Find a label with the given name. Args: name (Union[_sre.SRE_Pattern, str]): A str or regular expression to match against the name. create (bool): Whether to create the label if it doesn't exist (only if name is a str). Retur...
[ "def", "findLabel", "(", "self", ",", "query", ",", "create", "=", "False", ")", ":", "if", "isinstance", "(", "query", ",", "six", ".", "string_types", ")", ":", "query", "=", "query", ".", "lower", "(", ")", "for", "label", "in", "self", ".", "_l...
41.842105
27.368421
def com_google_fonts_check_unique_glyphnames(ttFont): """Font contains unique glyph names?""" if ttFont.sfntVersion == b'\x00\x01\x00\x00' and ttFont.get( "post") and ttFont["post"].formatType == 3.0: yield SKIP, ("TrueType fonts with a format 3.0 post table contain no" " glyph names.") ...
[ "def", "com_google_fonts_check_unique_glyphnames", "(", "ttFont", ")", ":", "if", "ttFont", ".", "sfntVersion", "==", "b'\\x00\\x01\\x00\\x00'", "and", "ttFont", ".", "get", "(", "\"post\"", ")", "and", "ttFont", "[", "\"post\"", "]", ".", "formatType", "==", "3...
35.727273
16.772727
def relax_AX(self): """Implement relaxation if option ``RelaxParam`` != 1.0.""" self.AXnr = self.cnst_A(self.X, self.Xf) if self.rlx == 1.0: self.AX = self.AXnr else: alpha = self.rlx self.AX = alpha*self.AXnr + (1-alpha)*self.block_cat( ...
[ "def", "relax_AX", "(", "self", ")", ":", "self", ".", "AXnr", "=", "self", ".", "cnst_A", "(", "self", ".", "X", ",", "self", ".", "Xf", ")", "if", "self", ".", "rlx", "==", "1.0", ":", "self", ".", "AX", "=", "self", ".", "AXnr", "else", ":...
35.2
16.9
def do_pp(self, arg): """pp expression Pretty-print the value of the expression. """ obj = self._getval(arg) try: repr(obj) except Exception: self.message(bdb.safe_repr(obj)) else: self.message(pprint.pformat(obj))
[ "def", "do_pp", "(", "self", ",", "arg", ")", ":", "obj", "=", "self", ".", "_getval", "(", "arg", ")", "try", ":", "repr", "(", "obj", ")", "except", "Exception", ":", "self", ".", "message", "(", "bdb", ".", "safe_repr", "(", "obj", ")", ")", ...
26.909091
12.272727
def centerOfMass(self): """Get the center of mass of actor. .. hint:: |fatlimb| |fatlimb.py|_ """ cmf = vtk.vtkCenterOfMass() cmf.SetInputData(self.polydata(True)) cmf.Update() c = cmf.GetCenter() return np.array(c)
[ "def", "centerOfMass", "(", "self", ")", ":", "cmf", "=", "vtk", ".", "vtkCenterOfMass", "(", ")", "cmf", ".", "SetInputData", "(", "self", ".", "polydata", "(", "True", ")", ")", "cmf", ".", "Update", "(", ")", "c", "=", "cmf", ".", "GetCenter", "...
27.1
11.5
def update(self, forecasts, observations): """ Update the statistics with forecasts and observations. Args: forecasts: The discrete Cumulative Distribution Functions of observations: """ if len(observations.shape) == 1: obs_cdfs = np.zeros((ob...
[ "def", "update", "(", "self", ",", "forecasts", ",", "observations", ")", ":", "if", "len", "(", "observations", ".", "shape", ")", "==", "1", ":", "obs_cdfs", "=", "np", ".", "zeros", "(", "(", "observations", ".", "size", ",", "self", ".", "thresho...
42.315789
17.368421
def tab_complete(input_list): """ <Purpose> Gets the list of all valid tab-complete strings from all enabled modules. <Arguments> input_list: The list of words the user entered. <Side Effects> None <Exceptions> None <Returns> A list of valid tab-complete strings """ commands = [] f...
[ "def", "tab_complete", "(", "input_list", ")", ":", "commands", "=", "[", "]", "for", "module", "in", "get_enabled_modules", "(", ")", ":", "if", "'tab_completer'", "in", "module_data", "[", "module", "]", ":", "commands", "+=", "module_data", "[", "module",...
26.111111
18.888889
def program(self): """ program: (statement)* """ root = Program() while self.token.nature != Nature.EOF: root.children.append(self.statement()) return root
[ "def", "program", "(", "self", ")", ":", "root", "=", "Program", "(", ")", "while", "self", ".", "token", ".", "nature", "!=", "Nature", ".", "EOF", ":", "root", ".", "children", ".", "append", "(", "self", ".", "statement", "(", ")", ")", "return"...
20.8
16.6
def reduce(self) -> None: """ Remove redundant segments. Since this class is implemented based on list, this method may require O(n) time. """ idx = 0 while idx < len(self): if idx > 0 and \ self[idx - 1].type == 'text' and self[id...
[ "def", "reduce", "(", "self", ")", "->", "None", ":", "idx", "=", "0", "while", "idx", "<", "len", "(", "self", ")", ":", "if", "idx", ">", "0", "and", "self", "[", "idx", "-", "1", "]", ".", "type", "==", "'text'", "and", "self", "[", "idx",...
31.066667
16
def _compile_pvariable_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> ...
[ "def", "_compile_pvariable_expression", "(", "self", ",", "expr", ":", "Expression", ",", "scope", ":", "Dict", "[", "str", ",", "TensorFluent", "]", ",", "batch_size", ":", "Optional", "[", "int", "]", "=", "None", ",", "noise", ":", "Optional", "[", "L...
47.633333
25.033333
def _mpsse_enable(self): """Enable MPSSE mode on the FTDI device.""" # Reset MPSSE by sending mask = 0 and mode = 0 self._check(ftdi.set_bitmode, 0, 0) # Enable MPSSE by sending mask = 0 and mode = 2 self._check(ftdi.set_bitmode, 0, 2)
[ "def", "_mpsse_enable", "(", "self", ")", ":", "# Reset MPSSE by sending mask = 0 and mode = 0", "self", ".", "_check", "(", "ftdi", ".", "set_bitmode", ",", "0", ",", "0", ")", "# Enable MPSSE by sending mask = 0 and mode = 2", "self", ".", "_check", "(", "ftdi", "...
45
8.5
def _align_iteration_with_cl_boundary(self, iteration, subtract=True): """Align iteration with cacheline boundary.""" # FIXME handle multiple datatypes element_size = self.kernel.datatypes_size[self.kernel.datatype] cacheline_size = self.machine['cacheline size'] elements_per_cac...
[ "def", "_align_iteration_with_cl_boundary", "(", "self", ",", "iteration", ",", "subtract", "=", "True", ")", ":", "# FIXME handle multiple datatypes", "element_size", "=", "self", ".", "kernel", ".", "datatypes_size", "[", "self", ".", "kernel", ".", "datatype", ...
44
22.344828
def to_jgif(graph): """Build a JGIF dictionary from a BEL graph. :param pybel.BELGraph graph: A BEL graph :return: A JGIF dictionary :rtype: dict .. warning:: Untested! This format is not general purpose and is therefore time is not heavily invested. If you want to use Cytoscape.j...
[ "def", "to_jgif", "(", "graph", ")", ":", "node_bel", "=", "{", "}", "u_v_r_bel", "=", "{", "}", "nodes_entry", "=", "[", "]", "edges_entry", "=", "[", "]", "for", "i", ",", "node", "in", "enumerate", "(", "sorted", "(", "graph", ",", "key", "=", ...
29.37037
22.91358
def class_balancing_oversample(X_train=None, y_train=None, printable=True): """Input the features and labels, return the features and labels after oversampling. Parameters ---------- X_train : numpy.array The inputs. y_train : numpy.array The targets. Examples -------- ...
[ "def", "class_balancing_oversample", "(", "X_train", "=", "None", ",", "y_train", "=", "None", ",", "printable", "=", "True", ")", ":", "# ======== Classes balancing", "if", "printable", ":", "tl", ".", "logging", ".", "info", "(", "\"Classes balancing for trainin...
32.223529
24.705882
def can_edit(self, user=None, request=None): """ Define if a user can edit or not the instance, according to his account or the request. """ can = False if request and not self.owner: if (getattr(settings, "UMAP_ALLOW_ANONYMOUS", False) and...
[ "def", "can_edit", "(", "self", ",", "user", "=", "None", ",", "request", "=", "None", ")", ":", "can", "=", "False", "if", "request", "and", "not", "self", ".", "owner", ":", "if", "(", "getattr", "(", "settings", ",", "\"UMAP_ALLOW_ANONYMOUS\"", ",",...
35.105263
15.315789
def pool_by_environmentvip(self, environment_vip_id): """ Method to return list object pool by environment vip id Param environment_vip_id: environment vip id Return list object pool """ uri = 'api/v3/pool/environment-vip/%s/' % environment_vip_id return super(A...
[ "def", "pool_by_environmentvip", "(", "self", ",", "environment_vip_id", ")", ":", "uri", "=", "'api/v3/pool/environment-vip/%s/'", "%", "environment_vip_id", "return", "super", "(", "ApiPool", ",", "self", ")", ".", "get", "(", "uri", ")" ]
33.3
16.9
def _factory(importname, base_class_type, path=None, *args, **kargs): ''' Load a module of a given base class type Parameter -------- importname: string Name of the module, etc. converter base_class_type: class type E.g converter path: Absoulte path o...
[ "def", "_factory", "(", "importname", ",", "base_class_type", ",", "path", "=", "None", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "def", "is_base_class", "(", "item", ")", ":", "return", "isclass", "(", "item", ")", "and", "item", ".", "__m...
32.475
20.925