text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def configure_namespacebrowser(self): """Configure associated namespace browser widget""" # Update namespace view self.sig_namespace_view.connect(lambda data: self.namespacebrowser.process_remote_view(data)) # Update properties of variables self.sig_var_properties.co...
[ "def", "configure_namespacebrowser", "(", "self", ")", ":", "# Update namespace view", "self", ".", "sig_namespace_view", ".", "connect", "(", "lambda", "data", ":", "self", ".", "namespacebrowser", ".", "process_remote_view", "(", "data", ")", ")", "# Update proper...
43.333333
0.01005
def generate(self): """Generate the page html file. Just open the destination file for writing and write the result of rendering this page. """ generated_content = '' if 'published' in (self._config['status'][0]).lower(): if os.path.isdir(self.dirs['www_dir'...
[ "def", "generate", "(", "self", ")", ":", "generated_content", "=", "''", "if", "'published'", "in", "(", "self", ".", "_config", "[", "'status'", "]", "[", "0", "]", ")", ".", "lower", "(", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "...
39.861111
0.005442
def _update_heap(self, peer): """Recalculate the peer's rank and update itself in the peer heap.""" rank = self.rank_calculator.get_rank(peer) if rank == peer.rank: return peer.rank = rank self.peer_heap.update_peer(peer)
[ "def", "_update_heap", "(", "self", ",", "peer", ")", ":", "rank", "=", "self", ".", "rank_calculator", ".", "get_rank", "(", "peer", ")", "if", "rank", "==", "peer", ".", "rank", ":", "return", "peer", ".", "rank", "=", "rank", "self", ".", "peer_he...
33.375
0.007299
def items(self): """Returns a generator of available ICachableItem in the ICachableSource """ for dictreader in self._csv_dictreader_list: for entry in dictreader: item = self.factory() item.key = self.key() item.attributes = entry ...
[ "def", "items", "(", "self", ")", ":", "for", "dictreader", "in", "self", ".", "_csv_dictreader_list", ":", "for", "entry", "in", "dictreader", ":", "item", "=", "self", ".", "factory", "(", ")", "item", ".", "key", "=", "self", ".", "key", "(", ")",...
43.933333
0.007429
def vel_disp(self, gamma, theta_E, r_eff, r_ani, R_slit, dR_slit, FWHM, rendering_number=1000): """ computes the averaged LOS velocity dispersion in the slit (convolved) :param gamma: power-law slope of the mass profile (isothermal = 2) :param theta_E: Einstein radius of the lens (in ar...
[ "def", "vel_disp", "(", "self", ",", "gamma", ",", "theta_E", ",", "r_eff", ",", "r_ani", ",", "R_slit", ",", "dR_slit", ",", "FWHM", ",", "rendering_number", "=", "1000", ")", ":", "sigma_s2_sum", "=", "0", "rho0_r0_gamma", "=", "self", ".", "_rho0_r0_g...
56.434783
0.005303
def get_exptime(self, img): """Obtain EXPTIME""" header = self.get_header(img) if 'EXPTIME' in header.keys(): etime = header['EXPTIME'] elif 'EXPOSED' in header.keys(): etime = header['EXPOSED'] else: etime = 1.0 return etime
[ "def", "get_exptime", "(", "self", ",", "img", ")", ":", "header", "=", "self", ".", "get_header", "(", "img", ")", "if", "'EXPTIME'", "in", "header", ".", "keys", "(", ")", ":", "etime", "=", "header", "[", "'EXPTIME'", "]", "elif", "'EXPOSED'", "in...
27.272727
0.006452
def detect_proc(): """Detect /proc filesystem style. This checks the /proc/{pid} directory for possible formats. Returns one of the followings as str: * `stat`: Linux-style, i.e. ``/proc/{pid}/stat``. * `status`: BSD-style, i.e. ``/proc/{pid}/status``. """ pid = os.getpid() for name in...
[ "def", "detect_proc", "(", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "for", "name", "in", "(", "'stat'", ",", "'status'", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "'/proc'", ",", "st...
33.571429
0.00207
def Parse(self, raw_data): """Take the data and yield results that passed through the filters. The output of each filter is added to a result set. So long as the filter selects, but does not modify, raw data, the result count will remain accurate. Args: raw_data: An iterable series of rdf va...
[ "def", "Parse", "(", "self", ",", "raw_data", ")", ":", "self", ".", "results", "=", "set", "(", ")", "if", "not", "self", ".", "filters", ":", "self", ".", "results", ".", "update", "(", "raw_data", ")", "else", ":", "for", "f", "in", "self", "....
29.55
0.004918
def remove_from_labels(self, label): """ :calls: `DELETE /repos/:owner/:repo/issues/:number/labels/:name <http://developer.github.com/v3/issues/labels>`_ :param label: :class:`github.Label.Label` or string :rtype: None """ assert isinstance(label, (github.Label.Label, str...
[ "def", "remove_from_labels", "(", "self", ",", "label", ")", ":", "assert", "isinstance", "(", "label", ",", "(", "github", ".", "Label", ".", "Label", ",", "str", ",", "unicode", ")", ")", ",", "label", "if", "isinstance", "(", "label", ",", "github",...
40.333333
0.004847
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: IpAccessControlListContext for this IpAccessControlListInstance :rtype: twilio.rest.api.v2010.acc...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "IpAccessControlListContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]"...
42.8
0.009146
def distinct_by_t(func): """ Transformation for Sequence.distinct_by :param func: distinct_by function :return: transformation """ def distinct_by(sequence): distinct_lookup = {} for element in sequence: key = func(element) if key not in distinct_lookup: ...
[ "def", "distinct_by_t", "(", "func", ")", ":", "def", "distinct_by", "(", "sequence", ")", ":", "distinct_lookup", "=", "{", "}", "for", "element", "in", "sequence", ":", "key", "=", "func", "(", "element", ")", "if", "key", "not", "in", "distinct_lookup...
34
0.00409
def _import_PREFIXCC(keyword=""): """ List models from web catalog (prefix.cc) and ask which one to import 2015-10-10: originally part of main ontospy; now standalone only 2016-06-19: eliminated dependency on extras.import_web """ SOURCE = "http://prefix.cc/popular/all.file.vann" opti...
[ "def", "_import_PREFIXCC", "(", "keyword", "=", "\"\"", ")", ":", "SOURCE", "=", "\"http://prefix.cc/popular/all.file.vann\"", "options", "=", "[", "]", "printDebug", "(", "\"----------\\nReading source...\"", ")", "g", "=", "Ontospy", "(", "SOURCE", ",", "verbose",...
36.020408
0.001103
def record_timestamp(pathname_full): """Record the timestamp of running in a dotfile.""" if Settings.test or Settings.list_only or not Settings.record_timestamp: return if not Settings.follow_symlinks and os.path.islink(pathname_full): if Settings.verbose: print('Not setting time...
[ "def", "record_timestamp", "(", "pathname_full", ")", ":", "if", "Settings", ".", "test", "or", "Settings", ".", "list_only", "or", "not", "Settings", ".", "record_timestamp", ":", "return", "if", "not", "Settings", ".", "follow_symlinks", "and", "os", ".", ...
43.310345
0.000779
def set_standard(self): """Set the charger to standard range for daily commute.""" if self.__maxrange_state: data = self._controller.command(self._id, 'charge_standard', wake_if_asleep=True) if data and data['response']['result']: ...
[ "def", "set_standard", "(", "self", ")", ":", "if", "self", ".", "__maxrange_state", ":", "data", "=", "self", ".", "_controller", ".", "command", "(", "self", ".", "_id", ",", "'charge_standard'", ",", "wake_if_asleep", "=", "True", ")", "if", "data", "...
50.625
0.004854
def _add_interval_elevations(self, gpx, min_interval_length=100): """ Adds elevation on points every min_interval_length and add missing elevation between """ for track in gpx.tracks: for segment in track.segments: last_interval_changed = 0 ...
[ "def", "_add_interval_elevations", "(", "self", ",", "gpx", ",", "min_interval_length", "=", "100", ")", ":", "for", "track", "in", "gpx", ".", "tracks", ":", "for", "segment", "in", "track", ".", "segments", ":", "last_interval_changed", "=", "0", "previous...
44.571429
0.004184
def filter_stack(graph, head, filters): """ Perform a walk in a depth-first order starting at *head*. Returns (visited, removes, orphans). * visited: the set of visited nodes * removes: the list of nodes where the node data does not all *filters* * orphans: tuples of (last_good, node...
[ "def", "filter_stack", "(", "graph", ",", "head", ",", "filters", ")", ":", "visited", ",", "removes", ",", "orphans", "=", "set", "(", "[", "head", "]", ")", ",", "set", "(", ")", ",", "set", "(", ")", "stack", "=", "deque", "(", "[", "(", "he...
30.466667
0.003534
def acquire(self, blocking=True, timeout=None): """Acquire the lock. If *blocking* is true (the default), then this will block until the lock can be acquired. The *timeout* parameter specifies an optional timeout in seconds. The return value is a boolean indicating whether the ...
[ "def", "acquire", "(", "self", ",", "blocking", "=", "True", ",", "timeout", "=", "None", ")", ":", "hub", "=", "get_hub", "(", ")", "try", ":", "# switcher.__call__ needs to be synchronized with a lock IF it can", "# be called from different threads. This is the case her...
48.326923
0.00078
def includeRect(self, r): """Extend rectangle to include rectangle r.""" if not len(r) == 4: raise ValueError("bad sequ. length") self.x0, self.y0, self.x1, self.y1 = TOOLS._union_rect(self, r) return self
[ "def", "includeRect", "(", "self", ",", "r", ")", ":", "if", "not", "len", "(", "r", ")", "==", "4", ":", "raise", "ValueError", "(", "\"bad sequ. length\"", ")", "self", ".", "x0", ",", "self", ".", "y0", ",", "self", ".", "x1", ",", "self", "."...
40.666667
0.008032
def on(self, source: mx.sym.Symbol, source_length: mx.sym.Symbol, source_seq_len: int) -> Callable: """ Returns callable to be used for updating coverage vectors in a sequence decoder. :param source: Shape: (batch_size, seq_len, encoder_num_hidden). :param source_length: Shape: (batch_s...
[ "def", "on", "(", "self", ",", "source", ":", "mx", ".", "sym", ".", "Symbol", ",", "source_length", ":", "mx", ".", "sym", ".", "Symbol", ",", "source_seq_len", ":", "int", ")", "->", "Callable", ":", "def", "update_coverage", "(", "prev_hidden", ":",...
50.545455
0.007061
def pipeline_url(self): """ Returns url for accessing pipeline entity. """ return PipelineEntity.get_url(server_url=self._session.server_url, pipeline_name=self.data.name)
[ "def", "pipeline_url", "(", "self", ")", ":", "return", "PipelineEntity", ".", "get_url", "(", "server_url", "=", "self", ".", "_session", ".", "server_url", ",", "pipeline_name", "=", "self", ".", "data", ".", "name", ")" ]
39.8
0.014778
def makeReadPacket(ID, reg, values=None): """ Creates a packet that reads the register(s) of servo ID at location reg. Make sure the values are in little endian (use Packet.le() if necessary) for 16 b (word size) values. """ pkt = makePacket(ID, xl320.XL320_READ, reg, values) return pkt
[ "def", "makeReadPacket", "(", "ID", ",", "reg", ",", "values", "=", "None", ")", ":", "pkt", "=", "makePacket", "(", "ID", ",", "xl320", ".", "XL320_READ", ",", "reg", ",", "values", ")", "return", "pkt" ]
35.875
0.027211
def url(self): """:class:`Asset`:Returns an asset of the emoji, if it is custom.""" if self.is_unicode_emoji(): return Asset(self._state) _format = 'gif' if self.animated else 'png' url = "https://cdn.discordapp.com/emojis/{0.id}.{1}".format(self, _format) return Ass...
[ "def", "url", "(", "self", ")", ":", "if", "self", ".", "is_unicode_emoji", "(", ")", ":", "return", "Asset", "(", "self", ".", "_state", ")", "_format", "=", "'gif'", "if", "self", ".", "animated", "else", "'png'", "url", "=", "\"https://cdn.discordapp....
41.625
0.008824
async def export_wallet(self, von_wallet: Wallet, path: str) -> None: """ Export an existing VON anchor wallet. Raise WalletState if wallet is closed. :param von_wallet: open wallet :param path: path to which to export wallet """ LOGGER.debug('WalletManager.export_walle...
[ "async", "def", "export_wallet", "(", "self", ",", "von_wallet", ":", "Wallet", ",", "path", ":", "str", ")", "->", "None", ":", "LOGGER", ".", "debug", "(", "'WalletManager.export_wallet >>> von_wallet %s, path %s'", ",", "von_wallet", ",", "path", ")", "if", ...
36.090909
0.006135
def inspect(logdir='', event_file='', tag=''): """Main function for inspector that prints out a digest of event files. Args: logdir: A log directory that contains event files. event_file: Or, a particular event file path. tag: An optional tag name to query for. Raises: ValueError: If neither log...
[ "def", "inspect", "(", "logdir", "=", "''", ",", "event_file", "=", "''", ",", "tag", "=", "''", ")", ":", "print", "(", "PRINT_SEPARATOR", "+", "'Processing event files... (this can take a few minutes)\\n'", "+", "PRINT_SEPARATOR", ")", "inspection_units", "=", "...
37.551724
0.010743
def constraint_from_parent_conflicts(self): """ Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints ...
[ "def", "constraint_from_parent_conflicts", "(", "self", ")", ":", "# ensure that we satisfy the parent dependencies of this dep", "from", "pipenv", ".", "vendor", ".", "packaging", ".", "specifiers", "import", "Specifier", "parent_dependencies", "=", "set", "(", ")", "has...
48.348837
0.004715
def push(self, patch=None, toa=None, meta=None): """Push a change on to the revision stack for this ObjectId. Pushing onto the stack is how you get revisions to be staged and scheduled for some future time. :param dict patch: None Denotes Delete :param int toa: Time of action :...
[ "def", "push", "(", "self", ",", "patch", "=", "None", ",", "toa", "=", "None", ",", "meta", "=", "None", ")", ":", "if", "not", "meta", ":", "meta", "=", "{", "}", "if", "not", "toa", ":", "toa", "=", "time", ".", "mktime", "(", "datetime", ...
33
0.00399
def _generateExperiment(options, outputDirPath, hsVersion, claDescriptionTemplateFile): """ Executes the --description option, which includes: 1. Perform provider compatibility checks 2. Preprocess the training and testing datasets (filter, join providers) 3. If test da...
[ "def", "_generateExperiment", "(", "options", ",", "outputDirPath", ",", "hsVersion", ",", "claDescriptionTemplateFile", ")", ":", "_gExperimentDescriptionSchema", "=", "_getExperimentDescriptionSchema", "(", ")", "# Validate JSON arg using JSON schema validator", "try", ":", ...
39.250865
0.015303
def trim(self, neighborhood, method="ztest", factor=3, replace="nan", verbose=True): """Remove outliers from the dataset. Identifies outliers by comparing each point to its neighbors using a statistical test. Parameters ---------- neighborhood : list of integers ...
[ "def", "trim", "(", "self", ",", "neighborhood", ",", "method", "=", "\"ztest\"", ",", "factor", "=", "3", ",", "replace", "=", "\"nan\"", ",", "verbose", "=", "True", ")", ":", "warnings", ".", "warn", "(", "\"trim\"", ",", "category", "=", "wt_except...
34.752809
0.003772
def p_Case(p): ''' Case : CASE ArgList COLON Terminator Block | DEFAULT COLON Terminator Block ''' if p[1] == 'case': p[0] = Case(p[1], p[2], p[4], p[5]) else: p[0] = Case(p[1], None, p[3], p[4])
[ "def", "p_Case", "(", "p", ")", ":", "if", "p", "[", "1", "]", "==", "'case'", ":", "p", "[", "0", "]", "=", "Case", "(", "p", "[", "1", "]", ",", "p", "[", "2", "]", ",", "p", "[", "4", "]", ",", "p", "[", "5", "]", ")", "else", ":...
25.777778
0.004167
def set_config_file(self, path): """ Set the config file. The contents must be valid YAML and there must be a top-level element 'tasks'. The listed tasks will be started according to their configuration, and the file will be watched for future changes. The changes will be acti...
[ "def", "set_config_file", "(", "self", ",", "path", ")", ":", "log", "=", "self", ".", "_params", ".", "get", "(", "'log'", ",", "self", ".", "_discard", ")", "if", "path", "!=", "self", ".", "_config_file", ":", "if", "self", ".", "_config_file", ":...
48.555556
0.003367
def _get_cct(x, y, z): """ Reference Hernandez-Andres, J., Lee, R. L., & Romero, J. (1999). Calculating correlated color temperatures across the entire gamut of daylight and skylight chromaticities. Applied Optics, 38(27), 5703-5709. """ x_e = 0.3320 y_e =...
[ "def", "_get_cct", "(", "x", ",", "y", ",", "z", ")", ":", "x_e", "=", "0.3320", "y_e", "=", "0.1858", "n", "=", "(", "(", "x", "/", "(", "x", "+", "z", "+", "z", ")", ")", "-", "x_e", ")", "/", "(", "(", "y", "/", "(", "x", "+", "z",...
28.565217
0.005891
def _commandline(self, *args, **kwargs): """Returns the command line (without pipes) as a list.""" # transform_args() is a hook (used in GromacsCommand very differently!) return [self.command_name] + self.transform_args(*args, **kwargs)
[ "def", "_commandline", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# transform_args() is a hook (used in GromacsCommand very differently!)", "return", "[", "self", ".", "command_name", "]", "+", "self", ".", "transform_args", "(", "*", "args...
64.5
0.019157
def writeString(self, str): """Write the content of the string in the output I/O buffer This routine handle the I18N transcoding from internal UTF-8 The buffer is lossless, i.e. will store in case of partial or delayed writes. """ ret = libxml2mod.xmlOutputBufferWriteStrin...
[ "def", "writeString", "(", "self", ",", "str", ")", ":", "ret", "=", "libxml2mod", ".", "xmlOutputBufferWriteString", "(", "self", ".", "_o", ",", "str", ")", "return", "ret" ]
49.714286
0.00565
def _roll_random(n): """returns a random # from 0 to N-1""" bits = util.bit_length(n - 1) byte_count = (bits + 7) // 8 hbyte_mask = pow(2, bits % 8) - 1 # so here's the plan: # we fetch as many random bits as we'd need to fit N-1, and if the # generated number is >= N, we try again. in the...
[ "def", "_roll_random", "(", "n", ")", ":", "bits", "=", "util", ".", "bit_length", "(", "n", "-", "1", ")", "byte_count", "=", "(", "bits", "+", "7", ")", "//", "8", "hbyte_mask", "=", "pow", "(", "2", ",", "bits", "%", "8", ")", "-", "1", "#...
37.6
0.001297
def parse_args_to_action_args(self, argv=None): ''' Parses args and returns an action and the args that were parsed ''' args = self.parse_args(argv) action = self.subcommands[args.subcommand][1] return action, args
[ "def", "parse_args_to_action_args", "(", "self", ",", "argv", "=", "None", ")", ":", "args", "=", "self", ".", "parse_args", "(", "argv", ")", "action", "=", "self", ".", "subcommands", "[", "args", ".", "subcommand", "]", "[", "1", "]", "return", "act...
36.571429
0.007634
def stop(self): 'cleans up and stops the discovery server' self.clearRemoteServices() self.clearLocalServices() self._stopThreads() self._serverStarted = False
[ "def", "stop", "(", "self", ")", ":", "self", ".", "clearRemoteServices", "(", ")", "self", ".", "clearLocalServices", "(", ")", "self", ".", "_stopThreads", "(", ")", "self", ".", "_serverStarted", "=", "False" ]
24.25
0.00995
def time(name=None): """ Creates the grammar for a Time or Duration (T) field, accepting only numbers in a certain pattern. :param name: name for the field :return: grammar for the date field """ if name is None: name = 'Time Field' # Basic field # This regex allows values...
[ "def", "time", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'Time Field'", "# Basic field", "# This regex allows values from 000000 to 235959", "field", "=", "pp", ".", "Regex", "(", "'(0[0-9]|1[0-9]|2[0-3])[0-5][0-9][0-5][0-9]'",...
23.444444
0.001517
def recordbatch(self, auth, resource, entries, defer=False): """ Records a list of historical entries to the resource specified. Calls a function that bulids a request that writes a list of historical entries to the specified resource. Args: auth: Takes the device cik ...
[ "def", "recordbatch", "(", "self", ",", "auth", ",", "resource", ",", "entries", ",", "defer", "=", "False", ")", ":", "return", "self", ".", "_call", "(", "'recordbatch'", ",", "auth", ",", "[", "resource", ",", "entries", "]", ",", "defer", ")" ]
42.5
0.005758
def apply_once(func, arr, axes, keepdims=True): """ Similar to `numpy.apply_over_axes`, except this performs the operation over a flattened version of all the axes, meaning that the function will only be called once. This only makes a difference for non-linear functions. Parameters ---------- ...
[ "def", "apply_once", "(", "func", ",", "arr", ",", "axes", ",", "keepdims", "=", "True", ")", ":", "all_axes", "=", "np", ".", "arange", "(", "arr", ".", "ndim", ")", "if", "isinstance", "(", "axes", ",", "int", ")", ":", "axes", "=", "{", "axes"...
35.573034
0.000307
def bulk(self, actions, stats_only=False, **kwargs): """ Executes bulk api by elasticsearch.helpers.bulk. :param actions: iterator containing the actions :param stats_only:if `True` only report number of successful/failed operations instead of just number of successful and a lis...
[ "def", "bulk", "(", "self", ",", "actions", ",", "stats_only", "=", "False", ",", "*", "*", "kwargs", ")", ":", "success", ",", "failed", "=", "es_helpers", ".", "bulk", "(", "self", ".", "client", ",", "actions", ",", "stats_only", ",", "*", "*", ...
55.357143
0.007614
def options(cls): """Return a dictionary of the ``Option`` objects for this config.""" return {k: v for k, v in cls.__dict__.items() if isinstance(v, Option)}
[ "def", "options", "(", "cls", ")", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "cls", ".", "__dict__", ".", "items", "(", ")", "if", "isinstance", "(", "v", ",", "Option", ")", "}" ]
57.333333
0.011494
def _create_rule(rule, index, backtrack): # type: (Rule, int, Dict[Type[Nonterminal], Type[Rule]]) -> Type[EpsilonRemovedRule] """ Create EpsilonRemovedRule. This rule will skip symbol at the `index`. :param rule: Original rule. :param index: Index of symbol that is rewritable to epsilon. :param...
[ "def", "_create_rule", "(", "rule", ",", "index", ",", "backtrack", ")", ":", "# type: (Rule, int, Dict[Type[Nonterminal], Type[Rule]]) -> Type[EpsilonRemovedRule]", "# remove old rules from the dictionary", "old_dict", "=", "rule", ".", "__dict__", ".", "copy", "(", ")", "...
44.5
0.006873
def create_relocate_package(cls, package_name, shade_prefix=None, recursive=True): """Convenience constructor for a package relocation rule. Essentially equivalent to just using ``shading_relocate('package_name.**')``. :param string package_name: Package name to shade (eg, ``org.pantsbuild.example``). ...
[ "def", "create_relocate_package", "(", "cls", ",", "package_name", ",", "shade_prefix", "=", "None", ",", "recursive", "=", "True", ")", ":", "return", "cls", ".", "create_relocate", "(", "from_pattern", "=", "cls", ".", "_format_package_glob", "(", "package_nam...
57.384615
0.009235
def psisloo(log_lik, **kwargs): r"""PSIS leave-one-out log predictive densities. Computes the log predictive densities given posterior samples of the log likelihood terms :math:`p(y_i|\theta^s)` in input parameter `log_lik`. Returns a sum of the leave-one-out log predictive densities `loo`, individ...
[ "def", "psisloo", "(", "log_lik", ",", "*", "*", "kwargs", ")", ":", "# ensure overwrite flag in passed arguments", "kwargs", "[", "'overwrite_lw'", "]", "=", "True", "# log raw weights from log_lik", "lw", "=", "-", "log_lik", "# compute Pareto smoothed log weights given...
32.952381
0.002105
def eff_default_transformer(fills=EFF_DEFAULT_FILLS): """ Return a simple transformer function for parsing EFF annotations. N.B., ignores all but the first effect. """ def _transformer(vals): if len(vals) == 0: return fills else: # ignore all but first effect...
[ "def", "eff_default_transformer", "(", "fills", "=", "EFF_DEFAULT_FILLS", ")", ":", "def", "_transformer", "(", "vals", ")", ":", "if", "len", "(", "vals", ")", "==", "0", ":", "return", "fills", "else", ":", "# ignore all but first effect", "match_eff_main", ...
34.892857
0.000996
def generate_ill_conditioned_dot_product(n, c, dps=100): """n ... length of vector c ... target condition number """ # Algorithm 6.1 from # # ACCURATE SUM AND DOT PRODUCT, # TAKESHI OGITA, SIEGFRIED M. RUMP, AND SHIN'ICHI OISHI. assert n >= 6 n2 = round(n / 2) x = numpy.zeros(n) ...
[ "def", "generate_ill_conditioned_dot_product", "(", "n", ",", "c", ",", "dps", "=", "100", ")", ":", "# Algorithm 6.1 from", "#", "# ACCURATE SUM AND DOT PRODUCT,", "# TAKESHI OGITA, SIEGFRIED M. RUMP, AND SHIN'ICHI OISHI.", "assert", "n", ">=", "6", "n2", "=", "round", ...
31.403846
0.001188
def handle(self, request, uri): """Request handler interface. :param request: Python requests Request object :param uri: URI of the request """ # Convert the call over to Stack-In-A-Box method = request.method headers = CaseInsensitiveDict() request_head...
[ "def", "handle", "(", "self", ",", "request", ",", "uri", ")", ":", "# Convert the call over to Stack-In-A-Box", "method", "=", "request", ".", "method", "headers", "=", "CaseInsensitiveDict", "(", ")", "request_headers", "=", "CaseInsensitiveDict", "(", ")", "req...
31.732143
0.001092
def image_resources(package=None, directory='resources'): """ Returns all images under the directory relative to a package path. If no directory or package is specified then the resources module of the calling package will be used. Images are recursively discovered. :param package: package name in dott...
[ "def", "image_resources", "(", "package", "=", "None", ",", "directory", "=", "'resources'", ")", ":", "if", "not", "package", ":", "package", "=", "calling_package", "(", ")", "package_dir", "=", "'.'", ".", "join", "(", "[", "package", ",", "directory", ...
42.863636
0.003112
def install_monitor(self, monitor_pattern: str, monitor_stat_func_name: str): """ Installs an MXNet monitor onto the underlying module. :param monitor_pattern: Pattern string. :param monitor_stat_func_name: Name of monitor statistics function. """ self._monitor = mx.moni...
[ "def", "install_monitor", "(", "self", ",", "monitor_pattern", ":", "str", ",", "monitor_stat_func_name", ":", "str", ")", ":", "self", ".", "_monitor", "=", "mx", ".", "monitor", ".", "Monitor", "(", "interval", "=", "C", ".", "MEASURE_SPEED_EVERY", ",", ...
55
0.005109
def convert_entry_to_path(path): # type: (Dict[S, Union[S, bool, Tuple[S], List[S]]]) -> S """Convert a pipfile entry to a string""" if not isinstance(path, Mapping): raise TypeError("expecting a mapping, received {0!r}".format(path)) if not any(key in path for key in ["file", "path"]): ...
[ "def", "convert_entry_to_path", "(", "path", ")", ":", "# type: (Dict[S, Union[S, bool, Tuple[S], List[S]]]) -> S", "if", "not", "isinstance", "(", "path", ",", "Mapping", ")", ":", "raise", "TypeError", "(", "\"expecting a mapping, received {0!r}\"", ".", "format", "(", ...
33.5
0.00363
def parse(self): """Parse this Berksfile into a dict.""" self.flush() self.seek(0) data = utils.ruby_lines(self.readlines()) data = [tuple(j.strip() for j in line.split(None, 1)) for line in data] datamap = {} for line in data: if len(l...
[ "def", "parse", "(", "self", ")", ":", "self", ".", "flush", "(", ")", "self", ".", "seek", "(", "0", ")", "data", "=", "utils", ".", "ruby_lines", "(", "self", ".", "readlines", "(", ")", ")", "data", "=", "[", "tuple", "(", "j", ".", "strip",...
47.568182
0.000936
def get_external_ip(): """Returns the current external IP, based on http://icanhazip.com/. It will probably fail if the network setup is too complicated or the service is down. """ response = requests.get('http://icanhazip.com/') if not response.ok: raise RuntimeError('Failed to get exte...
[ "def", "get_external_ip", "(", ")", ":", "response", "=", "requests", ".", "get", "(", "'http://icanhazip.com/'", ")", "if", "not", "response", ".", "ok", ":", "raise", "RuntimeError", "(", "'Failed to get external ip: %s'", "%", "response", ".", "content", ")",...
42.222222
0.002577
def bind(self, data): """ Bind a VertexBuffer that has structured data Parameters ---------- data : VertexBuffer The vertex buffer to bind. The field names of the array are mapped to attribute names in GLSL. """ # Check if not isin...
[ "def", "bind", "(", "self", ",", "data", ")", ":", "# Check", "if", "not", "isinstance", "(", "data", ",", "VertexBuffer", ")", ":", "raise", "ValueError", "(", "'Program.bind() requires a VertexBuffer.'", ")", "# Apply", "for", "name", "in", "data", ".", "d...
33
0.005894
def get_entrust(self): """ 获取委托单(目前返回20次调仓的结果) 操作数量都按1手模拟换算的 :return: """ xq_entrust_list = self._get_xq_history() entrust_list = [] replace_none = lambda s: s or 0 for xq_entrusts in xq_entrust_list: status = xq_entrusts["status"] # 调...
[ "def", "get_entrust", "(", "self", ")", ":", "xq_entrust_list", "=", "self", ".", "_get_xq_history", "(", ")", "entrust_list", "=", "[", "]", "replace_none", "=", "lambda", "s", ":", "s", "or", "0", "for", "xq_entrusts", "in", "xq_entrust_list", ":", "stat...
37.538462
0.001997
def _make_request(self, action): """ Perform the request :param action: action name :return: a dict containing the request result :rtype: dict """ if isinstance(action, list): kwargs = {'actions': action} action = 'send' else: ...
[ "def", "_make_request", "(", "self", ",", "action", ")", ":", "if", "isinstance", "(", "action", ",", "list", ")", ":", "kwargs", "=", "{", "'actions'", ":", "action", "}", "action", "=", "'send'", "else", ":", "kwargs", "=", "self", ".", "_get_method_...
26.642857
0.002587
def raw_decode(self, s, idx=0, _w=WHITESPACE.match, _PY3=PY3): """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. Optionally, ``idx`` can be used...
[ "def", "raw_decode", "(", "self", ",", "s", ",", "idx", "=", "0", ",", "_w", "=", "WHITESPACE", ".", "match", ",", "_PY3", "=", "PY3", ")", ":", "if", "idx", "<", "0", ":", "# Ensure that raw_decode bails on negative indexes, the regex", "# would otherwise mas...
44.32
0.001767
def parse_line(self, line): """Parses a single line of a GPI. Return a tuple `(processed_line, entities)`. Typically there will be a single entity, but in some cases there may be none (invalid line) or multiple (disjunctive clause in annotation extensions) Note: most ap...
[ "def", "parse_line", "(", "self", ",", "line", ")", ":", "vals", "=", "line", ".", "split", "(", "\"\\t\"", ")", "if", "len", "(", "vals", ")", "<", "7", ":", "self", ".", "report", ".", "error", "(", "line", ",", "assocparser", ".", "Report", "....
29.243902
0.004034
def __get_smtp(self): """ Return the appropraite smtplib depending on wherther we're using TLS """ use_tls = self.config['shutit.core.alerting.emailer.use_tls'] if use_tls: smtp = SMTP(self.config['shutit.core.alerting.emailer.smtp_server'], self.config['shutit.core.alerting.emailer.smtp_port']) smtp.star...
[ "def", "__get_smtp", "(", "self", ")", ":", "use_tls", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.use_tls'", "]", "if", "use_tls", ":", "smtp", "=", "SMTP", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.smtp_server'", "]", ...
47
0.02714
def generic_http_header_parser_for(header_name): """ A parser factory to extract the request id from an HTTP header :return: A parser that can be used to extract the request id from the current request context :rtype: ()->str|None """ def parser(): request_id = request.headers.get(heade...
[ "def", "generic_http_header_parser_for", "(", "header_name", ")", ":", "def", "parser", "(", ")", ":", "request_id", "=", "request", ".", "headers", ".", "get", "(", "header_name", ",", "''", ")", ".", "strip", "(", ")", "if", "not", "request_id", ":", "...
31.6
0.004098
def bind_blueprint(pale_api_module, flask_blueprint): """Binds an implemented pale API module to a Flask Blueprint.""" if not isinstance(flask_blueprint, Blueprint): raise TypeError(("pale.flask_adapter.bind_blueprint expected the " "passed in flask_blueprint to be an instance ...
[ "def", "bind_blueprint", "(", "pale_api_module", ",", "flask_blueprint", ")", ":", "if", "not", "isinstance", "(", "flask_blueprint", ",", "Blueprint", ")", ":", "raise", "TypeError", "(", "(", "\"pale.flask_adapter.bind_blueprint expected the \"", "\"passed in flask_blue...
43.366667
0.001504
def import_sip04(self, filename, timestep=None): """SIP04 data import Parameters ---------- filename: string Path to .mat or .csv file containing SIP-04 measurement results Examples -------- :: import tempfile import reda ...
[ "def", "import_sip04", "(", "self", ",", "filename", ",", "timestep", "=", "None", ")", ":", "df", "=", "reda_sip04", ".", "import_sip04_data", "(", "filename", ")", "if", "timestep", "is", "not", "None", ":", "print", "(", "'adding timestep'", ")", "df", ...
26.241379
0.002535
def get(cls, tab_uuid, tab_attachment_tab_id, custom_headers=None): """ Get a specific attachment. The header of the response contains the content-type of the attachment. :type api_context: context.ApiContext :type tab_uuid: str :type tab_attachment_tab_id: int :...
[ "def", "get", "(", "cls", ",", "tab_uuid", ",", "tab_attachment_tab_id", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_headers", "=", "{", "}", "api_client", "=", "client", ".", "ApiClient", "(", "cls", "....
36.666667
0.002215
def sorted_fields(cls): """Get the names of all writable metadata fields, sorted in the order that they should be written. This is a lexicographic order, except for instances of :class:`DateItemField`, which are sorted in year-month-day order. """ for property in...
[ "def", "sorted_fields", "(", "cls", ")", ":", "for", "property", "in", "sorted", "(", "cls", ".", "fields", "(", ")", ",", "key", "=", "cls", ".", "_field_sort_name", ")", ":", "yield", "property" ]
38.6
0.005063
def simulate(model, dr, N=1, T=40, s0=None, i0=None, m0=None, driving_process=None, seed=42, stochastic=True): ''' Simulate a model using the specified decision rule. Parameters ---------- model: NumericModel dr: decision rule s0: ndarray initial state where all simulatio...
[ "def", "simulate", "(", "model", ",", "dr", ",", "N", "=", "1", ",", "T", "=", "40", ",", "s0", "=", "None", ",", "i0", "=", "None", ",", "m0", "=", "None", ",", "driving_process", "=", "None", ",", "seed", "=", "42", ",", "stochastic", "=", ...
29.222222
0.00683
def load_config_from_json(self): """load config from existing json connector files.""" c = self.config self.log.debug("loading config from JSON") # load from engine config fname = os.path.join(self.profile_dir.security_dir, self.engine_json_file) self.log.info("loading co...
[ "def", "load_config_from_json", "(", "self", ")", ":", "c", "=", "self", ".", "config", "self", ".", "log", ".", "debug", "(", "\"loading config from JSON\"", ")", "# load from engine config", "fname", "=", "os", ".", "path", ".", "join", "(", "self", ".", ...
45.090909
0.005921
def annotate_tree_properties(comments): """ iterate through nodes and adds some magic properties to each of them representing opening list of children and closing it """ if not comments: return it = iter(comments) # get the first item, this will fail if no items ! old = next(it...
[ "def", "annotate_tree_properties", "(", "comments", ")", ":", "if", "not", "comments", ":", "return", "it", "=", "iter", "(", "comments", ")", "# get the first item, this will fail if no items !", "old", "=", "next", "(", "it", ")", "# first item starts a new thread",...
26.06383
0.001574
def _mets_header(self, now): """ Return the metsHdr Element. """ header_tag = etree.QName(utils.NAMESPACES[u"mets"], u"metsHdr") header_attrs = {} if self.createdate is None: header_attrs[u"CREATEDATE"] = now else: header_attrs[u"CREATEDAT...
[ "def", "_mets_header", "(", "self", ",", "now", ")", ":", "header_tag", "=", "etree", ".", "QName", "(", "utils", ".", "NAMESPACES", "[", "u\"mets\"", "]", ",", "u\"metsHdr\"", ")", "header_attrs", "=", "{", "}", "if", "self", ".", "createdate", "is", ...
33.15
0.002933
def create_model( self, parent, model, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a model. Returns a Model in the ``response`` field when it completes. When you ...
[ "def", "create_model", "(", "self", ",", "parent", ",", "model", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT",...
40.340426
0.002059
def _ReadStructureDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a structure data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[...
[ "def", "_ReadStructureDataTypeDefinition", "(", "self", ",", "definitions_registry", ",", "definition_values", ",", "definition_name", ",", "is_member", "=", "False", ")", ":", "if", "is_member", ":", "error_message", "=", "'data type not supported as member'", "raise", ...
38.037037
0.003799
def _get_length_sequences_where(x): """ This method calculates the length of all sub-sequences where the array x is either True or 1. Examples -------- >>> x = [0,1,0,0,1,1,1,0,0,1,0,1,1] >>> _get_length_sequences_where(x) >>> [1, 3, 1, 2] >>> x = [0,True,0,0,True,True,True,0,0,True,0,...
[ "def", "_get_length_sequences_where", "(", "x", ")", ":", "if", "len", "(", "x", ")", "==", "0", ":", "return", "[", "0", "]", "else", ":", "res", "=", "[", "len", "(", "list", "(", "group", ")", ")", "for", "value", ",", "group", "in", "itertool...
33.185185
0.004338
def _pdf(self, **kwargs): """Returns the pdf at the given values. The keyword arguments must contain all of parameters in self's params. Unrecognized arguments are ignored. """ if kwargs in self: vals = numpy.array([numpy.log(10) * self._norm * kwargs[param] ...
[ "def", "_pdf", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", "in", "self", ":", "vals", "=", "numpy", ".", "array", "(", "[", "numpy", ".", "log", "(", "10", ")", "*", "self", ".", "_norm", "*", "kwargs", "[", "param", "]", ...
39.909091
0.004454
def adjoint(self): r"""Return the (left) adjoint. Notes ----- Due to technicalities of operators from a complex space into a real space, this does not satisfy the usual adjoint equation: .. math:: \langle Ax, y \rangle = \langle x, A^*y \rangle Inst...
[ "def", "adjoint", "(", "self", ")", ":", "if", "self", ".", "space_is_real", ":", "return", "ZeroOperator", "(", "self", ".", "domain", ")", "else", ":", "return", "ComplexEmbedding", "(", "self", ".", "domain", ",", "scalar", "=", "1j", ")" ]
29.952381
0.00154
def connect_from_cli(cls, argv, use_cache=True): """ Connect with data taken from a command line interface. Parameters ---------- argv: list Command line parameters (executable name excluded) use_cache : bool True to use HTTP cache, False otherwis...
[ "def", "connect_from_cli", "(", "cls", ",", "argv", ",", "use_cache", "=", "True", ")", ":", "argparse", "=", "cls", ".", "_add_cytomine_cli_args", "(", "ArgumentParser", "(", ")", ")", "params", ",", "_", "=", "argparse", ".", "parse_known_args", "(", "ar...
34.769231
0.004306
def get_client_properties_per_page(self, per_page=1000, page=1, params=None): """ Get client properties per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list ...
[ "def", "get_client_properties_per_page", "(", "self", ",", "per_page", "=", "1000", ",", "page", "=", "1", ",", "params", "=", "None", ")", ":", "return", "self", ".", "_get_resource_per_page", "(", "resource", "=", "CLIENT_PROPERTIES", ",", "per_page", "=", ...
32.466667
0.003992
def on_disconnect(self=None) -> callable: """Use this decorator to automatically register a function for handling disconnections. This does the same thing as :meth:`add_handler` using the :class:`DisconnectHandler`. """ def decorator(func: callable) -> Handler: handler = pyr...
[ "def", "on_disconnect", "(", "self", "=", "None", ")", "->", "callable", ":", "def", "decorator", "(", "func", ":", "callable", ")", "->", "Handler", ":", "handler", "=", "pyrogram", ".", "DisconnectHandler", "(", "func", ")", "if", "self", "is", "not", ...
33.285714
0.008351
def search(self, **kwargs): '''Filter the annotation array down to only those Annotation objects matching the query. Parameters ---------- kwargs : search parameters See JObject.search Returns ------- results : AnnotationArray An...
[ "def", "search", "(", "self", ",", "*", "*", "kwargs", ")", ":", "results", "=", "AnnotationArray", "(", ")", "for", "annotation", "in", "self", ":", "if", "annotation", ".", "search", "(", "*", "*", "kwargs", ")", ":", "results", ".", "append", "(",...
22.074074
0.003215
def list_downloadable_sources(target_dir): """Returns a list of python source files is target_dir Parameters ---------- target_dir : str path to the directory where python source file are Returns ------- list list of paths to all Python source files in `target_dir` """ ...
[ "def", "list_downloadable_sources", "(", "target_dir", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "target_dir", ",", "fname", ")", "for", "fname", "in", "os", ".", "listdir", "(", "target_dir", ")", "if", "fname", ".", "endswith", "(",...
28.933333
0.002232
def mean(self, start=None, end=None, mask=None): """This calculated the average value of the time series over the given time range from `start` to `end`, when `mask` is truthy. """ return self.distribution(start=start, end=end, mask=mask).mean()
[ "def", "mean", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "mask", "=", "None", ")", ":", "return", "self", ".", "distribution", "(", "start", "=", "start", ",", "end", "=", "end", ",", "mask", "=", "mask", ")", ".", "...
45.5
0.007194
def get_absolute_limits(self): """ Returns a dict with the absolute limits for the current account. """ resp, body = self.method_get("/limits") absolute_limits = body.get("limits", {}).get("absolute") return absolute_limits
[ "def", "get_absolute_limits", "(", "self", ")", ":", "resp", ",", "body", "=", "self", ".", "method_get", "(", "\"/limits\"", ")", "absolute_limits", "=", "body", ".", "get", "(", "\"limits\"", ",", "{", "}", ")", ".", "get", "(", "\"absolute\"", ")", ...
37.857143
0.00738
def remove_port(zone, port, permanent=True): ''' Remove a specific port from a zone. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewalld.remove_port internal 443/tcp ''' cmd = '--zone={0} --remove-port={1}'.format(zone, port) if permanent: ...
[ "def", "remove_port", "(", "zone", ",", "port", ",", "permanent", "=", "True", ")", ":", "cmd", "=", "'--zone={0} --remove-port={1}'", ".", "format", "(", "zone", ",", "port", ")", "if", "permanent", ":", "cmd", "+=", "' --permanent'", "return", "__firewall_...
19.833333
0.002674
def SearchFetchable(session=None, **kwargs): """Search okcupid.com with the given parameters. Parameters are registered to this function through :meth:`~okcupyd.filter.Filters.register_filter_builder` of :data:`~okcupyd.json_search.search_filters`. :returns: A :class:`~okcupyd.util.fetchable.Fetcha...
[ "def", "SearchFetchable", "(", "session", "=", "None", ",", "*", "*", "kwargs", ")", ":", "session", "=", "session", "or", "Session", ".", "login", "(", ")", "return", "util", ".", "Fetchable", "(", "SearchManager", "(", "SearchJSONFetcher", "(", "session"...
34.947368
0.001466
def get_client(config_file=None, apikey=None, username=None, userpass=None, service_url=None, verify_ssl_certs=None, select_first=None): """Configure the API service and creates a new instance of client. :param str config_file: absolute path to configuration file :param str apikey: apikey fr...
[ "def", "get_client", "(", "config_file", "=", "None", ",", "apikey", "=", "None", ",", "username", "=", "None", ",", "userpass", "=", "None", ",", "service_url", "=", "None", ",", "verify_ssl_certs", "=", "None", ",", "select_first", "=", "None", ")", ":...
42.72973
0.000618
def cee_map_remap_fabric_priority_fabric_remapped_priority(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map") name_key = ET.SubElement(cee_map, "name") name_key...
[ "def", "cee_map_remap_fabric_priority_fabric_remapped_priority", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "cee_map", "=", "ET", ".", "SubElement", "(", "config", ",", "\"cee-map\"", ",", "xmln...
50.785714
0.005525
def _parse_line_vars(self, line): """ Parse a line in a [XXXXX:vars] section. """ key_values = {} # Undocumented feature allows json in vars sections like so: # [prod:vars] # json_like_vars=[{'name': 'htpasswd_auth'}] # We'll try this first. If it fai...
[ "def", "_parse_line_vars", "(", "self", ",", "line", ")", ":", "key_values", "=", "{", "}", "# Undocumented feature allows json in vars sections like so:", "# [prod:vars]", "# json_like_vars=[{'name': 'htpasswd_auth'}]", "# We'll try this first. If it fails, we'll fall back to norm...
36.04
0.002162
def make_model(self): """Assemble the SBGN model from the collected INDRA Statements. This method assembles an SBGN model from the set of INDRA Statements. The assembled model is set as the assembler's sbgn attribute (it is represented as an XML ElementTree internally). The model is ret...
[ "def", "make_model", "(", "self", ")", ":", "ppa", "=", "PysbPreassembler", "(", "self", ".", "statements", ")", "ppa", ".", "replace_activities", "(", ")", "self", ".", "statements", "=", "ppa", ".", "statements", "self", ".", "sbgn", "=", "emaker", "."...
38.666667
0.002102
def sigmoidal(arr, contrast, bias): r""" Sigmoidal contrast is type of contrast control that adjusts the contrast without saturating highlights or shadows. It allows control over two factors: the contrast range from light to dark, and where the middle value of the mid-tones falls. The result is ...
[ "def", "sigmoidal", "(", "arr", ",", "contrast", ",", "bias", ")", ":", "if", "(", "arr", ".", "max", "(", ")", ">", "1.0", "+", "epsilon", ")", "or", "(", "arr", ".", "min", "(", ")", "<", "0", "-", "epsilon", ")", ":", "raise", "ValueError", ...
30.348315
0.000359
def notify(title, message, prio='ALERT', facility='LOCAL5', fmt='[{title}] {message}', retcode=None): """ Uses the ``syslog`` core Python module, which is not available on Windows platforms. Optional parameters: * ``prio`` - Syslog prority ...
[ "def", "notify", "(", "title", ",", "message", ",", "prio", "=", "'ALERT'", ",", "facility", "=", "'LOCAL5'", ",", "fmt", "=", "'[{title}] {message}'", ",", "retcode", "=", "None", ")", ":", "prio_map", "=", "{", "'EMERG'", ":", "syslog", ".", "LOG_EMERG...
25.574468
0.0004
def update_item(cls, hash_key, range_key=None, attributes_to_set=None, attributes_to_add=None): """Update item attributes. Currently SET and ADD actions are supported.""" primary_key = cls._encode_key(hash_key, range_key) value_names = {} encoded_values = {} dynamizer = Dynamize...
[ "def", "update_item", "(", "cls", ",", "hash_key", ",", "range_key", "=", "None", ",", "attributes_to_set", "=", "None", ",", "attributes_to_add", "=", "None", ")", ":", "primary_key", "=", "cls", ".", "_encode_key", "(", "hash_key", ",", "range_key", ")", ...
40.974359
0.005501
def intersection(self, *others): r"""Return a new multiset with elements common to the multiset and all others. >>> ms = Multiset('aab') >>> sorted(ms.intersection('abc')) ['a', 'b'] You can also use the ``&`` operator for the same effect. However, the operator version ...
[ "def", "intersection", "(", "self", ",", "*", "others", ")", ":", "result", "=", "self", ".", "__copy__", "(", ")", "_elements", "=", "result", ".", "_elements", "_total", "=", "result", ".", "_total", "for", "other", "in", "map", "(", "self", ".", "...
40.666667
0.00431
def _get_username(self, username=None, use_config=True, config_filename=None): """Determine the username If a username is given, this name is used. Otherwise the configuration file will be consulted if `use_config` is set to True. The user is asked for the username if the username is no...
[ "def", "_get_username", "(", "self", ",", "username", "=", "None", ",", "use_config", "=", "True", ",", "config_filename", "=", "None", ")", ":", "if", "not", "username", "and", "use_config", ":", "if", "self", ".", "_config", "is", "None", ":", "self", ...
41.757576
0.004255
def unitcube_overlap(self, ndraws=10000, rstate=None): """Using `ndraws` Monte Carlo draws, estimate the fraction of overlap between the ellipsoid and the unit cube.""" if rstate is None: rstate = np.random samples = [self.sample(rstate=rstate) for i in range(ndraws)] ...
[ "def", "unitcube_overlap", "(", "self", ",", "ndraws", "=", "10000", ",", "rstate", "=", "None", ")", ":", "if", "rstate", "is", "None", ":", "rstate", "=", "np", ".", "random", "samples", "=", "[", "self", ".", "sample", "(", "rstate", "=", "rstate"...
35.363636
0.005013
def main() -> None: """ Command-line processor. See ``--help`` for details. """ main_only_quicksetup_rootlogger(level=logging.DEBUG) parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "input_file", help="Inp...
[ "def", "main", "(", ")", "->", "None", ":", "main_only_quicksetup_rootlogger", "(", "level", "=", "logging", ".", "DEBUG", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ")", ...
39.634615
0.000473
def sortByColumnName(self, name, order=QtCore.Qt.AscendingOrder): """ Sorts the tree by the inputed column name's index and the given order. :param name | <str> order | <QtCore.Qt.SortOrder> """ self.setSortingEnabled(True) s...
[ "def", "sortByColumnName", "(", "self", ",", "name", ",", "order", "=", "QtCore", ".", "Qt", ".", "AscendingOrder", ")", ":", "self", ".", "setSortingEnabled", "(", "True", ")", "self", ".", "sortByColumn", "(", "self", ".", "column", "(", "name", ")", ...
39.333333
0.008287
def get_full_basename(node, basename): """Resolve a partial base name to the full path. :param node: The node representing the base name. :type node: astroid.NodeNG :param basename: The partial base name to resolve. :type basename: str :returns: The fully resolved base name. :rtype: str ...
[ "def", "get_full_basename", "(", "node", ",", "basename", ")", ":", "full_basename", "=", "basename", "top_level_name", "=", "re", ".", "sub", "(", "r\"\\(.*\\)\"", ",", "\"\"", ",", "basename", ")", ".", "split", "(", "\".\"", ",", "1", ")", "[", "0", ...
37.560976
0.003165
def get_version (pkg = __name__, public = False): """ Uses `git describe` to dynamically generate a version for the current code. The version is effecvtively a traditional tri-tuple ala (major, minor, patch), with the addenda that in this case the patch string is a combination of the number of commits since ...
[ "def", "get_version", "(", "pkg", "=", "__name__", ",", "public", "=", "False", ")", ":", "try", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "except", ":", "# pylint: disable=W0702", "cwd", "=", "None", "try", ":", "try", ":", "mod", "=", "__impo...
33.209302
0.032653
def parse_multipart_form_data( boundary: bytes, data: bytes, arguments: Dict[str, List[bytes]], files: Dict[str, List[HTTPFile]], ) -> None: """Parses a ``multipart/form-data`` body. The ``boundary`` and ``data`` parameters are both byte strings. The dictionaries given in the arguments and ...
[ "def", "parse_multipart_form_data", "(", "boundary", ":", "bytes", ",", "data", ":", "bytes", ",", "arguments", ":", "Dict", "[", "str", ",", "List", "[", "bytes", "]", "]", ",", "files", ":", "Dict", "[", "str", ",", "List", "[", "HTTPFile", "]", "]...
39.910714
0.00131
def insert(self, value): "Insert value in the keystore. Return the UUID key." key = str(uuid4()) self.set(key, value) return key
[ "def", "insert", "(", "self", ",", "value", ")", ":", "key", "=", "str", "(", "uuid4", "(", ")", ")", "self", ".", "set", "(", "key", ",", "value", ")", "return", "key" ]
31.2
0.0125
def central_likelihood(self, axis): """Returns new histogram with all values replaced by their central likelihoods along axis.""" result = self.cumulative_density(axis) result.histogram = 1 - 2 * np.abs(result.histogram - 0.5) return result
[ "def", "central_likelihood", "(", "self", ",", "axis", ")", ":", "result", "=", "self", ".", "cumulative_density", "(", "axis", ")", "result", ".", "histogram", "=", "1", "-", "2", "*", "np", ".", "abs", "(", "result", ".", "histogram", "-", "0.5", "...
53.6
0.011029
def log(row=None, commit=True, *args, **kargs): """Log a dict to the global run's history. If commit is false, enables multiple calls before commiting. Eg. wandb.log({'train-loss': 0.5, 'accuracy': 0.9}) """ if run is None: raise ValueError( "You must call `wandb.init` in the ...
[ "def", "log", "(", "row", "=", "None", ",", "commit", "=", "True", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "if", "run", "is", "None", ":", "raise", "ValueError", "(", "\"You must call `wandb.init` in the same process before calling log\"", ")", "...
29
0.005894
def script_request_list_send(self, target_system, target_component, force_mavlink1=False): ''' Request the overall list of mission items from the system/component. target_system : System ID (uint8_t) target_component : Component ID (u...
[ "def", "script_request_list_send", "(", "self", ",", "target_system", ",", "target_component", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "script_request_list_encode", "(", "target_system", ",", "target_component"...
52.222222
0.01046