text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def linkage_group_ordering(linkage_records): """Convert degenerate linkage records into ordered info_frags-like records for comparison purposes. Simple example: >>> linkage_records = [ ... ['linkage_group_1', 31842, 94039, 'sctg_207'], ... ['linkage_group_1', 95303, 95303, 'sctg_20...
[ "def", "linkage_group_ordering", "(", "linkage_records", ")", ":", "new_records", "=", "dict", "(", ")", "for", "lg_name", ",", "linkage_group", "in", "itertools", ".", "groupby", "(", "linkage_records", ",", "operator", ".", "itemgetter", "(", "0", ")", ")", ...
34.254545
0.000516
def PC_AC1_calc(P, TOP, POP): """ Calculate percent chance agreement for Gwet's AC1. :param P: condition positive :type P : dict :param TOP: test outcome positive :type TOP : dict :param POP: population :type POP:dict :return: percent chance agreement as float """ try: ...
[ "def", "PC_AC1_calc", "(", "P", ",", "TOP", ",", "POP", ")", ":", "try", ":", "result", "=", "0", "classes", "=", "list", "(", "P", ".", "keys", "(", ")", ")", "for", "i", "in", "classes", ":", "pi", "=", "(", "(", "P", "[", "i", "]", "+", ...
25.818182
0.001698
def maven_url(self): ''' Download-URL from Maven ''' return '{prefix}/{path}/{artifact}/{version}/{filename}'.format( prefix = MAVEN_PREFIX, path = '/'.join(self.group.split('.')), artifact = self.artifact, version = self.version, ...
[ "def", "maven_url", "(", "self", ")", ":", "return", "'{prefix}/{path}/{artifact}/{version}/{filename}'", ".", "format", "(", "prefix", "=", "MAVEN_PREFIX", ",", "path", "=", "'/'", ".", "join", "(", "self", ".", "group", ".", "split", "(", "'.'", ")", ")", ...
34.6
0.042254
def device_time_str(self, resp, indent=" "): """Convenience to string method. """ time = resp.time uptime = resp.uptime downtime = resp.downtime time_s = datetime.datetime.utcfromtimestamp(time/1000000000) if time != None else None uptime_s = round(nanosec_to_hou...
[ "def", "device_time_str", "(", "self", ",", "resp", ",", "indent", "=", "\" \"", ")", ":", "time", "=", "resp", ".", "time", "uptime", "=", "resp", ".", "uptime", "downtime", "=", "resp", ".", "downtime", "time_s", "=", "datetime", ".", "datetime", "....
53.846154
0.01264
def parse(name, content, releases, get_head_fn): """ Parses the given content for a valid changelog :param name: str, package name :param content: str, content :param releases: list, releases :param get_head_fn: function :return: dict, changelog """ try: return {e["version"]:...
[ "def", "parse", "(", "name", ",", "content", ",", "releases", ",", "get_head_fn", ")", ":", "try", ":", "return", "{", "e", "[", "\"version\"", "]", ":", "e", "[", "\"changelog\"", "]", "for", "e", "in", "content", "[", "\"entries\"", "]", "if", "e",...
30.285714
0.002288
def _lincomb(self, a, x1, b, x2, out): """Implement the linear combination of ``x1`` and ``x2``. Compute ``out = a*x1 + b*x2`` using optimized BLAS routines if possible. This function is part of the subclassing API. Do not call it directly. Parameters ---------...
[ "def", "_lincomb", "(", "self", ",", "a", ",", "x1", ",", "b", ",", "x2", ",", "out", ")", ":", "_lincomb_impl", "(", "a", ",", "x1", ",", "b", ",", "x2", ",", "out", ")" ]
30.032258
0.002081
def _to_power_basis_degree8(nodes1, nodes2): r"""Compute the coefficients of an **intersection polynomial**. Helper for :func:`to_power_basis` in the case that B |eacute| zout's `theorem`_ tells us the **intersection polynomial** is degree :math:`8`. This happens if the two curves have degrees one and ...
[ "def", "_to_power_basis_degree8", "(", "nodes1", ",", "nodes2", ")", ":", "evaluated", "=", "[", "eval_intersection_polynomial", "(", "nodes1", ",", "nodes2", ",", "t_val", ")", "for", "t_val", "in", "_CHEB9", "]", "return", "polynomial", ".", "polyfit", "(", ...
36.346154
0.001031
def append(self, linenumber, raw_text, cells): """Add another row of data from a test suite""" self.rows.append(Row(linenumber, raw_text, cells))
[ "def", "append", "(", "self", ",", "linenumber", ",", "raw_text", ",", "cells", ")", ":", "self", ".", "rows", ".", "append", "(", "Row", "(", "linenumber", ",", "raw_text", ",", "cells", ")", ")" ]
53
0.012422
def _load_filters(): """ Locate all entry points by the name 'pmxbot_filters', each of which should refer to a callable(channel, msg) that must return True for the message not to be excluded. """ group = 'pmxbot_filters' eps = entrypoints.get_group_all(group=group) return [ep.load() for ep in eps]
[ "def", "_load_filters", "(", ")", ":", "group", "=", "'pmxbot_filters'", "eps", "=", "entrypoints", ".", "get_group_all", "(", "group", "=", "group", ")", "return", "[", "ep", ".", "load", "(", ")", "for", "ep", "in", "eps", "]" ]
33.111111
0.029412
def convertPrice(variant, regex=None, short_regex=None, none_regex=none_price_regex): ''' Helper function to convert the given input price into integers (cents count). :obj:`int`, :obj:`float` and :obj:`str` are supported :param variant: Price :param re.compile regex: Regex to convert str i...
[ "def", "convertPrice", "(", "variant", ",", "regex", "=", "None", ",", "short_regex", "=", "None", ",", "none_regex", "=", "none_price_regex", ")", ":", "if", "isinstance", "(", "variant", ",", "int", ")", "and", "not", "isinstance", "(", "variant", ",", ...
51.571429
0.00136
def decrypt_binary(self, binary, *args, **kwargs): """ input: bytes, output: bytes """ return self.decrypt(binary, *args, **kwargs)
[ "def", "decrypt_binary", "(", "self", ",", "binary", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "decrypt", "(", "binary", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
31.8
0.01227
def Brkic_2011_2(Re, eD): r'''Calculates Darcy friction factor using the method in Brkic (2011) [2]_ as shown in [1]_. .. math:: f_d = [-2\log(\frac{2.18\beta}{Re}+ \frac{\epsilon}{3.71D})]^{-2} .. math:: \beta = \ln \frac{Re}{1.816\ln\left(\frac{1.1Re}{\ln(1+1.1Re)}\right)} Param...
[ "def", "Brkic_2011_2", "(", "Re", ",", "eD", ")", ":", "beta", "=", "log", "(", "Re", "/", "(", "1.816", "*", "log", "(", "1.1", "*", "Re", "/", "log", "(", "1", "+", "1.1", "*", "Re", ")", ")", ")", ")", "return", "(", "-", "2", "*", "lo...
28.386364
0.000774
def rotate_v1(array, k): """ Rotate the entire array 'k' times T(n)- O(nk) :type array: List[int] :type k: int :rtype: void Do not return anything, modify array in-place instead. """ array = array[:] n = len(array) for i in range(k): # unused variable is not a problem ...
[ "def", "rotate_v1", "(", "array", ",", "k", ")", ":", "array", "=", "array", "[", ":", "]", "n", "=", "len", "(", "array", ")", "for", "i", "in", "range", "(", "k", ")", ":", "# unused variable is not a problem", "temp", "=", "array", "[", "n", "-"...
25.823529
0.002198
def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidObjectForm._init_map(self, record_types=record_types) self._my_map['assignedAgencyIds'] = [str(kwargs['agency_id'])]
[ "def", "_init_map", "(", "self", ",", "record_types", "=", "None", ",", "*", "*", "kwargs", ")", ":", "osid_objects", ".", "OsidObjectForm", ".", "_init_map", "(", "self", ",", "record_types", "=", "record_types", ")", "self", ".", "_my_map", "[", "'assign...
57.5
0.008584
def _AddToSingleColumnTable(self, tableName, columnHeading, newValue): """ Add an entry to a table containing a single column. Checks existing table entries to avoid duplicate entries if the given value already exists in the table. Parameters ---------- tableName : string Name of ...
[ "def", "_AddToSingleColumnTable", "(", "self", ",", "tableName", ",", "columnHeading", ",", "newValue", ")", ":", "match", "=", "None", "currentTable", "=", "self", ".", "_GetFromSingleColumnTable", "(", "tableName", ")", "if", "currentTable", "is", "not", "None...
31.979167
0.008217
def SensorsTriggersNotificationsGet(self, sensor_id, trigger_id): """ Obtain all notifications connected to a sensor-trigger combination. If successful, the result can be obtained from getResponse(), and should be a json string. @param sensor_id (int) - Sens...
[ "def", "SensorsTriggersNotificationsGet", "(", "self", ",", "sensor_id", ",", "trigger_id", ")", ":", "if", "self", ".", "__SenseApiCall__", "(", "'/sensors/{0}/triggers/{1}/notifications.json'", ".", "format", "(", "sensor_id", ",", "trigger_id", ")", ",", "'GET'", ...
53.466667
0.011029
def ensure_arg(args, arg, param=None): """Make sure the arg is present in the list of args. If arg is not present, adds the arg and the optional param. If present and param != None, sets the parameter following the arg to param. :param list args: strings representing an argument list. :param string arg: arg...
[ "def", "ensure_arg", "(", "args", ",", "arg", ",", "param", "=", "None", ")", ":", "for", "idx", ",", "found_arg", "in", "enumerate", "(", "args", ")", ":", "if", "found_arg", "==", "arg", ":", "if", "param", "is", "not", "None", ":", "args", "[", ...
32.714286
0.011315
def dehydrate_datetime(value): """ Dehydrator for `datetime` values. :param value: :type value: datetime :return: """ def seconds_and_nanoseconds(dt): if isinstance(dt, datetime): dt = DateTime.from_native(dt) zone_epoch = DateTime(1970, 1, 1, tzinfo=dt.tzinfo) ...
[ "def", "dehydrate_datetime", "(", "value", ")", ":", "def", "seconds_and_nanoseconds", "(", "dt", ")", ":", "if", "isinstance", "(", "dt", ",", "datetime", ")", ":", "dt", "=", "DateTime", ".", "from_native", "(", "dt", ")", "zone_epoch", "=", "DateTime", ...
34
0.001972
def broadcast(*args, **kwargs): """Explicitly broadcast any number of DataArray or Dataset objects against one another. xarray objects automatically broadcast against each other in arithmetic operations, so this function should not be necessary for normal use. If no change is needed, the input dat...
[ "def", "broadcast", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", ".", "dataarray", "import", "DataArray", "from", ".", "dataset", "import", "Dataset", "exclude", "=", "kwargs", ".", "pop", "(", "'exclude'", ",", "None", ")", "if", "excl...
29.953125
0.000252
def put_object(self, bucket_name, object_name, data, length, content_type='application/octet-stream', metadata=None, sse=None, progress=None, part_size=DEFAULT_PART_SIZE): """ Add a new object to the cloud storage server. NOTE: Maximum ob...
[ "def", "put_object", "(", "self", ",", "bucket_name", ",", "object_name", ",", "data", ",", "length", ",", "content_type", "=", "'application/octet-stream'", ",", "metadata", "=", "None", ",", "sse", "=", "None", ",", "progress", "=", "None", ",", "part_size...
40.493827
0.002083
def get_obj_frm_str(obj_str, **kwargs): """ Returns a python object from a python object string args: obj_str: python object path expamle "rdfframework.connections.ConnManager[{param1}]" kwargs: * kwargs used to format the 'obj_str' """ obj_str = obj_str.for...
[ "def", "get_obj_frm_str", "(", "obj_str", ",", "*", "*", "kwargs", ")", ":", "obj_str", "=", "obj_str", ".", "format", "(", "*", "*", "kwargs", ")", "args", "=", "[", "]", "kwargs", "=", "{", "}", "params", "=", "[", "]", "# parse the call portion of t...
29.708333
0.000679
def consume_token(self, tokens, index, tokens_len): """Consume a token. Returns a tuple of (tokens, tokens_len, index) when consumption is completed and tokens have been merged together. """ finished = False if tokens[index].line > self.line: finished = True...
[ "def", "consume_token", "(", "self", ",", "tokens", ",", "index", ",", "tokens_len", ")", ":", "finished", "=", "False", "if", "tokens", "[", "index", "]", ".", "line", ">", "self", ".", "line", ":", "finished", "=", "True", "end", "=", "index", "eli...
35.16129
0.001786
def setValue(self, newText): """Sets new text into the field""" self.text = newText self.cursorPosition = len(self.text) self._updateImage()
[ "def", "setValue", "(", "self", ",", "newText", ")", ":", "self", ".", "text", "=", "newText", "self", ".", "cursorPosition", "=", "len", "(", "self", ".", "text", ")", "self", ".", "_updateImage", "(", ")" ]
34.4
0.011364
def _full_axis_reduce(self, axis, func, alternate_index=None): """Applies map that reduce Manager to series but require knowledge of full axis. Args: func: Function to reduce the Manager by. This function takes in a Manager. axis: axis to apply the function to. alter...
[ "def", "_full_axis_reduce", "(", "self", ",", "axis", ",", "func", ",", "alternate_index", "=", "None", ")", ":", "result", "=", "self", ".", "data", ".", "map_across_full_axis", "(", "axis", ",", "func", ")", "if", "axis", "==", "0", ":", "columns", "...
50.526316
0.00818
def printUniqueTFAM(tfam, samples, prefix): """Prints a new TFAM with only unique samples. :param tfam: a representation of a TFAM file. :param samples: the position of the samples :param prefix: the prefix of the output file name :type tfam: list :type samples: dict :type prefix: str ...
[ "def", "printUniqueTFAM", "(", "tfam", ",", "samples", ",", "prefix", ")", ":", "fileName", "=", "prefix", "+", "\".unique_samples.tfam\"", "try", ":", "with", "open", "(", "fileName", ",", "\"w\"", ")", "as", "outputFile", ":", "for", "i", "in", "sorted",...
30.3
0.0016
def lock(self, key, timeout=0, sleep=0): """Emulate lock.""" return MockRedisLock(self, key, timeout, sleep)
[ "def", "lock", "(", "self", ",", "key", ",", "timeout", "=", "0", ",", "sleep", "=", "0", ")", ":", "return", "MockRedisLock", "(", "self", ",", "key", ",", "timeout", ",", "sleep", ")" ]
40.666667
0.016129
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2016-10-01: :mod:`v2016_10_01.models<azure.mgmt.keyvault.v2016_10_01.models>` * 2018-02-14: :mod:`v2018_02_14.models<azure.mgmt.keyvault.v2018_02_14.models>` """ if api_version == '20...
[ "def", "models", "(", "cls", ",", "api_version", "=", "DEFAULT_API_VERSION", ")", ":", "if", "api_version", "==", "'2016-10-01'", ":", "from", ".", "v2016_10_01", "import", "models", "return", "models", "elif", "api_version", "==", "'2018-02-14'", ":", "from", ...
45.230769
0.008333
def next_media_partname(self, ext): """Return |PackURI| instance for next available media partname. Partname is first available, starting at sequence number 1. Empty sequence numbers are reused. *ext* is used as the extension on the returned partname. """ def first_avail...
[ "def", "next_media_partname", "(", "self", ",", "ext", ")", ":", "def", "first_available_media_idx", "(", ")", ":", "media_idxs", "=", "sorted", "(", "[", "part", ".", "partname", ".", "idx", "for", "part", "in", "self", ".", "iter_parts", "(", ")", "if"...
39.3
0.002484
def unserialize_data(data, compression=False, encryption=False): """Unserializes the packet data and converts it from json format to normal Python datatypes. If you choose to enable encryption and/or compression when serializing data, you MUST enable the same options when unserializing data. Args:...
[ "def", "unserialize_data", "(", "data", ",", "compression", "=", "False", ",", "encryption", "=", "False", ")", ":", "try", ":", "if", "encryption", ":", "data", "=", "encryption", ".", "decrypt", "(", "data", ")", "except", "Exception", "as", "err", ":"...
30.666667
0.000752
def register_access_db(fullfilename: str, dsn: str, description: str) -> bool: """ (Windows only.) Registers a Microsoft Access database with ODBC. Args: fullfilename: filename of the existing database dsn: ODBC data source name to create description: description of the database...
[ "def", "register_access_db", "(", "fullfilename", ":", "str", ",", "dsn", ":", "str", ",", "description", ":", "str", ")", "->", "bool", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "fullfilename", ")", "return", "create_sys_dsn", "(", ...
25.304348
0.001656
def makevFunc(self,solution): ''' Construct the value function for each current state. Parameters ---------- solution : ConsumerSolution The solution to the single period consumption-saving problem. Must have a consumption function cFunc (using cubic or l...
[ "def", "makevFunc", "(", "self", ",", "solution", ")", ":", "vFuncNow", "=", "[", "]", "# Initialize an empty list of value functions", "# Loop over each current period state and construct the value function", "for", "i", "in", "range", "(", "self", ".", "StateCount", ")"...
48.673077
0.017428
def rolling_max(self, window_start, window_end, min_observations=None): """ Calculate a new SArray of the maximum value of different subsets over this SArray. The subset that the maximum is calculated over is defined as an inclusive range relative to the position to each value i...
[ "def", "rolling_max", "(", "self", ",", "window_start", ",", "window_end", ",", "min_observations", "=", "None", ")", ":", "min_observations", "=", "self", ".", "__check_min_observations", "(", "min_observations", ")", "agg_op", "=", "'__builtin__max__'", "return", ...
29.535354
0.001655
def matrix(self, coordinates, profile='mapbox/driving', sources=None, destinations=None, annotations=None): """Request a directions matrix for trips between coordinates In the default case, the matrix returns a symmetric matrix, using all input coordinates as sources and destina...
[ "def", "matrix", "(", "self", ",", "coordinates", ",", "profile", "=", "'mapbox/driving'", ",", "sources", "=", "None", ",", "destinations", "=", "None", ",", "annotations", "=", "None", ")", ":", "annotations", "=", "self", ".", "_validate_annotations", "("...
42.202703
0.001252
def wait_for_host(port, interval=1, timeout=30, to_start=True, queue=None, ssl_pymongo_options=None): """ Ping server and wait for response. Ping a mongod or mongos every `interval` seconds until it responds, or `timeout` seconds have passed. If `to_start` is set to False, will wait f...
[ "def", "wait_for_host", "(", "port", ",", "interval", "=", "1", ",", "timeout", "=", "30", ",", "to_start", "=", "True", ",", "queue", "=", "None", ",", "ssl_pymongo_options", "=", "None", ")", ":", "host", "=", "'localhost:%i'", "%", "port", "start_time...
34.421053
0.000743
def showMenu(self, point): """ Displays the menu for this filter widget. """ menu = QMenu(self) acts = {} acts['edit'] = menu.addAction('Edit quick filter...') trigger = menu.exec_(self.mapToGlobal(point)) if trigger == acts['ed...
[ "def", "showMenu", "(", "self", ",", "point", ")", ":", "menu", "=", "QMenu", "(", "self", ")", "acts", "=", "{", "}", "acts", "[", "'edit'", "]", "=", "menu", ".", "addAction", "(", "'Edit quick filter...'", ")", "trigger", "=", "menu", ".", "exec_"...
37.894737
0.00813
def parse(self): """ Returns a cleaned lxml ElementTree :returns: Whether the cleaned HTML has matches or not :rtype: bool """ # Create the element tree self.tree = self._build_tree(self.html_contents) # Get explicits elements to keep and discard ...
[ "def", "parse", "(", "self", ")", ":", "# Create the element tree", "self", ".", "tree", "=", "self", ".", "_build_tree", "(", "self", ".", "html_contents", ")", "# Get explicits elements to keep and discard", "self", ".", "elts_to_keep", "=", "self", ".", "_get_e...
31.586207
0.002119
def getCumulativeStats(self, nStatsSizeInBytes): """Fills out stats accumulated for the last connected application. Pass in sizeof( Compositor_CumulativeStats ) as second parameter.""" fn = self.function_table.getCumulativeStats pStats = Compositor_CumulativeStats() fn(byref(pStats), n...
[ "def", "getCumulativeStats", "(", "self", ",", "nStatsSizeInBytes", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getCumulativeStats", "pStats", "=", "Compositor_CumulativeStats", "(", ")", "fn", "(", "byref", "(", "pStats", ")", ",", "nStatsSizeInBy...
50.428571
0.008357
def preloop(self): """Initialization before prompting user for commands. Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub. """ cmd.Cmd.preloop(self) ## sets up command completion try: if readline: readline.read_history_file(sy...
[ "def", "preloop", "(", "self", ")", ":", "cmd", ".", "Cmd", ".", "preloop", "(", "self", ")", "## sets up command completion", "try", ":", "if", "readline", ":", "readline", ".", "read_history_file", "(", "sys", ".", "argv", "[", "0", "]", "+", "\".histo...
39.25
0.008299
def get_ordered_tokens_from_vocab(vocab: Vocab) -> List[str]: """ Returns the list of tokens in a vocabulary, ordered by increasing vocabulary id. :param vocab: Input vocabulary. :return: List of tokens. """ return [token for token, token_id in sorted(vocab.items(), key=lambda i: i[1])]
[ "def", "get_ordered_tokens_from_vocab", "(", "vocab", ":", "Vocab", ")", "->", "List", "[", "str", "]", ":", "return", "[", "token", "for", "token", ",", "token_id", "in", "sorted", "(", "vocab", ".", "items", "(", ")", ",", "key", "=", "lambda", "i", ...
38.125
0.009615
def sample(problem, N, calc_second_order=True, seed=None): """Generates model inputs using Saltelli's extension of the Sobol sequence. Returns a NumPy matrix containing the model inputs using Saltelli's sampling scheme. Saltelli's scheme extends the Sobol sequence in a way to reduce the error rat...
[ "def", "sample", "(", "problem", ",", "N", ",", "calc_second_order", "=", "True", ",", "seed", "=", "None", ")", ":", "if", "seed", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "D", "=", "problem", "[", "'num_vars'", "]", "groups", "=",...
36.022727
0.001228
def movement(self): """ Returns if this object is direct, retrograde or stationary. """ if abs(self.lonspeed) < 0.0003: return const.STATIONARY elif self.lonspeed > 0: return const.DIRECT else: return const.RETROGRADE
[ "def", "movement", "(", "self", ")", ":", "if", "abs", "(", "self", ".", "lonspeed", ")", "<", "0.0003", ":", "return", "const", ".", "STATIONARY", "elif", "self", ".", "lonspeed", ">", "0", ":", "return", "const", ".", "DIRECT", "else", ":", "return...
27.454545
0.016026
def construct(self, method, name, lowcut, highcut, samp_rate, filt_order, prepick, **kwargs): """ Construct a template using a given method. :param method: Method to make the template, see :mod:`eqcorrscan.core.template_gen` for possible methods. ...
[ "def", "construct", "(", "self", ",", "method", ",", "name", ",", "lowcut", ",", "highcut", ",", "samp_rate", ",", "filt_order", ",", "prepick", ",", "*", "*", "kwargs", ")", ":", "if", "method", "in", "[", "'from_meta_file'", ",", "'from_seishub'", ",",...
38.305263
0.000804
def raw_separation(self,mag_1,mag_2,steps=10000): """ Calculate the separation in magnitude-magnitude space between points and isochrone. Uses a dense sampling of the isochrone and calculates the metric distance from any isochrone sample point. Parameters: ----------- mag_1 : T...
[ "def", "raw_separation", "(", "self", ",", "mag_1", ",", "mag_2", ",", "steps", "=", "10000", ")", ":", "# http://stackoverflow.com/q/12653120/", "mag_1", "=", "np", ".", "array", "(", "mag_1", ",", "copy", "=", "False", ",", "ndmin", "=", "1", ")", "mag...
41.15625
0.022997
def construct_from(cls, group_info): """Constructs ``FileGroup`` instance from group information.""" group = cls(group_info['id']) group._info_cache = group_info return group
[ "def", "construct_from", "(", "cls", ",", "group_info", ")", ":", "group", "=", "cls", "(", "group_info", "[", "'id'", "]", ")", "group", ".", "_info_cache", "=", "group_info", "return", "group" ]
40.4
0.009709
def directory(self): """ Fetch the IDASettings instance for the curren plugin with directory scope. rtype: IDASettingsInterface """ if self._config_directory is None: ensure_ida_loaded() return DirectoryIDASettings(self._plugin_name, directory=self._config_di...
[ "def", "directory", "(", "self", ")", ":", "if", "self", ".", "_config_directory", "is", "None", ":", "ensure_ida_loaded", "(", ")", "return", "DirectoryIDASettings", "(", "self", ".", "_plugin_name", ",", "directory", "=", "self", ".", "_config_directory", ")...
35.555556
0.012195
def _format_to_floating_precision(self, precision): """ Format a nonzero finite BigFloat instance to a given number of significant digits. Returns a triple (negative, digits, exp) where: - negative is a boolean, True for a negative number, else False - digits is a string gi...
[ "def", "_format_to_floating_precision", "(", "self", ",", "precision", ")", ":", "if", "precision", "<=", "0", ":", "raise", "ValueError", "(", "\"precision argument should be at least 1\"", ")", "sign", ",", "digits", ",", "exp", "=", "_mpfr_get_str2", "(", "10",...
32.807692
0.002278
def build_rupture_node(rupt, probs_occur): """ :param rupt: a hazardlib rupture object :param probs_occur: a list of floats with sum 1 """ s = sum(probs_occur) if abs(s - 1) > pmf.PRECISION: raise ValueError('The sum of %s is not 1: %s' % (probs_occur, s)) h = rupt.hypocenter hp_...
[ "def", "build_rupture_node", "(", "rupt", ",", "probs_occur", ")", ":", "s", "=", "sum", "(", "probs_occur", ")", "if", "abs", "(", "s", "-", "1", ")", ">", "pmf", ".", "PRECISION", ":", "raise", "ValueError", "(", "'The sum of %s is not 1: %s'", "%", "(...
39.807692
0.000943
def subs_consts(self, expr): """Substitute constants in expression unless it is already a number.""" if isinstance(expr, numbers.Number): return expr else: return expr.subs(self.constants)
[ "def", "subs_consts", "(", "self", ",", "expr", ")", ":", "if", "isinstance", "(", "expr", ",", "numbers", ".", "Number", ")", ":", "return", "expr", "else", ":", "return", "expr", ".", "subs", "(", "self", ".", "constants", ")" ]
38.5
0.008475
def Entry(self, name, directory=None, create=1): """ Create `SCons.Node.FS.Entry` """ return self._create_node(name, self.env.fs.Entry, directory, create)
[ "def", "Entry", "(", "self", ",", "name", ",", "directory", "=", "None", ",", "create", "=", "1", ")", ":", "return", "self", ".", "_create_node", "(", "name", ",", "self", ".", "env", ".", "fs", ".", "Entry", ",", "directory", ",", "create", ")" ]
56
0.011765
def init_frag_list(fragment_list, new_frag_list): """Adapt the original fragment list to fit the build function requirements Parameters ---------- fragment_list : str, file or pathlib.Path The input fragment list. new_frag_list : str, file or pathlib.Path The output fragment list to...
[ "def", "init_frag_list", "(", "fragment_list", ",", "new_frag_list", ")", ":", "handle_frag_list", "=", "open", "(", "fragment_list", ",", "\"r\"", ")", "handle_new_frag_list", "=", "open", "(", "new_frag_list", ",", "\"w\"", ")", "handle_new_frag_list", ".", "wri...
25.41791
0.001131
def parse(self, text): """Attempt to parse source code.""" self.original_text = text try: return getattr(self, self.entry_point)(text) except (DeadEnd) as exc: raise ParserError(self.most_consumed, "Failed to parse input") from exc return tree
[ "def", "parse", "(", "self", ",", "text", ")", ":", "self", ".", "original_text", "=", "text", "try", ":", "return", "getattr", "(", "self", ",", "self", ".", "entry_point", ")", "(", "text", ")", "except", "(", "DeadEnd", ")", "as", "exc", ":", "r...
29.777778
0.01087
async def is_leader_from_status(self): """ Check to see if this unit is the leader. Returns True if so, and False if it is not, or if leadership does not make sense (e.g., there is no leader in this application.) This method is a kluge that calls FullStatus in the Client...
[ "async", "def", "is_leader_from_status", "(", "self", ")", ":", "app", "=", "self", ".", "name", ".", "split", "(", "\"/\"", ")", "[", "0", "]", "c", "=", "client", ".", "ClientFacade", ".", "from_connection", "(", "self", ".", "connection", ")", "stat...
38.972222
0.001391
def fetch_blob(cls, username, password, multifactor_password=None, client_id=None): """Just fetches the blob, could be used to store it locally""" session = fetcher.login(username, password, multifactor_password, client_id) blob = fetcher.fetch(session) fetcher.logout(session) r...
[ "def", "fetch_blob", "(", "cls", ",", "username", ",", "password", ",", "multifactor_password", "=", "None", ",", "client_id", "=", "None", ")", ":", "session", "=", "fetcher", ".", "login", "(", "username", ",", "password", ",", "multifactor_password", ",",...
46.285714
0.012121
def per_chat_id_in(s, types='all'): """ :param s: a list or set of chat id :param types: ``all`` or a list of chat types (``private``, ``group``, ``channel``) :return: a seeder function that returns the chat id only if the chat id is in ``s`` and chat type is in ``types...
[ "def", "per_chat_id_in", "(", "s", ",", "types", "=", "'all'", ")", ":", "return", "_wrap_none", "(", "lambda", "msg", ":", "msg", "[", "'chat'", "]", "[", "'id'", "]", "if", "(", "types", "==", "'all'", "or", "msg", "[", "'chat'", "]", "[", "'type...
33.5
0.010889
def p_gate_id_list_1(self, program): """ gate_id_list : gate_id_list ',' id """ program[0] = program[1] program[0].add_child(program[3]) self.update_symtab(program[3])
[ "def", "p_gate_id_list_1", "(", "self", ",", "program", ")", ":", "program", "[", "0", "]", "=", "program", "[", "1", "]", "program", "[", "0", "]", ".", "add_child", "(", "program", "[", "3", "]", ")", "self", ".", "update_symtab", "(", "program", ...
30.285714
0.009174
def delete_vhost(self, name): """ Delete a vhost. :param name: The vhost name :type name: str """ self._api_delete('/api/vhosts/{0}'.format( urllib.parse.quote_plus(name) ))
[ "def", "delete_vhost", "(", "self", ",", "name", ")", ":", "self", ".", "_api_delete", "(", "'/api/vhosts/{0}'", ".", "format", "(", "urllib", ".", "parse", ".", "quote_plus", "(", "name", ")", ")", ")" ]
23.3
0.008264
def vehicleTypes2flt(outSTRM, vtIDm): """ Currently, rather a stub than an implementation. Writes the vehicle ids stored in the given "vtIDm" map formatted as a .flt file readable by PHEM. The following may be a matter of changes: - A default map is assigned to all vehicle types with the same proba...
[ "def", "vehicleTypes2flt", "(", "outSTRM", ",", "vtIDm", ")", ":", "for", "q", "in", "sorted", "(", "vtIDm", ".", "_m", ")", ":", "print", "(", "\"%s,%s,%s\"", "%", "(", "vtIDm", ".", "g", "(", "q", ")", ",", "\"<VEHDIR>\\PC\\PC_%s.GEN\"", "%", "q", ...
41.545455
0.008565
def _mirror_groups(self): """ Mirrors the user's LDAP groups in the Django database and updates the user's membership. """ target_group_names = frozenset(self._get_groups().get_group_names()) current_group_names = frozenset( self._user.groups.values_list("name...
[ "def", "_mirror_groups", "(", "self", ")", ":", "target_group_names", "=", "frozenset", "(", "self", ".", "_get_groups", "(", ")", ".", "get_group_names", "(", ")", ")", "current_group_names", "=", "frozenset", "(", "self", ".", "_user", ".", "groups", ".", ...
41.410256
0.00242
def delete_relation(self, src, relation, target): ''' can be both used as (src, relation, dest) for a single relation or (src, relation) to delete all relations of that type from the src ''' self.__require_string__(relation) if src in self and target in self: self._get_it...
[ "def", "delete_relation", "(", "self", ",", "src", ",", "relation", ",", "target", ")", ":", "self", ".", "__require_string__", "(", "relation", ")", "if", "src", "in", "self", "and", "target", "in", "self", ":", "self", ".", "_get_item_node", "(", "src"...
62.166667
0.010582
async def wait_async(self): """ Wait until all transferred events have been sent. """ if self.error: raise self.error if not self.running: raise ValueError("Unable to send until client has been started.") try: await self._handler.wait_a...
[ "async", "def", "wait_async", "(", "self", ")", ":", "if", "self", ".", "error", ":", "raise", "self", ".", "error", "if", "not", "self", ".", "running", ":", "raise", "ValueError", "(", "\"Unable to send until client has been started.\"", ")", "try", ":", "...
46.029412
0.001877
def _get_module(module_name=None, module=None, register=True): """ finds module in sys.modules based on module name unless the module has already been found and is passed in """ if module is None and module_name is not None: try: module = sys.modules[module_name] except KeyError ...
[ "def", "_get_module", "(", "module_name", "=", "None", ",", "module", "=", "None", ",", "register", "=", "True", ")", ":", "if", "module", "is", "None", "and", "module_name", "is", "not", "None", ":", "try", ":", "module", "=", "sys", ".", "modules", ...
41.470588
0.001387
def tileSize(self, zoom): "Returns the size (in meters) of a tile" assert zoom in range(0, len(self.RESOLUTIONS)) return self.tileSizePx * self.RESOLUTIONS[int(zoom)]
[ "def", "tileSize", "(", "self", ",", "zoom", ")", ":", "assert", "zoom", "in", "range", "(", "0", ",", "len", "(", "self", ".", "RESOLUTIONS", ")", ")", "return", "self", ".", "tileSizePx", "*", "self", ".", "RESOLUTIONS", "[", "int", "(", "zoom", ...
46.75
0.010526
def compile_link_import_py_ext( srcs, extname=None, build_dir=None, compile_kwargs=None, link_kwargs=None, **kwargs): """ Compiles sources in `srcs` to a shared object (python extension) which is imported. If shared object is newer than the sources, they are not recompiled but instead it...
[ "def", "compile_link_import_py_ext", "(", "srcs", ",", "extname", "=", "None", ",", "build_dir", "=", "None", ",", "compile_kwargs", "=", "None", ",", "link_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "build_dir", "=", "build_dir", "or", "'.'"...
32.561404
0.000523
def reload(self): """Reload source from disk and initialize state.""" # read data and parse into blocks self.fload() lines = self.fobj.readlines() src_b = [l for l in lines if l.strip()] nblocks = len(src_b) self.src = ''.join(li...
[ "def", "reload", "(", "self", ")", ":", "# read data and parse into blocks", "self", ".", "fload", "(", ")", "lines", "=", "self", ".", "fobj", ".", "readlines", "(", ")", "src_b", "=", "[", "l", "for", "l", "in", "lines", "if", "l", ".", "strip", "(...
35.631579
0.017266
def disable(states): ''' Disable state runs. CLI Example: .. code-block:: bash salt '*' state.disable highstate salt '*' state.disable highstate,test.succeed_without_changes .. note:: To disable a state file from running provide the same name that would be passed...
[ "def", "disable", "(", "states", ")", ":", "ret", "=", "{", "'res'", ":", "True", ",", "'msg'", ":", "''", "}", "states", "=", "salt", ".", "utils", ".", "args", ".", "split_input", "(", "states", ")", "msg", "=", "[", "]", "_disabled", "=", "__s...
22.387755
0.000873
def prepare_duplicate_order_object(manager, origin_volume, iops, tier, duplicate_size, duplicate_snapshot_size, volume_type, hourly_billing_flag=False): """Prepare the duplicate order to submit to SoftLayer_Product::placeOrder() :param manag...
[ "def", "prepare_duplicate_order_object", "(", "manager", ",", "origin_volume", ",", "iops", ",", "tier", ",", "duplicate_size", ",", "duplicate_snapshot_size", ",", "volume_type", ",", "hourly_billing_flag", "=", "False", ")", ":", "# Verify that the origin volume has not...
45
0.000369
def publish(self, message_type=ON_SEND, client_id=None, client_storage=None, *args, **kwargs): """ Publishes a message """ self.publisher.publish( message_type, client_id, client_storage, *args, **kwargs)
[ "def", "publish", "(", "self", ",", "message_type", "=", "ON_SEND", ",", "client_id", "=", "None", ",", "client_storage", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "publisher", ".", "publish", "(", "message_type", "...
36.857143
0.011364
def get_data(n_clients): """ Import the dataset via sklearn, shuffle and split train/test. Return training, target lists for `n_clients` and a holdout test set """ print("Loading data") diabetes = load_diabetes() y = diabetes.target X = diabetes.data # Add constant to emulate interce...
[ "def", "get_data", "(", "n_clients", ")", ":", "print", "(", "\"Loading data\"", ")", "diabetes", "=", "load_diabetes", "(", ")", "y", "=", "diabetes", ".", "target", "X", "=", "diabetes", ".", "data", "# Add constant to emulate intercept", "X", "=", "np", "...
33.685714
0.000824
def find_token(request, token_type, service, **kwargs): """ The access token can be in a number of places. There are priority rules as to which one to use, abide by those: 1 If it's among the request parameters use that 2 If among the extra keyword arguments 3 Acquired by a previous run service...
[ "def", "find_token", "(", "request", ",", "token_type", ",", "service", ",", "*", "*", "kwargs", ")", ":", "if", "request", "is", "not", "None", ":", "try", ":", "_token", "=", "request", "[", "token_type", "]", "except", "KeyError", ":", "pass", "else...
31.8
0.000872
def restoreSettings( self, settings ): """ Restores the settings from the inputed settings instance. :param settings | <QSettings> :return <bool> success """ dataSet = self.dataSet() if ( not dataSet ): return False ...
[ "def", "restoreSettings", "(", "self", ",", "settings", ")", ":", "dataSet", "=", "self", ".", "dataSet", "(", ")", "if", "(", "not", "dataSet", ")", ":", "return", "False", "projexui", ".", "restoreDataSet", "(", "settings", ",", "self", ".", "uniqueNam...
27.9
0.025997
def get_encoder(ndarray_mode='b64'): """ Returns a JSON encoder that can handle: * :obj:`numpy.ndarray` * :obj:`numpy.floating` (converted to :obj:`float`) * :obj:`numpy.integer` (converted to :obj:`int`) * :obj:`numpy.dtype` * :obj:`astropy.units.Quantity` * :obj...
[ "def", "get_encoder", "(", "ndarray_mode", "=", "'b64'", ")", ":", "# Use specified numpy.ndarray serialization mode", "serialize_fns", "=", "{", "'b64'", ":", "serialize_ndarray_b64", ",", "'readable'", ":", "serialize_ndarray_readable", ",", "'npy'", ":", "serialize_nda...
38.315068
0.002091
def is_reseller_admin(self, req, admin_detail=None): """Returns True if the admin specified in the request represents a .reseller_admin. :param req: The swob.Request to check. :param admin_detail: The previously retrieved dict from :func:`get_admin_detail` o...
[ "def", "is_reseller_admin", "(", "self", ",", "req", ",", "admin_detail", "=", "None", ")", ":", "req", ".", "credentials_valid", "=", "False", "if", "self", ".", "is_super_admin", "(", "req", ")", ":", "return", "True", "if", "not", "admin_detail", ":", ...
45.2
0.002167
def strip(value): """ REMOVE WHITESPACE (INCLUDING CONTROL CHARACTERS) """ if not value or (ord(value[0]) > 32 and ord(value[-1]) > 32): return value s = 0 e = len(value) while s < e: if ord(value[s]) > 32: break s += 1 else: return "" fo...
[ "def", "strip", "(", "value", ")", ":", "if", "not", "value", "or", "(", "ord", "(", "value", "[", "0", "]", ")", ">", "32", "and", "ord", "(", "value", "[", "-", "1", "]", ")", ">", "32", ")", ":", "return", "value", "s", "=", "0", "e", ...
19.47619
0.002331
def flush(self): """Flush data that is left in the buffer.""" for data in self.buffer: self.output_width += data.output(self.output, self.output_width) self.buffer.clear() self.buffer_width = 0
[ "def", "flush", "(", "self", ")", ":", "for", "data", "in", "self", ".", "buffer", ":", "self", ".", "output_width", "+=", "data", ".", "output", "(", "self", ".", "output", ",", "self", ".", "output_width", ")", "self", ".", "buffer", ".", "clear", ...
38.666667
0.008439
def input_yes_no(msg=''): """ Simple helper function """ print '\n'+msg while(True): i=raw_input('Input yes or no: ') i=i.lower() if i=='y' or i=='yes': return True elif i=='n' or i=='no': return False else: print 'ERROR: Ba...
[ "def", "input_yes_no", "(", "msg", "=", "''", ")", ":", "print", "'\\n'", "+", "msg", "while", "(", "True", ")", ":", "i", "=", "raw_input", "(", "'Input yes or no: '", ")", "i", "=", "i", ".", "lower", "(", ")", "if", "i", "==", "'y'", "or", "i"...
24.142857
0.019943
def GetPresetsForOperatingSystem( cls, operating_system, operating_system_product, operating_system_version): """Determines the presets for a specific operating system. Args: operating_system (str): operating system for example "Windows". This should be one of the values in definiti...
[ "def", "GetPresetsForOperatingSystem", "(", "cls", ",", "operating_system", ",", "operating_system_product", ",", "operating_system_version", ")", ":", "operating_system", "=", "artifacts", ".", "OperatingSystemArtifact", "(", "family", "=", "operating_system", ",", "prod...
44.409091
0.001002
def __recieve_chunk(self): """ recieve a chunk """ if self.__response == const.CMD_DATA: if self.tcp: if self.verbose: print ("_rc_DATA! is {} bytes, tcp length is {}".format(len(self.__data), self.__tcp_length)) if len(self.__data) < (self.__tcp_length - 8): ...
[ "def", "__recieve_chunk", "(", "self", ")", ":", "if", "self", ".", "__response", "==", "const", ".", "CMD_DATA", ":", "if", "self", ".", "tcp", ":", "if", "self", ".", "verbose", ":", "print", "(", "\"_rc_DATA! is {} bytes, tcp length is {}\"", ".", "format...
48.338462
0.012165
def forward(self, address, types=None, lon=None, lat=None, country=None, bbox=None, limit=None, languages=None): """Returns a Requests response object that contains a GeoJSON collection of places matching the given address. `response.geojson()` returns the geocoding result as Ge...
[ "def", "forward", "(", "self", ",", "address", ",", "types", "=", "None", ",", "lon", "=", "None", ",", "lat", "=", "None", ",", "country", "=", "None", ",", "bbox", "=", "None", ",", "limit", "=", "None", ",", "languages", "=", "None", ")", ":",...
42.789474
0.001804
def radians_to(self, other): """ Returns the distance from this GeoPoint to another in radians. :param other: point the other GeoPoint :type other: GeoPoint :rtype: float """ d2r = math.pi / 180.0 lat1rad = self.latitude * d2r long1rad = self.long...
[ "def", "radians_to", "(", "self", ",", "other", ")", ":", "d2r", "=", "math", ".", "pi", "/", "180.0", "lat1rad", "=", "self", ".", "latitude", "*", "d2r", "long1rad", "=", "self", ".", "longitude", "*", "d2r", "lat2rad", "=", "other", ".", "latitude...
31.423077
0.002375
def lossless_float_to_int(funcname, func, argname, arg): """ A preprocessor that coerces integral floats to ints. Receipt of non-integral floats raises a TypeError. """ if not isinstance(arg, float): return arg arg_as_int = int(arg) if arg == arg_as_int: warnings.warn( ...
[ "def", "lossless_float_to_int", "(", "funcname", ",", "func", ",", "argname", ",", "arg", ")", ":", "if", "not", "isinstance", "(", "arg", ",", "float", ")", ":", "return", "arg", "arg_as_int", "=", "int", "(", "arg", ")", "if", "arg", "==", "arg_as_in...
26
0.001686
def load_fixtures(self, nodes=None, progress_callback=None, dry_run=False): """Load all fixtures for given nodes. If no nodes are given all fixtures will be loaded. :param list nodes: list of nodes to be loaded. :param callable progress_callback: Callback which will be called while ...
[ "def", "load_fixtures", "(", "self", ",", "nodes", "=", "None", ",", "progress_callback", "=", "None", ",", "dry_run", "=", "False", ")", ":", "if", "progress_callback", "and", "not", "callable", "(", "progress_callback", ")", ":", "raise", "Exception", "(",...
35.791667
0.002268
def save(self): """ Creates a new user and account. Returns the newly created user. """ username, email, password, first_name, last_name = (self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1'],...
[ "def", "save", "(", "self", ")", ":", "username", ",", "email", ",", "password", ",", "first_name", ",", "last_name", "=", "(", "self", ".", "cleaned_data", "[", "'username'", "]", ",", "self", ".", "cleaned_data", "[", "'email'", "]", ",", "self", "."...
49.733333
0.009211
def quick_sort(array, left, right): """快速排序""" if left >= right: return low = left high = right key = array[low] while left < right: # 将大于key的值放到右边 while left < right and array[right] > key: right -= 1 array[left] = array[right] # 将小于key的值放...
[ "def", "quick_sort", "(", "array", ",", "left", ",", "right", ")", ":", "if", "left", ">=", "right", ":", "return", "low", "=", "left", "high", "=", "right", "key", "=", "array", "[", "low", "]", "while", "left", "<", "right", ":", "# 将大于key的值放到右边", ...
20.074074
0.001761
def to_bluesky( traffic: Traffic, filename: Union[str, Path], minimum_time: Optional[timelike] = None, ) -> None: """Generates a Bluesky scenario file.""" if minimum_time is not None: minimum_time = to_datetime(minimum_time) traffic = traffic.query(f"timestamp >= '{minimum_time}'") ...
[ "def", "to_bluesky", "(", "traffic", ":", "Traffic", ",", "filename", ":", "Union", "[", "str", ",", "Path", "]", ",", "minimum_time", ":", "Optional", "[", "timelike", "]", "=", "None", ",", ")", "->", "None", ":", "if", "minimum_time", "is", "not", ...
33.725275
0.000317
def run(self) -> None: """Thread run method implementation.""" while True: request = self.input_queue.get() response = self._handle_request(request) self.output_queue.put(response)
[ "def", "run", "(", "self", ")", "->", "None", ":", "while", "True", ":", "request", "=", "self", ".", "input_queue", ".", "get", "(", ")", "response", "=", "self", ".", "_handle_request", "(", "request", ")", "self", ".", "output_queue", ".", "put", ...
37.833333
0.008621
def _parseBlockDevice(self, block_device): """ Parse a higher-level view of the block device mapping into something novaclient wants. This should be similar to how Horizon presents it. Required keys: device_name: The name of the device; e.g. vda or xda. source_typ...
[ "def", "_parseBlockDevice", "(", "self", ",", "block_device", ")", ":", "client_block_device", "=", "{", "}", "client_block_device", "[", "'device_name'", "]", "=", "block_device", ".", "get", "(", "'device_name'", ",", "'vda'", ")", "client_block_device", "[", ...
50.357143
0.001392
def importfile(filename): """ Imports a module specifically from a file. :param filename | <str> :return <module> || None """ pkg = packageFromPath(filename, includeModule=True) root = packageRootPath(filename) if root not in sys.path: sys.path.insert(0, root)...
[ "def", "importfile", "(", "filename", ")", ":", "pkg", "=", "packageFromPath", "(", "filename", ",", "includeModule", "=", "True", ")", "root", "=", "packageRootPath", "(", "filename", ")", "if", "root", "not", "in", "sys", ".", "path", ":", "sys", ".", ...
22.125
0.00813
def xml(self, indent = ""): """Serialise provenance data to XML. This is included in CLAM Metadata files""" xml = indent + "<provenance type=\"clam\" id=\""+self.serviceid+"\" name=\"" +self.servicename+"\" url=\"" + self.serviceurl+"\" outputtemplate=\""+self.outputtemplate_id+"\" outputtemplatelabel=\...
[ "def", "xml", "(", "self", ",", "indent", "=", "\"\"", ")", ":", "xml", "=", "indent", "+", "\"<provenance type=\\\"clam\\\" id=\\\"\"", "+", "self", ".", "serviceid", "+", "\"\\\" name=\\\"\"", "+", "self", ".", "servicename", "+", "\"\\\" url=\\\"\"", "+", "...
61.277778
0.008929
def install(name=None, refresh=False, sysupgrade=None, pkgs=None, sources=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which mod...
[ "def", "install", "(", "name", "=", "None", ",", "refresh", "=", "False", ",", "sysupgrade", "=", "None", ",", "pkgs", "=", "None", ",", "sources", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "pkg_params", ",", "pkg_type", "=", "__s...
35.609375
0.001281
def xpath(self, query): """Run Xpath expression and parse the resulting elements. Don't forget to use the FoLiA namesapace in your expressions, using folia: or the short form f: """ for result in self.tree.xpath(query,namespaces={'f': 'http://ilk.uvt.nl/folia','folia': 'http://ilk.uvt.nl/folia' }): ...
[ "def", "xpath", "(", "self", ",", "query", ")", ":", "for", "result", "in", "self", ".", "tree", ".", "xpath", "(", "query", ",", "namespaces", "=", "{", "'f'", ":", "'http://ilk.uvt.nl/folia'", ",", "'folia'", ":", "'http://ilk.uvt.nl/folia'", "}", ")", ...
88
0.019718
def classnameify(s): """ Makes a classname """ return ''.join(w if w in ACRONYMS else w.title() for w in s.split('_'))
[ "def", "classnameify", "(", "s", ")", ":", "return", "''", ".", "join", "(", "w", "if", "w", "in", "ACRONYMS", "else", "w", ".", "title", "(", ")", "for", "w", "in", "s", ".", "split", "(", "'_'", ")", ")" ]
24.4
0.02381
def close_room(self, room, namespace=None): """Close a room.""" return self.socketio.close_room(room=room, namespace=namespace or self.namespace)
[ "def", "close_room", "(", "self", ",", "room", ",", "namespace", "=", "None", ")", ":", "return", "self", ".", "socketio", ".", "close_room", "(", "room", "=", "room", ",", "namespace", "=", "namespace", "or", "self", ".", "namespace", ")" ]
49.5
0.00995
def clustermap( adata, obs_keys=None, use_raw=None, show=None, save=None, **kwds): """\ Hierarchically-clustered heatmap. Wraps `seaborn.clustermap <https://seaborn.pydata.org/generated/seaborn.clustermap.html>`__ for :class:`~anndata.AnnData`. Parameters ---------- adata : :cl...
[ "def", "clustermap", "(", "adata", ",", "obs_keys", "=", "None", ",", "use_raw", "=", "None", ",", "show", "=", "None", ",", "save", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "not", "isinstance", "(", "obs_keys", ",", "(", "str", ",", "...
34.720588
0.001647
def _dump_crawl_stats(self): ''' Dumps flattened crawling stats so the spiders do not have to ''' extras = {} spiders = {} spider_set = set() total_spider_count = 0 keys = self.redis_conn.keys('stats:crawler:*:*:*') for key in keys: #...
[ "def", "_dump_crawl_stats", "(", "self", ")", ":", "extras", "=", "{", "}", "spiders", "=", "{", "}", "spider_set", "=", "set", "(", ")", "total_spider_count", "=", "0", "keys", "=", "self", ".", "redis_conn", ".", "keys", "(", "'stats:crawler:*:*:*'", "...
31.037037
0.001735
def lambda_failure_response(*args): """ Helper function to create a Lambda Failure Response :return: A Flask Response """ response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE) return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502)
[ "def", "lambda_failure_response", "(", "*", "args", ")", ":", "response_data", "=", "jsonify", "(", "ServiceErrorResponses", ".", "_LAMBDA_FAILURE", ")", "return", "make_response", "(", "response_data", ",", "ServiceErrorResponses", ".", "HTTP_STATUS_CODE_502", ")" ]
38.25
0.009585
def create_context_menu(self, extended): """Create the context menu.""" menu = Gtk.Menu() self._menu(menu, extended) return menu
[ "def", "create_context_menu", "(", "self", ",", "extended", ")", ":", "menu", "=", "Gtk", ".", "Menu", "(", ")", "self", ".", "_menu", "(", "menu", ",", "extended", ")", "return", "menu" ]
31.2
0.0125
def create(vm_): ''' Create a single VM from a data dict ''' try: # Check for required profile parameters before sending any API calls. if vm_['profile'] and config.is_profile_configured( __opts__, __active_provider_name__ or 'dimensiondata', ...
[ "def", "create", "(", "vm_", ")", ":", "try", ":", "# Check for required profile parameters before sending any API calls.", "if", "vm_", "[", "'profile'", "]", "and", "config", ".", "is_profile_configured", "(", "__opts__", ",", "__active_provider_name__", "or", "'dimen...
32.824675
0.000768
def beta_confidence_intervals(ci_X, ntrials, ci=0.95): """ Compute confidence intervals of beta distributions. Parameters ---------- ci_X : numpy.array Computed confidence interval estimate from `ntrials` experiments ntrials : int The number of trials that were run. ci : flo...
[ "def", "beta_confidence_intervals", "(", "ci_X", ",", "ntrials", ",", "ci", "=", "0.95", ")", ":", "# Compute low and high confidence interval for symmetric CI about mean.", "ci_low", "=", "0.5", "-", "ci", "/", "2", "ci_high", "=", "0.5", "+", "ci", "/", "2", "...
30.261905
0.01753
def get_selection_owner(self, selection): """Return the window that owns selection (an atom), or X.NONE if there is no owner for the selection. Can raise BadAtom.""" r = request.GetSelectionOwner(display = self.display, selection = selection) return ...
[ "def", "get_selection_owner", "(", "self", ",", "selection", ")", ":", "r", "=", "request", ".", "GetSelectionOwner", "(", "display", "=", "self", ".", "display", ",", "selection", "=", "selection", ")", "return", "r", ".", "owner" ]
53.666667
0.018349
def flatten(master): """ :param dict master: a multilevel dictionary :return: a flattened dictionary :rtype: dict Flattens a multilevel dictionary into a single-level one so that:: {'foo': {'bar': { 'a': 1, 'b': True, ...
[ "def", "flatten", "(", "master", ")", ":", "result", "=", "{", "}", "def", "add", "(", "value", ",", "*", "keys", ")", ":", "if", "keys", "in", "result", ":", "raise", "ValueError", "(", "'Duplicate key %s'", "%", "keys", ")", "result", "[", "keys", ...
24.208333
0.000827