text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def load_soil_sample_data(sp): """ Sample data for the Soil object :param sp: Soil Object :return: """ # soil sp.g_mod = 60.0e6 # [Pa] sp.phi = 30 # [degrees] sp.relative_density = .40 # [decimal] sp.gwl = 2. # [m], ground water level sp.unit_dry_weight = 17000 # [N/m3] ...
[ "def", "load_soil_sample_data", "(", "sp", ")", ":", "# soil", "sp", ".", "g_mod", "=", "60.0e6", "# [Pa]", "sp", ".", "phi", "=", "30", "# [degrees]", "sp", ".", "relative_density", "=", ".40", "# [decimal]", "sp", ".", "gwl", "=", "2.", "# [m], ground wa...
28.333333
9.666667
def create_get_property_request_content(option): """Creates an XML for requesting of getting a property value of remote WebDAV resource. :param option: the property attributes as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be ...
[ "def", "create_get_property_request_content", "(", "option", ")", ":", "root", "=", "etree", ".", "Element", "(", "'propfind'", ",", "xmlns", "=", "'DAV:'", ")", "prop", "=", "etree", ".", "SubElement", "(", "root", ",", "'prop'", ")", "etree", ".", "SubEl...
56.076923
20.538462
def run(self): """Fetch remote code.""" link = self.content[0] try: r = requests.get(link) r.raise_for_status() self.content = [r.text] return super(RemoteCodeBlock, self).run() except Exception: document = self.state.document ...
[ "def", "run", "(", "self", ")", ":", "link", "=", "self", ".", "content", "[", "0", "]", "try", ":", "r", "=", "requests", ".", "get", "(", "link", ")", "r", ".", "raise_for_status", "(", ")", "self", ".", "content", "=", "[", "r", ".", "text",...
35.666667
12.666667
def accepts_admin_roles(func): """ Decorator that accepts only admin roles :param func: :return: """ if inspect.isclass(func): apply_function_to_members(func, accepts_admin_roles) return func else: @functools.wraps(func) def decorator(*args, **kwargs): ...
[ "def", "accepts_admin_roles", "(", "func", ")", ":", "if", "inspect", ".", "isclass", "(", "func", ")", ":", "apply_function_to_members", "(", "func", ",", "accepts_admin_roles", ")", "return", "func", "else", ":", "@", "functools", ".", "wraps", "(", "func"...
26.266667
16.266667
async def render_template(template_name_or_list: Union[str, List[str]], **context: Any) -> str: """Render the template with the context given. Arguments: template_name_or_list: Template name to render of a list of possible template names. context: The variables to pass to the templa...
[ "async", "def", "render_template", "(", "template_name_or_list", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ",", "*", "*", "context", ":", "Any", ")", "->", "str", ":", "await", "current_app", ".", "update_template_context", "(", "context...
45.727273
20.545455
def update_current_retention_level(self, value): """Set a new value for the current retention level. This updates the value of self.retain_files for an updated value of the retention level. Parameters ----------- value : int The new value to use for the rete...
[ "def", "update_current_retention_level", "(", "self", ",", "value", ")", ":", "# Determine the level at which output files should be kept", "self", ".", "current_retention_level", "=", "value", "try", ":", "global_retention_level", "=", "self", ".", "cp", ".", "get_opt_ta...
46.793103
19.034483
def bbox(self): """BBox""" return self.left, self.top, self.right, self.bottom
[ "def", "bbox", "(", "self", ")", ":", "return", "self", ".", "left", ",", "self", ".", "top", ",", "self", ".", "right", ",", "self", ".", "bottom" ]
30.666667
14.666667
def sink_delete(self, project, sink_name): """API call: delete a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink """ path = "projects/%s/sinks/%s" % (project, s...
[ "def", "sink_delete", "(", "self", ",", "project", ",", "sink_name", ")", ":", "path", "=", "\"projects/%s/sinks/%s\"", "%", "(", "project", ",", "sink_name", ")", "self", ".", "_gapic_api", ".", "delete_sink", "(", "path", ")" ]
32.818182
14.272727
def _parse_lines(self, linesource): ''' Parse lines of text for functions and classes ''' functions = [] classes = [] for line in linesource: if line.startswith('def ') and line.count('('): # exclude private stuff name = self._get_object_name(l...
[ "def", "_parse_lines", "(", "self", ",", "linesource", ")", ":", "functions", "=", "[", "]", "classes", "=", "[", "]", "for", "line", "in", "linesource", ":", "if", "line", ".", "startswith", "(", "'def '", ")", "and", "line", ".", "count", "(", "'('...
36.75
10.55
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._monetary_account_id is not None: return False if self._user_alias_created is not None: return False if self._responses is not ...
[ "def", "is_all_field_none", "(", "self", ")", ":", "if", "self", ".", "_id_", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_monetary_account_id", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_user_alias_created", "is...
20.636364
19.969697
def is_method(func): """Detects if the given callable is a method. In context of pytypes this function is more reliable than plain inspect.ismethod, e.g. it automatically bypasses wrappers from typechecked and override decorators. """ func0 = _actualfunc(func) argNames = getargnames(getargspecs(...
[ "def", "is_method", "(", "func", ")", ":", "func0", "=", "_actualfunc", "(", "func", ")", "argNames", "=", "getargnames", "(", "getargspecs", "(", "func0", ")", ")", "if", "len", "(", "argNames", ")", ">", "0", ":", "if", "argNames", "[", "0", "]", ...
41.047619
15.666667
def combine(self, pubkeys): """Add a number of public keys together.""" assert len(pubkeys) > 0 outpub = ffi.new('secp256k1_pubkey *') for item in pubkeys: assert ffi.typeof(item) is ffi.typeof('secp256k1_pubkey *') res = lib.secp256k1_ec_pubkey_combine( ...
[ "def", "combine", "(", "self", ",", "pubkeys", ")", ":", "assert", "len", "(", "pubkeys", ")", ">", "0", "outpub", "=", "ffi", ".", "new", "(", "'secp256k1_pubkey *'", ")", "for", "item", "in", "pubkeys", ":", "assert", "ffi", ".", "typeof", "(", "it...
32.266667
18.466667
def close(self): """Close the Marquise context, ensuring data is flushed and spool files are closed. This should always be closed explicitly, as there's no guarantees that it will happen when the instance is deleted. """ if self.marquise_ctx is None: self.__d...
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "marquise_ctx", "is", "None", ":", "self", ".", "__debug", "(", "\"Marquise handle is already closed, will do nothing.\"", ")", "# Multiple close() calls are okay.", "return", "self", ".", "__debug", "(", "\"...
39.894737
23.789474
def itervalues(obj): "Get value iterator from dictionary for Python 2 and 3" return iter(obj.values()) if sys.version_info.major == 3 else obj.itervalues()
[ "def", "itervalues", "(", "obj", ")", ":", "return", "iter", "(", "obj", ".", "values", "(", ")", ")", "if", "sys", ".", "version_info", ".", "major", "==", "3", "else", "obj", ".", "itervalues", "(", ")" ]
53.666667
27
def _is_expired_response(self, response): """ Check if the response failed because of an expired access token. """ if response.status_code != 401: return False challenge = response.headers.get('www-authenticate', '') return 'error="invalid_token"' in challenge
[ "def", "_is_expired_response", "(", "self", ",", "response", ")", ":", "if", "response", ".", "status_code", "!=", "401", ":", "return", "False", "challenge", "=", "response", ".", "headers", ".", "get", "(", "'www-authenticate'", ",", "''", ")", "return", ...
39.125
10.625
def make_cost_matrix(profit_matrix, inversion_function): """ Create a cost matrix from a profit matrix by calling 'inversion_function' to invert each value. The inversion function must take one numeric argument (of any type) and return another numeric argument which is presumed to be the cost invers...
[ "def", "make_cost_matrix", "(", "profit_matrix", ",", "inversion_function", ")", ":", "cost_matrix", "=", "[", "]", "for", "row", "in", "profit_matrix", ":", "cost_matrix", ".", "append", "(", "[", "inversion_function", "(", "value", ")", "for", "value", "in",...
30.088235
24.264706
def sround(x, precision=0): """ Round a single number using default non-deterministic generator. @param x: to round. @param precision: decimal places to round. """ sr = StochasticRound(precision=precision) return sr.round(x)
[ "def", "sround", "(", "x", ",", "precision", "=", "0", ")", ":", "sr", "=", "StochasticRound", "(", "precision", "=", "precision", ")", "return", "sr", ".", "round", "(", "x", ")" ]
27.888889
13.888889
def writeObject(self, obj): """ Appends an object to the serialization stream :param obj: A string or a deserialized Java object :raise RuntimeError: Unsupported type """ log_debug("Writing object of type {0}".format(type(obj).__name__)) if isinstance(obj, JavaAr...
[ "def", "writeObject", "(", "self", ",", "obj", ")", ":", "log_debug", "(", "\"Writing object of type {0}\"", ".", "format", "(", "type", "(", "obj", ")", ".", "__name__", ")", ")", "if", "isinstance", "(", "obj", ",", "JavaArray", ")", ":", "# Deserialized...
33.314286
10.514286
def create(self, name, data_type, dim_sizes): """Create a dataset. Args:: name dataset name data_type type of the data, set to one of the SDC.xxx constants; dim_sizes lengths of the dataset dimensions; a one- ...
[ "def", "create", "(", "self", ",", "name", ",", "data_type", ",", "dim_sizes", ")", ":", "# Validate args.", "if", "isinstance", "(", "dim_sizes", ",", "type", "(", "1", ")", ")", ":", "# allow k instead of [k]", "# for a 1-dim arr", "dim_sizes", "=", "[", "...
41.142857
22.02381
def execute_session(self, session_data): '''Execute a session in redis.''' pipe = self.client.pipeline() for sm in session_data: # loop through model sessions meta = sm.meta if sm.structures: self.flush_structure(sm, pipe) delquery = No...
[ "def", "execute_session", "(", "self", ",", "session_data", ")", ":", "pipe", "=", "self", ".", "client", ".", "pipeline", "(", ")", "for", "sm", "in", "session_data", ":", "# loop through model sessions\r", "meta", "=", "sm", ".", "meta", "if", "sm", ".",...
48.025641
12.487179
def bootstrap(nside, rand, nbar, *data): """ This function will bootstrap data based on the sky coverage of rand. It is different from bootstrap in the traditional sense, but for correlation functions it gives the correct answer with less computation. nbar : number density of rand, used to ...
[ "def", "bootstrap", "(", "nside", ",", "rand", ",", "nbar", ",", "*", "data", ")", ":", "def", "split", "(", "data", ",", "indices", ",", "axis", ")", ":", "\"\"\" This function splits array. It fixes the bug\n in numpy that zero length array are improperly h...
30.955056
19.853933
def create_or_edit(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin """Create or edit a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object ...
[ "def", "create_or_edit", "(", "self", ",", "id", ",", "seq", ",", "resource", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "HighlightSchema", "(", "exclude", "=", "(", "'id'", ",", "'seq'", ")", ")", "json", "=", "self", ".", ...
46.2
20.4
def write(self, features=None, outfile=None, format=0, is_leaf_fn=None, format_root_node=False, dist_formatter=None, support_formatter=None, name_formatter=None): """ Returns the newick representation of current node. Several ...
[ "def", "write", "(", "self", ",", "features", "=", "None", ",", "outfile", "=", "None", ",", "format", "=", "0", ",", "is_leaf_fn", "=", "None", ",", "format_root_node", "=", "False", ",", "dist_formatter", "=", "None", ",", "support_formatter", "=", "No...
33.173077
21.557692
def close(self): """关闭与远端的连接. 判断标志位closed是否为False,如果是则关闭,否则不进行操作 """ if self.closed is False: self.clean() try: self.writer.write_eof() except: pass self.writer.close() self.closed = True ...
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "closed", "is", "False", ":", "self", ".", "clean", "(", ")", "try", ":", "self", ".", "writer", ".", "write_eof", "(", ")", "except", ":", "pass", "self", ".", "writer", ".", "close", "("...
23.388889
14.111111
def _surfdens(self,R,z,phi=0.,t=0.): """ NAME: _surfdens PURPOSE: evaluate the surface density for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
[ "def", "_surfdens", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "r", "=", "numpy", ".", "sqrt", "(", "R", "**", "2.", "+", "z", "**", "2.", ")", "Rma", "=", "numpy", ".", "sqrt", "(", "R", "**", ...
32.12
16.36
def check(self): """Add platform specific checks""" if not self.is_valid: raise PolyaxonDeploymentConfigError( 'Deployment type `{}` not supported'.format(self.deployment_type)) check = False if self.is_kubernetes: check = self.check_for_kubernetes...
[ "def", "check", "(", "self", ")", ":", "if", "not", "self", ".", "is_valid", ":", "raise", "PolyaxonDeploymentConfigError", "(", "'Deployment type `{}` not supported'", ".", "format", "(", "self", ".", "deployment_type", ")", ")", "check", "=", "False", "if", ...
40.529412
13.470588
def add_types(graph, phenotypes): # TODO missing expression phenotypes! also basket type somehow :( """ Add disjoint union classes so that it is possible to see the invariants associated with individual phenotypes """ collect = defaultdict(set) def recurse(id_, start, level=0): #print(leve...
[ "def", "add_types", "(", "graph", ",", "phenotypes", ")", ":", "# TODO missing expression phenotypes! also basket type somehow :(", "collect", "=", "defaultdict", "(", "set", ")", "def", "recurse", "(", "id_", ",", "start", ",", "level", "=", "0", ")", ":", "#pr...
42.111111
24.259259
def get(self, fields=[], product_id=None, cid=None, props=None): '''taobao.product.get 获取一个产品的信息 两种方式查看一个产品详细信息: 传入product_id来查询 传入cid和props来查询''' request = TOPRequest('taobao.product.get') if not fields: fields = self.fields request['fields'] = fields ...
[ "def", "get", "(", "self", ",", "fields", "=", "[", "]", ",", "product_id", "=", "None", ",", "cid", "=", "None", ",", "props", "=", "None", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.product.get'", ")", "if", "not", "fields", ":", "fields...
40.846154
14.076923
def grouped(self): """ Yield the matches grouped by their final state in the automaton, i.e. structurally identical patterns only differing in constraints will be yielded together. Each group is yielded as a list of tuples consisting of a pattern and a match substitution. Yields...
[ "def", "grouped", "(", "self", ")", ":", "for", "_", "in", "self", ".", "_match", "(", "self", ".", "matcher", ".", "root", ")", ":", "yield", "list", "(", "self", ".", "_internal_iter", "(", ")", ")" ]
41
23.545455
def fetch_option_taskfileinfos(self, typ, element): """Fetch the options for possible files to load, replace etc for the given element. Thiss will call :meth:`ReftypeInterface.fetch_option_taskfileinfos`. :param typ: the typ of options. E.g. Asset, Alembic, Camera etc :type typ: str ...
[ "def", "fetch_option_taskfileinfos", "(", "self", ",", "typ", ",", "element", ")", ":", "inter", "=", "self", ".", "get_typ_interface", "(", "typ", ")", "return", "inter", ".", "fetch_option_taskfileinfos", "(", "element", ")" ]
48.714286
22.714286
def binary_cross_entropy_with_logits(input_, target, name=PROVIDED, loss_weight=None, per_example_weights=None, per_output_weights=None...
[ "def", "binary_cross_entropy_with_logits", "(", "input_", ",", "target", ",", "name", "=", "PROVIDED", ",", "loss_weight", "=", "None", ",", "per_example_weights", "=", "None", ",", "per_output_weights", "=", "None", ")", ":", "if", "target", "is", "None", ":"...
41.279412
17.75
def plot_sampler_fingerprint( sampler, hyperprior, weights=None, cutoff_weight=None, nbins=None, labels=None, burn=0, chain_mask=None, temp_idx=0, points=None, plot_samples=False, sample_color='k', point_color=None, point_lw=3, title='', rot_x_labels=False, figsize=None ): """Mak...
[ "def", "plot_sampler_fingerprint", "(", "sampler", ",", "hyperprior", ",", "weights", "=", "None", ",", "cutoff_weight", "=", "None", ",", "nbins", "=", "None", ",", "labels", "=", "None", ",", "burn", "=", "0", ",", "chain_mask", "=", "None", ",", "temp...
44.586207
20.235632
def get_section_metrics(cls): """ Get the mapping between metrics and sections in Manuscripts report :return: a dict with the mapping between metrics and sections in Manuscripts report """ # Those metrics are only for Pull Requests # github issues is covered as ITS ...
[ "def", "get_section_metrics", "(", "cls", ")", ":", "# Those metrics are only for Pull Requests", "# github issues is covered as ITS", "return", "{", "\"overview\"", ":", "{", "\"activity_metrics\"", ":", "[", "ClosedPR", ",", "SubmittedPR", "]", ",", "\"author_metrics\"", ...
38.405405
16.135135
def write_pdb(self, mol, filename, name=None, num=None): """ dump the molecule into pdb file with custom residue name and number. """ # ugly hack to get around the openbabel issues with inconsistent # residue labelling. scratch = tempfile.gettempdir() with Scratc...
[ "def", "write_pdb", "(", "self", ",", "mol", ",", "filename", ",", "name", "=", "None", ",", "num", "=", "None", ")", ":", "# ugly hack to get around the openbabel issues with inconsistent", "# residue labelling.", "scratch", "=", "tempfile", ".", "gettempdir", "(",...
35.909091
17.272727
def and_(self, other): """ Creates a new compound query using the <orb.QueryCompound.Op.And> type. :param other <Query> || <orb.QueryCompound> :return <orb.QueryCompound> :sa __and__ :usage |>>> from orb...
[ "def", "and_", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "(", "Query", ",", "QueryCompound", ")", ")", "or", "other", ".", "isNull", "(", ")", ":", "return", "self", ".", "copy", "(", ")", "elif", "not", "...
34.181818
17.545455
def Cpl(self): r'''Liquid-phase heat capacity of the chemical at its current temperature, in units of [J/kg/K]. For calculation of this property at other temperatures, or specifying manually the method used to calculate it, and more - see the object oriented interface :obj:`therm...
[ "def", "Cpl", "(", "self", ")", ":", "Cplm", "=", "self", ".", "HeatCapacityLiquid", "(", "self", ".", "T", ")", "if", "Cplm", ":", "return", "property_molar_to_mass", "(", "Cplm", ",", "self", ".", "MW", ")", "return", "None" ]
41.8
25.64
def _add_nic_to_mapping(self, net, dom, nic): """ Populates the given net spec mapping entry with the nics of the given domain, by the following rules: * If ``net`` is management, 'domain_name': nic_ip * For each interface: 'domain_name-eth#': nic_ip, where # is the ...
[ "def", "_add_nic_to_mapping", "(", "self", ",", "net", ",", "dom", ",", "nic", ")", ":", "dom_name", "=", "dom", "[", "'name'", "]", "idx", "=", "dom", "[", "'nics'", "]", ".", "index", "(", "nic", ")", "name", "=", "'{0}-eth{1}'", ".", "format", "...
36.282609
20.847826
def deepvalidation(self): """Perform deep validation of this element. Raises: :class:`DeepValidationError` """ if self.doc and self.doc.deepvalidation and self.parent.set and self.parent.set[0] != '_': try: self.doc.setdefinitions[self.parent.set]...
[ "def", "deepvalidation", "(", "self", ")", ":", "if", "self", ".", "doc", "and", "self", ".", "doc", ".", "deepvalidation", "and", "self", ".", "parent", ".", "set", "and", "self", ".", "parent", ".", "set", "[", "0", "]", "!=", "'_'", ":", "try", ...
52.166667
27.055556
def create_queue(self, Name, **kwargs): """ Create queue (undocumented API feature). :param Name: Queue name (required) :param kwargs: Optional fields to set (see edit_queue) :returns: ID of new queue or False when create fails :raises BadRequest: When queue already exists ...
[ "def", "create_queue", "(", "self", ",", "Name", ",", "*", "*", "kwargs", ")", ":", "return", "int", "(", "self", ".", "edit_queue", "(", "'new'", ",", "Name", "=", "Name", ",", "*", "*", "kwargs", ")", ")" ]
39.727273
16
def _is_bhyve_hyper(): ''' Returns a bool whether or not this node is a bhyve hypervisor ''' sysctl_cmd = 'sysctl hw.vmm.create' vmm_enabled = False try: stdout = subprocess.Popen(sysctl_cmd, shell=True, stdout=subproces...
[ "def", "_is_bhyve_hyper", "(", ")", ":", "sysctl_cmd", "=", "'sysctl hw.vmm.create'", "vmm_enabled", "=", "False", "try", ":", "stdout", "=", "subprocess", ".", "Popen", "(", "sysctl_cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PI...
33.857143
22.142857
def validate(self, columns=None): """ Validates the current record object to make sure it is ok to commit to the database. If the optional override dictionary is passed in, then it will use the given values vs. the one stored with this record object which can be useful to check to see i...
[ "def", "validate", "(", "self", ",", "columns", "=", "None", ")", ":", "schema", "=", "self", ".", "schema", "(", ")", "if", "not", "columns", ":", "ignore_flags", "=", "orb", ".", "Column", ".", "Flags", ".", "Virtual", "|", "orb", ".", "Column", ...
35.625
21.3125
def get_prep_value(self, value): """ Convert an Enum value into a string for the database """ if value is None: return None if isinstance(value, self.enum): return value.name raise ValueError("Unknown value {value:r} of type {cls}".format( ...
[ "def", "get_prep_value", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "self", ".", "enum", ")", ":", "return", "value", ".", "name", "raise", "ValueError", "(", "\"Unkno...
34.5
10.5
def get_record(self, **kwargs): # type: (str) -> Union[dr.DirectoryRecord, udfmod.UDFFileEntry] ''' Get the directory record for a particular path. Parameters: iso_path - The absolute path on the ISO9660 filesystem to get the record for. rr_path - T...
[ "def", "get_record", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# type: (str) -> Union[dr.DirectoryRecord, udfmod.UDFFileEntry]", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInvalidInput", "(", "'This object is not yet in...
48.95
29.85
def generate_matrices(dim = 40): """ Generates the matrices that positive and negative samples are multiplied with. The matrix for positive samples is randomly drawn from a uniform distribution, with elements in [-1, 1]. The matrix for negative examples is the sum of the positive matrix with a matrix drawn ...
[ "def", "generate_matrices", "(", "dim", "=", "40", ")", ":", "positive", "=", "numpy", ".", "random", ".", "uniform", "(", "-", "1", ",", "1", ",", "(", "dim", ",", "dim", ")", ")", "negative", "=", "positive", "+", "numpy", ".", "random", ".", "...
46.454545
17
def create_window(N, name=None, **kargs): r"""Returns the N-point window given a valid name :param int N: window size :param str name: window name (default is *rectangular*). Valid names are stored in :func:`~spectrum.window.window_names`. :param kargs: optional arguments are: * *beta*...
[ "def", "create_window", "(", "N", ",", "name", "=", "None", ",", "*", "*", "kargs", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'rectangle'", "name", "=", "name", ".", "lower", "(", ")", "assert", "name", "in", "list", "(", "window_nam...
41.424242
21
def compile( self, scss_string=None, scss_file=None, source_files=None, super_selector=None, filename=None, is_sass=None, line_numbers=True, import_static_css=False): """Compile Sass to CSS. Returns a single CSS string. This method is DEPRECATED; see :mod:`scss.comp...
[ "def", "compile", "(", "self", ",", "scss_string", "=", "None", ",", "scss_file", "=", "None", ",", "source_files", "=", "None", ",", "super_selector", "=", "None", ",", "filename", "=", "None", ",", "is_sass", "=", "None", ",", "line_numbers", "=", "Tru...
39.67619
16.590476
def compare_version(version1, version2): """ Compare version strings. :param version1; :param version2; :return: 1 if version1 is after version2; -1 if version1 is before version2; 0 if two versions are the same. """ v1Arr = version1.split(".") v2Arr = version2.split(".") len1 = len(...
[ "def", "compare_version", "(", "version1", ",", "version2", ")", ":", "v1Arr", "=", "version1", ".", "split", "(", "\".\"", ")", "v2Arr", "=", "version2", ".", "split", "(", "\".\"", ")", "len1", "=", "len", "(", "v1Arr", ")", "len2", "=", "len", "("...
27.166667
16.083333
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text_normalized') and self.text_normalized is not None: _dict['text_normalized'] = self.text_normalized return _dict
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'text_normalized'", ")", "and", "self", ".", "text_normalized", "is", "not", "None", ":", "_dict", "[", "'text_normalized'", "]", "=", "self", ".", "t...
39.714286
19
def record(self): # type: () -> bytes ''' Return a string representation of the Directory Record date. Parameters: None. Returns: A string representing this Directory Record Date. ''' if not self._initialized: raise pycdlibexception....
[ "def", "record", "(", "self", ")", ":", "# type: () -> bytes", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'Directory Record Date not initialized'", ")", "return", "struct", ".", "pack", "(", "self",...
35.3125
26.8125
def oaiset_url(self): """Return the OAISet URL for given community. :returns: URL of corresponding OAISet. :rtype: str """ return url_for( 'invenio_oaiserver.response', verb='ListRecords', metadataPrefix='oai_dc', set=self.oaiset_spec, _extern...
[ "def", "oaiset_url", "(", "self", ")", ":", "return", "url_for", "(", "'invenio_oaiserver.response'", ",", "verb", "=", "'ListRecords'", ",", "metadataPrefix", "=", "'oai_dc'", ",", "set", "=", "self", ".", "oaiset_spec", ",", "_external", "=", "True", ")" ]
31.9
14.7
def state_reachable(subsystem): """Return whether a state can be reached according to the network's TPM.""" # If there is a row `r` in the TPM such that all entries of `r - state` are # between -1 and 1, then the given state has a nonzero probability of being # reached from some state. # First we ta...
[ "def", "state_reachable", "(", "subsystem", ")", ":", "# If there is a row `r` in the TPM such that all entries of `r - state` are", "# between -1 and 1, then the given state has a nonzero probability of being", "# reached from some state.", "# First we take the submatrix of the conditioned TPM th...
58
17.916667
def prep_search_string(cls, search_string, match_substrings): """Prepares search string as a proper whoosh search string. :param search_string: The search string which should be prepared. :param match_substrings: ``True`` if you want to match substrings, ``False...
[ "def", "prep_search_string", "(", "cls", ",", "search_string", ",", "match_substrings", ")", ":", "if", "sys", ".", "version", "<", "'3'", "and", "not", "isinstance", "(", "search_string", ",", "unicode", ")", ":", "search_string", "=", "search_string", ".", ...
46.894737
17.631579
def calendars(self): """ Retrieves calendars for this month """ today = datetime.today() first_day, last_day = monthrange(today.year, today.month) from_dt = datetime(today.year, today.month, first_day) to_dt = datetime(today.year, today.month, last_day) pa...
[ "def", "calendars", "(", "self", ")", ":", "today", "=", "datetime", ".", "today", "(", ")", "first_day", ",", "last_day", "=", "monthrange", "(", "today", ".", "year", ",", "today", ".", "month", ")", "from_dt", "=", "datetime", "(", "today", ".", "...
37.833333
12.055556
def dispatch_event(self,event_type,*args): """ Internal event handling method. This method extends the behavior inherited from :py:meth:`pyglet.window.Window.dispatch_event()` by calling the various :py:meth:`handleEvent()` methods. By default, :py:meth:`Peng.handleEven...
[ "def", "dispatch_event", "(", "self", ",", "event_type", ",", "*", "args", ")", ":", "super", "(", "PengWindow", ",", "self", ")", ".", "dispatch_event", "(", "event_type", ",", "*", "args", ")", "try", ":", "p", "=", "self", ".", "peng", "m", "=", ...
44.043478
24.043478
def _delivery_report(err, msg): ''' Called once for each message produced to indicate delivery result. Triggered by poll() or flush(). ''' if err is not None: log.error('Message delivery failed: %s', err) else: log.debug('Message delivered to %s [%s]', msg.topic(), msg.partition())
[ "def", "_delivery_report", "(", "err", ",", "msg", ")", ":", "if", "err", "is", "not", "None", ":", "log", ".", "error", "(", "'Message delivery failed: %s'", ",", "err", ")", "else", ":", "log", ".", "debug", "(", "'Message delivered to %s [%s]'", ",", "m...
44.571429
20.857143
def on_draw(self, e): """Draw all visuals.""" gloo.clear() for visual in self.visuals: logger.log(5, "Draw visual `%s`.", visual) visual.on_draw()
[ "def", "on_draw", "(", "self", ",", "e", ")", ":", "gloo", ".", "clear", "(", ")", "for", "visual", "in", "self", ".", "visuals", ":", "logger", ".", "log", "(", "5", ",", "\"Draw visual `%s`.\"", ",", "visual", ")", "visual", ".", "on_draw", "(", ...
31.5
11.666667
def get_file(self, latitude, longitude): """ If the file can't be found -- it will be retrieved from the server. """ file_name = self.get_file_name(latitude, longitude) if not file_name: return None if (file_name in self.files): return self.files...
[ "def", "get_file", "(", "self", ",", "latitude", ",", "longitude", ")", ":", "file_name", "=", "self", ".", "get_file_name", "(", "latitude", ",", "longitude", ")", "if", "not", "file_name", ":", "return", "None", "if", "(", "file_name", "in", "self", "....
29.56
18.92
def str_extract(arr, pat, flags=0, expand=True): r""" Extract capture groups in the regex `pat` as columns in a DataFrame. For each subject string in the Series, extract groups from the first match of regular expression `pat`. Parameters ---------- pat : str Regular expression patt...
[ "def", "str_extract", "(", "arr", ",", "pat", ",", "flags", "=", "0", ",", "expand", "=", "True", ")", ":", "if", "not", "isinstance", "(", "expand", ",", "bool", ")", ":", "raise", "ValueError", "(", "\"expand must be True or False\"", ")", "if", "expan...
29.722222
24.222222
def readStoredSms(self, index, memory=None): """ Reads and returns the SMS message at the specified index :param index: The index of the SMS message in the specified memory :type index: int :param memory: The memory type to read from. If None, use the current default SMS read me...
[ "def", "readStoredSms", "(", "self", ",", "index", ",", "memory", "=", "None", ")", ":", "# Switch to the correct memory type if required", "self", ".", "_setSmsMemory", "(", "readDelete", "=", "memory", ")", "msgData", "=", "self", ".", "write", "(", "'AT+CMGR=...
56.169811
28.679245
def filter_pypi(self, entry): """Show only usefull packages""" for package in self.packages: if entry.title.lower().startswith(package): return entry
[ "def", "filter_pypi", "(", "self", ",", "entry", ")", ":", "for", "package", "in", "self", ".", "packages", ":", "if", "entry", ".", "title", ".", "lower", "(", ")", ".", "startswith", "(", "package", ")", ":", "return", "entry" ]
37.8
8.2
def jacobi(a, b): '''Calculates the value of the Jacobi symbol (a/b) where both a and b are positive integers, and b is odd :returns: -1, 0 or 1 ''' assert a > 0 assert b > 0 if a == 0: return 0 result = 1 while a > 1: if a & 1: if ((a-1)*(b-1) >> 2) & ...
[ "def", "jacobi", "(", "a", ",", "b", ")", ":", "assert", "a", ">", "0", "assert", "b", ">", "0", "if", "a", "==", "0", ":", "return", "0", "result", "=", "1", "while", "a", ">", "1", ":", "if", "a", "&", "1", ":", "if", "(", "(", "a", "...
20.68
22.28
def generate_token_string(self, action=None): """Generate a hash of the given token contents that can be verified. :param action: A string representing the action that the generated hash is valid for. This string is usually a URL. :returns: A string containin...
[ "def", "generate_token_string", "(", "self", ",", "action", "=", "None", ")", ":", "digest_maker", "=", "self", ".", "_digest_maker", "(", ")", "digest_maker", ".", "update", "(", "self", ".", "user_id", ")", "digest_maker", ".", "update", "(", "self", "."...
43.608696
15.826087
def add_days(self, *days): """Add one or several days to the program. Parameters ---------- *days Unpacked tuple containing :py:class:`streprogen.Day` instances. Examples ------- >>> program = Program('My training program') ...
[ "def", "add_days", "(", "self", ",", "*", "days", ")", ":", "for", "day", "in", "list", "(", "days", ")", ":", "self", ".", "days", ".", "append", "(", "day", ")" ]
25.388889
15.888889
def get_html(self): """Bibliographic entry in html format.""" # Author links au_link = ('<a href="https://www.scopus.com/authid/detail.url' '?origin=AuthorProfile&authorId={0}">{1}</a>') if len(self.authors) > 1: authors = u', '.join([au_link.format(a.auid,...
[ "def", "get_html", "(", "self", ")", ":", "# Author links", "au_link", "=", "(", "'<a href=\"https://www.scopus.com/authid/detail.url'", "'?origin=AuthorProfile&authorId={0}\">{1}</a>'", ")", "if", "len", "(", "self", ".", "authors", ")", ">", "1", ":", "authors", "="...
51
21.323529
def asdim(dimension): """Convert the input to a Dimension. Args: dimension: tuple, dict or string type to convert to Dimension Returns: A Dimension object constructed from the dimension spec. No copy is performed if the input is already a Dimension. """ if isinstance(dimens...
[ "def", "asdim", "(", "dimension", ")", ":", "if", "isinstance", "(", "dimension", ",", "Dimension", ")", ":", "return", "dimension", "elif", "isinstance", "(", "dimension", ",", "(", "tuple", ",", "dict", ",", "basestring", ")", ")", ":", "return", "Dime...
36.555556
21.722222
def handle(self, *args, **kwargs): """Run the executor listener. This method never returns.""" listener = ExecutorListener(redis_params=getattr(settings, 'FLOW_MANAGER', {}).get('REDIS_CONNECTION', {})) def _killer(signum, frame): """Kill the listener on receipt of a signal.""" ...
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "listener", "=", "ExecutorListener", "(", "redis_params", "=", "getattr", "(", "settings", ",", "'FLOW_MANAGER'", ",", "{", "}", ")", ".", "get", "(", "'REDIS_CONNECTION'"...
35.55
15.05
def get_what_txt(self): """ Overrides the base behaviour defined in ValidationError in order to add details about the function. :return: """ return 'input [{var}] for function [{func}]'.format(var=self.get_variable_str(), ...
[ "def", "get_what_txt", "(", "self", ")", ":", "return", "'input [{var}] for function [{func}]'", ".", "format", "(", "var", "=", "self", ".", "get_variable_str", "(", ")", ",", "func", "=", "self", ".", "validator", ".", "get_validated_func_display_name", "(", "...
52.857143
32.857143
def _brief_print_list(lst, limit=7): """Print at most `limit` elements of list.""" lst = list(lst) if len(lst) > limit: return _brief_print_list(lst[:limit//2], limit) + ', ..., ' + \ _brief_print_list(lst[-limit//2:], limit) return ', '.join(["'%s'"%str(i) for i in lst])
[ "def", "_brief_print_list", "(", "lst", ",", "limit", "=", "7", ")", ":", "lst", "=", "list", "(", "lst", ")", "if", "len", "(", "lst", ")", ">", "limit", ":", "return", "_brief_print_list", "(", "lst", "[", ":", "limit", "//", "2", "]", ",", "li...
43.142857
13.571429
def stats(self): """ Gets performance statistics and server information """ status, _, body = self._request('GET', self.stats_path(), {'Accept': 'application/json'}) if status == 200: return json.loads(bytes_to_str(body)) ...
[ "def", "stats", "(", "self", ")", ":", "status", ",", "_", ",", "body", "=", "self", ".", "_request", "(", "'GET'", ",", "self", ".", "stats_path", "(", ")", ",", "{", "'Accept'", ":", "'application/json'", "}", ")", "if", "status", "==", "200", ":...
34.2
16.6
def dump(self, force=False): """ Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value ...
[ "def", "dump", "(", "self", ",", "force", "=", "False", ")", ":", "if", "force", ":", "if", "self", ".", "_parsed", "is", "not", "None", ":", "native", "=", "self", ".", "parsed", ".", "dump", "(", "force", "=", "force", ")", "else", ":", "native...
27.285714
18.142857
def discard_unused_messages(self, ending_tier): """ Delete messages from errors, warnings, and notices whose tier is greater than the ending tier. """ stacks = [self.errors, self.warnings, self.notices] for stack in stacks: for message in stack: ...
[ "def", "discard_unused_messages", "(", "self", ",", "ending_tier", ")", ":", "stacks", "=", "[", "self", ".", "errors", ",", "self", ".", "warnings", ",", "self", ".", "notices", "]", "for", "stack", "in", "stacks", ":", "for", "message", "in", "stack", ...
35.272727
11.818182
def get_param_bounds_from_config(cp, section, tag, param): """Gets bounds for the given parameter from a section in a config file. Minimum and maximum values for bounds are specified by adding `min-{param}` and `max-{param}` options, where `{param}` is the name of the parameter. The types of boundary (...
[ "def", "get_param_bounds_from_config", "(", "cp", ",", "section", ",", "tag", ",", "param", ")", ":", "try", ":", "minbnd", "=", "float", "(", "cp", ".", "get_opt_tag", "(", "section", ",", "'min-'", "+", "param", ",", "tag", ")", ")", "except", "Error...
34.604651
22.790698
def _set_logger(self, name=None): """Adds a logger with a given `name`. If no name is given, name is constructed as `type(self).__name__`. """ if name is None: cls = self.__class__ name = '%s.%s' % (cls.__module__, cls.__name__) self._logger = lo...
[ "def", "_set_logger", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "cls", "=", "self", ".", "__class__", "name", "=", "'%s.%s'", "%", "(", "cls", ".", "__module__", ",", "cls", ".", "__name__", ")", "self", ".",...
30.090909
14.272727
def get_dict_for_class(self, class_name, state=None, base_name='View'): """The style dict for a given class and state. This collects the style attributes from parent classes and the class of the given object and gives precedence to values thereof to the children. The state attr...
[ "def", "get_dict_for_class", "(", "self", ",", "class_name", ",", "state", "=", "None", ",", "base_name", "=", "'View'", ")", ":", "classes", "=", "[", "]", "klass", "=", "class_name", "while", "True", ":", "classes", ".", "append", "(", "klass", ")", ...
30.490196
21.294118
def wordcount(text): '''Returns the count of the words in a file.''' bannedwords = read_file('stopwords.txt') wordcount = {} separated = separate(text) for word in separated: if word not in bannedwords: if not wordcount.has_key(word): wordcount[word] = 1 ...
[ "def", "wordcount", "(", "text", ")", ":", "bannedwords", "=", "read_file", "(", "'stopwords.txt'", ")", "wordcount", "=", "{", "}", "separated", "=", "separate", "(", "text", ")", "for", "word", "in", "separated", ":", "if", "word", "not", "in", "banned...
31.25
11.75
def list(self, **kwargs): """Retrieve a list of objects. Args: all (bool): If True, return all the items, without pagination per_page (int): Number of items to retrieve per request page (int): ID of the page to return (starts with page 1) as_list (bool): ...
[ "def", "list", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Duplicate data to avoid messing with what the user sent us", "data", "=", "kwargs", ".", "copy", "(", ")", "if", "self", ".", "gitlab", ".", "per_page", ":", "data", ".", "setdefault", "(", "'...
40.025
23.2
def getclasstree(classes, unique=0): """Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If...
[ "def", "getclasstree", "(", "classes", ",", "unique", "=", "0", ")", ":", "children", "=", "{", "}", "roots", "=", "[", "]", "for", "c", "in", "classes", ":", "if", "c", ".", "__bases__", ":", "for", "parent", "in", "c", ".", "__bases__", ":", "i...
43.125
15.291667
def get_size_in_bytes(self, handle): """Return the size in bytes.""" fpath = self._fpath_from_handle(handle) return os.stat(fpath).st_size
[ "def", "get_size_in_bytes", "(", "self", ",", "handle", ")", ":", "fpath", "=", "self", ".", "_fpath_from_handle", "(", "handle", ")", "return", "os", ".", "stat", "(", "fpath", ")", ".", "st_size" ]
39.75
3.5
def create_or_update_group_alias(self, name, alias_id=None, mount_accessor=None, canonical_id=None, mount_point=DEFAULT_MOUNT_POINT): """Creates or update a group alias. Supported methods: POST: /{mount_point}/group-alias. Produces: 200 application/json :param alias_id: ID of the g...
[ "def", "create_or_update_group_alias", "(", "self", ",", "name", ",", "alias_id", "=", "None", ",", "mount_accessor", "=", "None", ",", "canonical_id", "=", "None", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'name'", ":", ...
42.09375
19.53125
def identify(mw_uri, consumer_token, access_token, leeway=10.0, user_agent=defaults.USER_AGENT): """ Gather identifying information about a user via an authorized token. :Parameters: mw_uri : `str` The base URI of the MediaWiki installation. Note that the URI s...
[ "def", "identify", "(", "mw_uri", ",", "consumer_token", ",", "access_token", ",", "leeway", "=", "10.0", ",", "user_agent", "=", "defaults", ".", "USER_AGENT", ")", ":", "# Construct an OAuth auth", "auth", "=", "OAuth1", "(", "consumer_token", ".", "key", ",...
38.209302
17.72093
def load(prefix, epoch, ctx=None, **kwargs): """Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int epoch number of model we would like to load. ctx : Context or list of Context, optional ...
[ "def", "load", "(", "prefix", ",", "epoch", ",", "ctx", "=", "None", ",", "*", "*", "kwargs", ")", ":", "symbol", ",", "arg_params", ",", "aux_params", "=", "load_checkpoint", "(", "prefix", ",", "epoch", ")", "return", "FeedForward", "(", "symbol", ",...
35.137931
20.310345
def get_ip(): """ Get the default local IP address. From: https://stackoverflow.com/a/28950776 """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('10.255.255.255', 1)) ip = s.getsockname()[0] except (socket.error, IndexError): ip = '127.0.0.1' ...
[ "def", "get_ip", "(", ")", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "try", ":", "s", ".", "connect", "(", "(", "'10.255.255.255'", ",", "1", ")", ")", "ip", "=", "s", ".", "gets...
21.8125
16.8125
def execute(handlers): ''' Run the command :return: ''' # verify if the environment variables are correctly set check_environment() # create the argument parser parser = create_parser(handlers) # if no argument is provided, print help and exit if len(sys.argv[1:]) == 0: parser.print_help() ...
[ "def", "execute", "(", "handlers", ")", ":", "# verify if the environment variables are correctly set", "check_environment", "(", ")", "# create the argument parser", "parser", "=", "create_parser", "(", "handlers", ")", "# if no argument is provided, print help and exit", "if", ...
26
22.904762
def plot_brillouin(self): """ plot the Brillouin zone """ # get labels and lines labels = {} for k in self._bs.kpoints: if k.label: labels[k.label] = k.frac_coords lines = [] for b in self._bs.branches: lines.appen...
[ "def", "plot_brillouin", "(", "self", ")", ":", "# get labels and lines", "labels", "=", "{", "}", "for", "k", "in", "self", ".", "_bs", ".", "kpoints", ":", "if", "k", ".", "label", ":", "labels", "[", "k", ".", "label", "]", "=", "k", ".", "frac_...
29.764706
19.647059
def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be ...
[ "def", "_remove_tags", "(", "conn", ",", "load_balancer_names", ",", "tags", ")", ":", "params", "=", "{", "}", "conn", ".", "build_list_params", "(", "params", ",", "load_balancer_names", ",", "'LoadBalancerNames.member.%d'", ")", "conn", ".", "build_list_params"...
35.647059
20.470588
def rotation_matrix(d): """ Calculates a rotation matrix given a vector d. The direction of d corresponds to the rotation axis. The length of d corresponds to the sin of the angle of rotation. Variant of: http://mail.scipy.org/pipermail/numpy-discussion/2009-March/040806.html """ sin_angle ...
[ "def", "rotation_matrix", "(", "d", ")", ":", "sin_angle", "=", "np", ".", "linalg", ".", "norm", "(", "d", ")", "if", "sin_angle", "==", "0", ":", "return", "np", ".", "identity", "(", "3", ")", "d", "/=", "sin_angle", "eye", "=", "np", ".", "ey...
29.434783
22.130435
def merge(self, items): """ Merge the collection with the given items. :param items: The items to merge :type items: list or Collection :rtype: Collection """ if isinstance(items, BaseCollection): items = items.all() if not isinstance(items,...
[ "def", "merge", "(", "self", ",", "items", ")", ":", "if", "isinstance", "(", "items", ",", "BaseCollection", ")", ":", "items", "=", "items", ".", "all", "(", ")", "if", "not", "isinstance", "(", "items", ",", "list", ")", ":", "raise", "ValueError"...
23.777778
17.555556
def get_summary_dict(self, print_subelectrodes=True): """ Args: print_subelectrodes: Also print data on all the possible subelectrodes Returns: a summary of this electrode"s properties in dictionary format """ d = {} framework_com...
[ "def", "get_summary_dict", "(", "self", ",", "print_subelectrodes", "=", "True", ")", ":", "d", "=", "{", "}", "framework_comp", "=", "Composition", "(", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "_composition", ".", "items", "(", ...
43.142857
16.214286
def _tag_extent(self, data, start): """ Finds the extent of a tag, accounting for option quoting and new tags starting before the current one closes. Returns (found_close, end_pos) where valid is False if another tag started before this one closed. """ in_quote = False qu...
[ "def", "_tag_extent", "(", "self", ",", "data", ",", "start", ")", ":", "in_quote", "=", "False", "quotable", "=", "False", "lto", "=", "len", "(", "self", ".", "tag_opener", ")", "ltc", "=", "len", "(", "self", ".", "tag_closer", ")", "for", "i", ...
40.5
14.416667
def gps_velocity_old(GPS_RAW_INT): '''return GPS velocity vector''' return Vector3(GPS_RAW_INT.vel*0.01*cos(radians(GPS_RAW_INT.cog*0.01)), GPS_RAW_INT.vel*0.01*sin(radians(GPS_RAW_INT.cog*0.01)), 0)
[ "def", "gps_velocity_old", "(", "GPS_RAW_INT", ")", ":", "return", "Vector3", "(", "GPS_RAW_INT", ".", "vel", "*", "0.01", "*", "cos", "(", "radians", "(", "GPS_RAW_INT", ".", "cog", "*", "0.01", ")", ")", ",", "GPS_RAW_INT", ".", "vel", "*", "0.01", "...
55.75
20.75
def get_geoms_for_bounds(self, bounds): """ Helper method to get geometries within a certain bounds (as WKT). Returns GeoJSON (loaded as a list of python dictionaries). """ poly = ogr.CreateGeometryFromWkt(bounds) self._layer.SetSpatialFilter(poly) poly.Destroy()...
[ "def", "get_geoms_for_bounds", "(", "self", ",", "bounds", ")", ":", "poly", "=", "ogr", ".", "CreateGeometryFromWkt", "(", "bounds", ")", "self", ".", "_layer", ".", "SetSpatialFilter", "(", "poly", ")", "poly", ".", "Destroy", "(", ")", "return", "[", ...
35.909091
19.181818
def combine(cls, date, time): "Construct a datetime from a given date and a given time." if not isinstance(date, _date_class): raise TypeError("date argument must be a date instance") if not isinstance(time, _time_class): raise TypeError("time argument must be a time inst...
[ "def", "combine", "(", "cls", ",", "date", ",", "time", ")", ":", "if", "not", "isinstance", "(", "date", ",", "_date_class", ")", ":", "raise", "TypeError", "(", "\"date argument must be a date instance\"", ")", "if", "not", "isinstance", "(", "time", ",", ...
52.888889
17.333333
def on_train_begin(self, **kwargs:Any)->None: "Initializes the best value." self.best = float('inf') if self.operator == np.less else -float('inf')
[ "def", "on_train_begin", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "best", "=", "float", "(", "'inf'", ")", "if", "self", ".", "operator", "==", "np", ".", "less", "else", "-", "float", "(", "'inf'", "...
53.666667
15.666667
def submit_error(url, user, project, area, description, extra=None, default_message=None): """Celery task for submitting errors asynchronously. :param url: string URL for bugzscout :param user: string fogbugz user to designate when submitting via bugzscout :param proje...
[ "def", "submit_error", "(", "url", ",", "user", ",", "project", ",", "area", ",", "description", ",", "extra", "=", "None", ",", "default_message", "=", "None", ")", ":", "LOG", ".", "debug", "(", "'Creating new BugzScout instance.'", ")", "client", "=", "...
42.2
15.05
def zfs(): ''' Provide grains for zfs/zpool ''' grains = {} grains['zfs_support'] = __utils__['zfs.is_supported']() grains['zfs_feature_flags'] = __utils__['zfs.has_feature_flags']() if grains['zfs_support']: grains = salt.utils.dictupdate.update(grains, _zfs_pool_data(), merge_lists...
[ "def", "zfs", "(", ")", ":", "grains", "=", "{", "}", "grains", "[", "'zfs_support'", "]", "=", "__utils__", "[", "'zfs.is_supported'", "]", "(", ")", "grains", "[", "'zfs_feature_flags'", "]", "=", "__utils__", "[", "'zfs.has_feature_flags'", "]", "(", ")...
30.454545
27.363636
def color(ip, mac, hue, saturation, value): """Switch the bulb on with the given color.""" bulb = MyStromBulb(ip, mac) bulb.set_color_hsv(hue, saturation, value)
[ "def", "color", "(", "ip", ",", "mac", ",", "hue", ",", "saturation", ",", "value", ")", ":", "bulb", "=", "MyStromBulb", "(", "ip", ",", "mac", ")", "bulb", ".", "set_color_hsv", "(", "hue", ",", "saturation", ",", "value", ")" ]
42.5
4.5
def construct_chunk(cls, chunk_type, payload, encoding='utf-8'): """Construct and return a single chunk.""" if isinstance(payload, str): payload = payload.encode(encoding) elif not isinstance(payload, bytes): raise TypeError('cannot encode type: {}'.format(type(payload))) header = struct.pa...
[ "def", "construct_chunk", "(", "cls", ",", "chunk_type", ",", "payload", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "payload", ",", "str", ")", ":", "payload", "=", "payload", ".", "encode", "(", "encoding", ")", "elif", "not", ...
42.666667
15.555556
def get_es(self, default_builder=get_es): """Returns the elasticsearch Elasticsearch object to use. This uses the django get_es builder by default which takes into account settings in ``settings.py``. """ return super(S, self).get_es(default_builder=default_builder)
[ "def", "get_es", "(", "self", ",", "default_builder", "=", "get_es", ")", ":", "return", "super", "(", "S", ",", "self", ")", ".", "get_es", "(", "default_builder", "=", "default_builder", ")" ]
37.625
18.125
def clear_header(self, name: str) -> None: """Clears an outgoing header, undoing a previous `set_header` call. Note that this method does not apply to multi-valued headers set by `add_header`. """ if name in self._headers: del self._headers[name]
[ "def", "clear_header", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "if", "name", "in", "self", ".", "_headers", ":", "del", "self", ".", "_headers", "[", "name", "]" ]
36.5
11.75
def close_connection(self, connection_id): """Closes a connection. :param connection_id: ID of the connection to close. """ request = requests_pb2.CloseConnectionRequest() request.connection_id = connection_id self._apply(request)
[ "def", "close_connection", "(", "self", ",", "connection_id", ")", ":", "request", "=", "requests_pb2", ".", "CloseConnectionRequest", "(", ")", "request", ".", "connection_id", "=", "connection_id", "self", ".", "_apply", "(", "request", ")" ]
31.444444
9.666667