text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def contains(polygon, point): """ Tests whether point lies within the polygon """ in_hole = functools.reduce( lambda P, Q: P and Q, [interior.covers(point) for interior in polygon.interiors] ) if polygon.interiors else False return polygon.covers(p...
[ "def", "contains", "(", "polygon", ",", "point", ")", ":", "in_hole", "=", "functools", ".", "reduce", "(", "lambda", "P", ",", "Q", ":", "P", "and", "Q", ",", "[", "interior", ".", "covers", "(", "point", ")", "for", "interior", "in", "polygon", "...
37
8.555556
def from_json(cls, json_str): """Deserialize Vocab object from json string. Parameters ---------- json_str : str Serialized json string of a Vocab object. Returns ------- Vocab """ vocab_dict = json.loads(json_str) unknown_t...
[ "def", "from_json", "(", "cls", ",", "json_str", ")", ":", "vocab_dict", "=", "json", ".", "loads", "(", "json_str", ")", "unknown_token", "=", "vocab_dict", ".", "get", "(", "'unknown_token'", ")", "vocab", "=", "cls", "(", "unknown_token", "=", "unknown_...
35.222222
21.37037
def merge_qpoints(self, workdir, files_to_merge, out_prefix): """ Execute mrgscr inside directory `workdir` to merge `files_to_merge`. Produce new file with prefix `out_prefix` """ # We work with absolute paths. files_to_merge = [os.path.abspath(s) for s in list_strings(f...
[ "def", "merge_qpoints", "(", "self", ",", "workdir", ",", "files_to_merge", ",", "out_prefix", ")", ":", "# We work with absolute paths.", "files_to_merge", "=", "[", "os", ".", "path", ".", "abspath", "(", "s", ")", "for", "s", "in", "list_strings", "(", "f...
38.157895
23.473684
def getAllConnectedInterface(): """ returns all the connected devices which matches PyUSB.vid/PyUSB.pid. returns an array of PyUSB (Interface) objects """ # find all devices matching the vid/pid specified dev = usb.core.find(idVendor=0x2886, idProduct=0x0007) if ...
[ "def", "getAllConnectedInterface", "(", ")", ":", "# find all devices matching the vid/pid specified", "dev", "=", "usb", ".", "core", ".", "find", "(", "idVendor", "=", "0x2886", ",", "idProduct", "=", "0x0007", ")", "if", "not", "dev", ":", "logging", ".", "...
28.075472
18.358491
def _draw_cursor(self, dc, grid, row, col, pen=None, brush=None): """Draws cursor as Rectangle in lower right corner""" # If in full screen mode draw no cursor if grid.main_window.IsFullScreen(): return key = row, col, grid.current_table rect = ...
[ "def", "_draw_cursor", "(", "self", ",", "dc", ",", "grid", ",", "row", ",", "col", ",", "pen", "=", "None", ",", "brush", "=", "None", ")", ":", "# If in full screen mode draw no cursor", "if", "grid", ".", "main_window", ".", "IsFullScreen", "(", ")", ...
30.38806
17.835821
def parse_ini_file(self, path): """Parse ini file at ``path`` and return dict.""" cfgobj = ConfigObj(path, list_values=False) def extract_section(namespace, d): cfg = {} for key, val in d.items(): if isinstance(d[key], dict): cfg.updat...
[ "def", "parse_ini_file", "(", "self", ",", "path", ")", ":", "cfgobj", "=", "ConfigObj", "(", "path", ",", "list_values", "=", "False", ")", "def", "extract_section", "(", "namespace", ",", "d", ")", ":", "cfg", "=", "{", "}", "for", "key", ",", "val...
34.333333
18.266667
def _compute_weights(self): """ Computes the weights for the scaled unscented Kalman filter. """ n = self.n c = 1. / (n + 1) self.Wm = np.full(n + 1, c) self.Wc = self.Wm
[ "def", "_compute_weights", "(", "self", ")", ":", "n", "=", "self", ".", "n", "c", "=", "1.", "/", "(", "n", "+", "1", ")", "self", ".", "Wm", "=", "np", ".", "full", "(", "n", "+", "1", ",", "c", ")", "self", ".", "Wc", "=", "self", ".",...
29.285714
15.857143
def authenticate(self, req_data, identifier: Optional[str]=None, signature: Optional[str]=None, threshold: Optional[int] = None, verifier: Verifier=DidVerifier): """ Prepares the data to be serialised for signing and then verifies the signature :...
[ "def", "authenticate", "(", "self", ",", "req_data", ",", "identifier", ":", "Optional", "[", "str", "]", "=", "None", ",", "signature", ":", "Optional", "[", "str", "]", "=", "None", ",", "threshold", ":", "Optional", "[", "int", "]", "=", "None", "...
43.756757
20.513514
def save_form(self, request, form, change): """ Don't show links in the sitemap. """ obj = form.save(commit=False) if not obj.id and "in_sitemap" not in form.fields: obj.in_sitemap = False return super(LinkAdmin, self).save_form(request, form, change)
[ "def", "save_form", "(", "self", ",", "request", ",", "form", ",", "change", ")", ":", "obj", "=", "form", ".", "save", "(", "commit", "=", "False", ")", "if", "not", "obj", ".", "id", "and", "\"in_sitemap\"", "not", "in", "form", ".", "fields", ":...
38
7.5
def _compute_and_write_row_block( i, left_matrix, right_matrix, train_indices_out_path, test_indices_out_path, remove_empty_rows): """Compute row block (shard) of expansion for row i of the left_matrix. Compute a shard of the randomized Kronecker product and dump it on the fly. A standard Kronecker produ...
[ "def", "_compute_and_write_row_block", "(", "i", ",", "left_matrix", ",", "right_matrix", ",", "train_indices_out_path", ",", "test_indices_out_path", ",", "remove_empty_rows", ")", ":", "kron_blocks", "=", "[", "]", "num_rows", "=", "0", "num_removed_rows", "=", "0...
42.174825
23.251748
def sortByColumnName(self, name, order=QtCore.Qt.AscendingOrder): """ Sorts the tree by the inputed column name's index and the given order. :param name | <str> order | <QtCore.Qt.SortOrder> """ self.setSortingEnabled(True) s...
[ "def", "sortByColumnName", "(", "self", ",", "name", ",", "order", "=", "QtCore", ".", "Qt", ".", "AscendingOrder", ")", ":", "self", ".", "setSortingEnabled", "(", "True", ")", "self", ".", "sortByColumn", "(", "self", ".", "column", "(", "name", ")", ...
39.333333
14
def rasterize(self, dest_resolution, *, polygonize_width=0, crs=WEB_MERCATOR_CRS, fill_value=None, bounds=None, dtype=None, **polygonize_kwargs): """Binarize a FeatureCollection and produce a raster with the target resolution. Parameters ---------- dest_resolution: flo...
[ "def", "rasterize", "(", "self", ",", "dest_resolution", ",", "*", ",", "polygonize_width", "=", "0", ",", "crs", "=", "WEB_MERCATOR_CRS", ",", "fill_value", "=", "None", ",", "bounds", "=", "None", ",", "dtype", "=", "None", ",", "*", "*", "polygonize_k...
43.4375
27.525
def __send_command( self, name, args=None, withcontent=False, extralines=None, nblines=-1): """Send a command to the server. If args is not empty, we concatenate the given command with the content of this list. If extralines is not empty, they are sent one by one...
[ "def", "__send_command", "(", "self", ",", "name", ",", "args", "=", "None", ",", "withcontent", "=", "False", ",", "extralines", "=", "None", ",", "nblines", "=", "-", "1", ")", ":", "tosend", "=", "name", ".", "encode", "(", "\"utf-8\"", ")", "if",...
37.35
19.225
def resize(self, size): """Return a new Image instance with the given size.""" return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS))
[ "def", "resize", "(", "self", ",", "size", ")", ":", "return", "Image", "(", "self", ".", "pil_image", ".", "resize", "(", "size", ",", "PIL", ".", "Image", ".", "ANTIALIAS", ")", ")" ]
51.666667
15.666667
def _commandline_join(self, tokens): """Formats a list of tokens as a shell command This seems to be a repeated pattern; may be useful in superclass. """ commands = filter(None, map(str, tokens)) return self._command_delimiter.join(commands).strip()
[ "def", "_commandline_join", "(", "self", ",", "tokens", ")", ":", "commands", "=", "filter", "(", "None", ",", "map", "(", "str", ",", "tokens", ")", ")", "return", "self", ".", "_command_delimiter", ".", "join", "(", "commands", ")", ".", "strip", "("...
36.375
14.5
def assert_empty(self, class_name: str): """ Raises a ``ConfigurationError`` if ``self.params`` is not empty. We take ``class_name`` as an argument so that the error message gives some idea of where an error happened, if there was one. ``class_name`` should be the name of the `calling`...
[ "def", "assert_empty", "(", "self", ",", "class_name", ":", "str", ")", ":", "if", "self", ".", "params", ":", "raise", "ConfigurationError", "(", "\"Extra parameters passed to {}: {}\"", ".", "format", "(", "class_name", ",", "self", ".", "params", ")", ")" ]
58.111111
28.777778
def recv_connect(self, version=None, support=None, session=None): """DDP connect handler.""" del session # Meteor doesn't even use this! if self.connection is not None: raise MeteorError( 400, 'Session already established.', self.connection.connection...
[ "def", "recv_connect", "(", "self", ",", "version", "=", "None", ",", "support", "=", "None", ",", "session", "=", "None", ")", ":", "del", "session", "# Meteor doesn't even use this!", "if", "self", ".", "connection", "is", "not", "None", ":", "raise", "M...
43.8
14
def calculate_backend(name_from_env, backends=None): """ Calculates which backend to use with the following algorithm: - Try to read the GOLESS_BACKEND environment variable. Usually 'gevent' or 'stackless'. If a value is set but no backend is available or it fails to be created, this func...
[ "def", "calculate_backend", "(", "name_from_env", ",", "backends", "=", "None", ")", ":", "if", "backends", "is", "None", ":", "backends", "=", "_default_backends", "if", "name_from_env", ":", "if", "name_from_env", "not", "in", "backends", ":", "raise", "Runt...
38.785714
16.785714
def timeout(self, timeout): """ Set request timeout in seconds (or fractions of a second) """ if timeout is None: self._timeout = None # no timeout return self._timeout = float(timeout)
[ "def", "timeout", "(", "self", ",", "timeout", ")", ":", "if", "timeout", "is", "None", ":", "self", ".", "_timeout", "=", "None", "# no timeout", "return", "self", ".", "_timeout", "=", "float", "(", "timeout", ")" ]
32.714286
13.714286
def calc_observable_fraction(self,distance_modulus): """ Calculated observable fraction within each pixel of the target region. """ # This is the observable fraction after magnitude cuts in each # pixel of the ROI. observable_fraction = self.isochrone.observableFraction(...
[ "def", "calc_observable_fraction", "(", "self", ",", "distance_modulus", ")", ":", "# This is the observable fraction after magnitude cuts in each ", "# pixel of the ROI.", "observable_fraction", "=", "self", ".", "isochrone", ".", "observableFraction", "(", "self", ".", "mas...
44.076923
14.230769
def available_state(self, state: State) -> Tuple[State, ...]: """ Return the state reachable from a given state. """ result = [] for gene in self.genes: result.extend(self.available_state_for_gene(gene, state)) if len(result) > 1 and state in result: result.remove...
[ "def", "available_state", "(", "self", ",", "state", ":", "State", ")", "->", "Tuple", "[", "State", ",", "...", "]", ":", "result", "=", "[", "]", "for", "gene", "in", "self", ".", "genes", ":", "result", ".", "extend", "(", "self", ".", "availabl...
43.625
13.375
def get_catalog(self, locale): """Create Django translation catalogue for `locale`.""" with translation.override(locale): translation_engine = DjangoTranslation(locale, domain=self.domain, localedirs=self.paths) trans_cat = translation_engine._catalog trans_fallback_...
[ "def", "get_catalog", "(", "self", ",", "locale", ")", ":", "with", "translation", ".", "override", "(", "locale", ")", ":", "translation_engine", "=", "DjangoTranslation", "(", "locale", ",", "domain", "=", "self", ".", "domain", ",", "localedirs", "=", "...
49.444444
26.888889
def kwinsert(clas,pool_or_cursor,**kwargs): "kwargs version of insert" returning = kwargs.pop('returning',None) fields,vals = zip(*kwargs.items()) # note: don't do SpecialField resolution here; clas.insert takes care of it return clas.insert(pool_or_cursor,fields,vals,returning=returning)
[ "def", "kwinsert", "(", "clas", ",", "pool_or_cursor", ",", "*", "*", "kwargs", ")", ":", "returning", "=", "kwargs", ".", "pop", "(", "'returning'", ",", "None", ")", "fields", ",", "vals", "=", "zip", "(", "*", "kwargs", ".", "items", "(", ")", "...
51.5
14.833333
async def field(self, elem=None, elem_type=None, params=None, obj=None): """ Archive field :param elem: :param elem_type: :param params: :param obj: :return: """ elem_type = elem_type if elem_type else elem.__class__ fvalue = None ...
[ "async", "def", "field", "(", "self", ",", "elem", "=", "None", ",", "elem_type", "=", "None", ",", "params", "=", "None", ",", "obj", "=", "None", ")", ":", "elem_type", "=", "elem_type", "if", "elem_type", "else", "elem", ".", "__class__", "fvalue", ...
42.27451
30.705882
def project_get(project_id=None, name=None, profile=None, **connection_args): ''' Return a specific projects (keystone project-get) Overrides keystone tenant-get form api V2. For keystone api V3 only. .. versionadded:: 2016.11.0 project_id The project id. name The project ...
[ "def", "project_get", "(", "project_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "if", "_OS_IDENTITY_API_VERSION", ">", ...
27.483871
27.677419
def prepare_samples(job, fastqs, univ_options): """ This module will accept a dict object holding the 3 input prefixes and the patient id and will attempt to store the fastqs to the jobstore. The input files must satisfy the following 1. File extensions can only be fastq or fq (.gz is also allowed) ...
[ "def", "prepare_samples", "(", "job", ",", "fastqs", ",", "univ_options", ")", ":", "job", ".", "fileStore", ".", "logToMaster", "(", "'Downloading Inputs for %s'", "%", "univ_options", "[", "'patient'", "]", ")", "allowed_samples", "=", "{", "'tumor_dna_fastq_pre...
53.039474
23.828947
def f_effective_irradiance(poa_direct, poa_diffuse, am_abs, aoi, module): """ Calculate effective irradiance for Sandia Performance model :param poa_direct: plane of array direct irradiance [W/m**2] :param poa_diffuse: plane of array diffuse irradiance [W/m**2] :param am_abs: absolute air mass [dim...
[ "def", "f_effective_irradiance", "(", "poa_direct", ",", "poa_diffuse", ",", "am_abs", ",", "aoi", ",", "module", ")", ":", "Ee", "=", "pvlib", ".", "pvsystem", ".", "sapm_effective_irradiance", "(", "poa_direct", ",", "poa_diffuse", ",", "am_abs", ",", "aoi",...
46.642857
18.785714
def _do_timeout_for_query(self, timeout, datapath): """the process when the QUERY from the querier timeout expired.""" dpid = datapath.id hub.sleep(timeout) outport = self._to_querier[dpid]['port'] remove_dsts = [] for dst in self._to_hosts[dpid]: if not sel...
[ "def", "_do_timeout_for_query", "(", "self", ",", "timeout", ",", "datapath", ")", ":", "dpid", "=", "datapath", ".", "id", "hub", ".", "sleep", "(", "timeout", ")", "outport", "=", "self", ".", "_to_querier", "[", "dpid", "]", "[", "'port'", "]", "rem...
39.111111
16.555556
def remove_task_db(self, fid, force=False): '''将任务从数据库中删除''' self.remove_slice_db(fid) sql = 'DELETE FROM upload WHERE fid=?' self.cursor.execute(sql, [fid, ]) self.check_commit(force=force)
[ "def", "remove_task_db", "(", "self", ",", "fid", ",", "force", "=", "False", ")", ":", "self", ".", "remove_slice_db", "(", "fid", ")", "sql", "=", "'DELETE FROM upload WHERE fid=?'", "self", ".", "cursor", ".", "execute", "(", "sql", ",", "[", "fid", "...
37.5
5.833333
def from_etree(tree): """Constructs an executable form a given ElementTree structure. :param tree: :type tree: xml.etree.ElementTree.ElementTree :rtype: Executable """ exe = Executable(tree) exe.category = tree.findtext('category') exe.version = tree.fi...
[ "def", "from_etree", "(", "tree", ")", ":", "exe", "=", "Executable", "(", "tree", ")", "exe", ".", "category", "=", "tree", ".", "findtext", "(", "'category'", ")", "exe", ".", "version", "=", "tree", ".", "findtext", "(", "'version'", ")", "exe", "...
34.068966
16.965517
def punch2reader(rh, userid, fileLoc, spoolClass): """ Punch a file to a virtual reader of the specified virtual machine. Input: Request Handle - for general use and to hold the results userid - userid of the virtual machine fileLoc - File to send spoolClass -...
[ "def", "punch2reader", "(", "rh", ",", "userid", ",", "fileLoc", ",", "spoolClass", ")", ":", "rh", ".", "printSysLog", "(", "\"Enter punch2reader.punchFile\"", ")", "results", "=", "{", "}", "# Setting rc to time out rc code as default and its changed during runtime", ...
44.187135
16.385965
def write_cell(self, cell): """ Write the specified cell to the file. Parameters ---------- cell : ``Cell`` Cell to be written. Notes ----- Only the specified cell is written. Dependencies must be manually included. Returns ...
[ "def", "write_cell", "(", "self", ",", "cell", ")", ":", "self", ".", "_outfile", ".", "write", "(", "cell", ".", "to_gds", "(", "self", ".", "_res", ")", ")", "return", "self" ]
21.52381
19.619048
def ok(self, *msg): """ Prints a message with an ok prefix """ label = colors.green("OK") self._msg(label, *msg)
[ "def", "ok", "(", "self", ",", "*", "msg", ")", ":", "label", "=", "colors", ".", "green", "(", "\"OK\"", ")", "self", ".", "_msg", "(", "label", ",", "*", "msg", ")" ]
24.5
6.5
def get_hidden_signups(self): """ Return a list of Users who are *not* in the All Students list but have signed up for an activity. This is usually a list of signups for z-Withdrawn from TJ """ return EighthSignup.objects.filter(scheduled_activity__block=self).exclude(user__in=User.objects.g...
[ "def", "get_hidden_signups", "(", "self", ")", ":", "return", "EighthSignup", ".", "objects", ".", "filter", "(", "scheduled_activity__block", "=", "self", ")", ".", "exclude", "(", "user__in", "=", "User", ".", "objects", ".", "get_students", "(", ")", ")" ...
82.75
22.75
def transform_locus(region, window_center, window_size): """ transform an input genomic region into one suitable for the profile. :param region: input region to transform. :param window_center: which part of the input region to center on. :param window_size: how large the resultant region should ...
[ "def", "transform_locus", "(", "region", ",", "window_center", ",", "window_size", ")", ":", "if", "window_center", "==", "CENTRE", ":", "region", ".", "transform_center", "(", "window_size", ")", "else", ":", "raise", "ValueError", "(", "\"Don't know how to do th...
42.4375
19.0625
def to_import(self): # type: () -> ImportEndpoint """ Converts an EndpointDescription bean to an ImportEndpoint :return: An ImportEndpoint bean """ # Properties properties = self.get_properties() # Framework UUID fw_uid = self.get_framework_uuid(...
[ "def", "to_import", "(", "self", ")", ":", "# type: () -> ImportEndpoint", "# Properties", "properties", "=", "self", ".", "get_properties", "(", ")", "# Framework UUID", "fw_uid", "=", "self", ".", "get_framework_uuid", "(", ")", "# Endpoint name", "try", ":", "#...
25.057143
18.885714
def _get_sd(file_descr): """ Get streamdescriptor matching file_descr fileno. :param file_descr: file object :return: StreamDescriptor or None """ for stream_descr in NonBlockingStreamReader._streams: if file_descr == stream_descr.stream.fileno(): ...
[ "def", "_get_sd", "(", "file_descr", ")", ":", "for", "stream_descr", "in", "NonBlockingStreamReader", ".", "_streams", ":", "if", "file_descr", "==", "stream_descr", ".", "stream", ".", "fileno", "(", ")", ":", "return", "stream_descr", "return", "None" ]
32.181818
12.727273
def config(env=DEFAULT_ENV, default=None, **overrides): """Returns configured REDIS dictionary from REDIS_URL.""" config = {} s = os.environ.get(env, default) if s: config = parse(s) overrides = dict([(k.upper(), v) for k, v in overrides.items()]) config.update(overrides) retur...
[ "def", "config", "(", "env", "=", "DEFAULT_ENV", ",", "default", "=", "None", ",", "*", "*", "overrides", ")", ":", "config", "=", "{", "}", "s", "=", "os", ".", "environ", ".", "get", "(", "env", ",", "default", ")", "if", "s", ":", "config", ...
20.933333
26.2
def wrap_error( self, data, renderer_context, keys_are_fields, issue_is_title): """Convert error native data to the JSON API Error format JSON API has a different format for errors, but Django REST Framework doesn't have a separate rendering path for errors. This results in ...
[ "def", "wrap_error", "(", "self", ",", "data", ",", "renderer_context", ",", "keys_are_fields", ",", "issue_is_title", ")", ":", "response", "=", "renderer_context", ".", "get", "(", "\"response\"", ",", "None", ")", "status_code", "=", "str", "(", "response",...
38.452381
20.166667
def cache_backend(self): """ Get the cache backend Returns ~~~~~~~ Django cache backend """ if not hasattr(self, '_cache_backend'): if hasattr(django.core.cache, 'caches'): self._cache_backend = django.core.cache.caches[_cache_name] ...
[ "def", "cache_backend", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_cache_backend'", ")", ":", "if", "hasattr", "(", "django", ".", "core", ".", "cache", ",", "'caches'", ")", ":", "self", ".", "_cache_backend", "=", "django", "...
27.25
20.625
def visit_arg(self, node, parent): """visit an arg node by returning a fresh AssName instance""" return self.visit_assignname(node, parent, node.arg)
[ "def", "visit_arg", "(", "self", ",", "node", ",", "parent", ")", ":", "return", "self", ".", "visit_assignname", "(", "node", ",", "parent", ",", "node", ".", "arg", ")" ]
54.333333
8.666667
async def api_call(self, verb, action, params=None, add_authorization_token=True, retry=False): """Send api call.""" if add_authorization_token and not self.token: await self.refresh_token() try: return await self._api_call_impl(verb, action, params, add_authorization_to...
[ "async", "def", "api_call", "(", "self", ",", "verb", ",", "action", ",", "params", "=", "None", ",", "add_authorization_token", "=", "True", ",", "retry", "=", "False", ")", ":", "if", "add_authorization_token", "and", "not", "self", ".", "token", ":", ...
45.923077
23
def ToJson(self): """ Convert object members to a dictionary that can be parsed as JSON. Returns: dict: """ json = super(Block, self).ToJson() if self.Transactions[0] and isinstance(self.Transactions[0], str): json['tx'] = ['0x%s' % tx for tx in ...
[ "def", "ToJson", "(", "self", ")", ":", "json", "=", "super", "(", "Block", ",", "self", ")", ".", "ToJson", "(", ")", "if", "self", ".", "Transactions", "[", "0", "]", "and", "isinstance", "(", "self", ".", "Transactions", "[", "0", "]", ",", "s...
33.133333
23.266667
def passed(self): """ Return all the passing testcases :return: """ return [test for test in self.all() if not test.failed() and not test.skipped()]
[ "def", "passed", "(", "self", ")", ":", "return", "[", "test", "for", "test", "in", "self", ".", "all", "(", ")", "if", "not", "test", ".", "failed", "(", ")", "and", "not", "test", ".", "skipped", "(", ")", "]" ]
30.5
15.833333
def getModName(self): ''' Return the lowercased name of this module. Notes: This pulls the ``mod_name`` attribute on the class. This allows an implementer to set a arbitrary name for the module. If this attribute is not set, it defaults to ``self...
[ "def", "getModName", "(", "self", ")", ":", "ret", "=", "self", ".", "mod_name", "if", "ret", "is", "None", ":", "ret", "=", "self", ".", "__class__", ".", "__name__", "return", "ret", ".", "lower", "(", ")" ]
31.555556
21.888889
def parse_checkM_tables(tables): """ convert checkM genome info tables to dictionary """ g2info = {} for table in tables: for line in open(table): line = line.strip().split('\t') if line[0].startswith('Bin Id'): header = line header[8] ...
[ "def", "parse_checkM_tables", "(", "tables", ")", ":", "g2info", "=", "{", "}", "for", "table", "in", "tables", ":", "for", "line", "in", "open", "(", "table", ")", ":", "line", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "'\\t'", ")", ...
35.285714
9.857143
def raw(self): """ Get the raw value of the match, without using hardcoded value nor formatter. :return: :rtype: """ if self.input_string: return self.input_string[self.raw_start:self.raw_end] return None
[ "def", "raw", "(", "self", ")", ":", "if", "self", ".", "input_string", ":", "return", "self", ".", "input_string", "[", "self", ".", "raw_start", ":", "self", ".", "raw_end", "]", "return", "None" ]
29.333333
19.555556
def _compute_errors(self): """ Compute parameter errors based on the diagonal of the covariance matrix of the four harmonic coefficients for harmonics n=1 and n=2. """ try: coeffs = fit_first_and_second_harmonics(self.sample.values[0], ...
[ "def", "_compute_errors", "(", "self", ")", ":", "try", ":", "coeffs", "=", "fit_first_and_second_harmonics", "(", "self", ".", "sample", ".", "values", "[", "0", "]", ",", "self", ".", "sample", ".", "values", "[", "2", "]", ")", "covariance", "=", "c...
48.189189
22.567568
def accounts(self): """ Return an account reference :param account_id: :param accounts_password: The password for decrypting the secret :return: """ d = {} if False and not self._account_password: from ambry.dbexceptions import ConfigurationEr...
[ "def", "accounts", "(", "self", ")", ":", "d", "=", "{", "}", "if", "False", "and", "not", "self", ".", "_account_password", ":", "from", "ambry", ".", "dbexceptions", "import", "ConfigurationError", "raise", "ConfigurationError", "(", "\"Can't access accounts w...
33.375
19.958333
def load_reviews(self): """Fetches the MAL user reviews page and sets the current user's reviews attributes. :rtype: :class:`.User` :return: Current user object. """ page = 0 # collect all reviews over all pages. review_collection = [] while True: user_reviews = self.session.sess...
[ "def", "load_reviews", "(", "self", ")", ":", "page", "=", "0", "# collect all reviews over all pages.", "review_collection", "=", "[", "]", "while", "True", ":", "user_reviews", "=", "self", ".", "session", ".", "session", ".", "get", "(", "u'http://myanimelist...
35.846154
25.5
def xml(self): """ Create an ``lxml``-based XML DOM from the response. The tree will not have a root, so all queries need to be relative (i.e. start with a dot). """ try: from lxml import etree return etree.fromstring(self.content) except ImportErr...
[ "def", "xml", "(", "self", ")", ":", "try", ":", "from", "lxml", "import", "etree", "return", "etree", ".", "fromstring", "(", "self", ".", "content", ")", "except", "ImportError", "as", "ie", ":", "raise", "DependencyException", "(", "ie", ")" ]
36.2
10.9
def set_alarm_state(self, alarm_name, state_reason, state_value, state_reason_data=None): """ Temporarily sets the state of an alarm. When the updated StateValue differs from the previous value, the action configured for the appropriate state is invoked. This is n...
[ "def", "set_alarm_state", "(", "self", ",", "alarm_name", ",", "state_reason", ",", "state_value", ",", "state_reason_data", "=", "None", ")", ":", "params", "=", "{", "'AlarmName'", ":", "alarm_name", ",", "'StateReason'", ":", "state_reason", ",", "'StateValue...
39.607143
19.678571
def set_logger_dir(dirname, action=None): """ Set the directory for global logging. Args: dirname(str): log directory action(str): an action of ["k","d","q"] to be performed when the directory exists. Will ask user by default. "d": delete the directory. Note tha...
[ "def", "set_logger_dir", "(", "dirname", ",", "action", "=", "None", ")", ":", "global", "LOG_DIR", ",", "_FILE_HANDLER", "if", "_FILE_HANDLER", ":", "# unload and close the old file handler, so that we may safely delete the logger directory", "_logger", ".", "removeHandler",...
40.293103
20.87931
def _find_function_from_code(frame, code): """ Given a frame and a compiled function code, find the corresponding function object within the frame. This function addresses the following problem: when handling a stacktrace, we receive information about which piece of code was being executed in the form ...
[ "def", "_find_function_from_code", "(", "frame", ",", "code", ")", ":", "def", "find_code", "(", "iterable", ",", "depth", "=", "0", ")", ":", "if", "depth", ">", "3", ":", "return", "# Avoid potential infinite loops, or generally objects that are too deep.", "for",...
56.864865
32.162162
def pathstrip(path, n): """ Strip n leading components from the given path """ pathlist = [path] while os.path.dirname(pathlist[0]) != b'': pathlist[0:1] = os.path.split(pathlist[0]) return b'/'.join(pathlist[n:])
[ "def", "pathstrip", "(", "path", ",", "n", ")", ":", "pathlist", "=", "[", "path", "]", "while", "os", ".", "path", ".", "dirname", "(", "pathlist", "[", "0", "]", ")", "!=", "b''", ":", "pathlist", "[", "0", ":", "1", "]", "=", "os", ".", "p...
36.666667
9.333333
def vector_projection(v1, v2): '''compute the vector projection of v1 upon v2 Args: v1, v2: iterable indices 0, 1, 2 corresponding to cartesian coordinates Returns: 3-vector of the projection of point p onto the direction of v ''' return scalar_projection(v1, v2) * v2 / np....
[ "def", "vector_projection", "(", "v1", ",", "v2", ")", ":", "return", "scalar_projection", "(", "v1", ",", "v2", ")", "*", "v2", "/", "np", ".", "linalg", ".", "norm", "(", "v2", ")" ]
29.545455
25.545455
def update_contact(self, contact_id, email=None, name=None): """ Update a current contact :param contact_id: contact id :param email: user email :param name: user name """ params = {} if email is not None: params['email'] = email if n...
[ "def", "update_contact", "(", "self", ",", "contact_id", ",", "email", "=", "None", ",", "name", "=", "None", ")", ":", "params", "=", "{", "}", "if", "email", "is", "not", "None", ":", "params", "[", "'email'", "]", "=", "email", "if", "name", "is...
27.73913
15.304348
def Tt(CASRN, AvailableMethods=False, Method=None): r'''This function handles the retrieval of a chemical's triple temperature. Lookup is based on CASRNs. Will automatically select a data source to use if no Method is provided; returns None if the data is not available. Returns data from [1]_, or a che...
[ "def", "Tt", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "Staveley_data", ".", "index", ":", "methods", ".", "append", ...
28.931507
23.917808
def _compile_list(self, data, indent_level): """Correctly write possibly nested list.""" if len(data) == 0: return '--' elif not any(isinstance(i, (dict, list)) for i in data): return ', '.join(self._compile_literal(value) for value in data) else: # 'e...
[ "def", "_compile_list", "(", "self", ",", "data", ",", "indent_level", ")", ":", "if", "len", "(", "data", ")", "==", "0", ":", "return", "'--'", "elif", "not", "any", "(", "isinstance", "(", "i", ",", "(", "dict", ",", "list", ")", ")", "for", "...
41.512821
17.948718
def store_tokens(self, access_token, id_token): """Store OIDC tokens.""" session = self.request.session if self.get_settings('OIDC_STORE_ACCESS_TOKEN', False): session['oidc_access_token'] = access_token if self.get_settings('OIDC_STORE_ID_TOKEN', False): sessio...
[ "def", "store_tokens", "(", "self", ",", "access_token", ",", "id_token", ")", ":", "session", "=", "self", ".", "request", ".", "session", "if", "self", ".", "get_settings", "(", "'OIDC_STORE_ACCESS_TOKEN'", ",", "False", ")", ":", "session", "[", "'oidc_ac...
37.888889
17
def question_default_serializer(self, obj): """Convert a Question to a cached instance representation.""" if not obj: return None self.question_default_add_related_pks(obj) return dict(( ('id', obj.id), ('question_text', obj.question_text), ...
[ "def", "question_default_serializer", "(", "self", ",", "obj", ")", ":", "if", "not", "obj", ":", "return", "None", "self", ".", "question_default_add_related_pks", "(", "obj", ")", "return", "dict", "(", "(", "(", "'id'", ",", "obj", ".", "id", ")", ","...
40.25
16
def sync_close(self): """ 同步关闭 """ if self._closed: return while self._free: conn = self._free.popleft() if not conn.closed: # pragma: no cover conn.sync_close() for conn in self._used: if not...
[ "def", "sync_close", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "return", "while", "self", ".", "_free", ":", "conn", "=", "self", ".", "_free", ".", "popleft", "(", ")", "if", "not", "conn", ".", "closed", ":", "# pragma: no cover", "...
26.611111
10.166667
def disable_hostgroup_svc_checks(self, hostgroup): """Disable service checks for a hostgroup Format of the line that triggers function call:: DISABLE_HOSTGROUP_SVC_CHECKS;<hostgroup_name> :param hostgroup: hostgroup to disable :type hostgroup: alignak.objects.hostgroup.Hostgrou...
[ "def", "disable_hostgroup_svc_checks", "(", "self", ",", "hostgroup", ")", ":", "for", "host_id", "in", "hostgroup", ".", "get_hosts", "(", ")", ":", "if", "host_id", "in", "self", ".", "daemon", ".", "hosts", ":", "for", "service_id", "in", "self", ".", ...
42.866667
17.4
def complete_token_filtered(aliases, prefix, expanded): """Find all starting matches in dictionary *aliases* that start with *prefix*, but filter out any matches already in *expanded*.""" complete_ary = list(aliases.keys()) results = [cmd for cmd in complete_ary if cmd.startswith(pr...
[ "def", "complete_token_filtered", "(", "aliases", ",", "prefix", ",", "expanded", ")", ":", "complete_ary", "=", "list", "(", "aliases", ".", "keys", "(", ")", ")", "results", "=", "[", "cmd", "for", "cmd", "in", "complete_ary", "if", "cmd", ".", "starts...
40.636364
16.909091
def filter_and_process_statements( sts, grounding_score_cutoff: float = 0.8, belief_score_cutoff: float = 0.85, concepts_of_interest: List[str] = [], ): """ Filter preassembled statements according to certain rules. """ filtered_sts = [] counters = {} def update_counter(counter_name): ...
[ "def", "filter_and_process_statements", "(", "sts", ",", "grounding_score_cutoff", ":", "float", "=", "0.8", ",", "belief_score_cutoff", ":", "float", "=", "0.85", ",", "concepts_of_interest", ":", "List", "[", "str", "]", "=", "[", "]", ",", ")", ":", "filt...
26.824561
20.964912
def ElemMatch(q, *conditions): """ The ElemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. """ new_condition = {} for condition in conditions: deep_merge(condition.to_dict(), new_condition) return ...
[ "def", "ElemMatch", "(", "q", ",", "*", "conditions", ")", ":", "new_condition", "=", "{", "}", "for", "condition", "in", "conditions", ":", "deep_merge", "(", "condition", ".", "to_dict", "(", ")", ",", "new_condition", ")", "return", "Condition", "(", ...
35.8
17.6
def sphinx(ctx, browse=False, clean=False, watchdog=False, kill=False, status=False, opts=''): """Build Sphinx docs.""" cfg = config.load() if kill or status: if not watchdogctl(ctx, kill=kill): notify.info("No process bound to port {}".format(ctx.rituals.docs.watchdog.port)) re...
[ "def", "sphinx", "(", "ctx", ",", "browse", "=", "False", ",", "clean", "=", "False", ",", "watchdog", "=", "False", ",", "kill", "=", "False", ",", "status", "=", "False", ",", "opts", "=", "''", ")", ":", "cfg", "=", "config", ".", "load", "(",...
35.890756
19.504202
def verify_response_time(self, expected_below): """ Verify that response time (time span between request-response) is reasonable. :param expected_below: integer :return: Nothing :raises: ValueError if timedelta > expected time """ if self.timedelta > expected_bel...
[ "def", "verify_response_time", "(", "self", ",", "expected_below", ")", ":", "if", "self", ".", "timedelta", ">", "expected_below", ":", "raise", "ValueError", "(", "\"Response time is more (%f) than expected (%f)!\"", "%", "(", "self", ".", "timedelta", ",", "expec...
41.454545
17.272727
def initiate_multipart_upload(self, key_name, headers=None, reduced_redundancy=False, metadata=None, encrypt_key=False): """ Start a multipart upload operation. :type key_name: string :param key_name: The name of the ke...
[ "def", "initiate_multipart_upload", "(", "self", ",", "key_name", ",", "headers", "=", "None", ",", "reduced_redundancy", "=", "False", ",", "metadata", "=", "None", ",", "encrypt_key", "=", "False", ")", ":", "query_args", "=", "'uploads'", "provider", "=", ...
46.09375
20.375
def cb_set_provider_option(self, option, opt, value, parser): """optik callback for option setting""" if opt.startswith("--"): # remove -- on long option opt = opt[2:] else: # short option, get its long equivalent opt = self._short_options[opt[1:]]...
[ "def", "cb_set_provider_option", "(", "self", ",", "option", ",", "opt", ",", "value", ",", "parser", ")", ":", "if", "opt", ".", "startswith", "(", "\"--\"", ")", ":", "# remove -- on long option", "opt", "=", "opt", "[", "2", ":", "]", "else", ":", "...
38.833333
12.583333
def adaptive_rejection_sampling(logpdf: callable, a: float, b: float, domain: Tuple[float, float], n_samples: int, random_stream=None): """ Adaptive rejection sampling samples exactly ...
[ "def", "adaptive_rejection_sampling", "(", "logpdf", ":", "callable", ",", "a", ":", "float", ",", "b", ":", "float", ",", "domain", ":", "Tuple", "[", "float", ",", "float", "]", ",", "n_samples", ":", "int", ",", "random_stream", "=", "None", ")", ":...
35.678571
24.692857
def _pstore32(ins): """ Stores 2nd parameter at stack pointer (SP) + X, being X 1st parameter. 1st operand must be a SIGNED integer. """ value = ins.quad[2] offset = ins.quad[1] indirect = offset[0] == '*' if indirect: offset = offset[1:] I = int(offset) if I >= 0: ...
[ "def", "_pstore32", "(", "ins", ")", ":", "value", "=", "ins", ".", "quad", "[", "2", "]", "offset", "=", "ins", ".", "quad", "[", "1", "]", "indirect", "=", "offset", "[", "0", "]", "==", "'*'", "if", "indirect", ":", "offset", "=", "offset", ...
22.233333
17.766667
def __draw_cluster(self, data, cluster, color, marker): """! @brief Draw 2-D single cluster on axis using specified color and marker. """ for item in cluster: self.__ax.plot(data[item][0], data[item][1], color=color, marker=marker)
[ "def", "__draw_cluster", "(", "self", ",", "data", ",", "cluster", ",", "color", ",", "marker", ")", ":", "for", "item", "in", "cluster", ":", "self", ".", "__ax", ".", "plot", "(", "data", "[", "item", "]", "[", "0", "]", ",", "data", "[", "item...
39.428571
21.571429
def __decompressContent(self, coding, pgctnt): """ This is really obnoxious """ #preLen = len(pgctnt) if coding == 'deflate': compType = "deflate" bits_opts = [ -zlib.MAX_WBITS, # deflate zlib.MAX_WBITS, # zlib zlib.MAX_WBITS | 16, # gzip zlib.MAX_WBITS | 32, # "automati...
[ "def", "__decompressContent", "(", "self", ",", "coding", ",", "pgctnt", ")", ":", "#preLen = len(pgctnt)", "if", "coding", "==", "'deflate'", ":", "compType", "=", "\"deflate\"", "bits_opts", "=", "[", "-", "zlib", ".", "MAX_WBITS", ",", "# deflate", "zlib", ...
23.259259
21.962963
def _process_score(self, model_name, dependency_cache=None): """ Generates a score for a given model using the `dependency_cache`. """ version = self[model_name].version start = time.time() feature_values = self._solve_features(model_name, dependency_cache) logge...
[ "def", "_process_score", "(", "self", ",", "model_name", ",", "dependency_cache", "=", "None", ")", ":", "version", "=", "self", "[", "model_name", "]", ".", "version", "start", "=", "time", ".", "time", "(", ")", "feature_values", "=", "self", ".", "_so...
40.789474
21.315789
def install(self, struct, ui, debug=False): """ This is the only method that should be called from outside. Call it like: `DependencyInstaller(struct)` and it will install packages which are not present on system (it uses package managers specified by `struct` structure) ...
[ "def", "install", "(", "self", ",", "struct", ",", "ui", ",", "debug", "=", "False", ")", ":", "# the system dependencies should always go first", "self", ".", "__add_dependencies", "(", "self", ".", "get_system_deptype_shortcut", "(", ")", ",", "[", "]", ")", ...
44.2
17.266667
def find_vulnerabilities( cfg_list, blackbox_mapping_file, sources_and_sinks_file, interactive=False, nosec_lines=defaultdict(set) ): """Find vulnerabilities in a list of CFGs from a trigger_word_file. Args: cfg_list(list[CFG]): the list of CFGs to scan. blackbox_mapping_fil...
[ "def", "find_vulnerabilities", "(", "cfg_list", ",", "blackbox_mapping_file", ",", "sources_and_sinks_file", ",", "interactive", "=", "False", ",", "nosec_lines", "=", "defaultdict", "(", "set", ")", ")", ":", "vulnerabilities", "=", "list", "(", ")", "definitions...
28.394737
18.552632
def tile(self, ncols, nrows): """Automatically tile the panels of the figure. This will re-arranged all elements of the figure (first in the hierarchy) so that they will uniformly cover the figure area. Parameters ---------- ncols, nrows : type The number of...
[ "def", "tile", "(", "self", ",", "ncols", ",", "nrows", ")", ":", "dx", "=", "(", "self", ".", "width", "/", "ncols", ")", ".", "to", "(", "'px'", ")", ".", "value", "dy", "=", "(", "self", ".", "height", "/", "nrows", ")", ".", "to", "(", ...
29.517241
20.896552
def update(self, collection_name, instance): """ method finds Site Statistics record and update it DB representation """ assert isinstance(instance, SiteStatistics) if instance.db_id: query = {'_id': ObjectId(instance.db_id)} else: query = {DOMAIN_NAME: instance.d...
[ "def", "update", "(", "self", ",", "collection_name", ",", "instance", ")", ":", "assert", "isinstance", "(", "instance", ",", "SiteStatistics", ")", "if", "instance", ".", "db_id", ":", "query", "=", "{", "'_id'", ":", "ObjectId", "(", "instance", ".", ...
46.3
12.4
def capacity_method_selector(sl, fd, method, **kwargs): """ Calculates the bearing capacity of a foundation on soil using the specified method. :param sl: Soil Object :param fd: Foundation Object :param method: Method :param kwargs: :return: """ if method == 'vesics': capaci...
[ "def", "capacity_method_selector", "(", "sl", ",", "fd", ",", "method", ",", "*", "*", "kwargs", ")", ":", "if", "method", "==", "'vesics'", ":", "capacity_vesics_1975", "(", "sl", ",", "fd", ",", "*", "*", "kwargs", ")", "elif", "method", "==", "'nzs'...
32.727273
13.727273
def add_spatial_unit_condition(self, droppable_id, container_id, spatial_unit, match=True): """stub""" if not isinstance(spatial_unit, abc_mapping_primitives.SpatialUnit): raise InvalidArgument('spatial_unit is not a SpatialUnit') self.my_osid_object_form._my_map['spatialUnitConditi...
[ "def", "add_spatial_unit_condition", "(", "self", ",", "droppable_id", ",", "container_id", ",", "spatial_unit", ",", "match", "=", "True", ")", ":", "if", "not", "isinstance", "(", "spatial_unit", ",", "abc_mapping_primitives", ".", "SpatialUnit", ")", ":", "ra...
67.375
40.125
def delete(self, del_id): ''' Delete the id ''' if MReply2User.delete(del_id): output = {'del_zan': 1} else: output = {'del_zan': 0} return json.dump(output, self)
[ "def", "delete", "(", "self", ",", "del_id", ")", ":", "if", "MReply2User", ".", "delete", "(", "del_id", ")", ":", "output", "=", "{", "'del_zan'", ":", "1", "}", "else", ":", "output", "=", "{", "'del_zan'", ":", "0", "}", "return", "json", ".", ...
25.222222
14.777778
def get(self, username, password, *args, **kwargs): """Returns the User object Returns None if the user isn't found or the passwords don't match :param username: username of the user :param password: password of the user """ user = self.query.filter_by(username=username...
[ "def", "get", "(", "self", ",", "username", ",", "password", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "user", "=", "self", ".", "query", ".", "filter_by", "(", "username", "=", "username", ")", ".", "first", "(", ")", "if", "user", "a...
34.416667
17
def guess_depth_cutoff(cb_histogram): ''' Guesses at an appropriate barcode cutoff ''' with read_cbhistogram(cb_histogram) as fh: cb_vals = [int(p.strip().split()[1]) for p in fh] histo = np.histogram(np.log10(cb_vals), bins=50) vals = histo[0] edges = histo[1] mids = np.array([(edge...
[ "def", "guess_depth_cutoff", "(", "cb_histogram", ")", ":", "with", "read_cbhistogram", "(", "cb_histogram", ")", "as", "fh", ":", "cb_vals", "=", "[", "int", "(", "p", ".", "strip", "(", ")", ".", "split", "(", ")", "[", "1", "]", ")", "for", "p", ...
37
18.04
def advance(self, id=None): """ Advance to next token, optionally check that current token is 'id' """ if id and self.token.id != id: raise SyntaxError("Expected {0}".format(id)) self.token = self.next()
[ "def", "advance", "(", "self", ",", "id", "=", "None", ")", ":", "if", "id", "and", "self", ".", "token", ".", "id", "!=", "id", ":", "raise", "SyntaxError", "(", "\"Expected {0}\"", ".", "format", "(", "id", ")", ")", "self", ".", "token", "=", ...
31.125
14.125
def get_spectre_plot(self, sigma=0.05, step=0.01): """ Get a matplotlib plot of the UV-visible xas. Transition are plotted as vertical lines and as a sum of normal functions with sigma with. The broadening is applied in energy and the xas is plotted as a function of the wavelengt...
[ "def", "get_spectre_plot", "(", "self", ",", "sigma", "=", "0.05", ",", "step", "=", "0.01", ")", ":", "from", "pymatgen", ".", "util", ".", "plotting", "import", "pretty_plot", "from", "matplotlib", ".", "mlab", "import", "normpdf", "plt", "=", "pretty_pl...
36.54717
20.207547
def load_css(css_url=None, version='5.2.0'): """Load Dropzone's css resources with given version. .. versionadded:: 1.4.4 :param css_url: The CSS url for Dropzone.js. :param version: The version of Dropzone.js. """ css_filename = 'dropzone.min.css' serve_local =...
[ "def", "load_css", "(", "css_url", "=", "None", ",", "version", "=", "'5.2.0'", ")", ":", "css_filename", "=", "'dropzone.min.css'", "serve_local", "=", "current_app", ".", "config", "[", "'DROPZONE_SERVE_LOCAL'", "]", "if", "serve_local", ":", "css", "=", "'<...
39.380952
23.428571
def sequence_weights(aln, scaling='none', gap_chars='-.'): """Weight aligned sequences to emphasize more divergent members. Returns a list of floating-point numbers between 0 and 1, corresponding to the proportional weight of each sequence in the alignment. The first list is the weight of the first seq...
[ "def", "sequence_weights", "(", "aln", ",", "scaling", "=", "'none'", ",", "gap_chars", "=", "'-.'", ")", ":", "# Probability is hard, let's estimate by sampling!", "# Sample k from a population of 20 with replacement; how many unique k were", "# chosen? Average of 10000 runs for k =...
48.578947
21.094737
def wcomplex(wave): r""" Convert a waveform's dependent variable vector to complex. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for ...
[ "def", "wcomplex", "(", "wave", ")", ":", "ret", "=", "copy", ".", "copy", "(", "wave", ")", "ret", ".", "_dep_vector", "=", "ret", ".", "_dep_vector", ".", "astype", "(", "np", ".", "complex", ")", "return", "ret" ]
25.95
19.8
def submit(self, command='sleep 1', blocksize=1, tasks_per_node=1, job_name="parsl.auto"): """Submit the command onto a freshly instantiated AWS EC2 instance. Submit returns an ID that corresponds to the task that was just submitted. Parameters ---------- command : str ...
[ "def", "submit", "(", "self", ",", "command", "=", "'sleep 1'", ",", "blocksize", "=", "1", ",", "tasks_per_node", "=", "1", ",", "job_name", "=", "\"parsl.auto\"", ")", ":", "job_name", "=", "\"parsl.auto.{0}\"", ".", "format", "(", "time", ".", "time", ...
34.511628
23.348837
def merge_keywords(x,y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z
[ "def", "merge_keywords", "(", "x", ",", "y", ")", ":", "z", "=", "x", ".", "copy", "(", ")", "z", ".", "update", "(", "y", ")", "return", "z" ]
27.8
18.6
def relaxNGValidateFullElement(self, ctxt, elem): """Validate a full subtree when xmlRelaxNGValidatePushElement() returned 0 and the content of the node has been expanded. """ if ctxt is None: ctxt__o = None else: ctxt__o = ctxt._o if elem is None: elem__o = None ...
[ "def", "relaxNGValidateFullElement", "(", "self", ",", "ctxt", ",", "elem", ")", ":", "if", "ctxt", "is", "None", ":", "ctxt__o", "=", "None", "else", ":", "ctxt__o", "=", "ctxt", ".", "_o", "if", "elem", "is", "None", ":", "elem__o", "=", "None", "e...
44
12
def initialize(self, init=None, ctx=None, default_init=initializer.Uniform(), force_reinit=False): """Initializes parameter and gradient arrays. Only used for :py:class:`NDArray` API. Parameters ---------- init : Initializer The initializer to use. Overrid...
[ "def", "initialize", "(", "self", ",", "init", "=", "None", ",", "ctx", "=", "None", ",", "default_init", "=", "initializer", ".", "Uniform", "(", ")", ",", "force_reinit", "=", "False", ")", ":", "if", "self", ".", "_data", "is", "not", "None", "and...
40.776119
19.38806
def make_loop_body_and_orelse(top_of_loop, body_instrs, else_instrs, context): """ Make body and orelse lists for a for/while loop whose first instruction is `top_of_loop`. Parameters ---------- top_of_loop : Instruction The first body of the loop. For a for-loop, this should always be...
[ "def", "make_loop_body_and_orelse", "(", "top_of_loop", ",", "body_instrs", ",", "else_instrs", ",", "context", ")", ":", "# Remove the JUMP_ABSOLUTE and POP_BLOCK instructions at the bottom of the", "# loop.", "body_instrs", ".", "pop", "(", ")", "body_instrs", ".", "pop",...
34.435897
23.769231
def check_permission(permission, obj): """ Returns if the current user has rights for the permission passed in against the obj passed in :param permission: name of the permission :param obj: the object to check the permission against for the current user :return: 1 if the user has rights for thi...
[ "def", "check_permission", "(", "permission", ",", "obj", ")", ":", "mtool", "=", "api", ".", "get_tool", "(", "'portal_membership'", ")", "object", "=", "api", ".", "get_object", "(", "obj", ")", "return", "mtool", ".", "checkPermission", "(", "permission",...
44
15.272727
def encode(self, obj): """Fired for every object.""" s = super(CustomEncoder, self).encode(obj) # If uncompressed, postprocess for formatting if len(s.splitlines()) > 1: s = self.postprocess(s) return s
[ "def", "encode", "(", "self", ",", "obj", ")", ":", "s", "=", "super", "(", "CustomEncoder", ",", "self", ")", ".", "encode", "(", "obj", ")", "# If uncompressed, postprocess for formatting", "if", "len", "(", "s", ".", "splitlines", "(", ")", ")", ">", ...
35.428571
10.714286
def send_many(self, recipients, from_address=None, fee=None): """Send bitcoin from your wallet to multiple addresses. :param dictionary recipients: dictionary with the structure of 'address':amount :param str from_address: specific address to send from (optional) :param int fee: transac...
[ "def", "send_many", "(", "self", ",", "recipients", ",", "from_address", "=", "None", ",", "fee", "=", "None", ")", ":", "params", "=", "self", ".", "build_basic_request", "(", "read_only", "=", "False", ")", "if", "len", "(", "recipients", ")", "==", ...
42.028571
19.4
def enhex(d, separator=''): """ Convert bytes to their hexadecimal representation, optionally joined by a given separator. Args: d(bytes): The data to convert to hexadecimal representation. separator(str): The separator to insert between hexadecimal tuples. Returns: str: Th...
[ "def", "enhex", "(", "d", ",", "separator", "=", "''", ")", ":", "v", "=", "binascii", ".", "hexlify", "(", "d", ")", ".", "decode", "(", "'ascii'", ")", "if", "separator", ":", "return", "separator", ".", "join", "(", "v", "[", "i", ":", "i", ...
25.571429
20.714286
def Flush(self): """Flush all items from cache.""" while self._age: node = self._age.PopLeft() self.KillObject(node.data) self._hash = dict()
[ "def", "Flush", "(", "self", ")", ":", "while", "self", ".", "_age", ":", "node", "=", "self", ".", "_age", ".", "PopLeft", "(", ")", "self", ".", "KillObject", "(", "node", ".", "data", ")", "self", ".", "_hash", "=", "dict", "(", ")" ]
22.857143
16.714286
def conv_block(name, x, mid_channels, dilations=None, activation="relu", dropout=0.0): """2 layer conv block used in the affine coupling layer. Args: name: variable scope. x: 4-D or 5-D Tensor. mid_channels: Output channels of the second layer. dilations: Optional, list of integers. ...
[ "def", "conv_block", "(", "name", ",", "x", ",", "mid_channels", ",", "dilations", "=", "None", ",", "activation", "=", "\"relu\"", ",", "dropout", "=", "0.0", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "reuse", "=", "tf", ".", ...
33.428571
16.946429