text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def paste(client, event, channel, nick, rest): "Drop a link to your latest paste" path = '/last/{nick}'.format(**locals()) paste_root = pmxbot.config.get('librarypaste', 'http://paste.jaraco.com') url = urllib.parse.urljoin(paste_root, path) auth = pmxbot.config.get('librarypaste auth') resp = requests.head(url, ...
[ "def", "paste", "(", "client", ",", "event", ",", "channel", ",", "nick", ",", "rest", ")", ":", "path", "=", "'/last/{nick}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "paste_root", "=", "pmxbot", ".", "config", ".", "get", "(", "'li...
46.2
0.021231
def open_spider(self, spider): """ Callback function when spider is open. """ # Store timestamp to replace {time} in S3PIPELINE_URL self.ts = datetime.utcnow().replace(microsecond=0).isoformat().replace(':', '-')
[ "def", "open_spider", "(", "self", ",", "spider", ")", ":", "# Store timestamp to replace {time} in S3PIPELINE_URL", "self", ".", "ts", "=", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "microsecond", "=", "0", ")", ".", "isoformat", "(", ")", "...
41.166667
0.011905
def generate_pipeline(ctx, codebuild_image, source, buildspec_file, filename): # type: (click.Context, str, str, str, str) -> None """Generate a cloudformation template for a starter CD pipeline. This command will write a starter cloudformation template to the filename you provide. It contains a CodeC...
[ "def", "generate_pipeline", "(", "ctx", ",", "codebuild_image", ",", "source", ",", "buildspec_file", ",", "filename", ")", ":", "# type: (click.Context, str, str, str, str) -> None", "from", "chalice", "import", "pipeline", "factory", "=", "ctx", ".", "obj", "[", "...
41.657143
0.00067
def ordered(obj): """ Return sorted version of nested dicts/lists for comparing. Modified from: http://stackoverflow.com/a/25851972 """ if isinstance(obj, collections.abc.Mapping): return sorted((k, ordered(v)) for k, v in obj.items()) # Special case str since it's a collections.abc...
[ "def", "ordered", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "collections", ".", "abc", ".", "Mapping", ")", ":", "return", "sorted", "(", "(", "k", ",", "ordered", "(", "v", ")", ")", "for", "k", ",", "v", "in", "obj", ".", "it...
30.75
0.001972
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile): """ Channel Input File Read from File Method """ # Set file extension property self.fileExtension = extension # Dictionary of keywords/cards and parse fun...
[ "def", "_read", "(", "self", ",", "directory", ",", "filename", ",", "session", ",", "path", ",", "name", ",", "extension", ",", "spatial", ",", "spatialReferenceID", ",", "replaceParamFile", ")", ":", "# Set file extension property", "self", ".", "fileExtension...
38.067797
0.001302
def _unify_sources_and_hashes(source=None, source_hash=None, sources=None, source_hashes=None): ''' Silly little function to give us a standard tuple list for sources and source_hashes ''' if sources is None: sources = [] if source_hashes is None: s...
[ "def", "_unify_sources_and_hashes", "(", "source", "=", "None", ",", "source_hash", "=", "None", ",", "sources", "=", "None", ",", "source_hashes", "=", "None", ")", ":", "if", "sources", "is", "None", ":", "sources", "=", "[", "]", "if", "source_hashes", ...
31.16
0.001245
async def set_message( self, text=None, reply_to=0, parse_mode=(), link_preview=None): """ Changes the draft message on the Telegram servers. The changes are reflected in this object. :param str text: New text of the draft. Preserved if l...
[ "async", "def", "set_message", "(", "self", ",", "text", "=", "None", ",", "reply_to", "=", "0", ",", "parse_mode", "=", "(", ")", ",", "link_preview", "=", "None", ")", ":", "if", "text", "is", "None", ":", "text", "=", "self", ".", "_text", "if",...
31.659574
0.001304
def connect(state, host, for_fact=None): ''' Connect to a single host. Returns the SSH client if succesful. Stateless by design so can be run in parallel. ''' kwargs = _make_paramiko_kwargs(state, host) logger.debug('Connecting to: {0} ({1})'.format(host.name, kwargs)) # Hostname can be pr...
[ "def", "connect", "(", "state", ",", "host", ",", "for_fact", "=", "None", ")", ":", "kwargs", "=", "_make_paramiko_kwargs", "(", "state", ",", "host", ")", "logger", ".", "debug", "(", "'Connecting to: {0} ({1})'", ".", "format", "(", "host", ".", "name",...
27.757143
0.000497
def write_top(outpath, molecules, title): """ Write a basic TOP file. The topology is written in *outpath*. If *outpath* is en empty string, or anything for which ``bool(outpath) == False``, the topology is written on the standard error, and the header is omitted, and only what has been buit by...
[ "def", "write_top", "(", "outpath", ",", "molecules", ",", "title", ")", ":", "topmolecules", "=", "[", "]", "for", "i", "in", "molecules", ":", "if", "i", "[", "0", "]", ".", "endswith", "(", "'.o'", ")", ":", "topmolecules", ".", "append", "(", "...
38.066667
0.002277
def dump(self, conf_file=None): """ Dump the possibly updated config to a file. Args: conf_file: str, the destination, or None to overwrite the existing configuration. """ if conf_file: conf_dir = os.path.dirname(conf_file) if...
[ "def", "dump", "(", "self", ",", "conf_file", "=", "None", ")", ":", "if", "conf_file", ":", "conf_dir", "=", "os", ".", "path", ".", "dirname", "(", "conf_file", ")", "if", "not", "conf_dir", ":", "conf_dir", "=", "self", ".", "__invoke_dir", "elif", ...
37.395349
0.001212
def fill_livetime_hist(skydir, tab_sc, tab_gti, zmax, costh_edges): """Generate a sequence of livetime distributions at the sky positions given by ``skydir``. The output of the method are two NxM arrays containing a sequence of histograms for N sky positions and M incidence angle bins where the bin edg...
[ "def", "fill_livetime_hist", "(", "skydir", ",", "tab_sc", ",", "tab_gti", ",", "zmax", ",", "costh_edges", ")", ":", "if", "len", "(", "tab_gti", ")", "==", "0", ":", "shape", "=", "(", "len", "(", "costh_edges", ")", "-", "1", ",", "len", "(", "s...
34.359551
0.001271
def _displayattrs(attrib, expandattrs): """ Helper function to display the attributes of a Node object in lexicographic order. :param attrib: dictionary with the attributes :param expandattrs: if True also displays the value of the attributes """ if not attrib: return '' if expa...
[ "def", "_displayattrs", "(", "attrib", ",", "expandattrs", ")", ":", "if", "not", "attrib", ":", "return", "''", "if", "expandattrs", ":", "alist", "=", "[", "'%s=%r'", "%", "item", "for", "item", "in", "sorted", "(", "attrib", ".", "items", "(", ")", ...
30.533333
0.002119
def get_config(self, key, default=None): ''' Lookup a config field and return its value, first checking the route.config, then route.app.config.''' for conf in (self.config, self.app.conifg): if key in conf: return conf[key] return default
[ "def", "get_config", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "for", "conf", "in", "(", "self", ".", "config", ",", "self", ".", "app", ".", "conifg", ")", ":", "if", "key", "in", "conf", ":", "return", "conf", "[", "key", ...
47
0.010453
def is_equal(self, other_consonnant): """ >>> v_consonant = Consonant(Place.labio_dental, Manner.fricative, True, "v", False) >>> f_consonant = Consonant(Place.labio_dental, Manner.fricative, False, "f", False) >>> v_consonant.is_equal(f_consonant) False :param other_con...
[ "def", "is_equal", "(", "self", ",", "other_consonnant", ")", ":", "return", "self", ".", "place", "==", "other_consonnant", ".", "place", "and", "self", ".", "manner", "==", "other_consonnant", ".", "manner", "and", "self", ".", "voiced", "==", "other_conso...
45.666667
0.012522
def last_location_of_minimum(x): """ Returns the last location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ ...
[ "def", "last_location_of_minimum", "(", "x", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "return", "1.0", "-", "np", ".", "argmin", "(", "x", "[", ":", ":", "-", "1", "]", ")", "/", "len", "(", "x", ")", "if", "len", "(", "x", ...
33.166667
0.002445
def build(self, title, text, img_url): """ :param title: Title of the card :param text: Description of the card :param img_url: Image of the card """ super(ImageCard, self).build() self.title = Title(id=self.id + "-title", text=title, classname="card-title", size=...
[ "def", "build", "(", "self", ",", "title", ",", "text", ",", "img_url", ")", ":", "super", "(", "ImageCard", ",", "self", ")", ".", "build", "(", ")", "self", ".", "title", "=", "Title", "(", "id", "=", "self", ".", "id", "+", "\"-title\"", ",", ...
49.307692
0.009188
def writetofastq(data, dsort, read): """ Writes sorted data 'dsort dict' to a tmp files """ if read == 1: rrr = "R1" else: rrr = "R2" for sname in dsort: ## skip writing if empty. Write to tmpname handle = os.path.join(data.dirs.fastqs, "{}_{}_....
[ "def", "writetofastq", "(", "data", ",", "dsort", ",", "read", ")", ":", "if", "read", "==", "1", ":", "rrr", "=", "\"R1\"", "else", ":", "rrr", "=", "\"R2\"", "for", "sname", "in", "dsort", ":", "## skip writing if empty. Write to tmpname", "handle", "=",...
27.733333
0.011628
def to_python(self, reply, propagate=True): """Extracts the value out of the reply message. :param reply: In the case of a successful call the reply message will be:: {'ok': return_value, **default_fields} Therefore the method returns: return_value, **default_f...
[ "def", "to_python", "(", "self", ",", "reply", ",", "propagate", "=", "True", ")", ":", "try", ":", "return", "reply", "[", "'ok'", "]", "except", "KeyError", ":", "error", "=", "self", ".", "Error", "(", "*", "reply", ".", "get", "(", "'nok'", ")"...
30.884615
0.002415
def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs): ''' Execute a single state orchestration routine .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt-run state.orchestrate_high '{ stage_one: {salt.state: [{tgt: "db*"}, {...
[ "def", "orchestrate_high", "(", "data", ",", "test", "=", "None", ",", "queue", "=", "False", ",", "pillar", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "pillar", "is", "not", "None", "and", "not", "isinstance", "(", "pillar", ",", "dict", ...
30.676471
0.001859
def data_axis_order(self): """Permutation of ``(0, 1, 2)``. The value is determined from the ``'mapc', 'mapr', 'maps'`` header entries and determines the order of the axes of a dataset (`data_shape`) when stored in a file (`data_storage_shape`):: data_shape[i] == da...
[ "def", "data_axis_order", "(", "self", ")", ":", "if", "not", "self", ".", "header", ":", "return", "(", "0", ",", "1", ",", "2", ")", "try", ":", "mapc", "=", "self", ".", "header", "[", "'mapc'", "]", "[", "'value'", "]", "mapr", "=", "self", ...
38.463415
0.001237
def doc(func): """ Find the message shown when someone calls the help command Parameters ---------- func : function the function Returns ------- str The help message for this command """ stripped_chars = " \t" if hasattr(func, '__doc__'): docstr...
[ "def", "doc", "(", "func", ")", ":", "stripped_chars", "=", "\" \\t\"", "if", "hasattr", "(", "func", ",", "'__doc__'", ")", ":", "docstring", "=", "func", ".", "__doc__", ".", "lstrip", "(", "\" \\n\\t\"", ")", "if", "\"\\n\"", "in", "docstring", ":", ...
21.8
0.001757
def _draw_lines(self, bg, colour, extent, line, xo, yo): """Draw a set of lines from a vector tile.""" coords = [self._scale_coords(x, y, extent, xo, yo) for x, y in line] self._draw_lines_internal(coords, colour, bg)
[ "def", "_draw_lines", "(", "self", ",", "bg", ",", "colour", ",", "extent", ",", "line", ",", "xo", ",", "yo", ")", ":", "coords", "=", "[", "self", ".", "_scale_coords", "(", "x", ",", "y", ",", "extent", ",", "xo", ",", "yo", ")", "for", "x",...
59.5
0.008299
def _update_individual(X, W, R, gamma): """Update the individual components `S_i`. Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, timepoints] Each element in the list contains the fMRI data for alignment of one subject. W : ...
[ "def", "_update_individual", "(", "X", ",", "W", ",", "R", ",", "gamma", ")", ":", "subjs", "=", "len", "(", "X", ")", "S", "=", "[", "]", "for", "i", "in", "range", "(", "subjs", ")", ":", "S", ".", "append", "(", "RSRM", ".", "_shrink", "("...
31.354839
0.001996
def _upsample(self, method, limit=None, fill_value=None): """ Parameters ---------- method : string {'backfill', 'bfill', 'pad', 'ffill'} method for upsampling limit : int, default None Maximum size gap to fill when reindexing fill_value : scalar, ...
[ "def", "_upsample", "(", "self", ",", "method", ",", "limit", "=", "None", ",", "fill_value", "=", "None", ")", ":", "# we may need to actually resample as if we are timestamps", "if", "self", ".", "kind", "==", "'timestamp'", ":", "return", "super", "(", ")", ...
30.470588
0.001871
def cluster( self, cluster_id, location_id=None, serve_nodes=None, default_storage_type=None ): """Factory to create a cluster associated with this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_create_cluster] :end-befo...
[ "def", "cluster", "(", "self", ",", "cluster_id", ",", "location_id", "=", "None", ",", "serve_nodes", "=", "None", ",", "default_storage_type", "=", "None", ")", ":", "return", "Cluster", "(", "cluster_id", ",", "self", ",", "location_id", "=", "location_id...
42.382979
0.001963
def _write_to_device_and_return(cmd, ack, device_connection): '''Writes to a serial device. - Formats command - Wait for ack return - return parsed response''' log.debug('Write -> {}'.format(cmd.encode())) device_connection.write(cmd.encode()) response = device_connection.read_until(ack.enco...
[ "def", "_write_to_device_and_return", "(", "cmd", ",", "ack", ",", "device_connection", ")", ":", "log", ".", "debug", "(", "'Write -> {}'", ".", "format", "(", "cmd", ".", "encode", "(", ")", ")", ")", "device_connection", ".", "write", "(", "cmd", ".", ...
40.058824
0.001435
def add_docker_file_to_tarfile(self, docker_file, tar): """Add a Dockerfile to a tarfile""" with hp.a_temp_file() as dockerfile: log.debug("Context: ./Dockerfile") dockerfile.write("\n".join(docker_file.docker_lines).encode('utf-8')) dockerfile.seek(0) tar...
[ "def", "add_docker_file_to_tarfile", "(", "self", ",", "docker_file", ",", "tar", ")", ":", "with", "hp", ".", "a_temp_file", "(", ")", "as", "dockerfile", ":", "log", ".", "debug", "(", "\"Context: ./Dockerfile\"", ")", "dockerfile", ".", "write", "(", "\"\...
51.285714
0.008219
def exists(Name, region=None, key=None, keyid=None, profile=None): ''' Given a rule name, check to see if the given rule exists. Returns True if the given rule exists and returns False if the given rule does not exist. CLI example:: salt myminion boto_cloudwatch_event.exists myevent regio...
[ "def", "exists", "(", "Name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "="...
32.541667
0.001244
def sshpull(host, maildir, localmaildir, noop=False, verbose=False, filterfile=None): """Pull a remote maildir to the local one. """ store = _SSHStore(host, maildir) _pull(store, localmaildir, noop, verbose, filterfile)
[ "def", "sshpull", "(", "host", ",", "maildir", ",", "localmaildir", ",", "noop", "=", "False", ",", "verbose", "=", "False", ",", "filterfile", "=", "None", ")", ":", "store", "=", "_SSHStore", "(", "host", ",", "maildir", ")", "_pull", "(", "store", ...
46.2
0.008511
def convolve(data, kernel, method='scipy'): r"""Convolve data with kernel This method convolves the input data with a given kernel using FFT and is the default convolution used for all routines Parameters ---------- data : np.ndarray Input data array, normally a 2D image kernel : n...
[ "def", "convolve", "(", "data", ",", "kernel", ",", "method", "=", "'scipy'", ")", ":", "if", "data", ".", "ndim", "!=", "kernel", ".", "ndim", ":", "raise", "ValueError", "(", "'Data and kernel must have the same dimensions.'", ")", "if", "method", "not", "...
27.591549
0.000493
def readline(self): """Read a chunk of the output""" _LOGGER.info("reading line") line = self.read(self.line_length) if len(line) < self.line_length: _LOGGER.info("all lines read") return line
[ "def", "readline", "(", "self", ")", ":", "_LOGGER", ".", "info", "(", "\"reading line\"", ")", "line", "=", "self", ".", "read", "(", "self", ".", "line_length", ")", "if", "len", "(", "line", ")", "<", "self", ".", "line_length", ":", "_LOGGER", "....
34
0.008197
def close_client_stream(client_stream, unix_path): """ Closes provided client stream """ try: client_stream.shutdown(socket.SHUT_RDWR) if unix_path: logger.debug('%s: Connection closed', unix_path) else: peer = client_stream.getpeername() logger.debug(...
[ "def", "close_client_stream", "(", "client_stream", ",", "unix_path", ")", ":", "try", ":", "client_stream", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "if", "unix_path", ":", "logger", ".", "debug", "(", "'%s: Connection closed'", ",", "unix_path", ...
41.083333
0.001984
def files(self): """ Returns a data frame with Sample files. Not very readable... """ nameordered = self.samples.keys() nameordered.sort() ## replace curdir with . for shorter printing #fullcurdir = os.path.realpath(os.path.curdir) return pd.DataFrame([self.samples[i].fil...
[ "def", "files", "(", "self", ")", ":", "nameordered", "=", "self", ".", "samples", ".", "keys", "(", ")", "nameordered", ".", "sort", "(", ")", "## replace curdir with . for shorter printing", "#fullcurdir = os.path.realpath(os.path.curdir)", "return", "pd", ".", "D...
50.625
0.012136
def trace_symlink_target(link): """ Given a file that is known to be a symlink, trace it to its ultimate target. Raises TargetNotPresent when the target cannot be determined. Raises ValueError when the specified link is not a symlink. """ if not is_symlink(link): raise ValueError("link must point to a symlin...
[ "def", "trace_symlink_target", "(", "link", ")", ":", "if", "not", "is_symlink", "(", "link", ")", ":", "raise", "ValueError", "(", "\"link must point to a symlink on the system\"", ")", "while", "is_symlink", "(", "link", ")", ":", "orig", "=", "os", ".", "pa...
28.0625
0.030172
def get_ip(request): """Return the IP address inside the HTTP_X_FORWARDED_FOR var inside the `request` object. The return of this function can be overrided by the `LOCAL_GEOLOCATION_IP` variable in the `conf` module. This function will skip local IPs (starting with 10. and equals to 127.0.0.1)...
[ "def", "get_ip", "(", "request", ")", ":", "if", "getsetting", "(", "'LOCAL_GEOLOCATION_IP'", ")", ":", "return", "getsetting", "(", "'LOCAL_GEOLOCATION_IP'", ")", "forwarded_for", "=", "request", ".", "META", ".", "get", "(", "'HTTP_X_FORWARDED_FOR'", ")", "if"...
28.625
0.001408
def meff_lh_110(self, **kwargs): ''' Returns the light-hole band effective mass in the [110] direction, meff_lh_110, in units of electron mass. ''' return 2. / (2 * self.luttinger1(**kwargs) + self.luttinger2(**kwargs) + 3 * self.luttinger3(**kwargs))
[ "def", "meff_lh_110", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "2.", "/", "(", "2", "*", "self", ".", "luttinger1", "(", "*", "*", "kwargs", ")", "+", "self", ".", "luttinger2", "(", "*", "*", "kwargs", ")", "+", "3", "*", "sel...
43
0.009772
def get_definitive_name(self, unique_ajps, join_character = '-', prepend_label = True): """ Generates a definitive name for this benchmark run object, based on unique additional join parameters (as passed) """ name = '' for ajp in unique_ajps: if len(name) > 0...
[ "def", "get_definitive_name", "(", "self", ",", "unique_ajps", ",", "join_character", "=", "'-'", ",", "prepend_label", "=", "True", ")", ":", "name", "=", "''", "for", "ajp", "in", "unique_ajps", ":", "if", "len", "(", "name", ")", ">", "0", ":", "nam...
37.933333
0.012007
def _raise_deferred_exc(self): """Raises deferred exceptions from the daemon's synchronous path in the post-fork client.""" if self._deferred_exception: try: exc_type, exc_value, exc_traceback = self._deferred_exception raise_with_traceback(exc_value, exc_traceback) except TypeError:...
[ "def", "_raise_deferred_exc", "(", "self", ")", ":", "if", "self", ".", "_deferred_exception", ":", "try", ":", "exc_type", ",", "exc_value", ",", "exc_traceback", "=", "self", ".", "_deferred_exception", "raise_with_traceback", "(", "exc_value", ",", "exc_traceba...
49.8
0.009862
def prepare(self): """ Preparatory checks for whether this Executor can go ahead and (try to) build its targets. """ for s in self.get_all_sources(): if s.missing(): msg = "Source `%s' not found, needed by target `%s'." raise SCons.Erro...
[ "def", "prepare", "(", "self", ")", ":", "for", "s", "in", "self", ".", "get_all_sources", "(", ")", ":", "if", "s", ".", "missing", "(", ")", ":", "msg", "=", "\"Source `%s' not found, needed by target `%s'.\"", "raise", "SCons", ".", "Errors", ".", "Stop...
40.333333
0.008086
def _get_text(self): """ Get the current metadata """ if self._data.get("state") == PLAYING: color = self.py3.COLOR_PLAYING or self.py3.COLOR_GOOD state_symbol = self.state_play elif self._data.get("state") == PAUSED: color = self.py3.COLOR_PAU...
[ "def", "_get_text", "(", "self", ")", ":", "if", "self", ".", "_data", ".", "get", "(", "\"state\"", ")", "==", "PLAYING", ":", "color", "=", "self", ".", "py3", ".", "COLOR_PLAYING", "or", "self", ".", "py3", ".", "COLOR_GOOD", "state_symbol", "=", ...
33.363636
0.001985
def process_text(text, save_xml_name='trips_output.xml', save_xml_pretty=True, offline=False, service_endpoint='drum'): """Return a TripsProcessor by processing text. Parameters ---------- text : str The text to be processed. save_xml_name : Optional[str] The name o...
[ "def", "process_text", "(", "text", ",", "save_xml_name", "=", "'trips_output.xml'", ",", "save_xml_pretty", "=", "True", ",", "offline", "=", "False", ",", "service_endpoint", "=", "'drum'", ")", ":", "if", "not", "offline", ":", "html", "=", "client", ".",...
38.444444
0.000805
def delete(self): """Delete the persistent identifier. If the persistent identifier haven't been registered yet, it is removed from the database. Otherwise, it's marked as :attr:`invenio_pidstore.models.PIDStatus.DELETED`. :returns: `True` if the PID is successfully removed. ...
[ "def", "delete", "(", "self", ")", ":", "removed", "=", "False", "try", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "if", "self", ".", "is_new", "(", ")", ":", "# New persistent identifier which haven't been registered", "# yet.", ...
35.517241
0.00189
def _help_add_edge(self, u: BaseEntity, v: BaseEntity, attr: Mapping) -> str: """Help add a pre-built edge.""" self.add_node_from_data(u) self.add_node_from_data(v) return self._help_add_edge_helper(u, v, attr)
[ "def", "_help_add_edge", "(", "self", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "attr", ":", "Mapping", ")", "->", "str", ":", "self", ".", "add_node_from_data", "(", "u", ")", "self", ".", "add_node_from_data", "(", "v", ")", "ret...
39.666667
0.00823
def getFasta(opened_file, sequence_name): """ Retrieves a sequence from an opened multifasta file :param opened_file: an opened multifasta file eg. opened_file=open("/path/to/file.fa",'r+') :param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:1...
[ "def", "getFasta", "(", "opened_file", ",", "sequence_name", ")", ":", "lines", "=", "opened_file", ".", "readlines", "(", ")", "seq", "=", "str", "(", "\"\"", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "lines", ")", ")", ":", "line...
30.727273
0.01912
def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Re...
[ "def", "stop_and_persist", "(", "self", ",", "symbol", "=", "' '", ",", "text", "=", "None", ")", ":", "if", "not", "self", ".", "_enabled", ":", "return", "self", "symbol", "=", "decode_utf_8_text", "(", "symbol", ")", "if", "text", "is", "not", "None...
24.095238
0.001899
def _logsumexp(ary, *, b=None, b_inv=None, axis=None, keepdims=False, out=None, copy=True): """Stable logsumexp when b >= 0 and b is scalar. b_inv overwrites b unless b_inv is None. """ # check dimensions for result arrays ary = np.asarray(ary) if ary.dtype.kind == "i": ary = ary.astype...
[ "def", "_logsumexp", "(", "ary", ",", "*", ",", "b", "=", "None", ",", "b_inv", "=", "None", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ",", "out", "=", "None", ",", "copy", "=", "True", ")", ":", "# check dimensions for result arrays", ...
33.648148
0.001604
def mkfs(device, fs_type): ''' Makes a file system <fs_type> on partition <device>, destroying all data that resides on that partition. <fs_type> must be one of "ext2", "fat32", "fat16", "linux-swap" or "reiserfs" (if libreiserfs is installed) CLI Example: .. code-block:: bash salt '*...
[ "def", "mkfs", "(", "device", ",", "fs_type", ")", ":", "_validate_device", "(", "device", ")", "if", "not", "_is_fstype", "(", "fs_type", ")", ":", "raise", "CommandExecutionError", "(", "'Invalid fs_type passed to partition.mkfs'", ")", "if", "fs_type", "==", ...
28.533333
0.00113
def accept_publish( self, service, mask, value, method, handler=None, schedule=False): '''Set a handler for incoming publish messages :param service: the incoming message must have this service :type service: anything hash-able :param mask: value to be bitwise-an...
[ "def", "accept_publish", "(", "self", ",", "service", ",", "mask", ",", "value", ",", "method", ",", "handler", "=", "None", ",", "schedule", "=", "False", ")", ":", "# support @hub.accept_publish(serv, mask, val, meth) decorator usage", "if", "handler", "is", "No...
42.191489
0.001479
def register(self, address, retry=True): """This function will send a register packet to the discovered Neteria server. Args: address (tuple): A tuple of the (address, port) to send the register request to. retry (boolean): Whether or not we want to reset the cur...
[ "def", "register", "(", "self", ",", "address", ",", "retry", "=", "True", ")", ":", "logger", ".", "debug", "(", "\"<%s> Sending REGISTER request to: %s\"", "%", "(", "str", "(", "self", ".", "cuuid", ")", ",", "str", "(", "address", ")", ")", ")", "i...
35.23913
0.001801
def build_default_simulation(self, tax_benefit_system, count = 1): """ Build a simulation where: - There are ``count`` persons - There are ``count`` instances of each group entity, containing one person - Every person has, in each entity, the first rol...
[ "def", "build_default_simulation", "(", "self", ",", "tax_benefit_system", ",", "count", "=", "1", ")", ":", "simulation", "=", "Simulation", "(", "tax_benefit_system", ",", "tax_benefit_system", ".", "instantiate_entities", "(", ")", ")", "for", "population", "in...
49.2
0.009309
def _uniform_correlation_like_matrix(num_rows, batch_shape, dtype, seed): """Returns a uniformly random `Tensor` of "correlation-like" matrices. A "correlation-like" matrix is a symmetric square matrix with all entries between -1 and 1 (inclusive) and 1s on the main diagonal. Of these, the ones that are posit...
[ "def", "_uniform_correlation_like_matrix", "(", "num_rows", ",", "batch_shape", ",", "dtype", ",", "seed", ")", ":", "num_entries", "=", "num_rows", "*", "(", "num_rows", "+", "1", ")", "/", "2", "ones", "=", "tf", ".", "ones", "(", "shape", "=", "[", ...
44.837838
0.00944
def dict_jsonp(param): """Convert the parameter into a dictionary before calling jsonp, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonp(param)
[ "def", "dict_jsonp", "(", "param", ")", ":", "if", "not", "isinstance", "(", "param", ",", "dict", ")", ":", "param", "=", "dict", "(", "param", ")", "return", "jsonp", "(", "param", ")" ]
40.4
0.009709
def _summary(fit, pars=None, probs=None, **kwargs): """Summarize samples (compute mean, SD, quantiles) in all chains. REF: stanfit-class.R summary method Parameters ---------- fit : StanFit4Model object pars : str or sequence of str, optional Parameter names. By default use all paramet...
[ "def", "_summary", "(", "fit", ",", "pars", "=", "None", ",", "probs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "fit", ".", "mode", "==", "1", ":", "msg", "=", "\"Stan model {} is of mode 'test_grad'; sampling is not conducted.\"", "msg", "=", ...
43.225806
0.001824
def options(self, options=None): """Options Sets or gets the list of acceptable values for the Node Arguments: options {list} -- A list of valid values Raises: TypeError, ValueError Returns: None | list """ # If opts aren't set, this is a getter if options is None: return self._options ...
[ "def", "options", "(", "self", ",", "options", "=", "None", ")", ":", "# If opts aren't set, this is a getter", "if", "options", "is", "None", ":", "return", "self", ".", "_options", "# If the options are not a list", "if", "not", "isinstance", "(", "options", ","...
26.416
0.02948
def get_account_user(self, account_id, user_id, **kwargs): # noqa: E501 """Details of the user. # noqa: E501 An endpoint for retrieving details of the user. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/users/{userID} -H 'Authorization: Bearer API_KEY'` # noq...
[ "def", "get_account_user", "(", "self", ",", "account_id", ",", "user_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", ...
54.5
0.001639
def _preprocess_scan_params(self, xml_params): """ Processes the scan parameters. """ params = {} for param in xml_params: params[param.tag] = param.text or '' # Set default values. for key in self.scanner_params: if key not in params: para...
[ "def", "_preprocess_scan_params", "(", "self", ",", "xml_params", ")", ":", "params", "=", "{", "}", "for", "param", "in", "xml_params", ":", "params", "[", "param", ".", "tag", "]", "=", "param", ".", "text", "or", "''", "# Set default values.", "for", ...
46.71875
0.001966
def compile_function(node, globals_=None): """Convert an AST or string into a function with inspectable source. This function uses `compile_file` internally, but instead of returning the entire module it will return the function only. Args: node: A `FunctionDef` node or a `Module` node which contains at l...
[ "def", "compile_function", "(", "node", ",", "globals_", "=", "None", ")", ":", "if", "not", "isinstance", "(", "node", ",", "gast", ".", "AST", ")", ":", "if", "not", "isinstance", "(", "node", ",", "six", ".", "string_types", ")", ":", "raise", "Ty...
30.833333
0.009607
def domains(request): """ A page with number of services and layers faceted on domains. """ url = '' query = '*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0' if settings.SEARCH_TYPE == 'elasticsearch': url = '%s/select?q=%s' % (settings.SEARCH...
[ "def", "domains", "(", "request", ")", ":", "url", "=", "''", "query", "=", "'*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0'", "if", "settings", ".", "SEARCH_TYPE", "==", "'elasticsearch'", ":", "url", "=", "'%s/select?q=%s'", ...
39
0.002176
def to_str(self, pretty_print=False, encoding=None, **kw): u"""Converts a node with all of it's children to a string. Remaining arguments are passed to etree.tostring as is. kwarg without_comments: bool because it works only in C14N flags: 'pretty print' and 'encoding' are ignored. ...
[ "def", "to_str", "(", "self", ",", "pretty_print", "=", "False", ",", "encoding", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "kw", ".", "get", "(", "'without_comments'", ")", "and", "not", "kw", ".", "get", "(", "'method'", ")", ":", "kw", ...
36.521739
0.00232
def do_plot(args): """ Create plots of mcmc output """ import ugali.utils.plotting import pylab as plt config,name,label,coord = args filenames = make_filenames(config,label) srcfile = filenames['srcfile'] samfile = filenames['samfile'] memfile = filenames['memfile'] if not exists(...
[ "def", "do_plot", "(", "args", ")", ":", "import", "ugali", ".", "utils", ".", "plotting", "import", "pylab", "as", "plt", "config", ",", "name", ",", "label", ",", "coord", "=", "args", "filenames", "=", "make_filenames", "(", "config", ",", "label", ...
32.78125
0.01851
def delete_collection_cluster_role(self, **kwargs): """ delete collection of ClusterRole This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_cluster_role(async_req=True) ...
[ "def", "delete_collection_cluster_role", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "delete_collection_cluster_role...
167.666667
0.002196
def pcolormesh(*args, **kwargs): """ Use for large datasets Non-traditional `pcolormesh` kwargs are: - xticklabels, which will put x tick labels exactly in the center of the heatmap block - yticklables, which will put y tick labels exactly aligned in the center of the heatmap block - ...
[ "def", "pcolormesh", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Deal with arguments in kwargs that should be there, or need to be taken", "# out", "fig", ",", "ax", ",", "args", ",", "kwargs", "=", "maybe_get_fig_ax", "(", "*", "args", ",", "*", "*...
35.305085
0.000467
def present(name, password, permission): ''' Ensure the user exists on the Dell DRAC name: The users username password The password used to authenticate permission The permissions that should be assigned to a user ''' ret = {'name': name, 'result': True,...
[ "def", "present", "(", "name", ",", "password", ",", "permission", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", "}", "users", "=", "__salt__", "[", "'d...
26.35
0.000915
def ensure_text(fname, text, repo_dpath='.', force=None, locals_={}, chmod=None): """ Args: fname (str): file name text (str): repo_dpath (str): directory path string(default = '.') force (bool): (default = False) locals_ (dict): (default = {}) Example: >>>...
[ "def", "ensure_text", "(", "fname", ",", "text", ",", "repo_dpath", "=", "'.'", ",", "force", "=", "None", ",", "locals_", "=", "{", "}", ",", "chmod", "=", "None", ")", ":", "import", "utool", "as", "ut", "ut", ".", "colorprint", "(", "'Ensuring fna...
29.1875
0.002073
def get_channel_image(self, channel, img_size=300, skip_cache=False): """Get the logo for a channel""" from bs4 import BeautifulSoup from wikipedia.exceptions import PageError import re import wikipedia wikipedia.set_lang('fr') if not channel: _LOGGER...
[ "def", "get_channel_image", "(", "self", ",", "channel", ",", "img_size", "=", "300", ",", "skip_cache", "=", "False", ")", ":", "from", "bs4", "import", "BeautifulSoup", "from", "wikipedia", ".", "exceptions", "import", "PageError", "import", "re", "import", ...
41.083333
0.000991
def get_graph_url(self, target, graphite_url=None): """Get Graphite URL.""" return self._graphite_url(target, graphite_url=graphite_url, raw_data=False)
[ "def", "get_graph_url", "(", "self", ",", "target", ",", "graphite_url", "=", "None", ")", ":", "return", "self", ".", "_graphite_url", "(", "target", ",", "graphite_url", "=", "graphite_url", ",", "raw_data", "=", "False", ")" ]
55.333333
0.017857
def set_prewarp(self, prewarp): """ Updates the prewarp configuration used to skew images in OpenALPR before processing. :param prewarp: A unicode/ascii string (Python 2/3) or bytes array (Python 3) :return: None """ prewarp = _convert_to_charp(prewarp) s...
[ "def", "set_prewarp", "(", "self", ",", "prewarp", ")", ":", "prewarp", "=", "_convert_to_charp", "(", "prewarp", ")", "self", ".", "_set_prewarp_func", "(", "self", ".", "alpr_pointer", ",", "prewarp", ")" ]
36
0.01084
def get_key(raw=False): """ Gets a single key from stdin """ while True: try: if kbhit(): char = getch() ordinal = ord(char) if ordinal in (0, 224): extention = ord(getch()) scan_code = ordinal + exte...
[ "def", "get_key", "(", "raw", "=", "False", ")", ":", "while", "True", ":", "try", ":", "if", "kbhit", "(", ")", ":", "char", "=", "getch", "(", ")", "ordinal", "=", "ord", "(", "char", ")", "if", "ordinal", "in", "(", "0", ",", "224", ")", "...
32.105263
0.001592
def replace_color(self, before, after): """ Replaces a color on a surface with another one. :param before: Change all pixels with this color :param after: To that color :type before: tuple :type after: tuple """ #TODO: find out if this actually works ...
[ "def", "replace_color", "(", "self", ",", "before", ",", "after", ")", ":", "#TODO: find out if this actually works", "#((self.matrix[x][y] = after for y in range(self.height) if self.matrix[x][y] == before) for x in range(self.width))", "for", "x", "in", "range", "(", "self", "....
39.8
0.008183
def get_mean_and_stddevs(self, sites, rup, dists, imt, stds_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ mean_list = [] stddvs_list = [] # Loop over averaging ...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stds_types", ")", ":", "mean_list", "=", "[", "]", "stddvs_list", "=", "[", "]", "# Loop over averaging periods", "for", "period", "in", "self", ".", "avg...
37.264706
0.001538
def get_pool_for_host(self, host_id): """Returns the connection pool for the given host. This connection pool is used by the redis clients to make sure that it does not have to reconnect constantly. If you want to use a custom redis client you can pass this in as connection pool ...
[ "def", "get_pool_for_host", "(", "self", ",", "host_id", ")", ":", "if", "isinstance", "(", "host_id", ",", "HostInfo", ")", ":", "host_info", "=", "host_id", "host_id", "=", "host_info", ".", "host_id", "else", ":", "host_info", "=", "self", ".", "hosts",...
44.477273
0.001
def container_config_set(name, config_key, config_value, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Set a container config value name : Name of the container config_key : The config key to set config_value : The config value to s...
[ "def", "container_config_set", "(", "name", ",", "config_key", ",", "config_value", ",", "remote_addr", "=", "None", ",", "cert", "=", "None", ",", "key", "=", "None", ",", "verify_cert", "=", "True", ")", ":", "container", "=", "container_get", "(", "name...
24.26087
0.000861
def gravity(RAW_IMU, SENSOR_OFFSETS=None, ofs=None, mul=None, smooth=0.7): '''estimate pitch from accelerometer''' if hasattr(RAW_IMU, 'xacc'): rx = RAW_IMU.xacc * 9.81 / 1000.0 ry = RAW_IMU.yacc * 9.81 / 1000.0 rz = RAW_IMU.zacc * 9.81 / 1000.0 else: rx = RAW_IMU.AccX ...
[ "def", "gravity", "(", "RAW_IMU", ",", "SENSOR_OFFSETS", "=", "None", ",", "ofs", "=", "None", ",", "mul", "=", "None", ",", "smooth", "=", "0.7", ")", ":", "if", "hasattr", "(", "RAW_IMU", ",", "'xacc'", ")", ":", "rx", "=", "RAW_IMU", ".", "xacc"...
32.863636
0.001344
def make_chunks(self,length=0,overlap=0,play=0,sl=0,excl_play=0,pad_data=0): """ Divides the science segment into chunks of length seconds overlapped by overlap seconds. If the play option is set, only chunks that contain S2 playground data are generated. If the user has a more complicated way of ge...
[ "def", "make_chunks", "(", "self", ",", "length", "=", "0", ",", "overlap", "=", "0", ",", "play", "=", "0", ",", "sl", "=", "0", ",", "excl_play", "=", "0", ",", "pad_data", "=", "0", ")", ":", "time_left", "=", "self", ".", "dur", "(", ")", ...
48.163265
0.012043
def draw_graph(adata, layout=None, **kwargs) -> Union[Axes, List[Axes], None]: """\ Scatter plot in graph-drawing basis. Parameters ---------- {adata_color_etc} layout : {{'fa', 'fr', 'drl', ...}}, optional (default: last computed) One of the `draw_graph` layouts, see :func:`~sc...
[ "def", "draw_graph", "(", "adata", ",", "layout", "=", "None", ",", "*", "*", "kwargs", ")", "->", "Union", "[", "Axes", ",", "List", "[", "Axes", "]", ",", "None", "]", ":", "if", "layout", "is", "None", ":", "layout", "=", "str", "(", "adata", ...
33.407407
0.002155
def to_df(figure): """ Extracts the data from a Plotly Figure Parameters ---------- figure : plotly_figure Figure from which data will be extracted Returns a DataFrame or list of DataFrame """ dfs=[] for trace in figure['data']: if '...
[ "def", "to_df", "(", "figure", ")", ":", "dfs", "=", "[", "]", "for", "trace", "in", "figure", "[", "'data'", "]", ":", "if", "'scatter'", "in", "trace", "[", "'type'", "]", ":", "try", ":", "if", "type", "(", "trace", "[", "'x'", "]", "[", "0"...
33.454545
0.020678
def export_model(model_path): """Take the latest checkpoint and copy it to model_path. Assumes that all relevant model files are prefixed by the same name. (For example, foo.index, foo.meta and foo.data-00000-of-00001). Args: model_path: The path (can be a gs:// path) to export model """ ...
[ "def", "export_model", "(", "model_path", ")", ":", "estimator", "=", "tf", ".", "estimator", ".", "Estimator", "(", "model_fn", ",", "model_dir", "=", "FLAGS", ".", "work_dir", ",", "params", "=", "FLAGS", ".", "flag_values_dict", "(", ")", ")", "latest_c...
46.333333
0.001175
async def running(self): """Start websocket connection.""" try: async with self._session.ws_connect(self._url) as ws: self.state = STATE_RUNNING async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: ensure_futu...
[ "async", "def", "running", "(", "self", ")", ":", "try", ":", "async", "with", "self", ".", "_session", ".", "ws_connect", "(", "self", ".", "_url", ")", "as", "ws", ":", "self", ".", "state", "=", "STATE_RUNNING", "async", "for", "msg", "in", "ws", ...
41.333333
0.00197
def scan_and_connect(self, devnames, timeout=DEF_TIMEOUT, calibration=True): """Scan for and then connect to a set of one or more SK8s. This method is intended to be a simple way to combine the steps of running a BLE scan, checking the results and connecting to one or more devices. Whe...
[ "def", "scan_and_connect", "(", "self", ",", "devnames", ",", "timeout", "=", "DEF_TIMEOUT", ",", "calibration", "=", "True", ")", ":", "responses", "=", "self", ".", "scan_devices", "(", "devnames", ",", "timeout", ")", "for", "dev", "in", "devnames", ":"...
48.107143
0.009461
def main(): """Command-line entry point for running the view server.""" import getopt from . import __version__ as VERSION try: option_list, argument_list = getopt.gnu_getopt( sys.argv[1:], 'h', ['version', 'help', 'json-module=', 'debug', 'log-file=']) message ...
[ "def", "main", "(", ")", ":", "import", "getopt", "from", ".", "import", "__version__", "as", "VERSION", "try", ":", "option_list", ",", "argument_list", "=", "getopt", ".", "gnu_getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "'h'", ",", ...
38.068182
0.001164
def get_file_systems(filesystemid=None, keyid=None, key=None, profile=None, region=None, creation_token=None, **kwargs): ''' Get all EFS properties or a specific instance property if...
[ "def", "get_file_systems", "(", "filesystemid", "=", "None", ",", "keyid", "=", "None", ",", "key", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "creation_token", "=", "None", ",", "*", "*", "kwargs", ")", ":", "result", ...
32.296296
0.000556
def _annotate_crossmatch_with_value_added_parameters( self, crossmatchDict, catalogueName, searchPara, search_name): """*annotate each crossmatch with physical parameters such are distances etc* **Key Arguments:** - ``crossmatchDic...
[ "def", "_annotate_crossmatch_with_value_added_parameters", "(", "self", ",", "crossmatchDict", ",", "catalogueName", ",", "searchPara", ",", "search_name", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_annotate_crossmatch_with_value_added_parameters`` met...
41.574074
0.002175
def ParseFileObject(self, parser_mediator, file_object): """Parses a text file-like object using a pyparsing definition. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like obj...
[ "def", "ParseFileObject", "(", "self", ",", "parser_mediator", ",", "file_object", ")", ":", "# TODO: self._line_structures is a work-around and this needs", "# a structural fix.", "if", "not", "self", ".", "_line_structures", ":", "raise", "errors", ".", "UnableToParseFile...
37.010989
0.008097
def parse(self, limit=None): """ We process each of the postgres tables in turn. The order of processing is important here, as we build up a hashmap of internal vs external identifers (unique keys by type to FB id). These include allele, marker (gene), publication, strain, genoty...
[ "def", "parse", "(", "self", ",", "limit", "=", "None", ")", ":", "if", "limit", "is", "not", "None", ":", "LOG", ".", "info", "(", "\"Only parsing first %d rows of each file\"", ",", "limit", ")", "LOG", ".", "info", "(", "\"Parsing files...\"", ")", "if"...
38.315789
0.000893
def allck(): ''' 檢查所有股票買賣點,剔除$10以下、成交量小於1000張的股票。 ''' for i in twseno().allstockno: a = goristock.goristock(i) try: if a.stock_vol[-1] > 1000*1000 and a.raw_data[-1] > 10: #a.goback(3) ## 倒退天數 ck4m(a) except: pass
[ "def", "allck", "(", ")", ":", "for", "i", "in", "twseno", "(", ")", ".", "allstockno", ":", "a", "=", "goristock", ".", "goristock", "(", "i", ")", "try", ":", "if", "a", ".", "stock_vol", "[", "-", "1", "]", ">", "1000", "*", "1000", "and", ...
24.8
0.027237
def merge_versions(self, merge_id): """Get the merge versions from pagination""" payload = { 'order_by': 'updated_at', 'sort': 'asc', 'per_page': PER_PAGE } path = urijoin(GitLabClient.MERGES, str(merge_id), GitLabClient.VERSIONS) return self...
[ "def", "merge_versions", "(", "self", ",", "merge_id", ")", ":", "payload", "=", "{", "'order_by'", ":", "'updated_at'", ",", "'sort'", ":", "'asc'", ",", "'per_page'", ":", "PER_PAGE", "}", "path", "=", "urijoin", "(", "GitLabClient", ".", "MERGES", ",", ...
30.636364
0.008646
def _get_mean_rock(self, mag, _rake, rrup, is_reverse, imt): """ Calculate and return the mean intensity for rock sites. Implements an equation from table 2. """ if mag <= self.NEAR_FIELD_SATURATION_MAG: C = self.COEFFS_ROCK_LOWMAG[imt] else: C = ...
[ "def", "_get_mean_rock", "(", "self", ",", "mag", ",", "_rake", ",", "rrup", ",", "is_reverse", ",", "imt", ")", ":", "if", "mag", "<=", "self", ".", "NEAR_FIELD_SATURATION_MAG", ":", "C", "=", "self", ".", "COEFFS_ROCK_LOWMAG", "[", "imt", "]", "else", ...
41.086957
0.002068
def revfile_path(self): """ :return: The full path of revision file. :rtype: str """ return os.path.normpath(os.path.join( os.getcwd(), self.config.revision_file ))
[ "def", "revfile_path", "(", "self", ")", ":", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "self", ".", "config", ".", "revision_file", ")", ")" ]
25.333333
0.008475
def r_squared(obs, pred, one_to_one=False, log_trans=False): """ R^2 value for a regression of observed and predicted data Parameters ---------- obs : iterable Observed data pred : iterable Predicted data one_to_one : bool If True, calculates the R^2 based on the one...
[ "def", "r_squared", "(", "obs", ",", "pred", ",", "one_to_one", "=", "False", ",", "log_trans", "=", "False", ")", ":", "if", "log_trans", ":", "obs", "=", "np", ".", "log", "(", "obs", ")", "pred", "=", "np", ".", "log", "(", "pred", ")", "if", ...
27.075949
0.000451
def filterGraph(graph, node_fnc): """Remove all nodes for with node_fnc does not hold """ nodes = filter(lambda l: node_fnc(l), graph.nodes()) edges = {} gedges = graph.edges() for u in gedges: if u not in nodes: continue for v in gedges[u]: if v not in nodes: continue try: edge...
[ "def", "filterGraph", "(", "graph", ",", "node_fnc", ")", ":", "nodes", "=", "filter", "(", "lambda", "l", ":", "node_fnc", "(", "l", ")", ",", "graph", ".", "nodes", "(", ")", ")", "edges", "=", "{", "}", "gedges", "=", "graph", ".", "edges", "(...
20.368421
0.044444
def inherit_from_std_ex(node: astroid.node_classes.NodeNG) -> bool: """ Return true if the given class node is subclass of exceptions.Exception. """ ancestors = node.ancestors() if hasattr(node, "ancestors") else [] for ancestor in itertools.chain([node], ancestors): if ( anc...
[ "def", "inherit_from_std_ex", "(", "node", ":", "astroid", ".", "node_classes", ".", "NodeNG", ")", "->", "bool", ":", "ancestors", "=", "node", ".", "ancestors", "(", ")", "if", "hasattr", "(", "node", ",", "\"ancestors\"", ")", "else", "[", "]", "for",...
35.538462
0.00211
def jr6_jr6(mag_file, dir_path=".", input_dir_path="", meas_file="measurements.txt", spec_file="specimens.txt", samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt", specnum=1, samp_con='1', location='unknown', lat='', lon='', noave=False, meth_code="L...
[ "def", "jr6_jr6", "(", "mag_file", ",", "dir_path", "=", "\".\"", ",", "input_dir_path", "=", "\"\"", ",", "meas_file", "=", "\"measurements.txt\"", ",", "spec_file", "=", "\"specimens.txt\"", ",", "samp_file", "=", "\"samples.txt\"", ",", "site_file", "=", "\"s...
42.581749
0.001745
def dev_random_entropy(numbytes, fallback_to_urandom=True): """ Reads random bytes from the /dev/random entropy pool. NOTE: /dev/random is a blocking pseudorandom number generator. If the entropy pool runs out, this function will block until more environmental noise is gathered. If ...
[ "def", "dev_random_entropy", "(", "numbytes", ",", "fallback_to_urandom", "=", "True", ")", ":", "if", "os", ".", "name", "==", "'nt'", "and", "fallback_to_urandom", ":", "return", "dev_urandom_entropy", "(", "numbytes", ")", "return", "open", "(", "\"/dev/rando...
47.428571
0.001477
def sequence(db, chrom, start, end): """ return the sequence for a region using the UCSC DAS server. note the start is 1-based each feature will have it's own .sequence method which sends the correct start and end to this function. >>> sequence('hg18', 'chr2', 2223, 2230) 'caacttag' """...
[ "def", "sequence", "(", "db", ",", "chrom", ",", "start", ",", "end", ")", ":", "url", "=", "\"http://genome.ucsc.edu/cgi-bin/das/%s\"", "%", "db", "url", "+=", "\"/dna?segment=%s:%i,%i\"", "xml", "=", "U", ".", "urlopen", "(", "url", "%", "(", "chrom", ",...
34.357143
0.002024
def create_init_path(init_path, uid=-1, gid=-1): """create the init path if it does not exist""" if not os.path.exists(init_path): with open(init_path, 'wb'): pass os.chown(init_path, uid, gid);
[ "def", "create_init_path", "(", "init_path", ",", "uid", "=", "-", "1", ",", "gid", "=", "-", "1", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "init_path", ")", ":", "with", "open", "(", "init_path", ",", "'wb'", ")", ":", "pass...
37.5
0.008696
def url_for(self, view_name: str, **kwargs): '''Build a URL based on a view name and the values provided. In order to build a URL, all request parameters must be supplied as keyword arguments, and each parameter must pass the test for the specified parameter type. If these conditions ar...
[ "def", "url_for", "(", "self", ",", "view_name", ":", "str", ",", "*", "*", "kwargs", ")", ":", "# find the route by the supplied view name", "uri", ",", "route", "=", "self", ".", "router", ".", "find_route_by_view_name", "(", "view_name", ")", "if", "not", ...
38.515789
0.001066
def get_var_properties(self): """ Get some properties of the variables in the current namespace """ from spyder_kernels.utils.nsview import get_remote_data settings = self.namespace_view_settings if settings: ns = self._get_current_namespace() ...
[ "def", "get_var_properties", "(", "self", ")", ":", "from", "spyder_kernels", ".", "utils", ".", "nsview", "import", "get_remote_data", "settings", "=", "self", ".", "namespace_view_settings", "if", "settings", ":", "ns", "=", "self", ".", "_get_current_namespace"...
39.354839
0.0016
def run(self, cell, is_full_fc=False, parse_fc=True): """Make supercell force constants readable for phonopy Note ---- Born effective charges and dielectric constant tensor are read from QE output file if they exist. But this means dipole-dipole contributions are removed...
[ "def", "run", "(", "self", ",", "cell", ",", "is_full_fc", "=", "False", ",", "parse_fc", "=", "True", ")", ":", "with", "open", "(", "self", ".", "_filename", ")", "as", "f", ":", "fc_dct", "=", "self", ".", "_parse_q2r", "(", "f", ")", "self", ...
39.03125
0.001563
def cli_create_jar(argument_list): """ A subset of "jar" command. Creating new JARs only. """ usage_message = "usage: jarutil c [OPTIONS] file.jar files..." parser = argparse.ArgumentParser(usage=usage_message) parser.add_argument("jar_file", type=str, help="The file to...
[ "def", "cli_create_jar", "(", "argument_list", ")", ":", "usage_message", "=", "\"usage: jarutil c [OPTIONS] file.jar files...\"", "parser", "=", "argparse", ".", "ArgumentParser", "(", "usage", "=", "usage_message", ")", "parser", ".", "add_argument", "(", "\"jar_file\...
34.125
0.001783
def regex_replace(regex, repl, text): r""" thin wrapper around re.sub regex_replace MULTILINE and DOTALL are on by default in all util_regex functions Args: regex (str): pattern to find repl (str): replace pattern with this text (str): text to modify Returns: s...
[ "def", "regex_replace", "(", "regex", ",", "repl", ",", "text", ")", ":", "return", "re", ".", "sub", "(", "regex", ",", "repl", ",", "text", ",", "*", "*", "RE_KWARGS", ")" ]
30.219512
0.000782