text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def buildData(self, key, default=None): """ Returns the build information for the given key. :param key | <str> default | <variant> :return <variant> """ return self._buildData.get(nativestring(key), default)
[ "def", "buildData", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "return", "self", ".", "_buildData", ".", "get", "(", "nativestring", "(", "key", ")", ",", "default", ")" ]
30.7
0.012658
def venn(args): """ %prog venn *.benchmark Display benchmark results as Venn diagram. """ from matplotlib_venn import venn2 p = OptionParser(venn.__doc__) opts, args, iopts = p.set_image_options(args, figsize="9x9") if len(args) < 1: sys.exit(not p.print_help()) bcs = arg...
[ "def", "venn", "(", "args", ")", ":", "from", "matplotlib_venn", "import", "venn2", "p", "=", "OptionParser", "(", "venn", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"...
35.472727
0.000998
def playlist_create( self, name, description='', *, make_public=False, songs=None ): """Create a playlist. Parameters: name (str): Name to give the playlist. description (str): Description to give the playlist. make_public (bool, Optional): If ``True`` and account has a subscription, make...
[ "def", "playlist_create", "(", "self", ",", "name", ",", "description", "=", "''", ",", "*", ",", "make_public", "=", "False", ",", "songs", "=", "None", ")", ":", "share_state", "=", "'PUBLIC'", "if", "make_public", "else", "'PRIVATE'", "playlist", "=", ...
19.828571
0.041209
def _imputeMissing(X, center=True, unit=True, betaNotUnitVariance=False, betaA=1.0, betaB=1.0): ''' fill in missing values in the SNP matrix by the mean value optionally center the data and unit-variance it Args: X: scipy.array of SNP values. If dtype=='int8' the missin...
[ "def", "_imputeMissing", "(", "X", ",", "center", "=", "True", ",", "unit", "=", "True", ",", "betaNotUnitVariance", "=", "False", ",", "betaA", "=", "1.0", ",", "betaB", "=", "1.0", ")", ":", "typeX", "=", "X", ".", "dtype", "if", "typeX", "!=", "...
43.926471
0.017027
def store_item(self, item): ''' use this function to store a python object in the database ''' #print('storing item', item) item_id = self._id_of(item) #print('item_id', item_id) if item_id is None: #print('storing item', item) blob = self.serialize(item) ...
[ "def", "store_item", "(", "self", ",", "item", ")", ":", "#print('storing item', item)", "item_id", "=", "self", ".", "_id_of", "(", "item", ")", "#print('item_id', item_id)", "if", "item_id", "is", "None", ":", "#print('storing item', item)", "blob", "=", "self",...
36.714286
0.009488
def copy(self): """Return a copy""" mapping = OrderedDict(self.mapping.items()) return self.__class__(self.key, self.value, mapping)
[ "def", "copy", "(", "self", ")", ":", "mapping", "=", "OrderedDict", "(", "self", ".", "mapping", ".", "items", "(", ")", ")", "return", "self", ".", "__class__", "(", "self", ".", "key", ",", "self", ".", "value", ",", "mapping", ")" ]
38.25
0.012821
def _folder_item_method(self, analysis_brain, item): """Fills the analysis' method to the item passed in. :param analysis_brain: Brain that represents an analysis :param item: analysis' dictionary counterpart that represents a row """ is_editable = self.is_analysis_edition_allo...
[ "def", "_folder_item_method", "(", "self", ",", "analysis_brain", ",", "item", ")", ":", "is_editable", "=", "self", ".", "is_analysis_edition_allowed", "(", "analysis_brain", ")", "method_title", "=", "analysis_brain", ".", "getMethodTitle", "item", "[", "'Method'"...
47.380952
0.00197
def _process_all_allele_mutation_view(self, limit): """ This fetches the mutation type for the alleles, and maps them to the sequence alteration. Note that we create a BNode for the sequence alteration because it isn't publicly identified. <sequence alteration id> a <SO:m...
[ "def", "_process_all_allele_mutation_view", "(", "self", ",", "limit", ")", ":", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else", ":", "graph", "=", "self", ".", "graph", "model", "=", "Model", "(", "graph", ")", "line...
41.870968
0.002258
def emit(self, msg, level=1, debug=False): """ Emit a message to the user. :param msg: The message to emit. If ``debug`` is ``True``, the message will be emitted to ``stderr`` only if the ``debug`` attribute is ``True``. If ``debug`` ...
[ "def", "emit", "(", "self", ",", "msg", ",", "level", "=", "1", ",", "debug", "=", "False", ")", ":", "# Is it a debug message?", "if", "debug", ":", "if", "not", "self", ".", "debug", ":", "# Debugging not enabled, don't emit the message", "return", "stream",...
39.705882
0.001446
def download_fastqc_reports(self,download_dir): """ Downloads the QC report from the DNAnexus sequencing results project. Args: download_dir: `str` - The local directory path to download the QC report to. Returns: `str`. The filepath to the downloaded ...
[ "def", "download_fastqc_reports", "(", "self", ",", "download_dir", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "download_dir", ")", ":", "os", ".", "makedirs", "(", "download_dir", ")", "msg", "=", "\"the FASTQC reports to {download_dir}.\"", ...
45.611111
0.0179
def p_file_cr_text(self, f_term, predicate): """Sets file copyright text.""" try: for _, _, cr_text in self.graph.triples((f_term, predicate, None)): self.builder.set_file_copyright(self.doc, six.text_type(cr_text)) except CardinalityError: self.more_than_...
[ "def", "p_file_cr_text", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "try", ":", "for", "_", ",", "_", ",", "cr_text", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "self",...
49.428571
0.008523
def _osx_skype_status(status, message): """ Updates status and message for Skype IM application on Mac OSX. `status` Status type. `message` Status message. """ # XXX: Skype has a bug with it's applescript support on Snow Leopard # where it will ignore the "n...
[ "def", "_osx_skype_status", "(", "status", ",", "message", ")", ":", "# XXX: Skype has a bug with it's applescript support on Snow Leopard", "# where it will ignore the \"not exists process\" expression when", "# combined with \"tell application Skype\" and thus launches Skype if", "# it's not...
34.464286
0.000336
def destroy(name, call=None): """ This function irreversibly destroys a virtual machine on the cloud provider. Before doing so, it should fire an event on the Salt event bus. The tag for this event is `salt/cloud/<vm name>/destroying`. Once the virtual machine has been destroyed, another event is f...
[ "def", "destroy", "(", "name", ",", "call", "=", "None", ")", ":", "log", ".", "info", "(", "\"Attempting to delete instance %s\"", ",", "name", ")", "if", "not", "vb_machine_exists", "(", "name", ")", ":", "return", "\"{0} doesn't exist and can't be deleted\"", ...
29.357143
0.00157
def new(ruletype, **kwargs): """Instantiate a new build rule based on kwargs. Appropriate args list varies with rule type. Minimum args required: [... fill this in ...] """ try: ruleclass = TYPE_MAP[ruletype] except KeyError: raise error.InvalidRule('Unrecognized rule type...
[ "def", "new", "(", "ruletype", ",", "*", "*", "kwargs", ")", ":", "try", ":", "ruleclass", "=", "TYPE_MAP", "[", "ruletype", "]", "except", "KeyError", ":", "raise", "error", ".", "InvalidRule", "(", "'Unrecognized rule type: %s'", "%", "ruletype", ")", "t...
27.823529
0.002045
def check(ctx, repository, config): """Check commits.""" ctx.obj = Repo(repository=repository, config=config)
[ "def", "check", "(", "ctx", ",", "repository", ",", "config", ")", ":", "ctx", ".", "obj", "=", "Repo", "(", "repository", "=", "repository", ",", "config", "=", "config", ")" ]
38.333333
0.008547
def _populate_union_type_attributes(self, env, data_type): """ Converts a forward reference of a union into a complete definition. """ parent_type = None extends = data_type._ast_node.extends if extends: # A parent type must be fully defined and not just a for...
[ "def", "_populate_union_type_attributes", "(", "self", ",", "env", ",", "data_type", ")", ":", "parent_type", "=", "None", "extends", "=", "data_type", ".", "_ast_node", ".", "extends", "if", "extends", ":", "# A parent type must be fully defined and not just a forward"...
49.054545
0.001453
def xclaim(self, name, groupname, consumername, min_idle_time, message_ids, idle=None, time=None, retrycount=None, force=False, justid=False): """ Changes the ownership of a pending message. name: name of the stream. groupname: name of the consumer group. ...
[ "def", "xclaim", "(", "self", ",", "name", ",", "groupname", ",", "consumername", ",", "min_idle_time", ",", "message_ids", ",", "idle", "=", "None", ",", "time", "=", "None", ",", "retrycount", "=", "None", ",", "force", "=", "False", ",", "justid", "...
50.762712
0.00131
def filter_gene_list(stmts_in, gene_list, policy, allow_families=False, **kwargs): """Return statements that contain genes given in a list. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. gene_list : list[str] A ...
[ "def", "filter_gene_list", "(", "stmts_in", ",", "gene_list", ",", "policy", ",", "allow_families", "=", "False", ",", "*", "*", "kwargs", ")", ":", "invert", "=", "kwargs", ".", "get", "(", "'invert'", ",", "False", ")", "remove_bound", "=", "kwargs", "...
39.190476
0.000711
def popattr(obj, attr, default=NOT_PROVIDED): """ Useful for retrieving an object attr and removing it if it's part of it's dict while allowing retrieving from subclass. i.e. class A: a = 'a' class B(A): b = 'b' >>> popattr(B, 'a', None) 'a' >>> A.a 'a' """ ...
[ "def", "popattr", "(", "obj", ",", "attr", ",", "default", "=", "NOT_PROVIDED", ")", ":", "val", "=", "getattr", "(", "obj", ",", "attr", ",", "default", ")", "try", ":", "delattr", "(", "obj", ",", "attr", ")", "except", "AttributeError", ":", "if",...
22.238095
0.002053
def radialrange(self, origin, return_all_global_extrema=False): """returns the tuples (d_min, t_min) and (d_max, t_max) which minimize and maximize, respectively, the distance d = |self.point(t)-origin|.""" return bezier_radialrange(self, origin, return_all_global_extrema=return_...
[ "def", "radialrange", "(", "self", ",", "origin", ",", "return_all_global_extrema", "=", "False", ")", ":", "return", "bezier_radialrange", "(", "self", ",", "origin", ",", "return_all_global_extrema", "=", "return_all_global_extrema", ")" ]
67
0.00885
def download_object(self, obj_name, directory, structure=True): """ Alias for self.download(); included for backwards compatibility """ return self.download(obj=obj_name, directory=directory, structure=structure)
[ "def", "download_object", "(", "self", ",", "obj_name", ",", "directory", ",", "structure", "=", "True", ")", ":", "return", "self", ".", "download", "(", "obj", "=", "obj_name", ",", "directory", "=", "directory", ",", "structure", "=", "structure", ")" ]
42.5
0.011538
def find_candidates(word_string): ''' Finds all potential words word_string could have intended to mean. If a word is not incorrectly spelled, it will return this word first, else if will look for one letter edits that are correct. If there are no valid one letter edits, it will perform a two letter edi...
[ "def", "find_candidates", "(", "word_string", ")", ":", "if", "word_string", "is", "None", ":", "return", "{", "}", "elif", "isinstance", "(", "word_string", ",", "str", ")", ":", "return", "(", "validate_words", "(", "[", "word_string", "]", ")", "or", ...
55.0625
0.008929
def on_touch_move(self, touch): """Move the scrollbar to the touch, and update my ``scroll`` accordingly. """ if not self.scrolling or 'bar' not in self.ids: touch.ungrab(self) return touch.push() touch.apply_transform_2d(self.parent.to_local) ...
[ "def", "on_touch_move", "(", "self", ",", "touch", ")", ":", "if", "not", "self", ".", "scrolling", "or", "'bar'", "not", "in", "self", ".", "ids", ":", "touch", ".", "ungrab", "(", "self", ")", "return", "touch", ".", "push", "(", ")", "touch", "....
42.15
0.00232
def uint8_3(self, name): """parse a tuple of 3 uint8 values""" self._assert_is_string(name) frame = self._next_frame() if len(frame) != 3: raise MessageParserError("Expected exacty 3 byte for 3 unit8 values") vals = unpack("BBB", frame) self.results.__dict__[n...
[ "def", "uint8_3", "(", "self", ",", "name", ")", ":", "self", ".", "_assert_is_string", "(", "name", ")", "frame", "=", "self", ".", "_next_frame", "(", ")", "if", "len", "(", "frame", ")", "!=", "3", ":", "raise", "MessageParserError", "(", "\"Expecte...
38.111111
0.008547
def get_info_for_reshard(stream_details): """ Collect some data: number of open shards, key range, etc. Modifies stream_details to add a sorted list of OpenShards. Returns (min_hash_key, max_hash_key, stream_details) CLI example:: salt myminion boto_kinesis.get_info_for_reshard existing_st...
[ "def", "get_info_for_reshard", "(", "stream_details", ")", ":", "min_hash_key", "=", "0", "max_hash_key", "=", "0", "stream_details", "[", "\"OpenShards\"", "]", "=", "[", "]", "for", "shard", "in", "stream_details", "[", "\"Shards\"", "]", ":", "shard_id", "=...
45.870968
0.001377
def is_writable(self): """ Currently only works with hadoopcli """ if "/" in self.path: # example path: /log/ap/2013-01-17/00 parts = self.path.split("/") # start with the full path and then up the tree until we can check length = len(parts...
[ "def", "is_writable", "(", "self", ")", ":", "if", "\"/\"", "in", "self", ".", "path", ":", "# example path: /log/ap/2013-01-17/00", "parts", "=", "self", ".", "path", ".", "split", "(", "\"/\"", ")", "# start with the full path and then up the tree until we can check...
40.857143
0.002278
def soap_fault(message=None, actor=None, code=None, detail=None): """ Create a SOAP Fault message :param message: Human readable error message :param actor: Who discovered the error :param code: Error code :param detail: More specific error message :return: A SOAP Fault message as a string ...
[ "def", "soap_fault", "(", "message", "=", "None", ",", "actor", "=", "None", ",", "code", "=", "None", ",", "detail", "=", "None", ")", ":", "_string", "=", "_actor", "=", "_code", "=", "_detail", "=", "None", "if", "message", ":", "_string", "=", ...
27.857143
0.001239
def export_ownertrust(cls, trustdb=None): """Export ownertrust to a trustdb file. If there is already a file named :file:`trustdb.gpg` in the current GnuPG homedir, it will be renamed to :file:`trustdb.gpg.bak`. :param string trustdb: The path to the trustdb.gpg file. If not given, ...
[ "def", "export_ownertrust", "(", "cls", ",", "trustdb", "=", "None", ")", ":", "if", "trustdb", "is", "None", ":", "trustdb", "=", "os", ".", "path", ".", "join", "(", "cls", ".", "homedir", ",", "'trustdb.gpg'", ")", "try", ":", "os", ".", "rename",...
35.363636
0.001252
def _merge_beam_dim(tensor): """Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...] """ shape = common_layers.shape_list(tensor) shape[0] *= shape[1] # batch -> batch * beam_size shape.pop(1) # ...
[ "def", "_merge_beam_dim", "(", "tensor", ")", ":", "shape", "=", "common_layers", ".", "shape_list", "(", "tensor", ")", "shape", "[", "0", "]", "*=", "shape", "[", "1", "]", "# batch -> batch * beam_size", "shape", ".", "pop", "(", "1", ")", "# Remove bea...
27.538462
0.016216
def to_frame(self, data, state): """ Extract a single frame from the data buffer. The consumed data should be removed from the buffer. If no complete frame can be read, must raise a ``NoFrames`` exception. :param data: A ``bytearray`` instance containing the data so ...
[ "def", "to_frame", "(", "self", ",", "data", ",", "state", ")", ":", "# If we've read all the data, let the caller know", "if", "state", ".", "chunk_remaining", "<=", "0", ":", "raise", "exc", ".", "NoFrames", "(", ")", "# OK, how much data do we send on?", "data_le...
35.424242
0.001665
def extend(dset, array, **attrs): """ Extend an extensible dataset with an array of a compatible dtype. :param dset: an h5py dataset :param array: an array of length L :returns: the total length of the dataset (i.e. initial length + L) """ length = len(dset) if len(array) == 0: ...
[ "def", "extend", "(", "dset", ",", "array", ",", "*", "*", "attrs", ")", ":", "length", "=", "len", "(", "dset", ")", "if", "len", "(", "array", ")", "==", "0", ":", "return", "length", "newlength", "=", "length", "+", "len", "(", "array", ")", ...
31
0.00149
def elementMaker(name, *children, **attrs): """ Construct a string from the HTML element description. """ formattedAttrs = ' '.join('{}={}'.format(key, _gvquote(str(value))) for key, value in sorted(attrs.items())) formattedChildren = ''.join(children) return u'<{na...
[ "def", "elementMaker", "(", "name", ",", "*", "children", ",", "*", "*", "attrs", ")", ":", "formattedAttrs", "=", "' '", ".", "join", "(", "'{}={}'", ".", "format", "(", "key", ",", "_gvquote", "(", "str", "(", "value", ")", ")", ")", "for", "key"...
39.545455
0.002247
def write(self, filename, arcname=None, compress_type=None): """Put the bytes from filename into the archive under the name arcname.""" if not self.fp: raise RuntimeError( "Attempt to write to ZIP archive that was already closed") st = os.stat(filename) ...
[ "def", "write", "(", "self", ",", "filename", ",", "arcname", "=", "None", ",", "compress_type", "=", "None", ")", ":", "if", "not", "self", ".", "fp", ":", "raise", "RuntimeError", "(", "\"Attempt to write to ZIP archive that was already closed\"", ")", "st", ...
42.38835
0.000671
def peer_express_route_circuit_connections(self): """Instance depends on the API version: * 2018-12-01: :class:`PeerExpressRouteCircuitConnectionsOperations<azure.mgmt.network.v2018_12_01.operations.PeerExpressRouteCircuitConnectionsOperations>` * 2019-02-01: :class:`PeerExpressRouteCircu...
[ "def", "peer_express_route_circuit_connections", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'peer_express_route_circuit_connections'", ")", "if", "api_version", "==", "'2018-12-01'", ":", "from", ".", "v2018_12_01", ".", "operation...
76.714286
0.00828
async def set_default_min_hwe_kernel(cls, version: typing.Optional[str]): """See `get_default_min_hwe_kernel`.""" await cls.set_config( "default_min_hwe_kernel", "" if version is None else version)
[ "async", "def", "set_default_min_hwe_kernel", "(", "cls", ",", "version", ":", "typing", ".", "Optional", "[", "str", "]", ")", ":", "await", "cls", ".", "set_config", "(", "\"default_min_hwe_kernel\"", ",", "\"\"", "if", "version", "is", "None", "else", "ve...
55.5
0.008889
def iterread(self, table): """Iteratively read data from a GTFS table. Returns namedtuples.""" self.log('Reading: %s'%table) # Entity class cls = self.FACTORIES[table] f = self._open(table) # csv reader if unicodecsv: data = unicodecsv.reader(f, encoding='utf-8-sig') else: da...
[ "def", "iterread", "(", "self", ",", "table", ")", ":", "self", ".", "log", "(", "'Reading: %s'", "%", "table", ")", "# Entity class", "cls", "=", "self", ".", "FACTORIES", "[", "table", "]", "f", "=", "self", ".", "_open", "(", "table", ")", "# csv ...
28.148148
0.012723
def API520_W(Pset, Pback): r'''Calculates capacity correction due to backpressure on balanced spring-loaded PRVs in liquid service. For pilot operated valves, this is always 1. Applicable up to 50% of the percent gauge backpressure, For use in API 520 relief valve sizing. 1D interpolation among a table ...
[ "def", "API520_W", "(", "Pset", ",", "Pback", ")", ":", "gauge_backpressure", "=", "(", "Pback", "-", "atm", ")", "/", "(", "Pset", "-", "atm", ")", "*", "100.0", "# in percent", "if", "gauge_backpressure", "<", "15.0", ":", "return", "1.0", "return", ...
26.974359
0.001835
def ClientCertFromCSR(cls, csr): """Creates a new cert for the given common name. Args: csr: A CertificateSigningRequest. Returns: The signed cert. """ builder = x509.CertificateBuilder() # Use the client CN for a cert serial_id. This will ensure we do # not have clashing cert ...
[ "def", "ClientCertFromCSR", "(", "cls", ",", "csr", ")", ":", "builder", "=", "x509", ".", "CertificateBuilder", "(", ")", "# Use the client CN for a cert serial_id. This will ensure we do", "# not have clashing cert id.", "common_name", "=", "csr", ".", "GetCN", "(", "...
36.046512
0.000628
def default (self): """The default sequence command attributes (as an integer).""" byte = 0 for bit, name, value0, value1, default in SeqCmdAttrs.Table: if default == value1: byte = setBit(byte, bit, 1) return byte
[ "def", "default", "(", "self", ")", ":", "byte", "=", "0", "for", "bit", ",", "name", ",", "value0", ",", "value1", ",", "default", "in", "SeqCmdAttrs", ".", "Table", ":", "if", "default", "==", "value1", ":", "byte", "=", "setBit", "(", "byte", ",...
34
0.012295
def copyWorkitem(self, copied_from, title=None, description=None, prefix=None): """Create a workitem by copying from an existing one :param copied_from: the to-be-copied workitem id :param title: the new workitem title/summary. If `None`, will copy that from a t...
[ "def", "copyWorkitem", "(", "self", ",", "copied_from", ",", "title", "=", "None", ",", "description", "=", "None", ",", "prefix", "=", "None", ")", ":", "copied_wi", "=", "self", ".", "getWorkitem", "(", "copied_from", ")", "if", "title", "is", "None", ...
44.717949
0.001684
def run_script(self, args, event_writer, input_stream): """Handles all the specifics of running a modular input :param args: List of command line arguments passed to this script. :param event_writer: An ``EventWriter`` object for writing events. :param input_stream: An input stream for ...
[ "def", "run_script", "(", "self", ",", "args", ",", "event_writer", ",", "input_stream", ")", ":", "try", ":", "if", "len", "(", "args", ")", "==", "1", ":", "# This script is running as an input. Input definitions will be", "# passed on stdin as XML, and the script wil...
43.057692
0.001747
def Search(self,key): """Search disk list by partial mount point or ID """ results = [] for disk in self.disks: if disk.id.lower().find(key.lower()) != -1: results.append(disk) # TODO - search in list to match partial mount points elif key.lower() in disk.partition_paths: results.append(disk) re...
[ "def", "Search", "(", "self", ",", "key", ")", ":", "results", "=", "[", "]", "for", "disk", "in", "self", ".", "disks", ":", "if", "disk", ".", "id", ".", "lower", "(", ")", ".", "find", "(", "key", ".", "lower", "(", ")", ")", "!=", "-", ...
26.833333
0.039039
def _configDevActive(self, namestr, titlestr, devlist): """Generate configuration for I/O Queue Length. @param namestr: Field name component indicating device type. @param titlestr: Title component indicating device type. @param devlist: List of devices. """ ...
[ "def", "_configDevActive", "(", "self", ",", "namestr", ",", "titlestr", ",", "devlist", ")", ":", "name", "=", "'diskio_%s_active'", "%", "namestr", "if", "self", ".", "graphEnabled", "(", "name", ")", ":", "graph", "=", "MuninGraph", "(", "'Disk I/O - %s -...
48.347826
0.017637
def _CreateDynamicDisplayAdSettings(media_service, opener): """Creates settings for dynamic display ad. Args: media_service: a SudsServiceProxy instance for AdWords's MediaService. opener: an OpenerDirector instance. Returns: The dynamic display ad settings. """ image = _CreateImage(media_servic...
[ "def", "_CreateDynamicDisplayAdSettings", "(", "media_service", ",", "opener", ")", ":", "image", "=", "_CreateImage", "(", "media_service", ",", "opener", ",", "'https://goo.gl/dEvQeF'", ")", "logo", "=", "{", "'type'", ":", "'IMAGE'", ",", "'mediaId'", ":", "i...
24.115385
0.009202
def _group_tasks_by_name_and_status(task_dict): """ Takes a dictionary with sets of tasks grouped by their status and returns a dictionary with dictionaries with an array of tasks grouped by their status and task name """ group_status = {} for task in task_dict: if task.task_family n...
[ "def", "_group_tasks_by_name_and_status", "(", "task_dict", ")", ":", "group_status", "=", "{", "}", "for", "task", "in", "task_dict", ":", "if", "task", ".", "task_family", "not", "in", "group_status", ":", "group_status", "[", "task", ".", "task_family", "]"...
37.666667
0.00216
def visitParam_def(self, ctx:SystemRDLParser.Param_defContext): """ Parameter Definition block """ self.compiler.namespace.enter_scope() param_defs = [] for elem in ctx.getTypedRuleContexts(SystemRDLParser.Param_def_elemContext): param_def = self.visit(elem) ...
[ "def", "visitParam_def", "(", "self", ",", "ctx", ":", "SystemRDLParser", ".", "Param_defContext", ")", ":", "self", ".", "compiler", ".", "namespace", ".", "enter_scope", "(", ")", "param_defs", "=", "[", "]", "for", "elem", "in", "ctx", ".", "getTypedRul...
32.307692
0.009259
def _construct_manpage_specific_structure(self, parser_info): """ Construct a typical man page consisting of the following elements: NAME (automatically generated, out of our control) SYNOPSIS DESCRIPTION OPTIONS FILES SEE ALSO ...
[ "def", "_construct_manpage_specific_structure", "(", "self", ",", "parser_info", ")", ":", "items", "=", "[", "]", "# SYNOPSIS section", "synopsis_section", "=", "nodes", ".", "section", "(", "''", ",", "nodes", ".", "title", "(", "text", "=", "'Synopsis'", ")...
42.790698
0.000797
def do_help(self, options, args, parser): """Deal with help requests. Return True if it handled the request, False if not. """ # Handle help. if options.help: if self.classic: self.help_fn(topic='help') else: self.help_fn(...
[ "def", "do_help", "(", "self", ",", "options", ",", "args", ",", "parser", ")", ":", "# Handle help.", "if", "options", ".", "help", ":", "if", "self", ".", "classic", ":", "self", ".", "help_fn", "(", "topic", "=", "'help'", ")", "else", ":", "self"...
26.3125
0.002291
def inasafe_field_header(field, feature, parent): """Retrieve a header name of the field name from definitions. For instance: inasafe_field_header('minimum_needs__clean_water') -> 'Clean water' """ _ = feature, parent # NOQA age_fields = [under_5_displaced_count_field, over_60_displaced_count_...
[ "def", "inasafe_field_header", "(", "field", ",", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "age_fields", "=", "[", "under_5_displaced_count_field", ",", "over_60_displaced_count_field", "]", "symbol_mapping", "=", "{", "'ov...
35.294118
0.000811
def handle_profile_form(form): """Handle profile update form.""" form.process(formdata=request.form) if form.validate_on_submit(): email_changed = False with db.session.begin_nested(): # Update profile. current_userprofile.username = form.username.data cu...
[ "def", "handle_profile_form", "(", "form", ")", ":", "form", ".", "process", "(", "formdata", "=", "request", ".", "form", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "email_changed", "=", "False", "with", "db", ".", "session", ".", "beg...
41
0.000769
def exchange_bind(self, destination, source='', routing_key='', nowait=False, arguments=None): """This method binds an exchange to an exchange. RULE: A server MUST allow and ignore duplicate bindings - that is, two or more bind methods for a specific excha...
[ "def", "exchange_bind", "(", "self", ",", "destination", ",", "source", "=", "''", ",", "routing_key", "=", "''", ",", "nowait", "=", "False", ",", "arguments", "=", "None", ")", ":", "arguments", "=", "{", "}", "if", "arguments", "is", "None", "else",...
30.057471
0.001111
def _get_names(self, path: str) -> Iterator[str]: """Load required packages from path to requirements file """ for i in RequirementsFinder._get_names_cached(path): yield i
[ "def", "_get_names", "(", "self", ",", "path", ":", "str", ")", "->", "Iterator", "[", "str", "]", ":", "for", "i", "in", "RequirementsFinder", ".", "_get_names_cached", "(", "path", ")", ":", "yield", "i" ]
40.6
0.009662
def cached(f): """ Cache decorator for functions taking one or more arguments. :param f: The function to be cached. :return: The cached value. """ cache = f.cache = {} @functools.wraps(f) def decorator(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache:...
[ "def", "cached", "(", "f", ")", ":", "cache", "=", "f", ".", "cache", "=", "{", "}", "@", "functools", ".", "wraps", "(", "f", ")", "def", "decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "key", "=", "str", "(", "args", ")", ...
24.75
0.002433
def image_import(self, image_name, url, image_meta, remote_host=None): """Import image to zvmsdk image repository :param image_name: image name that can be uniquely identify an image :param str url: image url to specify the location of image such as http://netloc/path/to/file.tar...
[ "def", "image_import", "(", "self", ",", "image_name", ",", "url", ",", "image_meta", ",", "remote_host", "=", "None", ")", ":", "try", ":", "self", ".", "_imageops", ".", "image_import", "(", "image_name", ",", "url", ",", "image_meta", ",", "remote_host"...
51.346154
0.001471
def create(self, name, description=None, image_url=None, share=None, **kwargs): """Create a new group. Note that, although possible, there may be issues when not using an image URL from GroupMe's image service. :param str name: group name (140 characters maximum) :param str des...
[ "def", "create", "(", "self", ",", "name", ",", "description", "=", "None", ",", "image_url", "=", "None", ",", "share", "=", "None", ",", "*", "*", "kwargs", ")", ":", "payload", "=", "{", "'name'", ":", "name", ",", "'description'", ":", "descripti...
38.772727
0.002288
def resume_with_reason(self, reason): """Internal method for triggering a VM resume with a specified reason code. The reason code can be interpreted by device/drivers and thus it might behave slightly differently than a normal VM resume. :py:func:`IConsole.resume` ...
[ "def", "resume_with_reason", "(", "self", ",", "reason", ")", ":", "if", "not", "isinstance", "(", "reason", ",", "Reason", ")", ":", "raise", "TypeError", "(", "\"reason can only be an instance of type Reason\"", ")", "self", ".", "_call", "(", "\"resumeWithReaso...
37
0.010778
def terrain_request_send(self, lat, lon, grid_spacing, mask, force_mavlink1=False): ''' Request for terrain data and terrain status lat : Latitude of SW corner of first grid (degrees *10^7) (int32_t) lon : Longi...
[ "def", "terrain_request_send", "(", "self", ",", "lat", ",", "lon", ",", "grid_spacing", ",", "mask", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "terrain_request_encode", "(", "lat", ",", "lon", ",", "...
65.272727
0.009615
def crossover(cross): """Return an inspyred crossover function based on the given function. This function generator takes a function that operates on only two parent candidates to produce an iterable sequence of offspring (typically two). The generator handles the pairing of selected parents and co...
[ "def", "crossover", "(", "cross", ")", ":", "@", "functools", ".", "wraps", "(", "cross", ")", "def", "inspyred_crossover", "(", "random", ",", "candidates", ",", "args", ")", ":", "if", "len", "(", "candidates", ")", "%", "2", "==", "1", ":", "candi...
36.347826
0.000582
def _py_clean(parameter, tab): """Returns the code line to clean the output value of the specified parameter. """ if "out" in parameter.direction: if parameter.D > 0: if ":" in parameter.dimension and ("allocatable" in parameter.modifiers or ...
[ "def", "_py_clean", "(", "parameter", ",", "tab", ")", ":", "if", "\"out\"", "in", "parameter", ".", "direction", ":", "if", "parameter", ".", "D", ">", "0", ":", "if", "\":\"", "in", "parameter", ".", "dimension", "and", "(", "\"allocatable\"", "in", ...
61.346154
0.01358
def homoscedasticity(*args, alpha=.05): """Test equality of variance. Parameters ---------- sample1, sample2,... : array_like Array of sample data. May be different lengths. Returns ------- equal_var : boolean True if data have equal variance. p : float P-value....
[ "def", "homoscedasticity", "(", "*", "args", ",", "alpha", "=", ".05", ")", ":", "from", "scipy", ".", "stats", "import", "levene", ",", "bartlett", "k", "=", "len", "(", "args", ")", "if", "k", "<", "2", ":", "raise", "ValueError", "(", "\"Must ente...
32.327103
0.000281
def centroid_com(data, mask=None): """ Calculate the centroid of an n-dimensional array as its "center of mass" determined from moments. Invalid values (e.g. NaNs or infs) in the ``data`` array are automatically masked. Parameters ---------- data : array_like The input n-dimens...
[ "def", "centroid_com", "(", "data", ",", "mask", "=", "None", ")", ":", "data", "=", "data", ".", "astype", "(", "np", ".", "float", ")", "if", "mask", "is", "not", "None", "and", "mask", "is", "not", "np", ".", "ma", ".", "nomask", ":", "mask", ...
32.431818
0.00068
def pyang_plugin_init(): """Called by pyang plugin framework at to initialize the plugin.""" # Register the plugin plugin.register_plugin(SMIPlugin()) # Add our special argument syntax checkers syntax.add_arg_type('smi-oid', _chk_smi_oid) syntax.add_arg_type('smi-max-access', _chk_smi_max_acce...
[ "def", "pyang_plugin_init", "(", ")", ":", "# Register the plugin", "plugin", ".", "register_plugin", "(", "SMIPlugin", "(", ")", ")", "# Add our special argument syntax checkers", "syntax", ".", "add_arg_type", "(", "'smi-oid'", ",", "_chk_smi_oid", ")", "syntax", "....
43.363636
0.001367
def run_step(context): """Simple echo. Outputs context['echoMe']. Args: context: dictionary-like. context is mandatory. context must contain key 'echoMe' context['echoMe'] will echo the value to logger. This logger could well be stdout. When you e...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "assert", "context", ",", "(", "\"context must be set for echo. Did you set \"", "\"'echoMe=text here'?\"", ")", "context", ".", "assert_key_exists", "(", "'echoMe'", ",", ...
29.814815
0.001203
def get_summary(url, spk=True): ''' simple function to retrieve the header of a BSP file and return SPK object''' # connect to file at URL bspurl = urllib2.urlopen(url) # retrieve the "tip" of a file at URL bsptip = bspurl.read(10**5) # first 100kB # save data in fake file object (in-memory) ...
[ "def", "get_summary", "(", "url", ",", "spk", "=", "True", ")", ":", "# connect to file at URL", "bspurl", "=", "urllib2", ".", "urlopen", "(", "url", ")", "# retrieve the \"tip\" of a file at URL", "bsptip", "=", "bspurl", ".", "read", "(", "10", "**", "5", ...
30.526316
0.018395
def cached_download(url, name): """Download the data at a URL, and cache it under the given name. The file is stored under `pyav/test` with the given name in the directory :envvar:`PYAV_TESTDATA_DIR`, or the first that is writeable of: - the current virtualenv - ``/usr/local/share`` - ``/usr/...
[ "def", "cached_download", "(", "url", ",", "name", ")", ":", "clean_name", "=", "os", ".", "path", ".", "normpath", "(", "name", ")", "if", "clean_name", "!=", "name", ":", "raise", "ValueError", "(", "\"{} is not normalized.\"", ".", "format", "(", "name"...
24.283019
0.000747
def _augmenting_row_reduction(self): """ Augmenting row reduction step from LAPJV algorithm """ unassigned = np.where(self._x == -1)[0] for i in unassigned: for _ in range(self.c.size): # Time in this loop can be proportional to 1/epsilon ...
[ "def", "_augmenting_row_reduction", "(", "self", ")", ":", "unassigned", "=", "np", ".", "where", "(", "self", ".", "_x", "==", "-", "1", ")", "[", "0", "]", "for", "i", "in", "unassigned", ":", "for", "_", "in", "range", "(", "self", ".", "c", "...
34.774194
0.001805
def addVar(self, sig: object, name: str, sigType: VCD_SIG_TYPE, width: int, valueFormatter: Callable[["Value"], str]): """ Add variable to scope :ivar sig: user specified object to keep track of VcdVarInfo in change() :ivar sigType: vcd type name :ivar valueForma...
[ "def", "addVar", "(", "self", ",", "sig", ":", "object", ",", "name", ":", "str", ",", "sigType", ":", "VCD_SIG_TYPE", ",", "width", ":", "int", ",", "valueFormatter", ":", "Callable", "[", "[", "\"Value\"", "]", ",", "str", "]", ")", ":", "vInf", ...
49.928571
0.008427
def find_geometry(self, physics): r""" Find the Geometry associated with a given Physics Parameters ---------- physics : OpenPNM Physics Object Must be a Physics object Returns ------- An OpenPNM Geometry object Raises ------...
[ "def", "find_geometry", "(", "self", ",", "physics", ")", ":", "# If geometry happens to be in settings, look it up directly", "if", "'geometry'", "in", "physics", ".", "settings", ".", "keys", "(", ")", ":", "geom", "=", "self", ".", "geometries", "(", ")", "["...
32.071429
0.002162
def detach_popen(**kwargs): """ Use :class:`subprocess.Popen` to construct a child process, then hack the Popen so that it forgets the child it created, allowing it to survive a call to Popen.__del__. If the child process is not detached, there is a race between it exitting and __del__ being ca...
[ "def", "detach_popen", "(", "*", "*", "kwargs", ")", ":", "# This allows Popen() to be used for e.g. graceful post-fork error", "# handling, without tying the surrounding code into managing a Popen", "# object, which isn't possible for at least :mod:`mitogen.fork`. This", "# should be replaced...
41.8
0.001559
def fix_edge_pixels(self, edge_init_data, edge_init_done, edge_init_todo): """ This function fixes the pixels on the very edge of the tile. Drainage is calculated if the edge is downstream from the interior. If there is data available on the edge (from edge_init_data, for eg) the...
[ "def", "fix_edge_pixels", "(", "self", ",", "edge_init_data", ",", "edge_init_done", ",", "edge_init_todo", ")", ":", "data", ",", "dX", ",", "dY", ",", "direction", ",", "flats", "=", "self", ".", "data", ",", "self", ".", "dX", ",", "self", ".", "dY"...
51.477612
0.000569
def store_vector(self, hash_name, bucket_key, v, data): """ Stores vector and JSON-serializable data in bucket with specified key. """ if not hash_name in self.buckets: self.buckets[hash_name] = {} if not bucket_key in self.buckets[hash_name]: self.bucke...
[ "def", "store_vector", "(", "self", ",", "hash_name", ",", "bucket_key", ",", "v", ",", "data", ")", ":", "if", "not", "hash_name", "in", "self", ".", "buckets", ":", "self", ".", "buckets", "[", "hash_name", "]", "=", "{", "}", "if", "not", "bucket_...
36.545455
0.009709
def register_lcformat(formatkey, fileglob, timecols, magcols, errcols, readerfunc_module, readerfunc, readerfunc_kwargs=None, normfunc_module=No...
[ "def", "register_lcformat", "(", "formatkey", ",", "fileglob", ",", "timecols", ",", "magcols", ",", "errcols", ",", "readerfunc_module", ",", "readerfunc", ",", "readerfunc_kwargs", "=", "None", ",", "normfunc_module", "=", "None", ",", "normfunc", "=", "None",...
42.264574
0.002073
def strip_column_names(cols, keep_paren_contents=True): """ Utility script for renaming pandas columns to patsy-friendly names. Revised names have been: - stripped of all punctuation and whitespace (converted to text or `_`) - converted to lower case Takes a list of column names, retur...
[ "def", "strip_column_names", "(", "cols", ",", "keep_paren_contents", "=", "True", ")", ":", "# strip/replace punctuation", "new_cols", "=", "[", "_strip_column_name", "(", "col", ",", "keep_paren_contents", "=", "keep_paren_contents", ")", "for", "col", "in", "cols...
33.482759
0.001501
def check_ontology(fname): """ reads the ontology yaml file and does basic verifcation """ with open(fname, 'r') as stream: y = yaml.safe_load(stream) import pprint pprint.pprint(y)
[ "def", "check_ontology", "(", "fname", ")", ":", "with", "open", "(", "fname", ",", "'r'", ")", "as", "stream", ":", "y", "=", "yaml", ".", "safe_load", "(", "stream", ")", "import", "pprint", "pprint", ".", "pprint", "(", "y", ")" ]
26.25
0.009217
def parse_operand(string, location, tokens): """Parse an x86 instruction operand. """ mod = " ".join(tokens.get("modifier", "")) if "immediate" in tokens: imm = parse_immediate("".join(tokens["immediate"])) size = modifier_size.get(mod, None) oprnd = X86ImmediateOperand(imm, si...
[ "def", "parse_operand", "(", "string", ",", "location", ",", "tokens", ")", ":", "mod", "=", "\" \"", ".", "join", "(", "tokens", ".", "get", "(", "\"modifier\"", ",", "\"\"", ")", ")", "if", "\"immediate\"", "in", "tokens", ":", "imm", "=", "parse_imm...
30.625
0.001978
def fix_e305(self, result): """Add missing 2 blank lines after end of function or class.""" add_delete_linenum = 2 - int(result['info'].split()[-1]) cnt = 0 offset = result['line'] - 2 modified_lines = [] if add_delete_linenum < 0: # delete cr add_...
[ "def", "fix_e305", "(", "self", ",", "result", ")", ":", "add_delete_linenum", "=", "2", "-", "int", "(", "result", "[", "'info'", "]", ".", "split", "(", ")", "[", "-", "1", "]", ")", "cnt", "=", "0", "offset", "=", "result", "[", "'line'", "]",...
36.46875
0.001669
def __send_request(self, url, params=None): """Send request""" r = self.fetch(url, payload=params) return r.text
[ "def", "__send_request", "(", "self", ",", "url", ",", "params", "=", "None", ")", ":", "r", "=", "self", ".", "fetch", "(", "url", ",", "payload", "=", "params", ")", "return", "r", ".", "text" ]
26.6
0.014599
def ReadLink(path): ''' Read the target of the symbolic link at `path`. :param unicode path: Path to a symbolic link :returns unicode: Target of a symbolic link ''' _AssertIsLocal(path) if sys.platform != 'win32': return os.readlink(path) # @UndefinedVariable ...
[ "def", "ReadLink", "(", "path", ")", ":", "_AssertIsLocal", "(", "path", ")", "if", "sys", ".", "platform", "!=", "'win32'", ":", "return", "os", ".", "readlink", "(", "path", ")", "# @UndefinedVariable", "if", "not", "IsLink", "(", "path", ")", ":", "...
24.458333
0.001639
def DownloadFile(file_obj, target_path, buffer_size=BUFFER_SIZE): """Download an aff4 file to the local filesystem overwriting it if it exists. Args: file_obj: An aff4 object that supports the file interface (Read, Seek) target_path: Full path of file to write to. buffer_size: Read in chunks this size....
[ "def", "DownloadFile", "(", "file_obj", ",", "target_path", ",", "buffer_size", "=", "BUFFER_SIZE", ")", ":", "logging", ".", "info", "(", "u\"Downloading: %s to: %s\"", ",", "file_obj", ".", "urn", ",", "target_path", ")", "target_file", "=", "open", "(", "ta...
33.956522
0.012453
def splice(ol,start,deleteCount,*eles,**kwargs): ''' from elist.elist import * ol = ["angel", "clown", "mandarin", "surgeon"] id(ol) new = splice(ol,2,0,"drum") new id(new) #### ol = ["angel", "clown", "mandarin", "surgeon"] id(ol) new ...
[ "def", "splice", "(", "ol", ",", "start", ",", "deleteCount", ",", "*", "eles", ",", "*", "*", "kwargs", ")", ":", "if", "(", "'mode'", "in", "kwargs", ")", ":", "mode", "=", "kwargs", "[", "'mode'", "]", "else", ":", "mode", "=", "\"new\"", "len...
24.658537
0.011418
def emit(self, *args, **kwargs): """ Emits the signal, passing the given arguments to the callbacks. If one of the callbacks returns a value other than None, no further callbacks are invoked and the return value of the callback is returned to the caller of emit(). :type ...
[ "def", "emit", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "hard_subscribers", "is", "not", "None", ":", "for", "callback", ",", "user_args", ",", "user_kwargs", "in", "self", ".", "hard_subscribers", ":", "kwar...
48.536585
0.000985
def set_config(self, config): ''' Set launch data from a ToolConfig. ''' if self.launch_url == None: self.launch_url = config.launch_url self.custom_params.update(config.custom_params)
[ "def", "set_config", "(", "self", ",", "config", ")", ":", "if", "self", ".", "launch_url", "==", "None", ":", "self", ".", "launch_url", "=", "config", ".", "launch_url", "self", ".", "custom_params", ".", "update", "(", "config", ".", "custom_params", ...
33.428571
0.0125
def make_chunk_iter( stream, separator, limit=None, buffer_size=10 * 1024, cap_at_buffer=False ): """Works like :func:`make_line_iter` but accepts a separator which divides chunks. If you want newline based processing you should use :func:`make_line_iter` instead as it supports arbitrary newline ma...
[ "def", "make_chunk_iter", "(", "stream", ",", "separator", ",", "limit", "=", "None", ",", "buffer_size", "=", "10", "*", "1024", ",", "cap_at_buffer", "=", "False", ")", ":", "_iter", "=", "_make_chunk_iter", "(", "stream", ",", "limit", ",", "buffer_size...
33.873239
0.000404
def typical_or_extreme_period_type(self, value=None): """Corresponds to IDD Field `typical_or_extreme_period_type` Args: value (str): value for IDD Field `typical_or_extreme_period_type` if `value` is None it will not be checked against the specification and ...
[ "def", "typical_or_extreme_period_type", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "str", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need...
38.666667
0.002103
def getDependencies(self, available_components = None, search_dirs = None, target = None, available_only = False, test = False, warnings = True ): ''' Returns {component_name:component} ''' ...
[ "def", "getDependencies", "(", "self", ",", "available_components", "=", "None", ",", "search_dirs", "=", "None", ",", "target", "=", "None", ",", "available_only", "=", "False", ",", "test", "=", "False", ",", "warnings", "=", "True", ")", ":", "if", "s...
37
0.035748
def _recv_predicate(self, predicate, timeout='default', raise_eof=True): """ Receive until predicate returns a positive integer. The returned number is the size to return. """ if timeout == 'default': timeout = self._timeout self.timed_out = False s...
[ "def", "_recv_predicate", "(", "self", ",", "predicate", ",", "timeout", "=", "'default'", ",", "raise_eof", "=", "True", ")", ":", "if", "timeout", "==", "'default'", ":", "timeout", "=", "self", ".", "_timeout", "self", ".", "timed_out", "=", "False", ...
30.82
0.001258
def _build_connection_pool(cls, session: AppSession): '''Create connection pool.''' args = session.args connect_timeout = args.connect_timeout read_timeout = args.read_timeout if args.timeout: connect_timeout = read_timeout = args.timeout if args.limit_rate:...
[ "def", "_build_connection_pool", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "args", "=", "session", ".", "args", "connect_timeout", "=", "args", ".", "connect_timeout", "read_timeout", "=", "args", ".", "read_timeout", "if", "args", ".", "timeout...
36.278481
0.000679
def request(self, url: str, method: str = 'GET', *, callback=None, encoding: typing.Optional[str] = None, headers: dict = None, metadata: dict = None, request_config: dict = None, ...
[ "def", "request", "(", "self", ",", "url", ":", "str", ",", "method", ":", "str", "=", "'GET'", ",", "*", ",", "callback", "=", "None", ",", "encoding", ":", "typing", ".", "Optional", "[", "str", "]", "=", "None", ",", "headers", ":", "dict", "=...
33
0.011396
def get_last_available_price(self) -> PriceModel: """ Finds the last available price for security. Uses PriceDb. """ price_db = PriceDbApplication() symbol = SecuritySymbol(self.security.namespace, self.security.mnemonic) result = price_db.get_latest_price(symbol) return result
[ "def", "get_last_available_price", "(", "self", ")", "->", "PriceModel", ":", "price_db", "=", "PriceDbApplication", "(", ")", "symbol", "=", "SecuritySymbol", "(", "self", ".", "security", ".", "namespace", ",", "self", ".", "security", ".", "mnemonic", ")", ...
52.166667
0.009434
def full_datatype_to_mysql(d: str) -> str: """Converts a full datatype, e.g. INT, VARCHAR(10), VARCHAR(MAX), to a MySQL equivalent.""" d = d.upper() (s, length) = split_long_sqltype(d) if d in ["VARCHAR(MAX)", "NVARCHAR(MAX)"]: # http://wiki.ispirer.com/sqlways/mysql/data-types/longtext ...
[ "def", "full_datatype_to_mysql", "(", "d", ":", "str", ")", "->", "str", ":", "d", "=", "d", ".", "upper", "(", ")", "(", "s", ",", "length", ")", "=", "split_long_sqltype", "(", "d", ")", "if", "d", "in", "[", "\"VARCHAR(MAX)\"", ",", "\"NVARCHAR(MA...
38.692308
0.001942
def is_arabicstring(text): """ Checks for an Arabic standard Unicode block characters An arabic string can contain spaces, digits and pounctuation. but only arabic standard characters, not extended arabic @param text: input text @type text: unicode @return: True if all charaters are in Arabic...
[ "def", "is_arabicstring", "(", "text", ")", ":", "if", "re", ".", "search", "(", "u\"([^\\u0600-\\u0652%s%s%s\\s\\d])\"", "%", "(", "LAM_ALEF", ",", "LAM_ALEF_HAMZA_ABOVE", ",", "LAM_ALEF_MADDA_ABOVE", ")", ",", "text", ")", ":", "return", "False", "return", "Tr...
40
0.011278
def _cleanup(self, lr_decay_opt_states_reset: str, process_manager: Optional['DecoderProcessManager'] = None, keep_training_state = False): """ Cleans parameter files, training state directory and waits for remaining decoding processes. """ utils.cleanup_params_files(sel...
[ "def", "_cleanup", "(", "self", ",", "lr_decay_opt_states_reset", ":", "str", ",", "process_manager", ":", "Optional", "[", "'DecoderProcessManager'", "]", "=", "None", ",", "keep_training_state", "=", "False", ")", ":", "utils", ".", "cleanup_params_files", "(", ...
65.5
0.008598
def _parse_the_ned_object_results( self): """ *parse the ned results* **Key Arguments:** # - **Return:** - None .. todo:: - @review: when complete, clean _parse_the_ned_results method - @review: when complete add log...
[ "def", "_parse_the_ned_object_results", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``_parse_the_ned_results`` method'", ")", "results", "=", "[", "]", "headers", "=", "[", "\"objectName\"", ",", "\"objectType\"", ",", "\"raDeg\"", ...
38.081395
0.000595
def filter_user(user, using='records', interaction=None, part_of_week='allweek', part_of_day='allday'): """ Filter records of a User objects by interaction, part of week and day. Parameters ---------- user : User a bandicoot User object type : str, default 'records' ...
[ "def", "filter_user", "(", "user", ",", "using", "=", "'records'", ",", "interaction", "=", "None", ",", "part_of_week", "=", "'allweek'", ",", "part_of_day", "=", "'allday'", ")", ":", "if", "using", "==", "'recharges'", ":", "records", "=", "user", ".", ...
37.857143
0.002043
def call_env_check_consistency(cls, kb_app, builder: StandaloneHTMLBuilder, sphinx_env: BuildEnvironment): """ On env-check-consistency, do callbacks""" for callback in EventAction.get_callbacks(kb_app, SphinxEvent.ECC...
[ "def", "call_env_check_consistency", "(", "cls", ",", "kb_app", ",", "builder", ":", "StandaloneHTMLBuilder", ",", "sphinx_env", ":", "BuildEnvironment", ")", ":", "for", "callback", "in", "EventAction", ".", "get_callbacks", "(", "kb_app", ",", "SphinxEvent", "."...
52.285714
0.008065
def get_live_data_dir(): """ pygeth needs a base directory to store it's chain data. By default this is the directory that `geth` uses as it's `datadir`. """ if sys.platform == 'darwin': data_dir = os.path.expanduser(os.path.join( "~", "Library", "Ethereu...
[ "def", "get_live_data_dir", "(", ")", ":", "if", "sys", ".", "platform", "==", "'darwin'", ":", "data_dir", "=", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "\"~\"", ",", "\"Library\"", ",", "\"Ethereum\"", ",", ")",...
29.032258
0.001075
def make_thread_suspend_str( self, thread_id, frame, stop_reason=None, message=None, suspend_type="trace", frame_id_to_lineno=None ): """ :return tuple(str,str): Returns tuple(thread_suspended_str, thread_stack_str). ...
[ "def", "make_thread_suspend_str", "(", "self", ",", "thread_id", ",", "frame", ",", "stop_reason", "=", "None", ",", "message", "=", "None", ",", "suspend_type", "=", "\"trace\"", ",", "frame_id_to_lineno", "=", "None", ")", ":", "make_valid_xml_value", "=", "...
30.901961
0.00246
def GetTemplates(alias=None,location=None): """Gets the list of Templates available to the account and location. https://t3n.zendesk.com/entries/23102683-List-Available-Server-Templates :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter whe...
[ "def", "GetTemplates", "(", "alias", "=", "None", ",", "location", "=", "None", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "if", "location", "is", "None", ":", "location", ...
45.615385
0.033058
def set_result(self, result): ''' Set the result to Future object, wake up all the waiters :param result: result to set ''' if hasattr(self, '_result'): raise ValueError('Cannot set the result twice') self._result = result self._scheduler.emer...
[ "def", "set_result", "(", "self", ",", "result", ")", ":", "if", "hasattr", "(", "self", ",", "'_result'", ")", ":", "raise", "ValueError", "(", "'Cannot set the result twice'", ")", "self", ".", "_result", "=", "result", "self", ".", "_scheduler", ".", "e...
35.3
0.013812
def propagate(cls, date): """Compute the position of the sun at a given date Args: date (~beyond.utils.date.Date) Return: ~beyond.orbits.orbit.Orbit: Position of the sun in MOD frame Example: .. code-block:: python from beyond.util...
[ "def", "propagate", "(", "cls", ",", "date", ")", ":", "date", "=", "date", ".", "change_scale", "(", "'UT1'", ")", "t_ut1", "=", "date", ".", "julian_century", "lambda_M", "=", "280.460", "+", "36000.771", "*", "t_ut1", "M", "=", "np", ".", "radians",...
30.142857
0.001967