text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def info_update(self, obj_id, data): '''Update metadata with of a specified object. See http://msdn.microsoft.com/en-us/library/live/hh243648.aspx for the list of RW keys for each object type.''' return self(obj_id, method='put', data=data, auth_header=True)
[ "def", "info_update", "(", "self", ",", "obj_id", ",", "data", ")", ":", "return", "self", "(", "obj_id", ",", "method", "=", "'put'", ",", "data", "=", "data", ",", "auth_header", "=", "True", ")" ]
53
0.022305
def load_builtin_plugins(category=None, overwrite=False): """load plugins from builtin directories Parameters ---------- name: None or str category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugin...
[ "def", "load_builtin_plugins", "(", "category", "=", "None", ",", "overwrite", "=", "False", ")", ":", "# noqa: E501", "load_errors", "=", "[", "]", "for", "cat", ",", "path", "in", "_plugins_builtin", ".", "items", "(", ")", ":", "if", "cat", "!=", "cat...
41.040816
0.000486
def activate(): '''Activate an existing user (validate their email confirmation)''' email = click.prompt('Email') user = User.objects(email=email).first() if not user: exit_with_error('Invalid user') if user.confirmed_at is not None: exit_with_error('User email address already confir...
[ "def", "activate", "(", ")", ":", "email", "=", "click", ".", "prompt", "(", "'Email'", ")", "user", "=", "User", ".", "objects", "(", "email", "=", "email", ")", ".", "first", "(", ")", "if", "not", "user", ":", "exit_with_error", "(", "'Invalid use...
35.833333
0.002268
def detectMeegoPhone(self): """Return detection of a Meego phone Detects a phone running the Meego OS. """ return UAgentInfo.deviceMeego in self.__userAgent \ and UAgentInfo.mobi in self.__userAgent
[ "def", "detectMeegoPhone", "(", "self", ")", ":", "return", "UAgentInfo", ".", "deviceMeego", "in", "self", ".", "__userAgent", "and", "UAgentInfo", ".", "mobi", "in", "self", ".", "__userAgent" ]
33.857143
0.00823
def assign_power_curve(self, weather_df): r""" Calculates the power curve of the wind turbine cluster. The power curve is aggregated from the wind farms' and wind turbines' power curves by using :func:`power_plant.assign_power_curve`. Depending on the parameters of the WindTurbi...
[ "def", "assign_power_curve", "(", "self", ",", "weather_df", ")", ":", "# Set turbulence intensity for assigning power curve", "turbulence_intensity", "=", "(", "weather_df", "[", "'turbulence_intensity'", "]", ".", "values", ".", "mean", "(", ")", "if", "'turbulence_in...
46.892308
0.000643
def hopcroft(self): """ Performs the Hopcroft minimization algorithm Args: None Returns: DFA: The minimized input DFA """ def _getset(testset, partition): """ Checks if a set is in a partition Args: ...
[ "def", "hopcroft", "(", "self", ")", ":", "def", "_getset", "(", "testset", ",", "partition", ")", ":", "\"\"\"\n Checks if a set is in a partition\n Args:\n testset (set): The examined set\n partition (list): A list of sets\n ...
39.061224
0.001528
def list_mapped_classes(): """ Returns all the rdfclasses that have and associated elasticsearch mapping Args: None """ cls_dict = {key: value for key, value in MODULE.rdfclass.__dict__.items() if not isinst...
[ "def", "list_mapped_classes", "(", ")", ":", "cls_dict", "=", "{", "key", ":", "value", "for", "key", ",", "value", "in", "MODULE", ".", "rdfclass", ".", "__dict__", ".", "items", "(", ")", "if", "not", "isinstance", "(", "value", ",", "RdfConfigManager"...
41.115385
0.001828
def getTextualNode( self, textId: str, subreference: Union[str, BaseReference]=None, prevnext: bool=False, metadata: bool=False ) -> TextualNode: """ Retrieve a text node from the API :param textId: CtsTextMetadata Identifier :type...
[ "def", "getTextualNode", "(", "self", ",", "textId", ":", "str", ",", "subreference", ":", "Union", "[", "str", ",", "BaseReference", "]", "=", "None", ",", "prevnext", ":", "bool", "=", "False", ",", "metadata", ":", "bool", "=", "False", ")", "->", ...
35.285714
0.011827
def runMkdir(self, _dir, **kwargs): """ create a directory and its parents""" return self.runRemoteCommand('mkdir', {'dir': _dir, 'logEnviron': self.logEnviron, }, **kwargs)
[ "def", "runMkdir", "(", "self", ",", "_dir", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "runRemoteCommand", "(", "'mkdir'", ",", "{", "'dir'", ":", "_dir", ",", "'logEnviron'", ":", "self", ".", "logEnviron", ",", "}", ",", "*", "*", ...
53.8
0.010989
def can_recommend(self, client_data, extra_data={}): """The Curated recommender will always be able to recommend something""" self.logger.info("Curated can_recommend: {}".format(True)) return True
[ "def", "can_recommend", "(", "self", ",", "client_data", ",", "extra_data", "=", "{", "}", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Curated can_recommend: {}\"", ".", "format", "(", "True", ")", ")", "return", "True" ]
44.8
0.008772
def training(self, is_training=True): ''' Set this layer in the training mode or in predition mode if is_training=False ''' if is_training: callJavaFunc(self.value.training) else: callJavaFunc(self.value.evaluate) return self
[ "def", "training", "(", "self", ",", "is_training", "=", "True", ")", ":", "if", "is_training", ":", "callJavaFunc", "(", "self", ".", "value", ".", "training", ")", "else", ":", "callJavaFunc", "(", "self", ".", "value", ".", "evaluate", ")", "return", ...
32.111111
0.010101
async def start(self): """Enter the transaction or savepoint block.""" self.__check_state_base('start') if self._state is TransactionState.STARTED: raise apg_errors.InterfaceError( 'cannot start; the transaction is already started') con = self._connection ...
[ "async", "def", "start", "(", "self", ")", ":", "self", ".", "__check_state_base", "(", "'start'", ")", "if", "self", ".", "_state", "is", "TransactionState", ".", "STARTED", ":", "raise", "apg_errors", ".", "InterfaceError", "(", "'cannot start; the transaction...
37.875
0.001072
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params` """ assert self.sess is not None, \ 'Cannot...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "sess", "is", "not", "None", ",", "'Cannot use `generate` when no `sess` was provided'", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "labels", ...
36.071429
0.001929
def push(self, el): """ Put a new element in the queue. """ count = next(self.counter) heapq.heappush(self._queue, (el, count))
[ "def", "push", "(", "self", ",", "el", ")", ":", "count", "=", "next", "(", "self", ".", "counter", ")", "heapq", ".", "heappush", "(", "self", ".", "_queue", ",", "(", "el", ",", "count", ")", ")" ]
37
0.013245
def upload_binary(self, binary, timeout=2, interval=0.1): """ Upload all firmware blocks from binary and wait for long running command. """ block_number = 0 block_size = self._determine_max_block_size() for chunk in chunks(binary, block_size): try: ...
[ "def", "upload_binary", "(", "self", ",", "binary", ",", "timeout", "=", "2", ",", "interval", "=", "0.1", ")", ":", "block_number", "=", "0", "block_size", "=", "self", ".", "_determine_max_block_size", "(", ")", "for", "chunk", "in", "chunks", "(", "bi...
44.166667
0.002463
def AgregarMercaderia(self, orden=None, cod_tipo_prod=None, kilos=None, unidades=None, tropa=None, kilos_rec=None, unidades_rec=None, **kwargs): "Agrega la información referente a la mercadería del remito electrónico cárnico" mercaderia = dict(orden=orden, tropa=tropa, codTipoProd=cod_tipo_prod, kilos=k...
[ "def", "AgregarMercaderia", "(", "self", ",", "orden", "=", "None", ",", "cod_tipo_prod", "=", "None", ",", "kilos", "=", "None", ",", "unidades", "=", "None", ",", "tropa", "=", "None", ",", "kilos_rec", "=", "None", ",", "unidades_rec", "=", "None", ...
84.5
0.009766
def _emit_warning(cls, message): """Print an warning message to STDERR.""" sys.stderr.write('WARNING: {message}\n'.format(message=message)) sys.stderr.flush()
[ "def", "_emit_warning", "(", "cls", ",", "message", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'WARNING: {message}\\n'", ".", "format", "(", "message", "=", "message", ")", ")", "sys", ".", "stderr", ".", "flush", "(", ")" ]
44.75
0.010989
def release_name(self, username): """ release a name and add it to the temp list """ self.temp_names.append(username) if self.is_username_used(username): self.registered_names.remove(username)
[ "def", "release_name", "(", "self", ",", "username", ")", ":", "self", ".", "temp_names", ".", "append", "(", "username", ")", "if", "self", ".", "is_username_used", "(", "username", ")", ":", "self", ".", "registered_names", ".", "remove", "(", "username"...
45.6
0.008621
def update_where(self, res, depth=0, since=None, **kwargs): "Like update() but uses WHERE-style args" fetch = lambda: self._fetcher.fetch_all_latest(res, 0, kwargs, since=since) self._update(res, fetch, depth)
[ "def", "update_where", "(", "self", ",", "res", ",", "depth", "=", "0", ",", "since", "=", "None", ",", "*", "*", "kwargs", ")", ":", "fetch", "=", "lambda", ":", "self", ".", "_fetcher", ".", "fetch_all_latest", "(", "res", ",", "0", ",", "kwargs"...
57.5
0.017167
def _parse_upgrade_data(data): ''' Helper method to parse upgrade data from the NX-OS device. ''' upgrade_result = {} upgrade_result['upgrade_data'] = None upgrade_result['succeeded'] = False upgrade_result['upgrade_required'] = False upgrade_result['upgrade_non_disruptive'] = False ...
[ "def", "_parse_upgrade_data", "(", "data", ")", ":", "upgrade_result", "=", "{", "}", "upgrade_result", "[", "'upgrade_data'", "]", "=", "None", "upgrade_result", "[", "'succeeded'", "]", "=", "False", "upgrade_result", "[", "'upgrade_required'", "]", "=", "Fals...
40.481132
0.000227
def _make_style_str(styledict): """ Make an SVG style string from the dictionary. See also _parse_style_str also. """ s = '' for key in list(styledict.keys()): s += "%s:%s;" % (key, styledict[key]) return s
[ "def", "_make_style_str", "(", "styledict", ")", ":", "s", "=", "''", "for", "key", "in", "list", "(", "styledict", ".", "keys", "(", ")", ")", ":", "s", "+=", "\"%s:%s;\"", "%", "(", "key", ",", "styledict", "[", "key", "]", ")", "return", "s" ]
28.875
0.008403
def check(a, b): """ Checks to see if the two values are equal to each other. :param a | <str> b | <str> :return <bool> """ aencrypt = encrypt(a) bencrypt = encrypt(b) return a == b or a == bencrypt or aencrypt == b
[ "def", "check", "(", "a", ",", "b", ")", ":", "aencrypt", "=", "encrypt", "(", "a", ")", "bencrypt", "=", "encrypt", "(", "b", ")", "return", "a", "==", "b", "or", "a", "==", "bencrypt", "or", "aencrypt", "==", "b" ]
20.846154
0.010601
def cache_from_source(path, debug_override=None): """Given the path to a .py file, return the path to its .pyc/.pyo file. The .py file does not need to exist; this simply returns the path to the .pyc/.pyo file calculated as if the .py file were imported. The extension will be .pyc unless sys.flags.opt...
[ "def", "cache_from_source", "(", "path", ",", "debug_override", "=", "None", ")", ":", "debug", "=", "not", "sys", ".", "flags", ".", "optimize", "if", "debug_override", "is", "None", "else", "debug_override", "if", "debug", ":", "suffixes", "=", "DEBUG_BYTE...
41.275862
0.001633
def start_worker(node_ip_address, object_store_name, raylet_name, redis_address, worker_path, temp_dir, stdout_file=None, stderr_file=None): """This method starts a worker process. Args: ...
[ "def", "start_worker", "(", "node_ip_address", ",", "object_store_name", ",", "raylet_name", ",", "redis_address", ",", "worker_path", ",", "temp_dir", ",", "stdout_file", "=", "None", ",", "stderr_file", "=", "None", ")", ":", "command", "=", "[", "sys", ".",...
39.575
0.000617
def main(argv=None): '''TEST ONLY: this is called if run from command line''' parser = argparse.ArgumentParser() parser.add_argument('-i','--input_file', required=True) parser.add_argument('--input_file_format', default='sequence') parser.add_argument('--input_data_type', default='json') parser...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'-i'", ",", "'--input_file'", ",", "required", "=", "True", ")", "parser", ".", "add_argument", "(", "'--i...
41.131579
0.00875
def _write(self, string): """Helper function to call write_data on the provided FTDI device and verify it succeeds. """ # Get modem status. Useful to enable for debugging. #ret, status = ftdi.poll_modem_status(self._ctx) #if ret == 0: # logger.debug('Modem status ...
[ "def", "_write", "(", "self", ",", "string", ")", ":", "# Get modem status. Useful to enable for debugging.", "#ret, status = ftdi.poll_modem_status(self._ctx)", "#if ret == 0:", "#\tlogger.debug('Modem status {0:02X}'.format(status))", "#else:", "#\tlogger.debug('Modem status error {0}'.f...
51.909091
0.013758
def queryset(self, request): """ Filter objects which don't have a value in this language """ qs = super(MultilingualInlineAdmin, self).queryset(request) # Don't now what the hell I was thinking here, but this code breaks stuff: # # checkfield = self.get_fill_chec...
[ "def", "queryset", "(", "self", ",", "request", ")", ":", "qs", "=", "super", "(", "MultilingualInlineAdmin", ",", "self", ")", ".", "queryset", "(", "request", ")", "# Don't now what the hell I was thinking here, but this code breaks stuff:", "#", "# checkfield = self....
54.666667
0.008393
def izip_exact(*iterables): """ A lazy izip() that ensures that all iterables have the same length. A LengthMismatch exception is raised if the iterables' lengths differ. Examples -------- >>> list(zip_exc([])) [] >>> list(zip_exc((), (), ())) [] >>> list(zi...
[ "def", "izip_exact", "(", "*", "iterables", ")", ":", "rest", "=", "[", "chain", "(", "i", ",", "_throw", "(", ")", ")", "for", "i", "in", "iterables", "[", "1", ":", "]", "]", "first", "=", "chain", "(", "iterables", "[", "0", "]", ",", "_chec...
27.808511
0.001478
def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: ...
[ "def", "ip_interface", "(", "address", ")", ":", "try", ":", "return", "IPv4Interface", "(", "address", ")", "except", "(", "AddressValueError", ",", "NetmaskValueError", ")", ":", "pass", "try", ":", "return", "IPv6Interface", "(", "address", ")", "except", ...
28.787879
0.001018
def postChunked(host, selector, fields, files): """ Attempt to replace postMultipart() with nearly-identical interface. (The files tuple no longer requires the filename, and we only return the response body.) Uses the urllib2_file.py originally from http://fabien.seisen.org which was also draw...
[ "def", "postChunked", "(", "host", ",", "selector", ",", "fields", ",", "files", ")", ":", "params", "=", "urllib", ".", "urlencode", "(", "fields", ")", "url", "=", "'http://%s%s?%s'", "%", "(", "host", ",", "selector", ",", "params", ")", "u", "=", ...
40.75
0.009592
def _process_async_error(self, resp_body, error_class): """ The DNS API does not return a consistent format for their error messages. This abstracts out the differences in order to present a single unified message in the exception to be raised. """ def _fmt_error(err): ...
[ "def", "_process_async_error", "(", "self", ",", "resp_body", ",", "error_class", ")", ":", "def", "_fmt_error", "(", "err", ")", ":", "# Remove the cumbersome Java-esque message", "details", "=", "err", ".", "get", "(", "\"details\"", ",", "\"\"", ")", ".", "...
41.363636
0.002148
def _aspect_preserving_resize(image, resize_min): """Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. resize_min: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing the...
[ "def", "_aspect_preserving_resize", "(", "image", ",", "resize_min", ")", ":", "mlperf_log", ".", "resnet_print", "(", "key", "=", "mlperf_log", ".", "INPUT_RESIZE_ASPECT_PRESERVING", ",", "value", "=", "{", "\"min\"", ":", "resize_min", "}", ")", "shape", "=", ...
32.2
0.010558
def countthai(text: str, ignore_chars: str = _DEFAULT_IGNORE_CHARS) -> float: """ :param str text: input text :return: float, proportion of characters in the text that is Thai character """ if not text or not isinstance(text, str): return 0 if not ignore_chars: ignore_chars = ""...
[ "def", "countthai", "(", "text", ":", "str", ",", "ignore_chars", ":", "str", "=", "_DEFAULT_IGNORE_CHARS", ")", "->", "float", ":", "if", "not", "text", "or", "not", "isinstance", "(", "text", ",", "str", ")", ":", "return", "0", "if", "not", "ignore_...
23.956522
0.001745
def setBackground(self,bg): """ Sets the background of the submenu. The background may be a RGB or RGBA color to fill the background with. Alternatively, a :py:class:`peng3d.layer.Layer` instance or other object with a ``.draw()`` method may be supplied. It is a...
[ "def", "setBackground", "(", "self", ",", "bg", ")", ":", "self", ".", "bg", "=", "bg", "if", "isinstance", "(", "bg", ",", "list", ")", "or", "isinstance", "(", "bg", ",", "tuple", ")", ":", "if", "len", "(", "bg", ")", "==", "3", "and", "isin...
49.380952
0.02176
def _pastore8(ins): ''' Stores 2º operand content into address of 1st operand. 1st operand is an array element. Dimensions are pushed into the stack. Use '*' for indirect store on 1st operand (A pointer to an array) ''' output = _paddr(ins.quad[1]) value = ins.quad[2] if value[0] == '*'...
[ "def", "_pastore8", "(", "ins", ")", ":", "output", "=", "_paddr", "(", "ins", ".", "quad", "[", "1", "]", ")", "value", "=", "ins", ".", "quad", "[", "2", "]", "if", "value", "[", "0", "]", "==", "'*'", ":", "value", "=", "value", "[", "1", ...
26.392857
0.001305
def noam_norm(x, epsilon=1.0, name=None): """One version of layer normalization.""" with tf.name_scope(name, default_name="noam_norm", values=[x]): shape = x.get_shape() ndims = len(shape) return (tf.nn.l2_normalize(x, ndims - 1, epsilon=epsilon) * tf.sqrt( to_float(shape[-1])))
[ "def", "noam_norm", "(", "x", ",", "epsilon", "=", "1.0", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "name", ",", "default_name", "=", "\"noam_norm\"", ",", "values", "=", "[", "x", "]", ")", ":", "shape", "=", "x", ...
42.428571
0.009901
def common_type(a, b): """ Returns a type which is common for both a and b types. Returns None if no common types allowed. """ from symbols.type_ import SymbolBASICTYPE as BASICTYPE from symbols.type_ import Type as TYPE from symbols.type_ import SymbolTYPE if a is None or b is None: ...
[ "def", "common_type", "(", "a", ",", "b", ")", ":", "from", "symbols", ".", "type_", "import", "SymbolBASICTYPE", "as", "BASICTYPE", "from", "symbols", ".", "type_", "import", "Type", "as", "TYPE", "from", "symbols", ".", "type_", "import", "SymbolTYPE", "...
22.7
0.000845
def entropy(rho: Density, base: float = None) -> float: """ Returns the von-Neumann entropy of a mixed quantum state. Args: rho: A density matrix base: Optional logarithm base. Default is base e, and entropy is measures in nats. For bits set base to 2. Returns: ...
[ "def", "entropy", "(", "rho", ":", "Density", ",", "base", ":", "float", "=", "None", ")", "->", "float", ":", "op", "=", "asarray", "(", "rho", ".", "asoperator", "(", ")", ")", "probs", "=", "np", ".", "linalg", ".", "eigvalsh", "(", "op", ")",...
33.875
0.001795
def federation(address_or_id, fed_type='name', domain=None, allow_http=False): """Send a federation query to a Stellar Federation service. For more info, see the `complete guide on Stellar Federation. <https://www.stellar.org/developers/guides/concepts/federation.html>`_. :param str address_or_id: The...
[ "def", "federation", "(", "address_or_id", ",", "fed_type", "=", "'name'", ",", "domain", "=", "None", ",", "allow_http", "=", "False", ")", ":", "if", "fed_type", "==", "'name'", ":", "if", "'*'", "not", "in", "address_or_id", ":", "raise", "FederationErr...
45.1
0.001085
def plot(message, duration=1, ax=None): """ Plot a message Returns: ax a Matplotlib Axe """ lst_bin = _encode_binary(message) x, y = _create_x_y(lst_bin, duration) ax = _create_ax(ax) ax.plot(x, y, linewidth=2.0) delta_y = 0.1 ax.set_ylim(-delta_y, 1 + delta_y) ax.set_yticks...
[ "def", "plot", "(", "message", ",", "duration", "=", "1", ",", "ax", "=", "None", ")", ":", "lst_bin", "=", "_encode_binary", "(", "message", ")", "x", ",", "y", "=", "_create_x_y", "(", "lst_bin", ",", "duration", ")", "ax", "=", "_create_ax", "(", ...
26.0625
0.002315
def __inst_doc(self, docid, doc_type_name=None): """ Instantiate a document based on its document id. The information are taken from the whoosh index. """ doc = None docpath = self.fs.join(self.rootdir, docid) if not self.fs.exists(docpath): return Non...
[ "def", "__inst_doc", "(", "self", ",", "docid", ",", "doc_type_name", "=", "None", ")", ":", "doc", "=", "None", "docpath", "=", "self", ".", "fs", ".", "join", "(", "self", ".", "rootdir", ",", "docid", ")", "if", "not", "self", ".", "fs", ".", ...
39.413793
0.001708
def read_row(self, row_key, filter_=None): """Read a single row from this table. For example: .. literalinclude:: snippets_table.py :start-after: [START bigtable_read_row] :end-before: [END bigtable_read_row] :type row_key: bytes :param row_key: The key...
[ "def", "read_row", "(", "self", ",", "row_key", ",", "filter_", "=", "None", ")", ":", "row_set", "=", "RowSet", "(", ")", "row_set", ".", "add_row_key", "(", "row_key", ")", "result_iter", "=", "iter", "(", "self", ".", "read_rows", "(", "filter_", "=...
39.724138
0.001695
def _getNextArticleBatch(self): """download next batch of events based on the event uris in the uri list""" eventUri = self.queryParams["eventUri"] # move to the next page to download self._articlePage += 1 # if we have already obtained all pages, then exit if self._total...
[ "def", "_getNextArticleBatch", "(", "self", ")", ":", "eventUri", "=", "self", ".", "queryParams", "[", "\"eventUri\"", "]", "# move to the next page to download", "self", ".", "_articlePage", "+=", "1", "# if we have already obtained all pages, then exit", "if", "self", ...
46.434783
0.012844
def join(self): """Note that the Executor must be close()'d elsewhere, or join() will never return. """ self.inputfeeder_thread.join() self.pool.join() self.resulttracker_thread.join() self.failuretracker_thread.join()
[ "def", "join", "(", "self", ")", ":", "self", ".", "inputfeeder_thread", ".", "join", "(", ")", "self", ".", "pool", ".", "join", "(", ")", "self", ".", "resulttracker_thread", ".", "join", "(", ")", "self", ".", "failuretracker_thread", ".", "join", "...
28.125
0.038793
def _split_rules(rules): ''' Split rules with lists into individual rules. We accept some attributes as lists or strings. The data we get back from the execution module lists rules as individual rules. We need to split the provided rules into individual rules to compare them. ''' split = []...
[ "def", "_split_rules", "(", "rules", ")", ":", "split", "=", "[", "]", "for", "rule", "in", "rules", ":", "cidr_ip", "=", "rule", ".", "get", "(", "'cidr_ip'", ")", "group_name", "=", "rule", ".", "get", "(", "'source_group_name'", ")", "group_id", "="...
38.193548
0.000824
def set_quoted_text(self, quoted_text): """Sets the context's ``quoted_text`` flag. Useful when entering and exiting quoted text tokens.""" self.quoted_text = quoted_text self.line_comment = False return self
[ "def", "set_quoted_text", "(", "self", ",", "quoted_text", ")", ":", "self", ".", "quoted_text", "=", "quoted_text", "self", ".", "line_comment", "=", "False", "return", "self" ]
47.2
0.0125
def createAltHistoryPlot(self): '''Creates the altitude history plot.''' self.altHistRect = patches.Rectangle((self.leftPos+(self.vertSize/10.0),-0.25),0.5,0.5,facecolor='grey',edgecolor='none',alpha=0.4,zorder=4) self.axes.add_patch(self.altHistRect) self.altPlot, = self.axes.plot([self...
[ "def", "createAltHistoryPlot", "(", "self", ")", ":", "self", ".", "altHistRect", "=", "patches", ".", "Rectangle", "(", "(", "self", ".", "leftPos", "+", "(", "self", ".", "vertSize", "/", "10.0", ")", ",", "-", "0.25", ")", ",", "0.5", ",", "0.5", ...
100.571429
0.042254
def to_dict_list(mystr): """ Translate a string representation of a Bloomberg Open API Request/Response into a list of dictionaries.return Parameters ---------- mystr: str A string representation of one or more blpapi.request.Request or blp.message.Message, these should be '\\n'...
[ "def", "to_dict_list", "(", "mystr", ")", ":", "res", "=", "_parse", "(", "mystr", ")", "dicts", "=", "[", "]", "for", "res_dict", "in", "res", ":", "dicts", ".", "append", "(", "res_dict", ".", "asDict", "(", ")", ")", "return", "dicts" ]
27.75
0.002179
def find_template_filename(self, template_name): """ Searches for a file matching the given template name. If found, this method returns the pathlib.Path object of the found template file. Args: template_name (str): Name of the template, with or without a file ...
[ "def", "find_template_filename", "(", "self", ",", "template_name", ")", ":", "def", "next_file", "(", ")", ":", "filename", "=", "self", ".", "path", "/", "template_name", "yield", "filename", "try", ":", "exts", "=", "self", ".", "default_file_extensions", ...
28.3
0.002278
def dir_attribs(location, mode=None, owner=None, group=None, recursive=False, use_sudo=False): """ cuisine dir_attribs doesn't do sudo, so we implement our own Updates the mode/owner/group for the given remote directory.""" args = '' if recursive: args = args + ' -R ' if...
[ "def", "dir_attribs", "(", "location", ",", "mode", "=", "None", ",", "owner", "=", "None", ",", "group", "=", "None", ",", "recursive", "=", "False", ",", "use_sudo", "=", "False", ")", ":", "args", "=", "''", "if", "recursive", ":", "args", "=", ...
33.958333
0.001193
def compute_probability(trajectory_files, bbox=None, nx=None, ny=None, method='overall', parameter='location'): """ This function creates a probability (stochastic) grid for trajectory model data using 'overall' method (based on normalization by nsteps * nparticles)...
[ "def", "compute_probability", "(", "trajectory_files", ",", "bbox", "=", "None", ",", "nx", "=", "None", ",", "ny", "=", "None", ",", "method", "=", "'overall'", ",", "parameter", "=", "'location'", ")", ":", "xarray", "=", "np", ".", "linspace", "(", ...
50.696203
0.008817
def write_contents(self, table, reader): """Write the contents of `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql...
[ "def", "write_contents", "(", "self", ",", "table", ",", "reader", ")", ":", "f", "=", "self", ".", "FileObjFaker", "(", "table", ",", "reader", ".", "read", "(", "table", ")", ",", "self", ".", "process_row", ",", "self", ".", "verbose", ")", "self"...
54
0.009934
def setGridPen( self, gridPen ): """ Sets the pen that will be used when drawing the grid lines. :param gridPen | <QtGui.QPen> || <QtGui.QColor> """ delegate = self.itemDelegate() if ( isinstance(delegate, XTreeWidgetDelegate) ): delegate...
[ "def", "setGridPen", "(", "self", ",", "gridPen", ")", ":", "delegate", "=", "self", ".", "itemDelegate", "(", ")", "if", "(", "isinstance", "(", "delegate", ",", "XTreeWidgetDelegate", ")", ")", ":", "delegate", ".", "setGridPen", "(", "gridPen", ")" ]
36.888889
0.020588
def newton_refine1(s, new_s, curve1, t, new_t, curve2): """Image for :func:`.newton_refine` docstring.""" if NO_IMAGES: return points = np.hstack([curve1.evaluate(s), curve2.evaluate(t)]) points_new = np.hstack([curve1.evaluate(new_s), curve2.evaluate(new_t)]) ax = curve1.plot(256) curv...
[ "def", "newton_refine1", "(", "s", ",", "new_s", ",", "curve1", ",", "t", ",", "new_t", ",", "curve2", ")", ":", "if", "NO_IMAGES", ":", "return", "points", "=", "np", ".", "hstack", "(", "[", "curve1", ".", "evaluate", "(", "s", ")", ",", "curve2"...
26.444444
0.001351
def build(self, builder): """ Build XML by appending to builder """ params = {} # Add in the transaction type if self.transaction_type is not None: params["TransactionType"] = self.transaction_type if self.seqnum is None: # SeqNum is not ...
[ "def", "build", "(", "self", ",", "builder", ")", ":", "params", "=", "{", "}", "# Add in the transaction type", "if", "self", ".", "transaction_type", "is", "not", "None", ":", "params", "[", "\"TransactionType\"", "]", "=", "self", ".", "transaction_type", ...
29.764706
0.001914
def read_history_report(path, steps, x_name = None): """ Reads an history output report. """ data = pd.read_csv(path, delim_whitespace = True) if x_name != None: data[x_name] = data.X del data["X"] data["step"] = 0 t = 0. for i in range(len(steps)): dt = steps[i].duration loc = data...
[ "def", "read_history_report", "(", "path", ",", "steps", ",", "x_name", "=", "None", ")", ":", "data", "=", "pd", ".", "read_csv", "(", "path", ",", "delim_whitespace", "=", "True", ")", "if", "x_name", "!=", "None", ":", "data", "[", "x_name", "]", ...
22.611111
0.037736
def partial(cls, prefix, source): """Strip a prefix from the keys of another dictionary, returning a Bunch containing only valid key, value pairs.""" match = prefix + "." matches = cls([(key[len(match):], source[key]) for key in source if key.startswith(match)]) if not ...
[ "def", "partial", "(", "cls", ",", "prefix", ",", "source", ")", ":", "match", "=", "prefix", "+", "\".\"", "matches", "=", "cls", "(", "[", "(", "key", "[", "len", "(", "match", ")", ":", "]", ",", "source", "[", "key", "]", ")", "for", "key",...
38.2
0.017903
def rename_fields(layer, fields_to_copy): """Rename fields inside an attribute table. Only since QGIS 2.16. :param layer: The vector layer. :type layer: QgsVectorLayer :param fields_to_copy: Dictionary of fields to copy. :type fields_to_copy: dict """ for field in fields_to_copy: ...
[ "def", "rename_fields", "(", "layer", ",", "fields_to_copy", ")", ":", "for", "field", "in", "fields_to_copy", ":", "index", "=", "layer", ".", "fields", "(", ")", ".", "lookupField", "(", "field", ")", "if", "index", "!=", "-", "1", ":", "layer", ".",...
33.782609
0.001252
def index(self, date): """ Returns the index of a date in the table. """ for (i, (start, end, ruler)) in enumerate(self.table): if start <= date.jd <= end: return i return None
[ "def", "index", "(", "self", ",", "date", ")", ":", "for", "(", "i", ",", "(", "start", ",", "end", ",", "ruler", ")", ")", "in", "enumerate", "(", "self", ".", "table", ")", ":", "if", "start", "<=", "date", ".", "jd", "<=", "end", ":", "ret...
37.166667
0.008772
def _stack_format (stack): """Format a stack trace to a message. @return: formatted stack message @rtype: string """ s = StringIO() s.write('Traceback:') s.write(os.linesep) for frame, fname, lineno, method, lines, dummy in reversed(stack): s.write(' File %r, line %d, in %s' % ...
[ "def", "_stack_format", "(", "stack", ")", ":", "s", "=", "StringIO", "(", ")", "s", ".", "write", "(", "'Traceback:'", ")", "s", ".", "write", "(", "os", ".", "linesep", ")", "for", "frame", ",", "fname", ",", "lineno", ",", "method", ",", "lines"...
35.826087
0.002364
def load_all(self, workers=None, limit=None, n_expected=None): """Load all instances witih multiple threads. :param workers: number of workers to use to load instances, which defaults to what was given in the class initializer :param limit: return a maximum, which defaul...
[ "def", "load_all", "(", "self", ",", "workers", "=", "None", ",", "limit", "=", "None", ",", "n_expected", "=", "None", ")", ":", "if", "not", "self", ".", "has_data", ":", "self", ".", "_preempt", "(", "True", ")", "# we did the best we could (avoid repea...
43.5
0.001606
def pack_rows(rows, bitdepth): """Yield packed rows that are a byte array. Each byte is packed with the values from several pixels. """ assert bitdepth < 8 assert 8 % bitdepth == 0 # samples per byte spb = int(8 / bitdepth) def make_byte(block): """Take a block of (2, 4, or 8)...
[ "def", "pack_rows", "(", "rows", ",", "bitdepth", ")", ":", "assert", "bitdepth", "<", "8", "assert", "8", "%", "bitdepth", "==", "0", "# samples per byte", "spb", "=", "int", "(", "8", "/", "bitdepth", ")", "def", "make_byte", "(", "block", ")", ":", ...
27.125
0.001112
def exec_rule(self, rule): """ :rule : the Ant class of rule, which must have a start() function """ print("running Rule: {0}".format(rule.__name__)) ant = rule() ant.start()
[ "def", "exec_rule", "(", "self", ",", "rule", ")", ":", "print", "(", "\"running Rule: {0}\"", ".", "format", "(", "rule", ".", "__name__", ")", ")", "ant", "=", "rule", "(", ")", "ant", ".", "start", "(", ")" ]
30.857143
0.009009
def dimensioned_streams(dmap): """ Given a DynamicMap return all streams that have any dimensioned parameters i.e parameters also listed in the key dimensions. """ dimensioned = [] for stream in dmap.streams: stream_params = stream_parameters([stream]) if set([str(k) for k in dma...
[ "def", "dimensioned_streams", "(", "dmap", ")", ":", "dimensioned", "=", "[", "]", "for", "stream", "in", "dmap", ".", "streams", ":", "stream_params", "=", "stream_parameters", "(", "[", "stream", "]", ")", "if", "set", "(", "[", "str", "(", "k", ")",...
36.636364
0.002421
def pack_apply_message(f, args, kwargs, threshold=64e-6): """pack up a function, args, and kwargs to be sent over the wire as a series of buffers. Any object whose data is larger than `threshold` will not have their data copied (currently only numpy arrays support zero-copy)""" msg = [pickle.dumps(can(f...
[ "def", "pack_apply_message", "(", "f", ",", "args", ",", "kwargs", ",", "threshold", "=", "64e-6", ")", ":", "msg", "=", "[", "pickle", ".", "dumps", "(", "can", "(", "f", ")", ",", "-", "1", ")", "]", "databuffers", "=", "[", "]", "# for large obj...
43.357143
0.009677
def assert_ge(left, right, message=None, extra=None): """Raises an AssertionError if left_hand < right_hand.""" assert left >= right, _assert_fail_message(message, left, right, "<", extra)
[ "def", "assert_ge", "(", "left", ",", "right", ",", "message", "=", "None", ",", "extra", "=", "None", ")", ":", "assert", "left", ">=", "right", ",", "_assert_fail_message", "(", "message", ",", "left", ",", "right", ",", "\"<\"", ",", "extra", ")" ]
64.666667
0.010204
def view(self, start, end, max_items=None, *args, **kwargs): """ Implements the CalendarView option to FindItem. The difference between filter() and view() is that filter() only returns the master CalendarItem for recurring items, while view() unfolds recurring items and returns all CalendarItem...
[ "def", "view", "(", "self", ",", "start", ",", "end", ",", "max_items", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "qs", "=", "QuerySet", "(", "self", ")", ".", "filter", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
67.75
0.010009
def _build_cache(source_file, skip_cache=False): """Build the cached data. Either by parsing the RDF taxonomy file or a vocabulary file. :param source_file: source file of the taxonomy, RDF file :param skip_cache: if True, build cache will not be saved (pickled) - it is saved as <source_file.d...
[ "def", "_build_cache", "(", "source_file", ",", "skip_cache", "=", "False", ")", ":", "store", "=", "rdflib", ".", "ConjunctiveGraph", "(", ")", "if", "skip_cache", ":", "current_app", ".", "logger", ".", "info", "(", "\"You requested not to save the cache to disk...
38.275862
0.000351
def wrap(self, video_mode): """ Wraps a nested python sequence. """ size, bits, self.refresh_rate = video_mode self.width, self.height = size self.red_bits, self.green_bits, self.blue_bits = bits
[ "def", "wrap", "(", "self", ",", "video_mode", ")", ":", "size", ",", "bits", ",", "self", ".", "refresh_rate", "=", "video_mode", "self", ".", "width", ",", "self", ".", "height", "=", "size", "self", ".", "red_bits", ",", "self", ".", "green_bits", ...
33.857143
0.00823
def get_new_connection(self, conn_params): """Build a connection from its parameters.""" connection = ldap.ldapobject.ReconnectLDAPObject( uri=conn_params['uri'], retry_max=conn_params['retry_max'], retry_delay=conn_params['retry_delay'], bytes_mode=False)...
[ "def", "get_new_connection", "(", "self", ",", "conn_params", ")", ":", "connection", "=", "ldap", ".", "ldapobject", ".", "ReconnectLDAPObject", "(", "uri", "=", "conn_params", "[", "'uri'", "]", ",", "retry_max", "=", "conn_params", "[", "'retry_max'", "]", ...
33.16
0.002345
def _un_meta_name(self, name): """ Reverse of _meta_name """ if name.startswith('HTTP_'): name = name[5:] return name.replace('_', '-').title()
[ "def", "_un_meta_name", "(", "self", ",", "name", ")", ":", "if", "name", ".", "startswith", "(", "'HTTP_'", ")", ":", "name", "=", "name", "[", "5", ":", "]", "return", "name", ".", "replace", "(", "'_'", ",", "'-'", ")", ".", "title", "(", ")" ...
27
0.010256
def add_genre(dom): """ Add ``<mods:genre>`` with `electronic volume` content into ``<mods:originInfo``. """ mods_tag = get_mods_tag(dom) matched_genres = [ "electronic title", "electronic volume", ] genre = dom.find( "mods:genre", fn=lambda x: x.getConte...
[ "def", "add_genre", "(", "dom", ")", ":", "mods_tag", "=", "get_mods_tag", "(", "dom", ")", "matched_genres", "=", "[", "\"electronic title\"", ",", "\"electronic volume\"", ",", "]", "genre", "=", "dom", ".", "find", "(", "\"mods:genre\"", ",", "fn", "=", ...
25.954545
0.001689
def contains_offset(self, offset): """Check whether the section contains the file offset provided.""" if self.PointerToRawData is None: # bss and other sections containing only uninitialized data must have 0 # and do not take space in the file return False ...
[ "def", "contains_offset", "(", "self", ",", "offset", ")", ":", "if", "self", ".", "PointerToRawData", "is", "None", ":", "# bss and other sections containing only uninitialized data must have 0", "# and do not take space in the file", "return", "False", "return", "(", "adj...
49.846154
0.033333
def load_internal_cache(cls, pex, pex_info): """Possibly cache out the internal cache.""" internal_cache = os.path.join(pex, pex_info.internal_cache) with TRACER.timed('Searching dependency cache: %s' % internal_cache, V=2): if os.path.isdir(pex): for dist in find_distributions(internal_cache)...
[ "def", "load_internal_cache", "(", "cls", ",", "pex", ",", "pex_info", ")", ":", "internal_cache", "=", "os", ".", "path", ".", "join", "(", "pex", ",", "pex_info", ".", "internal_cache", ")", "with", "TRACER", ".", "timed", "(", "'Searching dependency cache...
45.2
0.013015
def vsearch_dereplicate_exact_seqs( fasta_filepath, output_filepath, output_uc=False, working_dir=None, strand="both", maxuniquesize=None, minuniquesize=None, sizein=False, sizeout=True, log_name="derep.log", HALT_EXEC=False): """ Generates clusters and fasta file of ...
[ "def", "vsearch_dereplicate_exact_seqs", "(", "fasta_filepath", ",", "output_filepath", ",", "output_uc", "=", "False", ",", "working_dir", "=", "None", ",", "strand", "=", "\"both\"", ",", "maxuniquesize", "=", "None", ",", "minuniquesize", "=", "None", ",", "s...
33.989362
0.000608
def clone(location: str, directory: str, *, branch: str=None, tag: str=None, commit: str=None, author_name: str=None, author_email: str=None) -> Commit: """ Clones the repository at the given location as a subrepo in the given directory. :param location: the location of the repository to clone ...
[ "def", "clone", "(", "location", ":", "str", ",", "directory", ":", "str", ",", "*", ",", "branch", ":", "str", "=", "None", ",", "tag", ":", "str", "=", "None", ",", "commit", ":", "str", "=", "None", ",", "author_name", ":", "str", "=", "None",...
53.272727
0.008936
def add_instrument(self, mount, instrument): """ Adds instrument to a robot. Parameters ---------- mount : str Specifies which axis the instruments is attached to. Valid options are "left" or "right". instrument : Instrument An instanc...
[ "def", "add_instrument", "(", "self", ",", "mount", ",", "instrument", ")", ":", "if", "mount", "in", "self", ".", "_instruments", ":", "prev_instr", "=", "self", ".", "_instruments", "[", "mount", "]", "raise", "RuntimeError", "(", "'Instrument {0} already on...
35.365079
0.000873
def slice_plot(netin, ax, nodelabels=None, timelabels=None, communities=None, plotedgeweights=False, edgeweightscalar=1, timeunit='', linestyle='k-', cmap=None, nodesize=100, nodekwargs=None, edgekwargs=None): r''' Fuction draws "slice graph" and exports axis handles Parameters ---------- netin ...
[ "def", "slice_plot", "(", "netin", ",", "ax", ",", "nodelabels", "=", "None", ",", "timelabels", "=", "None", ",", "communities", "=", "None", ",", "plotedgeweights", "=", "False", ",", "edgeweightscalar", "=", "1", ",", "timeunit", "=", "''", ",", "line...
34.159091
0.00194
def from_shape_pixel_scale_and_sub_grid_size(cls, shape, pixel_scale, sub_grid_size): """Setup a sub-grid from a 2D array shape and pixel scale. Here, the center of every pixel on the 2D \ array gives the grid's (y,x) arc-second coordinates, where each pixel has sub-pixels specified by the \ sub...
[ "def", "from_shape_pixel_scale_and_sub_grid_size", "(", "cls", ",", "shape", ",", "pixel_scale", ",", "sub_grid_size", ")", ":", "mask", "=", "msk", ".", "Mask", ".", "unmasked_for_shape_and_pixel_scale", "(", "shape", "=", "shape", ",", "pixel_scale", "=", "pixel...
60.333333
0.009324
def _split_out_of_braces(s): """Generator to split comma seperated string, but not split commas inside curly braces. >>> list(_split_out_of_braces("py{26, 27}-django{15, 16}, py32")) >>>['py{26, 27}-django{15, 16}, py32'] """ prev = 0 for m in re.finditer(r"{[^{}]*}|\s*,\s*", s): i...
[ "def", "_split_out_of_braces", "(", "s", ")", ":", "prev", "=", "0", "for", "m", "in", "re", ".", "finditer", "(", "r\"{[^{}]*}|\\s*,\\s*\"", ",", "s", ")", ":", "if", "not", "m", ".", "group", "(", ")", ".", "startswith", "(", "\"{\"", ")", ":", "...
28.444444
0.00189
def p_wait_statement(self, p): 'wait_statement : WAIT LPAREN cond RPAREN waitcontent_statement' p[0] = WaitStatement(p[3], p[5], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_wait_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "WaitStatement", "(", "p", "[", "3", "]", ",", "p", "[", "5", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", ...
49.5
0.00995
def lowest_common_hypernyms(self,target_synset): """Returns the common hypernyms of the synset and the target synset, which are furthest from the closest roots. Parameters ---------- target_synset : Synset Synset with which the common hypernyms are sought. ...
[ "def", "lowest_common_hypernyms", "(", "self", ",", "target_synset", ")", ":", "self_hypernyms", "=", "self", ".", "_recursive_hypernyms", "(", "set", "(", ")", ")", "other_hypernyms", "=", "target_synset", ".", "_recursive_hypernyms", "(", "set", "(", ")", ")",...
41.821429
0.016694
def set_possible(self): ''' break up a module path to its various parts (prefix, module, class, method) this uses PEP 8 conventions, so foo.Bar would be foo module with class Bar return -- list -- a list of possible interpretations of the module path (eg, foo.bar can be bar...
[ "def", "set_possible", "(", "self", ")", ":", "possible", "=", "[", "]", "name", "=", "self", ".", "name", "logger", ".", "debug", "(", "'Guessing test name: {}'", ".", "format", "(", "name", ")", ")", "name_f", "=", "self", ".", "name", ".", "lower", ...
41.313253
0.001994
def _bad_result(cls, error): """ :param str|unicode error: Syntax error from TryHaskell. :rtype: TryHaskell.Result """ return cls.Result(ok=False, expr='', files={}, stdout='', type='', value=error)
[ "def", "_bad_result", "(", "cls", ",", "error", ")", ":", "return", "cls", ".", "Result", "(", "ok", "=", "False", ",", "expr", "=", "''", ",", "files", "=", "{", "}", ",", "stdout", "=", "''", ",", "type", "=", "''", ",", "value", "=", "error"...
38.833333
0.012605
def WriteRow(stream, values): "Writes one row of comma-separated values to stream." stream.write(','.join([EncodeForCSV(val) for val in values])) stream.write('\n')
[ "def", "WriteRow", "(", "stream", ",", "values", ")", ":", "stream", ".", "write", "(", "','", ".", "join", "(", "[", "EncodeForCSV", "(", "val", ")", "for", "val", "in", "values", "]", ")", ")", "stream", ".", "write", "(", "'\\n'", ")" ]
41.75
0.023529
def ExtractEvents( self, parser_mediator, registry_key, codepage='cp1252', **kwargs): """Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg...
[ "def", "ExtractEvents", "(", "self", ",", "parser_mediator", ",", "registry_key", ",", "codepage", "=", "'cp1252'", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_ParseMRUListExKey", "(", "parser_mediator", ",", "registry_key", ",", "codepage", "=", "codepa...
45.363636
0.001965
def _query(self, method, path, data=None, page=False, retry=0): """ Fetch an object from the Graph API and parse the output, returning a tuple where the first item is the object yielded by the Graph API and the second is the URL for the next page of results, or ``None`` if results have b...
[ "def", "_query", "(", "self", ",", "method", ",", "path", ",", "data", "=", "None", ",", "page", "=", "False", ",", "retry", "=", "0", ")", ":", "if", "(", "data", ")", ":", "data", "=", "dict", "(", "(", "k", ".", "replace", "(", "'_sqbro_'", ...
38.969925
0.001881
def default_returns_func(symbol, start=None, end=None): """ Gets returns for a symbol. Queries Yahoo Finance. Attempts to cache SPY. Parameters ---------- symbol : str Ticker symbol, e.g. APPL. start : date, optional Earliest date to fetch data for. Defaults to earli...
[ "def", "default_returns_func", "(", "symbol", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "start", "is", "None", ":", "start", "=", "'1/1/1970'", "if", "end", "is", "None", ":", "end", "=", "_1_bday_ago", "(", ")", "start", "=...
28.181818
0.000779
def _convert_pattern(p_length, p_periodunit, p_offset=None): """ Converts a pattern in the form [0-9][dwmyb] and returns a date from the offset with the period of time added to it. """ result = None p_offset = p_offset or date.today() p_length = int(p_length) if p_periodunit == 'd': ...
[ "def", "_convert_pattern", "(", "p_length", ",", "p_periodunit", ",", "p_offset", "=", "None", ")", ":", "result", "=", "None", "p_offset", "=", "p_offset", "or", "date", ".", "today", "(", ")", "p_length", "=", "int", "(", "p_length", ")", "if", "p_peri...
31.636364
0.001395
def create_sequence_pretty_tensor(sequence_input, shape=None, save_state=True): """Creates a PrettyTensor object for the given sequence. The first dimension is treated as a time-dimension * batch and a default is set for `unroll` and `state_saver`. TODO(eiderman): Remove shape. Args: sequence_input: A ...
[ "def", "create_sequence_pretty_tensor", "(", "sequence_input", ",", "shape", "=", "None", ",", "save_state", "=", "True", ")", ":", "inputs", "=", "prettytensor", ".", "wrap_sequence", "(", "sequence_input", ".", "inputs", ",", "tensor_shape", "=", "shape", ")",...
39.05
0.00875
def getresponse(self): """Get the response from the server. If the HTTPConnection is in the correct state, returns an instance of HTTPResponse or of whatever object is returned by class the response_class variable. If a request has not been sent or if a previous response has ...
[ "def", "getresponse", "(", "self", ")", ":", "# if a prior response has been completed, then forget about it.", "if", "self", ".", "__response", "and", "self", ".", "__response", ".", "isclosed", "(", ")", ":", "self", ".", "__response", "=", "None", "# if a prior r...
41.407407
0.000874
def url_escape(value: Union[str, bytes], plus: bool = True) -> str: """Returns a URL-encoded version of the given value. If ``plus`` is true (the default), spaces will be represented as "+" instead of "%20". This is appropriate for query strings but not for the path component of a URL. Note that this...
[ "def", "url_escape", "(", "value", ":", "Union", "[", "str", ",", "bytes", "]", ",", "plus", ":", "bool", "=", "True", ")", "->", "str", ":", "quote", "=", "urllib", ".", "parse", ".", "quote_plus", "if", "plus", "else", "urllib", ".", "parse", "."...
40.384615
0.001862
def doi(self): """ https://es.wikipedia.org/wiki/Identificador_de_objeto_digital :return: a random Spanish CIF or NIE or NIF """ return random.choice([self.cif, self.nie, self.nif])()
[ "def", "doi", "(", "self", ")", ":", "return", "random", ".", "choice", "(", "[", "self", ".", "cif", ",", "self", ".", "nie", ",", "self", ".", "nif", "]", ")", "(", ")" ]
31.142857
0.008929
def delayedQuoteDF(symbol, token='', version=''): '''This returns the 15 minute delayed market quote. https://iexcloud.io/docs/api/#delayed-quote 15min delayed 4:30am - 8pm ET M-F when market is open Args: symbol (string); Ticker to request token (string); Access token vers...
[ "def", "delayedQuoteDF", "(", "symbol", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "df", "=", "pd", ".", "io", ".", "json", ".", "json_normalize", "(", "delayedQuote", "(", "symbol", ",", "token", ",", "version", ")", ")", "_toDate...
26.789474
0.001898
def load(self, filename): """Loads a config from disk""" content = open(filename) return Config(json.load(content))
[ "def", "load", "(", "self", ",", "filename", ")", ":", "content", "=", "open", "(", "filename", ")", "return", "Config", "(", "json", ".", "load", "(", "content", ")", ")" ]
34
0.014388
def to_rgba(colors, dtype=np.uint8): """ Convert a single or multiple RGB colors to RGBA colors. Parameters ---------- colors: (n,[3|4]) list of RGB or RGBA colors Returns ---------- colors: (n,4) list of RGBA colors (4,) single RGBA color """ if not util.is_sequen...
[ "def", "to_rgba", "(", "colors", ",", "dtype", "=", "np", ".", "uint8", ")", ":", "if", "not", "util", ".", "is_sequence", "(", "colors", ")", ":", "return", "# colors as numpy array", "colors", "=", "np", ".", "asanyarray", "(", "colors", ")", "# intege...
28.162791
0.000798
def dl_files(db, dl_dir, files, keep_subdirs=True, overwrite=False): """ Download specified files from a Physiobank database. Parameters ---------- db : str The Physiobank database directory to download. eg. For database: 'http://physionet.org/physiobank/database/mitdb', db='mitdb'....
[ "def", "dl_files", "(", "db", ",", "dl_dir", ",", "files", ",", "keep_subdirs", "=", "True", ",", "overwrite", "=", "False", ")", ":", "# Full url physiobank database", "db_url", "=", "posixpath", ".", "join", "(", "config", ".", "db_index_url", ",", "db", ...
39.436364
0.0009
def adapt_animation_layout(animation): """ Adapt the setter in an animation's layout so that Strip animations can run on on Matrix, Cube, or Circle layout, and Matrix or Cube animations can run on a Strip layout. """ layout = animation.layout required = getattr(animation, 'LAYOUT_CLASS', Non...
[ "def", "adapt_animation_layout", "(", "animation", ")", ":", "layout", "=", "animation", ".", "layout", "required", "=", "getattr", "(", "animation", ",", "'LAYOUT_CLASS'", ",", "None", ")", "if", "not", "required", "or", "isinstance", "(", "layout", ",", "r...
28.784314
0.000659
def findByPrefix(self, term, limit=20, searchSynonyms='true', searchAbbreviations='false', searchAcronyms='false', includeDeprecated='false', category=None, prefix=None): """ Find a concept by its prefix from: /vocabulary/autocomplete/{term} Arguments: term: Term prefix to find ...
[ "def", "findByPrefix", "(", "self", ",", "term", ",", "limit", "=", "20", ",", "searchSynonyms", "=", "'true'", ",", "searchAbbreviations", "=", "'false'", ",", "searchAcronyms", "=", "'false'", ",", "includeDeprecated", "=", "'false'", ",", "category", "=", ...
68.157895
0.012186
def adjoin(space, *lists, **kwargs): """ Glues together two sets of strings using the amount of space requested. The idea is to prettify. ---------- space : int number of spaces for padding lists : str list of str which being joined strlen : callable function used to...
[ "def", "adjoin", "(", "space", ",", "*", "lists", ",", "*", "*", "kwargs", ")", ":", "strlen", "=", "kwargs", ".", "pop", "(", "'strlen'", ",", "len", ")", "justfunc", "=", "kwargs", ".", "pop", "(", "'justfunc'", ",", "justify", ")", "out_lines", ...
32.424242
0.000907