text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def magick_to_rio(convert_opts): """Translate a limited subset of imagemagick convert commands to rio color operations Parameters ---------- convert_opts: String, imagemagick convert options Returns ------- operations string, ordered rio color operations """ ops = [] bands ...
[ "def", "magick_to_rio", "(", "convert_opts", ")", ":", "ops", "=", "[", "]", "bands", "=", "None", "def", "set_band", "(", "x", ")", ":", "global", "bands", "if", "x", ".", "upper", "(", ")", "==", "\"RGB\"", ":", "x", "=", "\"RGB\"", "bands", "=",...
25.516129
0.000609
def nt_db_search(self, files, base, unpack, euk_check, search_method, maximum_range, threads, evalue): ''' Nucleotide database search pipeline - pipeline where reads are searched as nucleotides, and hits are identified using nhmmer searches Parameters ------...
[ "def", "nt_db_search", "(", "self", ",", "files", ",", "base", ",", "unpack", ",", "euk_check", ",", "search_method", ",", "maximum_range", ",", "threads", ",", "evalue", ")", ":", "# Define outputs", "hmmsearch_output_table", "=", "files", ".", "hmmsearch_outpu...
46
0.002129
def AnnotateBED(bed, GTF, genome_file, bedcols=None, promoter=[1000,200]): """ Annotates a bed file. :param bed: either a /path/to/file.bed or a Pandas dataframe in bed format. /path/to/file.bed implies bedcols. :param GTF: /path/to/file.gtf :param genome_file: /path/to/file.genome - a tab separate...
[ "def", "AnnotateBED", "(", "bed", ",", "GTF", ",", "genome_file", ",", "bedcols", "=", "None", ",", "promoter", "=", "[", "1000", ",", "200", "]", ")", ":", "if", "type", "(", "bed", ")", "==", "type", "(", "\"string\"", ")", ":", "bed", "=", "pd...
32.107955
0.029008
def _handle_tag_definetext2(self): """Handle the DefineText2 tag.""" obj = _make_object("DefineText2") self._generic_definetext_parser(obj, self._get_struct_rgba) return obj
[ "def", "_handle_tag_definetext2", "(", "self", ")", ":", "obj", "=", "_make_object", "(", "\"DefineText2\"", ")", "self", ".", "_generic_definetext_parser", "(", "obj", ",", "self", ".", "_get_struct_rgba", ")", "return", "obj" ]
40.2
0.009756
def click_info_switch(f): """Decorator to create eager Click info switch option, as described in: http://click.pocoo.org/6/options/#callbacks-and-eager-options. Takes a no-argument function and abstracts the boilerplate required by Click (value checking, exit on done). Example: @click.opt...
[ "def", "click_info_switch", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "ctx", ",", "param", ",", "value", ")", ":", "if", "not", "value", "or", "ctx", ".", "resilient_parsing", ":", "return", "f", "(", ")", "ctx", ".", ...
27.807692
0.001337
def _add_loss_summaries(total_loss): """Add summaries for losses in CIFAR-10 model. Generates moving average for all losses and associated summaries for visualizing the performance of the network. Args: total_loss: Total loss from loss(). Returns: loss_averages_op: op for generating moving averages ...
[ "def", "_add_loss_summaries", "(", "total_loss", ")", ":", "# Compute the moving average of all individual losses and the total loss.", "loss_averages", "=", "tf", ".", "train", ".", "ExponentialMovingAverage", "(", "0.9", ",", "name", "=", "'avg'", ")", "losses", "=", ...
38.8
0.011066
def applyTransformOnGroup(self, transform, group): """Apply an SVG transformation to a RL Group shape. The transformation is the value of an SVG transform attribute like transform="scale(1, -1) translate(10, 30)". rotate(<angle> [<cx> <cy>]) is equivalent to: translate(<cx> <...
[ "def", "applyTransformOnGroup", "(", "self", ",", "transform", ",", "group", ")", ":", "tr", "=", "self", ".", "attrConverter", ".", "convertTransform", "(", "transform", ")", "for", "op", ",", "values", "in", "tr", ":", "if", "op", "==", "\"scale\"", ":...
40.945946
0.001934
def annual_frequency_of_exceedence(poe, t_haz): """ :param poe: array of probabilities of exceedence :param t_haz: hazard investigation time :returns: array of frequencies (with +inf values where poe=1) """ with warnings.catch_warnings(): warnings.simplefilter("ignore") # avoid R...
[ "def", "annual_frequency_of_exceedence", "(", "poe", ",", "t_haz", ")", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "# avoid RuntimeWarning: divide by zero encountered in log", "return", "-", ...
40.4
0.002421
def values(self, *args: str, **kwargs: str) -> "ValuesQuery": """ Make QuerySet return dicts instead of objects. """ fields_for_select = {} # type: Dict[str, str] for field in args: if field in fields_for_select: raise FieldError("Duplicate key {}".fo...
[ "def", "values", "(", "self", ",", "*", "args", ":", "str", ",", "*", "*", "kwargs", ":", "str", ")", "->", "\"ValuesQuery\"", ":", "fields_for_select", "=", "{", "}", "# type: Dict[str, str]", "for", "field", "in", "args", ":", "if", "field", "in", "f...
36.333333
0.001986
def pop_events(self, regex_pattern, timeout): """Pop events whose names match a regex pattern. If such event(s) exist, pop one event from each event queue that satisfies the condition. Otherwise, wait for an event that satisfies the condition to occur, with timeout. Results are...
[ "def", "pop_events", "(", "self", ",", "regex_pattern", ",", "timeout", ")", ":", "if", "not", "self", ".", "started", ":", "raise", "IllegalStateError", "(", "\"Dispatcher needs to be started before popping.\"", ")", "deadline", "=", "time", ".", "time", "(", "...
40.102564
0.001873
def getConfiguration(configPath = None): """ Reading the configuration file to look for where the different gates are running. :return: A json containing the information stored in the .cfg file. """ if configPath == None: # If a current.cfg has not been found, creating it by...
[ "def", "getConfiguration", "(", "configPath", "=", "None", ")", ":", "if", "configPath", "==", "None", ":", "# If a current.cfg has not been found, creating it by copying from default", "configPath", "=", "getConfigPath", "(", "\"browser.cfg\"", ")", "# Checking if the config...
39.234043
0.010053
def add_one(self, url: str, url_properties: Optional[URLProperties]=None, url_data: Optional[URLData]=None): '''Add a single URL to the table. Args: url: The URL to be added url_properties: Additional values to be saved url_data: Addit...
[ "def", "add_one", "(", "self", ",", "url", ":", "str", ",", "url_properties", ":", "Optional", "[", "URLProperties", "]", "=", "None", ",", "url_data", ":", "Optional", "[", "URLData", "]", "=", "None", ")", ":", "self", ".", "add_many", "(", "[", "A...
37.363636
0.019002
def run_validators(self, value): """ Test the given value against all the validators on the field, and either raise a `ValidationError` or simply return. """ errors = [] for validator in self.validators: if hasattr(validator, 'set_context'): va...
[ "def", "run_validators", "(", "self", ",", "value", ")", ":", "errors", "=", "[", "]", "for", "validator", "in", "self", ".", "validators", ":", "if", "hasattr", "(", "validator", ",", "'set_context'", ")", ":", "validator", ".", "set_context", "(", "sel...
38.826087
0.002186
def to_dot_file(self, fname: str): """ write a '.dot' file. """ with open(fname, 'w') as f: f.write(self.to_dot())
[ "def", "to_dot_file", "(", "self", ",", "fname", ":", "str", ")", ":", "with", "open", "(", "fname", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "self", ".", "to_dot", "(", ")", ")" ]
25.5
0.012658
def plot_ts(fignum, dates, ts): """ plot the geomagnetic polarity time scale Parameters __________ fignum : matplotlib figure number dates : bounding dates for plot ts : time scale ck95, gts04, or gts12 """ vertical_plot_init(fignum, 10, 3) TS, Chrons = pmag.get_ts(ts) p = 1...
[ "def", "plot_ts", "(", "fignum", ",", "dates", ",", "ts", ")", ":", "vertical_plot_init", "(", "fignum", ",", "10", ",", "3", ")", "TS", ",", "Chrons", "=", "pmag", ".", "get_ts", "(", "ts", ")", "p", "=", "1", "X", ",", "Y", "=", "[", "]", "...
28.5
0.000808
def get_parent(self, el, no_iframe=False): """Get parent.""" parent = el.parent if no_iframe and parent is not None and self.is_iframe(parent): parent = None return parent
[ "def", "get_parent", "(", "self", ",", "el", ",", "no_iframe", "=", "False", ")", ":", "parent", "=", "el", ".", "parent", "if", "no_iframe", "and", "parent", "is", "not", "None", "and", "self", ".", "is_iframe", "(", "parent", ")", ":", "parent", "=...
30
0.009259
def cluster_sample1(): "Start with wrong number of clusters." start_centers = [[3.7, 5.5]] template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE1, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION) template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE1, criterion = splitt...
[ "def", "cluster_sample1", "(", ")", ":", "start_centers", "=", "[", "[", "3.7", ",", "5.5", "]", "]", "template_clustering", "(", "start_centers", ",", "SIMPLE_SAMPLES", ".", "SAMPLE_SIMPLE1", ",", "criterion", "=", "splitting_type", ".", "BAYESIAN_INFORMATION_CRI...
72.4
0.019126
def omega_mixture(omegas, zs, CASRNs=None, Method=None, AvailableMethods=False): r'''This function handles the calculation of a mixture's acentric factor. Calculation is based on the omegas provided for each pure component. Will automatically select a method to use if no Method is provided...
[ "def", "omega_mixture", "(", "omegas", ",", "zs", ",", "CASRNs", "=", "None", ",", "Method", "=", "None", ",", "AvailableMethods", "=", "False", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "none_and_length_check", "(",...
32.441176
0.00044
def write_json(f: TextIO, deja_vu_sans_path: str, measurer: text_measurer.TextMeasurer, encodings: Iterable[str]) -> None: """Write the data required by PrecalculatedTextMeasurer to a stream.""" supported_characters = list( generate_supported_characters(deja_vu_sans_path)) ...
[ "def", "write_json", "(", "f", ":", "TextIO", ",", "deja_vu_sans_path", ":", "str", ",", "measurer", ":", "text_measurer", ".", "TextMeasurer", ",", "encodings", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "supported_characters", "=", "list", ...
54.444444
0.002006
def filtmask(sp, fmin=0.02, fmax=0.15, debugplot=0): """Filter spectrum in Fourier space and apply cosine bell. Parameters ---------- sp : numpy array Spectrum to be filtered and masked. fmin : float Minimum frequency to be employed. fmax : float Maximum frequency to be ...
[ "def", "filtmask", "(", "sp", ",", "fmin", "=", "0.02", ",", "fmax", "=", "0.15", ",", "debugplot", "=", "0", ")", ":", "# Fourier filtering", "xf", "=", "np", ".", "fft", ".", "fftfreq", "(", "sp", ".", "size", ")", "yf", "=", "np", ".", "fft", ...
30.438596
0.000558
def apply_link_ref(offset: int, length: int, value: bytes, bytecode: bytes) -> bytes: """ Returns the new bytecode with `value` put into the location indicated by `offset` and `length`. """ try: validate_empty_bytes(offset, length, bytecode) except ValidationError: raise BytecodeLink...
[ "def", "apply_link_ref", "(", "offset", ":", "int", ",", "length", ":", "int", ",", "value", ":", "bytes", ",", "bytecode", ":", "bytes", ")", "->", "bytes", ":", "try", ":", "validate_empty_bytes", "(", "offset", ",", "length", ",", "bytecode", ")", "...
35.6875
0.008532
def get_slide_vars(self, slide_src, source=None): """ Computes a single slide template vars from its html source code. Also extracts slide informations for the table of contents. """ presenter_notes = None find = re.search(r'<h\d[^>]*>presenter notes</h\d>', slide_src, ...
[ "def", "get_slide_vars", "(", "self", ",", "slide_src", ",", "source", "=", "None", ")", ":", "presenter_notes", "=", "None", "find", "=", "re", ".", "search", "(", "r'<h\\d[^>]*>presenter notes</h\\d>'", ",", "slide_src", ",", "re", ".", "DOTALL", "|", "re"...
34.630435
0.001221
def list(self, **params): """ Retrieve all products Returns all products available to the user according to the parameters provided :calls: ``get /products`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style access...
[ "def", "list", "(", "self", ",", "*", "*", "params", ")", ":", "_", ",", "_", ",", "products", "=", "self", ".", "http_client", ".", "get", "(", "\"/products\"", ",", "params", "=", "params", ")", "return", "products" ]
34.285714
0.008114
def posterior_predictive_to_xarray(self): """Convert posterior_predictive samples to xarray.""" data = {k: np.expand_dims(v, 0) for k, v in self.posterior_predictive.items()} return dict_to_dataset(data, library=self.pymc3, coords=self.coords, dims=self.dims)
[ "def", "posterior_predictive_to_xarray", "(", "self", ")", ":", "data", "=", "{", "k", ":", "np", ".", "expand_dims", "(", "v", ",", "0", ")", "for", "k", ",", "v", "in", "self", ".", "posterior_predictive", ".", "items", "(", ")", "}", "return", "di...
70
0.014134
def update(self, data={}, options={}): """ Update the configuration with new data. This can be passed either or both `data` and `options`. `options` is a dict of keypath/value pairs like this (similar to CherryPy's config mechanism: >>> c.update(options={ ...
[ "def", "update", "(", "self", ",", "data", "=", "{", "}", ",", "options", "=", "{", "}", ")", ":", "# Handle an update with a set of options like CherryPy does", "for", "key", "in", "options", ":", "self", "[", "key", "]", "=", "options", "[", "key", "]", ...
31
0.001787
def _overlap(y,yr,psd): """ returns the detector noise weighted inner product """ yyr = _inner_product(y,yr,psd) yy = _inner_product(y,y,psd) yryr = _inner_product(yr,yr,psd) olap = yyr/np.sqrt(yy*yryr) return olap
[ "def", "_overlap", "(", "y", ",", "yr", ",", "psd", ")", ":", "yyr", "=", "_inner_product", "(", "y", ",", "yr", ",", "psd", ")", "yy", "=", "_inner_product", "(", "y", ",", "y", ",", "psd", ")", "yryr", "=", "_inner_product", "(", "yr", ",", "...
33.571429
0.045643
def histogram(self, tag, values, bins, step=None): """Saves histogram of values. Args: tag: str: label for this data values: ndarray: will be flattened by this routine bins: number of bins in histogram, or array of bins for onp.histogram step: int: training step """ if step is N...
[ "def", "histogram", "(", "self", ",", "tag", ",", "values", ",", "bins", ",", "step", "=", "None", ")", ":", "if", "step", "is", "None", ":", "step", "=", "self", ".", "_step", "else", ":", "self", ".", "_step", "=", "step", "values", "=", "onp",...
33.405405
0.002358
def valid_sequences(self): """Returns list""" valid_sets = [[x] for x in self.possible_items if x['left'] == 0] change = True niter = 200 while change and niter > 0: change = False niter -=1 for possible in sorted(self.possible_items, key=lambd...
[ "def", "valid_sequences", "(", "self", ")", ":", "valid_sets", "=", "[", "[", "x", "]", "for", "x", "in", "self", ".", "possible_items", "if", "x", "[", "'left'", "]", "==", "0", "]", "change", "=", "True", "niter", "=", "200", "while", "change", "...
49.722222
0.008772
def draw(self, **kwargs): """ Draws the heatmap of the ranking matrix of variables. """ # Set the axes aspect to be equal self.ax.set_aspect("equal") # Generate a mask for the upper triangle mask = np.zeros_like(self.ranks_, dtype=np.bool) mask[np.triu_in...
[ "def", "draw", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Set the axes aspect to be equal", "self", ".", "ax", ".", "set_aspect", "(", "\"equal\"", ")", "# Generate a mask for the upper triangle", "mask", "=", "np", ".", "zeros_like", "(", "self", ".", ...
34.675676
0.001516
def compose_schemas(*schemas): """ Returns a single three-ple of the following for all provided schemas: - a map of attribute names to attributes for all related schema attributes - a set of names of all related required schema attributes - a set of names of all related default s...
[ "def", "compose_schemas", "(", "*", "schemas", ")", ":", "key", "=", "'jsonattrs:compose:'", "+", "','", ".", "join", "(", "[", "str", "(", "s", ".", "pk", ")", "for", "s", "in", "schemas", "]", ")", "cached", "=", "caches", "[", "'jsonattrs'", "]", ...
42.170732
0.000565
def calc_max_flexural_wavelength(self): """ Returns the approximate maximum flexural wavelength This is important when padding of the grid is required: in Flexure (this code), grids are padded out to one maximum flexural wavelength, but in any case, the flexural wavelength is a good character...
[ "def", "calc_max_flexural_wavelength", "(", "self", ")", ":", "if", "np", ".", "isscalar", "(", "self", ".", "D", ")", ":", "Dmax", "=", "self", ".", "D", "else", ":", "Dmax", "=", "self", ".", "D", ".", "max", "(", ")", "# This is an approximation if ...
47.823529
0.010856
def find_file(self, path, tgt_env='base', **kwargs): # pylint: disable=W0613 ''' Find the first file to match the path and ref, read the file out of git and send the path to the newly cached file ''' fnd = {'path': '', 'rel': ''} if os.path.isabs(path) or ...
[ "def", "find_file", "(", "self", ",", "path", ",", "tgt_env", "=", "'base'", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "fnd", "=", "{", "'path'", ":", "''", ",", "'rel'", ":", "''", "}", "if", "os", ".", "path", ".", "isabs", "(...
41.838384
0.000708
def logProbability(self, distn): """Form of distribution must be an array of counts in order of self.keys.""" x = numpy.asarray(distn) n = x.sum() return (logFactorial(n) - numpy.sum([logFactorial(k) for k in x]) + numpy.sum(x * numpy.log(self.dist.pmf)))
[ "def", "logProbability", "(", "self", ",", "distn", ")", ":", "x", "=", "numpy", ".", "asarray", "(", "distn", ")", "n", "=", "x", ".", "sum", "(", ")", "return", "(", "logFactorial", "(", "n", ")", "-", "numpy", ".", "sum", "(", "[", "logFactori...
45.333333
0.01083
def btc_tx_get_hash( tx_serialized, hashcode=None ): """ Make a transaction hash (txid) from a hex tx, optionally along with a sighash. This DOES NOT WORK for segwit transactions """ if btc_tx_is_segwit(tx_serialized): raise ValueError('Segwit transaction: {}'.format(tx_serialized)) tx_...
[ "def", "btc_tx_get_hash", "(", "tx_serialized", ",", "hashcode", "=", "None", ")", ":", "if", "btc_tx_is_segwit", "(", "tx_serialized", ")", ":", "raise", "ValueError", "(", "'Segwit transaction: {}'", ".", "format", "(", "tx_serialized", ")", ")", "tx_bin", "="...
40.357143
0.015571
def _transliterate (self, text, outFormat): """ Transliterate the text to the target transliteration scheme.""" result = [] for c in text: if c.isspace(): result.append(c) try: result.append(self[c].equivalents[outFormat.name]) except KeyError...
[ "def", "_transliterate", "(", "self", ",", "text", ",", "outFormat", ")", ":", "result", "=", "[", "]", "for", "c", "in", "text", ":", "if", "c", ".", "isspace", "(", ")", ":", "result", ".", "append", "(", "c", ")", "try", ":", "result", ".", ...
38.2
0.012788
def bulk_remove(self, named_graph, add, size=DEFAULT_CHUNK_SIZE): """ Remove batches of statements in n-sized chunks. """ return self.bulk_update(named_graph, add, size, is_add=False)
[ "def", "bulk_remove", "(", "self", ",", "named_graph", ",", "add", ",", "size", "=", "DEFAULT_CHUNK_SIZE", ")", ":", "return", "self", ".", "bulk_update", "(", "named_graph", ",", "add", ",", "size", ",", "is_add", "=", "False", ")" ]
42.2
0.009302
def _parse_common(text, **options): """ Tries to parse the string as a common datetime format. :param text: The string to parse. :type text: str :rtype: dict or None """ m = COMMON.match(text) has_date = False year = 0 month = 1 day = 1 if not m: raise ParserEr...
[ "def", "_parse_common", "(", "text", ",", "*", "*", "options", ")", ":", "m", "=", "COMMON", ".", "match", "(", "text", ")", "has_date", "=", "False", "year", "=", "0", "month", "=", "1", "day", "=", "1", "if", "not", "m", ":", "raise", "ParserEr...
22.819672
0.000689
def guess_url_vcs(url): """ Given a url, try to guess what kind of VCS it's for. Return None if we can't make a good guess. """ parsed = urllib.parse.urlsplit(url) if parsed.scheme in ('git', 'svn'): return parsed.scheme elif parsed.path.endswith('.git'): return 'git' e...
[ "def", "guess_url_vcs", "(", "url", ")", ":", "parsed", "=", "urllib", ".", "parse", ".", "urlsplit", "(", "url", ")", "if", "parsed", ".", "scheme", "in", "(", "'git'", ",", "'svn'", ")", ":", "return", "parsed", ".", "scheme", "elif", "parsed", "."...
31.227273
0.001412
def update_many(path,points): """update_many(path,points) path is a string points is a list of (timestamp,value) points """ if not points: return points = [ (int(t),float(v)) for (t,v) in points] points.sort(key=lambda p: p[0],reverse=True) #order points by timestamp, newest first fh = None try: fh = o...
[ "def", "update_many", "(", "path", ",", "points", ")", ":", "if", "not", "points", ":", "return", "points", "=", "[", "(", "int", "(", "t", ")", ",", "float", "(", "v", ")", ")", "for", "(", "t", ",", "v", ")", "in", "points", "]", "points", ...
24.9375
0.045894
def _add_conversation(self, conversation): """ Add the conversation and fire the :meth:`on_conversation_added` event. :param conversation: The conversation object to add. :type conversation: :class:`~.AbstractConversation` The conversation is added to the internal list of conve...
[ "def", "_add_conversation", "(", "self", ",", "conversation", ")", ":", "handler", "=", "functools", ".", "partial", "(", "self", ".", "_handle_conversation_exit", ",", "conversation", ")", "tokens", "=", "[", "]", "def", "linked_token", "(", "signal", ",", ...
37.621622
0.001401
def _parse_header_params(self,header_param_lines): '''解析头部参数''' headers = {} for line in header_param_lines: if line.strip(): # 跳过空行 key,val = line.split(':', 1) headers[key.lower()] = val.strip() return headers
[ "def", "_parse_header_params", "(", "self", ",", "header_param_lines", ")", ":", "headers", "=", "{", "}", "for", "line", "in", "header_param_lines", ":", "if", "line", ".", "strip", "(", ")", ":", "# 跳过空行", "key", ",", "val", "=", "line", ".", "split", ...
35
0.017422
def _convert_from(data): """Internal function that will be hooked to the native `json.loads` Find the right deserializer for a given value, taking into account the internal deserializer registry. """ try: module, klass_name = data['__class__'].rsplit('.', 1) klass = getattr(import_m...
[ "def", "_convert_from", "(", "data", ")", ":", "try", ":", "module", ",", "klass_name", "=", "data", "[", "'__class__'", "]", ".", "rsplit", "(", "'.'", ",", "1", ")", "klass", "=", "getattr", "(", "import_module", "(", "module", ")", ",", "klass_name"...
44.45
0.001101
def _restoreDPFromArchive(self): """Callback for item menu.""" dp = self._dp_menu_on if dp and dp.archived: dp.restore_from_archive(parent=self)
[ "def", "_restoreDPFromArchive", "(", "self", ")", ":", "dp", "=", "self", ".", "_dp_menu_on", "if", "dp", "and", "dp", ".", "archived", ":", "dp", ".", "restore_from_archive", "(", "parent", "=", "self", ")" ]
35.2
0.011111
def get_child_classes(cls, slot, page, instance=None): """Restrict child classes of Card to one of each: Header, Body and Footer""" child_classes = super(BootstrapCardPlugin, cls).get_child_classes(slot, page, instance) # allow only one child of type Header, Body, Footer for child in ins...
[ "def", "get_child_classes", "(", "cls", ",", "slot", ",", "page", ",", "instance", "=", "None", ")", ":", "child_classes", "=", "super", "(", "BootstrapCardPlugin", ",", "cls", ")", ".", "get_child_classes", "(", "slot", ",", "page", ",", "instance", ")", ...
58.75
0.008386
def _free_shortcut(self, shortcut): """ Replace the shortcut of elements, that has the shortcut passed. :param shortcut: The shortcut. :type shortcut: str """ alpha_numbers = '1234567890abcdefghijklmnopqrstuvwxyz' elements = self.parser.find('[accesskey]').list_...
[ "def", "_free_shortcut", "(", "self", ",", "shortcut", ")", ":", "alpha_numbers", "=", "'1234567890abcdefghijklmnopqrstuvwxyz'", "elements", "=", "self", ".", "parser", ".", "find", "(", "'[accesskey]'", ")", ".", "list_results", "(", ")", "found", "=", "False",...
38.857143
0.001794
def image_display(element, max_frames, fmt): """ Used to render elements to an image format (svg or png) if requested in the display formats. """ if fmt not in Store.display_formats: return None info = process_object(element) if info: display(HTML(info)) return b...
[ "def", "image_display", "(", "element", ",", "max_frames", ",", "fmt", ")", ":", "if", "fmt", "not", "in", "Store", ".", "display_formats", ":", "return", "None", "info", "=", "process_object", "(", "element", ")", "if", "info", ":", "display", "(", "HTM...
28.708333
0.001404
def evaluate(): """Get Policy and Value for each network, for each position Usage: python3 sharp_positions.py evaluate --sgf_dir data/s --model_dir models/ """ def short_str(v): if isinstance(v, float): return "{.3f}".format(v) return str(v) # Load positons ...
[ "def", "evaluate", "(", ")", ":", "def", "short_str", "(", "v", ")", ":", "if", "isinstance", "(", "v", ",", "float", ")", ":", "return", "\"{.3f}\"", ".", "format", "(", "v", ")", "return", "str", "(", "v", ")", "# Load positons", "sgf_names", ",", ...
35.52459
0.002245
def _check_module_attrs(self, node, module, module_names): """check that module_names (list of string) are accessible through the given module if the latest access name corresponds to a module, return it """ assert isinstance(module, astroid.Module), module while module_n...
[ "def", "_check_module_attrs", "(", "self", ",", "node", ",", "module", ",", "module_names", ")", ":", "assert", "isinstance", "(", "module", ",", "astroid", ".", "Module", ")", ",", "module", "while", "module_names", ":", "name", "=", "module_names", ".", ...
39.114286
0.002138
def create_address(kwargs=None, call=None): ''' Create a static address in a region. CLI Example: .. code-block:: bash salt-cloud -f create_address gce name=my-ip region=us-central1 address=IP ''' if call != 'function': raise SaltCloudSystemExit( 'The create_addres...
[ "def", "create_address", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_address function must be called with -f or --function.'", ")", "if", "not", "kwargs", "o...
26.285714
0.00131
def release(path, repository): """Create a new release upgrade recipe, for developers.""" upgrader = InvenioUpgrader() logger = upgrader.get_logger() try: endpoints = upgrader.find_endpoints() if not endpoints: logger.error("No upgrades found.") click.Abort() ...
[ "def", "release", "(", "path", ",", "repository", ")", ":", "upgrader", "=", "InvenioUpgrader", "(", ")", "logger", "=", "upgrader", ".", "get_logger", "(", ")", "try", ":", "endpoints", "=", "upgrader", ".", "find_endpoints", "(", ")", "if", "not", "end...
27.653846
0.001344
def _iter_serial_enum_member(eid, value, bitmask): """Iterate serial and CID of enum members with given value and bitmask. Here only valid values are returned, as `idaapi.BADNODE` always indicates an invalid member. """ cid, serial = idaapi.get_first_serial_enum_member(eid, value, bitmask) whil...
[ "def", "_iter_serial_enum_member", "(", "eid", ",", "value", ",", "bitmask", ")", ":", "cid", ",", "serial", "=", "idaapi", ".", "get_first_serial_enum_member", "(", "eid", ",", "value", ",", "bitmask", ")", "while", "cid", "!=", "idaapi", ".", "BADNODE", ...
43.1
0.002273
def best_buy_2(self): """量縮價不跌 """ result = self.data.capacity[-1] < self.data.capacity[-2] and \ self.data.price[-1] > self.data.price[-2] return result
[ "def", "best_buy_2", "(", "self", ")", ":", "result", "=", "self", ".", "data", ".", "capacity", "[", "-", "1", "]", "<", "self", ".", "data", ".", "capacity", "[", "-", "2", "]", "and", "self", ".", "data", ".", "price", "[", "-", "1", "]", ...
32.833333
0.014851
def applyTimeCalMs1(msrunContainer, specfile, correctionData, **kwargs): """Applies correction values to the MS1 ion m/z arrays in order to correct for a time dependent m/z error. :param msrunContainer: intance of :class:`maspy.core.MsrunContainer`, containing the :class:`maspy.core.Sai` items of t...
[ "def", "applyTimeCalMs1", "(", "msrunContainer", ",", "specfile", ",", "correctionData", ",", "*", "*", "kwargs", ")", ":", "toleranceMode", "=", "kwargs", ".", "get", "(", "'toleranceMode'", ",", "'relative'", ")", "if", "toleranceMode", "==", "'relative'", "...
48.37037
0.001502
def reset(self, initial_document=None, append_to_history=False): """ :param append_to_history: Append current input to history first. """ assert initial_document is None or isinstance(initial_document, Document) if append_to_history: self.append_to_history() ...
[ "def", "reset", "(", "self", ",", "initial_document", "=", "None", ",", "append_to_history", "=", "False", ")", ":", "assert", "initial_document", "is", "None", "or", "isinstance", "(", "initial_document", ",", "Document", ")", "if", "append_to_history", ":", ...
39.192982
0.002183
def _read_requirements(metadata, extras): """Read wheel metadata to know what it depends on. The `run_requires` attribute contains a list of dict or str specifying requirements. For dicts, it may contain an "extra" key to specify these requirements are for a specific extra. Unfortunately, not all field...
[ "def", "_read_requirements", "(", "metadata", ",", "extras", ")", ":", "extras", "=", "extras", "or", "(", ")", "requirements", "=", "[", "]", "for", "entry", "in", "metadata", ".", "run_requires", ":", "if", "isinstance", "(", "entry", ",", "six", ".", ...
44.5
0.000647
def oauth_connect(self, provider, action): """ This endpoint doesn't check if user is logged in, because it has two functions 1. If the user is not logged in, it will try to signup the user - if the social info exist, it will login - not, it will create a new account and...
[ "def", "oauth_connect", "(", "self", ",", "provider", ",", "action", ")", ":", "valid_actions", "=", "[", "\"connect\"", ",", "\"authorized\"", ",", "\"test\"", "]", "_redirect", "=", "views", ".", "auth", ".", "Account", ".", "account_settings", "if", "is_a...
36.490741
0.001976
def searchTag(self,HTAG="#python"): """Set Twitter search or stream criteria for the selection of tweets""" self.t = Twython(app_key =self.app_key , app_secret =self.app_secret , oauth_token =self.oauth_token ...
[ "def", "searchTag", "(", "self", ",", "HTAG", "=", "\"#python\"", ")", ":", "self", ".", "t", "=", "Twython", "(", "app_key", "=", "self", ".", "app_key", ",", "app_secret", "=", "self", ".", "app_secret", ",", "oauth_token", "=", "self", ".", "oauth_t...
54
0.038835
def run(self, lines): """ Match and generate dot code blocks.""" text = "\n".join(lines) while 1: m = BLOCK_RE.search(text) if m: command = m.group('command') # Whitelist command, prevent command injection. if command not i...
[ "def", "run", "(", "self", ",", "lines", ")", ":", "text", "=", "\"\\n\"", ".", "join", "(", "lines", ")", "while", "1", ":", "m", "=", "BLOCK_RE", ".", "search", "(", "text", ")", "if", "m", ":", "command", "=", "m", ".", "group", "(", "'comma...
37.830189
0.001458
def makeParser(self): """Generate the argparse parser object containing the bootloader accepted parameters """ self.parser = argparse.ArgumentParser(description='Starts the executable.', prog=("{0} -m scoop.bootstrap" ...
[ "def", "makeParser", "(", "self", ")", ":", "self", ".", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Starts the executable.'", ",", "prog", "=", "(", "\"{0} -m scoop.bootstrap\"", ")", ".", "format", "(", "sys", ".", "executabl...
54
0.001914
def values(self, values): """The values for insert , it can be a dict row or list tuple row. """ if isinstance(values, dict): l = [] for column in self._columns: l.append(values[column]) self._values.append(tuple(l)) else: ...
[ "def", "values", "(", "self", ",", "values", ")", ":", "if", "isinstance", "(", "values", ",", "dict", ")", ":", "l", "=", "[", "]", "for", "column", "in", "self", ".", "_columns", ":", "l", ".", "append", "(", "values", "[", "column", "]", ")", ...
30.666667
0.010554
async def set_passport_data_errors(self, user_id: base.Integer, errors: typing.List[types.PassportElementError]) -> base.Boolean: """ Informs a user that some of the Telegram Passport elements they provided contains errors. ...
[ "async", "def", "set_passport_data_errors", "(", "self", ",", "user_id", ":", "base", ".", "Integer", ",", "errors", ":", "typing", ".", "List", "[", "types", ".", "PassportElementError", "]", ")", "->", "base", ".", "Boolean", ":", "errors", "=", "prepare...
51.25
0.008208
def try_unbuffered_file(file, _alreadyopen={}): """ Try re-opening a file in an unbuffered mode and return it. If that fails, just return the original file. This function remembers the file descriptors it opens, so it never opens the same one twice. This is meant for files like sys....
[ "def", "try_unbuffered_file", "(", "file", ",", "_alreadyopen", "=", "{", "}", ")", ":", "try", ":", "fileno", "=", "file", ".", "fileno", "(", ")", "except", "(", "AttributeError", ",", "UnsupportedOperation", ")", ":", "# Unable to use fileno to re-open unbuff...
40.458333
0.001006
def beacon(config): ''' Broadcast values via zeroconf If the announced values are static, it is advised to set run_once: True (do not poll) on the beacon configuration. The following are required configuration settings: - ``servicetype`` - The service type to announce - ``port`` - The por...
[ "def", "beacon", "(", "config", ")", ":", "ret", "=", "[", "]", "changes", "=", "{", "}", "txt", "=", "{", "}", "global", "LAST_GRAINS", "_config", "=", "{", "}", "list", "(", "map", "(", "_config", ".", "update", ",", "config", ")", ")", "if", ...
41.789855
0.001186
def _create_axes_grid(length_plotters, rows, cols, **kwargs): """Create figure and axes for grids with multiple plots. Parameters ---------- n_items : int Number of panels required rows : int Number of rows cols : int Number of columns Returns ------- fig : ...
[ "def", "_create_axes_grid", "(", "length_plotters", ",", "rows", ",", "cols", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "\"constrained_layout\"", ",", "True", ")", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "rows", ","...
24.615385
0.001504
def _load_endpoints_to_config(self, provider, target_entity_id, config=None): """ Loads approved endpoints to the config. :type url_base: str :type provider: str :type target_entity_id: str :rtype: dict[str, Any] :param url_base: The proxy base url :para...
[ "def", "_load_endpoints_to_config", "(", "self", ",", "provider", ",", "target_entity_id", ",", "config", "=", "None", ")", ":", "idp_conf", "=", "copy", ".", "deepcopy", "(", "config", "or", "self", ".", "idp_config", ")", "for", "service", ",", "endpoint",...
40.916667
0.00199
def get_path_for_termid(self,termid): """ This function returns the path (in terms of phrase types) from one term the root @type termid: string @param termid: one term id @rtype: list @return: the path, list of phrase types """ terminal_id = self.term...
[ "def", "get_path_for_termid", "(", "self", ",", "termid", ")", ":", "terminal_id", "=", "self", ".", "terminal_for_term", ".", "get", "(", "termid", ")", "paths", "=", "self", ".", "paths_for_terminal", "[", "terminal_id", "]", "labels", "=", "[", "self", ...
40.083333
0.010163
def VerifierMiddleware(verifier): """Common wrapper for the authentication modules. * Parses the request before passing it on to the authentication module. * Sets 'pyoidc' cookie if authentication succeeds. * Redirects the user to complete the authentication. * Allows the user to ret...
[ "def", "VerifierMiddleware", "(", "verifier", ")", ":", "@", "wraps", "(", "verifier", ".", "verify", ")", "def", "wrapper", "(", "environ", ",", "start_response", ")", ":", "data", "=", "get_post", "(", "environ", ")", "kwargs", "=", "dict", "(", "urlpa...
42.147059
0.000682
def search(name=None, description=None, style=None, mood=None, start=0, \ results=15, buckets=None, limit=False, \ fuzzy_match=False, sort=None, max_familiarity=None, min_familiarity=None, \ max_hotttnesss=None, min_hotttnesss=None, test_new_things=None, rank_type=None, \ ...
[ "def", "search", "(", "name", "=", "None", ",", "description", "=", "None", ",", "style", "=", "None", ",", "mood", "=", "None", ",", "start", "=", "0", ",", "results", "=", "15", ",", "buckets", "=", "None", ",", "limit", "=", "False", ",", "fuz...
45.446154
0.015905
def quit(self, *args, **kwargs): # real signature unknown """ quit the instrument thread """ self.stop() self._stop = True self.msleep(2* int(1e3 / self.settings['update frequency'])) super(Plant, self).quit(*args, **kwargs)
[ "def", "quit", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# real signature unknown", "self", ".", "stop", "(", ")", "self", ".", "_stop", "=", "True", "self", ".", "msleep", "(", "2", "*", "int", "(", "1e3", "/", "self", "...
34.375
0.010638
def set_account_username(self, account, old_username, new_username): """ Account's username was changed. """ self._delete_account(account, old_username) self._save_account(account, new_username)
[ "def", "set_account_username", "(", "self", ",", "account", ",", "old_username", ",", "new_username", ")", ":", "self", ".", "_delete_account", "(", "account", ",", "old_username", ")", "self", ".", "_save_account", "(", "account", ",", "new_username", ")" ]
53.75
0.009174
def _get_value(self, variable): """Return value of variable in solution.""" return swiglpk.glp_get_col_prim( self._problem._p, self._problem._variables[variable])
[ "def", "_get_value", "(", "self", ",", "variable", ")", ":", "return", "swiglpk", ".", "glp_get_col_prim", "(", "self", ".", "_problem", ".", "_p", ",", "self", ".", "_problem", ".", "_variables", "[", "variable", "]", ")" ]
46.75
0.010526
def parse_coordinates(variant, category): """Find out the coordinates for a variant Args: variant(cyvcf2.Variant) Returns: coordinates(dict): A dictionary on the form: { 'position':<int>, 'end':<int>, 'end_chrom':<str>, 'length':<int>...
[ "def", "parse_coordinates", "(", "variant", ",", "category", ")", ":", "ref", "=", "variant", ".", "REF", "if", "variant", ".", "ALT", ":", "alt", "=", "variant", ".", "ALT", "[", "0", "]", "if", "category", "==", "\"str\"", "and", "not", "variant", ...
25.539474
0.001984
def log(**data): """RPC method for logging events Makes entry with new account creating Return None """ # Get data from request body entry = { "module": data["params"]["module"], "event": data["params"]["event"], "timestamp": data["params"]["timestamp"], "arguments": data["params"]["arguments"] } # Call...
[ "def", "log", "(", "*", "*", "data", ")", ":", "# Get data from request body", "entry", "=", "{", "\"module\"", ":", "data", "[", "\"params\"", "]", "[", "\"module\"", "]", ",", "\"event\"", ":", "data", "[", "\"params\"", "]", "[", "\"event\"", "]", ","...
26.571429
0.036364
def parse(self, data=None, table_name=None): """Parse the lines from index i :param data: optional, store the parsed result to it when specified :param table_name: when inside a table array, it is the table name """ temp = self.dict_() sub_table = None is_array =...
[ "def", "parse", "(", "self", ",", "data", "=", "None", ",", "table_name", "=", "None", ")", ":", "temp", "=", "self", ".", "dict_", "(", ")", "sub_table", "=", "None", "is_array", "=", "False", "line", "=", "''", "while", "True", ":", "line", "=", ...
48.046875
0.000637
def _maybe_unique_host(onion): """ :param onion: IAuthenticatedOnionClients provider :returns: a .onion hostname if all clients have the same name or raises ValueError otherwise """ hosts = [ onion.get_client(nm).hostname for nm in onion.client_names() ] if not hosts...
[ "def", "_maybe_unique_host", "(", "onion", ")", ":", "hosts", "=", "[", "onion", ".", "get_client", "(", "nm", ")", ".", "hostname", "for", "nm", "in", "onion", ".", "client_names", "(", ")", "]", "if", "not", "hosts", ":", "raise", "ValueError", "(", ...
28.782609
0.001462
def client_args_for_bank(bank_info, ofx_version): """ Return the client arguments to use for a particular Institution, as found from ofxhome. This provides us with an extension point to override or augment ofxhome data for specific institutions, such as those that require specific User-Agent headers...
[ "def", "client_args_for_bank", "(", "bank_info", ",", "ofx_version", ")", ":", "client_args", "=", "{", "'ofx_version'", ":", "str", "(", "ofx_version", ")", "}", "if", "'ofx.discovercard.com'", "in", "bank_info", "[", "'url'", "]", ":", "# Discover needs no User-...
43.5
0.000937
def get_id2gos(self, **kws): """Return associations as a dict: id2gos""" return self._get_id2gos(self.associations, **kws) if kws else self.id2gos
[ "def", "get_id2gos", "(", "self", ",", "*", "*", "kws", ")", ":", "return", "self", ".", "_get_id2gos", "(", "self", ".", "associations", ",", "*", "*", "kws", ")", "if", "kws", "else", "self", ".", "id2gos" ]
53.333333
0.018519
def _compute_iso_line(self): """ compute LineVisual vertices, connects and color-index """ level_index = [] connects = [] verts = [] # calculate which level are within data range # this works for now and the existing examples, but should be tested # thoro...
[ "def", "_compute_iso_line", "(", "self", ")", ":", "level_index", "=", "[", "]", "connects", "=", "[", "]", "verts", "=", "[", "]", "# calculate which level are within data range", "# this works for now and the existing examples, but should be tested", "# thoroughly also with...
39.684211
0.001294
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: FaxContext for this FaxInstance :rtype: twilio.rest.fax.v1.fax.FaxContext """ if ...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "FaxContext", "(", "self", ".", "_version", ",", "sid", "=", "self", ".", "_solution", "[", "'sid'", "]", ",", ")", "return", "s...
40.363636
0.011013
def addVariantOld(self, literal='', sense=0, gloss='', examples=[]): '''Appends variant sth to do that it would be possible to add Variant object ''' var = Variant(literal=literal, ...
[ "def", "addVariantOld", "(", "self", ",", "literal", "=", "''", ",", "sense", "=", "0", ",", "gloss", "=", "''", ",", "examples", "=", "[", "]", ")", ":", "var", "=", "Variant", "(", "literal", "=", "literal", ",", "sense", "=", "sense", ",", "gl...
29.333333
0.013216
def do_create_subject(self, subject_context): """ By the time this method is invoked, all possible ``SubjectContext`` data (session, identifiers, et. al.) has been made accessible using all known heuristics. :returns: a Subject instance reflecting the data in the specified ...
[ "def", "do_create_subject", "(", "self", ",", "subject_context", ")", ":", "security_manager", "=", "subject_context", ".", "resolve_security_manager", "(", ")", "session", "=", "subject_context", ".", "resolve_session", "(", ")", "session_creation_enabled", "=", "sub...
49
0.002224
def read_file(self, registry): """Returns reading file """ with open(registry, "r") as file_txt: read_file = file_txt.read() file_txt.close() return read_file
[ "def", "read_file", "(", "self", ",", "registry", ")", ":", "with", "open", "(", "registry", ",", "\"r\"", ")", "as", "file_txt", ":", "read_file", "=", "file_txt", ".", "read", "(", ")", "file_txt", ".", "close", "(", ")", "return", "read_file" ]
30.285714
0.009174
def outer_id(self, value): """The outer_id property. Args: value (int). the property value. """ if value == self._defaults['outerId'] and 'outerId' in self._values: del self._values['outerId'] else: self._values['outerId'] = value
[ "def", "outer_id", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'outerId'", "]", "and", "'outerId'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'outerId'", "]", "else", ":", "s...
30.6
0.009524
def _get_type_name(type_): # type: (type) -> str """Return a displayable name for the type. Args: type_: A class object. Returns: A string value describing the class name that can be used in a natural language sentence. """ name = repr(type_) if name.startswith("<")...
[ "def", "_get_type_name", "(", "type_", ")", ":", "# type: (type) -> str", "name", "=", "repr", "(", "type_", ")", "if", "name", ".", "startswith", "(", "\"<\"", ")", ":", "name", "=", "getattr", "(", "type_", ",", "\"__qualname__\"", ",", "getattr", "(", ...
29
0.002227
def __AddAdditionalPropertyType(self, name, property_schema): """Add a new nested AdditionalProperty message.""" new_type_name = 'AdditionalProperty' property_schema = dict(property_schema) # We drop the description here on purpose, so the resulting # messages are less repetitive...
[ "def", "__AddAdditionalPropertyType", "(", "self", ",", "name", ",", "property_schema", ")", ":", "new_type_name", "=", "'AdditionalProperty'", "property_schema", "=", "dict", "(", "property_schema", ")", "# We drop the description here on purpose, so the resulting", "# messa...
39.954545
0.002222
def leave_diff_mode(self): """Leave diff mode.""" assert self.diff_mode self.diff_mode = False self.diff_context_model = None self.diff_from_source = False self.setColumnCount(2) self.refresh()
[ "def", "leave_diff_mode", "(", "self", ")", ":", "assert", "self", ".", "diff_mode", "self", ".", "diff_mode", "=", "False", "self", ".", "diff_context_model", "=", "None", "self", ".", "diff_from_source", "=", "False", "self", ".", "setColumnCount", "(", "2...
30.25
0.008032
def draw_text(img, pos, text, color, font_scale=0.4): """ Draw text on an image. Args: pos (tuple): x, y; the position of the text text (str): font_scale (float): color (tuple): a 3-tuple BGR color in [0, 255] """ img = img.astype(np.uint8) x0, y0 = int(pos[0]), ...
[ "def", "draw_text", "(", "img", ",", "pos", ",", "text", ",", "color", ",", "font_scale", "=", "0.4", ")", ":", "img", "=", "img", ".", "astype", "(", "np", ".", "uint8", ")", "x0", ",", "y0", "=", "int", "(", "pos", "[", "0", "]", ")", ",", ...
34.740741
0.002075
def users_info(self, user_id=None, username=None, **kwargs): """Gets a user’s information, limited to the caller’s permissions.""" if user_id: return self.__call_api_get('users.info', userId=user_id, kwargs=kwargs) elif username: return self.__call_api_get('users.info', u...
[ "def", "users_info", "(", "self", ",", "user_id", "=", "None", ",", "username", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "user_id", ":", "return", "self", ".", "__call_api_get", "(", "'users.info'", ",", "userId", "=", "user_id", ",", "kwa...
54.5
0.009029
def print_timers(self): ''' PRINT EXECUTION TIMES FOR THE LIST OF PROGRAMS ''' self.timer += time() total_time = self.timer tmp = '* %s *' debug.log( '', '* '*29, tmp%(' '*51), tmp%('%s %s %s'%('Program Name'.ljust(20), 'Status'.ljust(7), 'Execute Ti...
[ "def", "print_timers", "(", "self", ")", ":", "self", ".", "timer", "+=", "time", "(", ")", "total_time", "=", "self", ".", "timer", "tmp", "=", "'* %s *'", "debug", ".", "log", "(", "''", ",", "'* '", "*", "29", ",", "tmp", "%", "(", "' '", "*...
32.785714
0.025397
def dump_with_fn(dump_fn, data, stream, **options): """ Dump 'data' to a string if 'stream' is None, or dump 'data' to a file or file-like object 'stream'. :param dump_fn: Callable to dump data :param data: Data to dump :param stream: File or file like object or None :param options: option...
[ "def", "dump_with_fn", "(", "dump_fn", ",", "data", ",", "stream", ",", "*", "*", "options", ")", ":", "if", "stream", "is", "None", ":", "return", "dump_fn", "(", "data", ",", "*", "*", "options", ")", "return", "dump_fn", "(", "data", ",", "stream"...
31.5625
0.001923
def execute(self, input_data): ''' Execute the ViewMemory worker ''' # Aggregate the output from all the memory workers into concise summary info output = {'meta': input_data['mem_meta']['tables']['info']} output['connscan'] = list(set([item['Remote Address'] for item in input_data['mem...
[ "def", "execute", "(", "self", ",", "input_data", ")", ":", "# Aggregate the output from all the memory workers into concise summary info", "output", "=", "{", "'meta'", ":", "input_data", "[", "'mem_meta'", "]", "[", "'tables'", "]", "[", "'info'", "]", "}", "outpu...
72.3
0.009563
def clear_old_remotes(self): ''' Remove cache directories for remotes no longer configured ''' try: cachedir_ls = os.listdir(self.cache_root) except OSError: cachedir_ls = [] # Remove actively-used remotes from list for repo in self.remotes...
[ "def", "clear_old_remotes", "(", "self", ")", ":", "try", ":", "cachedir_ls", "=", "os", ".", "listdir", "(", "self", ".", "cache_root", ")", "except", "OSError", ":", "cachedir_ls", "=", "[", "]", "# Remove actively-used remotes from list", "for", "repo", "in...
33.05
0.00147
def _get_queue(config): ''' Check the context for the notifier and construct it if not present ''' if 'watchdog.observer' not in __context__: queue = collections.deque() observer = Observer() for path in config.get('directories', {}): path_params = config.get('direct...
[ "def", "_get_queue", "(", "config", ")", ":", "if", "'watchdog.observer'", "not", "in", "__context__", ":", "queue", "=", "collections", ".", "deque", "(", ")", "observer", "=", "Observer", "(", ")", "for", "path", "in", "config", ".", "get", "(", "'dire...
32.2
0.001508
def close(self): """Close the stream.""" self.flush() self.stream.close() logging.StreamHandler.close(self)
[ "def", "close", "(", "self", ")", ":", "self", ".", "flush", "(", ")", "self", ".", "stream", ".", "close", "(", ")", "logging", ".", "StreamHandler", ".", "close", "(", "self", ")" ]
27
0.014388
def get_example(): """Make an example for training and testing. Outputs a tuple (label, features) where label is +1 if capital letters are the majority, and -1 otherwise; and features is a list of letters. """ features = random.sample(string.ascii_letters, NUM_SAMPLES) num_capitalized = l...
[ "def", "get_example", "(", ")", ":", "features", "=", "random", ".", "sample", "(", "string", ".", "ascii_letters", ",", "NUM_SAMPLES", ")", "num_capitalized", "=", "len", "(", "[", "letter", "for", "letter", "in", "features", "if", "letter", "in", "string...
46
0.011475
def _add_team_features(df): """Adds extra convenience features based on teams with and without possession, with the precondition that the there are 'team' and 'opp' specified in row. :df: A DataFrame representing a game's play-by-play data after _clean_features has been called and 'team' and 'o...
[ "def", "_add_team_features", "(", "df", ")", ":", "assert", "df", ".", "team", ".", "notnull", "(", ")", ".", "all", "(", ")", "homeOnOff", "=", "df", "[", "'team'", "]", "==", "df", "[", "'home'", "]", "# create column for distToGoal", "df", "[", "'di...
45.794118
0.000629
def log_level(level): """ Attempt to convert the given argument into a log level. Log levels are represented as integers, where higher values are more severe. If the given level is already an integer, it is simply returned. If the given level is a string that can be converted into an integer, i...
[ "def", "log_level", "(", "level", ")", ":", "from", "six", "import", "string_types", "if", "isinstance", "(", "level", ",", "int", ")", ":", "return", "level", "if", "isinstance", "(", "level", ",", "string_types", ")", ":", "try", ":", "return", "int", ...
37.125
0.010941
def put(self, prompt): """ Puts prompt in each downstream inbox (an actual queue). """ for queue in self.downstream_inboxes.values(): queue.put(prompt)
[ "def", "put", "(", "self", ",", "prompt", ")", ":", "for", "queue", "in", "self", ".", "downstream_inboxes", ".", "values", "(", ")", ":", "queue", ".", "put", "(", "prompt", ")" ]
31.666667
0.010256
def convert(data): """ Convert from unicode to native ascii """ try: st = basestring except NameError: st = str if isinstance(data, st): return str(data) elif isinstance(data, Mapping): return dict(map(convert, data.iteritems())) elif isinstance(data, Iter...
[ "def", "convert", "(", "data", ")", ":", "try", ":", "st", "=", "basestring", "except", "NameError", ":", "st", "=", "str", "if", "isinstance", "(", "data", ",", "st", ")", ":", "return", "str", "(", "data", ")", "elif", "isinstance", "(", "data", ...
24.1875
0.002488
def setParameter(self, name, index, value): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.setParameter`. """ if name == "learningMode": self.learningMode = bool(int(value)) self._epoch = 0 elif name == "inferenceMode": self._epoch = 0 if int(value) and not sel...
[ "def", "setParameter", "(", "self", ",", "name", ",", "index", ",", "value", ")", ":", "if", "name", "==", "\"learningMode\"", ":", "self", ".", "learningMode", "=", "bool", "(", "int", "(", "value", ")", ")", "self", ".", "_epoch", "=", "0", "elif",...
35.903226
0.014873