text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def data_received(self, data): """Add incoming data to buffer.""" data = data.decode('ascii') self.log.debug('received data: %s', data) self.telegram_buffer.append(data) for telegram in self.telegram_buffer.get_all(): self.handle_telegram(telegram)
[ "def", "data_received", "(", "self", ",", "data", ")", ":", "data", "=", "data", ".", "decode", "(", "'ascii'", ")", "self", ".", "log", ".", "debug", "(", "'received data: %s'", ",", "data", ")", "self", ".", "telegram_buffer", ".", "append", "(", "da...
36.75
10.25
def post(self, url: str, data: str, expected_status_code=201): """ Do a POST request """ r = requests.post(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT) self._check_response(r, expected_status_code) return r.json()
[ "def", "post", "(", "self", ",", "url", ":", "str", ",", "data", ":", "str", ",", "expected_status_code", "=", "201", ")", ":", "r", "=", "requests", ".", "post", "(", "self", ".", "_format_url", "(", "url", ")", ",", "json", "=", "data", ",", "h...
35.375
20.625
def solarized(): '''Set solarized colors in urxvt, tmux, and vim. More Infos: * Getting solarized colors right with urxvt, st, tmux and vim: https://bbs.archlinux.org/viewtopic.php?id=164108 * Creating ~/.Xresources: https://wiki.archlinux.org/index.php/Rxvt-unicode#Creating_.7E.2F.Xresour...
[ "def", "solarized", "(", ")", ":", "install_packages", "(", "[", "'rxvt-unicode'", ",", "'tmux'", ",", "'vim'", "]", ")", "install_file_legacy", "(", "'~/.Xresources'", ")", "if", "env", ".", "host_string", "==", "'localhost'", ":", "run", "(", "'xrdb ~/.Xres...
31.846154
19.076923
def set(self, x, y): """Set a pixel of the :class:`Canvas` object. :param x: x coordinate of the pixel :param y: y coordinate of the pixel """ x = normalize(x) y = normalize(y) col, row = get_pos(x, y) if type(self.chars[row][col]) != int: re...
[ "def", "set", "(", "self", ",", "x", ",", "y", ")", ":", "x", "=", "normalize", "(", "x", ")", "y", "=", "normalize", "(", "y", ")", "col", ",", "row", "=", "get_pos", "(", "x", ",", "y", ")", "if", "type", "(", "self", ".", "chars", "[", ...
26.285714
16.285714
def open(self): ''' Open file corresponding to the TUN device. ''' self.fd = open('/dev/net/tun', 'rb+', buffering=0) tun_flags = IFF_TAP | IFF_NO_PI | IFF_PERSIST ifr = struct.pack('16sH', self.name, tun_flags) fcntl.ioctl(self.fd, TUNSETIFF, ifr) fcntl.ioctl(self.fd, TU...
[ "def", "open", "(", "self", ")", ":", "self", ".", "fd", "=", "open", "(", "'/dev/net/tun'", ",", "'rb+'", ",", "buffering", "=", "0", ")", "tun_flags", "=", "IFF_TAP", "|", "IFF_NO_PI", "|", "IFF_PERSIST", "ifr", "=", "struct", ".", "pack", "(", "'1...
48.25
14.5
def _set_ignored_version(version): """ Private helper function that writes the most updated API version that was ignored by a user in the app :param version: Most recent ignored API update """ data = {'version': version} with open(filepath, 'w') as data_file: json.dump(data, data_fil...
[ "def", "_set_ignored_version", "(", "version", ")", ":", "data", "=", "{", "'version'", ":", "version", "}", "with", "open", "(", "filepath", ",", "'w'", ")", "as", "data_file", ":", "json", ".", "dump", "(", "data", ",", "data_file", ")" ]
34.888889
6.888889
def flatten(d, parent_key='', separator='__'): """ Flatten a nested dictionary. Parameters ---------- d: dict_like Dictionary to flatten. parent_key: string, optional Concatenated names of the parent keys. separator: string, optional Separator between the names of th...
[ "def", "flatten", "(", "d", ",", "parent_key", "=", "''", ",", "separator", "=", "'__'", ")", ":", "items", "=", "[", "]", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "new_key", "=", "parent_key", "+", "separator", "+", "k", "...
27.8125
19.5
def record_absent(name, zone, type, data, profile): ''' Ensures a record is absent. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argu...
[ "def", "record_absent", "(", "name", ",", "zone", ",", "type", ",", "data", ",", "profile", ")", ":", "zones", "=", "__salt__", "[", "'libcloud_dns.list_zones'", "]", "(", "profile", ")", "try", ":", "matching_zone", "=", "[", "z", "for", "z", "in", "z...
37.547619
22.309524
def make_signature(params, hmac_key): """ Calculate a HMAC-SHA-1 (using hmac_key) of all the params except "h=". Returns base64 encoded signature as string. """ # produce a list of "key=value" for all entries in params except `h' pairs = [x + "=" + ''.join(params[x]) for x in sorted(params.keys...
[ "def", "make_signature", "(", "params", ",", "hmac_key", ")", ":", "# produce a list of \"key=value\" for all entries in params except `h'", "pairs", "=", "[", "x", "+", "\"=\"", "+", "''", ".", "join", "(", "params", "[", "x", "]", ")", "for", "x", "in", "sor...
42.9
18.1
def iter_memory_snapshot(self, minAddr = None, maxAddr = None): """ Returns an iterator that allows you to go through the memory contents of a process. It's basically the same as the L{take_memory_snapshot} method, but it takes the snapshot of each memory region as it goes, as o...
[ "def", "iter_memory_snapshot", "(", "self", ",", "minAddr", "=", "None", ",", "maxAddr", "=", "None", ")", ":", "# One may feel tempted to include calls to self.suspend() and", "# self.resume() here, but that wouldn't work on a dead process.", "# It also wouldn't be needed when debug...
40.271739
23.228261
def handle_ignored_message( self, state_scope, msgid, line, node, args, confidence ): # pylint: disable=unused-argument """Report an ignored message. state_scope is either MSG_STATE_SCOPE_MODULE or MSG_STATE_SCOPE_CONFIG, depending on whether the message was disabled locally in the...
[ "def", "handle_ignored_message", "(", "self", ",", "state_scope", ",", "msgid", ",", "line", ",", "node", ",", "args", ",", "confidence", ")", ":", "# pylint: disable=unused-argument", "if", "state_scope", "==", "MSG_STATE_SCOPE_MODULE", ":", "try", ":", "orig_lin...
43.4
20.066667
def find_packages(): """Walk source directory tree and convert each sub directory to a package name. """ packages = ['pyctools'] for root, dirs, files in os.walk(os.path.join('src', 'pyctools')): package = '.'.join(root.split(os.sep)[1:]) for name in dirs: packages.appen...
[ "def", "find_packages", "(", ")", ":", "packages", "=", "[", "'pyctools'", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "os", ".", "path", ".", "join", "(", "'src'", ",", "'pyctools'", ")", ")", ":", "package", "=", ...
32.090909
16.454545
def fill_window(self, seqNum): """This function sends all of the packets necessary to fill out the segmentation window.""" if _debug: SSM._debug("fill_window %r", seqNum) if _debug: SSM._debug(" - actualWindowSize: %r", self.actualWindowSize) for ix in range(self.actualWindow...
[ "def", "fill_window", "(", "self", ",", "seqNum", ")", ":", "if", "_debug", ":", "SSM", ".", "_debug", "(", "\"fill_window %r\"", ",", "seqNum", ")", "if", "_debug", ":", "SSM", ".", "_debug", "(", "\" - actualWindowSize: %r\"", ",", "self", ".", "actua...
35.625
15.375
def srem_if_not_exists(self, key, member, other_key, client=None): """ Removes ``member`` from the set ``key`` if ``other_key`` does not exist (i.e. is empty). Returns the number of removed elements (0 or 1). """ return self._srem_if_not_exists( keys=[key, other_key],...
[ "def", "srem_if_not_exists", "(", "self", ",", "key", ",", "member", ",", "other_key", ",", "client", "=", "None", ")", ":", "return", "self", ".", "_srem_if_not_exists", "(", "keys", "=", "[", "key", ",", "other_key", "]", ",", "args", "=", "[", "memb...
40.666667
14.666667
def parse(self, rrstr): # type: (bytes) -> None ''' Parse a Rock Ridge Sharing Protocol record out of a string. Parameters: rrstr - The string to parse the record out of. Returns: Nothing. ''' if self._initialized: raise pycdlibexcep...
[ "def", "parse", "(", "self", ",", "rrstr", ")", ":", "# type: (bytes) -> None", "if", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'SP record already initialized!'", ")", "(", "su_len", ",", "su_entry_version_unused...
37.36
27.92
def _submit_calcs_on_client(calcs, client, func): """Submit calculations via dask.bag and a distributed client""" logging.info('Connected to client: {}'.format(client)) if LooseVersion(dask.__version__) < '0.18': dask_option_setter = dask.set_options else: dask_option_setter = dask.confi...
[ "def", "_submit_calcs_on_client", "(", "calcs", ",", "client", ",", "func", ")", ":", "logging", ".", "info", "(", "'Connected to client: {}'", ".", "format", "(", "client", ")", ")", "if", "LooseVersion", "(", "dask", ".", "__version__", ")", "<", "'0.18'",...
46.777778
10.666667
def list_topic_rules(topic=None, ruleDisabled=None, region=None, key=None, keyid=None, profile=None): ''' List all rules (for a given topic, if specified) Returns list of rules CLI Example: .. code-block:: bash salt myminion boto_iot.list_topic_rules Example Return: ...
[ "def", "list_topic_rules", "(", "topic", "=", "None", ",", "ruleDisabled", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", ...
27.55
21.6
def attributes(self): """ A dictionary mapping names of attributes to BiomartAttribute instances. This causes overwriting errors if there are diffferent pages which use the same attribute names, but is kept for backward compatibility. """ if not self._attribute_pages: ...
[ "def", "attributes", "(", "self", ")", ":", "if", "not", "self", ".", "_attribute_pages", ":", "self", ".", "fetch_attributes", "(", ")", "result", "=", "{", "}", "for", "page", "in", "self", ".", "_attribute_pages", ".", "values", "(", ")", ":", "resu...
36.769231
17.692308
def clear_doc(self, docname): """Remove the data associated with this instance of the domain.""" for fullname, (fn, x) in self.data['objects'].items(): if fn == docname: del self.data['objects'][fullname] for modname, (fn, x, x, x) in self.data['modules'].items(): ...
[ "def", "clear_doc", "(", "self", ",", "docname", ")", ":", "for", "fullname", ",", "(", "fn", ",", "x", ")", "in", "self", ".", "data", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "fn", "==", "docname", ":", "del", "self", ".", "d...
49.285714
14.714286
def _Main(self): """The main loop.""" self._StartProfiling(self._processing_configuration.profiling) if self._serializers_profiler: self._storage_writer.SetSerializersProfiler(self._serializers_profiler) if self._storage_profiler: self._storage_writer.SetStorageProfiler(self._storage_profi...
[ "def", "_Main", "(", "self", ")", ":", "self", ".", "_StartProfiling", "(", "self", ".", "_processing_configuration", ".", "profiling", ")", "if", "self", ".", "_serializers_profiler", ":", "self", ".", "_storage_writer", ".", "SetSerializersProfiler", "(", "sel...
30.171875
24.453125
def fit_transform(self, X, y=None): """Fit OneHotEncoder to X, then transform X. Equivalent to self.fit(X).transform(X), but more convenient and more efficient. See fit for the parameters, transform for the return value. Parameters ---------- X : array-like or sparse ma...
[ "def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "if", "self", ".", "categorical_features", "==", "\"auto\"", ":", "self", ".", "categorical_features", "=", "auto_select_categorical_features", "(", "X", ",", "threshold", "=", "...
35.272727
20.954545
def show_keyword_help(cur, arg): """ Call the built-in "show <command>", to display help for an SQL keyword. :param cur: cursor :param arg: string :return: list """ keyword = arg.strip('"').strip("'") query = "help '{0}'".format(keyword) log.debug(query) cur.execute(query) if...
[ "def", "show_keyword_help", "(", "cur", ",", "arg", ")", ":", "keyword", "=", "arg", ".", "strip", "(", "'\"'", ")", ".", "strip", "(", "\"'\"", ")", "query", "=", "\"help '{0}'\"", ".", "format", "(", "keyword", ")", "log", ".", "debug", "(", "query...
33.375
14.625
def write_rec(table_name, objid, data, index_name_values): """Write (upsert) a record using a tran.""" with DatastoreTransaction() as tx: entity = tx.get_upsert() entity.key.CopyFrom(make_key(table_name, objid)) prop = entity.property.add() prop.name = 'id' prop.value.s...
[ "def", "write_rec", "(", "table_name", ",", "objid", ",", "data", ",", "index_name_values", ")", ":", "with", "DatastoreTransaction", "(", ")", "as", "tx", ":", "entity", "=", "tx", ".", "get_upsert", "(", ")", "entity", ".", "key", ".", "CopyFrom", "(",...
30.947368
13.947368
def coalesce_headers(cls, header_lines): """Collects headers that are spread across multiple lines into a single row""" header_lines = [list(hl) for hl in header_lines if bool(hl)] if len(header_lines) == 0: return [] if len(header_lines) == 1: return header_li...
[ "def", "coalesce_headers", "(", "cls", ",", "header_lines", ")", ":", "header_lines", "=", "[", "list", "(", "hl", ")", "for", "hl", "in", "header_lines", "if", "bool", "(", "hl", ")", "]", "if", "len", "(", "header_lines", ")", "==", "0", ":", "retu...
32.535714
20.107143
def clear(cls): """ Clear all configuration properties from in-memory cache, but do NOT alter the custom configuration file. Used in unit-testing. """ # Clear the in-memory settings cache, forcing reload upon subsequent "get" # request. super(Configuration, cls).clear() # Reset in-memory cu...
[ "def", "clear", "(", "cls", ")", ":", "# Clear the in-memory settings cache, forcing reload upon subsequent \"get\"", "# request.", "super", "(", "Configuration", ",", "cls", ")", ".", "clear", "(", ")", "# Reset in-memory custom configuration info.", "_CustomConfigurationFileW...
39.5
18.1
def add_router_references(self, snet, address, dnets): """Add/update references to routers.""" if _debug: NetworkServiceAccessPoint._debug("add_router_references %r %r %r", snet, address, dnets) # see if we have an adapter for the snet if snet not in self.adapters: raise Run...
[ "def", "add_router_references", "(", "self", ",", "snet", ",", "address", ",", "dnets", ")", ":", "if", "_debug", ":", "NetworkServiceAccessPoint", ".", "_debug", "(", "\"add_router_references %r %r %r\"", ",", "snet", ",", "address", ",", "dnets", ")", "# see i...
47.2
23.5
def require_active_forms(self): """Rewrites Statements with Agents' active forms in active positions. As an example, the enzyme in a Modification Statement can be expected to be in an active state. Similarly, subjects of RegulateAmount and RegulateActivity Statements can be expected to ...
[ "def", "require_active_forms", "(", "self", ")", ":", "logger", ".", "info", "(", "'Setting required active forms on %d statements...'", "%", "len", "(", "self", ".", "statements", ")", ")", "new_stmts", "=", "[", "]", "for", "stmt", "in", "self", ".", "statem...
44.464286
15.071429
def attach_vpngw(self, req, id, driver): """Attach network to VPN gateway :Param req :Type object Request """ vpngw = driver.get_vnpgw(req.params, id) if vpngw is None: vpngw = driver.create_vpngw(req.params, id) response = driver.attach_vpngw(req.p...
[ "def", "attach_vpngw", "(", "self", ",", "req", ",", "id", ",", "driver", ")", ":", "vpngw", "=", "driver", ".", "get_vnpgw", "(", "req", ".", "params", ",", "id", ")", "if", "vpngw", "is", "None", ":", "vpngw", "=", "driver", ".", "create_vpngw", ...
31.941176
12.235294
def getFileSystemSize(dirPath): """ Return the free space, and total size of the file system hosting `dirPath`. :param str dirPath: A valid path to a directory. :return: free space and total size of file system :rtype: tuple """ assert os.path.exists(dirPath) diskStats = os.statvfs(dirP...
[ "def", "getFileSystemSize", "(", "dirPath", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "dirPath", ")", "diskStats", "=", "os", ".", "statvfs", "(", "dirPath", ")", "freeSpace", "=", "diskStats", ".", "f_frsize", "*", "diskStats", ".", "f_...
34.923077
14.307692
def import_submodules(context, root_module, path): """ Import all submodules and register them in the ``context`` namespace. >>> import_submodules(locals(), __name__, __path__) """ for _, module_name, _ in pkgutil.walk_packages(path, root_module + '.'): # this causes a Runtime error with mo...
[ "def", "import_submodules", "(", "context", ",", "root_module", ",", "path", ")", ":", "for", "_", ",", "module_name", ",", "_", "in", "pkgutil", ".", "walk_packages", "(", "path", ",", "root_module", "+", "'.'", ")", ":", "# this causes a Runtime error with m...
44.357143
17.071429
def dnld_assc(assc_name, go2obj=None, prt=sys.stdout): """Download association from http://geneontology.org/gene-associations.""" # Example assc_name: "tair.gaf" # Download the Association dirloc, assc_base = os.path.split(assc_name) if not dirloc: dirloc = os.getcwd() assc_locfile = os....
[ "def", "dnld_assc", "(", "assc_name", ",", "go2obj", "=", "None", ",", "prt", "=", "sys", ".", "stdout", ")", ":", "# Example assc_name: \"tair.gaf\"", "# Download the Association", "dirloc", ",", "assc_base", "=", "os", ".", "path", ".", "split", "(", "assc_n...
40.157895
13.526316
def submit(self, stanza): """Adds keys to the current configuration stanza as a dictionary of key-value pairs. :param stanza: A dictionary of key-value pairs for the stanza. :type stanza: ``dict`` :return: The :class:`Stanza` object. """ body = _encode(**stanza) ...
[ "def", "submit", "(", "self", ",", "stanza", ")", ":", "body", "=", "_encode", "(", "*", "*", "stanza", ")", "self", ".", "service", ".", "post", "(", "self", ".", "path", ",", "body", "=", "body", ")", "return", "self" ]
34.272727
12.454545
def _ows_check_generic_interfaces(configs, required_interfaces): """Check the complete contexts to determine the workload status. - Checks for missing or incomplete contexts - juju log details of missing required data. - determines the correct workload status - creates an appropriate message fo...
[ "def", "_ows_check_generic_interfaces", "(", "configs", ",", "required_interfaces", ")", ":", "incomplete_rel_data", "=", "incomplete_relation_data", "(", "configs", ",", "required_interfaces", ")", "state", "=", "None", "message", "=", "None", "missing_relations", "=",...
45.35
19.7125
def _fetch(url,): """ *Retrieve an HTML document or file from the web at a given URL* **Key Arguments:** - ``url`` -- the URL of the document or file **Return:** - ``url`` -- the URL of the document or file, or None if an error occured - ``body`` -- the text content of the HTML docum...
[ "def", "_fetch", "(", "url", ",", ")", ":", "import", "logging", "as", "log", "import", "socket", "from", "eventlet", "import", "Timeout", "from", "eventlet", ".", "green", "import", "urllib2", "import", "sys", "# TRY AND DOWNLOAD X TIMES BEFORE QUITING", "tries",...
31.25
18.613636
def reset(self): """Resets the state of the environment and returns an initial observation. In the case of multi-agent environments, this is a list. Returns: observation (object/list): the initial observation of the space. """ info = self._env.reset()[self.brain_name]...
[ "def", "reset", "(", "self", ")", ":", "info", "=", "self", ".", "_env", ".", "reset", "(", ")", "[", "self", ".", "brain_name", "]", "n_agents", "=", "len", "(", "info", ".", "agents", ")", "self", ".", "_check_agents", "(", "n_agents", ")", "self...
37.4375
16.875
def draw_vr_anaglyph(cube_fbo, vr_scene, active_scene, eye_poses=(.035, -.035)): """ Experimental anaglyph drawing function for VR system with red/blue glasses, used in Sirota lab. Draws a virtual scene in red and blue, from subject's (heda trackers) perspective in active scene. Note: assumes shader us...
[ "def", "draw_vr_anaglyph", "(", "cube_fbo", ",", "vr_scene", ",", "active_scene", ",", "eye_poses", "=", "(", ".035", ",", "-", ".035", ")", ")", ":", "color_masks", "=", "[", "(", "True", ",", "False", ",", "False", ",", "True", ")", ",", "(", "Fals...
38.642857
23.071429
def _jwt_required(realm): """Does the actual work of verifying the JWT data in the current request. This is done automatically for you by `jwt_required()` but you could call it manually. Doing so would be useful in the context of optional JWT access in your APIs. :param realm: an optional realm """...
[ "def", "_jwt_required", "(", "realm", ")", ":", "token", "=", "_jwt", ".", "request_callback", "(", ")", "if", "token", "is", "None", ":", "raise", "JWTError", "(", "'Authorization Required'", ",", "'Request does not contain an access token'", ",", "headers", "=",...
38.818182
25.363636
def currentRecord( self ): """ Returns the current record from this browser. :return <orb.Table> || None """ if ( self.currentMode() == XOrbBrowserWidget.Mode.Detail ): return self.detailWidget().currentRecord() elif ( self.curre...
[ "def", "currentRecord", "(", "self", ")", ":", "if", "(", "self", ".", "currentMode", "(", ")", "==", "XOrbBrowserWidget", ".", "Mode", ".", "Detail", ")", ":", "return", "self", ".", "detailWidget", "(", ")", ".", "currentRecord", "(", ")", "elif", "(...
36.318182
16.681818
def configure(self, app): ''' Load configuration from application configuration. For each storage, the configuration is loaded with the following pattern:: FS_{BACKEND_NAME}_{KEY} then {STORAGE_NAME}_FS_{KEY} If no configuration is set for a given key, global c...
[ "def", "configure", "(", "self", ",", "app", ")", ":", "config", "=", "Config", "(", ")", "prefix", "=", "PREFIX", ".", "format", "(", "self", ".", "name", ".", "upper", "(", ")", ")", "backend_key", "=", "'{0}BACKEND'", ".", "format", "(", "prefix",...
40.769231
23.897436
def userinfo(self, access_token): """Returns the user information based on the Auth0 access token. This endpoint will work only if openid was granted as a scope for the access_token. Args: access_token (str): Auth0 access token (obtained during login). Returns: ...
[ "def", "userinfo", "(", "self", ",", "access_token", ")", ":", "return", "self", ".", "get", "(", "url", "=", "'https://{}/userinfo'", ".", "format", "(", "self", ".", "domain", ")", ",", "headers", "=", "{", "'Authorization'", ":", "'Bearer {}'", ".", "...
31.375
25.6875
def get_organization_from_ckan(portal_url, org_id): """Toma la url de un portal y un id, y devuelve la organización a buscar. Args: portal_url (str): La URL del portal CKAN de origen. org_id (str): El id de la organización a buscar. Returns: d...
[ "def", "get_organization_from_ckan", "(", "portal_url", ",", "org_id", ")", ":", "ckan_portal", "=", "RemoteCKAN", "(", "portal_url", ")", "return", "ckan_portal", ".", "call_action", "(", "'organization_show'", ",", "data_dict", "=", "{", "'id'", ":", "org_id", ...
44.5
17.666667
def get_dict_to_print(field_to_obs): """Transform the field-to-obs mapping into a printable dictionary. Args: field_to_obs: Dict that maps string field to `Observation` list. Returns: A dict with the keys and values to print to console. """ def compressed_steps(steps): return {'num_steps': len(...
[ "def", "get_dict_to_print", "(", "field_to_obs", ")", ":", "def", "compressed_steps", "(", "steps", ")", ":", "return", "{", "'num_steps'", ":", "len", "(", "set", "(", "steps", ")", ")", ",", "'min_step'", ":", "min", "(", "steps", ")", ",", "'max_step'...
27.676471
18.764706
def pythonize(self, val): """Convert value into a dict:: * If value is a list, try to take the last element * split "key=value" string and convert to { key:value } :param val: value to convert :type val: :return: log level corresponding to value :rtype: str ...
[ "def", "pythonize", "(", "self", ",", "val", ")", ":", "val", "=", "unique_value", "(", "val", ")", "def", "split", "(", "keyval", ")", ":", "\"\"\"Split key-value string into (key,value)\n\n :param keyval: key value string\n :return: key, value\n ...
30.925
19.775
def declare_key_flag(flag_name, flag_values=_flagvalues.FLAGS): """Declares one flag as key to the current module. Key flags are flags that are deemed really important for a module. They are important when listing help messages; e.g., if the --helpshort command-line flag is used, then only the key flags of the...
[ "def", "declare_key_flag", "(", "flag_name", ",", "flag_values", "=", "_flagvalues", ".", "FLAGS", ")", ":", "if", "flag_name", "in", "_helpers", ".", "SPECIAL_FLAGS", ":", "# Take care of the special flags, e.g., --flagfile, --undefok.", "# These flags are defined in SPECIAL...
40.763158
24.578947
def debugrequest(self, event): """Handler for client-side debug requests""" try: self.log("Event: ", event.__dict__, lvl=critical) if event.data == "storejson": self.log("Storing received object to /tmp", lvl=critical) fp = open('/tmp/hfosdebugger...
[ "def", "debugrequest", "(", "self", ",", "event", ")", ":", "try", ":", "self", ".", "log", "(", "\"Event: \"", ",", "event", ".", "__dict__", ",", "lvl", "=", "critical", ")", "if", "event", ".", "data", "==", "\"storejson\"", ":", "self", ".", "log...
43.761905
17.380952
def list(self, from_=values.unset, to=values.unset, date_created_on_or_before=values.unset, date_created_after=values.unset, limit=None, page_size=None): """ Lists FaxInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit`...
[ "def", "list", "(", "self", ",", "from_", "=", "values", ".", "unset", ",", "to", "=", "values", ".", "unset", ",", "date_created_on_or_before", "=", "values", ".", "unset", ",", "date_created_after", "=", "values", ".", "unset", ",", "limit", "=", "None...
54.066667
28.533333
def _from_python(self, value): """ Converts python values to a form suitable for insertion into the xml we send to solr. """ if hasattr(value, 'strftime'): if hasattr(value, 'hour'): offset = value.utcoffset() if offset: ...
[ "def", "_from_python", "(", "self", ",", "value", ")", ":", "if", "hasattr", "(", "value", ",", "'strftime'", ")", ":", "if", "hasattr", "(", "value", ",", "'hour'", ")", ":", "offset", "=", "value", ".", "utcoffset", "(", ")", "if", "offset", ":", ...
33.322581
14.935484
def filter_report(self, filt=None, analytes=None, savedir=None, nbin=5): """ Visualise effect of data filters. Parameters ---------- filt : str Exact or partial name of filter to plot. Supports partial matching. i.e. if 'cluster' is specified, all ...
[ "def", "filter_report", "(", "self", ",", "filt", "=", "None", ",", "analytes", "=", "None", ",", "savedir", "=", "None", ",", "nbin", "=", "5", ")", ":", "return", "plot", ".", "filter_report", "(", "self", ",", "filt", ",", "analytes", ",", "savedi...
30.761905
19.047619
def write(self, nb, fp, **kwargs): """Write a notebook to a file like object""" nbs = self.writes(nb,**kwargs) if not py3compat.PY3 and not isinstance(nbs, unicode): # this branch is likely only taken for JSON on Python 2 nbs = py3compat.str_to_unicode(nbs) return...
[ "def", "write", "(", "self", ",", "nb", ",", "fp", ",", "*", "*", "kwargs", ")", ":", "nbs", "=", "self", ".", "writes", "(", "nb", ",", "*", "*", "kwargs", ")", "if", "not", "py3compat", ".", "PY3", "and", "not", "isinstance", "(", "nbs", ",",...
46.857143
10.857143
def rgba_bytes_tuple(self, x): """Provides the color corresponding to value `x` in the form of a tuple (R,G,B,A) with int values between 0 and 255. """ return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))
[ "def", "rgba_bytes_tuple", "(", "self", ",", "x", ")", ":", "return", "tuple", "(", "int", "(", "u", "*", "255.9999", ")", "for", "u", "in", "self", ".", "rgba_floats_tuple", "(", "x", ")", ")" ]
48.8
14
def _definition_from_example(example): """Generates a swagger definition json from a given example Works only for simple types in the dict Args: example: The example for which we want a definition Type is DICT Returns: A dict that is the ...
[ "def", "_definition_from_example", "(", "example", ")", ":", "assert", "isinstance", "(", "example", ",", "dict", ")", "def", "_has_simple_type", "(", "value", ")", ":", "accepted", "=", "(", "str", ",", "int", ",", "float", ",", "bool", ")", "return", "...
34.315789
14.736842
def build_from_generator(cls, generator, target_size, max_subtoken_length=None, reserved_tokens=None): """Builds a SubwordTextEncoder from the generated text. Args: generator: yields text. ta...
[ "def", "build_from_generator", "(", "cls", ",", "generator", ",", "target_size", ",", "max_subtoken_length", "=", "None", ",", "reserved_tokens", "=", "None", ")", ":", "token_counts", "=", "collections", ".", "defaultdict", "(", "int", ")", "for", "item", "in...
42.866667
17.466667
def min_max_temp(temp: str, unit: str = 'C') -> str: """ Format the Min and Max temp elemets into a readable string Ex: Maximum temperature of 23°C (73°F) at 18-15:00Z """ if not temp or len(temp) < 7: return '' if temp[:2] == 'TX': temp_type = 'Maximum' elif temp[:2] == 'TN...
[ "def", "min_max_temp", "(", "temp", ":", "str", ",", "unit", ":", "str", "=", "'C'", ")", "->", "str", ":", "if", "not", "temp", "or", "len", "(", "temp", ")", "<", "7", ":", "return", "''", "if", "temp", "[", ":", "2", "]", "==", "'TX'", ":"...
35.157895
18.842105
def proc_line_coordinate(self, line): """Extracts data from columns in ATOM/HETATM record.""" pdb_atom_col_dict = global_settings['ampal']['pdb_atom_col_dict'] at_type = line[0:6].strip() # 0 at_ser = int(line[6:11].strip()) # 1 at_name = line[12:16].strip() # 2 alt_lo...
[ "def", "proc_line_coordinate", "(", "self", ",", "line", ")", ":", "pdb_atom_col_dict", "=", "global_settings", "[", "'ampal'", "]", "[", "'pdb_atom_col_dict'", "]", "at_type", "=", "line", "[", "0", ":", "6", "]", ".", "strip", "(", ")", "# 0", "at_ser", ...
49.28
9.32
def read_plain_double(file_obj, count): """Read `count` 64-bit float (double) using the plain encoding.""" return struct.unpack("<{}d".format(count).encode("utf-8"), file_obj.read(8 * count))
[ "def", "read_plain_double", "(", "file_obj", ",", "count", ")", ":", "return", "struct", ".", "unpack", "(", "\"<{}d\"", ".", "format", "(", "count", ")", ".", "encode", "(", "\"utf-8\"", ")", ",", "file_obj", ".", "read", "(", "8", "*", "count", ")", ...
65.666667
16.333333
def split_lists(d, split_keys, new_name='split', check_length=True, deepcopy=True): """split_lists key:list pairs into dicts for each item in the lists NB: will only split if all split_keys are present Parameters ---------- d : dict split_keys : list keys to split ne...
[ "def", "split_lists", "(", "d", ",", "split_keys", ",", "new_name", "=", "'split'", ",", "check_length", "=", "True", ",", "deepcopy", "=", "True", ")", ":", "# noqa: E501", "flattened", "=", "flatten2d", "(", "d", ")", "new_d", "=", "{", "}", "for", "...
34.385542
19.421687
def checkForDuplicateInputs(rootnames): """ Check input files specified in ASN table for duplicate versions with multiple valid suffixes (_flt and _flc, for example). """ flist = [] duplist = [] for fname in rootnames: # Look for any recognized CTE-corrected products f1 = f...
[ "def", "checkForDuplicateInputs", "(", "rootnames", ")", ":", "flist", "=", "[", "]", "duplist", "=", "[", "]", "for", "fname", "in", "rootnames", ":", "# Look for any recognized CTE-corrected products", "f1", "=", "fileutil", ".", "buildRootname", "(", "fname", ...
30.473684
17.736842
def save_cloud_optimized(self, dest_url, resampling=Resampling.gauss, blocksize=256, overview_blocksize=256, creation_options=None): """Save as Cloud Optimized GeoTiff object to a new file. :param dest_url: path to the new raster :param resampling: which Resampling ...
[ "def", "save_cloud_optimized", "(", "self", ",", "dest_url", ",", "resampling", "=", "Resampling", ".", "gauss", ",", "blocksize", "=", "256", ",", "overview_blocksize", "=", "256", ",", "creation_options", "=", "None", ")", ":", "src", "=", "self", "# GeoRa...
53.818182
30.227273
def initialize_means_weights(data, clusters, init_means=None, init_weights=None, initialization='tsvd', max_assign_weight=0.75): """ Generates initial means and weights for state estimation. """ genes, cells = data.shape if init_means is None: if init_weights is not None: if len(...
[ "def", "initialize_means_weights", "(", "data", ",", "clusters", ",", "init_means", "=", "None", ",", "init_weights", "=", "None", ",", "initialization", "=", "'tsvd'", ",", "max_assign_weight", "=", "0.75", ")", ":", "genes", ",", "cells", "=", "data", ".",...
48.216216
16.783784
def ng_call_ctrl_function(self, element, func, params='', return_out=False): """ :Description: Will execute controller function with provided parameters. :Warning: This will only work for angular.js 1.x. :Warning: Requires angular debugging to be enabled. :param element: Element ...
[ "def", "ng_call_ctrl_function", "(", "self", ",", "element", ",", "func", ",", "params", "=", "''", ",", "return_out", "=", "False", ")", ":", "if", "isinstance", "(", "params", ",", "string_types", ")", ":", "param_str", "=", "params", "elif", "isinstance...
50.56
21.52
def export_mv_grid_new(self, session, mv_grid_districts): """ Exports MV grids to database for visualization purposes Parameters ---------- session : sqlalchemy.orm.session.Session Database session mv_grid_districts : List of MV grid_districts (instances of MVGridDis...
[ "def", "export_mv_grid_new", "(", "self", ",", "session", ",", "mv_grid_districts", ")", ":", "# check arguments", "if", "not", "all", "(", "isinstance", "(", "_", ",", "int", ")", "for", "_", "in", "mv_grid_districts", ")", ":", "raise", "TypeError", "(", ...
47.577236
22.813008
def get_ctm(self): """Copies the scaled font’s font current transform matrix. Note that the translation offsets ``(x0, y0)`` of the CTM are ignored by :class:`ScaledFont`. So, the matrix this method returns always has 0 as ``x0`` and ``y0``. :returns: A new :class:`Matrix` obje...
[ "def", "get_ctm", "(", "self", ")", ":", "matrix", "=", "Matrix", "(", ")", "cairo", ".", "cairo_scaled_font_get_ctm", "(", "self", ".", "_pointer", ",", "matrix", ".", "_pointer", ")", "self", ".", "_check_status", "(", ")", "return", "matrix" ]
33.714286
20.785714
def tauV(T): """ gets the eigenvalues (tau) and eigenvectors (V) from matrix T """ t,V,tr=[],[],0. ind1,ind2,ind3=0,1,2 evalues,evectmps=numpy.linalg.eig(T) evectors=numpy.transpose(evectmps) # to make compatible with Numeric convention for tau in evalues: tr += tau # tr ...
[ "def", "tauV", "(", "T", ")", ":", "t", ",", "V", ",", "tr", "=", "[", "]", ",", "[", "]", ",", "0.", "ind1", ",", "ind2", ",", "ind3", "=", "0", ",", "1", ",", "2", "evalues", ",", "evectmps", "=", "numpy", ".", "linalg", ".", "eig", "("...
31.34375
17.59375
def createElement(self, token): """Create an element but don't insert it anywhere""" name = token["name"] namespace = token.get("namespace", self.defaultNamespace) element = self.elementClass(name, namespace) element.attributes = token["data"] return element
[ "def", "createElement", "(", "self", ",", "token", ")", ":", "name", "=", "token", "[", "\"name\"", "]", "namespace", "=", "token", ".", "get", "(", "\"namespace\"", ",", "self", ".", "defaultNamespace", ")", "element", "=", "self", ".", "elementClass", ...
42.857143
11.142857
def _frozensetload(l: Loader, value, type_) -> FrozenSet: """ This loads into something like FrozenSet[int] """ t = type_.__args__[0] return frozenset(l.load(i, t) for i in value)
[ "def", "_frozensetload", "(", "l", ":", "Loader", ",", "value", ",", "type_", ")", "->", "FrozenSet", ":", "t", "=", "type_", ".", "__args__", "[", "0", "]", "return", "frozenset", "(", "l", ".", "load", "(", "i", ",", "t", ")", "for", "i", "in",...
32.333333
8.333333
def createAssetFromURL(self, url, async=False, metadata=None, callback=None): """Users the passed URL to load data. If async=false a json with the result is returned otherwise a json with an asset_id is returned. :param url: :param metadata: arbitrary additional description information for the asset :p...
[ "def", "createAssetFromURL", "(", "self", ",", "url", ",", "async", "=", "False", ",", "metadata", "=", "None", ",", "callback", "=", "None", ")", ":", "audio", "=", "{", "'uri'", ":", "url", "}", "config", "=", "{", "'async'", ":", "async", "}", "...
39.35
22.2
def translate_window_with_sizehint(self, window, width, height): """ Apply a window's sizing hints (if any) to a given width and height. This function wraps XGetWMNormalHints() and applies any resize increment and base size to your given width and height values. :param window: ...
[ "def", "translate_window_with_sizehint", "(", "self", ",", "window", ",", "width", ",", "height", ")", ":", "width_ret", "=", "ctypes", ".", "c_uint", "(", "0", ")", "height_ret", "=", "ctypes", ".", "c_uint", "(", "0", ")", "_libxdo", ".", "xdo_translate_...
41.105263
14.894737
def generate_null_snvs(df, snvs, num_null_sets=5): """ Generate a set of null SNVs based on an input list of SNVs and categorical annotations. Parameters ---------- df : pandas.DataFrame Pandas dataframe where each column is a categorization of SNPs. The index should be SN...
[ "def", "generate_null_snvs", "(", "df", ",", "snvs", ",", "num_null_sets", "=", "5", ")", ":", "import", "numpy", "as", "np", "import", "random", "random", ".", "seed", "(", "20151007", ")", "input_snvs", "=", "list", "(", "set", "(", "df", ".", "index...
37.939759
16.228916
async def grant(self, user_id, *permissions): " 给用户(user_id)授于权限(permission) " prefix = f"{self._prefix_perm}/{user_id}/" perm_names = [str(p) for p in permissions] checkings = [ KV.put.txn(prefix + p, b'\0', prev_kv=True) for p in perm_names ] succe...
[ "async", "def", "grant", "(", "self", ",", "user_id", ",", "*", "permissions", ")", ":", "prefix", "=", "f\"{self._prefix_perm}/{user_id}/\"", "perm_names", "=", "[", "str", "(", "p", ")", "for", "p", "in", "permissions", "]", "checkings", "=", "[", "KV", ...
39.208333
19.458333
def getHeader(filename, handle=None): """ Return a copy of the PRIMARY header, along with any group/extension header for this filename specification. """ _fname, _extn = parseFilename(filename) # Allow the user to provide an already opened PyFITS object # to derive the header from... # ...
[ "def", "getHeader", "(", "filename", ",", "handle", "=", "None", ")", ":", "_fname", ",", "_extn", "=", "parseFilename", "(", "filename", ")", "# Allow the user to provide an already opened PyFITS object", "# to derive the header from...", "#", "if", "not", "handle", ...
33.05
18.6
def is_driver(self): """Check whether the file is a Windows driver. This will return true only if there are reliable indicators of the image being a driver. """ # Checking that the ImageBase field of the OptionalHeader is above or # equal to 0x80000000 (that is, whether...
[ "def", "is_driver", "(", "self", ")", ":", "# Checking that the ImageBase field of the OptionalHeader is above or", "# equal to 0x80000000 (that is, whether it lies in the upper 2GB of", "# the address space, normally belonging to the kernel) is not a", "# reliable enough indicator. For instance,...
41.745098
24.392157
def scansum(self,seq,threshold = -1000): """ m.scansum(seq,threshold = -1000) -- Sum of scores over every window in the sequence. Returns total, number of matches above threshold, average score, sum of exp(score) """ ll = self.ll sum =...
[ "def", "scansum", "(", "self", ",", "seq", ",", "threshold", "=", "-", "1000", ")", ":", "ll", "=", "self", ".", "ll", "sum", "=", "0", "width", "=", "self", ".", "width", "width_r", "=", "range", "(", "width", ")", "width_rcr", "=", "range", "("...
36.515152
15.181818
async def start(self): """Start process execution.""" # arguments passed to the Docker command command_args = { 'command': self.command, 'container_image': self.requirements.get('image', constants.DEFAULT_CONTAINER_IMAGE), } # Get limit defaults. ...
[ "async", "def", "start", "(", "self", ")", ":", "# arguments passed to the Docker command", "command_args", "=", "{", "'command'", ":", "self", ".", "command", ",", "'container_image'", ":", "self", ".", "requirements", ".", "get", "(", "'image'", ",", "constant...
42.927711
26.056225
def read_mm_header(fh, byteorder, dtype, count, offsetsize): """Read FluoView mm_header tag from file and return as dict.""" mmh = fh.read_record(TIFF.MM_HEADER, byteorder=byteorder) mmh = recarray2dict(mmh) mmh['Dimensions'] = [ (bytes2str(d[0]).strip(), d[1], d[2], d[3], bytes2str(d[4]).strip(...
[ "def", "read_mm_header", "(", "fh", ",", "byteorder", ",", "dtype", ",", "count", ",", "offsetsize", ")", ":", "mmh", "=", "fh", ".", "read_record", "(", "TIFF", ".", "MM_HEADER", ",", "byteorder", "=", "byteorder", ")", "mmh", "=", "recarray2dict", "(",...
44.818182
18
def _create_significance_table(self,data): """ Create a table containing p-values for significance tests. Add features of the distributions and the p-values to the dataframe. Parameters ---------- data : pandas DataFrame The input dataset. Re...
[ "def", "_create_significance_table", "(", "self", ",", "data", ")", ":", "# list features of the variable e.g. matched, paired, n_expected", "df", "=", "pd", ".", "DataFrame", "(", "index", "=", "self", ".", "_continuous", "+", "self", ".", "_categorical", ",", "col...
42.381818
22.018182
def load_data(self, data, **kwargs): """ Bulk adds rdf data to the class args: data: the data to be loaded kwargs: strip_orphans: True or False - remove triples that have an orphan blanknode as the object obj_method: "list"...
[ "def", "load_data", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__set_map__", "(", "*", "*", "kwargs", ")", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "log", ".", "debug", "(", "\"Dataload stated\"...
37.555556
15.407407
def sample_wr(population, k): "Chooses k random elements (with replacement) from a population" n = len(population) _random, _int = random.random, int # speed hack result = [None] * k for i in xrange(k): j = _int(_random() * n) result[i] = population[j] return result
[ "def", "sample_wr", "(", "population", ",", "k", ")", ":", "n", "=", "len", "(", "population", ")", "_random", ",", "_int", "=", "random", ".", "random", ",", "int", "# speed hack \r", "result", "=", "[", "None", "]", "*", "k", "for", "i", "in", "x...
34.222222
15.333333
def parse_timestr(timestr): """ Parse a string describing a point in time. """ timedelta_secs = parse_timedelta(timestr) sync_start = datetime.now() if timedelta_secs: target = datetime.now() + timedelta(seconds=timedelta_secs) elif timestr.isdigit(): target = datetime.now()...
[ "def", "parse_timestr", "(", "timestr", ")", ":", "timedelta_secs", "=", "parse_timedelta", "(", "timestr", ")", "sync_start", "=", "datetime", ".", "now", "(", ")", "if", "timedelta_secs", ":", "target", "=", "datetime", ".", "now", "(", ")", "+", "timede...
38.34375
20.71875
def update(name, mac=None, mtu=None): ''' Update a nictag name : string name of nictag mac : string optional new mac for nictag mtu : int optional new MTU for nictag CLI Example: .. code-block:: bash salt '*' nictagadm.update trunk mtu=9000 ''' ret...
[ "def", "update", "(", "name", ",", "mac", "=", "None", ",", "mtu", "=", "None", ")", ":", "ret", "=", "{", "}", "if", "name", "not", "in", "list_nictags", "(", ")", ":", "return", "{", "'Error'", ":", "'nictag {0} does not exists.'", ".", "format", "...
30.94
24.54
def LDA_discriminants(x, labels): """ Linear Discriminant Analysis helper for determination how many columns of data should be reduced. **Args:** * `x` : input matrix (2d array), every row represents new sample * `labels` : list of labels (iterable), every item should be label for \ s...
[ "def", "LDA_discriminants", "(", "x", ",", "labels", ")", ":", "# validate inputs", "try", ":", "x", "=", "np", ".", "array", "(", "x", ")", "except", ":", "raise", "ValueError", "(", "'Impossible to convert x to a numpy array.'", ")", "# make the LDA", "eigen_v...
27.8
24.28
def tag_add(self, *tags): """ Return a view with the specified tags added """ return View({**self.spec, 'tag': list(set(self.tags) | set(tags))})
[ "def", "tag_add", "(", "self", ",", "*", "tags", ")", ":", "return", "View", "(", "{", "*", "*", "self", ".", "spec", ",", "'tag'", ":", "list", "(", "set", "(", "self", ".", "tags", ")", "|", "set", "(", "tags", ")", ")", "}", ")" ]
53
16.666667
def merge_configs(default, overwrite): """Recursively update a dict with the key/value pair of another. Dict values that are dictionaries themselves will be updated, whilst preserving existing keys. """ new_config = copy.deepcopy(default) for k, v in overwrite.items(): # Make sure to p...
[ "def", "merge_configs", "(", "default", ",", "overwrite", ")", ":", "new_config", "=", "copy", ".", "deepcopy", "(", "default", ")", "for", "k", ",", "v", "in", "overwrite", ".", "items", "(", ")", ":", "# Make sure to preserve existing items in", "# nested di...
31.588235
16.117647
def get_queryset(self): """ This view should return a list of all the Identities for the supplied query parameters. The query parameters should be in the form: {"address_type": "address"} e.g. {"msisdn": "+27123"} {"email": "foo@bar.com"} A specia...
[ "def", "get_queryset", "(", "self", ")", ":", "query_params", "=", "list", "(", "self", ".", "request", ".", "query_params", ".", "keys", "(", ")", ")", "# variable that stores criteria to filter identities by", "filter_criteria", "=", "{", "}", "# variable that sto...
39.6875
20.0875
def get(self, name): """ Looks for a name in the path. :param name: file name :return: path to the file """ for d in self.paths: if os.path.exists(d) and name in os.listdir(d): return os.path.join(d, name) logger.debug('File not found {}'.for...
[ "def", "get", "(", "self", ",", "name", ")", ":", "for", "d", "in", "self", ".", "paths", ":", "if", "os", ".", "path", ".", "exists", "(", "d", ")", "and", "name", "in", "os", ".", "listdir", "(", "d", ")", ":", "return", "os", ".", "path", ...
28.25
15.583333
def Wow64EnableWow64FsRedirection(Wow64FsEnableRedirection): """ This function may not work reliably when there are nested calls. Therefore, this function has been replaced by the L{Wow64DisableWow64FsRedirection} and L{Wow64RevertWow64FsRedirection} functions. @see: U{http://msdn.microsoft.com/en-...
[ "def", "Wow64EnableWow64FsRedirection", "(", "Wow64FsEnableRedirection", ")", ":", "_Wow64EnableWow64FsRedirection", "=", "windll", ".", "kernel32", ".", "Wow64EnableWow64FsRedirection", "_Wow64EnableWow64FsRedirection", ".", "argtypes", "=", "[", "BOOLEAN", "]", "_Wow64Enabl...
51.5
23.666667
def funTransEdgeY(theta, rho): """ Fringe matrix in Y :param theta: fringe angle, in [rad] :param rho: bend radius, in [m] :return: 2x2 numpy array """ return np.matrix([[1, 0], [-np.tan(theta) / rho, 1]], dtype=np.double)
[ "def", "funTransEdgeY", "(", "theta", ",", "rho", ")", ":", "return", "np", ".", "matrix", "(", "[", "[", "1", ",", "0", "]", ",", "[", "-", "np", ".", "tan", "(", "theta", ")", "/", "rho", ",", "1", "]", "]", ",", "dtype", "=", "np", ".", ...
30
12.625
def _set_igmp_po_intf_cfg(self, v, load=False): """ Setter method for igmp_po_intf_cfg, mapped from YANG variable /interface/port_channel/ip/igmp_po_intf_cfg (container) If this variable is read-only (config: false) in the source YANG file, then _set_igmp_po_intf_cfg is considered as a private metho...
[ "def", "_set_igmp_po_intf_cfg", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
79.181818
37.090909
def structure_recursion(self, struct, folder): """ From nested dictionaries representing .SAFE structure it recursively extracts all the files that need to be downloaded and stores them into class attribute `download_list`. :param struct: nested dictionaries representing a part of .SAFE...
[ "def", "structure_recursion", "(", "self", ",", "struct", ",", "folder", ")", ":", "has_subfolder", "=", "False", "for", "name", ",", "substruct", "in", "struct", ".", "items", "(", ")", ":", "subfolder", "=", "os", ".", "path", ".", "join", "(", "fold...
50.071429
22.214286
def parse_phones(self): """Parse TextGrid phone intervals. This method parses the phone intervals in a TextGrid to extract each phone and each phone's start and end times in the audio recording. For each phone, it instantiates the class Phone(), with the phone and its st...
[ "def", "parse_phones", "(", "self", ")", ":", "phones", "=", "[", "]", "for", "i", "in", "self", ".", "phone_intervals", ":", "start", "=", "float", "(", "i", "[", "i", ".", "index", "(", "'xmin = '", ")", "+", "7", ":", "i", ".", "index", "(", ...
41.6
21.25
def vcf_file_to_dict_of_vars(infile, reference_seqs): '''Loads just the variant info from input VCF file. If reference_seqs is given, should be a dict of seq name -> pyfastaq Fastaq sequence, and will be used to sanity check variants in input file. Any where CHROM is not in the dict, or REF string does ...
[ "def", "vcf_file_to_dict_of_vars", "(", "infile", ",", "reference_seqs", ")", ":", "variants", "=", "{", "}", "_", ",", "vcf_records", "=", "vcf_file_to_dict", "(", "infile", ",", "sort", "=", "False", ",", "remove_asterisk_alts", "=", "True", ",", "remove_use...
48.823529
29.882353
def lastPrePrepareSeqNo(self, n): """ This will _lastPrePrepareSeqNo to values greater than its previous values else it will not. To forcefully override as in case of `revert`, directly set `self._lastPrePrepareSeqNo` """ if n > self._lastPrePrepareSeqNo: self...
[ "def", "lastPrePrepareSeqNo", "(", "self", ",", "n", ")", ":", "if", "n", ">", "self", ".", "_lastPrePrepareSeqNo", ":", "self", ".", "_lastPrePrepareSeqNo", "=", "n", "else", ":", "self", ".", "logger", ".", "debug", "(", "'{} cannot set lastPrePrepareSeqNo t...
41.384615
13.230769
def from_raw_query(cls, query_string): """Parse raw string to query. Given a raw string (typically typed by the user), parse to a structured format and initialize the class. """ try: node_tree = grammar.parse(query_string) except IncompleteParseError: ...
[ "def", "from_raw_query", "(", "cls", ",", "query_string", ")", ":", "try", ":", "node_tree", "=", "grammar", ".", "parse", "(", "query_string", ")", "except", "IncompleteParseError", ":", "query_string", "=", "cls", ".", "fix_quotes", "(", "query_string", ")",...
35.5625
16.8125
def derive_identity_arf(name, arf): """Create an "identity" ARF that has uniform sensitivity. *name* The name of the ARF object to be created; passed to Sherpa. *arf* An existing ARF object on which to base this one. Returns: A new ARF1D object that has a uniform spectral response vec...
[ "def", "derive_identity_arf", "(", "name", ",", "arf", ")", ":", "from", "sherpa", ".", "astro", ".", "data", "import", "DataARF", "from", "sherpa", ".", "astro", ".", "instrument", "import", "ARF1D", "darf", "=", "DataARF", "(", "name", ",", "arf", ".",...
34.242424
22.727273
def clearSyntax(self): """Clear syntax. Disables syntax highlighting This method might take long time, if document is big. Don't call it if you don't have to (i.e. in destructor) """ if self._highlighter is not None: self._highlighter.terminate() self._highlighte...
[ "def", "clearSyntax", "(", "self", ")", ":", "if", "self", ".", "_highlighter", "is", "not", "None", ":", "self", ".", "_highlighter", ".", "terminate", "(", ")", "self", ".", "_highlighter", "=", "None", "self", ".", "languageChanged", ".", "emit", "(",...
40.444444
16
def _resolve_registered(self, event_handler, full_config) -> typing.Generator: """ Resolve registered filters :param event_handler: :param full_config: :return: """ for record in self._registered: filter_ = record.resolve(self._dispatcher, event_handl...
[ "def", "_resolve_registered", "(", "self", ",", "event_handler", ",", "full_config", ")", "->", "typing", ".", "Generator", ":", "for", "record", "in", "self", ".", "_registered", ":", "filter_", "=", "record", ".", "resolve", "(", "self", ".", "_dispatcher"...
33.333333
21.2
def build_instance_name(inst, obj=None): """Return an instance name from an instance, and set instance.path """ if obj is None: for _ in inst.properties.values(): inst.path.keybindings.__setitem__(_.name, _.value) return inst.path if not isinstance(obj, list): return buil...
[ "def", "build_instance_name", "(", "inst", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "for", "_", "in", "inst", ".", "properties", ".", "values", "(", ")", ":", "inst", ".", "path", ".", "keybindings", ".", "__setitem__", "(",...
45.45
17.05
def get_report_hook(self): """ Return a callback function suitable for using reporthook argument of urllib(.request).urlretrieve :return: function object """ def report_hook(chunkNumber, chunkSize, totalSize): if totalSize != -1 and not self._callback.range_initialize...
[ "def", "get_report_hook", "(", "self", ")", ":", "def", "report_hook", "(", "chunkNumber", ",", "chunkSize", ",", "totalSize", ")", ":", "if", "totalSize", "!=", "-", "1", "and", "not", "self", ".", "_callback", ".", "range_initialized", "(", ")", ":", "...
43.411765
16.470588
def remove_file(self, file_name, *args, **kwargs): """ :meth:`.WNetworkClientProto.remove_file` method implementation """ client = self.dav_client() remote_path = self.join_path(self.session_path(), file_name) if client.is_dir(remote_path) is True: raise ValueError('Unable to remove non-file entry') clie...
[ "def", "remove_file", "(", "self", ",", "file_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "client", "=", "self", ".", "dav_client", "(", ")", "remote_path", "=", "self", ".", "join_path", "(", "self", ".", "session_path", "(", ")", ",...
41.75
8.875
def multi_replace(str_, search_list, repl_list): r""" Performs multiple replace functions foreach item in search_list and repl_list. Args: str_ (str): string to search search_list (list): list of search strings repl_list (list or str): one or multiple replace strings Return...
[ "def", "multi_replace", "(", "str_", ",", "search_list", ",", "repl_list", ")", ":", "if", "isinstance", "(", "repl_list", ",", "six", ".", "string_types", ")", ":", "repl_list_", "=", "[", "repl_list", "]", "*", "len", "(", "search_list", ")", "else", "...
31.555556
18.416667
def cmd_tool(args=None): """ Command line tool to make a md5sum comparison of two .fil files. """ if 'bl' in local_host: header_loc = '/usr/local/sigproc/bin/header' #Current location of header command in GBT. else: raise IOError('Script only able to run in BL systems.') p = OptionPars...
[ "def", "cmd_tool", "(", "args", "=", "None", ")", ":", "if", "'bl'", "in", "local_host", ":", "header_loc", "=", "'/usr/local/sigproc/bin/header'", "#Current location of header command in GBT.", "else", ":", "raise", "IOError", "(", "'Script only able to run in BL systems...
27.082474
23.659794