text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def close(self): """ Close the ACE process and return the process's exit code. """ self.run_info['end'] = datetime.now() self._p.stdin.close() for line in self._p.stdout: if line.startswith('NOTE: tsdb run:'): self._read_run_info(line) ...
[ "def", "close", "(", "self", ")", ":", "self", ".", "run_info", "[", "'end'", "]", "=", "datetime", ".", "now", "(", ")", "self", ".", "_p", ".", "stdin", ".", "close", "(", ")", "for", "line", "in", "self", ".", "_p", ".", "stdout", ":", "if",...
34
0.004405
def findReference(self, name, cls=QtGui.QWidget): """ Looks up a reference from the widget based on its object name. :param name | <str> cls | <subclass of QtGui.QObject> :return <QtGui.QObject> || None """ ref_widg...
[ "def", "findReference", "(", "self", ",", "name", ",", "cls", "=", "QtGui", ".", "QWidget", ")", ":", "ref_widget", "=", "self", ".", "_referenceWidget", "if", "not", "ref_widget", ":", "return", "None", "if", "ref_widget", ".", "objectName", "(", ")", "...
32.375
0.009381
def get_solution(self) -> Tuple[str, str]: """ Returns the solution of the BV algorithm :return: a tuple of string corresponding to the dot-product partner vector and the bias term :rtype: Tuple[String, String] """ if self.solution is None: raise AssertionErr...
[ "def", "get_solution", "(", "self", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "if", "self", ".", "solution", "is", "None", ":", "raise", "AssertionError", "(", "\"You need to `run` this algorithm first\"", ")", "return", "self", ".", "solution" ]
38.4
0.007634
def cacheable_object(cls): """Decorator to add a reset() method that clears data cached by the @resettable_cached_property decorator. Technically this could be a mixin... """ def reset(self): if hasattr(self, '_resettable_cached_properties'): self._resettable_cached_properties =...
[ "def", "cacheable_object", "(", "cls", ")", ":", "def", "reset", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_resettable_cached_properties'", ")", ":", "self", ".", "_resettable_cached_properties", "=", "{", "}", "cls", ".", "reset", "=", "...
29.166667
0.00277
def _get_inferred_data_res(column, age): """ Calculate Resolution and m/m/m/m for column values. :param dict column: Column data :param list age: Age values :return dict column: Column data - modified """ try: with warnings.catch_warnings(): warnings.simplefilter("ignore"...
[ "def", "_get_inferred_data_res", "(", "column", ",", "age", ")", ":", "try", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "# Get the values for this column", "values", "=", "column", "[",...
42.513514
0.002486
def readTypedObject(self): """ Reads an aliased ActionScript object from the stream and attempts to 'cast' it into a python class. @see: L{pyamf.register_class} """ class_alias = self.readString() try: alias = self.context.getClassAlias(class_alias) ...
[ "def", "readTypedObject", "(", "self", ")", ":", "class_alias", "=", "self", ".", "readString", "(", ")", "try", ":", "alias", "=", "self", ".", "context", ".", "getClassAlias", "(", "class_alias", ")", "except", "pyamf", ".", "UnknownClassAlias", ":", "if...
27.25
0.002954
def get_composition_repository_assignment_session(self, proxy): """Gets the session for assigning composition to repository mappings. arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.CompositionRepositoryAssignmentSession) - a CompositionRepositoryAssig...
[ "def", "get_composition_repository_assignment_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_composition_repository_assignment", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "import", "sessions", "...
40.962963
0.00265
def comparison_image_list(self): """ returns a list of possible comparison images for the current cutout. Will query CADC to create the list when first called. @rtype: Table """ if self._comparison_image_list is not None: return self._comparison_image_list ...
[ "def", "comparison_image_list", "(", "self", ")", ":", "if", "self", ".", "_comparison_image_list", "is", "not", "None", ":", "return", "self", ".", "_comparison_image_list", "ref_ra", "=", "self", ".", "reading", ".", "ra", "*", "units", ".", "degree", "ref...
53.568627
0.005751
def play(self, call_params): """REST Play something on a Call Helper """ path = '/' + self.api_version + '/Play/' method = 'POST' return self.request(path, method, call_params)
[ "def", "play", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/Play/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")" ]
35.166667
0.009259
def trace_graph(graph): """Build a collection of "traces" for each package. A trace is a list of names that eventually leads to the package. For example, if A and B are root dependencies, A depends on C and D, B depends on C, and C depends on D, the return value would be like:: { N...
[ "def", "trace_graph", "(", "graph", ")", ":", "result", "=", "{", "None", ":", "[", "]", "}", "for", "vertex", "in", "graph", ":", "result", "[", "vertex", "]", "=", "[", "]", "for", "root", "in", "graph", ".", "iter_children", "(", "None", ")", ...
32.652174
0.001294
def remove_elements(target, indices): """Remove multiple elements from a list and return result. This implementation is faster than the alternative below. Also note the creation of a new list to avoid altering the original. We don't have any current use for the original intact list, but may in the f...
[ "def", "remove_elements", "(", "target", ",", "indices", ")", ":", "copied", "=", "list", "(", "target", ")", "for", "index", "in", "reversed", "(", "indices", ")", ":", "del", "copied", "[", "index", "]", "return", "copied" ]
35.666667
0.002278
def trim(self, n='all', x=True, y=True): """ This will set xmin and xmax based on the current zoom-level of the figures. n='all' Which figure to use for setting xmin and xmax. 'all' means all figures. You may also specify a list. x=True Trim the x-ra...
[ "def", "trim", "(", "self", ",", "n", "=", "'all'", ",", "x", "=", "True", ",", "y", "=", "True", ")", ":", "if", "len", "(", "self", ".", "_set_xdata", ")", "==", "0", "or", "len", "(", "self", ".", "_set_ydata", ")", "==", "0", ":", "self",...
34.526316
0.009637
def _findlinestarts(code): """Find the offsets in a byte code which are start of lines in the source Generate pairs offset,lineno as described in Python/compile.c This is a modified version of dis.findlinestarts, which allows multiplelinestarts with the same line number""" lineno...
[ "def", "_findlinestarts", "(", "code", ")", ":", "lineno", "=", "code", ".", "co_firstlineno", "addr", "=", "0", "for", "byte_incr", ",", "line_incr", "in", "zip", "(", "code", ".", "co_lnotab", "[", "0", ":", ":", "2", "]", ",", "code", ".", "co_lno...
45.076923
0.008361
def helmholtz_free_energy(self, t, structure=None): """ Phonon contribution to the Helmholtz free energy at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/mol-c. A mol-c is the abbreviation of a mole-cell, that is, the number ...
[ "def", "helmholtz_free_energy", "(", "self", ",", "t", ",", "structure", "=", "None", ")", ":", "if", "t", "==", "0", ":", "return", "self", ".", "zero_point_energy", "(", "structure", "=", "structure", ")", "freqs", "=", "self", ".", "_positive_frequencie...
40.818182
0.006526
def update_payload_in_draft_for_edit_extension(self, upload_stream, publisher_name, extension_name, draft_id, file_name=None, **kwargs): """UpdatePayloadInDraftForEditExtension. [Preview API] :param object upload_stream: Stream to upload :param str publisher_name: :param str exte...
[ "def", "update_payload_in_draft_for_edit_extension", "(", "self", ",", "upload_stream", ",", "publisher_name", ",", "extension_name", ",", "draft_id", ",", "file_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "route_values", "=", "{", "}", "if", "publish...
54.068966
0.005639
def search_raw(self, query, indices=None, doc_types=None, headers=None, **query_params): """Execute a search against one or more indices to get the search hits. `query` must be a Search object, a Query object, or a custom dictionary of search parameters using the query DSL to be passed ...
[ "def", "search_raw", "(", "self", ",", "query", ",", "indices", "=", "None", ",", "doc_types", "=", "None", ",", "headers", "=", "None", ",", "*", "*", "query_params", ")", ":", "from", ".", "query", "import", "Search", ",", "Query", "if", "isinstance"...
44.375
0.005517
def delete(self): """ Remove object :return: None """ logging.debug('Remove {x.__class__.__name__} [{x.name}]'.format(x=self)) request_url = self._artifactory.drive + '/api/{uri}/{x.name}'.format(uri=self._uri, x=self) r = self._session.delete( request...
[ "def", "delete", "(", "self", ")", ":", "logging", ".", "debug", "(", "'Remove {x.__class__.__name__} [{x.name}]'", ".", "format", "(", "x", "=", "self", ")", ")", "request_url", "=", "self", ".", "_artifactory", ".", "drive", "+", "'/api/{uri}/{x.name}'", "."...
30.923077
0.009662
def _render(self, request, formencode=False, realm=None): """Render a signed request according to signature type Returns a 3-tuple containing the request URI, headers, and body. If the formencode argument is True and the body contains parameters, it is escaped and returned as a valid f...
[ "def", "_render", "(", "self", ",", "request", ",", "formencode", "=", "False", ",", "realm", "=", "None", ")", ":", "# TODO what if there are body params on a header-type auth?", "# TODO what if there are query params on a body-type auth?", "uri", ",", "headers", ",", "b...
51.527778
0.003175
def buscar_idtrafficreturn_opcvip(self, nome_opcao_txt): """Search id of Option VIP when tipo_opcao = 'Retorno de trafego' ​​ :return: Dictionary with the following structure: :: {‘trafficreturn_opt’: ‘trafficreturn_opt’: <'id'>} :raise InvalidParameterError: Environment ...
[ "def", "buscar_idtrafficreturn_opcvip", "(", "self", ",", "nome_opcao_txt", ")", ":", "trafficreturn_map", "=", "dict", "(", ")", "trafficreturn_map", "[", "'trafficreturn'", "]", "=", "nome_opcao_txt", "url", "=", "'optionvip/trafficreturn/search/'", "code", ",", "xm...
38.708333
0.007353
def get_unspent_outputs(self, address): """ Get unspent outputs at the address :param address: :return: """ logging.debug('get_unspent_outputs for address=%s', address) spendables = self.spendables_for_address(bitcoin_address=address) if spendables: ...
[ "def", "get_unspent_outputs", "(", "self", ",", "address", ")", ":", "logging", ".", "debug", "(", "'get_unspent_outputs for address=%s'", ",", "address", ")", "spendables", "=", "self", ".", "spendables_for_address", "(", "bitcoin_address", "=", "address", ")", "...
35.909091
0.004938
def addMonths(date, months): """ Returns the new date based on the inputted months. :param date | <datetime.date> months | <int> :return <datetime.date> """ # map from Qt information if type(date).__name__ in ('QDate', 'QDateTime', 'QTime'): date ...
[ "def", "addMonths", "(", "date", ",", "months", ")", ":", "# map from Qt information", "if", "type", "(", "date", ")", ".", "__name__", "in", "(", "'QDate'", ",", "'QDateTime'", ",", "'QTime'", ")", ":", "date", "=", "date", ".", "toPython", "(", ")", ...
23.457143
0.003509
def proxied_get(self, *args, **kwargs): """ Perform the query and returns a single object matching the given keyword arguments. This customizes the queryset to return an instance of ``ProxyDataSharingConsent`` when the searched-for ``DataSharingConsent`` instance does not exist. ...
[ "def", "proxied_get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "original_kwargs", "=", "kwargs", ".", "copy", "(", ")", "if", "'course_id'", "in", "kwargs", ":", "try", ":", "# Check if we have a course ID or a course run ID", "course_...
46.724138
0.005785
def joint(*parsers): '''Joint two or more parsers, implements the operator of `(+)`.''' @Parser def joint_parser(text, index): values = [] prev_v = None for p in parsers: if prev_v: index = prev_v.index prev_v = v = p(text, index) i...
[ "def", "joint", "(", "*", "parsers", ")", ":", "@", "Parser", "def", "joint_parser", "(", "text", ",", "index", ")", ":", "values", "=", "[", "]", "prev_v", "=", "None", "for", "p", "in", "parsers", ":", "if", "prev_v", ":", "index", "=", "prev_v",...
29.2
0.002212
def show_system_monitor_output_switch_status_rbridge_id_out(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_system_monitor = ET.Element("show_system_monitor") config = show_system_monitor output = ET.SubElement(show_system_monitor, "output")...
[ "def", "show_system_monitor_output_switch_status_rbridge_id_out", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_system_monitor", "=", "ET", ".", "Element", "(", "\"show_system_monitor\"", ")", "c...
45.615385
0.003306
def add_user_to_group(iam_client, user, group, quiet = False): """ Add an IAM user to an IAM group :param iam_client: :param group: :param user: :param user_info: :param dry_run: :return: """ if not quiet: printInfo('Adding user to group %s...' % group) iam_client.ad...
[ "def", "add_user_to_group", "(", "iam_client", ",", "user", ",", "group", ",", "quiet", "=", "False", ")", ":", "if", "not", "quiet", ":", "printInfo", "(", "'Adding user to group %s...'", "%", "group", ")", "iam_client", ".", "add_user_to_group", "(", "GroupN...
25.571429
0.018868
def _activate_logger(cls, logger_name, simple_name, detail_level, handler, connection, propagate): """ Configure the specified logger, and activate logging and set detail level for connections. The specified logger is always a single pywbem logger; the simple ...
[ "def", "_activate_logger", "(", "cls", ",", "logger_name", ",", "simple_name", ",", "detail_level", ",", "handler", ",", "connection", ",", "propagate", ")", ":", "if", "handler", "is", "not", "None", ":", "assert", "isinstance", "(", "handler", ",", "loggin...
43.625
0.000841
def calculate_mean_vectors(X, y): """Calculates the mean samples per class Parameters: ----------- X : array-like, shape (m, n) - the samples y : array-like, shape (m, ) - the class labels Returns: -------- mean_vectors : array-like, shape (k, ) Those are the mean samples f...
[ "def", "calculate_mean_vectors", "(", "X", ",", "y", ")", ":", "return", "[", "np", ".", "mean", "(", "X", "[", "y", "==", "cl", ",", ":", "]", ",", "axis", "=", "0", ")", "for", "cl", "in", "np", ".", "unique", "(", "y", ")", "]" ]
25.3125
0.009524
def record_ce_entries(self): # type: () -> bytes ''' Return a string representing the Rock Ridge entries in the Continuation Entry. Parameters: None. Returns: A string representing the Rock Ridge entry. ''' if not self._initialized: ...
[ "def", "record_ce_entries", "(", "self", ")", ":", "# type: () -> bytes", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'Rock Ridge extension not yet initialized'", ")", "return", "self", ".", "_record", ...
31.428571
0.011038
def download_from(self, buff, remote_path): """Downloads file from WebDAV and writes it in buffer. :param buff: buffer object for writing of downloaded file content. :param remote_path: path to file on WebDAV server. """ urn = Urn(remote_path) if self.is_dir(urn.path()):...
[ "def", "download_from", "(", "self", ",", "buff", ",", "remote_path", ")", ":", "urn", "=", "Urn", "(", "remote_path", ")", "if", "self", ".", "is_dir", "(", "urn", ".", "path", "(", ")", ")", ":", "raise", "OptionNotValid", "(", "name", "=", "'remot...
39.066667
0.003333
def record_mode(self, record_opt, channel=0): """ Params: channel: video index, start from 0 record_opt: +----------------------------+-----------------+-------------------+ | ParamName | ParamValue type | Description | +----------...
[ "def", "record_mode", "(", "self", ",", "record_opt", ",", "channel", "=", "0", ")", ":", "ret", "=", "self", ".", "command", "(", "'configManager.cgi?action=setConfig&RecordMode'", "'[{0}].Mode={1}'", ".", "format", "(", "channel", ",", "record_opt", ")", ")", ...
41.56
0.001881
def save(self, **kwargs): """ Method that creates the translations tasks for every selected instance :param kwargs: :return: """ try: # result_ids = [] manager = Manager() for item in self.model_class.objects.language(manager.get_main_...
[ "def", "save", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "# result_ids = []", "manager", "=", "Manager", "(", ")", "for", "item", "in", "self", ".", "model_class", ".", "objects", ".", "language", "(", "manager", ".", "get_main_language...
46.058824
0.007509
def hide_arp_holder_system_max_arp(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_arp_holder = ET.SubElement(config, "hide-arp-holder", xmlns="urn:brocade.com:mgmt:brocade-arp") system_max = ET.SubElement(hide_arp_holder, "system-max") arp ...
[ "def", "hide_arp_holder_system_max_arp", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "hide_arp_holder", "=", "ET", ".", "SubElement", "(", "config", ",", "\"hide-arp-holder\"", ",", "xmlns", "=...
42.909091
0.006224
def validate_key(key: str): """ Validates the given key. :param key: the key to validate :raises InvalidKeyError: raised if the given key is invalid """ if "//" in key: raise DoubleSlashKeyError(key) elif normpath(key) != key: raise NonNorm...
[ "def", "validate_key", "(", "key", ":", "str", ")", ":", "if", "\"//\"", "in", "key", ":", "raise", "DoubleSlashKeyError", "(", "key", ")", "elif", "normpath", "(", "key", ")", "!=", "key", ":", "raise", "NonNormalisedKeyError", "(", "key", ")" ]
33
0.0059
def _do_packet(self, packet, ip, port): """ React to incoming packet :param packet: Packet to handle :type packet: T >= paps.si.app.message.APPMessage :param ip: Client ip address :type ip: unicode :param port: Client port :type port: int :rtype: ...
[ "def", "_do_packet", "(", "self", ",", "packet", ",", "ip", ",", "port", ")", ":", "msg_type", "=", "packet", ".", "header", ".", "message_type", "if", "msg_type", "==", "MsgType", ".", "JOIN", ":", "self", ".", "_do_join_packet", "(", "packet", ",", "...
32
0.003035
def linebuffered_stdout(): """ Always line buffer stdout so pipes and redirects are CLI friendly. """ if sys.stdout.line_buffering: return sys.stdout orig = sys.stdout new = type(orig)(orig.buffer, encoding=orig.encoding, errors=orig.errors, line_buffering=True) new.mode...
[ "def", "linebuffered_stdout", "(", ")", ":", "if", "sys", ".", "stdout", ".", "line_buffering", ":", "return", "sys", ".", "stdout", "orig", "=", "sys", ".", "stdout", "new", "=", "type", "(", "orig", ")", "(", "orig", ".", "buffer", ",", "encoding", ...
37.666667
0.002882
def write(self, buf, **kwargs): """ Write the bytes from ``buffer`` to the device. Transmits a stop bit if ``stop`` is set. If ``start`` or ``end`` is provided, then the buffer will be sliced as if ``buffer[start:end]``. This will not cause an allocation like ``buffer[st...
[ "def", "write", "(", "self", ",", "buf", ",", "*", "*", "kwargs", ")", ":", "self", ".", "i2c", ".", "writeto", "(", "self", ".", "device_address", ",", "buf", ",", "*", "*", "kwargs", ")", "if", "self", ".", "_debug", ":", "print", "(", "\"i2c_d...
45.588235
0.003793
def get_marker_style(line): """Get the style dictionary for matplotlib marker objects""" style = {} style['alpha'] = line.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['facecolor'] = color_to_hex(line.get_markerfacecolor()) style['edgecolor'] = color_to_hex(line.get_ma...
[ "def", "get_marker_style", "(", "line", ")", ":", "style", "=", "{", "}", "style", "[", "'alpha'", "]", "=", "line", ".", "get_alpha", "(", ")", "if", "style", "[", "'alpha'", "]", "is", "None", ":", "style", "[", "'alpha'", "]", "=", "1", "style",...
39.095238
0.001189
def merge_config( config: Mapping[str, Any], override_config: Mapping[str, Any] = None, override_config_fn: str = None, ) -> Mapping[str, Any]: """Override config with additional configuration in override_config or override_config_fn Used in script to merge CLI options with Config Args: ...
[ "def", "merge_config", "(", "config", ":", "Mapping", "[", "str", ",", "Any", "]", ",", "override_config", ":", "Mapping", "[", "str", ",", "Any", "]", "=", "None", ",", "override_config_fn", ":", "str", "=", "None", ",", ")", "->", "Mapping", "[", "...
33.347826
0.002535
def get_cfg_lbl(cfg, name=None, nonlbl_keys=INTERNAL_CFGKEYS, key_order=None, with_name=True, default_cfg=None, sep=''): r""" Formats a flat configuration dict into a short string label. This is useful for re-creating command line strings. Args: cfg (dict): name (str): (...
[ "def", "get_cfg_lbl", "(", "cfg", ",", "name", "=", "None", ",", "nonlbl_keys", "=", "INTERNAL_CFGKEYS", ",", "key_order", "=", "None", ",", "with_name", "=", "True", ",", "default_cfg", "=", "None", ",", "sep", "=", "''", ")", ":", "import", "utool", ...
37.322222
0.00116
def git_list_config(repo_dir): """Return a list of the git configuration.""" command = ['git', 'config', '--list'] raw = execute_git_command(command, repo_dir=repo_dir).splitlines() output = {key: val for key, val in [cfg.split('=', 1) for cfg in raw]} # TODO(sam): maybe turn this into...
[ "def", "git_list_config", "(", "repo_dir", ")", ":", "command", "=", "[", "'git'", ",", "'config'", ",", "'--list'", "]", "raw", "=", "execute_git_command", "(", "command", ",", "repo_dir", "=", "repo_dir", ")", ".", "splitlines", "(", ")", "output", "=", ...
42.7
0.002294
def _normalize_data(stream, date_format=None): """ This function is meant to normalize data for upload to the Luminoso Analytics system. Currently it only normalizes dates. If date_format is not specified, or if there's no date in a particular doc, the the doc is yielded unchanged. """ for ...
[ "def", "_normalize_data", "(", "stream", ",", "date_format", "=", "None", ")", ":", "for", "doc", "in", "stream", ":", "if", "'date'", "in", "doc", "and", "date_format", "is", "not", "None", ":", "try", ":", "doc", "[", "'date'", "]", "=", "_convert_da...
43.315789
0.001189
def __db_print(self_,level,msg,*args,**kw): """ Calls the logger returned by the get_logger() function, prepending the result of calling dbprint_prefix() (if any). See python's logging module for details. """ self_or_cls = self_.self_or_cls if get_logger(name=sel...
[ "def", "__db_print", "(", "self_", ",", "level", ",", "msg", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "self_or_cls", "=", "self_", ".", "self_or_cls", "if", "get_logger", "(", "name", "=", "self_or_cls", ".", "name", ")", ".", "isEnabledFor", ...
40
0.012216
def get_kernel_spec(self, kernel_name): """Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name is not found. """ if kernel_name == CURRENT_ENV_KERNEL_NAME: return self.kernel_spec_class( resour...
[ "def", "get_kernel_spec", "(", "self", ",", "kernel_name", ")", ":", "if", "kernel_name", "==", "CURRENT_ENV_KERNEL_NAME", ":", "return", "self", ".", "kernel_spec_class", "(", "resource_dir", "=", "ipykernel", ".", "kernelspec", ".", "RESOURCES", ",", "*", "*",...
45.818182
0.005837
def bitfield_update(w, range_start, range_end, newvalue, truncating=False): """ Return wirevector w but with some of the bits overwritten by newvalue. :param w: a wirevector to use as the starting point for the update :param range_start: the start of the range of bits to be updated :param range_end: th...
[ "def", "bitfield_update", "(", "w", ",", "range_start", ",", "range_end", ",", "newvalue", ",", "truncating", "=", "False", ")", ":", "from", ".", "corecircuits", "import", "concat_list", "w", "=", "as_wires", "(", "w", ")", "idxs", "=", "list", "(", "ra...
48.843137
0.003935
async def setup(self): """Setting up DynamoDB table, if it not exists.""" try: client = await self.db response = await client.list_tables() created = False # create table if not already created. if self.table_name not in response["TableNames"]:...
[ "async", "def", "setup", "(", "self", ")", ":", "try", ":", "client", "=", "await", "self", ".", "db", "response", "=", "await", "client", ".", "list_tables", "(", ")", "created", "=", "False", "# create table if not already created.", "if", "self", ".", "...
56.52
0.006263
def _state_to_task(cls, tstate, shard_state, eta=None, countdown=None): """Generate task for slice according to current states. Args: tstate: An instance of TransientShardState. shard_state: An instance of ShardStat...
[ "def", "_state_to_task", "(", "cls", ",", "tstate", ",", "shard_state", ",", "eta", "=", "None", ",", "countdown", "=", "None", ")", ":", "base_path", "=", "tstate", ".", "base_path", "task_name", "=", "MapperWorkerCallbackHandler", ".", "get_task_name", "(", ...
32.473684
0.003934
def write(self, symbol, data, metadata=None, prune_previous_version=True, **kwargs): """ Write 'data' under the specified 'symbol' name to this library. Parameters ---------- symbol : `str` symbol name for the item data : to be persisted m...
[ "def", "write", "(", "self", ",", "symbol", ",", "data", ",", "metadata", "=", "None", ",", "prune_previous_version", "=", "True", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_arctic_lib", ".", "check_quota", "(", ")", "version", "=", "{", "'_id'"...
44.2
0.005312
def close_statement(self, connection_id, statement_id): """Closes a statement. :param connection_id: ID of the current connection. :param statement_id: ID of the statement to close. """ request = requests_pb2.CloseStatementRequest() request.conne...
[ "def", "close_statement", "(", "self", ",", "connection_id", ",", "statement_id", ")", ":", "request", "=", "requests_pb2", ".", "CloseStatementRequest", "(", ")", "request", ".", "connection_id", "=", "connection_id", "request", ".", "statement_id", "=", "stateme...
28.928571
0.004785
def update_changes_after_row_delete(self, row_num): """ Update self.changes so that row numbers for edited rows are still correct. I.e., if row 4 was edited and then row 2 was deleted, row 4 becomes row 3. This function updates self.changes to reflect that. """ if row_num...
[ "def", "update_changes_after_row_delete", "(", "self", ",", "row_num", ")", ":", "if", "row_num", "in", "self", ".", "changes", ".", "copy", "(", ")", ":", "self", ".", "changes", ".", "remove", "(", "row_num", ")", "updated_rows", "=", "[", "]", "for", ...
42.882353
0.005369
def setCurrentIndex(self, index): """ Sets the current item to the item at the inputed index. :param index | <int> """ if self._currentIndex == index: return self._currentIndex = index self.currentIndexChanged.emit(index) for i, item in...
[ "def", "setCurrentIndex", "(", "self", ",", "index", ")", ":", "if", "self", ".", "_currentIndex", "==", "index", ":", "return", "self", ".", "_currentIndex", "=", "index", "self", ".", "currentIndexChanged", ".", "emit", "(", "index", ")", "for", "i", "...
26.533333
0.004854
def fitness(self, width, height): """ In guillotine algorithm case, returns the min of the fitness of all free sections, for the given dimension, both normal and rotated (if rotation enabled.) """ assert(width > 0 and height > 0) # Get best fitness section. ...
[ "def", "fitness", "(", "self", ",", "width", ",", "height", ")", ":", "assert", "(", "width", ">", "0", "and", "height", ">", "0", ")", "# Get best fitness section.", "section", ",", "rotated", "=", "self", ".", "_select_fittest_section", "(", "width", ","...
37.052632
0.00554
def create(gandi, name, value=None, filename=None): """ Create a new SSH key. """ if not value and not filename: raise UsageError('You must set value OR filename.') if value and filename: raise UsageError('You must not set value AND filename.') if filename: value = filename.rea...
[ "def", "create", "(", "gandi", ",", "name", ",", "value", "=", "None", ",", "filename", "=", "None", ")", ":", "if", "not", "value", "and", "not", "filename", ":", "raise", "UsageError", "(", "'You must set value OR filename.'", ")", "if", "value", "and", ...
30.133333
0.002146
def log_power_spectrum(frames, fft_points=512, normalize=True): """Log power spectrum of each frame in frames. Args: frames (array): The frame array in which each row is a frame. fft_points (int): The length of FFT. If fft_length is greater than frame_len, the frames will be zero-pa...
[ "def", "log_power_spectrum", "(", "frames", ",", "fft_points", "=", "512", ",", "normalize", "=", "True", ")", ":", "power_spec", "=", "power_spectrum", "(", "frames", ",", "fft_points", ")", "power_spec", "[", "power_spec", "<=", "1e-20", "]", "=", "1e-20",...
38.045455
0.001166
def mapScan(mapFunc, reductionFunc, *iterables, **kwargs): """Exectues the :meth:`~scoop.futures.map` function and then applies a reduction function to its result while keeping intermediate reduction values. This is a blocking call. :param mapFunc: Any picklable callable object (function or class objec...
[ "def", "mapScan", "(", "mapFunc", ",", "reductionFunc", ",", "*", "iterables", ",", "*", "*", "kwargs", ")", ":", "return", "submit", "(", "_recursiveReduce", ",", "mapFunc", ",", "reductionFunc", ",", "True", ",", "*", "iterables", ")", ".", "result", "...
45.962963
0.002368
def all_logging_disabled(highest_level=logging.CRITICAL): """Disable all logging temporarily. A context manager that will prevent any logging messages triggered during the body from being processed. Args: highest_level: the maximum logging level that is being blocked """ previous_level = l...
[ "def", "all_logging_disabled", "(", "highest_level", "=", "logging", ".", "CRITICAL", ")", ":", "previous_level", "=", "logging", ".", "root", ".", "manager", ".", "disable", "logging", ".", "disable", "(", "highest_level", ")", "try", ":", "yield", "finally",...
31.785714
0.004367
def get_vtkjs_url(*args): """After using ``export_vtkjs()`` to create a ``.vtkjs`` file from a data scene which is uploaded to an online file hosting service like Dropbox, use this method to get a shareable link to that scene on the `PVGeo VTKjs viewer`_. .. _PVGeo VTKjs viewer: http://viewer.vtki....
[ "def", "get_vtkjs_url", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "host", "=", "'dropbox'", "inURL", "=", "args", "[", "0", "]", "elif", "len", "(", "args", ")", "==", "2", ":", "host", "=", "args", "[", "0", ...
32.5625
0.003728
def sys_maxfd(): """ Returns the maximum file descriptor limit. This is guaranteed to return a useful int value. """ maxfd = None try: maxfd = int(resource.getrlimit(resource.RLIMIT_NOFILE)[0]) if maxfd == resource.RLIM_INFINITY: #...
[ "def", "sys_maxfd", "(", ")", ":", "maxfd", "=", "None", "try", ":", "maxfd", "=", "int", "(", "resource", ".", "getrlimit", "(", "resource", ".", "RLIMIT_NOFILE", ")", "[", "0", "]", ")", "if", "maxfd", "==", "resource", ".", "RLIM_INFINITY", ":", "...
31.857143
0.008715
def on_menu(self, event): '''handle menu selections''' state = self.state ret = self.menu.find_selected(event) if ret is None: return ret.call_handler() state.child_pipe_send.send(ret)
[ "def", "on_menu", "(", "self", ",", "event", ")", ":", "state", "=", "self", ".", "state", "ret", "=", "self", ".", "menu", ".", "find_selected", "(", "event", ")", "if", "ret", "is", "None", ":", "return", "ret", ".", "call_handler", "(", ")", "st...
29.625
0.008197
def autocommand(func): """ A simplified decorator for making a single function a Command instance. In the future this will leverage PEP0484 to do really smart function parsing and conversion to argparse actions. """ name = func.__name__ title, desc = command.parse_docstring(func) if not title: ...
[ "def", "autocommand", "(", "func", ")", ":", "name", "=", "func", ".", "__name__", "title", ",", "desc", "=", "command", ".", "parse_docstring", "(", "func", ")", "if", "not", "title", ":", "title", "=", "'Auto command for: %s'", "%", "name", "if", "not"...
43.416667
0.00188
def classes(self, values): """Classes setter.""" if isinstance(values, dict): if self.__data is not None and len(self.__data) != len(values): raise ValueError( 'number of samples do not match the previously assigned data') elif set(self.keys) !...
[ "def", "classes", "(", "self", ",", "values", ")", ":", "if", "isinstance", "(", "values", ",", "dict", ")", ":", "if", "self", ".", "__data", "is", "not", "None", "and", "len", "(", "self", ".", "__data", ")", "!=", "len", "(", "values", ")", ":...
46.5
0.00703
def build_time(start_time): """ Calculate build time per package """ diff_time = round(time.time() - start_time, 2) if diff_time <= 59.99: sum_time = str(diff_time) + " Sec" elif diff_time > 59.99 and diff_time <= 3599.99: sum_time = round(diff_time / 60, 2) sum_time_list...
[ "def", "build_time", "(", "start_time", ")", ":", "diff_time", "=", "round", "(", "time", ".", "time", "(", ")", "-", "start_time", ",", "2", ")", "if", "diff_time", "<=", "59.99", ":", "sum_time", "=", "str", "(", "diff_time", ")", "+", "\" Sec\"", ...
41.722222
0.001302
def get_iss(self, key): """ Get the Issuer ID :param key: Key to the information in the state database :return: The issuer ID """ _state = self.get_state(key) if not _state: raise KeyError(key) return _state['iss']
[ "def", "get_iss", "(", "self", ",", "key", ")", ":", "_state", "=", "self", ".", "get_state", "(", "key", ")", "if", "not", "_state", ":", "raise", "KeyError", "(", "key", ")", "return", "_state", "[", "'iss'", "]" ]
25.545455
0.006873
def get_files(self): """ :calls: `GET /repos/:owner/:repo/pulls/:number/files <http://developer.github.com/v3/pulls>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.File.File` """ return github.PaginatedList.PaginatedList( github.File.File, ...
[ "def", "get_files", "(", "self", ")", ":", "return", "github", ".", "PaginatedList", ".", "PaginatedList", "(", "github", ".", "File", ".", "File", ",", "self", ".", "_requester", ",", "self", ".", "url", "+", "\"/files\"", ",", "None", ")" ]
35.909091
0.009877
def cns_vwl_str_len(self): """ Return a new IPAString, containing only: 1. the consonants, 2. the vowels, and 3. the stress diacritics, and 4. the length diacritics in the current string. :rtype: IPAString """ return IPAString(ip...
[ "def", "cns_vwl_str_len", "(", "self", ")", ":", "return", "IPAString", "(", "ipa_chars", "=", "[", "c", "for", "c", "in", "self", ".", "ipa_chars", "if", "(", "c", ".", "is_letter", ")", "or", "(", "c", ".", "is_suprasegmental", "and", "(", "c", "."...
29.857143
0.009281
def in_use(self): """Check whether this device is in use, i.e. mounted or unlocked.""" if self.is_mounted or self.is_unlocked: return True if self.is_partition_table: for device in self._daemon: if device.partition_slave == self and device.in_use: ...
[ "def", "in_use", "(", "self", ")", ":", "if", "self", ".", "is_mounted", "or", "self", ".", "is_unlocked", ":", "return", "True", "if", "self", ".", "is_partition_table", ":", "for", "device", "in", "self", ".", "_daemon", ":", "if", "device", ".", "pa...
39.555556
0.005495
def make_list(obj, cast=True): """ Converts an object *obj* to a list and returns it. Objects of types *tuple* and *set* are converted if *cast* is *True*. Otherwise, and for all other types, *obj* is put in a new list. """ if isinstance(obj, list): return list(obj) if isinstance(obj, ty...
[ "def", "make_list", "(", "obj", ",", "cast", "=", "True", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "list", "(", "obj", ")", "if", "isinstance", "(", "obj", ",", "types", ".", "GeneratorType", ")", ":", "return", "l...
35
0.006424
def highlight_project_bid(session, bid_id): """ Highlight a bid on a project """ headers = { 'Content-Type': 'application/x-www-form-urlencoded' } bid_data = { 'action': 'highlight' } # POST /api/projects/0.1/bids/{bid_id}/?action=revoke endpoint = 'bids/{}'.format(bi...
[ "def", "highlight_project_bid", "(", "session", ",", "bid_id", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", "}", "bid_data", "=", "{", "'action'", ":", "'highlight'", "}", "# POST /api/projects/0.1/bids/{bid_id}/?action=revo...
36.363636
0.001218
def rank_alternation(edm_missing, rank, niter=50, print_out=False, edm_true=None): """Complete and denoise EDM using rank alternation. Iteratively impose rank and strucutre to complete marix entries :param edm_missing: EDM with 0 where no measurement was taken. :param rank: expected rank of complete E...
[ "def", "rank_alternation", "(", "edm_missing", ",", "rank", ",", "niter", "=", "50", ",", "print_out", "=", "False", ",", "edm_true", "=", "None", ")", ":", "from", "pylocus", ".", "basics", "import", "low_rank_approximation", "errs", "=", "[", "]", "N", ...
38.8
0.003592
def from_two_vectors(self, vec1, vec2): '''get a rotation matrix from two vectors. This returns a rotation matrix which when applied to vec1 will produce a vector pointing in the same direction as vec2''' angle = vec1.angle(vec2) cross = vec1 % vec2 if cross.length(...
[ "def", "from_two_vectors", "(", "self", ",", "vec1", ",", "vec2", ")", ":", "angle", "=", "vec1", ".", "angle", "(", "vec2", ")", "cross", "=", "vec1", "%", "vec2", "if", "cross", ".", "length", "(", ")", "==", "0", ":", "# the two vectors are colinear...
43.818182
0.00813
def _parse_work(self, cts_file, textgroup): """ Parses a work from a cts file :param cts_file: Path to the CTS File :type cts_file: str :param textgroup: Textgroup to which the Work is a part of :type textgroup: CtsTextgroupMetadata :return: Parsed Work and the Texts, as...
[ "def", "_parse_work", "(", "self", ",", "cts_file", ",", "textgroup", ")", ":", "with", "io", ".", "open", "(", "cts_file", ")", "as", "__xml__", ":", "work", ",", "texts", "=", "self", ".", "classes", "[", "\"work\"", "]", ".", "parse", "(", "resour...
36.529412
0.00471
def launch(self, host="local", port=8080): """Calling the Launch method on a Site object will serve the top node of the cherrypy Root object tree""" # Need to add in the appbar if many apps self.root.templateVars['app_bar'] = self.site_app_bar for fullRoute, _ in self.site_a...
[ "def", "launch", "(", "self", ",", "host", "=", "\"local\"", ",", "port", "=", "8080", ")", ":", "# Need to add in the appbar if many apps", "self", ".", "root", ".", "templateVars", "[", "'app_bar'", "]", "=", "self", ".", "site_app_bar", "for", "fullRoute", ...
43.857143
0.00319
def _set_params(self): """Sets the parameters with types, descriptions and default value if any""" # TODO: manage different in/out styles if self.docs['in']['params']: # list of parameters is like: (name, description, type) self.docs['out']['params'] = list(self.docs['in'...
[ "def", "_set_params", "(", "self", ")", ":", "# TODO: manage different in/out styles", "if", "self", ".", "docs", "[", "'in'", "]", "[", "'params'", "]", ":", "# list of parameters is like: (name, description, type)", "self", ".", "docs", "[", "'out'", "]", "[", "...
43.5
0.00346
def validate_jhove(filename, jhove=None, ignore=None): """Validate TIFF file using jhove -m TIFF-hul. Raise ValueError if jhove outputs an error message unless the message contains one of the strings in 'ignore'. JHOVE does not support bigtiff or more than 50 IFDs. See `JHOVE TIFF-hul Module <htt...
[ "def", "validate_jhove", "(", "filename", ",", "jhove", "=", "None", ",", "ignore", "=", "None", ")", ":", "import", "subprocess", "# noqa: delayed import", "if", "ignore", "is", "None", ":", "ignore", "=", "[", "'More than 50 IFDs'", "]", "if", "jhove", "is...
34.214286
0.001015
def drawLine(self, p1, p2): """Draw a line between two points. """ p1 = Point(p1) p2 = Point(p2) if not (self.lastPoint == p1): self.draw_cont += "%g %g m\n" % JM_TUPLE(p1 * self.ipctm) self.lastPoint = p1 self.updateRect(p1) self.draw...
[ "def", "drawLine", "(", "self", ",", "p1", ",", "p2", ")", ":", "p1", "=", "Point", "(", "p1", ")", "p2", "=", "Point", "(", "p2", ")", "if", "not", "(", "self", ".", "lastPoint", "==", "p1", ")", ":", "self", ".", "draw_cont", "+=", "\"%g %g m...
31.5
0.004405
def timeout_process_add_queue(self, module, cache_time): """ Add a module to the timeout_queue if it is scheduled in the future or if it is due for an update immediately just trigger that. the timeout_queue is a dict with the scheduled time as the key and the value is a list of ...
[ "def", "timeout_process_add_queue", "(", "self", ",", "module", ",", "cache_time", ")", ":", "# If already set to update do nothing", "if", "module", "in", "self", ".", "timeout_update_due", ":", "return", "# remove if already in the queue", "key", "=", "self", ".", "...
42.688889
0.001018
def op_mult(self, text): """op_mult = "*" ;""" self._attempting(text) return terminal("*")(text).retyped(TokenType.op_mult)
[ "def", "op_mult", "(", "self", ",", "text", ")", ":", "self", ".", "_attempting", "(", "text", ")", "return", "terminal", "(", "\"*\"", ")", "(", "text", ")", ".", "retyped", "(", "TokenType", ".", "op_mult", ")" ]
33
0.007407
def makedirs_(path, user=None, group=None, mode=None): ''' Ensure that the directory containing this path is available. .. note:: The path must end with a trailing slash otherwise the directory/directories will be created up to the parent directory...
[ "def", "makedirs_", "(", "path", ",", "user", "=", "None", ",", "group", "=", "None", ",", "mode", "=", "None", ")", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "if", "mode", ":", "mode", "=", "salt", ".", "utils", ...
31.328125
0.000967
def as_binning(obj, copy: bool = False) -> BinningBase: """Ensure that an object is a binning Parameters --------- obj : BinningBase or array_like Can be a binning, numpy-like bins or full physt bins copy : If true, ensure that the returned object is independent """ if isinstance(ob...
[ "def", "as_binning", "(", "obj", ",", "copy", ":", "bool", "=", "False", ")", "->", "BinningBase", ":", "if", "isinstance", "(", "obj", ",", "BinningBase", ")", ":", "if", "copy", ":", "return", "obj", ".", "copy", "(", ")", "else", ":", "return", ...
28.470588
0.002
def get_sets(path_to_data): """ Get a training, validation and a testset as well as a dictionary that maps each formula_id to an index (0...nr_of_formulas - 1). Parameters ---------- path_to_data : A pickle file that contains a list of datasets. Returns ------- tuple ...
[ "def", "get_sets", "(", "path_to_data", ")", ":", "loaded", "=", "pickle", ".", "load", "(", "open", "(", "path_to_data", ",", "'rb'", ")", ")", "datasets", "=", "loaded", "[", "'handwriting_datasets'", "]", "training_set", ",", "validation_set", ",", "test_...
34.314286
0.000405
def set_agent(self, agent): """ Links behaviour with its owner agent Args: agent (spade.agent.Agent): the agent who owns the behaviour """ self.agent = agent self.queue = asyncio.Queue(loop=self.agent.loop) self.presence = agent.presence self.w...
[ "def", "set_agent", "(", "self", ",", "agent", ")", ":", "self", ".", "agent", "=", "agent", "self", ".", "queue", "=", "asyncio", ".", "Queue", "(", "loop", "=", "self", ".", "agent", ".", "loop", ")", "self", ".", "presence", "=", "agent", ".", ...
26.916667
0.005988
def posthoc_mannwhitney(a, val_col=None, group_col=None, use_continuity=True, alternative='two-sided', p_adjust=None, sort=True): '''Pairwise comparisons with Mann-Whitney rank test. Parameters ---------- a : array_like or pandas DataFrame object An array, any object exposing the array interfa...
[ "def", "posthoc_mannwhitney", "(", "a", ",", "val_col", "=", "None", ",", "group_col", "=", "None", ",", "use_continuity", "=", "True", ",", "alternative", "=", "'two-sided'", ",", "p_adjust", "=", "None", ",", "sort", "=", "True", ")", ":", "x", ",", ...
37.108696
0.003424
def collate_tensors(batch, stack_tensors=torch.stack): """ Collate a list of type ``k`` (dict, namedtuple, list, etc.) with tensors. Inspired by: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31 Args: batch (list of k): List of rows of type ``k``. s...
[ "def", "collate_tensors", "(", "batch", ",", "stack_tensors", "=", "torch", ".", "stack", ")", ":", "if", "all", "(", "[", "torch", ".", "is_tensor", "(", "b", ")", "for", "b", "in", "batch", "]", ")", ":", "return", "stack_tensors", "(", "batch", ")...
44.44186
0.004096
def _get_parser(extra_args): """Return ArgumentParser with any extra arguments.""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) dirs = appdirs.AppDirs('hangups', 'hangups') default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.tx...
[ "def", "_get_parser", "(", "extra_args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ",", ")", "dirs", "=", "appdirs", ".", "AppDirs", "(", "'hangups'", ",", "'hangups...
37.333333
0.001451
def is_unicode_string(string): """ Return ``True`` if the given string is a Unicode string, that is, of type ``unicode`` in Python 2 or ``str`` in Python 3. Return ``None`` if ``string`` is ``None``. :param str string: the string to be checked :rtype: bool """ if string is None: ...
[ "def", "is_unicode_string", "(", "string", ")", ":", "if", "string", "is", "None", ":", "return", "None", "if", "PY2", ":", "return", "isinstance", "(", "string", ",", "unicode", ")", "return", "isinstance", "(", "string", ",", "str", ")" ]
27.266667
0.002364
def register_on_guest_property_changed(self, callback): """Set the callback function to consume on guest property changed events. Callback receives a IGuestPropertyChangedEvent object. Returns the callback_id """ event_type = library.VBoxEventType.on_guest_property_chan...
[ "def", "register_on_guest_property_changed", "(", "self", ",", "callback", ")", ":", "event_type", "=", "library", ".", "VBoxEventType", ".", "on_guest_property_changed", "return", "self", ".", "event_source", ".", "register_callback", "(", "callback", ",", "event_typ...
38.7
0.005051
def all(cls): """ Return an iterator that successively yields saved model instances. Models are saved in an unordered :py:class:`Set`, so the iterator will return them in arbitrary order. Example:: for note in Note.all(): print note.content ...
[ "def", "all", "(", "cls", ")", ":", "for", "result", "in", "cls", ".", "_query", ".", "all_index", "(", ")", ":", "yield", "cls", ".", "load", "(", "result", ",", "convert_key", "=", "False", ")" ]
34.736842
0.00295
def replace(self, request, id): """Replace an object.""" try: object = self.model.objects.get(id=id) except self.model.DoesNotExist: return self._render( request = request, template = '404', context = { '...
[ "def", "replace", "(", "self", ",", "request", ",", "id", ")", ":", "try", ":", "object", "=", "self", ".", "model", ".", "objects", ".", "get", "(", "id", "=", "id", ")", "except", "self", ".", "model", ".", "DoesNotExist", ":", "return", "self", ...
29.9
0.023758
async def answer_media_group(self, media: typing.Union[MediaGroup, typing.List], disable_notification: typing.Union[base.Boolean, None] = None, reply=False) -> typing.List[Message]: """ Use this method to send a group of photos or videos ...
[ "async", "def", "answer_media_group", "(", "self", ",", "media", ":", "typing", ".", "Union", "[", "MediaGroup", ",", "typing", ".", "List", "]", ",", "disable_notification", ":", "typing", ".", "Union", "[", "base", ".", "Boolean", ",", "None", "]", "="...
60.95
0.008078
def describe(self, uri, format="", convert=True): """ A simple DESCRIBE query with no 'where' arguments. 'uri' is the resource you want to describe. TODO: there are some errors with describe queries, due to the results being sent back For the moment we're not using them much.. needs to be tested more. """ ...
[ "def", "describe", "(", "self", ",", "uri", ",", "format", "=", "\"\"", ",", "convert", "=", "True", ")", ":", "lines", "=", "[", "\"PREFIX %s: <%s>\"", "%", "(", "k", ",", "r", ")", "for", "k", ",", "r", "in", "self", ".", "prefixes", ".", "iter...
32.05
0.028788
def login(self, user, passwd): """login user passwd Performs the login operation for Security Center, storing the token that Security Center has generated for this login session for future queries. """ data = self.raw_query('auth', 'login', da...
[ "def", "login", "(", "self", ",", "user", ",", "passwd", ")", ":", "data", "=", "self", ".", "raw_query", "(", "'auth'", ",", "'login'", ",", "data", "=", "{", "'username'", ":", "user", ",", "'password'", ":", "passwd", "}", ")", "self", ".", "_to...
41.5
0.007075
def generate( self, builddir, modbuilddir, component, active_dependencies, immediate_dependencies, all_dependencies, application, toplevel ): ''' active_dependencies is the dictionary of components that need to be built for this component, but will not already have been built for...
[ "def", "generate", "(", "self", ",", "builddir", ",", "modbuilddir", ",", "component", ",", "active_dependencies", ",", "immediate_dependencies", ",", "all_dependencies", ",", "application", ",", "toplevel", ")", ":", "include_root_dirs", "=", "''", "if", "applica...
49.668571
0.007219
def _call_marginalizevlos(self,o,**kwargs): """Call the DF, marginalizing over line-of-sight velocity""" #Get d, l, vperp l= o.ll(obs=[1.,0.,0.],ro=1.)*_DEGTORAD vperp= o.vll(ro=1.,vo=1.,obs=[1.,0.,0.,0.,0.,0.]) R= o.R(use_physical=False) phi= o.phi(use_physical=False) ...
[ "def", "_call_marginalizevlos", "(", "self", ",", "o", ",", "*", "*", "kwargs", ")", ":", "#Get d, l, vperp", "l", "=", "o", ".", "ll", "(", "obs", "=", "[", "1.", ",", "0.", ",", "0.", "]", ",", "ro", "=", "1.", ")", "*", "_DEGTORAD", "vperp", ...
53.638298
0.025321
def update(instance, full_clean=True, post_save=False, **kwargs): "Atomically update instance, setting field/value pairs from kwargs" # apply the updated args to the instance to mimic the change # note that these might slightly differ from the true database values # as the DB could have been updated by...
[ "def", "update", "(", "instance", ",", "full_clean", "=", "True", ",", "post_save", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# apply the updated args to the instance to mimic the change", "# note that these might slightly differ from the true database values", "# as ...
40.607143
0.001718
def set_defaults(self, default_config_params): """ Set default values from specified ConfigParams and returns a new ConfigParams object. :param default_config_params: ConfigMap with default parameter values. :return: a new ConfigParams object. """ map = StringValueMap.f...
[ "def", "set_defaults", "(", "self", ",", "default_config_params", ")", ":", "map", "=", "StringValueMap", ".", "from_maps", "(", "default_config_params", ",", "self", ")", "return", "ConfigParams", "(", "map", ")" ]
38.1
0.007692
def add_textop_iter(func): """Decorator to declare custom *ITER* function as a new textops op An *ITER* function is a function that will receive the input text as a *LIST* of lines. One have to iterate over this list and generate a result (it can be a list, a generator, a dict, a string, an int ...) ...
[ "def", "add_textop_iter", "(", "func", ")", ":", "op", "=", "type", "(", "func", ".", "__name__", ",", "(", "WrapOpIter", ",", ")", ",", "{", "'fn'", ":", "staticmethod", "(", "func", ")", "}", ")", "setattr", "(", "textops", ".", "ops", ",", "func...
31.361111
0.006873
def to_block(self, env, parent=None): """Convert the transient block to a :class:`ethereum.blocks.Block`""" return Block(self.header, self.transaction_list, self.uncles, env=env, parent=parent)
[ "def", "to_block", "(", "self", ",", "env", ",", "parent", "=", "None", ")", ":", "return", "Block", "(", "self", ".", "header", ",", "self", ".", "transaction_list", ",", "self", ".", "uncles", ",", "env", "=", "env", ",", "parent", "=", "parent", ...
69
0.014354
def parse_data_display(self, node): """ Parses <DataDisplay> @param node: Node containing the <DataDisplay> element @type node: xml.etree.Element """ if 'title' in node.lattrib: title = node.lattrib['title'] else: self.raise_error('<DataD...
[ "def", "parse_data_display", "(", "self", ",", "node", ")", ":", "if", "'title'", "in", "node", ".", "lattrib", ":", "title", "=", "node", ".", "lattrib", "[", "'title'", "]", "else", ":", "self", ".", "raise_error", "(", "'<DataDisplay> must have a title.'"...
29.105263
0.005254
def lv_connect_generators(lv_grid_district, graph, debug=False): """ Connect LV generators to LV grid Args ---- lv_grid_district: LVGridDistrictDing0 LVGridDistrictDing0 object for which the connection process has to be done graph: :networkx:`NetworkX Graph Obj< >` NetworkX gra...
[ "def", "lv_connect_generators", "(", "lv_grid_district", ",", "graph", ",", "debug", "=", "False", ")", ":", "cable_lf", "=", "cfg_ding0", ".", "get", "(", "'assumptions'", ",", "'load_factor_lv_cable_fc_normal'", ")", "cos_phi_gen", "=", "cfg_ding0", ".", "get", ...
40.083333
0.001217
def generate_data(self, data_dir, tmp_dir, task_id=-1): """Generates training/dev data. Args: data_dir: a string tmp_dir: a string task_id: an optional integer Returns: shard or shards for which data was generated. """ tf.logging.info("generate_data task_id=%s" % task_id) ...
[ "def", "generate_data", "(", "self", ",", "data_dir", ",", "tmp_dir", ",", "task_id", "=", "-", "1", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"generate_data task_id=%s\"", "%", "task_id", ")", "encoder", "=", "self", ".", "get_or_create_vocab", ...
37.695652
0.003375
def _as_array_or_item(data): """Return the given values as a numpy array, or as an individual item if it's a 0d datetime64 or timedelta64 array. Importantly, this function does not copy data if it is already an ndarray - otherwise, it will not be possible to update Variable values in place. This f...
[ "def", "_as_array_or_item", "(", "data", ")", ":", "data", "=", "np", ".", "asarray", "(", "data", ")", "if", "data", ".", "ndim", "==", "0", ":", "if", "data", ".", "dtype", ".", "kind", "==", "'M'", ":", "data", "=", "np", ".", "datetime64", "(...
38.142857
0.001218