text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def model_argmax(sess, x, predictions, samples, feed=None): """ Helper function that computes the current class prediction :param sess: TF session :param x: the input placeholder :param predictions: the model's symbolic output :param samples: numpy array with input samples (dims must match x) :param feed:...
[ "def", "model_argmax", "(", "sess", ",", "x", ",", "predictions", ",", "samples", ",", "feed", "=", "None", ")", ":", "feed_dict", "=", "{", "x", ":", "samples", "}", "if", "feed", "is", "not", "None", ":", "feed_dict", ".", "update", "(", "feed", ...
38.666667
0.008413
def character_copy(self, char): """Return a dictionary describing character ``char``.""" ret = self.character_stat_copy(char) chara = self._real.character[char] nv = self.character_nodes_stat_copy(char) if nv: ret['node_val'] = nv ev = self.character_portals_s...
[ "def", "character_copy", "(", "self", ",", "char", ")", ":", "ret", "=", "self", ".", "character_stat_copy", "(", "char", ")", "chara", "=", "self", ".", "_real", ".", "character", "[", "char", "]", "nv", "=", "self", ".", "character_nodes_stat_copy", "(...
37.333333
0.001243
def load(stream, Loader=Loader): """ Parse the first YAML document in a stream and produce the corresponding Python object. """ loader = Loader(stream) try: return loader.get_single_data() finally: loader.dispose()
[ "def", "load", "(", "stream", ",", "Loader", "=", "Loader", ")", ":", "loader", "=", "Loader", "(", "stream", ")", "try", ":", "return", "loader", ".", "get_single_data", "(", ")", "finally", ":", "loader", ".", "dispose", "(", ")" ]
24.9
0.003876
def Validate(self): """The filter exists, and has valid filter and hint expressions.""" if self.type not in filters.Filter.classes: raise DefinitionError("Undefined filter type %s" % self.type) self._filter.Validate(self.expression) Validate(self.hint, "Filter has invalid hint")
[ "def", "Validate", "(", "self", ")", ":", "if", "self", ".", "type", "not", "in", "filters", ".", "Filter", ".", "classes", ":", "raise", "DefinitionError", "(", "\"Undefined filter type %s\"", "%", "self", ".", "type", ")", "self", ".", "_filter", ".", ...
49.333333
0.006645
def toHex(val): """Converts the given value (0-255) into its hexadecimal representation""" hex = "0123456789abcdef" return hex[int(val / 16)] + hex[int(val - int(val / 16) * 16)]
[ "def", "toHex", "(", "val", ")", ":", "hex", "=", "\"0123456789abcdef\"", "return", "hex", "[", "int", "(", "val", "/", "16", ")", "]", "+", "hex", "[", "int", "(", "val", "-", "int", "(", "val", "/", "16", ")", "*", "16", ")", "]" ]
46.75
0.005263
def bind_sockets( port: int, address: str = None, family: socket.AddressFamily = socket.AF_UNSPEC, backlog: int = _DEFAULT_BACKLOG, flags: int = None, reuse_port: bool = False, ) -> List[socket.socket]: """Creates listening sockets bound to the given port and address. Returns a list of ...
[ "def", "bind_sockets", "(", "port", ":", "int", ",", "address", ":", "str", "=", "None", ",", "family", ":", "socket", ".", "AddressFamily", "=", "socket", ".", "AF_UNSPEC", ",", "backlog", ":", "int", "=", "_DEFAULT_BACKLOG", ",", "flags", ":", "int", ...
40.009009
0.000439
def ensure_cache_id(self, cache_id_obj): """Ensure the integrity of the cache id object.""" cache_id = self._get_canonical_id(cache_id_obj) if cache_id != self._cache_id_obj: raise ValueError( "cache mismatch {0} != {1}".format( cache_id, self._cac...
[ "def", "ensure_cache_id", "(", "self", ",", "cache_id_obj", ")", ":", "cache_id", "=", "self", ".", "_get_canonical_id", "(", "cache_id_obj", ")", "if", "cache_id", "!=", "self", ".", "_cache_id_obj", ":", "raise", "ValueError", "(", "\"cache mismatch {0} != {1}\"...
46.428571
0.006042
def draw_plane_wave_3d(ax, beam, dist_to_center=0): """Draw the polarization of a plane wave.""" Ex = []; Ey = []; Ez = [] k = [cos(beam.phi)*sin(beam.theta), sin(beam.phi)*sin(beam.theta), cos(beam.theta)] kx, ky, kz = k Nt = 1000 tstep = 7*pi/4/(Nt-1) alpha...
[ "def", "draw_plane_wave_3d", "(", "ax", ",", "beam", ",", "dist_to_center", "=", "0", ")", ":", "Ex", "=", "[", "]", "Ey", "=", "[", "]", "Ez", "=", "[", "]", "k", "=", "[", "cos", "(", "beam", ".", "phi", ")", "*", "sin", "(", "beam", ".", ...
33.191489
0.001868
def primary_key_tuple(self, item): """ Get the primary key tuple from an item """ if self.range_key is None: return (item[self.hash_key.name],) else: return (item[self.hash_key.name], item[self.range_key.name])
[ "def", "primary_key_tuple", "(", "self", ",", "item", ")", ":", "if", "self", ".", "range_key", "is", "None", ":", "return", "(", "item", "[", "self", ".", "hash_key", ".", "name", "]", ",", ")", "else", ":", "return", "(", "item", "[", "self", "."...
42.166667
0.007752
def _download_and_parse_dataset(tmp_dir, train): """Downloads and prepairs the dataset to be parsed by the data_generator.""" file_path = generator_utils.maybe_download(tmp_dir, _SNLI_ZIP, _SNLI_URL) zip_ref = zipfile.ZipFile(file_path, 'r') zip_ref.extractall(tmp_dir) zip_ref.close() file_name = 'train' i...
[ "def", "_download_and_parse_dataset", "(", "tmp_dir", ",", "train", ")", ":", "file_path", "=", "generator_utils", ".", "maybe_download", "(", "tmp_dir", ",", "_SNLI_ZIP", ",", "_SNLI_URL", ")", "zip_ref", "=", "zipfile", ".", "ZipFile", "(", "file_path", ",", ...
45.4
0.019438
def gmap(args): """ %prog gmap database.fasta fastafile Wrapper for `gmap`. """ p = OptionParser(gmap.__doc__) p.add_option("--cross", default=False, action="store_true", help="Cross-species alignment") p.add_option("--npaths", default=0, type="int", help="...
[ "def", "gmap", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "gmap", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--cross\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Cross-species alignment\"...
32.475
0.000747
def check_network_health(self): r""" This method check the network topological health by checking for: (1) Isolated pores (2) Islands or isolated clusters of pores (3) Duplicate throats (4) Bidirectional throats (ie. symmetrical adjacency matrix) ...
[ "def", "check_network_health", "(", "self", ")", ":", "health", "=", "HealthDict", "(", ")", "health", "[", "'disconnected_clusters'", "]", "=", "[", "]", "health", "[", "'isolated_pores'", "]", "=", "[", "]", "health", "[", "'trim_pores'", "]", "=", "[", ...
37.366667
0.000579
def make_tar(tfn, source_dirs, ignore_path=[], optimize_python=True): ''' Make a zip file `fn` from the contents of source_dis. ''' # selector function def select(fn): rfn = realpath(fn) for p in ignore_path: if p.endswith('/'): p = p[:-1] if ...
[ "def", "make_tar", "(", "tfn", ",", "source_dirs", ",", "ignore_path", "=", "[", "]", ",", "optimize_python", "=", "True", ")", ":", "# selector function", "def", "select", "(", "fn", ")", ":", "rfn", "=", "realpath", "(", "fn", ")", "for", "p", "in", ...
30.106383
0.000684
def _verified_content_type_from_id(content_type_id): # type: (int) -> ContentType """Load a message :class:`ContentType` for the specified content type ID. :param int content_type_id: Content type ID :return: Message content type :rtype: ContentType :raises UnknownIdentityError: if unknown cont...
[ "def", "_verified_content_type_from_id", "(", "content_type_id", ")", ":", "# type: (int) -> ContentType", "try", ":", "return", "ContentType", "(", "content_type_id", ")", "except", "ValueError", "as", "error", ":", "raise", "UnknownIdentityError", "(", "\"Unknown conten...
39.769231
0.003781
async def listWorkers(self, *args, **kwargs): """ Get a list of all active workers of a workerType Get a list of all active workers of a workerType. `listWorkers` allows a response to be filtered by quarantined and non quarantined workers. To filter the query, you should call t...
[ "async", "def", "listWorkers", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"listWorkers\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")"...
44.333333
0.008412
def attach_tracker(self, stanza, tracker=None): """ Return a new tracker or modify one to track the stanza. :param stanza: Stanza to track. :type stanza: :class:`aioxmpp.Message` :param tracker: Existing tracker to attach to. :type tracker: :class:`.tracking.MessageTrack...
[ "def", "attach_tracker", "(", "self", ",", "stanza", ",", "tracker", "=", "None", ")", ":", "if", "stanza", ".", "xep0184_received", "is", "not", "None", ":", "raise", "ValueError", "(", "\"requesting delivery receipts for delivery receipts is not \"", "\"allowed\"", ...
35.725
0.001362
def check_nonce(self, nonce): """Checks that the nonce only contains only safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.nonce_length return (set(nonce) <= self.safe_characters and lower <= len(nonce) <= upper)
[ "def", "check_nonce", "(", "self", ",", "nonce", ")", ":", "lower", ",", "upper", "=", "self", ".", "nonce_length", "return", "(", "set", "(", "nonce", ")", "<=", "self", ".", "safe_characters", "and", "lower", "<=", "len", "(", "nonce", ")", "<=", "...
44
0.006369
def add_default(self, ext, content_type): """ Add a child ``<Default>`` element with attributes set to parameter values. """ default = CT_Default.new(ext, content_type) self.append(default)
[ "def", "add_default", "(", "self", ",", "ext", ",", "content_type", ")", ":", "default", "=", "CT_Default", ".", "new", "(", "ext", ",", "content_type", ")", "self", ".", "append", "(", "default", ")" ]
33
0.008439
def redirects_handler(*args, **kwargs): """Fixes Admin contrib redirects compatibility problems introduced in Django 1.4 by url handling changes. """ path = args[0].path shift = '../' if 'delete' in path: # Weird enough 'delete' is not handled by TreeItemAdmin::response_change(). ...
[ "def", "redirects_handler", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "path", "=", "args", "[", "0", "]", ".", "path", "shift", "=", "'../'", "if", "'delete'", "in", "path", ":", "# Weird enough 'delete' is not handled by TreeItemAdmin::response_chang...
31.882353
0.005376
def eccentricity(self): """ The eccentricity of the 2D Gaussian function that has the same second-order moments as the source. The eccentricity is the fraction of the distance along the semimajor axis at which the focus lies. .. math:: e = \\sqrt{1 - \\frac{b^2}{a^2}} ...
[ "def", "eccentricity", "(", "self", ")", ":", "l1", ",", "l2", "=", "self", ".", "covariance_eigvals", "if", "l1", "==", "0", ":", "return", "0.", "# pragma: no cover", "return", "np", ".", "sqrt", "(", "1.", "-", "(", "l2", "/", "l1", ")", ")" ]
31.666667
0.003407
def main(): """Builds a yaml file""" parser = argparse.ArgumentParser(description='Compose a yaml file.') parser.add_argument( 'root', type=argparse.FileType('r'), help='The root yaml file to compose.' ) args = parser.parse_args() result = yaml.load(args.root, Loader=Co...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Compose a yaml file.'", ")", "parser", ".", "add_argument", "(", "'root'", ",", "type", "=", "argparse", ".", "FileType", "(", "'r'", ")", ",", "help...
24.928571
0.002762
def _msg(self, label, *msg): """ Prints a message with a label """ if self.quiet is False: txt = self._unpack_msg(*msg) print("[" + label + "] " + txt)
[ "def", "_msg", "(", "self", ",", "label", ",", "*", "msg", ")", ":", "if", "self", ".", "quiet", "is", "False", ":", "txt", "=", "self", ".", "_unpack_msg", "(", "*", "msg", ")", "print", "(", "\"[\"", "+", "label", "+", "\"] \"", "+", "txt", "...
28.714286
0.009662
def validate_config_file(cls, config_filepath): """ Validates the filepath to the config. Detects whether it is a true YAML file + existance :param config_filepath: str, file path to the config file to query :return: None :raises: IOError """ is_file = os.path.isfile(co...
[ "def", "validate_config_file", "(", "cls", ",", "config_filepath", ")", ":", "is_file", "=", "os", ".", "path", ".", "isfile", "(", "config_filepath", ")", "if", "not", "is_file", "and", "os", ".", "path", ".", "isabs", "(", "config_filepath", ")", ":", ...
44.777778
0.006075
def construct_1d_ndarray_preserving_na(values, dtype=None, copy=False): """ Construct a new ndarray, coercing `values` to `dtype`, preserving NA. Parameters ---------- values : Sequence dtype : numpy.dtype, optional copy : bool, default False Note that copies may still be made with ...
[ "def", "construct_1d_ndarray_preserving_na", "(", "values", ",", "dtype", "=", "None", ",", "copy", "=", "False", ")", ":", "subarr", "=", "np", ".", "array", "(", "values", ",", "dtype", "=", "dtype", ",", "copy", "=", "copy", ")", "if", "dtype", "is"...
29.575
0.000818
def changed(self, path_info, checksum_info): """Checks if data has changed. A file is considered changed if: - It doesn't exist on the working directory (was unlinked) - Checksum is not computed (saving a new file) - The checkusm stored in the State is different from...
[ "def", "changed", "(", "self", ",", "path_info", ",", "checksum_info", ")", ":", "logger", ".", "debug", "(", "\"checking if '{}'('{}') has changed.\"", ".", "format", "(", "path_info", ",", "checksum_info", ")", ")", "if", "not", "self", ".", "exists", "(", ...
32.183673
0.001231
def _get_namedrange(book, rangename, sheetname=None): """Get range from a workbook. A workbook can contain multiple definitions for a single name, as a name can be defined for the entire book or for a particular sheet. If sheet is None, the book-wide def is searched, otherwise sheet-local def ...
[ "def", "_get_namedrange", "(", "book", ",", "rangename", ",", "sheetname", "=", "None", ")", ":", "def", "cond", "(", "namedef", ")", ":", "if", "namedef", ".", "type", ".", "upper", "(", ")", "==", "\"RANGE\"", ":", "if", "namedef", ".", "name", "."...
29.17284
0.000409
def get_readonly_field_data(field_name, instance, view=None, fun_kwargs=None): """ Returns field humanized value, label and widget which are used to display of instance or view readonly data. Args: field_name: name of the field which will be displayed instance: model instance view: v...
[ "def", "get_readonly_field_data", "(", "field_name", ",", "instance", ",", "view", "=", "None", ",", "fun_kwargs", "=", "None", ")", ":", "fun_kwargs", "=", "fun_kwargs", "or", "{", "}", "if", "view", ":", "view_readonly_data", "=", "_get_view_readonly_data", ...
38.583333
0.005269
def inet_ntop(af, addr): """Convert an IP address from binary form into text represenation""" if af == socket.AF_INET: return inet_ntoa(addr) elif af == socket.AF_INET6: # IPv6 addresses have 128bits (16 bytes) if len(addr) != 16: raise Exception("Illegal syntax for IP ad...
[ "def", "inet_ntop", "(", "af", ",", "addr", ")", ":", "if", "af", "==", "socket", ".", "AF_INET", ":", "return", "inet_ntoa", "(", "addr", ")", "elif", "af", "==", "socket", ".", "AF_INET6", ":", "# IPv6 addresses have 128bits (16 bytes)", "if", "len", "("...
41.740741
0.001735
def upsert(self, document, cond): """ Update a document, if it exist - insert it otherwise. Note: this will update *all* documents matching the query. :param document: the document to insert or the fields to update :param cond: which document to look for :returns: a lis...
[ "def", "upsert", "(", "self", ",", "document", ",", "cond", ")", ":", "updated_docs", "=", "self", ".", "update", "(", "document", ",", "cond", ")", "if", "updated_docs", ":", "return", "updated_docs", "else", ":", "return", "[", "self", ".", "insert", ...
32.5625
0.003731
def clean(self): """ Final validations of model fields. 1. Validate that selected site for enterprise customer matches with the selected identity provider's site. """ super(EnterpriseCustomerIdentityProviderAdminForm, self).clean() provider_id = self.cleaned_data.get('p...
[ "def", "clean", "(", "self", ")", ":", "super", "(", "EnterpriseCustomerIdentityProviderAdminForm", ",", "self", ")", ".", "clean", "(", ")", "provider_id", "=", "self", ".", "cleaned_data", ".", "get", "(", "'provider_id'", ",", "None", ")", "enterprise_custo...
44.880952
0.003634
def get_instances(device_owners=None, vnic_type=None, instance_id=None): """Returns filtered list of all instances in the neutron db""" session = db.get_reader_session() with session.begin(): port_model = models_v2.Port binding_model = ml2_models.PortBinding instances = (session ...
[ "def", "get_instances", "(", "device_owners", "=", "None", ",", "vnic_type", "=", "None", ",", "instance_id", "=", "None", ")", ":", "session", "=", "db", ".", "get_reader_session", "(", ")", "with", "session", ".", "begin", "(", ")", ":", "port_model", ...
46
0.001183
def update_keyjar(keyjar): """ Go through the whole key jar, key bundle by key bundle and update them one by one. :param keyjar: The key jar to update """ for iss, kbl in keyjar.items(): for kb in kbl: kb.update()
[ "def", "update_keyjar", "(", "keyjar", ")", ":", "for", "iss", ",", "kbl", "in", "keyjar", ".", "items", "(", ")", ":", "for", "kb", "in", "kbl", ":", "kb", ".", "update", "(", ")" ]
24.9
0.003876
def _setup_logger(self): '''Set up a logger.''' log = logging.getLogger('latexmk.py') handler = logging.StreamHandler() log.addHandler(handler) if self.opt.verbose: log.setLevel(logging.INFO) return log
[ "def", "_setup_logger", "(", "self", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "'latexmk.py'", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "log", ".", "addHandler", "(", "handler", ")", "if", "self", ".", "opt", ".", "...
25.5
0.007576
def closure_for_targets(cls, target_roots, exclude_scopes=None, include_scopes=None, bfs=None, postorder=None, respect_intransitive=False): """Computes the closure of the given targets respecting the given input scopes. :API: public :param list target_roots: The list of Targets t...
[ "def", "closure_for_targets", "(", "cls", ",", "target_roots", ",", "exclude_scopes", "=", "None", ",", "include_scopes", "=", "None", ",", "bfs", "=", "None", ",", "postorder", "=", "None", ",", "respect_intransitive", "=", "False", ")", ":", "target_roots", ...
45.844444
0.008068
def fermi_fourier_trans_inverse_conjugate_4(qubits): """We will need to map the momentum states in the reversed order for spin-down states to the position picture. This transformation can be simply implemented the complex conjugate of the former one. We only need to change the S gate to S* = S ** 3. ...
[ "def", "fermi_fourier_trans_inverse_conjugate_4", "(", "qubits", ")", ":", "yield", "fswap", "(", "qubits", "[", "1", "]", ",", "qubits", "[", "2", "]", ")", ",", "yield", "fermi_fourier_trans_2", "(", "qubits", "[", "0", "]", ",", "qubits", "[", "1", "]...
39.944444
0.001359
def send_messages(self, email_messages): """Write all messages to the stream in a thread-safe way.""" if not email_messages: return with self._lock: try: stream_created = self.open() for message in email_messages: if six...
[ "def", "send_messages", "(", "self", ",", "email_messages", ")", ":", "if", "not", "email_messages", ":", "return", "with", "self", ".", "_lock", ":", "try", ":", "stream_created", "=", "self", ".", "open", "(", ")", "for", "message", "in", "email_messages...
35.210526
0.004367
def substitute(self, var_map, cont=False, tag=None): """Substitute sub-expressions both on the lhs and rhs Args: var_map (dict): Dictionary with entries of the form ``{expr: substitution}`` """ return self.apply(substitute, var_map=var_map, cont=cont, tag=tag...
[ "def", "substitute", "(", "self", ",", "var_map", ",", "cont", "=", "False", ",", "tag", "=", "None", ")", ":", "return", "self", ".", "apply", "(", "substitute", ",", "var_map", "=", "var_map", ",", "cont", "=", "cont", ",", "tag", "=", "tag", ")"...
39.25
0.006231
def switch_to_frame(driver, frame, timeout=settings.SMALL_TIMEOUT): """ Wait for an iframe to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.frame(). @Params driver - the webdriver object (required) frame - the frame element, name, or index time...
[ "def", "switch_to_frame", "(", "driver", ",", "frame", ",", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", ")", ":", "start_ms", "=", "time", ".", "time", "(", ")", "*", "1000.0", "stop_ms", "=", "start_ms", "+", "(", "timeout", "*", "1000.0", ")", ...
35.863636
0.001235
def surfaceIntersection(actor1, actor2, tol=1e-06, lw=3): """Intersect 2 surfaces and return a line actor. .. hint:: |surfIntersect.py|_ """ bf = vtk.vtkIntersectionPolyDataFilter() poly1 = actor1.GetMapper().GetInput() poly2 = actor2.GetMapper().GetInput() bf.SetInputData(0, poly1) bf....
[ "def", "surfaceIntersection", "(", "actor1", ",", "actor2", ",", "tol", "=", "1e-06", ",", "lw", "=", "3", ")", ":", "bf", "=", "vtk", ".", "vtkIntersectionPolyDataFilter", "(", ")", "poly1", "=", "actor1", ".", "GetMapper", "(", ")", ".", "GetInput", ...
31.785714
0.002183
def getBestMatchingSegment(self, c, i, activeState): """For the given cell, find the segment with the largest number of active synapses. This routine is aggressive in finding the best match. The permanence value of synapses is allowed to be below connectedPerm. The number of active synapses is allowed t...
[ "def", "getBestMatchingSegment", "(", "self", ",", "c", ",", "i", ",", "activeState", ")", ":", "maxActivity", ",", "which", "=", "self", ".", "minThreshold", ",", "-", "1", "for", "j", ",", "s", "in", "enumerate", "(", "self", ".", "cells", "[", "c"...
41.333333
0.009009
def write_xsd(cls) -> None: """Write the complete base schema file `HydPyConfigBase.xsd` based on the template file `HydPyConfigBase.xsdt`. Method |XSDWriter.write_xsd| adds model specific information to the general information of template file `HydPyConfigBase.xsdt` regarding r...
[ "def", "write_xsd", "(", "cls", ")", "->", "None", ":", "with", "open", "(", "cls", ".", "filepath_source", ")", "as", "file_", ":", "template", "=", "file_", ".", "read", "(", ")", "template", "=", "template", ".", "replace", "(", "'<!--include model se...
45.722222
0.00119
def _request(self, req_type, url, **kwargs): """ Make a request via the `requests` module. If the result has an HTTP error status, convert that to a Python exception. """ logger.debug('%s %s' % (req_type, url)) result = self.session.request(req_type, url, **kwargs) ...
[ "def", "_request", "(", "self", ",", "req_type", ",", "url", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'%s %s'", "%", "(", "req_type", ",", "url", ")", ")", "result", "=", "self", ".", "session", ".", "request", "(", "req_typ...
37.44
0.002083
def send_packet(self, packet): """ Sends a message to the Pebble. :param packet: The message to send. :type packet: .PebblePacket """ if self.log_packet_level: logger.log(self.log_packet_level, "-> %s", packet) serialised = packet.serialise_packet() ...
[ "def", "send_packet", "(", "self", ",", "packet", ")", ":", "if", "self", ".", "log_packet_level", ":", "logger", ".", "log", "(", "self", ".", "log_packet_level", ",", "\"-> %s\"", ",", "packet", ")", "serialised", "=", "packet", ".", "serialise_packet", ...
34.333333
0.004728
def calculate_new_length(gene_split, gene_results, hit): ''' Function for calcualting new length if the gene is split on several contigs ''' # Looping over splitted hits and calculate new length first = 1 for split in gene_split[hit['sbjct_header']]: new_start = int(gene_results[split]['sbjct_st...
[ "def", "calculate_new_length", "(", "gene_split", ",", "gene_results", ",", "hit", ")", ":", "# Looping over splitted hits and calculate new length", "first", "=", "1", "for", "split", "in", "gene_split", "[", "hit", "[", "'sbjct_header'", "]", "]", ":", "new_start"...
31.923077
0.02807
def resetdb(): """ Clear out the database """ from airflow import models # alembic adds significant import time, so we import it lazily from alembic.migration import MigrationContext log.info("Dropping tables that exist") models.base.Base.metadata.drop_all(settings.engine) mc = Mi...
[ "def", "resetdb", "(", ")", ":", "from", "airflow", "import", "models", "# alembic adds significant import time, so we import it lazily", "from", "alembic", ".", "migration", "import", "MigrationContext", "log", ".", "info", "(", "\"Dropping tables that exist\"", ")", "mo...
26.85
0.001799
def dates_to_keep(dates, years=0, months=0, weeks=0, days=0, firstweekday=SATURDAY, now=None): """ Return a set of dates that should be kept, out of ``dates``. See ``to_keep`` for a description of arguments. """ datetimes = to_keep((datetime.combine(d, time()) fo...
[ "def", "dates_to_keep", "(", "dates", ",", "years", "=", "0", ",", "months", "=", "0", ",", "weeks", "=", "0", ",", "days", "=", "0", ",", "firstweekday", "=", "SATURDAY", ",", "now", "=", "None", ")", ":", "datetimes", "=", "to_keep", "(", "(", ...
43
0.001751
def update(self): """Updates the currently running animation. This method should be called in every frame where you want an animation to run. Its job is to figure out if it is time to move onto the next image in the animation. """ returnValue = False # typical return va...
[ "def", "update", "(", "self", ")", ":", "returnValue", "=", "False", "# typical return value\r", "if", "self", ".", "state", "!=", "PygAnimation", ".", "PLAYING", ":", "return", "returnValue", "# The job here is to figure out the index of the image to show\r", "# and the ...
45.621622
0.0029
def read(self): """ Read pin value @rtype: int @return: I{0} when LOW, I{1} when HIGH """ val = self._fd.read() self._fd.seek(0) return int(val)
[ "def", "read", "(", "self", ")", ":", "val", "=", "self", ".", "_fd", ".", "read", "(", ")", "self", ".", "_fd", ".", "seek", "(", "0", ")", "return", "int", "(", "val", ")" ]
20
0.009569
def apply_clifford_to_pauli(self, clifford, pauli_in): r""" Given a circuit that consists only of elements of the Clifford group, return its action on a PauliTerm. In particular, for Clifford C, and Pauli P, this returns the PauliTerm representing CPC^{\dagger}. :param ...
[ "def", "apply_clifford_to_pauli", "(", "self", ",", "clifford", ",", "pauli_in", ")", ":", "# do nothing if `pauli_in` is the identity", "if", "is_identity", "(", "pauli_in", ")", ":", "return", "pauli_in", "indices_and_terms", "=", "list", "(", "zip", "(", "*", "...
48.028571
0.004665
def drop_table_with_environment_context(self, dbname, name, deleteData, environment_context): """ Parameters: - dbname - name - deleteData - environment_context """ self.send_drop_table_with_environment_context(dbname, name, deleteData, environment_context) self.recv_drop_table_w...
[ "def", "drop_table_with_environment_context", "(", "self", ",", "dbname", ",", "name", ",", "deleteData", ",", "environment_context", ")", ":", "self", ".", "send_drop_table_with_environment_context", "(", "dbname", ",", "name", ",", "deleteData", ",", "environment_co...
33.6
0.008696
def count_posts(self, tag=None, user_id=None, include_draft=False): """ Returns the total number of posts for the give filter :param tag: Filter by a specific tag :type tag: str :param user_id: Filter by a specific user :type user_id: str :param include_draft: Wh...
[ "def", "count_posts", "(", "self", ",", "tag", "=", "None", ",", "user_id", "=", "None", ",", "include_draft", "=", "False", ")", ":", "result", "=", "0", "with", "self", ".", "_engine", ".", "begin", "(", ")", "as", "conn", ":", "try", ":", "count...
41.4
0.001889
def do_replace(eval_ctx, s, old, new, count=None): """Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the fir...
[ "def", "do_replace", "(", "eval_ctx", ",", "s", ",", "old", ",", "new", ",", "count", "=", "None", ")", ":", "if", "count", "is", "None", ":", "count", "=", "-", "1", "if", "not", "eval_ctx", ".", "autoescape", ":", "return", "unicode", "(", "s", ...
36.56
0.001066
def register(self, callback_id: str, handler: Any, name: str = "*") -> None: """ Register a new handler for a specific :class:`slack.actions.Action` `callback_id`. Optional routing based on the action name too. The name argument is useful for actions of type `interactive_message` to pro...
[ "def", "register", "(", "self", ",", "callback_id", ":", "str", ",", "handler", ":", "Any", ",", "name", ":", "str", "=", "\"*\"", ")", "->", "None", ":", "LOG", ".", "info", "(", "\"Registering %s, %s to %s\"", ",", "callback_id", ",", "name", ",", "h...
42.444444
0.005122
def all_fields(self): """A list with all the fields contained in this object.""" return [field for container in FieldsContainer.class_container.values() for field in getattr(self, container)]
[ "def", "all_fields", "(", "self", ")", ":", "return", "[", "field", "for", "container", "in", "FieldsContainer", ".", "class_container", ".", "values", "(", ")", "for", "field", "in", "getattr", "(", "self", ",", "container", ")", "]" ]
47.2
0.0125
def shortcut_show(self, shortcut_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/shortcuts#get-shortcut" api_path = "/api/v2/shortcuts/{shortcut_id}" api_path = api_path.format(shortcut_id=shortcut_id) return self.call(api_path, **kwargs)
[ "def", "shortcut_show", "(", "self", ",", "shortcut_id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/shortcuts/{shortcut_id}\"", "api_path", "=", "api_path", ".", "format", "(", "shortcut_id", "=", "shortcut_id", ")", "return", "self", ".", ...
56.6
0.010453
def get_gists(self, since=github.GithubObject.NotSet): """ :calls: `GET /gists <http://developer.github.com/v3/gists>`_ :param since: datetime.datetime format YYYY-MM-DDTHH:MM:SSZ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Gist.Gist` """ assert ...
[ "def", "get_gists", "(", "self", ",", "since", "=", "github", ".", "GithubObject", ".", "NotSet", ")", ":", "assert", "since", "is", "github", ".", "GithubObject", ".", "NotSet", "or", "isinstance", "(", "since", ",", "datetime", ".", "datetime", ")", ",...
44.6875
0.005479
def endpoint(self, *args): """endpoint: Decorates a function to make it a CLI endpoint The function must be called do_<some>_<action> and accept one 'args' parameter. It will be converted into a ./cli some action commandline endpoint. A set of Arguments can be p...
[ "def", "endpoint", "(", "self", ",", "*", "args", ")", ":", "# Decorator function", "def", "decorator", "(", "func", ")", ":", "func_name", "=", "func", ".", "__name__", "func_name", "=", "func_name", ".", "replace", "(", "\"do_\"", ",", "\"\"", ")", "ac...
46.160714
0.003409
def compute_allocated_size(size, is_encrypted): # type: (int, bool) -> int """Compute allocated size on disk :param int size: size (content length) :param bool is_ecrypted: if entity is encrypted :rtype: int :return: required size on disk """ # compute siz...
[ "def", "compute_allocated_size", "(", "size", ",", "is_encrypted", ")", ":", "# type: (int, bool) -> int", "# compute size", "if", "size", ">", "0", ":", "if", "is_encrypted", ":", "# cipher_len_without_iv = (clear_len / aes_bs + 1) * aes_bs", "allocatesize", "=", "(", "s...
37.434783
0.003398
def text_width(string, font_name, font_size): """Determine with width in pixels of string.""" return stringWidth(string, fontName=font_name, fontSize=font_size)
[ "def", "text_width", "(", "string", ",", "font_name", ",", "font_size", ")", ":", "return", "stringWidth", "(", "string", ",", "fontName", "=", "font_name", ",", "fontSize", "=", "font_size", ")" ]
55.333333
0.005952
def put(self, path=None, method='PUT', **options): """ Equals :meth:`route` with a ``PUT`` method parameter. """ return self.route(path, method, **options)
[ "def", "put", "(", "self", ",", "path", "=", "None", ",", "method", "=", "'PUT'", ",", "*", "*", "options", ")", ":", "return", "self", ".", "route", "(", "path", ",", "method", ",", "*", "*", "options", ")" ]
56.333333
0.011696
def update(self): """ Upates the user's SDB inventory Loops through all items on a page and checks for an item that has changed. A changed item is identified as the remove attribute being set to anything greater than 0. It will then update each page accordingly with the ...
[ "def", "update", "(", "self", ")", ":", "for", "x", "in", "range", "(", "1", ",", "self", ".", "inventory", ".", "pages", "+", "1", ")", ":", "if", "self", ".", "_hasPageChanged", "(", "x", ")", ":", "form", "=", "self", ".", "_updateForm", "(", ...
41.26087
0.006179
def AddClusterTags(r, tags, dry_run=False): """ Adds tags to the cluster. @type tags: list of str @param tags: tags to add to the cluster @type dry_run: bool @param dry_run: whether to perform a dry run @rtype: int @return: job id """ query = { "dry-run": dry_run, ...
[ "def", "AddClusterTags", "(", "r", ",", "tags", ",", "dry_run", "=", "False", ")", ":", "query", "=", "{", "\"dry-run\"", ":", "dry_run", ",", "\"tag\"", ":", "tags", ",", "}", "return", "r", ".", "request", "(", "\"put\"", ",", "\"/2/tags\"", ",", "...
19.842105
0.002532
def openid_form(parser, token): """ Render OpenID form. Allows to pre set the provider:: {% openid_form "https://www.google.com/accounts/o8/id" %} Also creates custom button URLs by concatenating all arguments after the provider's URL {% openid_form "https://www.google.com/accounts/o8/id" S...
[ "def", "openid_form", "(", "parser", ",", "token", ")", ":", "bits", "=", "get_bits", "(", "token", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "return", "FormNode", "(", "bits", "[", "0", "]", ",", "bits", "[", "1", ":", "]", ")", "if",...
26.05
0.011111
def description_director(**kwargs): """Direct which class should be used based on the director qualifier. """ description_type = {'physical': DCFormat} qualifier = kwargs.get('qualifier') # Determine the type of element needed, based on the qualifier. element_class = description_type.get(qu...
[ "def", "description_director", "(", "*", "*", "kwargs", ")", ":", "description_type", "=", "{", "'physical'", ":", "DCFormat", "}", "qualifier", "=", "kwargs", ".", "get", "(", "'qualifier'", ")", "# Determine the type of element needed, based on the qualifier.", "ele...
36.142857
0.001927
def process_import_request(username, path, timestamp, logger_handler): """ React to import request. Look into user's directory and react to files user uploaded there. Behavior of this function can be set by setting variables in :mod:`ftp.settings`. Args: username (str): Name of the use...
[ "def", "process_import_request", "(", "username", ",", "path", ",", "timestamp", ",", "logger_handler", ")", ":", "items", "=", "[", "]", "error_protocol", "=", "[", "]", "# import logger into local namespace", "global", "logger", "logger", "=", "logger_handler", ...
34.829268
0.000227
def fetch(self): """ Fetch a UserBindingInstance :returns: Fetched UserBindingInstance :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, ...
[ "def", "fetch", "(", "self", ")", ":", "params", "=", "values", ".", "of", "(", "{", "}", ")", "payload", "=", "self", ".", "_version", ".", "fetch", "(", "'GET'", ",", "self", ".", "_uri", ",", "params", "=", "params", ",", ")", "return", "UserB...
26
0.005059
def release(self): """Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after ...
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "__owner", "!=", "_get_ident", "(", ")", ":", "raise", "RuntimeError", "(", "\"cannot release un-acquired lock\"", ")", "self", ".", "__count", "=", "count", "=", "self", ".", "__count", "-", "1",...
39.62963
0.002737
def doRollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of ...
[ "def", "doRollover", "(", "self", ")", ":", "# if self.stream:", "# self.stream.close()", "# get the time that this sequence started at and make it a TimeTuple", "t", "=", "self", ".", "rolloverAt", "-", "self", ".", "interval", "if", "self", ".", "utc", ":", "timeTu...
47.211538
0.003192
def interact(self, msg='SHUTIT PAUSE POINT', shutit_pexpect_child=None, print_input=True, level=1, resize=True, color='32', default_msg=None, wait=-1): """Same as pause_point, but sets up the terminal ready for unm...
[ "def", "interact", "(", "self", ",", "msg", "=", "'SHUTIT PAUSE POINT'", ",", "shutit_pexpect_child", "=", "None", ",", "print_input", "=", "True", ",", "level", "=", "1", ",", "resize", "=", "True", ",", "color", "=", "'32'", ",", "default_msg", "=", "N...
34.190476
0.051491
def string_range(last): """Compute the range of string between "a" and last. This works for simple "a to z" lists, but also for "a to zz" lists. """ for k in range(len(last)): for x in product(string.ascii_lowercase, repeat=k+1): result = ''.join(x) yield result ...
[ "def", "string_range", "(", "last", ")", ":", "for", "k", "in", "range", "(", "len", "(", "last", ")", ")", ":", "for", "x", "in", "product", "(", "string", ".", "ascii_lowercase", ",", "repeat", "=", "k", "+", "1", ")", ":", "result", "=", "''",...
32.272727
0.00274
def iter_attrs( idx_bytes ): ''' called when idx_chars is just past "<a " inside an HTML anchor tag generates tuple(end_idx, attr_name, attr_value) ''' ## read to the end of the "A" tag while 1: idx, attr_name, next_b = read_to(idx_bytes, ['=', '>']) attr_vals = [] ...
[ "def", "iter_attrs", "(", "idx_bytes", ")", ":", "## read to the end of the \"A\" tag", "while", "1", ":", "idx", ",", "attr_name", ",", "next_b", "=", "read_to", "(", "idx_bytes", ",", "[", "'='", ",", "'>'", "]", ")", "attr_vals", "=", "[", "]", "## stop...
35.071429
0.015857
def filter_signal(self, data_frame, ts='mag_sum_acc'): """ This method filters a data frame signal as suggested in :cite:`Kassavetis2015`. First step is to high \ pass filter the data frame using a \ `Butterworth <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/sc...
[ "def", "filter_signal", "(", "self", ",", "data_frame", ",", "ts", "=", "'mag_sum_acc'", ")", ":", "b", ",", "a", "=", "signal", ".", "butter", "(", "self", ".", "filter_order", ",", "2", "*", "self", ".", "cutoff_frequency", "/", "self", ".", "samplin...
54.863636
0.006515
def on_pause(self): """Sync the database with the current state of the game.""" self.engine.commit() self.strings.save() self.funcs.save() self.config.write()
[ "def", "on_pause", "(", "self", ")", ":", "self", ".", "engine", ".", "commit", "(", ")", "self", ".", "strings", ".", "save", "(", ")", "self", ".", "funcs", ".", "save", "(", ")", "self", ".", "config", ".", "write", "(", ")" ]
32.166667
0.010101
def timezone(self, lat, lon, datetime, language=None, sensor=None): """Get time offset data for given location. :param lat: Latitude of queried point :param lon: Longitude of queried point :param language: The language in which to return results. For full list ...
[ "def", "timezone", "(", "self", ",", "lat", ",", "lon", ",", "datetime", ",", "language", "=", "None", ",", "sensor", "=", "None", ")", ":", "parameters", "=", "dict", "(", "location", "=", "\"%f,%f\"", "%", "(", "lat", ",", "lon", ")", ",", "times...
42.173913
0.003024
def encode_setid(uint128): """Encode uint128 setid as stripped b32encoded string""" hi, lo = divmod(uint128, 2**64) return b32encode(struct.pack('<QQ', lo, hi))[:-6].lower()
[ "def", "encode_setid", "(", "uint128", ")", ":", "hi", ",", "lo", "=", "divmod", "(", "uint128", ",", "2", "**", "64", ")", "return", "b32encode", "(", "struct", ".", "pack", "(", "'<QQ'", ",", "lo", ",", "hi", ")", ")", "[", ":", "-", "6", "]"...
45.5
0.005405
def search_book(self, anywords, page=1): """ 检索图书 :param anywords: 检索关键字 :param page: 页码 :return: 图书列表 """ result = [] html = self.__search_book_html(anywords, page) soup = BeautifulSoup(html) tds = soup.select(selector='tbody')[0].select('...
[ "def", "search_book", "(", "self", ",", "anywords", ",", "page", "=", "1", ")", ":", "result", "=", "[", "]", "html", "=", "self", ".", "__search_book_html", "(", "anywords", ",", "page", ")", "soup", "=", "BeautifulSoup", "(", "html", ")", "tds", "=...
33.820513
0.001474
def get_last_modified_timestamp(self): """ Looks at the files in a git root directory and grabs the last modified timestamp """ cmd = "find . -print0 | xargs -0 stat -f '%T@ %p' | sort -n | tail -1 | cut -f2- -d' '" ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stde...
[ "def", "get_last_modified_timestamp", "(", "self", ")", ":", "cmd", "=", "\"find . -print0 | xargs -0 stat -f '%T@ %p' | sort -n | tail -1 | cut -f2- -d' '\"", "ps", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess"...
49
0.02005
def next_minifat(self, current): """ Helpers provides access to next mini-FAT sector and returns it's seekable position. Should not be called from external code. """ position = 0 sector_size = self.header.sector_size // 4 sector = self.header.minifat_sector_start ...
[ "def", "next_minifat", "(", "self", ",", "current", ")", ":", "position", "=", "0", "sector_size", "=", "self", ".", "header", ".", "sector_size", "//", "4", "sector", "=", "self", ".", "header", ".", "minifat_sector_start", "while", "sector", "!=", "ENDOF...
34.9
0.002789
def preprocess_for_eval(image, image_size=224, normalize=True): """Preprocesses the given image for evaluation. Args: image: `Tensor` representing an image of arbitrary size. image_size: int, how large the output image should be. normalize: bool, if True the image is normalized. Returns: A prepr...
[ "def", "preprocess_for_eval", "(", "image", ",", "image_size", "=", "224", ",", "normalize", "=", "True", ")", ":", "if", "normalize", ":", "image", "=", "tf", ".", "to_float", "(", "image", ")", "/", "255.0", "image", "=", "_do_scale", "(", "image", "...
34.352941
0.016667
def pop_range(self, start, stop=None, withscores=True, **options): '''Remove and return a range from the ordered set by score.''' return self.backend.execute( self.client.zpopbyscore(self.id, start, stop, withscores=withscores, **options), ...
[ "def", "pop_range", "(", "self", ",", "start", ",", "stop", "=", "None", ",", "withscores", "=", "True", ",", "*", "*", "options", ")", ":", "return", "self", ".", "backend", ".", "execute", "(", "self", ".", "client", ".", "zpopbyscore", "(", "self"...
58.166667
0.00565
def _trim_xpath(self, xpath, prop): """ Removes primitive type tags from an XPATH """ xroot = self._get_xroot_for(prop) if xroot is None and isinstance(xpath, string_types): xtags = xpath.split(XPATH_DELIM) if xtags[-1] in _iso_tag_primitives: xroot = X...
[ "def", "_trim_xpath", "(", "self", ",", "xpath", ",", "prop", ")", ":", "xroot", "=", "self", ".", "_get_xroot_for", "(", "prop", ")", "if", "xroot", "is", "None", "and", "isinstance", "(", "xpath", ",", "string_types", ")", ":", "xtags", "=", "xpath",...
29.833333
0.00542
def inc_ptr(self, ptr): """Get next circular buffer data pointer.""" result = ptr + self.reading_len[self.ws_type] if result >= 0x10000: result = self.data_start return result
[ "def", "inc_ptr", "(", "self", ",", "ptr", ")", ":", "result", "=", "ptr", "+", "self", ".", "reading_len", "[", "self", ".", "ws_type", "]", "if", "result", ">=", "0x10000", ":", "result", "=", "self", ".", "data_start", "return", "result" ]
35.666667
0.009132
def read(self, entity=None, attrs=None, ignore=None, params=None): """Provide a default value for ``entity``. By default, ``nailgun.entity_mixins.EntityReadMixin.read`` provides a default value for ``entity`` like so:: entity = type(self)() However, :class:`SSHKey` require...
[ "def", "read", "(", "self", ",", "entity", "=", "None", ",", "attrs", "=", "None", ",", "ignore", "=", "None", ",", "params", "=", "None", ")", ":", "# read() should not change the state of the object it's called on, but", "# super() alters the attributes of any entity ...
38.884615
0.001931
def daterange(self, datecol, date_start, op, **args): """ Returns rows in a date range """ df = self._daterange(datecol, date_start, op, **args) if df is None: self.err("Can not select date range data") self.df = df
[ "def", "daterange", "(", "self", ",", "datecol", ",", "date_start", ",", "op", ",", "*", "*", "args", ")", ":", "df", "=", "self", ".", "_daterange", "(", "datecol", ",", "date_start", ",", "op", ",", "*", "*", "args", ")", "if", "df", "is", "Non...
33.5
0.007273
def create_certificate(self, cert_info, request=False, valid_from=0, valid_to=315360000, sn=1, key_length=1024, hash_alg="sha256", write_to_file=False, cert_dir="", cipher_passphrase=None): """ Can create certificate reques...
[ "def", "create_certificate", "(", "self", ",", "cert_info", ",", "request", "=", "False", ",", "valid_from", "=", "0", ",", "valid_to", "=", "315360000", ",", "sn", "=", "1", ",", "key_length", "=", "1024", ",", "hash_alg", "=", "\"sha256\"", ",", "write...
48.417808
0.001525
def read_file(filename, mode="r", readlines=True): '''write_file will open a file, "filename" and write content, "content" and properly close the file ''' with open(filename, mode) as filey: if readlines is True: content = filey.readlines() else: content = file...
[ "def", "read_file", "(", "filename", ",", "mode", "=", "\"r\"", ",", "readlines", "=", "True", ")", ":", "with", "open", "(", "filename", ",", "mode", ")", "as", "filey", ":", "if", "readlines", "is", "True", ":", "content", "=", "filey", ".", "readl...
33.8
0.002882
def ls(obj=None): """List available layers, or infos on a given layer""" if obj is None: import builtins all = builtins.__dict__.copy() all.update(globals()) objlst = sorted(conf.layers, key=lambda x:x.__name__) for o in objlst: print("%-10s : %s" %(...
[ "def", "ls", "(", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "import", "builtins", "all", "=", "builtins", ".", "__dict__", ".", "copy", "(", ")", "all", ".", "update", "(", "globals", "(", ")", ")", "objlst", "=", "sorted", "(...
39.666667
0.010256
def run(self): """ Writes data in JSON format into the task's output target. The data objects have the following attributes: * `_id` is the default Elasticsearch id field, * `text`: the text, * `date`: the day when the data was created. """ today = date...
[ "def", "run", "(", "self", ")", ":", "today", "=", "datetime", ".", "date", ".", "today", "(", ")", "with", "self", ".", "output", "(", ")", ".", "open", "(", "'w'", ")", "as", "output", ":", "for", "i", "in", "range", "(", "5", ")", ":", "ou...
33.529412
0.003413
def _is_in_restart(self, x, y): """Checks if the game is to be restarted by request.""" x1, y1, x2, y2 = self._new_game return x1 <= x < x2 and y1 <= y < y2
[ "def", "_is_in_restart", "(", "self", ",", "x", ",", "y", ")", ":", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "self", ".", "_new_game", "return", "x1", "<=", "x", "<", "x2", "and", "y1", "<=", "y", "<", "y2" ]
44.25
0.011111
def get_sorted_structure(self, key=None, reverse=False): """ Get a sorted copy of the structure. The parameters have the same meaning as in list.sort. By default, sites are sorted by the electronegativity of the species. Note that Slab has to override this because of the differen...
[ "def", "get_sorted_structure", "(", "self", ",", "key", "=", "None", ",", "reverse", "=", "False", ")", ":", "sites", "=", "sorted", "(", "self", ",", "key", "=", "key", ",", "reverse", "=", "reverse", ")", "s", "=", "Structure", ".", "from_sites", "...
53.55
0.001835
def libvlc_video_take_snapshot(p_mi, num, psz_filepath, i_width, i_height): '''Take a snapshot of the current video window. If i_width AND i_height is 0, original size is used. If i_width XOR i_height is 0, original aspect-ratio is preserved. @param p_mi: media player instance. @param num: number of...
[ "def", "libvlc_video_take_snapshot", "(", "p_mi", ",", "num", ",", "psz_filepath", ",", "i_width", ",", "i_height", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_take_snapshot'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_take...
59.533333
0.00441
def initiate_sniff(self, initial=False): """ Initiate a sniffing task. Make sure we only have one sniff request running at any given time. If a finished sniffing request is around, collect its result (which can raise its exception). """ if self.sniffing_task and self.snif...
[ "def", "initiate_sniff", "(", "self", ",", "initial", "=", "False", ")", ":", "if", "self", ".", "sniffing_task", "and", "self", ".", "sniffing_task", ".", "done", "(", ")", ":", "try", ":", "if", "self", ".", "sniffing_task", "is", "not", "None", ":",...
40.055556
0.00542
def do_child_matches(self, params): """ \x1b[1mNAME\x1b[0m child_matches - Prints paths that have at least 1 child that matches <pattern> \x1b[1mSYNOPSIS\x1b[0m child_matches <path> <pattern> [inverse] \x1b[1mOPTIONS\x1b[0m * inverse: display paths which don't match (default: false) \...
[ "def", "do_child_matches", "(", "self", ",", "params", ")", ":", "seen", "=", "set", "(", ")", "# we don't want to recurse once there's a child matching, hence exclude_recurse=", "for", "path", "in", "self", ".", "_zk", ".", "fast_tree", "(", "params", ".", "path", ...
29.611111
0.004541
async def getLiftRows(self, lops): ''' Yield row tuples from a series of lift operations. Row tuples only requirement is that the first element be the binary id of a node. Args: lops (list): A list of lift operations. Yields: (tuple): (layer_ind...
[ "async", "def", "getLiftRows", "(", "self", ",", "lops", ")", ":", "for", "layeridx", ",", "layr", "in", "enumerate", "(", "self", ".", "layers", ")", ":", "async", "for", "x", "in", "layr", ".", "getLiftRows", "(", "lops", ")", ":", "yield", "layeri...
29.8125
0.004065
def route(vertices_resources, nets, machine, constraints, placements, allocations={}, core_resource=Cores, radius=20): """Routing algorithm based on Neighbour Exploring Routing (NER). Algorithm refrence: J. Navaridas et al. SpiNNaker: Enhanced multicast routing, Parallel Computing (2014). htt...
[ "def", "route", "(", "vertices_resources", ",", "nets", ",", "machine", ",", "constraints", ",", "placements", ",", "allocations", "=", "{", "}", ",", "core_resource", "=", "Cores", ",", "radius", "=", "20", ")", ":", "wrap_around", "=", "machine", ".", ...
44.442623
0.000361
def _generate_auth_token(self, channel_name): """Generate a token for authentication with the given channel. :param str channel_name: Name of the channel to generate a signature for. :rtype: str """ subject = "{}:{}".format(self.connection.socket_id, channel_name) h = hm...
[ "def", "_generate_auth_token", "(", "self", ",", "channel_name", ")", ":", "subject", "=", "\"{}:{}\"", ".", "format", "(", "self", ".", "connection", ".", "socket_id", ",", "channel_name", ")", "h", "=", "hmac", ".", "new", "(", "self", ".", "secret_as_by...
42.090909
0.008457
def webIDToStoreID(key, webid): """ Takes a webid (a 16-character str suitable for including in URLs) and a key (an int, a private key for decoding it) and produces a storeID. """ if len(webid) != 16: return None try: int(webid, 16) except TypeError: return None e...
[ "def", "webIDToStoreID", "(", "key", ",", "webid", ")", ":", "if", "len", "(", "webid", ")", "!=", "16", ":", "return", "None", "try", ":", "int", "(", "webid", ",", "16", ")", "except", "TypeError", ":", "return", "None", "except", "ValueError", ":"...
26.578947
0.003824
def adupdates(x, g, L, stepsize, inner_stepsizes, niter, random=False, callback=None, callback_loop='outer'): r"""Alternating Dual updates method. The Alternating Dual (AD) updates method of McGaffin and Fessler `[MF2015] <http://ieeexplore.ieee.org/document/7271047/>`_ is designed to solve a...
[ "def", "adupdates", "(", "x", ",", "g", ",", "L", ",", "stepsize", ",", "inner_stepsizes", ",", "niter", ",", "random", "=", "False", ",", "callback", "=", "None", ",", "callback_loop", "=", "'outer'", ")", ":", "# Check the lenghts of the lists (= number of d...
42.517045
0.000131
def encrypted_gradient(self, sum_to=None): """Compute and encrypt gradient. When `sum_to` is given, sum the encrypted gradient to it, assumed to be another vector of the same size """ gradient = self.compute_gradient() encrypted_gradient = encrypt_vector(self.pubkey, gra...
[ "def", "encrypted_gradient", "(", "self", ",", "sum_to", "=", "None", ")", ":", "gradient", "=", "self", ".", "compute_gradient", "(", ")", "encrypted_gradient", "=", "encrypt_vector", "(", "self", ".", "pubkey", ",", "gradient", ")", "if", "sum_to", "is", ...
35.923077
0.004175
def operate(self, left, right, operation): """ Do operation on colors args: left (str): left side right (str): right side operation (str): Operation returns: str """ operation = { '+': operator.add, '-': oper...
[ "def", "operate", "(", "self", ",", "left", ",", "right", ",", "operation", ")", ":", "operation", "=", "{", "'+'", ":", "operator", ".", "add", ",", "'-'", ":", "operator", ".", "sub", ",", "'*'", ":", "operator", ".", "mul", ",", "'/'", ":", "o...
27.625
0.004376