text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _exp_schedule(iteration, k=20, lam=0.005, limit=100): ''' Possible scheduler for simulated_annealing, based on the aima example. ''' return k * math.exp(-lam * iteration)
[ "def", "_exp_schedule", "(", "iteration", ",", "k", "=", "20", ",", "lam", "=", "0.005", ",", "limit", "=", "100", ")", ":", "return", "k", "*", "math", ".", "exp", "(", "-", "lam", "*", "iteration", ")" ]
37.2
23.6
def as_dict(self): """json friendly dict representation of Kpoints""" d = {"comment": self.comment, "nkpoints": self.num_kpts, "generation_style": self.style.name, "kpoints": self.kpts, "usershift": self.kpts_shift, "kpts_weights": self.kpts_weights, "coord_type": ...
[ "def", "as_dict", "(", "self", ")", ":", "d", "=", "{", "\"comment\"", ":", "self", ".", "comment", ",", "\"nkpoints\"", ":", "self", ".", "num_kpts", ",", "\"generation_style\"", ":", "self", ".", "style", ".", "name", ",", "\"kpoints\"", ":", "self", ...
46.235294
16.235294
def output_args(f): """decorator for output-formatting args applied to %pxresult and %%px """ args = [ magic_arguments.argument('-r', action="store_const", dest='groupby', const='order', help="collate outputs in order (same as group-outputs=order)" ), ...
[ "def", "output_args", "(", "f", ")", ":", "args", "=", "[", "magic_arguments", ".", "argument", "(", "'-r'", ",", "action", "=", "\"store_const\"", ",", "dest", "=", "'groupby'", ",", "const", "=", "'order'", ",", "help", "=", "\"collate outputs in order (sa...
38.631579
25.184211
def init_app(self, app): """Flask application initialization.""" self.init_config(app) app.extensions['inspire-crawler'] = self app.cli.add_command(crawler_cmd)
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "self", ".", "init_config", "(", "app", ")", "app", ".", "extensions", "[", "'inspire-crawler'", "]", "=", "self", "app", ".", "cli", ".", "add_command", "(", "crawler_cmd", ")" ]
37.6
7
def read_blob(self,blob_dim,n_blob=0): """Read blob from a selection. """ n_blobs = self.calc_n_blobs(blob_dim) if n_blob > n_blobs or n_blob < 0: raise ValueError('Please provide correct n_blob value. Given %i, but max values is %i'%(n_blob,n_blobs)) # This prevent...
[ "def", "read_blob", "(", "self", ",", "blob_dim", ",", "n_blob", "=", "0", ")", ":", "n_blobs", "=", "self", ".", "calc_n_blobs", "(", "blob_dim", ")", "if", "n_blob", ">", "n_blobs", "or", "n_blob", "<", "0", ":", "raise", "ValueError", "(", "'Please ...
44.02
30.72
def get_cache_key(self, offset=0, limit=0, order=None, post_slug=''): """ The return of Get """ return hashlib.sha1( '.'.join([ str(self._get_data_source_url()), str(offset), str(limit), str(order), str(p...
[ "def", "get_cache_key", "(", "self", ",", "offset", "=", "0", ",", "limit", "=", "0", ",", "order", "=", "None", ",", "post_slug", "=", "''", ")", ":", "return", "hashlib", ".", "sha1", "(", "'.'", ".", "join", "(", "[", "str", "(", "self", ".", ...
30
13
def _fill(self, data, total_length, padding_symbol): """ Overridden :meth:`.WSimplePadding._fill` method. This methods adds padding symbol at the beginning and at the end of the specified data. :param data: data to append to :param total_length: target length :param padding_symbol: symbol to pad :return: b...
[ "def", "_fill", "(", "self", ",", "data", ",", "total_length", ",", "padding_symbol", ")", ":", "delta", "=", "total_length", "-", "len", "(", "data", ")", "return", "(", "(", "padding_symbol", "*", "random_int", "(", "delta", ")", ")", "+", "data", ")...
37.166667
15.583333
def getConfigRoot(cls, create = False): """ Return the mapped configuration root node """ try: return manager.gettree(getattr(cls, 'configkey'), create) except AttributeError: return None
[ "def", "getConfigRoot", "(", "cls", ",", "create", "=", "False", ")", ":", "try", ":", "return", "manager", ".", "gettree", "(", "getattr", "(", "cls", ",", "'configkey'", ")", ",", "create", ")", "except", "AttributeError", ":", "return", "None" ]
30.5
11.75
def tab_under_menu(self): """ Returns the tab that sits under the context menu. :return: QWidget """ if self._menu_pos: return self.tabBar().tabAt(self._menu_pos) else: return self.currentIndex()
[ "def", "tab_under_menu", "(", "self", ")", ":", "if", "self", ".", "_menu_pos", ":", "return", "self", ".", "tabBar", "(", ")", ".", "tabAt", "(", "self", ".", "_menu_pos", ")", "else", ":", "return", "self", ".", "currentIndex", "(", ")" ]
28.777778
11.666667
def display_upstream_structure(structure_dict): """Displays pipeline structure in the jupyter notebook. Args: structure_dict (dict): dict returned by :func:`~steppy.base.Step.upstream_structure`. """ graph = _create_graph(structure_dict) plt = Image(graph.create_png()) displ...
[ "def", "display_upstream_structure", "(", "structure_dict", ")", ":", "graph", "=", "_create_graph", "(", "structure_dict", ")", "plt", "=", "Image", "(", "graph", ".", "create_png", "(", ")", ")", "display", "(", "plt", ")" ]
31.8
13.2
def loop(self): """ Thread's main loop. Don't meant to be called by user directly. Call inherited start() method instead. Events are read only once time every min(read_freq, timeout) seconds at best and only if the size of events to read is >= threshold. """ # Wh...
[ "def", "loop", "(", "self", ")", ":", "# When the loop must be terminated .stop() is called, 'stop'", "# is written to pipe fd so poll() returns and .check_events()", "# returns False which make evaluate the While's stop condition", "# ._stop_event.isSet() wich put an end to the thread's execution...
44.222222
17.666667
def load(self, filename): """Load file information from a filename.""" self.metadata_blocks = [] self.tags = None self.cuesheet = None self.seektable = None self.filename = filename fileobj = StrictFileObject(open(filename, "rb")) try: self.__...
[ "def", "load", "(", "self", ",", "filename", ")", ":", "self", ".", "metadata_blocks", "=", "[", "]", "self", ".", "tags", "=", "None", "self", ".", "cuesheet", "=", "None", "self", ".", "seektable", "=", "None", "self", ".", "filename", "=", "filena...
30.6
16.2
def extract_physical_plan(self, topology): """ Returns the representation of physical plan that will be returned from Tracker. """ physicalPlan = { "instances": {}, "instance_groups": {}, "stmgrs": {}, "spouts": {}, "bolts": {}, "config": {}, "...
[ "def", "extract_physical_plan", "(", "self", ",", "topology", ")", ":", "physicalPlan", "=", "{", "\"instances\"", ":", "{", "}", ",", "\"instance_groups\"", ":", "{", "}", ",", "\"stmgrs\"", ":", "{", "}", ",", "\"spouts\"", ":", "{", "}", ",", "\"bolts...
31.557895
18.421053
def get_repos(self): """ Gets the repos for the organization and builds the URL/headers for getting timestamps of stargazers. """ print 'Getting repos.' #Uses the developer API. Note this could change. headers = {'Accept': 'application/vnd.github.v3.star+json', '...
[ "def", "get_repos", "(", "self", ")", ":", "print", "'Getting repos.'", "#Uses the developer API. Note this could change.", "headers", "=", "{", "'Accept'", ":", "'application/vnd.github.v3.star+json'", ",", "'Authorization'", ":", "'token '", "+", "self", ".", "token", ...
45.058824
20.352941
def run(self): ''' Run the logic for saltkey ''' self._update_opts() cmd = self.opts['fun'] veri = None ret = None try: if cmd in ('accept', 'reject', 'delete'): ret = self._run_cmd('name_match') if not isinstan...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_update_opts", "(", ")", "cmd", "=", "self", ".", "opts", "[", "'fun'", "]", "veri", "=", "None", "ret", "=", "None", "try", ":", "if", "cmd", "in", "(", "'accept'", ",", "'reject'", ",", "'delet...
42.649123
17.666667
def get_teams(self): """Get teams.""" if self._cache['teams']: return self._cache['teams'] teams = [] for j, player in enumerate(self._header.initial.players): added = False for i in range(0, len(self._header.initial.players)): if playe...
[ "def", "get_teams", "(", "self", ")", ":", "if", "self", ".", "_cache", "[", "'teams'", "]", ":", "return", "self", ".", "_cache", "[", "'teams'", "]", "teams", "=", "[", "]", "for", "j", ",", "player", "in", "enumerate", "(", "self", ".", "_header...
40.09375
9.34375
def print_roi(self, loglevel=logging.INFO): """Print information about the spectral and spatial properties of the ROI (sources, diffuse components).""" self.logger.log(loglevel, '\n' + str(self.roi))
[ "def", "print_roi", "(", "self", ",", "loglevel", "=", "logging", ".", "INFO", ")", ":", "self", ".", "logger", ".", "log", "(", "loglevel", ",", "'\\n'", "+", "str", "(", "self", ".", "roi", ")", ")" ]
55
4.5
def write_amendment(self, amendment_id, file_content, branch, author): """Given an amendment_id, temporary filename of content, branch and auth_info Deprecated but needed until we merge api local-dep to master... """ gh_user = branch.split('_amendment_')[0] msg = "Update Amendm...
[ "def", "write_amendment", "(", "self", ",", "amendment_id", ",", "file_content", ",", "branch", ",", "author", ")", ":", "gh_user", "=", "branch", ".", "split", "(", "'_amendment_'", ")", "[", "0", "]", "msg", "=", "\"Update Amendment '%s' via OpenTree API\"", ...
45.615385
16.692308
def loadAddressbyPrefix(self, prefix, type, network_id, callback=None, errback=None): """ Load an existing address by prefix, type and network into a high level Address object :param str prefix: CIDR prefix of an existing Address :param str type: Type of address assignement (planned, as...
[ "def", "loadAddressbyPrefix", "(", "self", ",", "prefix", ",", "type", ",", "network_id", ",", "callback", "=", "None", ",", "errback", "=", "None", ")", ":", "import", "ns1", ".", "ipam", "network", "=", "ns1", ".", "ipam", ".", "Network", "(", "self"...
54.75
29.083333
def ValidateAccessAndSubjects(requested_access, subjects): """Does basic requested access validation. Args: requested_access: String consisting or 'r', 'w' and 'q' characters. subjects: A list of subjects that are about to be accessed with a given requested_access. Used for logging purposes only. ...
[ "def", "ValidateAccessAndSubjects", "(", "requested_access", ",", "subjects", ")", ":", "if", "not", "requested_access", ":", "raise", "access_control", ".", "UnauthorizedAccess", "(", "\"Must specify requested access type for %s\"", "%", "subjects", ")", "for", "s", "i...
32.375
23.09375
def amdf(lag, size): """ Average Magnitude Difference Function non-linear filter for a given size and a fixed lag. Parameters ---------- lag : Time lag, in samples. See ``freq2lag`` if needs conversion from frequency values. size : Moving average size. Returns ------- A callable that a...
[ "def", "amdf", "(", "lag", ",", "size", ")", ":", "filt", "=", "(", "1", "-", "z", "**", "-", "lag", ")", ".", "linearize", "(", ")", "@", "tostream", "def", "amdf_filter", "(", "sig", ",", "zero", "=", "0.", ")", ":", "return", "maverage", "("...
23.909091
26.030303
def _binary_arithemtic(self, left, binary, right): """ Parameters ---------- operand: Column object, integer or float Value on which to apply operator to this column binary: char binary arithmetic operator (-, +, *, /, ^, %) Returns ------...
[ "def", "_binary_arithemtic", "(", "self", ",", "left", ",", "binary", ",", "right", ")", ":", "if", "isinstance", "(", "right", ",", "(", "int", ",", "float", ")", ")", ":", "right", "=", "right", "elif", "isinstance", "(", "right", ",", "Column", ")...
31.688889
18.266667
def login(self, url=None, api_key=None, login=None, pwd=None, api_version=None, timeout=None, verify=True, alt_filepath=None, domain=None, **kwargs): """ Login to SMC API and retrieve a valid session. Sessions use a pool connection manager to provide dynamic scalability ...
[ "def", "login", "(", "self", ",", "url", "=", "None", ",", "api_key", "=", "None", ",", "login", "=", "None", ",", "pwd", "=", "None", ",", "api_version", "=", "None", ",", "timeout", "=", "None", ",", "verify", "=", "True", ",", "alt_filepath", "=...
45.150442
24.495575
def _get_iris_args(attrs): """ Converts the xarray attrs into args that can be passed into Iris """ # iris.unit is deprecated in Iris v1.9 import cf_units args = {'attributes': _filter_attrs(attrs, iris_forbidden_keys)} args.update(_pick_attrs(attrs, ('standard_name', 'long_name',))) unit_ar...
[ "def", "_get_iris_args", "(", "attrs", ")", ":", "# iris.unit is deprecated in Iris v1.9", "import", "cf_units", "args", "=", "{", "'attributes'", ":", "_filter_attrs", "(", "attrs", ",", "iris_forbidden_keys", ")", "}", "args", ".", "update", "(", "_pick_attrs", ...
41.454545
15.363636
def toosm(self): """Generate a OSM node element subtree. Returns: etree.Element: OSM node element """ node = create_elem('node', {'id': str(self.ident), 'lat': str(self.latitude), 'lon': str(self.longitu...
[ "def", "toosm", "(", "self", ")", ":", "node", "=", "create_elem", "(", "'node'", ",", "{", "'id'", ":", "str", "(", "self", ".", "ident", ")", ",", "'lat'", ":", "str", "(", "self", ".", "latitude", ")", ",", "'lon'", ":", "str", "(", "self", ...
36.578947
19
def record_path(self): ''' If recording is not enabled, return `None` as record path. ''' if self.record_button.get_property('active') and (self.record_path_selector .selected_path): return self.record_path_selector.se...
[ "def", "record_path", "(", "self", ")", ":", "if", "self", ".", "record_button", ".", "get_property", "(", "'active'", ")", "and", "(", "self", ".", "record_path_selector", ".", "selected_path", ")", ":", "return", "self", ".", "record_path_selector", ".", "...
40.111111
26.777778
def zero_pad_data_extend(self, job_data_seg, curr_seg): """When using zero padding, *all* data is analysable, but the setup functions must include the padding data where it is available so that we are not zero-padding in the middle of science segments. This function takes a job_data_seg,...
[ "def", "zero_pad_data_extend", "(", "self", ",", "job_data_seg", ",", "curr_seg", ")", ":", "if", "self", ".", "zero_padding", "is", "False", ":", "return", "job_data_seg", "else", ":", "start_pad", "=", "int", "(", "self", ".", "get_opt", "(", "'segment-sta...
53.882353
20.705882
def has_submenu_items(self, current_page, allow_repeating_parents, original_menu_tag, menu_instance=None, request=None): """ When rendering pages in a menu template a `has_children_in_menu` attribute is added to each page, letting template developers know whethe...
[ "def", "has_submenu_items", "(", "self", ",", "current_page", ",", "allow_repeating_parents", ",", "original_menu_tag", ",", "menu_instance", "=", "None", ",", "request", "=", "None", ")", ":", "return", "menu_instance", ".", "page_has_children", "(", "self", ")" ...
56.928571
26.785714
def isSequence(arg): """Check if input is iterable.""" if hasattr(arg, "strip"): return False if hasattr(arg, "__getslice__"): return True if hasattr(arg, "__iter__"): return True return False
[ "def", "isSequence", "(", "arg", ")", ":", "if", "hasattr", "(", "arg", ",", "\"strip\"", ")", ":", "return", "False", "if", "hasattr", "(", "arg", ",", "\"__getslice__\"", ")", ":", "return", "True", "if", "hasattr", "(", "arg", ",", "\"__iter__\"", "...
25.333333
14.333333
def filter_examples(self, field_names): """Remove unknown words from dataset examples with respect to given field. Arguments: field_names (list(str)): Within example only the parts with field names in field_names will have their unknown words deleted. """ for...
[ "def", "filter_examples", "(", "self", ",", "field_names", ")", ":", "for", "i", ",", "example", "in", "enumerate", "(", "self", ".", "examples", ")", ":", "for", "field_name", "in", "field_names", ":", "vocab", "=", "set", "(", "self", ".", "fields", ...
48.285714
16.642857
def create_user_task(sender=None, body=None, **kwargs): # pylint: disable=unused-argument """ Create a :py:class:`UserTaskStatus` record for each :py:class:`UserTaskMixin`. Also creates a :py:class:`UserTaskStatus` for each chain, chord, or group containing the new :py:class:`UserTaskMixin`. """ ...
[ "def", "create_user_task", "(", "sender", "=", "None", ",", "body", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "try", ":", "task_class", "=", "import_string", "(", "sender", ")", "except", "ImportError", ":", "return",...
50.222222
24.444444
def auth(self, auth_method, key): """ Sets authentication info for current tag """ self.method = auth_method self.key = key if self.debug: print("Changing used auth key to " + str(key) + " using method " + ("A" if auth_method == self.rfid.auth_a else "B"))
[ "def", "auth", "(", "self", ",", "auth_method", ",", "key", ")", ":", "self", ".", "method", "=", "auth_method", "self", ".", "key", "=", "key", "if", "self", ".", "debug", ":", "print", "(", "\"Changing used auth key to \"", "+", "str", "(", "key", ")...
34.333333
20.777778
def username_from_request(request): """ unloads username from default POST request """ if config.USERNAME_FORM_FIELD in request.POST: return request.POST[config.USERNAME_FORM_FIELD][:255] return None
[ "def", "username_from_request", "(", "request", ")", ":", "if", "config", ".", "USERNAME_FORM_FIELD", "in", "request", ".", "POST", ":", "return", "request", ".", "POST", "[", "config", ".", "USERNAME_FORM_FIELD", "]", "[", ":", "255", "]", "return", "None" ...
43
12.2
def main(): """ NAME sort_specimens.py DESCRIPTION Reads in a pmag_specimen formatted file and separates it into different components (A,B...etc.) SYNTAX sort_specimens.py [-h] [command line options] INPUT takes pmag_specimens.txt formatted input file OPTIONS...
[ "def", "main", "(", ")", ":", "dir_path", "=", "'.'", "inspec", "=", "\"pmag_specimens.txt\"", "if", "'-WD'", "in", "sys", ".", "argv", ":", "ind", "=", "sys", ".", "argv", ".", "index", "(", "'-WD'", ")", "dir_path", "=", "sys", ".", "argv", "[", ...
37.758065
25.080645
def get_snapshots(self, si, logger, vm_uuid): """ Restores a virtual machine to a snapshot :param vim.ServiceInstance si: py_vmomi service instance :param logger: Logger :param vm_uuid: uuid of the virtual machine """ vm = self.pyvmomi_service.find_by_uuid(si, vm_...
[ "def", "get_snapshots", "(", "self", ",", "si", ",", "logger", ",", "vm_uuid", ")", ":", "vm", "=", "self", ".", "pyvmomi_service", ".", "find_by_uuid", "(", "si", ",", "vm_uuid", ")", "logger", ".", "info", "(", "\"Get snapshots\"", ")", "snapshots", "=...
36.916667
12.416667
def classify(self, peer_dir_meta): """Classify this entry as 'new', 'unmodified', or 'modified'.""" assert self.classification is None peer_entry_meta = None if peer_dir_meta: # Metadata is generally available, so we can detect 'new' or 'modified' peer_entry_meta ...
[ "def", "classify", "(", "self", ",", "peer_dir_meta", ")", ":", "assert", "self", ".", "classification", "is", "None", "peer_entry_meta", "=", "None", "if", "peer_dir_meta", ":", "# Metadata is generally available, so we can detect 'new' or 'modified'", "peer_entry_meta", ...
42.727273
16.863636
async def reset_wallet(self) -> str: """ Close and delete HolderProver wallet, then create and open a replacement on prior link secret. Note that this operation effectively destroys private keys for credential definitions. Its intended use is primarily for testing and demonstration. ...
[ "async", "def", "reset_wallet", "(", "self", ")", "->", "str", ":", "LOGGER", ".", "debug", "(", "'HolderProver.reset_wallet >>>'", ")", "self", ".", "_assert_link_secret", "(", "'reset_wallet'", ")", "seed", "=", "self", ".", "wallet", ".", "_seed", "wallet_n...
32.527778
20.861111
def _get_merge_keys(self): """ Note: has side effects (copy/delete key columns) Parameters ---------- left right on Returns ------- left_keys, right_keys """ left_keys = [] right_keys = [] join_names = [] ...
[ "def", "_get_merge_keys", "(", "self", ")", ":", "left_keys", "=", "[", "]", "right_keys", "=", "[", "]", "join_names", "=", "[", "]", "right_drop", "=", "[", "]", "left_drop", "=", "[", "]", "left", ",", "right", "=", "self", ".", "left", ",", "se...
41.405405
18.810811
def logout(self): """ 登出会话 :return: self """ self.req(API_ACCOUNT_LOGOUT % self.ck()) self.cookies = {} self.user_alias = None self.persist()
[ "def", "logout", "(", "self", ")", ":", "self", ".", "req", "(", "API_ACCOUNT_LOGOUT", "%", "self", ".", "ck", "(", ")", ")", "self", ".", "cookies", "=", "{", "}", "self", ".", "user_alias", "=", "None", "self", ".", "persist", "(", ")" ]
20.5
15.3
def rewrite_file_imports(item, vendored_libs, vendor_dir): """Rewrite 'import xxx' and 'from xxx import' for vendored_libs""" text = item.read_text(encoding='utf-8') renames = LIBRARY_RENAMES for k in LIBRARY_RENAMES.keys(): if k not in vendored_libs: vendored_libs.append(k) for ...
[ "def", "rewrite_file_imports", "(", "item", ",", "vendored_libs", ",", "vendor_dir", ")", ":", "text", "=", "item", ".", "read_text", "(", "encoding", "=", "'utf-8'", ")", "renames", "=", "LIBRARY_RENAMES", "for", "k", "in", "LIBRARY_RENAMES", ".", "keys", "...
32.185185
13.296296
def _get_filename(self, key, filename): """Write key to file. Either this method or :meth:`~simplekv.KeyValueStore._get_file` will be called by :meth:`~simplekv.KeyValueStore.get_file`. This method only accepts filenames and will open the file with a mode of ``wb``, then call :me...
[ "def", "_get_filename", "(", "self", ",", "key", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "dest", ":", "return", "self", ".", "_get_file", "(", "key", ",", "dest", ")" ]
44.583333
13.083333
def ingest(self, co, classname=None, code_objects={}, show_asm=None): """ Pick out tokens from an uncompyle6 code object, and transform them, returning a list of uncompyle6 'Token's. The transformations are made to assist the deparsing grammar. Specificially: - vario...
[ "def", "ingest", "(", "self", ",", "co", ",", "classname", "=", "None", ",", "code_objects", "=", "{", "}", ",", "show_asm", "=", "None", ")", ":", "if", "not", "show_asm", ":", "show_asm", "=", "self", ".", "show_asm", "bytecode", "=", "self", ".", ...
46.190476
18.419913
def run(cmd): """Run the given command. Raises OSError is the command returns a non-zero exit status. """ log.debug("running '%s'", cmd) fixed_cmd = cmd if sys.platform == "win32" and cmd.count('"') > 2: fixed_cmd = '"' + cmd + '"' retval = os.system(fixed_cmd) if hasattr(os, "W...
[ "def", "run", "(", "cmd", ")", ":", "log", ".", "debug", "(", "\"running '%s'\"", ",", "cmd", ")", "fixed_cmd", "=", "cmd", "if", "sys", ".", "platform", "==", "\"win32\"", "and", "cmd", ".", "count", "(", "'\"'", ")", ">", "2", ":", "fixed_cmd", "...
29.0625
15.1875
def authorizer(self, schemes, resource, action, request_args): """Construct the Authorization header for a request. Args: schemes (list of str): Authentication schemes supported for the requested action. resource (str): Object upon which an action is being performed. ...
[ "def", "authorizer", "(", "self", ",", "schemes", ",", "resource", ",", "action", ",", "request_args", ")", ":", "if", "not", "schemes", ":", "return", "u''", ",", "u''", "for", "scheme", "in", "schemes", ":", "if", "scheme", "in", "self", ".", "scheme...
42.76
22.72
def ParseLastVisitedRow( self, parser_mediator, query, row, cache=None, database=None, **unused_kwargs): """Parses a last visited row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): qu...
[ "def", "ParseLastVisitedRow", "(", "self", ",", "parser_mediator", ",", "query", ",", "row", ",", "cache", "=", "None", ",", "database", "=", "None", ",", "*", "*", "unused_kwargs", ")", ":", "query_hash", "=", "hash", "(", "query", ")", "hidden", "=", ...
44.25
20.4
def flatten(obj): ''' TODO: add docs ''' if isseq(obj): ret = [] for item in obj: if isseq(item): ret.extend(flatten(item)) else: ret.append(item) return ret if isdict(obj): ret = dict() for key, value in obj.items(): for skey, sval in _relflatten(value): ...
[ "def", "flatten", "(", "obj", ")", ":", "if", "isseq", "(", "obj", ")", ":", "ret", "=", "[", "]", "for", "item", "in", "obj", ":", "if", "isseq", "(", "item", ")", ":", "ret", ".", "extend", "(", "flatten", "(", "item", ")", ")", "else", ":"...
22
21.6
def WriteXml(self, w, option, elementName=None): """ Method writes the xml representation of the managed object. """ if elementName == None: x = w.createElement(self.propMoMeta.xmlAttribute) else: x = w.createElement(elementName) for at in UcsUtils.GetUcsPropertyMetaAttributeList(self.classId): atMeta ...
[ "def", "WriteXml", "(", "self", ",", "w", ",", "option", ",", "elementName", "=", "None", ")", ":", "if", "elementName", "==", "None", ":", "x", "=", "w", ".", "createElement", "(", "self", ".", "propMoMeta", ".", "xmlAttribute", ")", "else", ":", "x...
37.2
16.05
def write_zip_fp(fp, data, properties, dir_data_list=None): """ Write custom zip file of data and properties to fp :param fp: the file point to which to write the header :param data: the data to write to the file; may be None :param properties: the properties to write to the file; m...
[ "def", "write_zip_fp", "(", "fp", ",", "data", ",", "properties", ",", "dir_data_list", "=", "None", ")", ":", "assert", "data", "is", "not", "None", "or", "properties", "is", "not", "None", "# dir_data_list has the format: local file record offset, name, data length,...
50.279412
24.132353
def latinize(value): """ Converts (transliterates) greek letters to latin equivalents. """ def replace_double_character(match): search = ('Θ Χ Ψ ' 'θ χ ψ ' 'ΟΥ ΑΥ ΕΥ ' 'Ου Αυ Ευ ' 'ου αυ ευ').split() replace = ('TH C...
[ "def", "latinize", "(", "value", ")", ":", "def", "replace_double_character", "(", "match", ")", ":", "search", "=", "(", "'Θ Χ Ψ '", "'θ χ ψ '", "'ΟΥ ΑΥ ΕΥ '", "'Ου Αυ Ευ '", "'ου αυ ευ').spli", "t", "(", ")", "", "", "replace", "=", "(", "'TH CH PS '", "'t...
32.454545
12.757576
def extrude(self, uem, reference, collar=0.0, skip_overlap=False): """Extrude reference boundary collars from uem reference |----| |--------------| |-------------| uem |---------------------| |-------------------------------| extruded |--| |--| |---| |-----| |...
[ "def", "extrude", "(", "self", ",", "uem", ",", "reference", ",", "collar", "=", "0.0", ",", "skip_overlap", "=", "False", ")", ":", "if", "collar", "==", "0.", "and", "not", "skip_overlap", ":", "return", "uem", "collars", ",", "overlap_regions", "=", ...
36.821429
21.410714
def send_response_only(self, code, message=None): """Send the response header only.""" if message is None: if code in self.responses: message = self.responses[code][0] else: message = '' if self.request_version != 'HTTP/0.9': if...
[ "def", "send_response_only", "(", "self", ",", "code", ",", "message", "=", "None", ")", ":", "if", "message", "is", "None", ":", "if", "code", "in", "self", ".", "responses", ":", "message", "=", "self", ".", "responses", "[", "code", "]", "[", "0",...
43.076923
10.461538
def lock_file(f, block=False): """ If block=False (the default), die hard and fast if another process has already grabbed the lock for this file. If block=True, wait for the lock to be released, then continue. """ try: flags = fcntl.LOCK_EX if not block: flags |= fcn...
[ "def", "lock_file", "(", "f", ",", "block", "=", "False", ")", ":", "try", ":", "flags", "=", "fcntl", ".", "LOCK_EX", "if", "not", "block", ":", "flags", "|=", "fcntl", ".", "LOCK_NB", "fcntl", ".", "flock", "(", "f", ".", "fileno", "(", ")", ",...
32.588235
16.117647
def _validate_plan_base( new_plan, base_plan, is_partition_subset=True, allow_rf_change=False, ): """Validate if given plan is valid comparing with given base-plan. Validate following assertions: - Partition-check: New partition-set should be subset of base-partition set - Replica-count...
[ "def", "_validate_plan_base", "(", "new_plan", ",", "base_plan", ",", "is_partition_subset", "=", "True", ",", "allow_rf_change", "=", "False", ",", ")", ":", "# Verify that partitions in plan are subset of base plan.", "new_partitions", "=", "set", "(", "[", "(", "p_...
35.308824
19.235294
def wr_txt(self, fout_txt="gos_depth01.txt", title=None): """write text table of depth-01 GO terms and their letter representation.""" with open(fout_txt, 'w') as prt: self.prt_header(prt, title) data_nts = self.prt_txt(prt) sys.stdout.write(" {N:>5} items WROTE: {TX...
[ "def", "wr_txt", "(", "self", ",", "fout_txt", "=", "\"gos_depth01.txt\"", ",", "title", "=", "None", ")", ":", "with", "open", "(", "fout_txt", ",", "'w'", ")", "as", "prt", ":", "self", ".", "prt_header", "(", "prt", ",", "title", ")", "data_nts", ...
53.571429
7.571429
def get_sources(arxiv_id): """ Download sources on arXiv for a given preprint. .. note:: Bulk download of sources from arXiv is not permitted by their API. \ You should have a look at http://arxiv.org/help/bulk_data_s3. :param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401...
[ "def", "get_sources", "(", "arxiv_id", ")", ":", "try", ":", "request", "=", "requests", ".", "get", "(", "ARXIV_EPRINT_URL", ".", "format", "(", "arxiv_id", "=", "arxiv_id", ")", ")", "request", ".", "raise_for_status", "(", ")", "file_object", "=", "io",...
35.952381
23.095238
def get_resources_of_type(network_id, type_id, **kwargs): """ Return the Nodes, Links and ResourceGroups which have the type specified. """ nodes_with_type = db.DBSession.query(Node).join(ResourceType).filter(Node.network_id==network_id, ResourceType.type_id==type_id).all() links_with_t...
[ "def", "get_resources_of_type", "(", "network_id", ",", "type_id", ",", "*", "*", "kwargs", ")", ":", "nodes_with_type", "=", "db", ".", "DBSession", ".", "query", "(", "Node", ")", ".", "join", "(", "ResourceType", ")", ".", "filter", "(", "Node", ".", ...
59.363636
41.363636
def plot_posterior_contour(self, idx_param1=0, idx_param2=1, res1=100, res2=100, smoothing=0.01): """ Plots a contour of the kernel density estimation of a 2D projection of the current posterior distribution. :param int idx_param1: Parameter to be treated as :math:`x` when p...
[ "def", "plot_posterior_contour", "(", "self", ",", "idx_param1", "=", "0", ",", "idx_param2", "=", "1", ",", "res1", "=", "100", ",", "res2", "=", "100", ",", "smoothing", "=", "0.01", ")", ":", "return", "plt", ".", "contour", "(", "*", "self", ".",...
45.789474
27.578947
def editPlan(self, plan, new_plan): """ Edits a plan :param plan: Plan to edit :param new_plan: New plan :type plan: models.Plan :raises: FBchatException if request failed """ data = { "event_reminder_id": plan.uid, "delete": "fals...
[ "def", "editPlan", "(", "self", ",", "plan", ",", "new_plan", ")", ":", "data", "=", "{", "\"event_reminder_id\"", ":", "plan", ".", "uid", ",", "\"delete\"", ":", "\"false\"", ",", "\"date\"", ":", "new_plan", ".", "time", ",", "\"location_name\"", ":", ...
32.473684
13.421053
def on_train_begin(self, pbar, **kwargs:Any)->None: "Initialize optimizer and learner hyperparameters." setattr(pbar, 'clean_on_interrupt', True) self.learn.save('tmp') self.opt = self.learn.opt self.opt.lr = self.sched.start self.stop,self.best_loss = False,0. re...
[ "def", "on_train_begin", "(", "self", ",", "pbar", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "setattr", "(", "pbar", ",", "'clean_on_interrupt'", ",", "True", ")", "self", ".", "learn", ".", "save", "(", "'tmp'", ")", "self", ".", ...
42.625
7.875
def setup(): """ Creates required directories and copy checkers and reports. """ # # Check if dir is writable # if not os.access(AtomShieldsScanner.HOME, os.W_OK): # AtomShieldsScanner.HOME = os.path.expanduser("~/.atomshields") # AtomShieldsScanner.CHECKERS_DIR = os.path.join(AtomShieldsScanner.HOME...
[ "def", "setup", "(", ")", ":", "# # Check if dir is writable", "# if not os.access(AtomShieldsScanner.HOME, os.W_OK):", "# \tAtomShieldsScanner.HOME = os.path.expanduser(\"~/.atomshields\")", "# \tAtomShieldsScanner.CHECKERS_DIR = os.path.join(AtomShieldsScanner.HOME, \"checkers\")", "# \tAtomShie...
37.46875
28.34375
def memory_full(): """Check if the memory is too full for further caching.""" current_process = psutil.Process(os.getpid()) return (current_process.memory_percent() > config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)
[ "def", "memory_full", "(", ")", ":", "current_process", "=", "psutil", ".", "Process", "(", "os", ".", "getpid", "(", ")", ")", "return", "(", "current_process", ".", "memory_percent", "(", ")", ">", "config", ".", "MAXIMUM_CACHE_MEMORY_PERCENTAGE", ")" ]
45.2
9.6
def create_upload_url(self, upload_id, number, size, hash_value, hash_alg): """ Given an upload created by create_upload retrieve a url where we can upload a chunk. :param upload_id: uuid of the upload :param number: int incrementing number of the upload (1-based index) :param si...
[ "def", "create_upload_url", "(", "self", ",", "upload_id", ",", "number", ",", "size", ",", "hash_value", ",", "hash_alg", ")", ":", "if", "number", "<", "1", ":", "raise", "ValueError", "(", "\"Chunk number must be > 0\"", ")", "data", "=", "{", "\"number\"...
41.238095
18.47619
def clusterflow_pipelines_section(self): """ Generate HTML for section about pipelines, generated from information parsed from run files. """ data = dict() pids_guessed = '' for f,d in self.clusterflow_runfiles.items(): pid = d.get('pipeline_id', 'unknown') ...
[ "def", "clusterflow_pipelines_section", "(", "self", ")", ":", "data", "=", "dict", "(", ")", "pids_guessed", "=", "''", "for", "f", ",", "d", "in", "self", ".", "clusterflow_runfiles", ".", "items", "(", ")", ":", "pid", "=", "d", ".", "get", "(", "...
52.555556
23.6
def set_json(self, reason='', new_page=False): """Send the JSON from the cache to the usernotes wiki page. Arguments: reason: the change reason that will be posted to the wiki changelog (str) Raises: OverflowError if the new JSON data is greater than max_...
[ "def", "set_json", "(", "self", ",", "reason", "=", "''", ",", "new_page", "=", "False", ")", ":", "compressed_json", "=", "json", ".", "dumps", "(", "self", ".", "_compress_json", "(", "self", ".", "cached_json", ")", ")", "if", "len", "(", "compresse...
34.966667
20.633333
def update_buttons(self): """Updates the enable status of delete and reset buttons.""" current_scheme = self.current_scheme names = self.get_option("names") try: names.pop(names.index(u'Custom')) except ValueError: pass delete_enabled = current_sch...
[ "def", "update_buttons", "(", "self", ")", ":", "current_scheme", "=", "self", ".", "current_scheme", "names", "=", "self", ".", "get_option", "(", "\"names\"", ")", "try", ":", "names", ".", "pop", "(", "names", ".", "index", "(", "u'Custom'", ")", ")",...
39.727273
11.909091
def findAllNext(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear after this Tag in the document.""" return self._findAll(name, attrs, text, limit, self.nextGenerator, **kwar...
[ "def", "findAllNext", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "limit", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_findAll", "(", "name", ",", "attrs", ",", ...
53
11.833333
def from_pdb(cls, path, forcefield=None, loader=PDBFile, strict=True, **kwargs): """ Loads topology, positions and, potentially, velocities and vectors, from a PDB or PDBx file Parameters ---------- path : str Path to PDB/PDBx file forcefields : list ...
[ "def", "from_pdb", "(", "cls", ",", "path", ",", "forcefield", "=", "None", ",", "loader", "=", "PDBFile", ",", "strict", "=", "True", ",", "*", "*", "kwargs", ")", ":", "pdb", "=", "loader", "(", "path", ")", "box", "=", "kwargs", ".", "pop", "(...
41.548387
24.645161
def parse_selectors(model, fields=None, exclude=None, key_map=None, **options): """Validates fields are valid and maps pseudo-fields to actual fields for a given model class. """ fields = fields or DEFAULT_SELECTORS exclude = exclude or () key_map = key_map or {} validated = [] for alia...
[ "def", "parse_selectors", "(", "model", ",", "fields", "=", "None", ",", "exclude", "=", "None", ",", "key_map", "=", "None", ",", "*", "*", "options", ")", ":", "fields", "=", "fields", "or", "DEFAULT_SELECTORS", "exclude", "=", "exclude", "or", "(", ...
34.3
19.033333
def get_local_environnement(self): """ Mix the environment and the environment variables into a new local environment dictionary Note: We cannot just update the global os.environ because this would effect all other checks. :return: local environment variables :r...
[ "def", "get_local_environnement", "(", "self", ")", ":", "# Do not use copy.copy() here, as the resulting copy still", "# changes the real environment (it is still a os._Environment", "# instance).", "local_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "for", "local_v...
35.333333
16.666667
def __run_spark_submit(lane_yaml, dist_dir, spark_home, spark_args, silent): """ Submits the packaged application to spark using a `spark-submit` subprocess Parameters ---------- lane_yaml (str): Path to the YAML lane definition file dist_dir (str): Path to the directory where the packaged code...
[ "def", "__run_spark_submit", "(", "lane_yaml", ",", "dist_dir", ",", "spark_home", ",", "spark_args", ",", "silent", ")", ":", "# spark-submit binary", "cmd", "=", "[", "'spark-submit'", "if", "spark_home", "is", "None", "else", "os", ".", "path", ".", "join",...
35.9
25.1
def strToUtf8(value): ''' :type value: ``str`` :param value: value to encode ''' kassert.is_of_types(value, str) if sys.version_info < (3,): return ''.join([unichr(ord(x)) for x in value]) return value
[ "def", "strToUtf8", "(", "value", ")", ":", "kassert", ".", "is_of_types", "(", "value", ",", "str", ")", "if", "sys", ".", "version_info", "<", "(", "3", ",", ")", ":", "return", "''", ".", "join", "(", "[", "unichr", "(", "ord", "(", "x", ")", ...
25.444444
17.888889
def seqingroups(groups,seq): 'helper for contigsub. takes the list of lists returned by groupelts and an array to check.\ returns (groupindex,indexingroup,matchlen) of longest match or None if no match' if not (groups and seq): return None bestmatch=None,None,0 if any(len(g)<2 for g in groups): raise Val...
[ "def", "seqingroups", "(", "groups", ",", "seq", ")", ":", "if", "not", "(", "groups", "and", "seq", ")", ":", "return", "None", "bestmatch", "=", "None", ",", "None", ",", "0", "if", "any", "(", "len", "(", "g", ")", "<", "2", "for", "g", "in"...
50.7
22.9
def bfs_multi_edges(G, source, reverse=False, keys=True, data=False): """Produce edges in a breadth-first-search starting at source. ----- Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py by D. Eppstein, July 2004. """ from collections import deque from functools import partial if r...
[ "def", "bfs_multi_edges", "(", "G", ",", "source", ",", "reverse", "=", "False", ",", "keys", "=", "True", ",", "data", "=", "False", ")", ":", "from", "collections", "import", "deque", "from", "functools", "import", "partial", "if", "reverse", ":", "G",...
33.516129
14.258065
def color_percentages(file_list, n_tasks=9, file_name="color_percent.png", intensification_factor=1.2): """ Creates an image in which each cell in the avida grid is represented as a square of 9 sub-cells. Each of these 9 sub-cells represents a different task, and is colored such th...
[ "def", "color_percentages", "(", "file_list", ",", "n_tasks", "=", "9", ",", "file_name", "=", "\"color_percent.png\"", ",", "intensification_factor", "=", "1.2", ")", ":", "# Load data", "data", "=", "task_percentages", "(", "load_grid_data", "(", "file_list", ")...
44.021277
23.893617
def LDREX(cpu, dest, src, offset=None): """ LDREX loads data from memory. * If the physical address has the shared TLB attribute, LDREX tags the physical address as exclusive access for the current processor, and clears any exclusive access tag for this processor fo...
[ "def", "LDREX", "(", "cpu", ",", "dest", ",", "src", ",", "offset", "=", "None", ")", ":", "# TODO: add lock mechanism to underlying memory --GR, 2017-06-06", "cpu", ".", "_LDR", "(", "dest", ",", "src", ",", "32", ",", "False", ",", "offset", ")" ]
48
17.733333
def interval( value=None, unit='s', years=None, quarters=None, months=None, weeks=None, days=None, hours=None, minutes=None, seconds=None, milliseconds=None, microseconds=None, nanoseconds=None, ): """ Returns an interval literal Parameters ----------...
[ "def", "interval", "(", "value", "=", "None", ",", "unit", "=", "'s'", ",", "years", "=", "None", ",", "quarters", "=", "None", ",", "months", "=", "None", ",", "weeks", "=", "None", ",", "days", "=", "None", ",", "hours", "=", "None", ",", "minu...
24.602941
17.720588
def profile_settings_args_install_json(self, ij, required): """Return args based on install.json params. Args: ij (dict): The install.json contents. required (bool): If True only required args will be returned. Returns: dict: Dictionary of required or option...
[ "def", "profile_settings_args_install_json", "(", "self", ",", "ij", ",", "required", ")", ":", "profile_args", "=", "{", "}", "# add App specific args", "for", "p", "in", "ij", ".", "get", "(", "'params'", ")", "or", "[", "]", ":", "# TODO: fix this required ...
44.941176
23.147059
def get_drawing(self, drawing_id): """ Return the Drawing or raise a 404 if the drawing is unknown """ try: return self._drawings[drawing_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Drawing ID {} doesn't exist".format(drawing_id))
[ "def", "get_drawing", "(", "self", ",", "drawing_id", ")", ":", "try", ":", "return", "self", ".", "_drawings", "[", "drawing_id", "]", "except", "KeyError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "\"Drawing ID {} doesn't...
37.625
17.375
def asarray(self): """ Construct a numpy array from this column. Note that this creates a copy of the data, so modifications made to the array will *not* be recorded in the original document. """ # most codes don't use this feature, this is the only place # numpy is used here, and importing numpy can be ...
[ "def", "asarray", "(", "self", ")", ":", "# most codes don't use this feature, this is the only place", "# numpy is used here, and importing numpy can be", "# time-consuming, so we derfer the import until needed.", "import", "numpy", "try", ":", "dtype", "=", "ligolwtypes", ".", "T...
40.266667
18.133333
def replace_priority_class(self, name, body, **kwargs): # noqa: E501 """replace_priority_class # noqa: E501 replace the specified PriorityClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
[ "def", "replace_priority_class", "(", "self", ",", "name", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "sel...
57.041667
30.458333
def assign_unassigned_members(self, group_category_id, sync=None): """ Assign unassigned members. Assign all unassigned members as evenly as possible among the existing student groups. """ path = {} data = {} params = {} # REQUIRED - P...
[ "def", "assign_unassigned_members", "(", "self", ",", "group_category_id", ",", "sync", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - group_category_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"g...
43.583333
28.833333
def _transform_row_wrapper(self, row): """ Transforms a single source row. :param dict[str|str] row: The source row. """ self._count_total += 1 try: # Transform the naturals keys in line to technical keys. in_row = copy.copy(row) out_...
[ "def", "_transform_row_wrapper", "(", "self", ",", "row", ")", ":", "self", ".", "_count_total", "+=", "1", "try", ":", "# Transform the naturals keys in line to technical keys.", "in_row", "=", "copy", ".", "copy", "(", "row", ")", "out_row", "=", "{", "}", "...
32.512821
13.74359
def open_connection(self): """Open an sqlite connection to the metadata database. By default the metadata database will be used in the plugin dir, unless an explicit path has been set using setmetadataDbPath, or overridden in QSettings. If the db does not exist it will be create...
[ "def", "open_connection", "(", "self", ")", ":", "self", ".", "connection", "=", "None", "base_directory", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "metadata_db_path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "base_direct...
38.08
20.68
def _check_classmethod_declaration(self, node): """Checks for uses of classmethod() or staticmethod() When a @classmethod or @staticmethod decorator should be used instead. A message will be emitted only if the assignment is at a class scope and only if the classmethod's argument belong...
[ "def", "_check_classmethod_declaration", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ".", "value", ",", "astroid", ".", "Call", ")", ":", "return", "# check the function called is \"classmethod\" or \"staticmethod\"", "func", "=", "no...
36.315789
20
def insert_paragraph_before(self, text=None, style=None): """ Return a newly created paragraph, inserted directly before this paragraph. If *text* is supplied, the new paragraph contains that text in a single run. If *style* is provided, that style is assigned to the new paragrap...
[ "def", "insert_paragraph_before", "(", "self", ",", "text", "=", "None", ",", "style", "=", "None", ")", ":", "paragraph", "=", "self", ".", "_insert_paragraph_before", "(", ")", "if", "text", ":", "paragraph", ".", "add_run", "(", "text", ")", "if", "st...
39.846154
15.384615
def get_sos_decomposition(sdp, y_mat=None, threshold=0.0): """Given a solution of the dual problem, it returns the SOS decomposition. :param sdp: The SDP relaxation to be solved. :type sdp: :class:`ncpol2sdpa.sdp`. :param y_mat: Optional parameter providing the dual solution of the ...
[ "def", "get_sos_decomposition", "(", "sdp", ",", "y_mat", "=", "None", ",", "threshold", "=", "0.0", ")", ":", "if", "len", "(", "sdp", ".", "monomial_sets", ")", "!=", "1", ":", "raise", "Exception", "(", "\"Cannot automatically match primal and dual \"", "+"...
42.641509
15.962264
def resolve_type(arg): # type: (object) -> InternalType """ Resolve object to one of our internal collection types or generic built-in type. Args: arg: object to resolve """ arg_type = type(arg) if arg_type == list: assert isinstance(arg, list) # this line helps mypy figure...
[ "def", "resolve_type", "(", "arg", ")", ":", "# type: (object) -> InternalType", "arg_type", "=", "type", "(", "arg", ")", "if", "arg_type", "==", "list", ":", "assert", "isinstance", "(", "arg", ",", "list", ")", "# this line helps mypy figure out types", "sample...
38.384615
14.076923
def market_close(self, session, mins) -> Session: """ Time intervals for market close Args: session: [allday, day, am, pm, night] mins: mintues before close Returns: Session of start_time and end_time """ if session not in self.exch: ...
[ "def", "market_close", "(", "self", ",", "session", ",", "mins", ")", "->", "Session", ":", "if", "session", "not", "in", "self", ".", "exch", ":", "return", "SessNA", "end_time", "=", "self", ".", "exch", "[", "session", "]", "[", "-", "1", "]", "...
30.928571
14.214286
def get(self, targetId): """ Yields the analysed wav data. :param targetId: :return: """ result = self._targetController.analyse(targetId) if result: if len(result) == 2: if result[1] == 404: return result ...
[ "def", "get", "(", "self", ",", "targetId", ")", ":", "result", "=", "self", ".", "_targetController", ".", "analyse", "(", "targetId", ")", "if", "result", ":", "if", "len", "(", "result", ")", "==", "2", ":", "if", "result", "[", "1", "]", "==", ...
29
14.411765
def sources_list(ruby=None, runas=None, gem_bin=None): ''' List the configured gem sources. :param gem_bin: string : None Full path to ``gem`` binary to use. :param ruby: string : None If RVM or rbenv are installed, the ruby version and gemset to use. Ignored if ``gem_bin`` is s...
[ "def", "sources_list", "(", "ruby", "=", "None", ",", "runas", "=", "None", ",", "gem_bin", "=", "None", ")", ":", "ret", "=", "_gem", "(", "[", "'sources'", "]", ",", "ruby", ",", "gem_bin", "=", "gem_bin", ",", "runas", "=", "runas", ")", "return...
29.05
20.25
def get_fitness(self, solution): """Return fitness for the given solution.""" return self._fitness_function(solution, *self._fitness_args, **self._fitness_kwargs)
[ "def", "get_fitness", "(", "self", ",", "solution", ")", ":", "return", "self", ".", "_fitness_function", "(", "solution", ",", "*", "self", ".", "_fitness_args", ",", "*", "*", "self", ".", "_fitness_kwargs", ")" ]
53.25
14.25
def insert_with_id(obj): """ Generates a unique ID for the supplied legislator/committee/bill and inserts it into the appropriate collection. """ if '_id' in obj: raise ValueError("object already has '_id' field") # add created_at/updated_at on insert obj['created_at'] = datetime.da...
[ "def", "insert_with_id", "(", "obj", ")", ":", "if", "'_id'", "in", "obj", ":", "raise", "ValueError", "(", "\"object already has '_id' field\"", ")", "# add created_at/updated_at on insert", "obj", "[", "'created_at'", "]", "=", "datetime", ".", "datetime", ".", ...
29.442308
18.365385
def build(self, builder): """ Build XML by appending to builder """ builder.start("Annotations") # populate the flags for annotation in self.annotations: annotation.build(builder) builder.end("Annotations")
[ "def", "build", "(", "self", ",", "builder", ")", ":", "builder", ".", "start", "(", "\"Annotations\"", ")", "# populate the flags", "for", "annotation", "in", "self", ".", "annotations", ":", "annotation", ".", "build", "(", "builder", ")", "builder", ".", ...
24.181818
11.272727
def connect_to(self, service_name, **kwargs): """ Shortcut method to make instantiating the ``Connection`` classes easier. Forwards ``**kwargs`` like region, keys, etc. on to the constructor. :param service_name: A string that specifies the name of the desired servi...
[ "def", "connect_to", "(", "self", ",", "service_name", ",", "*", "*", "kwargs", ")", ":", "service_class", "=", "self", ".", "get_connection", "(", "service_name", ")", "return", "service_class", ".", "connect_to", "(", "*", "*", "kwargs", ")" ]
37.6
21.6
def walkFlattenChilds(self) -> Generator[ Union[Tuple[Tuple[int, int], TransTmpl], 'OneOfTransaction'], None, None]: """ :return: generator of generators of tuples ((startBitAddress, endBitAddress), TransTmpl instance) for each possiblility in this transac...
[ "def", "walkFlattenChilds", "(", "self", ")", "->", "Generator", "[", "Union", "[", "Tuple", "[", "Tuple", "[", "int", ",", "int", "]", ",", "TransTmpl", "]", ",", "'OneOfTransaction'", "]", ",", "None", ",", "None", "]", ":", "for", "p", "in", "self...
44.363636
12.545455
def StrToInt(input_string, bitlength): """ Return True if the concrete value of the input_string ends with suffix otherwise false. :param input_string: the string we want to transform in an integer :param bitlength: bitlength of the bitvector representing the index of the substring :return BVV...
[ "def", "StrToInt", "(", "input_string", ",", "bitlength", ")", ":", "try", ":", "return", "BVV", "(", "int", "(", "input_string", ".", "value", ")", ",", "bitlength", ")", "except", "ValueError", ":", "return", "BVV", "(", "-", "1", ",", "bitlength", "...
40.466667
26.066667
def python_sidebar_help(python_input): """ Create the `Layout` for the help text for the current item in the sidebar. """ token = 'class:sidebar.helptext' def get_current_description(): """ Return the description of the selected option. """ i = 0 for category...
[ "def", "python_sidebar_help", "(", "python_input", ")", ":", "token", "=", "'class:sidebar.helptext'", "def", "get_current_description", "(", ")", ":", "\"\"\"\n Return the description of the selected option.\n \"\"\"", "i", "=", "0", "for", "category", "in", ...
31.321429
14.321429
def read_lsm_eventlist(fh): """Read LSM events from file and return as list of (time, type, text).""" count = struct.unpack('<II', fh.read(8))[1] events = [] while count > 0: esize, etime, etype = struct.unpack('<IdI', fh.read(16)) etext = bytes2str(stripnull(fh.read(esize - 16))) ...
[ "def", "read_lsm_eventlist", "(", "fh", ")", ":", "count", "=", "struct", ".", "unpack", "(", "'<II'", ",", "fh", ".", "read", "(", "8", ")", ")", "[", "1", "]", "events", "=", "[", "]", "while", "count", ">", "0", ":", "esize", ",", "etime", "...
38.6
15.5
def _sanitize_acronyms(unsafe_acronyms): """ Check acronyms against regex. Normalize valid acronyms to upper-case. If an invalid acronym is encountered raise InvalidAcronymError. """ valid_acronym = regex.compile(u'^[\p{Ll}\p{Lu}\p{Nd}]+$') acronyms = [] for a in unsafe_acronyms: ...
[ "def", "_sanitize_acronyms", "(", "unsafe_acronyms", ")", ":", "valid_acronym", "=", "regex", ".", "compile", "(", "u'^[\\p{Ll}\\p{Lu}\\p{Nd}]+$'", ")", "acronyms", "=", "[", "]", "for", "a", "in", "unsafe_acronyms", ":", "if", "valid_acronym", ".", "match", "("...
29.866667
12.533333
def sign(self): """Signature function""" self.verify_integrity() if session.get('u2f_sign_required', False): if request.method == 'GET': response = self.get_signature_challenge() if response['status'] == 'ok': return jsoni...
[ "def", "sign", "(", "self", ")", ":", "self", ".", "verify_integrity", "(", ")", "if", "session", ".", "get", "(", "'u2f_sign_required'", ",", "False", ")", ":", "if", "request", ".", "method", "==", "'GET'", ":", "response", "=", "self", ".", "get_sig...
33.727273
18.181818