text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def zext(self, num): """Zero-extend this farray by *num* bits. Returns a new farray. """ zero = self.ftype.box(0) return self.__class__(self._items + [zero] * num, ftype=self.ftype)
[ "def", "zext", "(", "self", ",", "num", ")", ":", "zero", "=", "self", ".", "ftype", ".", "box", "(", "0", ")", "return", "self", ".", "__class__", "(", "self", ".", "_items", "+", "[", "zero", "]", "*", "num", ",", "ftype", "=", "self", ".", ...
30.857143
16.285714
def get_sub_accounts(self, account_id, params={}): """ Return list of subaccounts within the account with the passed canvas id. https://canvas.instructure.com/doc/api/accounts.html#method.accounts.sub_accounts """ url = ACCOUNTS_API.format(account_id) + "/sub_accounts" ...
[ "def", "get_sub_accounts", "(", "self", ",", "account_id", ",", "params", "=", "{", "}", ")", ":", "url", "=", "ACCOUNTS_API", ".", "format", "(", "account_id", ")", "+", "\"/sub_accounts\"", "accounts", "=", "[", "]", "for", "datum", "in", "self", ".", ...
33.928571
23.5
def stream_copy(source, destination, chunk_size=512 * 1024): """Copy all data from the source stream into the destination stream in chunks of size chunk_size :return: amount of bytes written""" br = 0 while True: chunk = source.read(chunk_size) destination.write(chunk) br +=...
[ "def", "stream_copy", "(", "source", ",", "destination", ",", "chunk_size", "=", "512", "*", "1024", ")", ":", "br", "=", "0", "while", "True", ":", "chunk", "=", "source", ".", "read", "(", "chunk_size", ")", "destination", ".", "write", "(", "chunk",...
29.857143
15.857143
def publictypes(self): """ get all public types """ for t in self.wsdl.schema.types.values(): if t in self.params: continue if t in self.types: continue item = (t, t) self.types.append(item) self.types.sort(key=lambd...
[ "def", "publictypes", "(", "self", ")", ":", "for", "t", "in", "self", ".", "wsdl", ".", "schema", ".", "types", ".", "values", "(", ")", ":", "if", "t", "in", "self", ".", "params", ":", "continue", "if", "t", "in", "self", ".", "types", ":", ...
32.6
10.4
def portfolio_value(portfolio, date, price='close'): """Total value of a portfolio (dict mapping symbols to numbers of shares) $CASH used as symbol for USD """ value = 0.0 for (sym, sym_shares) in portfolio.iteritems(): sym_price = None if sym_shares: sym_price = get_pri...
[ "def", "portfolio_value", "(", "portfolio", ",", "date", ",", "price", "=", "'close'", ")", ":", "value", "=", "0.0", "for", "(", "sym", ",", "sym_shares", ")", "in", "portfolio", ".", "iteritems", "(", ")", ":", "sym_price", "=", "None", "if", "sym_sh...
46.590909
23.318182
def partitionBy(*cols): """ Creates a :class:`WindowSpec` with the partitioning defined. """ sc = SparkContext._active_spark_context jspec = sc._jvm.org.apache.spark.sql.expressions.Window.partitionBy(_to_java_cols(cols)) return WindowSpec(jspec)
[ "def", "partitionBy", "(", "*", "cols", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "jspec", "=", "sc", ".", "_jvm", ".", "org", ".", "apache", ".", "spark", ".", "sql", ".", "expressions", ".", "Window", ".", "partitionBy", "(", ...
41.142857
16.571429
def AsDict(self, dt=True): """ A dict representation of this Shake instance. The return value uses the same key names as the JSON representation. Return: A dict representing this Shake instance """ data = {} if self.id: data['id'] = self...
[ "def", "AsDict", "(", "self", ",", "dt", "=", "True", ")", ":", "data", "=", "{", "}", "if", "self", ".", "id", ":", "data", "[", "'id'", "]", "=", "self", ".", "id", "if", "self", ".", "name", ":", "data", "[", "'name'", "]", "=", "self", ...
28.842105
17.368421
def show2(self): """ Rebuild the TLS packet with the same context, and then .show() it. We need self.__class__ to call the subclass in a dynamic way. Howether we do not want the tls_session.{r,w}cs.seq_num to be updated. We have to bring back the init states (it's possible the c...
[ "def", "show2", "(", "self", ")", ":", "s", "=", "self", ".", "tls_session", "rcs_snap", "=", "s", ".", "rcs", ".", "snapshot", "(", ")", "wcs_snap", "=", "s", ".", "wcs", ".", "snapshot", "(", ")", "s", ".", "rcs", "=", "self", ".", "rcs_snap_in...
35.304348
22.608696
def distance(p0, p1, deg=True, r=r_earth_mean): """ Return the distance between two points on the surface of the Earth. Parameters ---------- p0 : point-like (or array of point-like) [longitude, latitude] objects p1 : point-like (or array of point-like) [longitude, latitude] objects deg : b...
[ "def", "distance", "(", "p0", ",", "p1", ",", "deg", "=", "True", ",", "r", "=", "r_earth_mean", ")", ":", "single", ",", "(", "p0", ",", "p1", ")", "=", "_to_arrays", "(", "(", "p0", ",", "2", ")", ",", "(", "p1", ",", "2", ")", ")", "if",...
26.534884
22.209302
def transit_delete_key(self, name, mount_point='transit'): """DELETE /<mount_point>/keys/<name> :param name: :type name: :param mount_point: :type mount_point: :return: :rtype: """ url = '/v1/{0}/keys/{1}'.format(mount_point, name) return ...
[ "def", "transit_delete_key", "(", "self", ",", "name", ",", "mount_point", "=", "'transit'", ")", ":", "url", "=", "'/v1/{0}/keys/{1}'", ".", "format", "(", "mount_point", ",", "name", ")", "return", "self", ".", "_adapter", ".", "delete", "(", "url", ")" ...
27.833333
16.083333
def multivariate_normal(random, mean, cov): """ Draw random samples from a multivariate normal distribution. Parameters ---------- random : np.random.RandomState instance Random state. mean : array_like Mean of the n-dimensional distribution. cov : array_like Covaria...
[ "def", "multivariate_normal", "(", "random", ",", "mean", ",", "cov", ")", ":", "from", "numpy", ".", "linalg", "import", "cholesky", "L", "=", "cholesky", "(", "cov", ")", "return", "L", "@", "random", ".", "randn", "(", "L", ".", "shape", "[", "0",...
25.478261
18.608696
def get_user_profile(self, user_id): """ Get user profile. Returns user profile data, including user id, name, and profile pic. When requesting the profile for the user accessing the API, the user's calendar feed URL will be returned as well. """ ...
[ "def", "get_user_profile", "(", "self", ",", "user_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - user_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"user_id\"", "]", "=", "user_id", "self", ".", "logge...
39.052632
28.368421
def put_user_policy(self, user_name, policy_name, policy_json): """ Adds or updates the specified policy document for the specified user. :type user_name: string :param user_name: The name of the user the policy is associated with. :type policy_name: string :param polic...
[ "def", "put_user_policy", "(", "self", ",", "user_name", ",", "policy_name", ",", "policy_json", ")", ":", "params", "=", "{", "'UserName'", ":", "user_name", ",", "'PolicyName'", ":", "policy_name", ",", "'PolicyDocument'", ":", "policy_json", "}", "return", ...
36.222222
18.888889
def to_bigquery_field(self, name_case=DdlParseBase.NAME_CASE.original): """Generate BigQuery JSON field define""" col_name = self.get_name(name_case) mode = self.bigquery_mode if self.array_dimensional <= 1: # no or one dimensional array data type type = self.bi...
[ "def", "to_bigquery_field", "(", "self", ",", "name_case", "=", "DdlParseBase", ".", "NAME_CASE", ".", "original", ")", ":", "col_name", "=", "self", ".", "get_name", "(", "name_case", ")", "mode", "=", "self", ".", "bigquery_mode", "if", "self", ".", "arr...
33.771429
21.285714
def set_application_parameters(self, application_id, framework_type, repository_url): """ Sets parameters for the Hybrid Analysis Mapping ThreadFix functionality. :param application_id: Application identifier. :param framework_type: The web framework the app was built on. ('None', 'DETEC...
[ "def", "set_application_parameters", "(", "self", ",", "application_id", ",", "framework_type", ",", "repository_url", ")", ":", "params", "=", "{", "'frameworkType'", ":", "framework_type", ",", "'repositoryUrl'", ":", "repository_url", "}", "return", "self", ".", ...
56.416667
30.083333
def getCmdParams(cmd, request, **fields): """Update or fill the fields parameters depending on command code. Both cmd and drAppId can be provided # noqa: E501 in string or int format.""" drCode = None params = None drAppId = None # Fetch the parameters if cmd is found in dict if isinstan...
[ "def", "getCmdParams", "(", "cmd", ",", "request", ",", "*", "*", "fields", ")", ":", "drCode", "=", "None", "params", "=", "None", "drAppId", "=", "None", "# Fetch the parameters if cmd is found in dict", "if", "isinstance", "(", "cmd", ",", "int", ")", ":"...
41.107692
16.938462
def disassemble_all(bytecode, pc=0, fork=DEFAULT_FORK): """ Disassemble all instructions in bytecode :param bytecode: an evm bytecode (binary) :type bytecode: str | bytes | bytearray | iterator :param pc: program counter of the first instruction(optional) :type pc: int :para...
[ "def", "disassemble_all", "(", "bytecode", ",", "pc", "=", "0", ",", "fork", "=", "DEFAULT_FORK", ")", ":", "if", "isinstance", "(", "bytecode", ",", "bytes", ")", ":", "bytecode", "=", "bytearray", "(", "bytecode", ")", "if", "isinstance", "(", "bytecod...
26.116279
19.488372
def open(self, options=None, mimetype='application/octet-stream'): """ open: return a file like object for self. The method can be used with the 'with' statment. """ return self.connection.open(self, options, mimetype)
[ "def", "open", "(", "self", ",", "options", "=", "None", ",", "mimetype", "=", "'application/octet-stream'", ")", ":", "return", "self", ".", "connection", ".", "open", "(", "self", ",", "options", ",", "mimetype", ")" ]
42.166667
11.833333
def set_server_handler(self, handler_func, name=None, header_filter=None, alias=None, interval=0.5): """Sets an automatic handler for the type of message template currently loaded. This feature allows users to set a python handler function which is called automatically by the Rammbock message q...
[ "def", "set_server_handler", "(", "self", ",", "handler_func", ",", "name", "=", "None", ",", "header_filter", "=", "None", ",", "alias", "=", "None", ",", "interval", "=", "0.5", ")", ":", "msg_template", "=", "self", ".", "_get_message_template", "(", ")...
49
29.324324
def _add_kwarg_datasets(datasets, kwargs): """Add data sets of the given kwargs. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicode` to varies """ for te...
[ "def", "_add_kwarg_datasets", "(", "datasets", ",", "kwargs", ")", ":", "for", "test_method_suffix", ",", "dataset", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "datasets", "[", "test_method_suffix", "]", "=", "dataset" ]
28.928571
13.928571
def svg_polygon(coordinates, color): """ Create an svg triangle for the stationary heatmap. Parameters ---------- coordinates: list The coordinates defining the polygon color: string RGB color value e.g. #26ffd1 Returns ------- string, the svg string for the polygon...
[ "def", "svg_polygon", "(", "coordinates", ",", "color", ")", ":", "coord_str", "=", "[", "]", "for", "c", "in", "coordinates", ":", "coord_str", ".", "append", "(", "\",\"", ".", "join", "(", "map", "(", "str", ",", "c", ")", ")", ")", "coord_str", ...
25.727273
20
def luhn_checksum(number, chars=DIGITS): ''' Calculates the Luhn checksum for `number` :param number: string or int :param chars: string >>> luhn_checksum(1234) 4 ''' length = len(chars) number = [chars.index(n) for n in reversed(str(number))] return ( sum(number[::2])...
[ "def", "luhn_checksum", "(", "number", ",", "chars", "=", "DIGITS", ")", ":", "length", "=", "len", "(", "chars", ")", "number", "=", "[", "chars", ".", "index", "(", "n", ")", "for", "n", "in", "reversed", "(", "str", "(", "number", ")", ")", "]...
22.529412
22.882353
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: ChannelContext for this ChannelInstance :rtype: twilio.rest.chat.v1.service.channel.ChannelContex...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "ChannelContext", "(", "self", ".", "_version", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]", ",", "...
38.2
17.933333
def _make_load_template(self): """ Return a function that loads a template by name. """ loader = self._make_loader() def load_template(template_name): return loader.load_name(template_name) return load_template
[ "def", "_make_load_template", "(", "self", ")", ":", "loader", "=", "self", ".", "_make_loader", "(", ")", "def", "load_template", "(", "template_name", ")", ":", "return", "loader", ".", "load_name", "(", "template_name", ")", "return", "load_template" ]
23.909091
15.727273
def fn_getdatetime_list(fn): """Extract all datetime strings from input filename """ #Want to split last component fn = os.path.split(os.path.splitext(fn)[0])[-1] import re #WV01_12JUN152223255-P1BS_R1C1-102001001B3B9800__WV01_12JUN152224050-P1BS_R1C1-102001001C555C00-DEM_4x.tif #Need to par...
[ "def", "fn_getdatetime_list", "(", "fn", ")", ":", "#Want to split last component", "fn", "=", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "splitext", "(", "fn", ")", "[", "0", "]", ")", "[", "-", "1", "]", "import", "re", "#WV01_12...
47.175439
24.54386
def set_context(self, definition: Definition, explanation: str) -> None: """Set the source code context for this error.""" self.definition = definition self.explanation = explanation
[ "def", "set_context", "(", "self", ",", "definition", ":", "Definition", ",", "explanation", ":", "str", ")", "->", "None", ":", "self", ".", "definition", "=", "definition", "self", ".", "explanation", "=", "explanation" ]
50.75
9.5
def reboot(name, call=None): ''' Reboot a VM. .. versionadded:: 2016.3.0 name The name of the VM to reboot. CLI Example: .. code-block:: bash salt-cloud -a reboot my-vm ''' if call != 'action': raise SaltCloudSystemExit( 'The start action must be ...
[ "def", "reboot", "(", "name", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The start action must be called with -a or --action.'", ")", "log", ".", "info", "(", "'Rebooting node %s'", ",", "name", ...
19.347826
25.173913
def has_no_error( state, incorrect_msg="Have a look at the console: your code contains an error. Fix it and try again!", ): """Check whether the submission did not generate a runtime error. If all SCTs for an exercise pass, before marking the submission as correct pythonwhat will automatically check wh...
[ "def", "has_no_error", "(", "state", ",", "incorrect_msg", "=", "\"Have a look at the console: your code contains an error. Fix it and try again!\"", ",", ")", ":", "state", ".", "assert_root", "(", "\"has_no_error\"", ")", "if", "state", ".", "reporter", ".", "errors", ...
42.822581
31.983871
def add_filter(self, files_filter, filter_type=DefaultFilterType): """ Add a files filter to this iterator. For a file to be processed, it must match ALL filters, eg they are added with ADD, not OR. :param files_filter: filter to apply, must be an object inheriting from filters.FilterAP...
[ "def", "add_filter", "(", "self", ",", "files_filter", ",", "filter_type", "=", "DefaultFilterType", ")", ":", "self", ".", "__filters", ".", "append", "(", "(", "files_filter", ",", "filter_type", ")", ")", "return", "self" ]
47.7
25.7
def parse_assignment(self, stream): """ AssignmentStmt ::= Name WSC AssignmentSymbol WSC Value StatementDelim """ lineno = stream.lineno name = self.next_token(stream) self.ensure_assignment(stream) at_an_end = any(( self.has_end_group(stream), ...
[ "def", "parse_assignment", "(", "self", ",", "stream", ")", ":", "lineno", "=", "stream", ".", "lineno", "name", "=", "self", ".", "next_token", "(", "stream", ")", "self", ".", "ensure_assignment", "(", "stream", ")", "at_an_end", "=", "any", "(", "(", ...
37.210526
9.526316
def _make_counter_path(self, machine_name, counter_name, instance_name, counters): """ When handling non english versions, the counters don't work quite as documented. This is because strings like "Bytes Sent/sec" might appear multiple times in the english master, and might not have mapp...
[ "def", "_make_counter_path", "(", "self", ",", "machine_name", ",", "counter_name", ",", "instance_name", ",", "counters", ")", ":", "path", "=", "\"\"", "if", "WinPDHCounter", ".", "_use_en_counter_names", ":", "'''\n In this case, we don't have any translatio...
47.134615
29.211538
def symmetry_measure(points_distorted, points_perfect): """ Computes the continuous symmetry measure of the (distorted) set of points "points_distorted" with respect to the (perfect) set of points "points_perfect". :param points_distorted: List of points describing a given (distorted) polyhedron for whi...
[ "def", "symmetry_measure", "(", "points_distorted", ",", "points_perfect", ")", ":", "# When there is only one point, the symmetry measure is 0.0 by definition", "if", "len", "(", "points_distorted", ")", "==", "1", ":", "return", "{", "'symmetry_measure'", ":", "0.0", ",...
74.384615
37.846154
def generate_models(config, raml_resources): """ Generate model for each resource in :raml_resources: The DB model name is generated using singular titled version of current resource's url. E.g. for resource under url '/stories', model with name 'Story' will be generated. :param config: Pyramid Co...
[ "def", "generate_models", "(", "config", ",", "raml_resources", ")", ":", "from", ".", "models", "import", "handle_model_generation", "if", "not", "raml_resources", ":", "return", "for", "raml_resource", "in", "raml_resources", ":", "# No need to generate models for dyn...
40.878788
17.818182
def reprsig(fun, name=None, method=False): """Format a methods signature for display.""" args, varargs, keywords, defs, kwargs = [], [], None, [], {} argspec = fun if callable(fun): name = fun.__name__ if name is None else name argspec = getargspec(fun) try: args = argspec[0]...
[ "def", "reprsig", "(", "fun", ",", "name", "=", "None", ",", "method", "=", "False", ")", ":", "args", ",", "varargs", ",", "keywords", ",", "defs", ",", "kwargs", "=", "[", "]", ",", "[", "]", ",", "None", ",", "[", "]", ",", "{", "}", "args...
31.521739
15.565217
def WRatio(s1, s2, force_ascii=True, full_process=True): """ Return a measure of the sequences' similarity between 0 and 100, using different algorithms. **Steps in the order they occur** #. Run full_process from utils on both strings #. Short circuit if this makes either string empty #. Take ...
[ "def", "WRatio", "(", "s1", ",", "s2", ",", "force_ascii", "=", "True", ",", "full_process", "=", "True", ")", ":", "if", "full_process", ":", "p1", "=", "utils", ".", "full_process", "(", "s1", ",", "force_ascii", "=", "force_ascii", ")", "p2", "=", ...
35.052632
22.657895
def encode(self, value): """encode(value) -> bytearray Encodes the given value to a bytearray according to this Complex Type definition. """ e = self.evrs.get(value, None) if not e: log.error(str(value) + " not found as EVR. Cannot encode.") retur...
[ "def", "encode", "(", "self", ",", "value", ")", ":", "e", "=", "self", ".", "evrs", ".", "get", "(", "value", ",", "None", ")", "if", "not", "e", ":", "log", ".", "error", "(", "str", "(", "value", ")", "+", "\" not found as EVR. Cannot encode.\"", ...
32
16.833333
def service_checks(self, name): """ Return the service checks received under the given name """ return [ ServiceCheckStub( ensure_unicode(stub.check_id), ensure_unicode(stub.name), stub.status, normalize_tags(stu...
[ "def", "service_checks", "(", "self", ",", "name", ")", ":", "return", "[", "ServiceCheckStub", "(", "ensure_unicode", "(", "stub", ".", "check_id", ")", ",", "ensure_unicode", "(", "stub", ".", "name", ")", ",", "stub", ".", "status", ",", "normalize_tags...
33.4
12.466667
def find_isolated_tile_indices(hand_34): """ Tiles that don't have -1, 0 and +1 neighbors :param hand_34: array of tiles in 34 tile format :return: array of isolated tiles indices """ isolated_indices = [] for x in range(0, CHUN + 1): # for honor tiles we don't need to check nearby ...
[ "def", "find_isolated_tile_indices", "(", "hand_34", ")", ":", "isolated_indices", "=", "[", "]", "for", "x", "in", "range", "(", "0", ",", "CHUN", "+", "1", ")", ":", "# for honor tiles we don't need to check nearby tiles", "if", "is_honor", "(", "x", ")", "a...
33.517241
14.344828
def zero(self): """Return a tensor of all zeros. Examples -------- >>> space = odl.rn(3) >>> x = space.zero() >>> x rn(3).element([ 0., 0., 0.]) """ return self.element(np.zeros(self.shape, dtype=self.dtype, ...
[ "def", "zero", "(", "self", ")", ":", "return", "self", ".", "element", "(", "np", ".", "zeros", "(", "self", ".", "shape", ",", "dtype", "=", "self", ".", "dtype", ",", "order", "=", "self", ".", "default_order", ")", ")" ]
27.916667
17.833333
def create_logout_request(self, destination, issuer_entity_id, subject_id=None, name_id=None, reason=None, expire=None, message_id=0, consent=None, extensions=None, sign=False, session_indexes=None, s...
[ "def", "create_logout_request", "(", "self", ",", "destination", ",", "issuer_entity_id", ",", "subject_id", "=", "None", ",", "name_id", "=", "None", ",", "reason", "=", "None", ",", "expire", "=", "None", ",", "message_id", "=", "0", ",", "consent", "=",...
45.588235
20.470588
def functions_factory(cls, coef, degree, knots, ext, **kwargs): """ Given some coefficients, return a B-spline. """ return cls._basis_spline_factory(coef, degree, knots, 0, ext)
[ "def", "functions_factory", "(", "cls", ",", "coef", ",", "degree", ",", "knots", ",", "ext", ",", "*", "*", "kwargs", ")", ":", "return", "cls", ".", "_basis_spline_factory", "(", "coef", ",", "degree", ",", "knots", ",", "0", ",", "ext", ")" ]
34.166667
17.166667
def scatter_plot(data, index_x, index_y, percent=100.0, seed=1, size=50, title=None, outfile=None, wait=True): """ Plots two attributes against each other. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param data: the dataset :type data: Instances :param i...
[ "def", "scatter_plot", "(", "data", ",", "index_x", ",", "index_y", ",", "percent", "=", "100.0", ",", "seed", "=", "1", ",", "size", "=", "50", ",", "title", "=", "None", ",", "outfile", "=", "None", ",", "wait", "=", "True", ")", ":", "if", "no...
32.537313
20.089552
def new(self, bootstrap_with=None, use_timer=False, with_proof=False): """ Actual constructor of the solver. """ if not self.maplesat: self.maplesat = pysolvers.maplesat_new() if bootstrap_with: for clause in bootstrap_with: ...
[ "def", "new", "(", "self", ",", "bootstrap_with", "=", "None", ",", "use_timer", "=", "False", ",", "with_proof", "=", "False", ")", ":", "if", "not", "self", ".", "maplesat", ":", "self", ".", "maplesat", "=", "pysolvers", ".", "maplesat_new", "(", ")...
35.473684
19.263158
def set_inlets(self, pores=None, clusters=None): r""" Parameters ---------- pores : array_like The list of inlet pores from which the Phase can enter the Network clusters : list of lists - can be just one list but each list defines a cluster of pores tha...
[ "def", "set_inlets", "(", "self", ",", "pores", "=", "None", ",", "clusters", "=", "None", ")", ":", "if", "pores", "is", "not", "None", ":", "logger", ".", "info", "(", "\"Setting inlet pores at shared pressure\"", ")", "clusters", "=", "[", "]", "cluster...
39.315789
16.868421
def nvmlUnitGetUnitInfo(unit): r""" /** * Retrieves the static information associated with a unit. * * For S-class products. * * See \ref nvmlUnitInfo_t for details on available unit info. * * @param unit The identifier of the target unit *...
[ "def", "nvmlUnitGetUnitInfo", "(", "unit", ")", ":", "\"\"\"\n/**\n * Retrieves the static information associated with a unit.\n *\n * For S-class products.\n *\n * See \\ref nvmlUnitInfo_t for details on available unit info.\n *\n * @param unit The identifier of the targ...
37.853659
28.463415
def contains_any(self, other): """Check if any flags are set. (OsuMod.Hidden | OsuMod.HardRock) in flags # Check if either hidden or hardrock are enabled. OsuMod.keyMod in flags # Check if any keymod is enabled. """ return self.value == other.value or self.value & other.value
[ "def", "contains_any", "(", "self", ",", "other", ")", ":", "return", "self", ".", "value", "==", "other", ".", "value", "or", "self", ".", "value", "&", "other", ".", "value" ]
44.428571
23.142857
def pop_fw_local(self, tenant_id, net_id, direc, node_ip): """Populate the local cache. Read the Network DB and populate the local cache. Read the subnet from the Subnet DB, given the net_id and populate the cache. """ net = self.get_network(net_id) serv_obj = se...
[ "def", "pop_fw_local", "(", "self", ",", "tenant_id", ",", "net_id", ",", "direc", ",", "node_ip", ")", ":", "net", "=", "self", ".", "get_network", "(", "net_id", ")", "serv_obj", "=", "self", ".", "get_service_obj", "(", "tenant_id", ")", "serv_obj", "...
45.88
19.76
def _inspect_class(cls, subclass): """ Args: cls(:py:class:`Plugin`): Parent class subclass(:py:class:`Plugin`): Subclass to evaluate Returns: Result: Named tuple Inspect subclass for inclusion Values for errorcode: * 0: No error Error codes between 0 and...
[ "def", "_inspect_class", "(", "cls", ",", "subclass", ")", ":", "if", "callable", "(", "subclass", ".", "_skipload_", ")", ":", "result", "=", "subclass", ".", "_skipload_", "(", ")", "if", "isinstance", "(", "result", ",", "tuple", ")", ":", "skip", "...
23.755102
19.795918
def _virtual_hv(osdata): ''' Returns detailed hypervisor information from sysfs Currently this seems to be used only by Xen ''' grains = {} # Bail early if we're not running on Xen try: if 'xen' not in osdata['virtual']: return grains except KeyError: return ...
[ "def", "_virtual_hv", "(", "osdata", ")", ":", "grains", "=", "{", "}", "# Bail early if we're not running on Xen", "try", ":", "if", "'xen'", "not", "in", "osdata", "[", "'virtual'", "]", ":", "return", "grains", "except", "KeyError", ":", "return", "grains",...
42.090909
21.436364
def _create_header(self): """ Function to create the GroupHeader (GrpHdr) in the CstmrCdtTrfInitn Node """ # Retrieve the node to which we will append the group header. CstmrCdtTrfInitn_node = self._xml.find('CstmrCdtTrfInitn') # Create the header nodes. ...
[ "def", "_create_header", "(", "self", ")", ":", "# Retrieve the node to which we will append the group header.", "CstmrCdtTrfInitn_node", "=", "self", ".", "_xml", ".", "find", "(", "'CstmrCdtTrfInitn'", ")", "# Create the header nodes.", "GrpHdr_node", "=", "ET", ".", "E...
35.9375
11.5
def decode_filter(text, encoding='utf-8'): """ decode a binary object to str and filter out non-printable characters Parameters ---------- text: bytes the binary object to be decoded encoding: str the encoding to be used Returns ------- str the decoded a...
[ "def", "decode_filter", "(", "text", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "text", "is", "not", "None", ":", "text", "=", "text", ".", "decode", "(", "encoding", ",", "errors", "=", "'ignore'", ")", "printable", "=", "set", "(", "string", ...
24.521739
18
def reset(self): """Reset metric counter.""" self._positions = [] self._line = 1 self._curr = None # current scope we are analyzing self._scope = 0 self.language = None
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_positions", "=", "[", "]", "self", ".", "_line", "=", "1", "self", ".", "_curr", "=", "None", "# current scope we are analyzing", "self", ".", "_scope", "=", "0", "self", ".", "language", "=", "None...
30.142857
14.571429
def tokenize(self, docs): """ The first pass consists of converting documents into "transactions" (sets of their tokens) and the initial frequency/support filtering. Then iterate until we close in on a final set. `docs` can be any iterator or generator so long as it yie...
[ "def", "tokenize", "(", "self", ",", "docs", ")", ":", "if", "self", ".", "min_sup", "<", "1", "/", "len", "(", "docs", ")", ":", "raise", "Exception", "(", "'`min_sup` must be greater than or equal to `1/len(docs)`.'", ")", "# First pass", "candidates", "=", ...
37.880952
22.071429
def create_archive(archive, filenames, verbosity=0, program=None, interactive=True): """Create given archive with given files.""" util.check_new_filename(archive) util.check_archive_filelist(filenames) if verbosity >= 0: util.log_info("Creating %s ..." % archive) res = _create_archive(archiv...
[ "def", "create_archive", "(", "archive", ",", "filenames", ",", "verbosity", "=", "0", ",", "program", "=", "None", ",", "interactive", "=", "True", ")", ":", "util", ".", "check_new_filename", "(", "archive", ")", "util", ".", "check_archive_filelist", "(",...
45.545455
16.818182
def get_peer_resources(self, peer_jid): """ Return a dict mapping resources of the given bare `peer_jid` to the presence state last received for that resource. Unavailable presence states are not included. If the bare JID is in a error state (i.e. an error presence stanza has be...
[ "def", "get_peer_resources", "(", "self", ",", "peer_jid", ")", ":", "try", ":", "d", "=", "dict", "(", "self", ".", "_presences", "[", "peer_jid", "]", ")", "d", ".", "pop", "(", "None", ",", "None", ")", "return", "d", "except", "KeyError", ":", ...
35.266667
17.933333
def cache_context(self, context): ''' Cache the given context to disk ''' if not os.path.isdir(os.path.dirname(self.cache_path)): os.mkdir(os.path.dirname(self.cache_path)) with salt.utils.files.fopen(self.cache_path, 'w+b') as cache: self.serial.dump(cont...
[ "def", "cache_context", "(", "self", ",", "context", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "cache_path", ")", ")", ":", "os", ".", "mkdir", "(", "os", ".", "path", ".", ...
40.5
17
def change_content_type(self, new_ctype, guess=False): """ Copies object to itself, but applies a new content-type. The guess feature requires the container to be CDN-enabled. If not then the content-type must be supplied. If using guess with a CDN-enabled container, new_ctype ca...
[ "def", "change_content_type", "(", "self", ",", "new_ctype", ",", "guess", "=", "False", ")", ":", "self", ".", "container", ".", "change_object_content_type", "(", "self", ",", "new_ctype", "=", "new_ctype", ",", "guess", "=", "guess", ")" ]
51.1
19.3
def block_user_signals(self, name, ignore_error=False): """ Temporarily disconnects the user-defined signals for the specified parameter name. Note this only affects those connections made with connect_signal_changed(), and I do not recommend adding new connections ...
[ "def", "block_user_signals", "(", "self", ",", "name", ",", "ignore_error", "=", "False", ")", ":", "x", "=", "self", ".", "_find_parameter", "(", "name", ".", "split", "(", "\"/\"", ")", ",", "quiet", "=", "ignore_error", ")", "# if it pooped.", "if", "...
36
20.631579
def device_unlocked(self, device): """Show unlock notification for specified device object.""" if not self._mounter.is_handleable(device): return self._show_notification( 'device_unlocked', _('Device unlocked'), _('{0.device_presentation} unlocked'...
[ "def", "device_unlocked", "(", "self", ",", "device", ")", ":", "if", "not", "self", ".", "_mounter", ".", "is_handleable", "(", "device", ")", ":", "return", "self", ".", "_show_notification", "(", "'device_unlocked'", ",", "_", "(", "'Device unlocked'", ")...
39.111111
10.333333
def fill_area(self, x, y, width, height, color, opacity = 1): """fill rectangular area with specified color""" self.save_context() self.rectangle(x, y, width, height) self._add_instruction("clip") self.rectangle(x, y, width, height) self.fill(color, opacity) self....
[ "def", "fill_area", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ",", "color", ",", "opacity", "=", "1", ")", ":", "self", ".", "save_context", "(", ")", "self", ".", "rectangle", "(", "x", ",", "y", ",", "width", ",", "height", ...
41.25
7.5
def read(self, size=None): """Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all re...
[ "def", "read", "(", "self", ",", "size", "=", "None", ")", ":", "if", "not", "self", ".", "_is_open", ":", "raise", "IOError", "(", "'Not opened.'", ")", "if", "self", ".", "_fsntfs_data_stream", ":", "return", "self", ".", "_fsntfs_data_stream", ".", "r...
27.826087
20.347826
def get_lines_from_file(filename, lineno, context_lines): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ def get_lines(start, end): return [linecache.getline(filename, l).rstrip() for l in range(start, ...
[ "def", "get_lines_from_file", "(", "filename", ",", "lineno", ",", "context_lines", ")", ":", "def", "get_lines", "(", "start", ",", "end", ")", ":", "return", "[", "linecache", ".", "getline", "(", "filename", ",", "l", ")", ".", "rstrip", "(", ")", "...
41.6875
17.8125
def get_period_last_30_days() -> str: """ Returns the last week as a period string """ today = Datum() today.today() # start_date = today - timedelta(days=30) start_date = today.clone() start_date.subtract_days(30) period = get_period(start_date.value, today.value) return period
[ "def", "get_period_last_30_days", "(", ")", "->", "str", ":", "today", "=", "Datum", "(", ")", "today", ".", "today", "(", ")", "# start_date = today - timedelta(days=30)", "start_date", "=", "today", ".", "clone", "(", ")", "start_date", ".", "subtract_days", ...
30.3
14.7
def _update_ned_query_history( self): """*Update the database helper table to give details of the ned cone searches performed* *Usage:* .. code-block:: python stream._update_ned_query_history() """ self.log.debug('starting the ``_update_ned_quer...
[ "def", "_update_ned_query_history", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_update_ned_query_history`` method'", ")", "myPid", "=", "self", ".", "myPid", "# ASTROCALC UNIT CONVERTER OBJECT", "converter", "=", "unit_conversion", "(...
32.358696
15.728261
def filter(self, filter_arguments): """ Takes a dictionary of filter parameters. Return a list of objects based on a list of parameters. """ results = self._get_content() # Filter based on a dictionary of search parameters if isinstance(filter_arguments, dict): ...
[ "def", "filter", "(", "self", ",", "filter_arguments", ")", ":", "results", "=", "self", ".", "_get_content", "(", ")", "# Filter based on a dictionary of search parameters", "if", "isinstance", "(", "filter_arguments", ",", "dict", ")", ":", "for", "item", ",", ...
37.56
17.8
def set_imap_cb(self, w, index): """This callback is invoked when the user selects a new intensity map from the preferences pane.""" name = imap.get_names()[index] self.t_.set(intensity_map=name)
[ "def", "set_imap_cb", "(", "self", ",", "w", ",", "index", ")", ":", "name", "=", "imap", ".", "get_names", "(", ")", "[", "index", "]", "self", ".", "t_", ".", "set", "(", "intensity_map", "=", "name", ")" ]
44.6
2.2
def genfromtxt_args_error(self): """ Passed as keyword arguments to [`numpy.genfromtxt`][1] when called by `scipy_data_fitting.Data.load_error`. Even if defined here, the `usecols` value will always be reset based on `scipy_data_fitting.Data.error_columns` before being passed to...
[ "def", "genfromtxt_args_error", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_genfromtxt_args_error'", ")", ":", "self", ".", "_genfromtxt_args_error", "=", "self", ".", "genfromtxt_args", ".", "copy", "(", ")", "return", "self", ".", "...
44.625
24.25
def go_down(self): """ Go down one, wrap to beginning if necessary """ if self.current_option < len(self.items) - 1: self.current_option += 1 else: self.current_option = 0 self.draw()
[ "def", "go_down", "(", "self", ")", ":", "if", "self", ".", "current_option", "<", "len", "(", "self", ".", "items", ")", "-", "1", ":", "self", ".", "current_option", "+=", "1", "else", ":", "self", ".", "current_option", "=", "0", "self", ".", "d...
27.444444
11.444444
def _handle_display_data(self, msg): """ Overridden to handle rich data types, like SVG. """ if not self._hidden and self._is_from_this_session(msg): source = msg['content']['source'] data = msg['content']['data'] metadata = msg['content']['metadata'] ...
[ "def", "_handle_display_data", "(", "self", ",", "msg", ")", ":", "if", "not", "self", ".", "_hidden", "and", "self", ".", "_is_from_this_session", "(", "msg", ")", ":", "source", "=", "msg", "[", "'content'", "]", "[", "'source'", "]", "data", "=", "m...
53.423077
15.884615
def parse(cls, root): """ Create a new MDWrap by parsing root. :param root: Element or ElementTree to be parsed into a MDWrap. :raises exceptions.ParseError: If mdWrap does not contain MDTYPE :raises exceptions.ParseError: If xmlData contains no children """ if r...
[ "def", "parse", "(", "cls", ",", "root", ")", ":", "if", "root", ".", "tag", "!=", "utils", ".", "lxmlns", "(", "\"mets\"", ")", "+", "\"mdWrap\"", ":", "raise", "exceptions", ".", "ParseError", "(", "\"MDWrap can only parse mdWrap elements with METS namespace.\...
40.103448
19.275862
def filter(self,x): """ Filter the signal """ y = signal.lfilter(self.b,[1],x) return y
[ "def", "filter", "(", "self", ",", "x", ")", ":", "y", "=", "signal", ".", "lfilter", "(", "self", ".", "b", ",", "[", "1", "]", ",", "x", ")", "return", "y" ]
20.333333
10
def as_string(self, name=None): """ Declares a stream converting each tuple on this stream into a string using `str(tuple)`. The stream is typed as a :py:const:`string stream <streamsx.topology.schema.CommonSchema.String>`. If this stream is already typed as a string stream the...
[ "def", "as_string", "(", "self", ",", "name", "=", "None", ")", ":", "sas", "=", "self", ".", "_change_schema", "(", "streamsx", ".", "topology", ".", "schema", ".", "CommonSchema", ".", "String", ",", "'as_string'", ",", "name", ")", ".", "_layout", "...
39.541667
28.041667
def run_migrations(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ with engine.connect() as connection: context.configure( connection=connection, target_metadata=Model.metadata) ...
[ "def", "run_migrations", "(", ")", ":", "with", "engine", ".", "connect", "(", ")", "as", "connection", ":", "context", ".", "configure", "(", "connection", "=", "connection", ",", "target_metadata", "=", "Model", ".", "metadata", ")", "with", "context", "...
27.357143
13.071429
def find_hal(self, atoms): """Look for halogen bond acceptors (Y-{O|P|N|S}, with Y=C,P,S)""" data = namedtuple('hal_acceptor', 'o o_orig_idx y y_orig_idx') a_set = [] # All oxygens, nitrogen, sulfurs with neighboring carbon, phosphor, nitrogen or sulfur for a in [at for at in ato...
[ "def", "find_hal", "(", "self", ",", "atoms", ")", ":", "data", "=", "namedtuple", "(", "'hal_acceptor'", ",", "'o o_orig_idx y y_orig_idx'", ")", "a_set", "=", "[", "]", "# All oxygens, nitrogen, sulfurs with neighboring carbon, phosphor, nitrogen or sulfur", "for", "a",...
68.916667
35.5
def generate_sizes(name, genome_dir): """Generate a sizes file with length of sequences in FASTA file.""" fa = os.path.join(genome_dir, name, "{}.fa".format(name)) sizes = fa + ".sizes" g = Fasta(fa) with open(sizes, "w") as f: for seqname in g.keys(): f.write("{}\t{}\n".format(s...
[ "def", "generate_sizes", "(", "name", ",", "genome_dir", ")", ":", "fa", "=", "os", ".", "path", ".", "join", "(", "genome_dir", ",", "name", ",", "\"{}.fa\"", ".", "format", "(", "name", ")", ")", "sizes", "=", "fa", "+", "\".sizes\"", "g", "=", "...
42.25
12.875
def path_glob(pattern, current_dir=None): """Use pathlib for ant-like patterns, like: "**/*.py" :param pattern: File/directory pattern to use (as string). :param current_dir: Current working directory (as Path, pathlib.Path, str) :return Resolved Path (as path.Path). """ if not current_di...
[ "def", "path_glob", "(", "pattern", ",", "current_dir", "=", "None", ")", ":", "if", "not", "current_dir", ":", "current_dir", "=", "pathlib", ".", "Path", ".", "cwd", "(", ")", "elif", "not", "isinstance", "(", "current_dir", ",", "pathlib", ".", "Path"...
38.2
14.2
def run_command(self, cmd, history=True, new_prompt=True): """Run command in interpreter""" if not cmd: cmd = '' else: if history: self.add_to_history(cmd) if not self.multithreaded: if 'input' not in cmd: self....
[ "def", "run_command", "(", "self", ",", "cmd", ",", "history", "=", "True", ",", "new_prompt", "=", "True", ")", ":", "if", "not", "cmd", ":", "cmd", "=", "''", "else", ":", "if", "history", ":", "self", ".", "add_to_history", "(", "cmd", ")", "if"...
43.75
18.1
def script(self, s): """ Parse a script by compiling it. Return a :class:`Contract` or None. """ try: script = self._network.script.compile(s) script_info = self._network.contract.info_for_script(script) return Contract(script_info, self._netwo...
[ "def", "script", "(", "self", ",", "s", ")", ":", "try", ":", "script", "=", "self", ".", "_network", ".", "script", ".", "compile", "(", "s", ")", "script_info", "=", "self", ".", "_network", ".", "contract", ".", "info_for_script", "(", "script", "...
33
13
def dcos_version(): """Return the version of the running cluster. :return: DC/OS cluster version as a string """ url = _gen_url('dcos-metadata/dcos-version.json') response = dcos.http.request('get', url) if response.status_code == 200: return response.json()['version'] else: ...
[ "def", "dcos_version", "(", ")", ":", "url", "=", "_gen_url", "(", "'dcos-metadata/dcos-version.json'", ")", "response", "=", "dcos", ".", "http", ".", "request", "(", "'get'", ",", "url", ")", "if", "response", ".", "status_code", "==", "200", ":", "retur...
29.272727
12.909091
def _auth_session(self, username, password): """ Creates session to Hetzner account, authenticates with given credentials and returns the session, if authentication was successful. Otherwise raises error. """ api = self.api[self.account]['auth'] endpoint = api.get('endpoi...
[ "def", "_auth_session", "(", "self", ",", "username", ",", "password", ")", ":", "api", "=", "self", ".", "api", "[", "self", ".", "account", "]", "[", "'auth'", "]", "endpoint", "=", "api", ".", "get", "(", "'endpoint'", ",", "self", ".", "api", "...
56.291667
21.208333
def __isValidTGZ(self, suffix): """To determine whether the suffix `.tar.gz` or `.tgz` format""" if suffix and isinstance(suffix, string_types): if suffix.endswith(".tar.gz") or suffix.endswith(".tgz"): return True return False
[ "def", "__isValidTGZ", "(", "self", ",", "suffix", ")", ":", "if", "suffix", "and", "isinstance", "(", "suffix", ",", "string_types", ")", ":", "if", "suffix", ".", "endswith", "(", "\".tar.gz\"", ")", "or", "suffix", ".", "endswith", "(", "\".tgz\"", ")...
46.5
14.333333
def _clone(self, **kwargs): """ Create a clone of this collection. The only param in the initial collection is the filter context. Each chainable filter is added to the clone and returned to preserve previous iterators and their returned elements. :return: :class...
[ "def", "_clone", "(", "self", ",", "*", "*", "kwargs", ")", ":", "params", "=", "copy", ".", "deepcopy", "(", "self", ".", "_params", ")", "if", "self", ".", "_iexact", ":", "params", ".", "update", "(", "iexact", "=", "self", ".", "_iexact", ")", ...
36.666667
12.533333
def is_ambiguous(self, dt, idx=None): """ Whether or not the "wall time" of a given datetime is ambiguous in this zone. :param dt: A :py:class:`datetime.datetime`, naive or time zone aware. :return: Returns ``True`` if ambiguous, ``False`` otherwise. ...
[ "def", "is_ambiguous", "(", "self", ",", "dt", ",", "idx", "=", "None", ")", ":", "if", "idx", "is", "None", ":", "idx", "=", "self", ".", "_find_last_transition", "(", "dt", ")", "# Calculate the difference in offsets from current to previous", "timestamp", "="...
27.964286
22.464286
def instance_attr_ancestors(self, name, context=None): """Iterate over the parents that define the given name as an attribute. :param name: The name to find definitions for. :type name: str :returns: The parents that define the given name as an instance attribute. :...
[ "def", "instance_attr_ancestors", "(", "self", ",", "name", ",", "context", "=", "None", ")", ":", "for", "astroid", "in", "self", ".", "ancestors", "(", "context", "=", "context", ")", ":", "if", "name", "in", "astroid", ".", "instance_attrs", ":", "yie...
36.615385
14.615385
def update_version(self, version, step=1): "Compute an new version and write it as a tag" # update the version based on the flags passed. if self.config.patch: version.patch += step if self.config.minor: version.minor += step if self.config.major: ...
[ "def", "update_version", "(", "self", ",", "version", ",", "step", "=", "1", ")", ":", "# update the version based on the flags passed.", "if", "self", ".", "config", ".", "patch", ":", "version", ".", "patch", "+=", "step", "if", "self", ".", "config", ".",...
36
18.090909
def close(self): """Closes the underlying database file.""" if hasattr(self.db, 'close'): with self.write_mutex: self.db.close()
[ "def", "close", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "db", ",", "'close'", ")", ":", "with", "self", ".", "write_mutex", ":", "self", ".", "db", ".", "close", "(", ")" ]
33.6
8.4
def webfont_cookie(request): '''Adds WEBFONT Flag to the context''' if hasattr(request, 'COOKIES') and request.COOKIES.get(WEBFONT_COOKIE_NAME, None): return { WEBFONT_COOKIE_NAME.upper(): True } return { WEBFONT_COOKIE_NAME.upper(): False }
[ "def", "webfont_cookie", "(", "request", ")", ":", "if", "hasattr", "(", "request", ",", "'COOKIES'", ")", "and", "request", ".", "COOKIES", ".", "get", "(", "WEBFONT_COOKIE_NAME", ",", "None", ")", ":", "return", "{", "WEBFONT_COOKIE_NAME", ".", "upper", ...
23.75
25.416667
def parse(self, text, context=0, skip_style_tags=False): """Parse *text*, returning a :class:`.Wikicode` object tree. If given, *context* will be passed as a starting context to the parser. This is helpful when this function is used inside node attribute setters. For example, :class:`.E...
[ "def", "parse", "(", "self", ",", "text", ",", "context", "=", "0", ",", "skip_style_tags", "=", "False", ")", ":", "tokens", "=", "self", ".", "_tokenizer", ".", "tokenize", "(", "text", ",", "context", ",", "skip_style_tags", ")", "code", "=", "self"...
46.736842
23.947368
def setup(self, builder: Builder): """Performs this component's simulation setup. The ``setup`` method is automatically called by the simulation framework. The framework passes in a ``builder`` object which provides access to a variety of framework subsystems and metadata. Para...
[ "def", "setup", "(", "self", ",", "builder", ":", "Builder", ")", ":", "self", ".", "config", "=", "builder", ".", "configuration", ".", "mortality", "self", ".", "population_view", "=", "builder", ".", "population", ".", "get_view", "(", "[", "'alive'", ...
43.526316
28.842105
def _parse_leaves(self, leaves) -> List[Tuple[str, int]]: """Returns a list of pairs (leaf_name, distance)""" return [(self._leaf_name(leaf), 0) for leaf in leaves]
[ "def", "_parse_leaves", "(", "self", ",", "leaves", ")", "->", "List", "[", "Tuple", "[", "str", ",", "int", "]", "]", ":", "return", "[", "(", "self", ".", "_leaf_name", "(", "leaf", ")", ",", "0", ")", "for", "leaf", "in", "leaves", "]" ]
59.333333
13
def compose_all(stream, Loader=Loader): """ Parse all YAML documents in a stream and produce corresponding representation trees. """ loader = Loader(stream) try: while loader.check_node(): yield loader.get_node() finally: loader.dispose()
[ "def", "compose_all", "(", "stream", ",", "Loader", "=", "Loader", ")", ":", "loader", "=", "Loader", "(", "stream", ")", "try", ":", "while", "loader", ".", "check_node", "(", ")", ":", "yield", "loader", ".", "get_node", "(", ")", "finally", ":", "...
25.818182
10.181818
def platform_from_version(major, minor): """ returns the minimum platform version that can load the given class version indicated by major.minor or None if no known platforms match the given version """ v = (major, minor) for low, high, name in _platforms: if low <= v <= high: ...
[ "def", "platform_from_version", "(", "major", ",", "minor", ")", ":", "v", "=", "(", "major", ",", "minor", ")", "for", "low", ",", "high", ",", "name", "in", "_platforms", ":", "if", "low", "<=", "v", "<=", "high", ":", "return", "name", "return", ...
28.583333
15.25
def init(cls): """ Bind elements to callbacks. """ for el in cls.switcher_els: el.checked = False cls.bind_switcher() cls._draw_conspects() cls._create_searchable_typeahead()
[ "def", "init", "(", "cls", ")", ":", "for", "el", "in", "cls", ".", "switcher_els", ":", "el", ".", "checked", "=", "False", "cls", ".", "bind_switcher", "(", ")", "cls", ".", "_draw_conspects", "(", ")", "cls", ".", "_create_searchable_typeahead", "(", ...
21.272727
13.818182
def fit(self, Z, **fit_params): """Fit all the transforms one after the other and transform the data, then fit the transformed data using the final estimator. Parameters ---------- Z : ArrayRDD, TupleRDD or DictRDD Input data in blocked distributed format. R...
[ "def", "fit", "(", "self", ",", "Z", ",", "*", "*", "fit_params", ")", ":", "Zt", ",", "fit_params", "=", "self", ".", "_pre_transform", "(", "Z", ",", "*", "*", "fit_params", ")", "self", ".", "steps", "[", "-", "1", "]", "[", "-", "1", "]", ...
30.647059
18.058824
def notification_push(dev_type, to, message=None, **kwargs): """ Send data from your server to your users' devices. """ key = { 'ANDROID': settings.GCM_ANDROID_APIKEY, 'IOS': settings.GCM_IOS_APIKEY } if not key[dev_type]: raise ImproperlyConfigured( "You hav...
[ "def", "notification_push", "(", "dev_type", ",", "to", ",", "message", "=", "None", ",", "*", "*", "kwargs", ")", ":", "key", "=", "{", "'ANDROID'", ":", "settings", ".", "GCM_ANDROID_APIKEY", ",", "'IOS'", ":", "settings", ".", "GCM_IOS_APIKEY", "}", "...
31.588235
22.529412
def _follow_link(self, link_path_components, link): """Follow a link w.r.t. a path resolved so far. The component is either a real file, which is a no-op, or a symlink. In the case of a symlink, we have to modify the path as built up so far /a/b => ../c should yield /a/../c (...
[ "def", "_follow_link", "(", "self", ",", "link_path_components", ",", "link", ")", ":", "link_path", "=", "link", ".", "contents", "sep", "=", "self", ".", "_path_separator", "(", "link_path", ")", "# For links to absolute paths, we want to throw out everything", "# i...
43.575
18.725
def sr(x, promisc=None, filter=None, iface=None, nofilter=0, *args, **kargs): """Send and receive packets at layer 3""" s = conf.L3socket(promisc=promisc, filter=filter, iface=iface, nofilter=nofilter) result = sndrcv(s, x, *args, **kargs) s.close() return result
[ "def", "sr", "(", "x", ",", "promisc", "=", "None", ",", "filter", "=", "None", ",", "iface", "=", "None", ",", "nofilter", "=", "0", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "s", "=", "conf", ".", "L3socket", "(", "promisc", "=", ...
42.714286
16.285714
def _StopProcessStatusRPCServer(self): """Stops the process status RPC server.""" if not self._rpc_server: return # Make sure the engine gets one more status update so it knows # the worker has completed. self._WaitForStatusNotRunning() self._rpc_server.Stop() self._rpc_server = None...
[ "def", "_StopProcessStatusRPCServer", "(", "self", ")", ":", "if", "not", "self", ".", "_rpc_server", ":", "return", "# Make sure the engine gets one more status update so it knows", "# the worker has completed.", "self", ".", "_WaitForStatusNotRunning", "(", ")", "self", "...
28.8
20.133333
def _detect_loops(self, loop_callback=None): """ Loop detection. :param func loop_callback: A callback function for each detected loop backedge. :return: None """ loop_finder = self.project.analyses.LoopFinder(kb=self.kb, normalize=False, fail_fast=self._fail_fast) ...
[ "def", "_detect_loops", "(", "self", ",", "loop_callback", "=", "None", ")", ":", "loop_finder", "=", "self", ".", "project", ".", "analyses", ".", "LoopFinder", "(", "kb", "=", "self", ".", "kb", ",", "normalize", "=", "False", ",", "fail_fast", "=", ...
36.3
27.1
def load_from_file(path, fmt=None, is_training=True): ''' load data from file ''' if fmt is None: fmt = 'squad' assert fmt in ['squad', 'csv'], 'input format must be squad or csv' qp_pairs = [] if fmt == 'squad': with open(path) as data_file: data = json.load(data...
[ "def", "load_from_file", "(", "path", ",", "fmt", "=", "None", ",", "is_training", "=", "True", ")", ":", "if", "fmt", "is", "None", ":", "fmt", "=", "'squad'", "assert", "fmt", "in", "[", "'squad'", ",", "'csv'", "]", ",", "'input format must be squad o...
44.631579
19.736842