text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def calcAcceptanceRatio(self, V, W): """ Given a order vector V and a proposed order vector W, calculate the acceptance ratio for changing to W when using MCMC. ivar: dict<int,<dict,<int,int>>> wmg: A two-dimensional dictionary that associates integer representations of eac...
[ "def", "calcAcceptanceRatio", "(", "self", ",", "V", ",", "W", ")", ":", "acceptanceRatio", "=", "1.0", "for", "comb", "in", "itertools", ".", "combinations", "(", "V", ",", "2", ")", ":", "#Check if comb[0] is ranked before comb[1] in V and W", "vIOverJ", "=", ...
50.482759
0.008713
def _apply_vqsr(in_file, ref_file, recal_file, tranch_file, sensitivity_cutoff, filter_type, data): """Apply VQSR based on the specified tranche, returning a filtered VCF file. """ base, ext = utils.splitext_plus(in_file) out_file = "{base}-{filter}filter{ext}".format(base=base, ext=ext,...
[ "def", "_apply_vqsr", "(", "in_file", ",", "ref_file", ",", "recal_file", ",", "tranch_file", ",", "sensitivity_cutoff", ",", "filter_type", ",", "data", ")", ":", "base", ",", "ext", "=", "utils", ".", "splitext_plus", "(", "in_file", ")", "out_file", "=", ...
48.771429
0.002298
def _remove(self, handler, send_event=True): """ Remove handler instance and detach any methods bound to it from uninhibited. :param object handler: handler instance :return object: The handler you added is given back so this can be used as a decorator. """ for event in ...
[ "def", "_remove", "(", "self", ",", "handler", ",", "send_event", "=", "True", ")", ":", "for", "event", "in", "self", ":", "event", ".", "remove_handlers_bound_to_instance", "(", "handler", ")", "self", ".", "handlers", ".", "remove", "(", "handler", ")",...
40
0.008147
def stop_ckan(self): """ Stop and remove the web container """ remove_container(self._get_container_name('web'), force=True) remove_container(self._get_container_name('datapusher'), force=True)
[ "def", "stop_ckan", "(", "self", ")", ":", "remove_container", "(", "self", ".", "_get_container_name", "(", "'web'", ")", ",", "force", "=", "True", ")", "remove_container", "(", "self", ".", "_get_container_name", "(", "'datapusher'", ")", ",", "force", "=...
38
0.008584
def normalize_excludes(rootpath, excludes): """ Normalize the excluded directory list: * must be either an absolute path or start with rootpath, * otherwise it is joined with rootpath * with trailing slash """ sep = os.path.sep f_excludes = [] for exclude in excludes: if not ...
[ "def", "normalize_excludes", "(", "rootpath", ",", "excludes", ")", ":", "sep", "=", "os", ".", "path", ".", "sep", "f_excludes", "=", "[", "]", "for", "exclude", "in", "excludes", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "exclude", ")...
33.8125
0.001799
def aggregate(all_stats): """Combine stats for multiple optimizers to obtain one mean and sd. Useful for combining stats for the same optimizer class and multiple problems. Args: all_stats: dict; output from compare. """ aggregate_stats = {'means': [], 'standard_deviations': []} for op...
[ "def", "aggregate", "(", "all_stats", ")", ":", "aggregate_stats", "=", "{", "'means'", ":", "[", "]", ",", "'standard_deviations'", ":", "[", "]", "}", "for", "optimizer_key", "in", "all_stats", ":", "# runs is the mean, for add_mean_sd function", "mean_stats", "...
36.208333
0.002242
def request_quotes(tickers_list, selected_columns=['*']): """Request Yahoo Finance recent quotes. Returns quotes information from YQL. The columns to be requested are listed at selected_columns. Check `here <http://goo.gl/8AROUD>`_ for more information on YQL. >>> request_quotes(['AAPL'], ['Name',...
[ "def", "request_quotes", "(", "tickers_list", ",", "selected_columns", "=", "[", "'*'", "]", ")", ":", "__validate_list", "(", "tickers_list", ")", "__validate_list", "(", "selected_columns", ")", "query", "=", "'select {cols} from yahoo.finance.quotes where symbol in ({v...
33.75
0.00072
def run(self, data_service, project_file): """ Attach a remote file to activity with used relationship. :param data_service: DataServiceApi: service used to attach relationship :param project_file: ProjectFile: contains details about a file we will attach """ remote_path ...
[ "def", "run", "(", "self", ",", "data_service", ",", "project_file", ")", ":", "remote_path", "=", "project_file", ".", "path", "file_dict", "=", "data_service", ".", "get_file", "(", "project_file", ".", "id", ")", ".", "json", "(", ")", "file_version_id", ...
57.818182
0.009288
def saveFileEnc(self, filename, encoding): """Dump an XML document, converting it to the given encoding """ ret = libxml2mod.xmlSaveFileEnc(filename, self._o, encoding) return ret
[ "def", "saveFileEnc", "(", "self", ",", "filename", ",", "encoding", ")", ":", "ret", "=", "libxml2mod", ".", "xmlSaveFileEnc", "(", "filename", ",", "self", ".", "_o", ",", "encoding", ")", "return", "ret" ]
50
0.009852
def convert_separable_convolution(builder, layer, input_names, output_names, keras_layer): """ Convert separable convolution layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object....
[ "def", "convert_separable_convolution", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "_check_data_format", "(", "keras_layer", ")", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "inp...
32.556962
0.039623
def create(parser_func: Union[ParsingMethodForStream, ParsingMethodForFile], caught: Exception): """ Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests https://github.com/nose-devs/nose/issues/725 :param parser_func: :par...
[ "def", "create", "(", "parser_func", ":", "Union", "[", "ParsingMethodForStream", ",", "ParsingMethodForFile", "]", ",", "caught", ":", "Exception", ")", ":", "msg", "=", "'Caught TypeError while calling parsing function \\''", "+", "str", "(", "parser_func", ".", "...
60.285714
0.009335
def listdir(self, location, authority_name=None): ''' List archive path components at a given location .. Note :: When using listdir on versioned archives, listdir will provide the version numbers when a full archive path is supplied as the location argument...
[ "def", "listdir", "(", "self", ",", "location", ",", "authority_name", "=", "None", ")", ":", "authority_name", ",", "location", "=", "self", ".", "_normalize_archive_name", "(", "location", ",", "authority_name", "=", "authority_name", ")", "if", "authority_nam...
28.948276
0.001152
def __copyfile2(source, destination): """Copy data and all stat info ("cp -p source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the o...
[ "def", "__copyfile2", "(", "source", ",", "destination", ")", ":", "logger", ".", "info", "(", "\"copyfile2: %s -> %s\"", "%", "(", "source", ",", "destination", ")", ")", "try", ":", "__create_destdir", "(", "destination", ")", "shutil", ".", "copy2", "(", ...
30.681818
0.001437
def smoothed_moving_average(data, period): """ Smoothed Moving Average. Formula: smma = avg(data(n)) - avg(data(n)/n) + data(t)/n """ catch_errors.check_for_period_error(data, period) series = pd.Series(data) return series.ewm(alpha = 1.0/period).mean().values.flatten()
[ "def", "smoothed_moving_average", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "series", "=", "pd", ".", "Series", "(", "data", ")", "return", "series", ".", "ewm", "(", "alpha", "=",...
29.4
0.009901
def make_multinuc(relname, nucleii): """Creates a rst.sty Latex string representation of a multi-nuclear RST relation.""" nuc_strings = [] for nucleus in nucleii: nuc_strings.append( MULTINUC_ELEMENT_TEMPLATE.substitute(nucleus=nucleus) ) nucleii_string = "\n\t" + "\n\t".join(nuc_strings) re...
[ "def", "make_multinuc", "(", "relname", ",", "nucleii", ")", ":", "nuc_strings", "=", "[", "]", "for", "nucleus", "in", "nucleii", ":", "nuc_strings", ".", "append", "(", "MULTINUC_ELEMENT_TEMPLATE", ".", "substitute", "(", "nucleus", "=", "nucleus", ")", ")...
56.857143
0.014851
def get_hostname(config_url=None): """ Returns the IOpipe collector's hostname. If the `AWS_REGION` environment variable is not set or unsupported then `us-east-1` will be used by default. In this case, `us-east-1` is `metrics-api.iopipe.com`. :param config_url: A optional config URL to use. :...
[ "def", "get_hostname", "(", "config_url", "=", "None", ")", ":", "region_string", "=", "\"\"", "if", "config_url", ":", "return", "urlparse", "(", "config_url", ")", ".", "hostname", "aws_region", "=", "os", ".", "getenv", "(", "\"AWS_REGION\"", ")", "if", ...
37.764706
0.00152
def list_cmd(cmd, src_path): ''' Executes a `sketchtool list` command and parse the output :cmd: A sketchtool list command :type <list> :src_path: File to export. :type <str> :returns: A list of pages. Artboards & slices are included in the page hierarchy ''' cmd.extend([src_path]) logger.debug(u'Executi...
[ "def", "list_cmd", "(", "cmd", ",", "src_path", ")", ":", "cmd", ".", "extend", "(", "[", "src_path", "]", ")", "logger", ".", "debug", "(", "u'Executing cmd: %s'", "%", "cmd", ")", "result", "=", "execute", "(", "cmd", ")", "if", "not", "result", ":...
30.235294
0.020755
def font_parse_string(font): """ Convert from font string/tyuple into a Qt style sheet string :param font: "Arial 10 Bold" or ('Arial', 10, 'Bold) :return: style string that can be combined with other style strings """ if font is None: return '' if type(font) is str: _font ...
[ "def", "font_parse_string", "(", "font", ")", ":", "if", "font", "is", "None", ":", "return", "''", "if", "type", "(", "font", ")", "is", "str", ":", "_font", "=", "font", ".", "split", "(", "' '", ")", "else", ":", "_font", "=", "font", "family", ...
24.478261
0.001709
def complex_dtype(dtype, default=None): """Return complex counterpart of ``dtype`` if existing, else ``default``. Parameters ---------- dtype : Real or complex floating point data type. It can be given in any way the `numpy.dtype` constructor understands. default : Object to...
[ "def", "complex_dtype", "(", "dtype", ",", "default", "=", "None", ")", ":", "dtype", ",", "dtype_in", "=", "np", ".", "dtype", "(", "dtype", ")", ",", "dtype", "if", "is_complex_floating_dtype", "(", "dtype", ")", ":", "return", "dtype", "try", ":", "...
27.053571
0.000637
def watch_transient_file(self, filename, mask, proc_class): """ Watch a transient file, which will be created and deleted frequently over time (e.g. pid file). @attention: Currently under the call to this function it is not possible to correctly watch the events triggered into t...
[ "def", "watch_transient_file", "(", "self", ",", "filename", ",", "mask", ",", "proc_class", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "if", "dirname", "==", "''", ":", "return", "{", "}", "# Maintains coherence wit...
47.15
0.001039
def copy(self): """Return a clone of this retry manager""" return Retry(max_tries=self.max_tries, delay=self.delay, backoff=self.backoff, max_jitter=self.max_jitter / 100.0, max_delay=self.max_delay, sleep_func=self.sleep_func, deadline=self.deadline, retry_exce...
[ "def", "copy", "(", "self", ")", ":", "return", "Retry", "(", "max_tries", "=", "self", ".", "max_tries", ",", "delay", "=", "self", ".", "delay", ",", "backoff", "=", "self", ".", "backoff", ",", "max_jitter", "=", "self", ".", "max_jitter", "/", "1...
69
0.014327
def start_response(self, status, headers, exc_info = None): """WSGI callable to begin the HTTP response.""" if self.started_response: if not exc_info: raise AssertionError("WSGI start_response called a second " "time with no exc_info.") else: try: ...
[ "def", "start_response", "(", "self", ",", "status", ",", "headers", ",", "exc_info", "=", "None", ")", ":", "if", "self", ".", "started_response", ":", "if", "not", "exc_info", ":", "raise", "AssertionError", "(", "\"WSGI start_response called a second \"", "\"...
33.0625
0.014706
def pub_ret(self, load): ''' Request the return data from a specific jid, only allowed if the requesting minion also initialted the execution. :param dict load: The minion payload :rtype: dict :return: Return data corresponding to a given JID ''' load = ...
[ "def", "pub_ret", "(", "self", ",", "load", ")", ":", "load", "=", "self", ".", "__verify_load", "(", "load", ",", "(", "'jid'", ",", "'id'", ",", "'tok'", ")", ")", "if", "load", "is", "False", ":", "return", "{", "}", "# Check that this minion can ac...
36.48
0.002137
def process_value(self, value): """Process publication value """ # UID -> SuperModel if api.is_uid(value): return self.to_super_model(value) # Content -> SuperModel elif api.is_object(value): return self.to_super_model(value) # String -> Un...
[ "def", "process_value", "(", "self", ",", "value", ")", ":", "# UID -> SuperModel", "if", "api", ".", "is_uid", "(", "value", ")", ":", "return", "self", ".", "to_super_model", "(", "value", ")", "# Content -> SuperModel", "elif", "api", ".", "is_object", "(...
36.923077
0.00203
def csep_close(ra, rb): """Return the closest separation vector between each point in one set, and every point in a second set. Parameters ---------- ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions. Two sets of points. `ra` is the set of points from which the closest ...
[ "def", "csep_close", "(", "ra", ",", "rb", ")", ":", "seps", "=", "csep", "(", "ra", ",", "rb", ")", "seps_sq", "=", "np", ".", "sum", "(", "np", ".", "square", "(", "seps", ")", ",", "axis", "=", "-", "1", ")", "i_close", "=", "np", ".", "...
31.269231
0.001193
def to_python(cls, value, **kwargs): """String deserialisation just return the value as a string""" if not value: return '' try: return str(value) except: pass try: return value.encode('utf-8') except: pass ...
[ "def", "to_python", "(", "cls", ",", "value", ",", "*", "*", "kwargs", ")", ":", "if", "not", "value", ":", "return", "''", "try", ":", "return", "str", "(", "value", ")", "except", ":", "pass", "try", ":", "return", "value", ".", "encode", "(", ...
29.615385
0.012594
def sort(TableName,DestinationTableName=None,ParameterNames=None,Accending=True,Output=False,File=None): """ INPUT PARAMETERS: TableName: name of source table (required) DestinationTableName: name of resulting table (optional) ParameterNames: list...
[ "def", "sort", "(", "TableName", ",", "DestinationTableName", "=", "None", ",", "ParameterNames", "=", "None", ",", "Accending", "=", "True", ",", "Output", "=", "False", ",", "File", "=", "None", ")", ":", "number_of_rows", "=", "LOCAL_TABLE_CACHE", "[", ...
47.555556
0.016027
def visitObjectMacro(self, ctx: jsgParser.ObjectExprContext): """ objectMacro : ID EQUALS membersDef SEMI """ name = as_token(ctx) self._context.grammarelts[name] = JSGObjectExpr(self._context, ctx.membersDef(), name)
[ "def", "visitObjectMacro", "(", "self", ",", "ctx", ":", "jsgParser", ".", "ObjectExprContext", ")", ":", "name", "=", "as_token", "(", "ctx", ")", "self", ".", "_context", ".", "grammarelts", "[", "name", "]", "=", "JSGObjectExpr", "(", "self", ".", "_c...
59.5
0.012448
def _get_custom_models(models): """Returns CustomModels for models with a custom `__implementation__`""" if models is None: models = Model.model_class_reverse_map.values() custom_models = OrderedDict() for cls in models: impl = getattr(cls, "__implementation__", None) if impl i...
[ "def", "_get_custom_models", "(", "models", ")", ":", "if", "models", "is", "None", ":", "models", "=", "Model", ".", "model_class_reverse_map", ".", "values", "(", ")", "custom_models", "=", "OrderedDict", "(", ")", "for", "cls", "in", "models", ":", "imp...
29.75
0.002037
def computeMaxPool(input_width): """ Compute CNN max pool width. see 'cnn_sdr.py' """ wout = math.floor((input_width + 2 * PADDING - KERNEL_SIZE) / STRIDE + 1) return int(math.floor(wout / 2.0))
[ "def", "computeMaxPool", "(", "input_width", ")", ":", "wout", "=", "math", ".", "floor", "(", "(", "input_width", "+", "2", "*", "PADDING", "-", "KERNEL_SIZE", ")", "/", "STRIDE", "+", "1", ")", "return", "int", "(", "math", ".", "floor", "(", "wout...
33.166667
0.019608
def searchFilesIndex(self, nameData, fileData, fileIndex, searchString, category="", math=False, game=False, extension=""): """Search the files index using the namedata and returns the filedata""" try: fileFile = open(fileIndex, 'rt') except IOError: self.repo.printd("Error: Unable to read index file " + se...
[ "def", "searchFilesIndex", "(", "self", ",", "nameData", ",", "fileData", ",", "fileIndex", ",", "searchString", ",", "category", "=", "\"\"", ",", "math", "=", "False", ",", "game", "=", "False", ",", "extension", "=", "\"\"", ")", ":", "try", ":", "f...
28.176471
0.042367
def prepare_allele_name(self, allele_name): """ netMHCIIpan has some unique requirements for allele formats, expecting the following forms: - DRB1_0101 (for non-alpha/beta pairs) - HLA-DQA10501-DQB10636 (for alpha and beta pairs) Other than human class II alleles, the ...
[ "def", "prepare_allele_name", "(", "self", ",", "allele_name", ")", ":", "parsed_alleles", "=", "parse_classi_or_classii_allele_name", "(", "allele_name", ")", "if", "len", "(", "parsed_alleles", ")", "==", "1", ":", "allele", "=", "parsed_alleles", "[", "0", "]...
36.545455
0.001616
def writepy(self, pathname, basename = ""): """Add all files from "pathname" to the ZIP archive. If pathname is a package directory, search the directory and all package subdirectories recursively for all *.py and enter the modules into the archive. If pathname is a plain direc...
[ "def", "writepy", "(", "self", ",", "pathname", ",", "basename", "=", "\"\"", ")", ":", "dir", ",", "name", "=", "os", ".", "path", ".", "split", "(", "pathname", ")", "if", "os", ".", "path", ".", "isdir", "(", "pathname", ")", ":", "initname", ...
48.90625
0.002192
def add_filter(self, files_filter, filter_type=DefaultFilterType): """ Add a files filter to this iterator. For a file to be processed, it must match ALL filters, eg they are added with ADD, not OR. :param files_filter: filter to apply, must be an object inheriting from filters.FilterAP...
[ "def", "add_filter", "(", "self", ",", "files_filter", ",", "filter_type", "=", "DefaultFilterType", ")", ":", "self", ".", "__filters", ".", "append", "(", "(", "files_filter", ",", "filter_type", ")", ")", "return", "self" ]
47.7
0.00823
def message_to_event(direction, message): """Prepare an ``RFC1459Message`` for event dispatch. We do this because we have to handle special things as well, such as CTCP and deconstructing verbs properly. """ server = message.server # change numerics into nice names if message.verb in numer...
[ "def", "message_to_event", "(", "direction", ",", "message", ")", ":", "server", "=", "message", ".", "server", "# change numerics into nice names", "if", "message", ".", "verb", "in", "numerics", ":", "message", ".", "verb", "=", "numerics", "[", "message", "...
40.308458
0.001205
def parents( self, node ): """Retrieve/calculate the set of parents for the given node""" if 'index' in node: index = node['index']() parents = list(meliaeloader.children( node, index, 'parents' )) return parents return []
[ "def", "parents", "(", "self", ",", "node", ")", ":", "if", "'index'", "in", "node", ":", "index", "=", "node", "[", "'index'", "]", "(", ")", "parents", "=", "list", "(", "meliaeloader", ".", "children", "(", "node", ",", "index", ",", "'parents'", ...
39.571429
0.024735
def check_if_exists(self, use_user_site): # type: (bool) -> bool """Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.conflicts_with appropriately. """ if self.req is None: return False ...
[ "def", "check_if_exists", "(", "self", ",", "use_user_site", ")", ":", "# type: (bool) -> bool", "if", "self", ".", "req", "is", "None", ":", "return", "False", "try", ":", "# get_distribution() will resolve the entire list of requirements", "# anyway, and we've already det...
44.95122
0.001593
def isolines(obj, prop, val, outliers=None, data_range=None, clipped=np.inf, weights=None, weight_min=0, weight_transform=Ellipsis, mask=None, valid_range=None, transform=None, smooth=False, yield_addresses=False): ''' isolines(mesh, prop, val) ...
[ "def", "isolines", "(", "obj", ",", "prop", ",", "val", ",", "outliers", "=", "None", ",", "data_range", "=", "None", ",", "clipped", "=", "np", ".", "inf", ",", "weights", "=", "None", ",", "weight_min", "=", "0", ",", "weight_transform", "=", "Elli...
49.757353
0.015068
def simxGetStringParameter(clientID, paramIdentifier, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' paramValue = ct.POINTER(ct.c_char)() ret = c_GetStringParameter(clientID, paramIdentifier, ct.byref(paramValue), operationMode) ...
[ "def", "simxGetStringParameter", "(", "clientID", ",", "paramIdentifier", ",", "operationMode", ")", ":", "paramValue", "=", "ct", ".", "POINTER", "(", "ct", ".", "c_char", ")", "(", ")", "ret", "=", "c_GetStringParameter", "(", "clientID", ",", "paramIdentifi...
31.761905
0.0131
def execute(self): """ Called to execute the task. This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in prepare(), executed() or failed(). """ T = self.tm.trace if T: T.write(self.t...
[ "def", "execute", "(", "self", ")", ":", "T", "=", "self", ".", "tm", ".", "trace", "if", "T", ":", "T", ".", "write", "(", "self", ".", "trace_message", "(", "u'Task.execute()'", ",", "self", ".", "node", ")", ")", "try", ":", "cached_targets", "=...
37.318182
0.00178
def plan_validation(user, plan=None, on_activation=False): """ Validates validator that represents quotas in a given system :param user: :param plan: :return: """ if plan is None: # if plan is not given, the default is to use current plan of the user plan = user.userplan.plan...
[ "def", "plan_validation", "(", "user", ",", "plan", "=", "None", ",", "on_activation", "=", "False", ")", ":", "if", "plan", "is", "None", ":", "# if plan is not given, the default is to use current plan of the user", "plan", "=", "user", ".", "userplan", ".", "pl...
31.25
0.00097
def validated_type(base_type, name=None, validate=None): """Convenient way to create a new type by adding validation to existing type. Example: :: Ipv4Address = validated_type( String, 'Ipv4Address', # regexp simplified for demo purposes Regexp('^\d+\.\d+\.\d+\.\d+$...
[ "def", "validated_type", "(", "base_type", ",", "name", "=", "None", ",", "validate", "=", "None", ")", ":", "if", "validate", "is", "None", ":", "validate", "=", "[", "]", "if", "not", "is_sequence", "(", "validate", ")", ":", "validate", "=", "[", ...
35.065217
0.010253
def reset(self): """ Resets the state. """ # Session IDs can be random on every connection self.id = struct.unpack('q', os.urandom(8))[0] self._sequence = 0 self._last_msg_id = 0
[ "def", "reset", "(", "self", ")", ":", "# Session IDs can be random on every connection", "self", ".", "id", "=", "struct", ".", "unpack", "(", "'q'", ",", "os", ".", "urandom", "(", "8", ")", ")", "[", "0", "]", "self", ".", "_sequence", "=", "0", "se...
28.375
0.008547
def addAlias(self, namespace_uri, desired_alias, implicit=False): """Add an alias from this namespace URI to the desired alias """ if isinstance(namespace_uri, bytes): namespace_uri = str(namespace_uri, encoding="utf-8") # Check that desired_alias is not an openid protocol fi...
[ "def", "addAlias", "(", "self", ",", "namespace_uri", ",", "desired_alias", ",", "implicit", "=", "False", ")", ":", "if", "isinstance", "(", "namespace_uri", ",", "bytes", ")", ":", "namespace_uri", "=", "str", "(", "namespace_uri", ",", "encoding", "=", ...
45.044444
0.000966
def connect(self): """Connect to wdb server""" log.info('Connecting socket on %s:%d' % (self.server, self.port)) tries = 0 while not self._socket and tries < 10: try: time.sleep(.2 * tries) self._socket = Socket((self.server, self.port)) ...
[ "def", "connect", "(", "self", ")", ":", "log", ".", "info", "(", "'Connecting socket on %s:%d'", "%", "(", "self", ".", "server", ",", "self", ".", "port", ")", ")", "tries", "=", "0", "while", "not", "self", ".", "_socket", "and", "tries", "<", "10...
35.043478
0.002415
def set_auth_request(self, interface_id, address=None): """ Set the authentication request field for the specified engine. """ self.interface.set_auth_request(interface_id, address) self._engine.update()
[ "def", "set_auth_request", "(", "self", ",", "interface_id", ",", "address", "=", "None", ")", ":", "self", ".", "interface", ".", "set_auth_request", "(", "interface_id", ",", "address", ")", "self", ".", "_engine", ".", "update", "(", ")" ]
31.625
0.011538
def check_path(): """Check sys.path: is Spyder properly installed?""" dirname = osp.abspath(osp.join(osp.dirname(__file__), osp.pardir)) if dirname not in sys.path: show_warning("Spyder must be installed properly " "(e.g. from source: 'python setup.py install'),\n" ...
[ "def", "check_path", "(", ")", ":", "dirname", "=", "osp", ".", "abspath", "(", "osp", ".", "join", "(", "osp", ".", "dirname", "(", "__file__", ")", ",", "osp", ".", "pardir", ")", ")", "if", "dirname", "not", "in", "sys", ".", "path", ":", "sho...
53.25
0.002309
def send_chaos_queries(self): """Send chaos queries to identify the DNS server and its manufacturer Note: we send 2 queries for BIND stuff per RFC 4892 and 1 query per RFC 6304 Note: we are not waiting on a second response because we shouldn't be getting injected packets here ...
[ "def", "send_chaos_queries", "(", "self", ")", ":", "names", "=", "[", "\"HOSTNAME.BIND\"", ",", "\"VERSION.BIND\"", ",", "\"ID.SERVER\"", "]", "self", ".", "results", "=", "{", "'exp-name'", ":", "\"chaos-queries\"", "}", "for", "name", "in", "names", ":", ...
46.413793
0.001456
def get_list_of_sql_string_literals_from_quoted_csv(x: str) -> List[str]: """ Used to extract SQL column type parameters. For example, MySQL has column types that look like ``ENUM('a', 'b', 'c', 'd')``. This function takes the ``"'a', 'b', 'c', 'd'"`` and converts it to ``['a', 'b', 'c', 'd']``. """...
[ "def", "get_list_of_sql_string_literals_from_quoted_csv", "(", "x", ":", "str", ")", "->", "List", "[", "str", "]", ":", "f", "=", "io", ".", "StringIO", "(", "x", ")", "reader", "=", "csv", ".", "reader", "(", "f", ",", "delimiter", "=", "','", ",", ...
49
0.001821
def _collect_state_names(self, variable): "Return a list of states that the variable takes in the data" states = sorted(list(self.data.ix[:, variable].dropna().unique())) return states
[ "def", "_collect_state_names", "(", "self", ",", "variable", ")", ":", "states", "=", "sorted", "(", "list", "(", "self", ".", "data", ".", "ix", "[", ":", ",", "variable", "]", ".", "dropna", "(", ")", ".", "unique", "(", ")", ")", ")", "return", ...
51.25
0.009615
def generate(env): """Add Builders and construction variables for zip to an Environment.""" try: bld = env['BUILDERS']['Zip'] except KeyError: bld = ZipBuilder env['BUILDERS']['Zip'] = bld env['ZIP'] = 'zip' env['ZIPFLAGS'] = SCons.Util.CLVar('') env['ZIPCOM'] ...
[ "def", "generate", "(", "env", ")", ":", "try", ":", "bld", "=", "env", "[", "'BUILDERS'", "]", "[", "'Zip'", "]", "except", "KeyError", ":", "bld", "=", "ZipBuilder", "env", "[", "'BUILDERS'", "]", "[", "'Zip'", "]", "=", "bld", "env", "[", "'ZIP'...
31.5
0.015419
def chshell(name, shell): ''' Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) ...
[ "def", "chshell", "(", "name", ",", "shell", ")", ":", "pre_info", "=", "info", "(", "name", ")", "if", "not", "pre_info", ":", "raise", "CommandExecutionError", "(", "'User \\'{0}\\' does not exist'", ".", "format", "(", "name", ")", ")", "if", "shell", "...
24.45
0.001969
def parse_conf_args(argv): """Parse command line options into {section: (option, key)} which can be used for overlaying on top of config :param argv: list of argumets to be parsed :return: Dictionary in the following format: {section: (option, key)}""" args = {} for rarg in argv: if re...
[ "def", "parse_conf_args", "(", "argv", ")", ":", "args", "=", "{", "}", "for", "rarg", "in", "argv", ":", "if", "re", ".", "match", "(", "\"^--.*\"", ",", "rarg", ")", ":", "arg", "=", "rarg", ".", "replace", "(", "'--'", ",", "''", ",", "1", "...
31.966667
0.002024
def run_create_admin(*args): ''' creating the default administrator. ''' post_data = { 'user_name': 'giser', 'user_email': 'giser@osgeo.cn', 'user_pass': '131322', 'role': '3300', } if MUser.get_by_name(post_data['user_name']): print('User {user_name} alre...
[ "def", "run_create_admin", "(", "*", "args", ")", ":", "post_data", "=", "{", "'user_name'", ":", "'giser'", ",", "'user_email'", ":", "'giser@osgeo.cn'", ",", "'user_pass'", ":", "'131322'", ",", "'role'", ":", "'3300'", ",", "}", "if", "MUser", ".", "get...
28.071429
0.002463
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ print("Running migrations online") project_path = get_project_path() project_config = get_project_config(project_path) backen...
[ "def", "run_migrations_online", "(", ")", ":", "print", "(", "\"Running migrations online\"", ")", "project_path", "=", "get_project_path", "(", ")", "project_config", "=", "get_project_config", "(", "project_path", ")", "backend", "=", "get_backend", "(", "project_pa...
26.142857
0.008787
def _pipeline_cell(args, cell_body): """Implements the pipeline subcommand in the %%bq magic. Args: args: the arguments following '%%bq pipeline'. cell_body: Cell contents. """ name = args.get('name') if name is None: raise Exception('Pipeline name was not specified.') impor...
[ "def", "_pipeline_cell", "(", "args", ",", "cell_body", ")", ":", "name", "=", "args", ".", "get", "(", "'name'", ")", "if", "name", "is", "None", ":", "raise", "Exception", "(", "'Pipeline name was not specified.'", ")", "import", "google", ".", "datalab", ...
39.9
0.008806
def is_json(mimetype): """Indicates if this mimetype is JSON or not. By default a request is considered to include JSON data if the mimetype is ``application/json`` or ``application/*+json``. """ if not mimetype: return False if ";" in mimetype: # Allow Content-Type header to be passed...
[ "def", "is_json", "(", "mimetype", ")", ":", "if", "not", "mimetype", ":", "return", "False", "if", "\";\"", "in", "mimetype", ":", "# Allow Content-Type header to be passed", "mimetype", "=", "get_mimetype", "(", "mimetype", ")", "if", "mimetype", "==", "\"appl...
37.142857
0.001876
def getAugYbus(self, U0, gbus): """ Based on AugYbus.m from MatDyn by Stijn Cole, developed at Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/ electa/teaching/matdyn/} for more information. @rtype: csr_matrix @return: The augmented bus admittance matrix. ...
[ "def", "getAugYbus", "(", "self", ",", "U0", ",", "gbus", ")", ":", "j", "=", "0", "+", "1j", "buses", "=", "self", ".", "case", ".", "connected_buses", "nb", "=", "len", "(", "buses", ")", "Ybus", ",", "_", ",", "_", "=", "self", ".", "case", ...
30.774194
0.002033
def locked(self): """Context generator for `with` statement, yields thread-safe connection. :return: thread-safe connection :rtype: pydbal.connection.Connection """ conn = self._get_connection() try: self._lock(conn) yield conn finally: ...
[ "def", "locked", "(", "self", ")", ":", "conn", "=", "self", ".", "_get_connection", "(", ")", "try", ":", "self", ".", "_lock", "(", "conn", ")", "yield", "conn", "finally", ":", "self", ".", "_unlock", "(", "conn", ")" ]
28.083333
0.008621
def save_hdf(self,filename,path=''): """Saves all relevant data to .h5 file; so state can be restored. """ self.dataframe.to_hdf(filename,'{}/df'.format(path))
[ "def", "save_hdf", "(", "self", ",", "filename", ",", "path", "=", "''", ")", ":", "self", ".", "dataframe", ".", "to_hdf", "(", "filename", ",", "'{}/df'", ".", "format", "(", "path", ")", ")" ]
45
0.027322
def get_jids_filter(count, filter_find_job=True): ''' Return a list of all job ids :param int count: show not more than the count of most recent jobs :param bool filter_find_jobs: filter out 'saltutil.find_job' jobs ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT * FRO...
[ "def", "get_jids_filter", "(", "count", ",", "filter_find_job", "=", "True", ")", ":", "with", "_get_serv", "(", "ret", "=", "None", ",", "commit", "=", "True", ")", "as", "cur", ":", "sql", "=", "'''SELECT * FROM (\n SELECT DISTINCT `jid` ,`lo...
36.666667
0.001107
def sandwich_decompositions(coords0, coords1, samples=SAMPLES): """Create composite gates, decompose, and return a list of canonical coordinates""" decomps = [] for _ in range(samples): circ = qf.Circuit() circ += qf.CANONICAL(*coords0, 0, 1) circ += qf.random_gate([0]) c...
[ "def", "sandwich_decompositions", "(", "coords0", ",", "coords1", ",", "samples", "=", "SAMPLES", ")", ":", "decomps", "=", "[", "]", "for", "_", "in", "range", "(", "samples", ")", ":", "circ", "=", "qf", ".", "Circuit", "(", ")", "circ", "+=", "qf"...
31.25
0.001942
def search_full(self, regex, return_string=True, advance_pointer=True): """ Search from the current position. If `return_string` is false and a match is found, returns the number of characters matched (from the current position *up to* the end of the match). >>> s =...
[ "def", "search_full", "(", "self", ",", "regex", ",", "return_string", "=", "True", ",", "advance_pointer", "=", "True", ")", ":", "regex", "=", "get_regex", "(", "regex", ")", "self", ".", "match", "=", "regex", ".", "search", "(", "self", ".", "strin...
32
0.001896
def _tseitin(ex, auxvarname, auxvars=None): """ Convert a factored expression to a literal, and a list of constraints. """ if isinstance(ex, Literal): return ex, list() else: if auxvars is None: auxvars = list() lits = list() constraints = list() ...
[ "def", "_tseitin", "(", "ex", ",", "auxvarname", ",", "auxvars", "=", "None", ")", ":", "if", "isinstance", "(", "ex", ",", "Literal", ")", ":", "return", "ex", ",", "list", "(", ")", "else", ":", "if", "auxvars", "is", "None", ":", "auxvars", "=",...
27.916667
0.001443
def iter_equivalent_nodes(self, node: BaseEntity) -> Iterable[BaseEntity]: """Iterate over nodes that are equivalent to the given node, including the original.""" yield node yield from self._equivalent_node_iterator_helper(node, {node})
[ "def", "iter_equivalent_nodes", "(", "self", ",", "node", ":", "BaseEntity", ")", "->", "Iterable", "[", "BaseEntity", "]", ":", "yield", "node", "yield", "from", "self", ".", "_equivalent_node_iterator_helper", "(", "node", ",", "{", "node", "}", ")" ]
64.25
0.011538
def create(self, name=None, prefix=None, pkgs=None, channels=None): """Create an environment with a specified set of packages.""" logger.debug(str((prefix, pkgs, channels))) # TODO: Fix temporal hack if (not pkgs or (not isinstance(pkgs, (list, tuple)) and not i...
[ "def", "create", "(", "self", ",", "name", "=", "None", ",", "prefix", "=", "None", ",", "pkgs", "=", "None", ",", "channels", "=", "None", ")", ":", "logger", ".", "debug", "(", "str", "(", "(", "prefix", ",", "pkgs", ",", "channels", ")", ")", ...
38.255814
0.001186
def find_existing_anchors(soup): """Return existing ids (and names) from a soup.""" existing_anchors = set() for tag in soup.find_all(True): for attr in ['id', 'name']: if tag.has_attr(attr): existing_anchors.add(tag.get(attr)) return existing_anchors
[ "def", "find_existing_anchors", "(", "soup", ")", ":", "existing_anchors", "=", "set", "(", ")", "for", "tag", "in", "soup", ".", "find_all", "(", "True", ")", ":", "for", "attr", "in", "[", "'id'", ",", "'name'", "]", ":", "if", "tag", ".", "has_att...
33.75
0.021661
def list_terreinobjecten_by_huisnummer(self, huisnummer): ''' List all `terreinobjecten` for a :class:`Huisnummer` :param huisnummer: The :class:`Huisnummer` for which the \ `terreinobjecten` are wanted. :rtype: A :class:`list` of :class:`Terreinobject` ''' t...
[ "def", "list_terreinobjecten_by_huisnummer", "(", "self", ",", "huisnummer", ")", ":", "try", ":", "id", "=", "huisnummer", ".", "id", "except", "AttributeError", ":", "id", "=", "huisnummer", "def", "creator", "(", ")", ":", "res", "=", "crab_gateway_request"...
34.5
0.001658
def plot_map_basemap(fignum, lats, lons, Opts): """ plot_map_basemap(fignum, lats,lons,Opts) makes a basemap with lats/lons requires working installation of Basemap Parameters: _______________ fignum : matplotlib figure number lats : array or list of latitudes lons : array or lis...
[ "def", "plot_map_basemap", "(", "fignum", ",", "lats", ",", "lons", ",", "Opts", ")", ":", "if", "not", "has_basemap", ":", "print", "(", "'-W- Basemap must be installed to run plot_map_basemap'", ")", "return", "fig", "=", "plt", ".", "figure", "(", "num", "=...
46.275862
0.000973
def values(self, axis): """ Returns the values of the given axis from all the datasets within this chart. :param axis | <str> :return [<variant>, ..] """ output = [] for dataset in self.datasets(): output +...
[ "def", "values", "(", "self", ",", "axis", ")", ":", "output", "=", "[", "]", "for", "dataset", "in", "self", ".", "datasets", "(", ")", ":", "output", "+=", "dataset", ".", "values", "(", "axis", ")", "return", "output" ]
25.857143
0.013333
def putParamset(self, remote, address, paramset, value): """Set paramsets manually""" try: return self.proxies["%s-%s" % (self._interface_id, remote)].putParamset(address, paramset, value) except Exception as err: LOG.debug("ServerThread.putParamset: Exception: %s" % str(...
[ "def", "putParamset", "(", "self", ",", "remote", ",", "address", ",", "paramset", ",", "value", ")", ":", "try", ":", "return", "self", ".", "proxies", "[", "\"%s-%s\"", "%", "(", "self", ".", "_interface_id", ",", "remote", ")", "]", ".", "putParamse...
53.333333
0.009231
def cursor(self): """The position of the cursor in the text.""" if self._cursor < 0: self.cursor = 0 if self._cursor > len(self): self.cursor = len(self) return self._cursor
[ "def", "cursor", "(", "self", ")", ":", "if", "self", ".", "_cursor", "<", "0", ":", "self", ".", "cursor", "=", "0", "if", "self", ".", "_cursor", ">", "len", "(", "self", ")", ":", "self", ".", "cursor", "=", "len", "(", "self", ")", "return"...
24.777778
0.008658
def text(self): """The text displayed on the block. String containing ``"%s"`` in place of inserts. eg. ``'say %s for %s secs'`` """ parts = [("%s" if isinstance(p, Insert) else p) for p in self.parts] parts = [("%%" if p == "%" else p) for p in parts] # escape percent...
[ "def", "text", "(", "self", ")", ":", "parts", "=", "[", "(", "\"%s\"", "if", "isinstance", "(", "p", ",", "Insert", ")", "else", "p", ")", "for", "p", "in", "self", ".", "parts", "]", "parts", "=", "[", "(", "\"%%\"", "if", "p", "==", "\"%\"",...
30.909091
0.008571
def getprimeover(N): """Return a random N-bit prime number using the System's best Cryptographic random source. Use GMP if available, otherwise fallback to PyCrypto """ if HAVE_GMP: randfunc = random.SystemRandom() r = gmpy2.mpz(randfunc.getrandbits(N)) r = gmpy2.bit_set(r, ...
[ "def", "getprimeover", "(", "N", ")", ":", "if", "HAVE_GMP", ":", "randfunc", "=", "random", ".", "SystemRandom", "(", ")", "r", "=", "gmpy2", ".", "mpz", "(", "randfunc", ".", "getrandbits", "(", "N", ")", ")", "r", "=", "gmpy2", ".", "bit_set", "...
30.789474
0.001658
def add_rect(img, box, color=None, thickness=1): """ Draws a bounding box inside the image. :param img: Input image :param box: Box object that defines the bounding box. :param color: Color of the box :param thickness: Thickness of line :return: Rectangle added image """ if color is...
[ "def", "add_rect", "(", "img", ",", "box", ",", "color", "=", "None", ",", "thickness", "=", "1", ")", ":", "if", "color", "is", "None", ":", "color", "=", "COL_GRAY", "box", "=", "box", ".", "to_int", "(", ")", "cv", ".", "rectangle", "(", "img"...
29.133333
0.002217
def main(command_line=True, **kwargs): """ NAME sio_magic.py DESCRIPTION converts SIO .mag format files to magic_measurements format files SYNTAX sio_magic.py [command line options] OPTIONS -h: prints the help message and quits. -usr USER: identify user, ...
[ "def", "main", "(", "command_line", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# initialize some stuff", "mag_file", "=", "None", "codelist", "=", "None", "infile_type", "=", "\"mag\"", "noave", "=", "0", "methcode", ",", "inst", "=", "\"LP-NO\"", ",...
45.959184
0.023407
def get_method(self, name, arg_types=()): """ searches for the method matching the name and having argument type descriptors matching those in arg_types. Parameters ========== arg_types : sequence of strings each string is a parameter type, in the non-pretty fo...
[ "def", "get_method", "(", "self", ",", "name", ",", "arg_types", "=", "(", ")", ")", ":", "# ensure any lists or iterables are converted to tuple for", "# comparison against get_arg_type_descriptors()", "arg_types", "=", "tuple", "(", "arg_types", ")", "for", "m", "in",...
32.576923
0.002294
def createAndCleanTPED(tped, tfam, samples, oldSamples, chosenSamples, prefix, completion, completionT, concordance, concordanceT): """Complete a TPED for duplicate samples. :param tped: the ``tped`` containing the duplicated samples. :param tfam: the ``tfam`` ...
[ "def", "createAndCleanTPED", "(", "tped", ",", "tfam", ",", "samples", ",", "oldSamples", ",", "chosenSamples", ",", "prefix", ",", "completion", ",", "completionT", ",", "concordance", ",", "concordanceT", ")", ":", "zeroedOutFile", "=", "None", "try", ":", ...
39.963636
0.000296
def update_records(self, qs, batch_size=1000, **kwargs): """ Updates multiple records. This method is optimized for speed. It takes a QuerySet and the same arguments as QuerySet.update(). Optionnaly, you can specify the size of the batch send to Algolia with batch_size (default ...
[ "def", "update_records", "(", "self", ",", "qs", ",", "batch_size", "=", "1000", ",", "*", "*", "kwargs", ")", ":", "tmp", "=", "{", "}", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "name", "=", "self", ".", "__transl...
35.28125
0.001724
def query_pending_jobs(auth, repo_name=None, return_raw=False): """Return pending jobs""" url = '%s/pending?format=json' % HOST_ROOT LOG.debug('About to fetch %s' % url) req = requests.get(url, auth=auth, timeout=TCP_TIMEOUT) # If the revision doesn't exist on buildapi, that means there are # n...
[ "def", "query_pending_jobs", "(", "auth", ",", "repo_name", "=", "None", ",", "return_raw", "=", "False", ")", ":", "url", "=", "'%s/pending?format=json'", "%", "HOST_ROOT", "LOG", ".", "debug", "(", "'About to fetch %s'", "%", "url", ")", "req", "=", "reque...
29.65625
0.00102
def emergence(network, state, do_blackbox=False, do_coarse_grain=True, time_scales=None): """Check for the emergence of a micro-system into a macro-system. Checks all possible blackboxings and coarse-grainings of a system to find the spatial scale with maximum integrated information. Use...
[ "def", "emergence", "(", "network", ",", "state", ",", "do_blackbox", "=", "False", ",", "do_coarse_grain", "=", "True", ",", "time_scales", "=", "None", ")", ":", "micro_phi", "=", "compute", ".", "major_complex", "(", "network", ",", "state", ")", ".", ...
38.702128
0.000536
def rst(value_rule): '''Given the data and type information, generate a list of strings for insertion into a RST document. ''' lines = [] if value_rule.has('type'): value_type = value_rule['type'].value else: value_type = 'string' if value_type=='ignore': pass els...
[ "def", "rst", "(", "value_rule", ")", ":", "lines", "=", "[", "]", "if", "value_rule", ".", "has", "(", "'type'", ")", ":", "value_type", "=", "value_rule", "[", "'type'", "]", ".", "value", "else", ":", "value_type", "=", "'string'", "if", "value_type...
23
0.017207
def expression(expr): """ Returns a function that treats the keys of a dictionary as locals, and returns the expression, e.g.: >>> expression("foo")({'foo': 'bar'}) 'bar' >>> expression("bar + 1")({'bar': 2}) 3 >>> expression("get('foo bar') == 'baz'")({'foo bar': 'baz'}) True "...
[ "def", "expression", "(", "expr", ")", ":", "if", "callable", "(", "expr", ")", ":", "return", "expr", "if", "len", "(", "expr", ")", "==", "0", ":", "return", "lambda", "d", ":", "None", "def", "_expr", "(", "data", ",", "*", "*", "kwargs", ")",...
25.62069
0.001297
def dump_database(id): """Backup the Postgres database locally.""" log("Generating a backup of the database on Heroku...") dump_filename = "data.dump" data_directory = "data" dump_dir = os.path.join(data_directory, id) if not os.path.exists(dump_dir): os.makedirs(dump_dir) subproce...
[ "def", "dump_database", "(", "id", ")", ":", "log", "(", "\"Generating a backup of the database on Heroku...\"", ")", "dump_filename", "=", "\"data.dump\"", "data_directory", "=", "\"data\"", "dump_dir", "=", "os", ".", "path", ".", "join", "(", "data_directory", ",...
34.583333
0.001172
def gofmt(ui, repo, *pats, **opts): """apply gofmt to modified files Applies gofmt to the modified files in the repository that match the given patterns. """ if codereview_disabled: raise hg_util.Abort(codereview_disabled) files = ChangedExistingFiles(ui, repo, pats, opts) files = gofmt_required(files) if n...
[ "def", "gofmt", "(", "ui", ",", "repo", ",", "*", "pats", ",", "*", "*", "opts", ")", ":", "if", "codereview_disabled", ":", "raise", "hg_util", ".", "Abort", "(", "codereview_disabled", ")", "files", "=", "ChangedExistingFiles", "(", "ui", ",", "repo", ...
26
0.035714
def merge_runs(res_list, print_progress=True): """ Merges a set of runs with differing (possibly variable) numbers of live points into one run. Parameters ---------- res_list : list of :class:`~dynesty.results.Results` instances A list of :class:`~dynesty.results.Results` instances retu...
[ "def", "merge_runs", "(", "res_list", ",", "print_progress", "=", "True", ")", ":", "ntot", "=", "len", "(", "res_list", ")", "counter", "=", "0", "# Establish our set of baseline runs and \"add-on\" runs.", "rlist_base", "=", "[", "]", "rlist_add", "=", "[", "]...
32.513274
0.001321
def register_single(key, value, param=None): '''Generates resolver to return singleton value and adds it to global container''' get_current_scope().container.register(key, lambda: value, param)
[ "def", "register_single", "(", "key", ",", "value", ",", "param", "=", "None", ")", ":", "get_current_scope", "(", ")", ".", "container", ".", "register", "(", "key", ",", "lambda", ":", "value", ",", "param", ")" ]
66.333333
0.00995
def check_directory(placeholders): """ Find out, and create if needed, the directory in which the feed will be downloaded """ feed = placeholders.feed args = feed.args placeholders.directory = "This very directory" # wink, wink placeholders.fullpath = os.path.join( placeholders....
[ "def", "check_directory", "(", "placeholders", ")", ":", "feed", "=", "placeholders", ".", "feed", "args", "=", "feed", ".", "args", "placeholders", ".", "directory", "=", "\"This very directory\"", "# wink, wink", "placeholders", ".", "fullpath", "=", "os", "."...
38.34375
0.000795
def get_model(model_fn, train_data, param): """Feed model_fn with train_data and param """ model_param = merge_dicts({"train_data": train_data}, param["model"], param.get("shared", {})) return model_fn(**model_param)
[ "def", "get_model", "(", "model_fn", ",", "train_data", ",", "param", ")", ":", "model_param", "=", "merge_dicts", "(", "{", "\"train_data\"", ":", "train_data", "}", ",", "param", "[", "\"model\"", "]", ",", "param", ".", "get", "(", "\"shared\"", ",", ...
45.6
0.008621
def write_geno(data, sidx): """ write the geno output formerly used by admixture, still supported by adegenet, perhaps. Also, sNMF still likes .geno. """ ## grab snp and bis data from tmparr start = time.time() tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name)) ...
[ "def", "write_geno", "(", "data", ",", "sidx", ")", ":", "## grab snp and bis data from tmparr", "start", "=", "time", ".", "time", "(", ")", "tmparrs", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "outfiles", ",", "\"tmp-{}.h5\"", ...
39.849315
0.008722
def to_pfull_from_phalf(arr, pfull_coord): """Compute data at full pressure levels from values at half levels.""" phalf_top = arr.isel(**{internal_names.PHALF_STR: slice(1, None)}) phalf_top = replace_coord(phalf_top, internal_names.PHALF_STR, internal_names.PFULL_STR, pfull_co...
[ "def", "to_pfull_from_phalf", "(", "arr", ",", "pfull_coord", ")", ":", "phalf_top", "=", "arr", ".", "isel", "(", "*", "*", "{", "internal_names", ".", "PHALF_STR", ":", "slice", "(", "1", ",", "None", ")", "}", ")", "phalf_top", "=", "replace_coord", ...
56.3
0.001748
def dirpath(self): """Returns a Path object for the directory associated with this object.""" if self.isfile(): return Path(op.dirname(self._fspath)) else: return Path(self)
[ "def", "dirpath", "(", "self", ")", ":", "if", "self", ".", "isfile", "(", ")", ":", "return", "Path", "(", "op", ".", "dirname", "(", "self", ".", "_fspath", ")", ")", "else", ":", "return", "Path", "(", "self", ")" ]
36
0.013575
def _make_repr(class_name, *args, **kwargs): """ Generate a repr string. Positional arguments should be the positional arguments used to construct the class. Keyword arguments should consist of tuples of the attribute value and default. If the value is the default, then it won't be rendered in ...
[ "def", "_make_repr", "(", "class_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "arguments", "=", "[", "repr", "(", "arg", ")", "for", "arg", "in", "args", "]", "arguments", ".", "extend", "(", "\"{}={!r}\"", ".", "format", "(", "name", ...
31.44
0.001235
def main(argString=None): """The main function of the module. :param argString: the options. :type argString: list These are the steps: 1. Prints the options. 2. Compute frequency using Plink. 3. Runs bafRegress. """ # Getting and checking the options args = parseArgs(argStr...
[ "def", "main", "(", "argString", "=", "None", ")", ":", "# Getting and checking the options", "args", "=", "parseArgs", "(", "argString", ")", "checkArgs", "(", "args", ")", "logger", ".", "info", "(", "\"Options used:\"", ")", "for", "key", ",", "value", "i...
29.238095
0.000788
def as_list(value): """clever string spliting: .. code-block:: python >>> print(as_list('value')) ['value'] >>> print(as_list('v1 v2')) ['v1', 'v2'] >>> print(as_list(None)) [] >>> print(as_list(['v1'])) ['v1'] """ if isinstance(value, (l...
[ "def", "as_list", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "value", "if", "not", "value", ":", "return", "[", "]", "for", "c", "in", "'\\n '", ":", "if", "c", "in", "value"...
22.782609
0.001832
def get_relaxation(self, level, objective=None, inequalities=None, equalities=None, substitutions=None, momentinequalities=None, momentequalities=None, momentsubstitutions=None, removeequalities=False, extramonomials=None, ...
[ "def", "get_relaxation", "(", "self", ",", "level", ",", "objective", "=", "None", ",", "inequalities", "=", "None", ",", "equalities", "=", "None", ",", "substitutions", "=", "None", ",", "momentinequalities", "=", "None", ",", "momentequalities", "=", "Non...
55.586207
0.001097
def convert(outputfile, inputfile, to_format, from_format): """ Convert pretrained word embedding file in one format to another. """ emb = word_embedding.WordEmbedding.load( inputfile, format=_input_choices[from_format][1], binary=_input_choices[from_format][2]) emb.save(outputfile, ...
[ "def", "convert", "(", "outputfile", ",", "inputfile", ",", "to_format", ",", "from_format", ")", ":", "emb", "=", "word_embedding", ".", "WordEmbedding", ".", "load", "(", "inputfile", ",", "format", "=", "_input_choices", "[", "from_format", "]", "[", "1",...
44.444444
0.002451
def _volume_percentage(self, volume): """Returns the plunger percentage for a given volume. We use this to calculate what actual position the plunger axis needs to be at in order to achieve the correct volume of liquid. """ if volume < 0: raise RuntimeError( ...
[ "def", "_volume_percentage", "(", "self", ",", "volume", ")", ":", "if", "volume", "<", "0", ":", "raise", "RuntimeError", "(", "\"Volume must be a positive number, got {}.\"", ".", "format", "(", "volume", ")", ")", "if", "volume", ">", "self", ".", "max_volu...
41.736842
0.002466
def load_imdb(): """ Load IMDB dataset Transform input data into an RDD of Sample """ from keras.preprocessing import sequence from keras.datasets import imdb (X_train, y_train), (X_test, y_test) = imdb.load_data(nb_words=20000) X_train = sequence.pad_sequences(X_train, maxlen=100) X...
[ "def", "load_imdb", "(", ")", ":", "from", "keras", ".", "preprocessing", "import", "sequence", "from", "keras", ".", "datasets", "import", "imdb", "(", "X_train", ",", "y_train", ")", ",", "(", "X_test", ",", "y_test", ")", "=", "imdb", ".", "load_data"...
36.727273
0.002415
def record_list_projects(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /record-xxxx/listProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects """ return DXHTTPRequest('/%s/listProjec...
[ "def", "record_list_projects", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/listProjects'", "%", "object_id", ",", "input_params", ",", "always_...
54.428571
0.010336