text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def maybe_coroutine(obj): """ If 'obj' is a coroutine and we're using Python3, wrap it in ensureDeferred. Otherwise return the original object. (This is to insert in all callback chains from user code, in case that user code is Python3 and used 'async def') """ if six.PY3 and asyncio.iscoro...
[ "def", "maybe_coroutine", "(", "obj", ")", ":", "if", "six", ".", "PY3", "and", "asyncio", ".", "iscoroutine", "(", "obj", ")", ":", "return", "defer", ".", "ensureDeferred", "(", "obj", ")", "return", "obj" ]
34.272727
15
def preparer(telefoon): ''' Edit a phone value to a value that can be validated as a phone number. This takes the incoming value and : Removes all whitespace ( space, tab , newline , ... ) characters Removes the following characters: " / - . " If no + ...
[ "def", "preparer", "(", "telefoon", ")", ":", "if", "telefoon", "is", "None", "or", "telefoon", "==", "colander", ".", "null", ":", "return", "colander", ".", "null", "if", "'landcode'", "in", "telefoon", "and", "telefoon", ".", "get", "(", "'landcode'", ...
51.695652
24.478261
def validate_sdl( document_ast: DocumentNode, schema_to_extend: GraphQLSchema = None, rules: Sequence[RuleType] = None, ) -> List[GraphQLError]: """Validate an SDL document.""" context = SDLValidationContext(document_ast, schema_to_extend) if rules is None: rules = specified_sdl_rules ...
[ "def", "validate_sdl", "(", "document_ast", ":", "DocumentNode", ",", "schema_to_extend", ":", "GraphQLSchema", "=", "None", ",", "rules", ":", "Sequence", "[", "RuleType", "]", "=", "None", ",", ")", "->", "List", "[", "GraphQLError", "]", ":", "context", ...
36
11.416667
def _integrateLinearOrbit(vxvv,pot,t,method,dt): """ NAME: integrateLinearOrbit PURPOSE: integrate a one-dimensional orbit INPUT: vxvv - initial condition [x,vx] pot - linearPotential or list of linearPotentials t - list of times at which to output (0 has to be in this...
[ "def", "_integrateLinearOrbit", "(", "vxvv", ",", "pot", ",", "t", ",", "method", ",", "dt", ")", ":", "#First check that the potential has C", "if", "'_c'", "in", "method", ":", "if", "not", "ext_loaded", "or", "not", "_check_c", "(", "pot", ")", ":", "if...
47
21
def _ref(self, param, base_name=None): """ Store a parameter schema and return a reference to it. :param schema: Swagger parameter definition. :param base_name: Name that should be used for the reference. :rtype: dict :returns: JSON pointer to th...
[ "def", "_ref", "(", "self", ",", "param", ",", "base_name", "=", "None", ")", ":", "name", "=", "base_name", "or", "param", ".", "get", "(", "'title'", ",", "''", ")", "or", "param", ".", "get", "(", "'name'", ",", "''", ")", "pointer", "=", "sel...
28.789474
19.526316
def remove_state_machine(self, state_machine_id): """Remove the state machine for a specified state machine id from the list of registered state machines. :param state_machine_id: the id of the state machine to be removed """ import rafcon.core.singleton as core_singletons remov...
[ "def", "remove_state_machine", "(", "self", ",", "state_machine_id", ")", ":", "import", "rafcon", ".", "core", ".", "singleton", "as", "core_singletons", "removed_state_machine", "=", "None", "if", "state_machine_id", "in", "self", ".", "_state_machines", ":", "l...
49
20.588235
def get_all_interface_details(devId, auth, url): """ function takes the devId of a specific device and the ifindex value assigned to a specific interface and issues a RESTFUL call to get the interface details file as known by the HP IMC Base Platform ICC module for the target device. :param devId: ...
[ "def", "get_all_interface_details", "(", "devId", ",", "auth", ",", "url", ")", ":", "get_all_interface_details_url", "=", "\"/imcrs/plat/res/device/\"", "+", "str", "(", "devId", ")", "+", "\"/interface/?start=0&size=1000&desc=false&total=false\"", "f_url", "=", "url", ...
37.418605
30.139535
def create_revlookup_query(self, *fulltext_searchterms, **keyvalue_searchterms): ''' Create the part of the solr request that comes after the question mark, e.g. ?URL=*dkrz*&CHECKSUM=*abc*. If allowed search keys are configured, only these are used. If no'allowed search keys are ...
[ "def", "create_revlookup_query", "(", "self", ",", "*", "fulltext_searchterms", ",", "*", "*", "keyvalue_searchterms", ")", ":", "LOGGER", ".", "debug", "(", "'create_revlookup_query...'", ")", "allowed_search_keys", "=", "self", ".", "__allowed_search_keys", "only_se...
45.460317
22.603175
def timestamp_to_local_time(timestamp, timezone_name): """Convert epoch timestamp to a localized Delorean datetime object. Arguments --------- timestamp : int The timestamp to convert. timezone_name : datetime.timezone The timezone of the desired local time. Returns -------...
[ "def", "timestamp_to_local_time", "(", "timestamp", ",", "timezone_name", ")", ":", "# first convert timestamp to UTC", "utc_time", "=", "datetime", ".", "utcfromtimestamp", "(", "float", "(", "timestamp", ")", ")", "delo", "=", "Delorean", "(", "utc_time", ",", "...
29.857143
15.095238
def wordlist2cognates(wordlist, source, expert='expert', ref='cogid'): """Turn a wordlist into a cognate set list, using the cldf parameters.""" for k in wordlist: yield dict( Form_ID=wordlist[k, 'lid'], ID=k, Form=wordlist[k, 'ipa'], Cognateset_ID='{0}-{1...
[ "def", "wordlist2cognates", "(", "wordlist", ",", "source", ",", "expert", "=", "'expert'", ",", "ref", "=", "'cogid'", ")", ":", "for", "k", "in", "wordlist", ":", "yield", "dict", "(", "Form_ID", "=", "wordlist", "[", "k", ",", "'lid'", "]", ",", "...
41.545455
12.909091
def options(f): """ Shared options, used by all bartender commands """ f = click.option('--config', envvar='VODKA_HOME', default=click.get_app_dir('vodka'), help="location of config file")(f) return f
[ "def", "options", "(", "f", ")", ":", "f", "=", "click", ".", "option", "(", "'--config'", ",", "envvar", "=", "'VODKA_HOME'", ",", "default", "=", "click", ".", "get_app_dir", "(", "'vodka'", ")", ",", "help", "=", "\"location of config file\"", ")", "(...
30.714286
26.714286
def get(self,id): '''Return all the semantic tag related to the given tag id :returns: a semantic tag or None :rtype: list of ckan.model.semantictag.SemanticTag object ''' query = meta.Session.query(TagSemanticTag).filter(TagSemanticTag.id==id) return query.first()
[ "def", "get", "(", "self", ",", "id", ")", ":", "query", "=", "meta", ".", "Session", ".", "query", "(", "TagSemanticTag", ")", ".", "filter", "(", "TagSemanticTag", ".", "id", "==", "id", ")", "return", "query", ".", "first", "(", ")" ]
30.111111
26.111111
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credential_type') and self.credential_type is not None: _dict['credential_type'] = self.credential_type if hasattr(self, 'client_id') and self.client_id...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'credential_type'", ")", "and", "self", ".", "credential_type", "is", "not", "None", ":", "_dict", "[", "'credential_type'", "]", "=", "self", ".", "c...
55.145833
21.166667
def register_callbacks(self, on_create, on_modify, on_delete): """ Register callbacks for file creation, modification, and deletion """ self.on_create = on_create self.on_modify = on_modify self.on_delete = on_delete
[ "def", "register_callbacks", "(", "self", ",", "on_create", ",", "on_modify", ",", "on_delete", ")", ":", "self", ".", "on_create", "=", "on_create", "self", ".", "on_modify", "=", "on_modify", "self", ".", "on_delete", "=", "on_delete" ]
48.8
8
def is_merc_projection(srs): """ Return true if the map projection matches that used by VEarth, Google, OSM, etc. Is currently necessary for zoom-level shorthand for scale-denominator. """ if srs.lower() == '+init=epsg:900913': return True # observed srs = dict([p.split('=') fo...
[ "def", "is_merc_projection", "(", "srs", ")", ":", "if", "srs", ".", "lower", "(", ")", "==", "'+init=epsg:900913'", ":", "return", "True", "# observed", "srs", "=", "dict", "(", "[", "p", ".", "split", "(", "'='", ")", "for", "p", "in", "srs", ".", ...
35
24.590909
def is_postponed_evaluation_enabled(node: astroid.node_classes.NodeNG) -> bool: """Check if the postponed evaluation of annotations is enabled""" name = "annotations" module = node.root() stmt = module.locals.get(name) return ( stmt and isinstance(stmt[0], astroid.ImportFrom) ...
[ "def", "is_postponed_evaluation_enabled", "(", "node", ":", "astroid", ".", "node_classes", ".", "NodeNG", ")", "->", "bool", ":", "name", "=", "\"annotations\"", "module", "=", "node", ".", "root", "(", ")", "stmt", "=", "module", ".", "locals", ".", "get...
35.3
18.2
def out_degree_iter(self, nbunch=None, t=None): """Return an iterator for (node, out_degree) at time t. The node out degree is the number of interactions outgoing from the node in a given timeframe. Parameters ---------- nbunch : iterable container, optional (default=all nodes)...
[ "def", "out_degree_iter", "(", "self", ",", "nbunch", "=", "None", ",", "t", "=", "None", ")", ":", "if", "nbunch", "is", "None", ":", "nodes_nbrs", "=", "self", ".", "_succ", ".", "items", "(", ")", "else", ":", "nodes_nbrs", "=", "(", "(", "n", ...
30.44898
21.591837
def encrypt_key(key_object, password): """ <Purpose> Return a string containing 'key_object' in encrypted form. Encrypted strings may be safely saved to a file. The corresponding decrypt_key() function can be applied to the encrypted string to restore the original key object. 'key_object' is a key...
[ "def", "encrypt_key", "(", "key_object", ",", "password", ")", ":", "# Does 'key_object' have the correct format?", "# This check will ensure 'key_object' has the appropriate number", "# of objects and object types, and that all dict keys are properly named.", "# Raise 'securesystemslib.except...
37.537313
26.701493
def _get_segments(self): """ Subclasses may override this method. """ points = list(self.points) segments = [[]] lastWasOffCurve = False firstIsMove = points[0].type == "move" for point in points: segments[-1].append(point) if point...
[ "def", "_get_segments", "(", "self", ")", ":", "points", "=", "list", "(", "self", ".", "points", ")", "segments", "=", "[", "[", "]", "]", "lastWasOffCurve", "=", "False", "firstIsMove", "=", "points", "[", "0", "]", ".", "type", "==", "\"move\"", "...
33.529412
7.411765
def affects(self, reglist): """ Returns if this instruction affects any of the registers in reglist. """ if isinstance(reglist, str): reglist = [reglist] reglist = single_registers(reglist) return len([x for x in self.destroys if x in reglist]) > 0
[ "def", "affects", "(", "self", ",", "reglist", ")", ":", "if", "isinstance", "(", "reglist", ",", "str", ")", ":", "reglist", "=", "[", "reglist", "]", "reglist", "=", "single_registers", "(", "reglist", ")", "return", "len", "(", "[", "x", "for", "x...
30.1
15.6
def dqdv_cycle(cycle, splitter=True, **kwargs): """Convenience functions for creating dq-dv data from given capacity and voltage cycle. Returns the a DataFrame with a 'voltage' and a 'incremental_capacity' column. Args: cycle (pandas.DataFrame): the cycle data ('voltage', 'capacity...
[ "def", "dqdv_cycle", "(", "cycle", ",", "splitter", "=", "True", ",", "*", "*", "kwargs", ")", ":", "c_first", "=", "cycle", ".", "loc", "[", "cycle", "[", "\"direction\"", "]", "==", "-", "1", "]", "c_last", "=", "cycle", ".", "loc", "[", "cycle",...
36.534483
19.551724
def _checkSuccessorReadyToRunMultiplePredecessors(self, jobGraph, jobNode, successorJobStoreID): """Handle the special cases of checking if a successor job is ready to run when there are multiple predecessors""" # See implementation note at the top of this file for discussion of multiple predece...
[ "def", "_checkSuccessorReadyToRunMultiplePredecessors", "(", "self", ",", "jobGraph", ",", "jobNode", ",", "successorJobStoreID", ")", ":", "# See implementation note at the top of this file for discussion of multiple predecessors", "logger", ".", "debug", "(", "\"Successor job: %s...
60.241379
34.551724
def _setup_serializers(self): """ Auto set the return serializer based on Accept headers http://docs.webob.org/en/latest/reference.html#header-getters Intersection of requested types and supported types tells us if we can in fact respond in one of the request formats """...
[ "def", "_setup_serializers", "(", "self", ")", ":", "acceptable_offers", "=", "self", ".", "request", ".", "accept", ".", "acceptable_offers", "(", "self", ".", "response", ".", "supported_mime_types", ")", "if", "len", "(", "acceptable_offers", ")", ">", "0",...
41.5
25.115385
def __extract_features(self): """! @brief Extracts features from CF-tree cluster. """ self.__features = []; if (len(self.__tree.leafes) == 1): # parameters are too general, copy all entries for entry in self.__tree.leaf...
[ "def", "__extract_features", "(", "self", ")", ":", "self", ".", "__features", "=", "[", "]", "if", "(", "len", "(", "self", ".", "__tree", ".", "leafes", ")", "==", "1", ")", ":", "# parameters are too general, copy all entries\r", "for", "entry", "in", "...
31.294118
15.470588
def ber(tp, tn, fp, fn): """Balanced Error Rate [0, 1] :param int tp: number of true positives :param int tn: number of true negatives :param int fp: number of false positives :param int fn: number of false negatives :rtype: float """ return (fp / float(tn + fp) + fn / float(fn + t...
[ "def", "ber", "(", "tp", ",", "tn", ",", "fp", ",", "fn", ")", ":", "return", "(", "fp", "/", "float", "(", "tn", "+", "fp", ")", "+", "fn", "/", "float", "(", "fn", "+", "tp", ")", ")", "/", "2" ]
31.8
10.6
async def update_rooms(self): """Request data.""" homes = await self.get_home_list() for home in homes: payload = {"homeId": home.get("homeId"), "timeZoneNum": "+01:00"} data = await self.request("selectRoombyHome", payload) rooms = data.get('roomInfo', []) ...
[ "async", "def", "update_rooms", "(", "self", ")", ":", "homes", "=", "await", "self", ".", "get_home_list", "(", ")", "for", "home", "in", "homes", ":", "payload", "=", "{", "\"homeId\"", ":", "home", ".", "get", "(", "\"homeId\"", ")", ",", "\"timeZon...
47.25
15.222222
def _get_distset(tgt): ''' Get the distribution string for use with rpmbuild and mock ''' # Centos adds 'centos' string to rpm names, removing that to have # consistent naming on Centos and Redhat, and allow for Amazon naming tgtattrs = tgt.split('-') if tgtattrs[0] == 'amzn': distse...
[ "def", "_get_distset", "(", "tgt", ")", ":", "# Centos adds 'centos' string to rpm names, removing that to have", "# consistent naming on Centos and Redhat, and allow for Amazon naming", "tgtattrs", "=", "tgt", ".", "split", "(", "'-'", ")", "if", "tgtattrs", "[", "0", "]", ...
33.533333
23.4
def xdg_config_dirs(): """Returns a list of paths taken from the XDG_CONFIG_DIRS and XDG_CONFIG_HOME environment varibables if they exist """ paths = [] if 'XDG_CONFIG_HOME' in os.environ: paths.append(os.environ['XDG_CONFIG_HOME']) if 'XDG_CONFIG_DIRS' in os.environ: paths.exten...
[ "def", "xdg_config_dirs", "(", ")", ":", "paths", "=", "[", "]", "if", "'XDG_CONFIG_HOME'", "in", "os", ".", "environ", ":", "paths", ".", "append", "(", "os", ".", "environ", "[", "'XDG_CONFIG_HOME'", "]", ")", "if", "'XDG_CONFIG_DIRS'", "in", "os", "."...
33.538462
13.692308
def sort(args): """ %prog sort fastafile Sort a list of sequences and output with sorted IDs, etc. """ p = OptionParser(sort.__doc__) p.add_option("--sizes", default=False, action="store_true", help="Sort by decreasing size [default: %default]") opts, args = p.parse_args(a...
[ "def", "sort", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "sort", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--sizes\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Sort by decreasing size [...
28.567568
20.513514
def bokeh_shot_chart(data, x="LOC_X", y="LOC_Y", fill_color="#1f77b4", scatter_size=10, fill_alpha=0.4, line_alpha=0.4, court_line_color='gray', court_line_width=1, hover_tool=False, tooltips=None, **kwargs): # TODO: Settings for hover tooltip """ ...
[ "def", "bokeh_shot_chart", "(", "data", ",", "x", "=", "\"LOC_X\"", ",", "y", "=", "\"LOC_Y\"", ",", "fill_color", "=", "\"#1f77b4\"", ",", "scatter_size", "=", "10", ",", "fill_alpha", "=", "0.4", ",", "line_alpha", "=", "0.4", ",", "court_line_color", "=...
37.262295
22.245902
def extract_paragraphs(xml_string): """Returns list of paragraphs in an NLM XML. Parameters ---------- xml_string : str String containing valid NLM XML. Returns ------- list of str List of extracted paragraphs in an NLM XML """ tree = etree.fromstring(xml_string.enc...
[ "def", "extract_paragraphs", "(", "xml_string", ")", ":", "tree", "=", "etree", ".", "fromstring", "(", "xml_string", ".", "encode", "(", "'utf-8'", ")", ")", "paragraphs", "=", "[", "]", "# In NLM xml, all plaintext is within <p> tags, and is the only thing", "# that...
33.4
20.72
def findSequencesOnDisk(cls, pattern, include_hidden=False, strictPadding=False): """ Yield the sequences found in the given directory. Examples: >>> findSequencesOnDisk('/path/to/files') The `pattern` can also specify glob-like shell wildcards including the following: ...
[ "def", "findSequencesOnDisk", "(", "cls", ",", "pattern", ",", "include_hidden", "=", "False", ",", "strictPadding", "=", "False", ")", ":", "# reserve some functions we're going to need quick access to", "_not_hidden", "=", "lambda", "f", ":", "not", "f", ".", "sta...
36.550459
21.321101
def get_edge_string(self, i): """Return a string based on the bond order""" order = self.orders[i] if order == 0: return Graph.get_edge_string(self, i) else: # pad with zeros to make sure that string sort is identical to number sort return "%03i" % ord...
[ "def", "get_edge_string", "(", "self", ",", "i", ")", ":", "order", "=", "self", ".", "orders", "[", "i", "]", "if", "order", "==", "0", ":", "return", "Graph", ".", "get_edge_string", "(", "self", ",", "i", ")", "else", ":", "# pad with zeros to make ...
39.375
16
def _configure_logging(self, logger_dict=None): """ Configures the logging module with a given dictionary, which in most cases was loaded from a configuration file. If no dictionary is provided, it falls back to a default configuration. See `Python docs <https://docs.py...
[ "def", "_configure_logging", "(", "self", ",", "logger_dict", "=", "None", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Configure logging\"", ")", "# Let's be sure, that for our log no handlers are registered anymore", "for", "handler", "in", "self", ".", "log"...
46.827586
25.310345
def unpack(self, column_name_prefix = "X", column_types=None, na_value=None, limit=None): """ Convert an SArray of list, array, or dict type to an SFrame with multiple columns. `unpack` expands an SArray using the values of each list/array/dict as elements in a new SFrame of mul...
[ "def", "unpack", "(", "self", ",", "column_name_prefix", "=", "\"X\"", ",", "column_types", "=", "None", ",", "na_value", "=", "None", ",", "limit", "=", "None", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "if", "self", ".", "...
37.156566
24.419192
def write_event(self, event): """Writes an event proto to disk. This method is threadsafe with respect to invocations of itself. Args: event: The event proto. Raises: IOError: If writing the event proto to disk fails. """ self._lock.acquire() try: self._events_writer.Wri...
[ "def", "write_event", "(", "self", ",", "event", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_events_writer", ".", "WriteEvent", "(", "event", ")", "self", ".", "_event_count", "+=", "1", "if", "self", ".", "_a...
36.727273
19.272727
def get_active_tasks(self): """Return a list of UUIDs of active tasks.""" current_tasks = self.celery.control.inspect().active() or dict() return [ task.get('id') for host in current_tasks.values() for task in host]
[ "def", "get_active_tasks", "(", "self", ")", ":", "current_tasks", "=", "self", ".", "celery", ".", "control", ".", "inspect", "(", ")", ".", "active", "(", ")", "or", "dict", "(", ")", "return", "[", "task", ".", "get", "(", "'id'", ")", "for", "h...
49.4
21.6
def url_for(self, attr=None, filter_value=None, service_type=None, endpoint_type="publicURL", service_name=None, volume_service_name=None): """Fetches the public URL from the given service for a particular endpoint attribute. If none given, returns the first. See tests fo...
[ "def", "url_for", "(", "self", ",", "attr", "=", "None", ",", "filter_value", "=", "None", ",", "service_type", "=", "None", ",", "endpoint_type", "=", "\"publicURL\"", ",", "service_name", "=", "None", ",", "volume_service_name", "=", "None", ")", ":", "m...
43.928571
15.392857
def fit_model(y, x, yMaxLag, xMaxLag, includesOriginalX=True, noIntercept=False, sc=None): """ Fit an autoregressive model with additional exogenous variables. The model predicts a value at time t of a dependent variable, Y, as a function of previous values of Y, and a combination of previous values of ...
[ "def", "fit_model", "(", "y", ",", "x", ",", "yMaxLag", ",", "xMaxLag", ",", "includesOriginalX", "=", "True", ",", "noIntercept", "=", "False", ",", "sc", "=", "None", ")", ":", "assert", "sc", "!=", "None", ",", "\"Missing SparkContext\"", "jvm", "=", ...
50.885714
34.028571
def get_default_config(self): """ Returns the default collector settings """ config = super(ExampleCollector, self).get_default_config() config.update({ 'path': 'example' }) return config
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "ExampleCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'example'", "}", ")", "return", "config" ]
27.888889
13
def setCurrentProfile(self, profile): """ Sets the current profile to the inputed profile. :param profile | <XViewProfile> """ try: index = self._profiles.index(profile) except ValueError: index = -1 self._profileComb...
[ "def", "setCurrentProfile", "(", "self", ",", "profile", ")", ":", "try", ":", "index", "=", "self", ".", "_profiles", ".", "index", "(", "profile", ")", "except", "ValueError", ":", "index", "=", "-", "1", "self", ".", "_profileCombo", ".", "setCurrentI...
27.75
13.75
def __get_WIOD_SEA_extension(root_path, year, data_sheet='DATA'): """ Utility function to get the extension data from the SEA file in WIOD This function is based on the structure in the WIOD_SEA_July14 file. Missing values are set to zero. The function works if the SEA file is either in path or in a s...
[ "def", "__get_WIOD_SEA_extension", "(", "root_path", ",", "year", ",", "data_sheet", "=", "'DATA'", ")", ":", "sea_ext", "=", "'.xlsx'", "sea_start", "=", "'WIOD_SEA'", "_SEA_folder", "=", "os", ".", "path", ".", "join", "(", "root_path", ",", "'SEA'", ")", ...
36.459184
18.959184
def send_notification(self, method, args, kwargs): """Send a notification.""" msg = dumps([1, method, args, kwargs]) self.send(msg)
[ "def", "send_notification", "(", "self", ",", "method", ",", "args", ",", "kwargs", ")", ":", "msg", "=", "dumps", "(", "[", "1", ",", "method", ",", "args", ",", "kwargs", "]", ")", "self", ".", "send", "(", "msg", ")" ]
38
8.5
def getParams(self): """ get params """ rv = np.array([]) if self.n_terms>0: rv = np.concatenate([np.reshape(self.B[term_i],self.B[term_i].size, order='F') for term_i in range(self.n_terms)]) return rv
[ "def", "getParams", "(", "self", ")", ":", "rv", "=", "np", ".", "array", "(", "[", "]", ")", "if", "self", ".", "n_terms", ">", "0", ":", "rv", "=", "np", ".", "concatenate", "(", "[", "np", ".", "reshape", "(", "self", ".", "B", "[", "term_...
40
26.333333
def is_protected(self): """ Determine if the function is protected using a check on msg.sender Only detects if msg.sender is directly used in a condition For example, it wont work for: address a = msg.sender require(a == owner) Returns...
[ "def", "is_protected", "(", "self", ")", ":", "if", "self", ".", "is_constructor", ":", "return", "True", "conditional_vars", "=", "self", ".", "all_conditional_solidity_variables_read", "(", "include_loop", "=", "False", ")", "args_vars", "=", "self", ".", "all...
37.235294
21.470588
def mtf_image_transformer_cifar_4x(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "batch:32" hparams.layout = "batch:batch" hparams.batch_size = 128 return hparams
[ "def", "mtf_image_transformer_cifar_4x", "(", ")", ":", "hparams", "=", "mtf_image_transformer_base_cifar", "(", ")", "hparams", ".", "mesh_shape", "=", "\"batch:32\"", "hparams", ".", "layout", "=", "\"batch:batch\"", "hparams", ".", "batch_size", "=", "128", "retu...
32.714286
8.857143
def registered(self, driver, frameworkId, masterInfo): """ Invoked when the scheduler successfully registers with a Mesos master """ log.debug("Registered with framework ID %s", frameworkId.value) # Save the framework ID self.frameworkId = frameworkId.value
[ "def", "registered", "(", "self", ",", "driver", ",", "frameworkId", ",", "masterInfo", ")", ":", "log", ".", "debug", "(", "\"Registered with framework ID %s\"", ",", "frameworkId", ".", "value", ")", "# Save the framework ID", "self", ".", "frameworkId", "=", ...
42.714286
13.571429
def _convert_to_var(self, graph, var_res): """ Create tf.Variables from a list of numpy arrays var_res: dictionary of numpy arrays with the key names corresponding to var """ with graph.as_default(): var = {} for key, value in var_res.items(): ...
[ "def", "_convert_to_var", "(", "self", ",", "graph", ",", "var_res", ")", ":", "with", "graph", ".", "as_default", "(", ")", ":", "var", "=", "{", "}", "for", "key", ",", "value", "in", "var_res", ".", "items", "(", ")", ":", "if", "value", "is", ...
34.285714
15.142857
def get_network_instances(self, name=""): """ get_network_instances implementation for NX-OS """ # command 'show vrf detail' returns all VRFs with detailed information # format: list of dictionaries with keys such as 'vrf_name' and 'rd' command = "show vrf detail" vrf_table_raw ...
[ "def", "get_network_instances", "(", "self", ",", "name", "=", "\"\"", ")", ":", "# command 'show vrf detail' returns all VRFs with detailed information", "# format: list of dictionaries with keys such as 'vrf_name' and 'rd'", "command", "=", "\"show vrf detail\"", "vrf_table_raw", "...
41.764706
23.568627
def assignParameters(self,**kwds): ''' Assign an arbitrary number of attributes to this agent. Parameters ---------- **kwds : keyword arguments Any number of keyword arguments of the form key=value. Each value will be assigned to the attribute named in s...
[ "def", "assignParameters", "(", "self", ",", "*", "*", "kwds", ")", ":", "for", "key", "in", "kwds", ":", "setattr", "(", "self", ",", "key", ",", "kwds", "[", "key", "]", ")" ]
27
23.125
def forward_moves(self, position): """ Finds possible moves one step and two steps in front of Pawn. :type: position: Board :rtype: list """ if position.is_square_empty(self.square_in_front(self.location)): """ If square in front is empty ...
[ "def", "forward_moves", "(", "self", ",", "position", ")", ":", "if", "position", ".", "is_square_empty", "(", "self", ".", "square_in_front", "(", "self", ".", "location", ")", ")", ":", "\"\"\"\n If square in front is empty add the move\n \"\"\""...
39
18.655172
def sync(self, *buckets): """Sync either a list of buckets or the entire connection. Force all API calls to S3 and populate the database with the current state of S3. :param \*string \*buckets: Buckets to sync """ if buckets: for _bucket in buckets: ...
[ "def", "sync", "(", "self", ",", "*", "buckets", ")", ":", "if", "buckets", ":", "for", "_bucket", "in", "buckets", ":", "for", "key", "in", "mimicdb", ".", "backend", ".", "smembers", "(", "tpl", ".", "bucket", "%", "_bucket", ")", ":", "mimicdb", ...
45.193548
29.032258
def _quote(self, value, multiline=True): """ Return a safely quoted version of a value. Raise a ConfigObjError if the value cannot be safely quoted. If multiline is ``True`` (default) then use triple quotes if necessary. * Don't quote values that don't need it. ...
[ "def", "_quote", "(", "self", ",", "value", ",", "multiline", "=", "True", ")", ":", "if", "multiline", "and", "self", ".", "write_empty_values", "and", "value", "==", "''", ":", "# Only if multiline is set, so that it is used for values not", "# keys, and not values ...
41.731343
22.925373
def create_response(self, status=201): """Generate a Response object for a POST request. By default, the newly created object will be passed to the specified ResponseHandler and will be serialized as the response body. """ self.response = self.get_response_handler() self...
[ "def", "create_response", "(", "self", ",", "status", "=", "201", ")", ":", "self", ".", "response", "=", "self", ".", "get_response_handler", "(", ")", "self", ".", "response", ".", "process", "(", "self", ".", "obj", ")", "return", "self", ".", "_res...
46.666667
16.555556
def _read_projections(folder, indices): """Read mayo projections from a folder.""" datasets = [] # Get the relevant file names file_names = sorted([f for f in os.listdir(folder) if f.endswith(".dcm")]) if len(file_names) == 0: raise ValueError('No DICOM files found in {}'.format(folder)) ...
[ "def", "_read_projections", "(", "folder", ",", "indices", ")", ":", "datasets", "=", "[", "]", "# Get the relevant file names", "file_names", "=", "sorted", "(", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", "folder", ")", "if", "f", ".", "ends...
33.173913
19.73913
def extract(cls, keystr): """ for #{key} returns key """ regex = r'#{\s*(%s)\s*}' % cls.ALLOWED_KEY return re.match(regex, keystr).group(1)
[ "def", "extract", "(", "cls", ",", "keystr", ")", ":", "regex", "=", "r'#{\\s*(%s)\\s*}'", "%", "cls", ".", "ALLOWED_KEY", "return", "re", ".", "match", "(", "regex", ",", "keystr", ")", ".", "group", "(", "1", ")" ]
40
8
def key_func(*keys, **kwargs): """Creates a "key function" based on given keys. Resulting function will perform lookup using specified keys, in order, on the object passed to it as an argument. For example, ``key_func('a', 'b')(foo)`` is equivalent to ``foo['a']['b']``. :param keys: Lookup keys ...
[ "def", "key_func", "(", "*", "keys", ",", "*", "*", "kwargs", ")", ":", "ensure_argcount", "(", "keys", ",", "min_", "=", "1", ")", "ensure_keyword_args", "(", "kwargs", ",", "optional", "=", "(", "'default'", ",", ")", ")", "keys", "=", "list", "(",...
30.297297
18.486486
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by ...
[ "def", "folderitem", "(", "self", ",", "obj", ",", "item", ",", "index", ")", ":", "cat", "=", "obj", ".", "getCategoryTitle", "(", ")", "cat_order", "=", "self", ".", "an_cats_order", ".", "get", "(", "cat", ")", "if", "self", ".", "do_cats", ":", ...
34.704225
16.661972
def start(self): """Commence audio processing. If successful, the stream is considered active. """ err = _pa.Pa_StartStream(self._stream) if err == _pa.paStreamIsNotStopped: return self._handle_error(err)
[ "def", "start", "(", "self", ")", ":", "err", "=", "_pa", ".", "Pa_StartStream", "(", "self", ".", "_stream", ")", "if", "err", "==", "_pa", ".", "paStreamIsNotStopped", ":", "return", "self", ".", "_handle_error", "(", "err", ")" ]
25.7
15.9
def _float(value): """Conversion of state vector field, with automatic unit handling """ if "[" in value: # There is a unit field value, sep, unit = value.partition("[") unit = sep + unit # As defined in the CCSDS Orbital Data Message Blue Book, the unit should # be ...
[ "def", "_float", "(", "value", ")", ":", "if", "\"[\"", "in", "value", ":", "# There is a unit field", "value", ",", "sep", ",", "unit", "=", "value", ".", "partition", "(", "\"[\"", ")", "unit", "=", "sep", "+", "unit", "# As defined in the CCSDS Orbital Da...
36.227273
20.318182
def dump(obj, file_path, prettify=False): """ Dumps a data structure to the filesystem as TOML. The given value must be either a dict of dict values, a dict, or a TOML file constructed by this module. """ with open(file_path, 'w') as fp: fp.write(dumps(obj))
[ "def", "dump", "(", "obj", ",", "file_path", ",", "prettify", "=", "False", ")", ":", "with", "open", "(", "file_path", ",", "'w'", ")", "as", "fp", ":", "fp", ".", "write", "(", "dumps", "(", "obj", ")", ")" ]
35
17.25
def correct_word(word_string): ''' Finds all valid one and two letter corrections for word_string, returning the word with the highest relative probability as type str. ''' if word_string is None: return "" elif isinstance(word_string, str): return max(find_candidates(word_string...
[ "def", "correct_word", "(", "word_string", ")", ":", "if", "word_string", "is", "None", ":", "return", "\"\"", "elif", "isinstance", "(", "word_string", ",", "str", ")", ":", "return", "max", "(", "find_candidates", "(", "word_string", ")", ",", "key", "="...
39.818182
26.181818
def get_characteristic_subpattern(subpatterns): """Picks the most characteristic from a list of linear patterns Current order used is: names > common_names > common_chars """ if not isinstance(subpatterns, list): return subpatterns if len(subpatterns)==1: return subpatterns[0] ...
[ "def", "get_characteristic_subpattern", "(", "subpatterns", ")", ":", "if", "not", "isinstance", "(", "subpatterns", ",", "list", ")", ":", "return", "subpatterns", "if", "len", "(", "subpatterns", ")", "==", "1", ":", "return", "subpatterns", "[", "0", "]",...
40.138889
13.861111
def _update(qs): """ Increment the sort_order in a queryset. Handle IntegrityErrors caused by unique constraints. """ try: with transaction.atomic(): qs.update(sort_order=models.F('sort_order') + 1) except IntegrityError: for obj i...
[ "def", "_update", "(", "qs", ")", ":", "try", ":", "with", "transaction", ".", "atomic", "(", ")", ":", "qs", ".", "update", "(", "sort_order", "=", "models", ".", "F", "(", "'sort_order'", ")", "+", "1", ")", "except", "IntegrityError", ":", "for", ...
35.083333
17.25
def gender(self, iso5218: bool = False, symbol: bool = False) -> Union[str, int]: """Get a random gender. Get a random title of gender, code for the representation of human sexes is an international standard that defines a representation of human sexes through a language-...
[ "def", "gender", "(", "self", ",", "iso5218", ":", "bool", "=", "False", ",", "symbol", ":", "bool", "=", "False", ")", "->", "Union", "[", "str", ",", "int", "]", ":", "if", "iso5218", ":", "return", "self", ".", "random", ".", "choice", "(", "[...
34.28
21.56
def _load(self): """Load the MODIS RSR data for the band requested""" if self.is_sw or self.platform_name == 'EOS-Aqua': scale = 0.001 else: scale = 1.0 detector = read_modis_response(self.requested_band_filename, scale) self.rsr = detector if self...
[ "def", "_load", "(", "self", ")", ":", "if", "self", ".", "is_sw", "or", "self", ".", "platform_name", "==", "'EOS-Aqua'", ":", "scale", "=", "0.001", "else", ":", "scale", "=", "1.0", "detector", "=", "read_modis_response", "(", "self", ".", "requested_...
34.2
18.4
def get_url_for_id(client_site_url, apikey, resource_id): """Return the URL for the given resource ID. Contacts the client site's API to get the URL for the ID and returns it. :raises CouldNotGetURLError: if getting the URL fails for any reason """ # TODO: Handle invalid responses from the client...
[ "def", "get_url_for_id", "(", "client_site_url", ",", "apikey", ",", "resource_id", ")", ":", "# TODO: Handle invalid responses from the client site.", "url", "=", "client_site_url", "+", "u\"deadoralive/get_url_for_resource_id\"", "params", "=", "{", "\"resource_id\"", ":", ...
39.5
20.45
def set_primary_heartbeat(self, interface_id): """ Set this interface as the primary heartbeat for this engine. This will 'unset' the current primary heartbeat and move to specified interface_id. Clusters and Master NGFW Engines only. :param str,int interface_id...
[ "def", "set_primary_heartbeat", "(", "self", ",", "interface_id", ")", ":", "self", ".", "interface", ".", "set_unset", "(", "interface_id", ",", "'primary_heartbeat'", ")", "self", ".", "_engine", ".", "update", "(", ")" ]
43.571429
17.857143
def _handleUssd(self, lines): """ Handler for USSD event notification line(s) """ if self._ussdSessionEvent: # A sendUssd() call is waiting for this response - parse it self._ussdResponse = self._parseCusdResponse(lines) # Notify waiting thread self._ussdS...
[ "def", "_handleUssd", "(", "self", ",", "lines", ")", ":", "if", "self", ".", "_ussdSessionEvent", ":", "# A sendUssd() call is waiting for this response - parse it", "self", ".", "_ussdResponse", "=", "self", ".", "_parseCusdResponse", "(", "lines", ")", "# Notify wa...
47.285714
10.857143
def _mass(self,R,z=0.,t=0.): """ NAME: _mass PURPOSE: evaluate the mass within R for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height t - time OUTPUT: the mass enclosed HISTOR...
[ "def", "_mass", "(", "self", ",", "R", ",", "z", "=", "0.", ",", "t", "=", "0.", ")", ":", "if", "z", "is", "None", ":", "r", "=", "R", "else", ":", "r", "=", "nu", ".", "sqrt", "(", "R", "**", "2.", "+", "z", "**", "2.", ")", "return",...
31.166667
19.055556
def add_status_job(self, job_func, name=None, timeout=3): """Adds a job to be included during calls to the `/status` endpoint. :param job_func: the status function. :param name: the name used in the JSON response for the given status function. The name of the function is th...
[ "def", "add_status_job", "(", "self", ",", "job_func", ",", "name", "=", "None", ",", "timeout", "=", "3", ")", ":", "job_name", "=", "job_func", ".", "__name__", "if", "name", "is", "None", "else", "name", "job", "=", "(", "job_name", ",", "timeout", ...
48.666667
16.416667
def cmd_gateway_find(network, iface, host, tcp, dport, timeout, verbose): """ Try to reach an external IP using any host has a router. Useful to find routers in your network. First, uses arping to detect alive hosts and obtain MAC addresses. Later, create a network packet and put each MAC address...
[ "def", "cmd_gateway_find", "(", "network", ",", "iface", ",", "host", ",", "tcp", ",", "dport", ",", "timeout", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "="...
28.319149
25.510638
def _set_axis(self,traces,on=None,side='right',title=''): """ Sets the axis in which each trace should appear If the axis doesn't exist then a new axis is created Parameters: ----------- traces : list(str) List of trace names on : string The axis in which the traces should be placed. If this is not i...
[ "def", "_set_axis", "(", "self", ",", "traces", ",", "on", "=", "None", ",", "side", "=", "'right'", ",", "title", "=", "''", ")", ":", "fig", "=", "{", "}", "fig_cpy", "=", "fig_to_dict", "(", "self", ")", ".", "copy", "(", ")", "fig", "[", "'...
27.507937
19.698413
async def login(self, client_name, request, redirect_uri=None, **params): """Process login with OAuth. :param client_name: A name one of configured clients :param request: Web request :param redirect_uri: An URI for authorization redirect """ client = self.client(client_...
[ "async", "def", "login", "(", "self", ",", "client_name", ",", "request", ",", "redirect_uri", "=", "None", ",", "*", "*", "params", ")", ":", "client", "=", "self", ".", "client", "(", "client_name", ",", "logger", "=", "self", ".", "app", ".", "log...
38.716667
21.1
def get_project_logs(self, request): """ Get logs from log service. Unsuccessful opertaion will cause an LogException. :type request: GetProjectLogsRequest :param request: the GetProjectLogs request parameters class. :return: GetLogsResponse ...
[ "def", "get_project_logs", "(", "self", ",", "request", ")", ":", "headers", "=", "{", "}", "params", "=", "{", "}", "if", "request", ".", "get_query", "(", ")", "is", "not", "None", ":", "params", "[", "'query'", "]", "=", "request", ".", "get_query...
35.842105
14.842105
def Handle(self, unused_args, token=None): """Build the data structure representing the config.""" sections = {} for descriptor in config.CONFIG.type_infos: if descriptor.section in sections: continue section_data = {} for parameter in self._ListParametersInSection(descriptor.sec...
[ "def", "Handle", "(", "self", ",", "unused_args", ",", "token", "=", "None", ")", ":", "sections", "=", "{", "}", "for", "descriptor", "in", "config", ".", "CONFIG", ".", "type_infos", ":", "if", "descriptor", ".", "section", "in", "sections", ":", "co...
31.192308
18.461538
def enrich_internal_unqualified_edges(graph, subgraph): """Add the missing unqualified edges between entities in the subgraph that are contained within the full graph. :param pybel.BELGraph graph: The full BEL graph :param pybel.BELGraph subgraph: The query BEL subgraph """ for u, v in itt.combinat...
[ "def", "enrich_internal_unqualified_edges", "(", "graph", ",", "subgraph", ")", ":", "for", "u", ",", "v", "in", "itt", ".", "combinations", "(", "subgraph", ",", "2", ")", ":", "if", "not", "graph", ".", "has_edge", "(", "u", ",", "v", ")", ":", "co...
38.615385
16
def parsing_token_generator(data_dir, tmp_dir, train, source_vocab_size, target_vocab_size): """Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files parsing_{train,dev}.trees, which contain trees in WSJ format. Args: data_dir: ...
[ "def", "parsing_token_generator", "(", "data_dir", ",", "tmp_dir", ",", "train", ",", "source_vocab_size", ",", "target_vocab_size", ")", ":", "# TODO(lukaszkaiser): Correct these calls to generate vocabularies. No data", "# sources are being passed.", "del", "(", "data_dir", "...
38.619048
18.809524
def _get_repo_details(saltenv): ''' Return repo details for the specified saltenv as a namedtuple ''' contextkey = 'winrepo._get_repo_details.{0}'.format(saltenv) if contextkey in __context__: (winrepo_source_dir, local_dest, winrepo_file) = __context__[contextkey] else: winrepo...
[ "def", "_get_repo_details", "(", "saltenv", ")", ":", "contextkey", "=", "'winrepo._get_repo_details.{0}'", ".", "format", "(", "saltenv", ")", "if", "contextkey", "in", "__context__", ":", "(", "winrepo_source_dir", ",", "local_dest", ",", "winrepo_file", ")", "=...
37.948052
20.077922
def refresh(self): """ Refreshing a Library or individual item causes the metadata for the item to be refreshed, even if it already has metadata. You can think of refreshing as "update metadata for the requested item even if it already has some". You should refresh a Library ...
[ "def", "refresh", "(", "self", ")", ":", "key", "=", "'%s/refresh'", "%", "self", ".", "key", "self", ".", "_server", ".", "query", "(", "key", ",", "method", "=", "self", ".", "_server", ".", "_session", ".", "put", ")" ]
58.176471
25.176471
def expand_classes_glob(classes, salt_data): ''' Expand the list of `classes` to no longer include any globbing. :param iterable(str) classes: Iterable of classes :param dict salt_data: configuration data :return: Expanded list of classes with resolved globbing :rtype: list(str) ''' all...
[ "def", "expand_classes_glob", "(", "classes", ",", "salt_data", ")", ":", "all_classes", "=", "[", "]", "expanded_classes", "=", "[", "]", "saltclass_path", "=", "salt_data", "[", "'path'", "]", "for", "_class", "in", "classes", ":", "all_classes", ".", "ext...
29.666667
20.047619
def request_param_update(self, var_id): """Place a param update request on the queue""" self._useV2 = self.cf.platform.get_protocol_version() >= 4 pk = CRTPPacket() pk.set_header(CRTPPort.PARAM, READ_CHANNEL) if self._useV2: pk.data = struct.pack('<H', var_id) ...
[ "def", "request_param_update", "(", "self", ",", "var_id", ")", ":", "self", ".", "_useV2", "=", "self", ".", "cf", ".", "platform", ".", "get_protocol_version", "(", ")", ">=", "4", "pk", "=", "CRTPPacket", "(", ")", "pk", ".", "set_header", "(", "CRT...
42.818182
13.454545
def from_xdr_object(cls, op_xdr_object): """Creates a :class:`SetOptions` object from an XDR Operation object. """ if not op_xdr_object.sourceAccount: source = None else: source = encode_check( 'account', op_xdr_object.sourceAccount[0].ed2...
[ "def", "from_xdr_object", "(", "cls", ",", "op_xdr_object", ")", ":", "if", "not", "op_xdr_object", ".", "sourceAccount", ":", "source", "=", "None", "else", ":", "source", "=", "encode_check", "(", "'account'", ",", "op_xdr_object", ".", "sourceAccount", "[",...
40.403509
16.508772
def convenience_calc_fisher_approx(self, params): """ Calculates the BHHH approximation of the Fisher Information Matrix for this model / dataset. """ shapes, intercepts, betas = self.convenience_split_params(params) args = [betas, self.design, ...
[ "def", "convenience_calc_fisher_approx", "(", "self", ",", "params", ")", ":", "shapes", ",", "intercepts", ",", "betas", "=", "self", ".", "convenience_split_params", "(", "params", ")", "args", "=", "[", "betas", ",", "self", ".", "design", ",", "self", ...
32.043478
13.086957
def write_Note(file, note, bpm=120, repeat=0, verbose=False): """Expect a Note object from mingus.containers and save it into a MIDI file, specified in file. You can set the velocity and channel in Note.velocity and Note.channel. """ m = MidiFile() t = MidiTrack(bpm) m.tracks = [t] whil...
[ "def", "write_Note", "(", "file", ",", "note", ",", "bpm", "=", "120", ",", "repeat", "=", "0", ",", "verbose", "=", "False", ")", ":", "m", "=", "MidiFile", "(", ")", "t", "=", "MidiTrack", "(", "bpm", ")", "m", ".", "tracks", "=", "[", "t", ...
30.875
16.1875
def parse_photo(data): """ Parse a ``MeetupPhoto`` from the given response data. Returns ------- A `pythonkc_meetups.types.`MeetupPhoto``. """ return MeetupPhoto( id=data.get('photo_id', data.get('id', None)), url=data.get('photo_link', None), highres_url=data.get('...
[ "def", "parse_photo", "(", "data", ")", ":", "return", "MeetupPhoto", "(", "id", "=", "data", ".", "get", "(", "'photo_id'", ",", "data", ".", "get", "(", "'id'", ",", "None", ")", ")", ",", "url", "=", "data", ".", "get", "(", "'photo_link'", ",",...
25.333333
17.466667
def setViewTypes(self, viewTypes, window=None): """ Sets the view types that can be used for this widget. If the optional \ window member is supplied, then the registerToWindow method will be \ called for each view. :param viewTypes | [<sublcass of XView>, ..] ...
[ "def", "setViewTypes", "(", "self", ",", "viewTypes", ",", "window", "=", "None", ")", ":", "if", "window", ":", "for", "viewType", "in", "self", ".", "_viewTypes", ":", "viewType", ".", "unregisterFromWindow", "(", "window", ")", "self", ".", "_viewTypes"...
36.05
16.35
def autorenew_deactivate(cls, fqdn): """Activate deautorenew""" fqdn = fqdn.lower() result = cls.call('domain.autorenew.deactivate', fqdn) return result
[ "def", "autorenew_deactivate", "(", "cls", ",", "fqdn", ")", ":", "fqdn", "=", "fqdn", ".", "lower", "(", ")", "result", "=", "cls", ".", "call", "(", "'domain.autorenew.deactivate'", ",", "fqdn", ")", "return", "result" ]
25.714286
19.714286
def parents(self, node, relations=None): """ Return all direct parents of specified node. Wraps networkx by default. Arguments --------- node: string identifier for node in ontology relations: list of strings list of relation (object proper...
[ "def", "parents", "(", "self", ",", "node", ",", "relations", "=", "None", ")", ":", "g", "=", "self", ".", "get_graph", "(", ")", "if", "node", "in", "g", ":", "parents", "=", "list", "(", "g", ".", "predecessors", "(", "node", ")", ")", "if", ...
29.625
18.541667
def shell_django(session: DjangoSession, backend: ShellBackend): """ This command includes Django DB Session """ namespace = { 'session': session } namespace.update(backend.get_namespace()) embed(user_ns=namespace, header=backend.header)
[ "def", "shell_django", "(", "session", ":", "DjangoSession", ",", "backend", ":", "ShellBackend", ")", ":", "namespace", "=", "{", "'session'", ":", "session", "}", "namespace", ".", "update", "(", "backend", ".", "get_namespace", "(", ")", ")", "embed", "...
29.444444
12.777778
def GetCursorPos() -> tuple: """ GetCursorPos from Win32. Get current mouse cursor positon. Return tuple, two ints tuple (x, y). """ point = ctypes.wintypes.POINT(0, 0) ctypes.windll.user32.GetCursorPos(ctypes.byref(point)) return point.x, point.y
[ "def", "GetCursorPos", "(", ")", "->", "tuple", ":", "point", "=", "ctypes", ".", "wintypes", ".", "POINT", "(", "0", ",", "0", ")", "ctypes", ".", "windll", ".", "user32", ".", "GetCursorPos", "(", "ctypes", ".", "byref", "(", "point", ")", ")", "...
30.111111
6.555556
def handle(self, object, *args, **kw): ''' Calls each plugin in this PluginSet with the specified object, arguments, and keywords in the standard group plugin order. The return value from each successive invoked plugin is passed as the first parameter to the next plugin. The final return value is th...
[ "def", "handle", "(", "self", ",", "object", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "not", "bool", "(", "self", ")", ":", "if", "not", "self", ".", "spec", "or", "self", ".", "spec", "==", "SPEC_ALL", ":", "raise", "ValueError", ...
43.052632
21.473684
def open_channel( self, kind, dest_addr=None, src_addr=None, window_size=None, max_packet_size=None, timeout=None, ): """ Request a new channel to the server. `Channels <.Channel>` are socket-like objects used for the actual transfer of...
[ "def", "open_channel", "(", "self", ",", "kind", ",", "dest_addr", "=", "None", ",", "src_addr", "=", "None", ",", "window_size", "=", "None", ",", "max_packet_size", "=", "None", ",", "timeout", "=", "None", ",", ")", ":", "if", "not", "self", ".", ...
39.351064
17.5
def circuit_drawer(circuit, scale=0.7, filename=None, style=None, output='text', interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, ...
[ "def", "circuit_drawer", "(", "circuit", ",", "scale", "=", "0.7", ",", "filename", "=", "None", ",", "style", "=", "None", ",", "output", "=", "'text'", ",", "interactive", "=", "False", ",", "line_length", "=", "None", ",", "plot_barriers", "=", "True"...
51.171598
23.39645
def empty_like(self, shape): """ Make an empty LabelArray with the same categories as ``self``, filled with ``self.missing_value``. """ return type(self).from_codes_and_metadata( codes=np.full( shape, self.reverse_categories[self.missin...
[ "def", "empty_like", "(", "self", ",", "shape", ")", ":", "return", "type", "(", "self", ")", ".", "from_codes_and_metadata", "(", "codes", "=", "np", ".", "full", "(", "shape", ",", "self", ".", "reverse_categories", "[", "self", ".", "missing_value", "...
37.2
15.2
def create_cli(create_app=None): """Create CLI for ``inveniomanage`` command. :param create_app: Flask application factory. :returns: Click command group. .. versionadded: 1.0.0 """ def create_cli_app(info): """Application factory for CLI app. Internal function for creating th...
[ "def", "create_cli", "(", "create_app", "=", "None", ")", ":", "def", "create_cli_app", "(", "info", ")", ":", "\"\"\"Application factory for CLI app.\n\n Internal function for creating the CLI. When invoked via\n ``inveniomanage`` FLASK_APP must be set.\n \"\"\"", ...
27.642857
16.5
def postloop(self): """Take care of any unfinished business. Despite the claims in the Cmd documentation, Cmd.postloop() is not a stub. """ cmd.Cmd.postloop(self) # Clean up command completion d1_cli.impl.util.print_info("Exiting...")
[ "def", "postloop", "(", "self", ")", ":", "cmd", ".", "Cmd", ".", "postloop", "(", "self", ")", "# Clean up command completion", "d1_cli", ".", "impl", ".", "util", ".", "print_info", "(", "\"Exiting...\"", ")" ]
33.75
21.625
def _check_repos(self, repos): """Check if repodata urls are valid.""" self._checking_repos = [] self._valid_repos = [] for repo in repos: worker = self.download_is_valid_url(repo) worker.sig_finished.connect(self._repos_checked) worker.repo = repo ...
[ "def", "_check_repos", "(", "self", ",", "repos", ")", ":", "self", ".", "_checking_repos", "=", "[", "]", "self", ".", "_valid_repos", "=", "[", "]", "for", "repo", "in", "repos", ":", "worker", "=", "self", ".", "download_is_valid_url", "(", "repo", ...
35.4
12.9
def transformer_librispeech_v2(): """HParams for training ASR model on LibriSpeech V2.""" hparams = transformer_base() hparams.max_length = 1240000 hparams.max_input_seq_length = 1550 hparams.max_target_seq_length = 350 hparams.batch_size = 16 hparams.num_decoder_layers = 4 hparams.num_encoder_layers =...
[ "def", "transformer_librispeech_v2", "(", ")", ":", "hparams", "=", "transformer_base", "(", ")", "hparams", ".", "max_length", "=", "1240000", "hparams", ".", "max_input_seq_length", "=", "1550", "hparams", ".", "max_target_seq_length", "=", "350", "hparams", "."...
29.227273
11.909091
def replace(self, ): """Replace the current reftrack :returns: None :rtype: None :raises: None """ tfi = self.get_taskfileinfo_selection() if tfi: self.reftrack.replace(tfi)
[ "def", "replace", "(", "self", ",", ")", ":", "tfi", "=", "self", ".", "get_taskfileinfo_selection", "(", ")", "if", "tfi", ":", "self", ".", "reftrack", ".", "replace", "(", "tfi", ")" ]
23.3
15.1