text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_client(self, email=None, password=None, **__): """Get the google data client.""" if self.client is not None: return self.client return Auth(email, password)
[ "def", "get_client", "(", "self", ",", "email", "=", "None", ",", "password", "=", "None", ",", "*", "*", "__", ")", ":", "if", "self", ".", "client", "is", "not", "None", ":", "return", "self", ".", "client", "return", "Auth", "(", "email", ",", ...
39.2
0.01
def addclassifications(agdir, prop, version=None, statfeats = [0,4,5,6,7,8]): """ Calculates real score probability of prop from an activegit repo. version is string name of activegit tag. Default agdir initialization will have latest tag, so version is optional. statfeats set to work with alnotebook n...
[ "def", "addclassifications", "(", "agdir", ",", "prop", ",", "version", "=", "None", ",", "statfeats", "=", "[", "0", ",", "4", ",", "5", ",", "6", ",", "7", ",", "8", "]", ")", ":", "try", ":", "ag", "=", "activegit", ".", "ActiveGit", "(", "a...
37.578947
0.01776
def choropleth(): """ Returns """ path=os.path.join(os.path.dirname(__file__), '../data/choropleth.csv') df=pd.read_csv(path) del df['Unnamed: 0'] df['z']=[np.random.randint(0,100) for _ in range(len(df))] return df
[ "def", "choropleth", "(", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../data/choropleth.csv'", ")", "df", "=", "pd", ".", "read_csv", "(", "path", ")", "del", "df", "[...
24
0.0625
def map_statistic(self, plot): """ Mapping aesthetics to computed statistics """ data = self.data if not len(data): return type(data)() # Assemble aesthetics from layer, plot and stat mappings aesthetics = deepcopy(self.mapping) if self.inheri...
[ "def", "map_statistic", "(", "self", ",", "plot", ")", ":", "data", "=", "self", ".", "data", "if", "not", "len", "(", "data", ")", ":", "return", "type", "(", "data", ")", "(", ")", "# Assemble aesthetics from layer, plot and stat mappings", "aesthetics", "...
37.369565
0.001134
def _reciprocal_condition_number(lu_mat, one_norm): r"""Compute reciprocal condition number of a matrix. Args: lu_mat (numpy.ndarray): A 2D array of a matrix :math:`A` that has been LU-factored, with the non-diagonal part of :math:`L` stored in the strictly lower triangle and :m...
[ "def", "_reciprocal_condition_number", "(", "lu_mat", ",", "one_norm", ")", ":", "if", "_scipy_lapack", "is", "None", ":", "raise", "OSError", "(", "\"This function requires SciPy for calling into LAPACK.\"", ")", "# pylint: disable=no-member", "rcond", ",", "info", "=", ...
35.137931
0.000955
def _get_focused_item(self): """ Returns the currently focused item """ focused_model = self._selection.focus if not focused_model: return None return self.canvas.get_view_for_model(focused_model)
[ "def", "_get_focused_item", "(", "self", ")", ":", "focused_model", "=", "self", ".", "_selection", ".", "focus", "if", "not", "focused_model", ":", "return", "None", "return", "self", ".", "canvas", ".", "get_view_for_model", "(", "focused_model", ")" ]
39.166667
0.008333
def filter_on_wire_representation(ava, acs, required=None, optional=None): """ :param ava: A dictionary with attributes and values :param acs: List of tuples (Attribute Converter name, Attribute Converter instance) :param required: A list of saml.Attributes :param optional: A list of saml.At...
[ "def", "filter_on_wire_representation", "(", "ava", ",", "acs", ",", "required", "=", "None", ",", "optional", "=", "None", ")", ":", "acsdic", "=", "dict", "(", "[", "(", "ac", ".", "name_format", ",", "ac", ")", "for", "ac", "in", "acs", "]", ")", ...
29.512821
0.000841
def ascii2h5(bh_dir=None): """ Convert the Burstein & Heiles (1982) dust map from ASCII to HDF5. """ if bh_dir is None: bh_dir = os.path.join(data_dir_default, 'bh') fname = os.path.join(bh_dir, '{}.ascii') f = h5py.File('bh.h5', 'w') for region in ('hinorth', 'hisouth'): ...
[ "def", "ascii2h5", "(", "bh_dir", "=", "None", ")", ":", "if", "bh_dir", "is", "None", ":", "bh_dir", "=", "os", ".", "path", ".", "join", "(", "data_dir_default", ",", "'bh'", ")", "fname", "=", "os", ".", "path", ".", "join", "(", "bh_dir", ",", ...
25.955224
0.001662
def call_arg_index(self): """Determines the index of the parameter in a call list using string manipulation and context information.""" #The function name we are calling should be in el_name by now if self._call_index is None: if (self.el_section == "body" and ...
[ "def", "call_arg_index", "(", "self", ")", ":", "#The function name we are calling should be in el_name by now", "if", "self", ".", "_call_index", "is", "None", ":", "if", "(", "self", ".", "el_section", "==", "\"body\"", "and", "self", ".", "el_call", "in", "[", ...
48.578947
0.011683
def _push_next(self): """Assign next batch workload to workers.""" r = next(self._iter, None) if r is None: return self._key_queue.put((self._sent_idx, r)) self._sent_idx += 1
[ "def", "_push_next", "(", "self", ")", ":", "r", "=", "next", "(", "self", ".", "_iter", ",", "None", ")", "if", "r", "is", "None", ":", "return", "self", ".", "_key_queue", ".", "put", "(", "(", "self", ".", "_sent_idx", ",", "r", ")", ")", "s...
31.571429
0.008811
def _extension_module_tags(): """ Returns valid tags an extension module might have """ import sysconfig tags = [] if six.PY2: # see also 'SHLIB_EXT' multiarch = sysconfig.get_config_var('MULTIARCH') if multiarch is not None: tags.append(multiarch) else: ...
[ "def", "_extension_module_tags", "(", ")", ":", "import", "sysconfig", "tags", "=", "[", "]", "if", "six", ".", "PY2", ":", "# see also 'SHLIB_EXT'", "multiarch", "=", "sysconfig", ".", "get_config_var", "(", "'MULTIARCH'", ")", "if", "multiarch", "is", "not",...
32.277778
0.001672
def deserialize(cls, assoc_s): """ Parse an association as stored by serialize(). inverse of serialize @param assoc_s: Association as serialized by serialize() @type assoc_s: str @return: instance of this class """ pairs = kvform.kvToSeq(assoc_s, str...
[ "def", "deserialize", "(", "cls", ",", "assoc_s", ")", ":", "pairs", "=", "kvform", ".", "kvToSeq", "(", "assoc_s", ",", "strict", "=", "True", ")", "keys", "=", "[", "]", "values", "=", "[", "]", "for", "k", ",", "v", "in", "pairs", ":", "keys",...
27.483871
0.002268
def _read_file(filename): """ Read a res2dinv-file and return the header Parameters ---------- filename : string Data filename Returns ------ type : int type of array extracted from header file_data : :py:class:`StringIO.StringIO` content of file in a String...
[ "def", "_read_file", "(", "filename", ")", ":", "# read data", "with", "open", "(", "filename", ",", "'r'", ")", "as", "fid2", ":", "abem_data_orig", "=", "fid2", ".", "read", "(", ")", "fid", "=", "StringIO", "(", ")", "fid", ".", "write", "(", "abe...
20.1875
0.001477
def downgrade(): """Downgrade database.""" ctx = op.get_context() insp = Inspector.from_engine(ctx.connection.engine) for fk in insp.get_foreign_keys('transaction'): if fk['referred_table'] == 'accounts_user': op.drop_constraint( op.f(fk['name']), 'transaction', type...
[ "def", "downgrade", "(", ")", ":", "ctx", "=", "op", ".", "get_context", "(", ")", "insp", "=", "Inspector", ".", "from_engine", "(", "ctx", ".", "connection", ".", "engine", ")", "for", "fk", "in", "insp", ".", "get_foreign_keys", "(", "'transaction'", ...
36.166667
0.001497
def unbounded(self): """Whether the solution is unbounded""" self._check_valid() return (self._problem._p.get_status() == qsoptex.SolutionStatus.UNBOUNDED)
[ "def", "unbounded", "(", "self", ")", ":", "self", ".", "_check_valid", "(", ")", "return", "(", "self", ".", "_problem", ".", "_p", ".", "get_status", "(", ")", "==", "qsoptex", ".", "SolutionStatus", ".", "UNBOUNDED", ")" ]
38.2
0.010256
def center_crop(im, min_sz=None): """ Return a center crop of an image """ r,c,*_ = im.shape if min_sz is None: min_sz = min(r,c) start_r = math.ceil((r-min_sz)/2) start_c = math.ceil((c-min_sz)/2) return crop(im, start_r, start_c, min_sz)
[ "def", "center_crop", "(", "im", ",", "min_sz", "=", "None", ")", ":", "r", ",", "c", ",", "", "*", "_", "=", "im", ".", "shape", "if", "min_sz", "is", "None", ":", "min_sz", "=", "min", "(", "r", ",", "c", ")", "start_r", "=", "math", ".", ...
36.714286
0.019011
def parse_if_header_dict(environ): """Parse HTTP_IF header into a dictionary and lists, and cache the result. @see http://www.webdav.org/specs/rfc4918.html#HEADER_If """ if "wsgidav.conditions.if" in environ: return if "HTTP_IF" not in environ: environ["wsgidav.conditions.if"] = No...
[ "def", "parse_if_header_dict", "(", "environ", ")", ":", "if", "\"wsgidav.conditions.if\"", "in", "environ", ":", "return", "if", "\"HTTP_IF\"", "not", "in", "environ", ":", "environ", "[", "\"wsgidav.conditions.if\"", "]", "=", "None", "environ", "[", "\"wsgidav....
32.830189
0.001116
def do_max(environment, value, case_sensitive=False, attribute=None): """Return the largest item from the sequence. .. sourcecode:: jinja {{ [1, 2, 3]|max }} -> 3 :param case_sensitive: Treat upper and lower case strings as distinct. :param attribute: Get the object with the max v...
[ "def", "do_max", "(", "environment", ",", "value", ",", "case_sensitive", "=", "False", ",", "attribute", "=", "None", ")", ":", "return", "_min_or_max", "(", "environment", ",", "value", ",", "max", ",", "case_sensitive", ",", "attribute", ")" ]
34.583333
0.002347
def get_tasks(self): """Returns an ordered dictionary {task_name: task} of all tasks within this workflow. :return: Ordered dictionary with key being task_name (str) and an instance of a corresponding task from this workflow :rtype: OrderedDict """ tasks = collect...
[ "def", "get_tasks", "(", "self", ")", ":", "tasks", "=", "collections", ".", "OrderedDict", "(", ")", "for", "dep", "in", "self", ".", "ordered_dependencies", ":", "tasks", "[", "dep", ".", "name", "]", "=", "dep", ".", "task", "return", "tasks" ]
36.5
0.008909
def to_ufo_background_image(self, ufo_glyph, layer): """Copy the backgound image from the GSLayer to the UFO Glyph.""" image = layer.backgroundImage if image is None: return ufo_image = ufo_glyph.image ufo_image.fileName = image.path ufo_image.transformation = image.transform ufo_gly...
[ "def", "to_ufo_background_image", "(", "self", ",", "ufo_glyph", ",", "layer", ")", ":", "image", "=", "layer", ".", "backgroundImage", "if", "image", "is", "None", ":", "return", "ufo_image", "=", "ufo_glyph", ".", "image", "ufo_image", ".", "fileName", "="...
39.363636
0.002257
def import_modules_from_package(package): """Import modules from package and append into sys.modules :param package: full package name, e.g. east.asts """ path = [os.path.dirname(__file__), '..'] + package.split('.') path = os.path.join(*path) for root, dirs, files in os.walk(path): for...
[ "def", "import_modules_from_package", "(", "package", ")", ":", "path", "=", "[", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'..'", "]", "+", "package", ".", "split", "(", "'.'", ")", "path", "=", "os", ".", "path", ".", "join", ...
43.2
0.001511
def escape_string(string): """Escape a string for use in Gerrit commands. :arg str string: The string to escape. :returns: The string with necessary escapes and surrounding double quotes so that it can be passed to any of the Gerrit commands that require double-quoted strings. """ ...
[ "def", "escape_string", "(", "string", ")", ":", "result", "=", "string", "result", "=", "result", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", "result", "=", "result", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")", "return", "'\"'", "+", ...
31.071429
0.002232
def read_csv(user_id, records_path, antennas_path=None, attributes_path=None, recharges_path=None, network=False, duration_format='seconds', describe=True, warnings=True, errors=False, drop_duplicates=False): """ Load user records from a CSV file. Parameters ---------- us...
[ "def", "read_csv", "(", "user_id", ",", "records_path", ",", "antennas_path", "=", "None", ",", "attributes_path", "=", "None", ",", "recharges_path", "=", "None", ",", "network", "=", "False", ",", "duration_format", "=", "'seconds'", ",", "describe", "=", ...
35.179487
0.000945
def retrieve_element_or_default(self, location, default=None): """ Args: location: default: Returns: """ loc_descriptor = self._get_location_descriptor(location) # find node node = None try: node = sel...
[ "def", "retrieve_element_or_default", "(", "self", ",", "location", ",", "default", "=", "None", ")", ":", "loc_descriptor", "=", "self", ".", "_get_location_descriptor", "(", "location", ")", "# find node", "node", "=", "None", "try", ":", "node", "=", "self"...
23.5
0.011364
def get_peak_pos(im, wrap=False): """Get the peak position with subpixel precision Parameters ---------- im: 2d array The image containing a peak wrap: boolean, defaults False True if the image reoresents a torric world Returns ------- [y,x]: 2 numbers The posit...
[ "def", "get_peak_pos", "(", "im", ",", "wrap", "=", "False", ")", ":", "im", "=", "np", ".", "asarray", "(", "im", ")", "# remove invalid values (assuming im>0)", "im", "[", "np", ".", "logical_not", "(", "np", ".", "isfinite", "(", "im", ")", ")", "]"...
25.179487
0.00049
def visit_Assign(self, node): """ Implement assignment walker. Parse class properties defined via the property() function """ # [[[cog # cog.out("print(pcolor('Enter assign visitor', 'magenta'))") # ]]] # [[[end]]] # ### # Class-level assi...
[ "def", "visit_Assign", "(", "self", ",", "node", ")", ":", "# [[[cog", "# cog.out(\"print(pcolor('Enter assign visitor', 'magenta'))\")", "# ]]]", "# [[[end]]]", "# ###", "# Class-level assignment may also be a class attribute that is not", "# a managed attribute, record it anyway, no ha...
33.682927
0.001407
def tplot_rename(old_name, new_name): """ This function will rename tplot variables that are already stored in memory. Parameters: old_name : str Old name of the Tplot Variable new_name : str New name of the Tplot Variable Returns: None ...
[ "def", "tplot_rename", "(", "old_name", ",", "new_name", ")", ":", "#check if old name is in current dictionary", "if", "old_name", "not", "in", "pytplot", ".", "data_quants", ".", "keys", "(", ")", ":", "print", "(", "\"That name is currently not in pytplot\"", ")", ...
29.378378
0.012467
def popup(self): """ Show the notification from code. This will initialize and activate if needed. Notes ------ This does NOT block. Callbacks should be used to handle click events or the `show` state should be observed to know when it is closed. ...
[ "def", "popup", "(", "self", ")", ":", "if", "not", "self", ".", "is_initialized", ":", "self", ".", "initialize", "(", ")", "if", "not", "self", ".", "proxy_is_active", ":", "self", ".", "activate_proxy", "(", ")", "self", ".", "show", "=", "True" ]
31.533333
0.008214
def step3(self): """step3() dels with -ic-, -full, -ness etc. similar strategy to step2.""" if self.b[self.k] == 'e': if self.ends("icate"): self.r("ic") elif self.ends("ative"): self.r("") elif self.ends("alize"): self.r("al") elif self...
[ "def", "step3", "(", "self", ")", ":", "if", "self", ".", "b", "[", "self", ".", "k", "]", "==", "'e'", ":", "if", "self", ".", "ends", "(", "\"icate\"", ")", ":", "self", ".", "r", "(", "\"ic\"", ")", "elif", "self", ".", "ends", "(", "\"ati...
43.357143
0.014516
def prune_by_ngram_count_per_work(self, minimum=None, maximum=None, label=None): """Removes results rows if the n-gram count for all works bearing that n-gram is outside the range specified by `minimum` and `maximum`. That is, if a single witness of...
[ "def", "prune_by_ngram_count_per_work", "(", "self", ",", "minimum", "=", "None", ",", "maximum", "=", "None", ",", "label", "=", "None", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Pruning results by n-gram count per work'", ")", "matches", "=", "se...
43.219512
0.001656
def flush(self, using=None, **kwargs): """ Preforms a flush operation on the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.flush`` unchanged. """ return self._get_connection(using).indices.flush(index=self._name, **kwargs)
[ "def", "flush", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "flush", "(", "index", "=", "self", ".", "_name", ",", "*", "*", "kwargs", ...
37.5
0.009772
def _check_depth_limits(input_dict): '''Returns the default upper and lower depth values if not in dictionary :param input_dict: Dictionary corresponding to the kwargs dictionary of calling function :returns: 'upper_depth': Upper seismogenic depth (float) 'lower_depth': Lower seism...
[ "def", "_check_depth_limits", "(", "input_dict", ")", ":", "if", "(", "'upper_depth'", "in", "input_dict", ".", "keys", "(", ")", ")", "and", "input_dict", "[", "'upper_depth'", "]", ":", "if", "input_dict", "[", "'upper_depth'", "]", "<", "0.", ":", "rais...
37.185185
0.000971
def main(): """ NAME squish.py DESCRIPTION takes dec/inc data and "squishes" with specified flattening factor, flt using formula tan(Io)=flt*tan(If) INPUT declination inclination OUTPUT "squished" declincation inclination SYNTAX ...
[ "def", "main", "(", ")", ":", "ofile", "=", "\"\"", "if", "'-h'", "in", "sys", ".", "argv", ":", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "if", "'-F'", "in", "sys", ".", "argv", ":", "ind", "=", "sys", ".", "ar...
24.867925
0.024818
def handle_translocation_illegal(self, line: str, position: int, tokens: ParseResults) -> None: """Handle a malformed translocation.""" raise MalformedTranslocationWarning(self.get_line_number(), line, position, tokens)
[ "def", "handle_translocation_illegal", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "tokens", ":", "ParseResults", ")", "->", "None", ":", "raise", "MalformedTranslocationWarning", "(", "self", ".", "get_line_number", "(", ")", ",", ...
77.666667
0.017021
def getPeerStats(self): """Get NTP Peer Stats for localhost by querying local NTP Server. @return: Dictionary of NTP stats converted to seconds. """ info_dict = {} output = util.exec_command([ntpqCmd, '-n', '-c', 'peers']) for line in output.splitlines(): ...
[ "def", "getPeerStats", "(", "self", ")", ":", "info_dict", "=", "{", "}", "output", "=", "util", ".", "exec_command", "(", "[", "ntpqCmd", ",", "'-n'", ",", "'-c'", ",", "'peers'", "]", ")", "for", "line", "in", "output", ".", "splitlines", "(", ")",...
40.904762
0.013652
def write(self, data): """ Write the given data to the file. """ # Do the write self.backingStream.write(data) for listener in self.writeListeners: # Send out notifications listener(len(data))
[ "def", "write", "(", "self", ",", "data", ")", ":", "# Do the write", "self", ".", "backingStream", ".", "write", "(", "data", ")", "for", "listener", "in", "self", ".", "writeListeners", ":", "# Send out notifications", "listener", "(", "len", "(", "data", ...
24.727273
0.014184
def discover(url, options={}): """ Retrieve the API definition from the given URL and construct a Patchboard to interface with it. """ try: resp = requests.get(url, headers=Patchboard.default_headers) except Exception as e: raise PatchboardError("Problem discovering API: {0}".for...
[ "def", "discover", "(", "url", ",", "options", "=", "{", "}", ")", ":", "try", ":", "resp", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "Patchboard", ".", "default_headers", ")", "except", "Exception", "as", "e", ":", "raise", "Patc...
32.111111
0.001681
def get_gpubsub_publisher(config, metrics, changes_channel, **kw): """Get a GPubsubPublisher client. A factory function that validates configuration, creates an auth and pubsub API client, and returns a Google Pub/Sub Publisher provider. Args: config (dict): Google Cloud Pub/Sub-related co...
[ "def", "get_gpubsub_publisher", "(", "config", ",", "metrics", ",", "changes_channel", ",", "*", "*", "kw", ")", ":", "builder", "=", "gpubsub_publisher", ".", "GPubsubPublisherBuilder", "(", "config", ",", "metrics", ",", "changes_channel", ",", "*", "*", "kw...
39.25
0.001244
def p_function_statement(self, p): 'function_statement : funcvardecls function_calc' p[0] = p[1] + (p[2],) p.set_lineno(0, p.lineno(1))
[ "def", "p_function_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "(", "p", "[", "2", "]", ",", ")", "p", ".", "set_lineno", "(", "0", ",", "p", ".", "lineno", "(", "1", ")", ")" ]
39
0.012579
def gpg_app_put_key( blockchain_id, appname, keyname, key_data, txid=None, immutable=False, proxy=None, wallet_keys=None, config_dir=None ): """ Put an application GPG key. Stash the private key locally to an app-specific keyring. Return {'status': True, 'key_url': ..., 'key_data': ...} on success ...
[ "def", "gpg_app_put_key", "(", "blockchain_id", ",", "appname", ",", "keyname", ",", "key_data", ",", "txid", "=", "None", ",", "immutable", "=", "False", ",", "proxy", "=", "None", ",", "wallet_keys", "=", "None", ",", "config_dir", "=", "None", ")", ":...
42.263158
0.014604
def thaw(vault_client, src_file, opt): """Given the combination of a Secretfile and the output of a freeze operation, will restore secrets to usable locations""" if not os.path.exists(src_file): raise aomi.exceptions.AomiFile("%s does not exist" % src_file) tmp_dir = ensure_tmpdir() zip_fil...
[ "def", "thaw", "(", "vault_client", ",", "src_file", ",", "opt", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "src_file", ")", ":", "raise", "aomi", ".", "exceptions", ".", "AomiFile", "(", "\"%s does not exist\"", "%", "src_file", ")", ...
42.111111
0.00129
def has_true(self, e, extra_constraints=(), solver=None, model_callback=None): #pylint:disable=unused-argument """ Should return True if `e` can possible be True. :param e: The AST. :param extra_constraints: Extra constraints (as ASTs) to add to the solver for this s...
[ "def", "has_true", "(", "self", ",", "e", ",", "extra_constraints", "=", "(", ")", ",", "solver", "=", "None", ",", "model_callback", "=", "None", ")", ":", "#pylint:disable=unused-argument", "#if self._solver_required and solver is None:", "# raise BackendError(\"%s ...
55.066667
0.011905
def save(self): """The save method for Animal class is over-ridden to set Alive=False when a Death date is entered. This is not the case for a cause of death.""" if self.Death: self.Alive = False super(Animal, self).save()
[ "def", "save", "(", "self", ")", ":", "if", "self", ".", "Death", ":", "self", ".", "Alive", "=", "False", "super", "(", "Animal", ",", "self", ")", ".", "save", "(", ")" ]
51
0.011583
def getID(code_file): """Get the language ID of the input file language""" json_path = ghostfolder+'/'+json_file if os.path.exists(json_path): pass else: download_file('https://ghostbin.com/languages.json') lang = detect_lang(code_file) json_data = json.load(file(json_path))#don't think i need this though ...
[ "def", "getID", "(", "code_file", ")", ":", "json_path", "=", "ghostfolder", "+", "'/'", "+", "json_file", "if", "os", ".", "path", ".", "exists", "(", "json_path", ")", ":", "pass", "else", ":", "download_file", "(", "'https://ghostbin.com/languages.json'", ...
31.894737
0.033654
def do_reload(module: types.ModuleType, newer_than: int) -> bool: """ Executes the reload of the specified module if the source file that it was loaded from was updated more recently than the specified time :param module: A module object to be reloaded :param newer_than: The time in...
[ "def", "do_reload", "(", "module", ":", "types", ".", "ModuleType", ",", "newer_than", ":", "int", ")", "->", "bool", ":", "path", "=", "getattr", "(", "module", ",", "'__file__'", ")", "directory", "=", "getattr", "(", "module", ",", "'__path__'", ",", ...
31.7
0.00102
def pdftotext_conversion_is_bad(txtlines): """Check if conversion after pdftotext is bad. Sometimes pdftotext performs a bad conversion which consists of many spaces and garbage characters. This method takes a list of strings obtained from a pdftotext conversion and examines them to see if they ar...
[ "def", "pdftotext_conversion_is_bad", "(", "txtlines", ")", ":", "# Numbers of 'words' and 'whitespaces' found in document:", "numWords", "=", "numSpaces", "=", "0", "# whitespace character pattern:", "p_space", "=", "re", ".", "compile", "(", "unicode", "(", "r'(\\s)'", ...
39
0.000894
def is_multi_timeseries_orthogonal(nc, variable): ''' Returns true if the variable is a orthogonal multidimensional array representation of time series. For more information on what this means see CF 1.6 §H.2.1 http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html#_orthogonal_multidime...
[ "def", "is_multi_timeseries_orthogonal", "(", "nc", ",", "variable", ")", ":", "# x(i), y(i), z(i), t(o)", "# X(i, o)", "dims", "=", "nc", ".", "variables", "[", "variable", "]", ".", "dimensions", "cmatrix", "=", "coordinate_dimension_matrix", "(", "nc", ")", "fo...
30.441176
0.000936
def k_means(points, k, **kwargs): """ Find k centroids that attempt to minimize the k- means problem: https://en.wikipedia.org/wiki/Metric_k-center Parameters ---------- points: (n, d) float Points in a space k : int Number of centroids to compute **kwargs : dict ...
[ "def", "k_means", "(", "points", ",", "k", ",", "*", "*", "kwargs", ")", ":", "from", "scipy", ".", "cluster", ".", "vq", "import", "kmeans", "from", "scipy", ".", "spatial", "import", "cKDTree", "points", "=", "np", ".", "asanyarray", "(", "points", ...
27.828571
0.000992
def find_declaration( declarations, decl_type=None, name=None, parent=None, recursive=True, fullname=None): """ Returns single declaration that match criteria, defined by developer. If more the one declaration was found None will be returned. For more inf...
[ "def", "find_declaration", "(", "declarations", ",", "decl_type", "=", "None", ",", "name", "=", "None", ",", "parent", "=", "None", ",", "recursive", "=", "True", ",", "fullname", "=", "None", ")", ":", "decl", "=", "find_all_declarations", "(", "declarat...
24.62963
0.001447
def _request(self, url, params=None, data=None, files=None, auth=None, timeout=None, raw_response=False, retry_on_error=True, method=None): """Given a page url and a dict of params, open and return the page. :param url: the url to grab content from. :param para...
[ "def", "_request", "(", "self", ",", "url", ",", "params", "=", "None", ",", "data", "=", "None", ",", "files", "=", "None", ",", "auth", "=", "None", ",", "timeout", "=", "None", ",", "raw_response", "=", "False", ",", "retry_on_error", "=", "True",...
45.989796
0.000869
def is_ready(self): """ Check if pod is in READY condition :return: bool """ if PodCondition.READY in self.get_conditions(): logger.info("Pod: %s in namespace: %s is ready!", self.name, self.namespace) return True return False
[ "def", "is_ready", "(", "self", ")", ":", "if", "PodCondition", ".", "READY", "in", "self", ".", "get_conditions", "(", ")", ":", "logger", ".", "info", "(", "\"Pod: %s in namespace: %s is ready!\"", ",", "self", ".", "name", ",", "self", ".", "namespace", ...
32.222222
0.010067
def clear(self): "Remove all items and reset internal structures" dict.clear(self) self._key = 0 if hasattr(self._tree_view, "wx_obj"): self._tree_view.wx_obj.DeleteAllItems()
[ "def", "clear", "(", "self", ")", ":", "dict", ".", "clear", "(", "self", ")", "self", ".", "_key", "=", "0", "if", "hasattr", "(", "self", ".", "_tree_view", ",", "\"wx_obj\"", ")", ":", "self", ".", "_tree_view", ".", "wx_obj", ".", "DeleteAllItems...
36.5
0.008929
def get_paths(self, connection, path): """ Return *real* and *virtual* paths, resolves ".." with "up" action. *Real* path is path for path_io, when *virtual* deals with "user-view" and user requests :param connection: internal options for current connected user :type con...
[ "def", "get_paths", "(", "self", ",", "connection", ",", "path", ")", ":", "virtual_path", "=", "pathlib", ".", "PurePosixPath", "(", "path", ")", "if", "not", "virtual_path", ".", "is_absolute", "(", ")", ":", "virtual_path", "=", "connection", ".", "curr...
43.222222
0.001676
def unlink(self, node, hyperedge): """ Unlink given node and hyperedge. @type node: node @param node: Node. @type hyperedge: hyperedge @param hyperedge: Hyperedge. """ self.node_links[node].remove(hyperedge) self.edge_links[hyperedge].remove(no...
[ "def", "unlink", "(", "self", ",", "node", ",", "hyperedge", ")", ":", "self", ".", "node_links", "[", "node", "]", ".", "remove", "(", "hyperedge", ")", "self", ".", "edge_links", "[", "hyperedge", "]", ".", "remove", "(", "node", ")", "self", ".", ...
28.461538
0.010471
def clean(amount): """ Converts a number to a number with decimal point. :param str amount: The input number. :rtype: str """ # Return empty input immediately. if not amount: return amount if re.search(r'[\. ][0-9]{3},[0-9]{1,2}$', amount): ...
[ "def", "clean", "(", "amount", ")", ":", "# Return empty input immediately.", "if", "not", "amount", ":", "return", "amount", "if", "re", ".", "search", "(", "r'[\\. ][0-9]{3},[0-9]{1,2}$'", ",", "amount", ")", ":", "# Assume amount is in 1.123,12 or 1 123,12 format (Du...
33.692308
0.00222
def summarizeReads(file_handle, file_type): """ open a fasta or fastq file, prints number of of reads, average length of read, total number of bases, longest, shortest and median read, total number and average of individual base (A, T, G, C, N). """ base_counts = defaultdict(int) read_nu...
[ "def", "summarizeReads", "(", "file_handle", ",", "file_type", ")", ":", "base_counts", "=", "defaultdict", "(", "int", ")", "read_number", "=", "0", "total_length", "=", "0", "length_list", "=", "[", "]", "records", "=", "SeqIO", ".", "parse", "(", "file_...
31.375
0.000966
def attachedimages_inline_factory(lang='en', max_width='', debug=False): ''' Returns InlineModelAdmin for attached images. 'lang' is the language for GearsUploader (can be 'en' and 'ru' at the moment). 'max_width' is default resize width parameter to be set in widget. ''' class _At...
[ "def", "attachedimages_inline_factory", "(", "lang", "=", "'en'", ",", "max_width", "=", "''", ",", "debug", "=", "False", ")", ":", "class", "_AttachedImagesInline", "(", "GenericTabularInline", ")", ":", "model", "=", "AttachedImage", "form", "=", "attachedima...
39.785714
0.001754
def cli(env, billing_id, datacenter): """Adds a load balancer given the id returned from create-options.""" mgr = SoftLayer.LoadBalancerManager(env.client) if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAb...
[ "def", "cli", "(", "env", ",", "billing_id", ",", "datacenter", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "if", "not", "formatting", ".", "confirm", "(", "\"This action will incur charges on your \"", "\"accou...
47.888889
0.002278
def name(self): """ The name of the functional. If the functional is not found in the aliases, the string has the form X_NAME+C_NAME """ if self.xc in self.defined_aliases: return self.defined_aliases[self.xc].name xc = (self.x, self.c) if xc in self.defined_alias...
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "xc", "in", "self", ".", "defined_aliases", ":", "return", "self", ".", "defined_aliases", "[", "self", ".", "xc", "]", ".", "name", "xc", "=", "(", "self", ".", "x", ",", "self", ".", "c",...
45.5
0.015086
def peel_around(method): """ This function will be deprecated. Removes one wrap around the method (given as a parameter) and returns the wrap. If the method is not wrapped, returns None. """ _permission_to_touch_wraps.acquire() # released in finally part try: if hasattr(method,'__as...
[ "def", "peel_around", "(", "method", ")", ":", "_permission_to_touch_wraps", ".", "acquire", "(", ")", "# released in finally part", "try", ":", "if", "hasattr", "(", "method", ",", "'__aspects_enabled'", ")", ":", "# new-style aspect, easy!", "method", ".", "__aspe...
35.344828
0.008547
def _lstat(self, path): '''IMPORTANT: expects `path`'s parent to already be deref()'erenced.''' if path not in self.entries: return OverlayStat(*self.originals['os:lstat'](path)[:10], st_overlay=0) return self.entries[path].stat
[ "def", "_lstat", "(", "self", ",", "path", ")", ":", "if", "path", "not", "in", "self", ".", "entries", ":", "return", "OverlayStat", "(", "*", "self", ".", "originals", "[", "'os:lstat'", "]", "(", "path", ")", "[", ":", "10", "]", ",", "st_overla...
48.4
0.00813
def float_encode(self, value): """Convert the integer value to its IGMPv3 encoded time value if needed. If value < 128, return the value specified. If >= 128, encode as a floating point value. Value can be 0 - 31744. """ if value < 128: code = value elif value > 31743: code = 25...
[ "def", "float_encode", "(", "self", ",", "value", ")", ":", "if", "value", "<", "128", ":", "code", "=", "value", "elif", "value", ">", "31743", ":", "code", "=", "255", "else", ":", "exp", "=", "0", "value", ">>=", "3", "while", "(", "value", ">...
24.631579
0.032922
def train(target, dataset, cluster_spec, ctx): """Train Inception on a dataset for a number of steps.""" # Number of workers and parameter servers are infered from the workers and ps # hosts string. num_workers = len(cluster_spec.as_dict()['worker']) num_parameter_servers = len(cluster_spec.as_dict()['ps']) ...
[ "def", "train", "(", "target", ",", "dataset", ",", "cluster_spec", ",", "ctx", ")", ":", "# Number of workers and parameter servers are infered from the workers and ps", "# hosts string.", "num_workers", "=", "len", "(", "cluster_spec", ".", "as_dict", "(", ")", "[", ...
44.177358
0.011946
def temporary_file(mode): """Cross platform temporary file creation. This is an alternative to ``tempfile.NamedTemporaryFile`` that also works on windows and avoids the "file being used by another process" error. """ tempdir = tempfile.gettempdir() basename = 'tmpfile-%s' % (uuid.uuid4()) ...
[ "def", "temporary_file", "(", "mode", ")", ":", "tempdir", "=", "tempfile", ".", "gettempdir", "(", ")", "basename", "=", "'tmpfile-%s'", "%", "(", "uuid", ".", "uuid4", "(", ")", ")", "full_filename", "=", "os", ".", "path", ".", "join", "(", "tempdir...
32.210526
0.001587
def grant(self, lock, unit): '''Maybe grant the lock to a unit. The decision to grant the lock or not is made for $lock by a corresponding method grant_$lock, which you may define in a subclass. If no such method is defined, the default_grant method is used. See Serial.default_g...
[ "def", "grant", "(", "self", ",", "lock", ",", "unit", ")", ":", "if", "not", "hookenv", ".", "is_leader", "(", ")", ":", "return", "False", "# Not the leader, so we cannot grant.", "# Set of units already granted the lock.", "granted", "=", "set", "(", ")", "fo...
37.707317
0.001261
def load(self, cnf, metadata_construction=False): """ The base load method, loads the configuration :param cnf: The configuration as a dictionary :param metadata_construction: Is this only to be able to construct metadata. If so some things can be left out. :return: The Conf...
[ "def", "load", "(", "self", ",", "cnf", ",", "metadata_construction", "=", "False", ")", ":", "_uc", "=", "self", ".", "unicode_convert", "for", "arg", "in", "COMMON_ARGS", ":", "if", "arg", "==", "\"virtual_organization\"", ":", "if", "\"virtual_organization\...
39.086957
0.001085
def erf(f=Ellipsis): ''' erf(x) yields a potential function that calculates the error function over the input x. If x is a constant, yields a constant potential function. erf() is equivalent to erf(...), which is just the error function, calculated over its inputs. ''' f = to_potential(f) ...
[ "def", "erf", "(", "f", "=", "Ellipsis", ")", ":", "f", "=", "to_potential", "(", "f", ")", "if", "is_const_potential", "(", "f", ")", ":", "return", "const_potential", "(", "np", ".", "erf", "(", "f", ".", "c", ")", ")", "elif", "is_identity_potenti...
47.3
0.012448
def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Add...
[ "def", "_windows_remotes_on", "(", "port", ",", "which_end", ")", ":", "remotes", "=", "set", "(", ")", "try", ":", "data", "=", "subprocess", ".", "check_output", "(", "[", "'netstat'", ",", "'-n'", "]", ")", "# pylint: disable=minimum-python-version", "excep...
33.861111
0.001595
def create(cls, mr_spec, shard_number, shard_attempt, _writer_state=None): """Inherit docs.""" writer_spec = cls.get_params(mr_spec.mapper, allow_old=False) # Determine parameters key = cls._generate_filename(writer_spec, mr_spec.name, mr_spec.mapreduce_id, ...
[ "def", "create", "(", "cls", ",", "mr_spec", ",", "shard_number", ",", "shard_attempt", ",", "_writer_state", "=", "None", ")", ":", "writer_spec", "=", "cls", ".", "get_params", "(", "mr_spec", ".", "mapper", ",", "allow_old", "=", "False", ")", "# Determ...
36.4375
0.001672
def rm(path, isdir=False): """delete file or dir returns True if deleted, if file/dir not exists, return False :param path: path to delete :param isdir: set True if you want to delete dir """ if isdir: deleted = os.path.isdir(path) shutil.rmtree(path, ignore_errors=True) eli...
[ "def", "rm", "(", "path", ",", "isdir", "=", "False", ")", ":", "if", "isdir", ":", "deleted", "=", "os", ".", "path", ".", "isdir", "(", "path", ")", "shutil", ".", "rmtree", "(", "path", ",", "ignore_errors", "=", "True", ")", "elif", "os", "."...
28.25
0.002141
def _build_collapse_to_gene_dict(graph) -> Dict[BaseEntity, Set[BaseEntity]]: """Build a collapse dictionary. :param pybel.BELGraph graph: A BEL graph :return: A dictionary of {node: set of PyBEL node tuples} """ collapse_dict = defaultdict(set) r2g = {} for gene_node, rna_node, d in graph...
[ "def", "_build_collapse_to_gene_dict", "(", "graph", ")", "->", "Dict", "[", "BaseEntity", ",", "Set", "[", "BaseEntity", "]", "]", ":", "collapse_dict", "=", "defaultdict", "(", "set", ")", "r2g", "=", "{", "}", "for", "gene_node", ",", "rna_node", ",", ...
30.038462
0.002481
def COM(z, M, **cosmo): """ Calculate concentration for halo of mass 'M' at redshift 'z' Parameters ---------- z : float / numpy array Redshift to find concentration of halo M : float / numpy array Halo mass at redshift 'z'. Must be same size as 'z' cosmo : dict Dictiona...
[ "def", "COM", "(", "z", ",", "M", ",", "*", "*", "cosmo", ")", ":", "# Check that z and M are arrays", "z", "=", "np", ".", "array", "(", "z", ",", "ndmin", "=", "1", ",", "dtype", "=", "float", ")", "M", "=", "np", ".", "array", "(", "M", ",",...
38.428571
0.000362
def rename(args): """ %prog rename genes.bed [gaps.bed] Rename genes for annotation release. For genes on chromosomes (e.g. the 12th gene on C1): Bo1g00120 For genes on scaffolds (e.g. the 12th gene on unplaced Scaffold00285): Bo00285s120 The genes identifiers will increment by 10. S...
[ "def", "rename", "(", "args", ")", ":", "import", "string", "p", "=", "OptionParser", "(", "rename", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"-a\"", ",", "dest", "=", "\"gene_increment\"", ",", "default", "=", "10", ",", "type", "=", "\"int...
33.288889
0.001297
def normalizeLibValue(value): """ Normalizes lib value. * **value** must not be ``None``. * Returned value is the same type as the input value. """ if value is None: raise ValueError("Lib value must not be None.") if isinstance(value, (list, tuple)): for v in value: ...
[ "def", "normalizeLibValue", "(", "value", ")", ":", "if", "value", "is", "None", ":", "raise", "ValueError", "(", "\"Lib value must not be None.\"", ")", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "for", "v", "in", "...
28.789474
0.00177
def set_ec2_settings(self, aws_region=None, aws_availability_zone=None, vpc_id=None, subnet_id=None, master_elastic_ip=None, role_instance_profile=None, ...
[ "def", "set_ec2_settings", "(", "self", ",", "aws_region", "=", "None", ",", "aws_availability_zone", "=", "None", ",", "vpc_id", "=", "None", ",", "subnet_id", "=", "None", ",", "master_elastic_ip", "=", "None", ",", "role_instance_profile", "=", "None", ",",...
40.733333
0.008793
def apply_complement(self, a, return_Ya=False): """Apply the complementary projection to an array. :param z: array with ``shape==(N,m)``. :return: :math:`P_{\\mathcal{Y}^\\perp,\\mathcal{X}}z = z - P_{\\mathcal{X},\\mathcal{Y}^\\perp} z`. """ # is projection the zer...
[ "def", "apply_complement", "(", "self", ",", "a", ",", "return_Ya", "=", "False", ")", ":", "# is projection the zero operator? --> complement is identity", "if", "self", ".", "V", ".", "shape", "[", "1", "]", "==", "0", ":", "if", "return_Ya", ":", "return", ...
32.5
0.002491
def ConstructObject(self, py_obj): ''' note py_obj items are NOT converted to PyJs types! ''' obj = self.NewObject() for k, v in py_obj.items(): obj.put(unicode(k), v) return obj
[ "def", "ConstructObject", "(", "self", ",", "py_obj", ")", ":", "obj", "=", "self", ".", "NewObject", "(", ")", "for", "k", ",", "v", "in", "py_obj", ".", "items", "(", ")", ":", "obj", ".", "put", "(", "unicode", "(", "k", ")", ",", "v", ")", ...
36.166667
0.009009
def get_equation_components(equation_str): """ Breaks down a string representing only the equation part of a model element. Recognizes the various types of model elements that may exist, and identifies them. Parameters ---------- equation_str : basestring the first section in each model...
[ "def", "get_equation_components", "(", "equation_str", ")", ":", "component_structure_grammar", "=", "_include_common_grammar", "(", "r\"\"\"\n entry = component / subscript_definition / lookup_definition\n component = name _ subscriptlist? _ \"=\" _ expression\n subscript_definition = ...
31.41
0.001235
def get_diversity(self,X): """compute mean diversity of individual outputs""" # diversity in terms of cosine distances between features feature_correlations = np.zeros(X.shape[0]-1) for i in np.arange(1,X.shape[0]-1): feature_correlations[i] = max(0.0,r2_score(X[0],X[i])) ...
[ "def", "get_diversity", "(", "self", ",", "X", ")", ":", "# diversity in terms of cosine distances between features", "feature_correlations", "=", "np", ".", "zeros", "(", "X", ".", "shape", "[", "0", "]", "-", "1", ")", "for", "i", "in", "np", ".", "arange"...
49.75
0.014815
def pickle_to_param(obj, name): """ Return the top-level element of a document sub-tree containing the pickled serialization of a Python object. """ return from_pyvalue(u"pickle:%s" % name, unicode(pickle.dumps(obj)))
[ "def", "pickle_to_param", "(", "obj", ",", "name", ")", ":", "return", "from_pyvalue", "(", "u\"pickle:%s\"", "%", "name", ",", "unicode", "(", "pickle", ".", "dumps", "(", "obj", ")", ")", ")" ]
36.166667
0.027027
def get_ppis(self, ppi_df): """Generate Complex Statements from the HPRD PPI data. Parameters ---------- ppi_df : pandas.DataFrame DataFrame loaded from the BINARY_PROTEIN_PROTEIN_INTERACTIONS.txt file. """ logger.info('Processing PPIs...') ...
[ "def", "get_ppis", "(", "self", ",", "ppi_df", ")", ":", "logger", ".", "info", "(", "'Processing PPIs...'", ")", "for", "ix", ",", "row", "in", "ppi_df", ".", "iterrows", "(", ")", ":", "agA", "=", "self", ".", "_make_agent", "(", "row", "[", "'HPRD...
40
0.00222
def add_slot_ports(self, slot): """ Add the ports to be added for a adapter card :param str slot: Slot name """ slot_nb = int(slot[4]) # slot_adapter = None # if slot in self.node['properties']: # slot_adapter = self.node['properties'][slot] #...
[ "def", "add_slot_ports", "(", "self", ",", "slot", ")", ":", "slot_nb", "=", "int", "(", "slot", "[", "4", "]", ")", "# slot_adapter = None", "# if slot in self.node['properties']:", "# slot_adapter = self.node['properties'][slot]", "# elif self.device_info['model'] == 'c...
35.096774
0.001789
def prepare_for_reraise(error, exc_info=None): """Prepares the exception for re-raising with reraise method. This method attaches type and traceback info to the error object so that reraise can properly reraise it using this info. """ if not hasattr(error, "_type_"): if exc_info is None: ...
[ "def", "prepare_for_reraise", "(", "error", ",", "exc_info", "=", "None", ")", ":", "if", "not", "hasattr", "(", "error", ",", "\"_type_\"", ")", ":", "if", "exc_info", "is", "None", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "error", ".",...
33.461538
0.002237
def browse(self): ''' Browse the history of a single file adds one commit that doesn't contain changes in test_file_1. there are four commits in summary, so the check for buffer line count compares with 3. at the end, a fifth commit must be present due to resetting the fi...
[ "def", "browse", "(", "self", ")", ":", "check", "=", "self", ".", "_check", "marker_text", "=", "Random", ".", "string", "(", ")", "self", ".", "vim", ".", "buffer", ".", "set_content", "(", "[", "marker_text", "]", ")", "self", ".", "_save", "(", ...
36.814815
0.001961
def filter_by_key(self, keys, ID=None): """ Keep only Measurements with given keys. """ keys = to_list(keys) fil = lambda x: x in keys if ID is None: ID = self.ID return self.filter(fil, applyto='keys', ID=ID)
[ "def", "filter_by_key", "(", "self", ",", "keys", ",", "ID", "=", "None", ")", ":", "keys", "=", "to_list", "(", "keys", ")", "fil", "=", "lambda", "x", ":", "x", "in", "keys", "if", "ID", "is", "None", ":", "ID", "=", "self", ".", "ID", "retur...
29.888889
0.01083
def set_config(**kwargs): """Set up the configure of profiler (only accepts keyword arguments). Parameters ---------- filename : string, output file for profile data profile_all : boolean, all profile types enabled profile_symbolic : boolean, whether to profile symbolic ...
[ "def", "set_config", "(", "*", "*", "kwargs", ")", ":", "kk", "=", "kwargs", ".", "keys", "(", ")", "vv", "=", "kwargs", ".", "values", "(", ")", "check_call", "(", "_LIB", ".", "MXSetProcessProfilerConfig", "(", "len", "(", "kwargs", ")", ",", "c_st...
39.428571
0.002122
def create_class_from_xml_string(target_class, xml_string): """Creates an instance of the target class from a string. :param target_class: The class which will be instantiated and populated with the contents of the XML. This class must have a c_tag and a c_namespace class variable. :param x...
[ "def", "create_class_from_xml_string", "(", "target_class", ",", "xml_string", ")", ":", "if", "not", "isinstance", "(", "xml_string", ",", "six", ".", "binary_type", ")", ":", "xml_string", "=", "xml_string", ".", "encode", "(", "'utf-8'", ")", "tree", "=", ...
49.388889
0.001104
def compute_offset_nuth(dh, slope, aspect, min_count=100, remove_outliers=True, plot=True): """Compute horizontal offset between input rasters using Nuth and Kaab [2011] (nuth) method """ import scipy.optimize as optimization if dh.count() < min_count: sys.exit("Not enough dh samples") if s...
[ "def", "compute_offset_nuth", "(", "dh", ",", "slope", ",", "aspect", ",", "min_count", "=", "100", ",", "remove_outliers", "=", "True", ",", "plot", "=", "True", ")", ":", "import", "scipy", ".", "optimize", "as", "optimization", "if", "dh", ".", "count...
38.104046
0.013454
def egress(self, envelope, http_headers, operation, binding_options): """Overriding the egress function to set our headers. Args: envelope: An Element with the SOAP request data. http_headers: A dict of the current http headers. operation: The SoapOperation instance. binding_options: An...
[ "def", "egress", "(", "self", ",", "envelope", ",", "http_headers", ",", "operation", ",", "binding_options", ")", ":", "custom_headers", "=", "self", ".", "_header_handler", ".", "GetHTTPHeaders", "(", ")", "http_headers", ".", "update", "(", "custom_headers", ...
35.933333
0.001808
def return_hdr(self): """Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str ...
[ "def", "return_hdr", "(", "self", ")", ":", "orig", "=", "{", "}", "for", "xml_file", "in", "self", ".", "filename", ".", "glob", "(", "'*.xml'", ")", ":", "if", "xml_file", ".", "stem", "[", "0", "]", "!=", "'.'", ":", "orig", "[", "xml_file", "...
35.09375
0.000866
def validAspects(self, ID, aspList): """ Returns a list with the aspects an object makes with the other six planets, considering a list of possible aspects. """ obj = self.chart.getObject(ID) res = [] for otherID in const.LIST_SEVEN_PLANETS: ...
[ "def", "validAspects", "(", "self", ",", "ID", ",", "aspList", ")", ":", "obj", "=", "self", ".", "chart", ".", "getObject", "(", "ID", ")", "res", "=", "[", "]", "for", "otherID", "in", "const", ".", "LIST_SEVEN_PLANETS", ":", "if", "ID", "==", "o...
31.619048
0.010234
def rates_for_location(self, postal_code, location_deets=None): """Shows the sales tax rates for a given location.""" request = self._get("rates/" + postal_code, location_deets) return self.responder(request)
[ "def", "rates_for_location", "(", "self", ",", "postal_code", ",", "location_deets", "=", "None", ")", ":", "request", "=", "self", ".", "_get", "(", "\"rates/\"", "+", "postal_code", ",", "location_deets", ")", "return", "self", ".", "responder", "(", "requ...
57.25
0.008621
def parse_xml(self, node): """ Parse a map from ElementTree xml node :param node: ElementTree xml node :return: self """ self._set_properties(node) self.background_color = node.get('backgroundcolor', self.background_color) ...
[ "def", "parse_xml", "(", "self", ",", "node", ")", ":", "self", ".", "_set_properties", "(", "node", ")", "self", ".", "background_color", "=", "node", ".", "get", "(", "'backgroundcolor'", ",", "self", ".", "background_color", ")", "# *** do not chang...
38.297872
0.001625
def combine_intersections( intersections, nodes1, degree1, nodes2, degree2, all_types ): r"""Combine curve-curve intersections into curved polygon(s). .. note:: This is a helper used only by :meth:`.Surface.intersect`. Does so assuming each intersection lies on an edge of one of two :class...
[ "def", "combine_intersections", "(", "intersections", ",", "nodes1", ",", "degree1", ",", "nodes2", ",", "degree2", ",", "all_types", ")", ":", "if", "intersections", ":", "return", "basic_interior_combine", "(", "intersections", ")", "elif", "all_types", ":", "...
39.104167
0.00052
def _process_scopes(scopes): """Parse a scopes list into a set of all scopes and a set of sufficient scope sets. scopes: A list of strings, each of which is a space-separated list of scopes. Examples: ['scope1'] ['scope1', 'scope2'] ['scope1', 'scope2 scope3'] Retu...
[ "def", "_process_scopes", "(", "scopes", ")", ":", "all_scopes", "=", "set", "(", ")", "sufficient_scopes", "=", "set", "(", ")", "for", "scope_set", "in", "scopes", ":", "scope_set_scopes", "=", "frozenset", "(", "scope_set", ".", "split", "(", ")", ")", ...
39
0.009535
def uncompress_files(original, destination): """ Move file from original path to destination path. :type original: str :param original: The location of zip file :type destination: str :param destination: The extract path """ with zipfile.ZipFile(original) as zips: ...
[ "def", "uncompress_files", "(", "original", ",", "destination", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "original", ")", "as", "zips", ":", "extract_path", "=", "os", ".", "path", ".", "join", "(", "destination", ")", "zips", ".", "extractall", ...
30.230769
0.002469
def setup(self, phase=None, quantity='', conductance='', **kwargs): r""" This method takes several arguments that are essential to running the algorithm and adds them to the settings. Parameters ---------- phase : OpenPNM Phase object The phase on which the a...
[ "def", "setup", "(", "self", ",", "phase", "=", "None", ",", "quantity", "=", "''", ",", "conductance", "=", "''", ",", "*", "*", "kwargs", ")", ":", "if", "phase", ":", "self", ".", "settings", "[", "'phase'", "]", "=", "phase", ".", "name", "if...
38.827586
0.000866
def cumulative_time_on_drug( drug_events_df: DataFrame, query_times_df: DataFrame, event_lasts_for_timedelta: datetime.timedelta = None, event_lasts_for_quantity: float = None, event_lasts_for_units: str = None, patient_colname: str = DEFAULT_PATIENT_COLNAME, ...
[ "def", "cumulative_time_on_drug", "(", "drug_events_df", ":", "DataFrame", ",", "query_times_df", ":", "DataFrame", ",", "event_lasts_for_timedelta", ":", "datetime", ".", "timedelta", "=", "None", ",", "event_lasts_for_quantity", ":", "float", "=", "None", ",", "ev...
50.248175
0.000142
def is_known_type(self, type_name): """Check if type is known to the type system. Returns: bool: True if the type is a known instantiated simple type, False otherwise """ type_name = str(type_name) if type_name in self.known_types: return True r...
[ "def", "is_known_type", "(", "self", ",", "type_name", ")", ":", "type_name", "=", "str", "(", "type_name", ")", "if", "type_name", "in", "self", ".", "known_types", ":", "return", "True", "return", "False" ]
26.666667
0.009063
def makeMany2ManyRelatedManager(formodel, name_relmodel, name_formodel): '''formodel is the model which the manager .''' class _Many2ManyRelatedManager(Many2ManyRelatedManager): pass _Many2ManyRelatedManager.formodel = formodel _Many2ManyRelatedManager.name_relmodel = name_relmodel ...
[ "def", "makeMany2ManyRelatedManager", "(", "formodel", ",", "name_relmodel", ",", "name_formodel", ")", ":", "class", "_Many2ManyRelatedManager", "(", "Many2ManyRelatedManager", ")", ":", "pass", "_Many2ManyRelatedManager", ".", "formodel", "=", "formodel", "_Many2ManyRel...
40.3
0.002427