text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def pufunc(func): """ Called by pfunc to convert NumPy ufuncs to deterministic factories. """ def dtrm_generator(*args): if len(args) != func.nin: raise ValueError('invalid number of arguments') name = func.__name__ + '(' + '_'.join( [str(arg) for arg in list(args...
[ "def", "pufunc", "(", "func", ")", ":", "def", "dtrm_generator", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "!=", "func", ".", "nin", ":", "raise", "ValueError", "(", "'invalid number of arguments'", ")", "name", "=", "func", ".", "__na...
35.464286
0.00098
def split(*items): """Split samples into all possible genomes for alignment. """ out = [] for data in [x[0] for x in items]: dis_orgs = data["config"]["algorithm"].get("disambiguate") if dis_orgs: if not data.get("disambiguate", None): data["disambiguate"] = {...
[ "def", "split", "(", "*", "items", ")", ":", "out", "=", "[", "]", "for", "data", "in", "[", "x", "[", "0", "]", "for", "x", "in", "items", "]", ":", "dis_orgs", "=", "data", "[", "\"config\"", "]", "[", "\"algorithm\"", "]", ".", "get", "(", ...
42.791667
0.000952
def get_geo_top_tracks(self, country, location=None, limit=None, cacheable=True): """Get the most popular tracks on Last.fm last week by country. Parameters: country (Required) : A country name, as defined by the ISO 3166-1 country names standard location (Optional) : A metro...
[ "def", "get_geo_top_tracks", "(", "self", ",", "country", ",", "location", "=", "None", ",", "limit", "=", "None", ",", "cacheable", "=", "True", ")", ":", "params", "=", "{", "\"country\"", ":", "country", "}", "if", "location", ":", "params", "[", "\...
34.966667
0.002783
def open_machine(self, settings_file): """Opens a virtual machine from the existing settings file. The opened machine remains unregistered until you call :py:func:`register_machine` . The specified settings file name must be fully qualified. The file must exist and be a ...
[ "def", "open_machine", "(", "self", ",", "settings_file", ")", ":", "if", "not", "isinstance", "(", "settings_file", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"settings_file can only be an instance of type basestring\"", ")", "machine", "=", "self", ...
38.5
0.006757
def dump(obj, fp, pretty=False, escaped=True): """ Serialize ``obj`` as a VDF formatted stream to ``fp`` (a ``.write()``-supporting file-like object). """ if not isinstance(obj, dict): raise TypeError("Expected data to be an instance of``dict``") if not hasattr(fp, 'write'): rais...
[ "def", "dump", "(", "obj", ",", "fp", ",", "pretty", "=", "False", ",", "escaped", "=", "True", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"Expected data to be an instance of``dict``\"", ")", "if", ...
39.3125
0.001553
async def create( cls, architecture: str, mac_addresses: typing.Sequence[str], power_type: str, power_parameters: typing.Mapping[str, typing.Any] = None, *, subarchitecture: str = None, min_hwe_kernel: str = None, hostname: str = None, domain: typing.Union[int...
[ "async", "def", "create", "(", "cls", ",", "architecture", ":", "str", ",", "mac_addresses", ":", "typing", ".", "Sequence", "[", "str", "]", ",", "power_type", ":", "str", ",", "power_parameters", ":", "typing", ".", "Mapping", "[", "str", ",", "typing"...
43.886364
0.001013
def _force_edge_active_move(self, state: _STATE) -> _STATE: """Move which forces a random edge to appear on some sequence. This move chooses random edge from the edges which do not belong to any sequence and modifies state in such a way, that this chosen edge appears on some sequence of...
[ "def", "_force_edge_active_move", "(", "self", ",", "state", ":", "_STATE", ")", "->", "_STATE", ":", "seqs", ",", "edges", "=", "state", "unused_edges", "=", "edges", ".", "copy", "(", ")", "# List edges which do not belong to any linear sequence.", "for", "seq",...
34.483871
0.00182
def validate(args): """ Check that the CLI arguments passed to autosub are valid. """ if args.format not in FORMATTERS: print( "Subtitle format not supported. " "Run with --list-formats to see all supported formats." ) return False if args.src_languag...
[ "def", "validate", "(", "args", ")", ":", "if", "args", ".", "format", "not", "in", "FORMATTERS", ":", "print", "(", "\"Subtitle format not supported. \"", "\"Run with --list-formats to see all supported formats.\"", ")", "return", "False", "if", "args", ".", "src_lan...
27.933333
0.001153
def local( year, month, day, hour=0, minute=0, second=0, microsecond=0 ): # type: (int, int, int, int, int, int, int) -> DateTime """ Return a DateTime in the local timezone. """ return datetime( year, month, day, hour, minute, second, microsecond, tz=local_timezone() )
[ "def", "local", "(", "year", ",", "month", ",", "day", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", ":", "# type: (int, int, int, int, int, int, int) -> DateTime", "return", "datetime", "(", "y...
32.777778
0.006601
def register_hooks(self, field): """Register a field on its target hooks.""" for hook, subhooks in field.register_hooks(): self.hooks[hook].append(field) self.subhooks[hook] |= set(subhooks)
[ "def", "register_hooks", "(", "self", ",", "field", ")", ":", "for", "hook", ",", "subhooks", "in", "field", ".", "register_hooks", "(", ")", ":", "self", ".", "hooks", "[", "hook", "]", ".", "append", "(", "field", ")", "self", ".", "subhooks", "[",...
45.2
0.008696
def delete(cont, path=None, profile=None): ''' Delete a container, or delete an object from a container. CLI Example to delete a container:: salt myminion swift.delete mycontainer CLI Example to delete an object from a container:: salt myminion swift.delete mycontainer remoteobject ...
[ "def", "delete", "(", "cont", ",", "path", "=", "None", ",", "profile", "=", "None", ")", ":", "swift_conn", "=", "_auth", "(", "profile", ")", "if", "path", "is", "None", ":", "return", "swift_conn", ".", "delete_container", "(", "cont", ")", "else", ...
26.333333
0.002037
def clean(cls, cpf): u""" Retorna apenas os dígitos do CPF. >>> CPF.clean('581.194.436-59') '58119443659' """ if isinstance(cpf, six.string_types): cpf = int(re.sub('[^0-9]', '', cpf)) return '{0:011d}'.format(cpf)
[ "def", "clean", "(", "cls", ",", "cpf", ")", ":", "if", "isinstance", "(", "cpf", ",", "six", ".", "string_types", ")", ":", "cpf", "=", "int", "(", "re", ".", "sub", "(", "'[^0-9]'", ",", "''", ",", "cpf", ")", ")", "return", "'{0:011d}'", ".", ...
24.909091
0.007042
def align_cell(fmt, elem, width): """Returns an aligned element.""" if fmt == "<": return elem + ' ' * (width - len(elem)) if fmt == ">": return ' ' * (width - len(elem)) + elem return elem
[ "def", "align_cell", "(", "fmt", ",", "elem", ",", "width", ")", ":", "if", "fmt", "==", "\"<\"", ":", "return", "elem", "+", "' '", "*", "(", "width", "-", "len", "(", "elem", ")", ")", "if", "fmt", "==", "\">\"", ":", "return", "' '", "*", "(...
30.714286
0.004525
def _get_or_create_s3_bucket(s3, name): """Get an S3 bucket resource after making sure it exists""" exists = True try: s3.meta.client.head_bucket(Bucket=name) except botocore.exceptions.ClientError as e: error_code = int(e.response["Error"]["Code"]) if error_code == 404: ...
[ "def", "_get_or_create_s3_bucket", "(", "s3", ",", "name", ")", ":", "exists", "=", "True", "try", ":", "s3", ".", "meta", ".", "client", ".", "head_bucket", "(", "Bucket", "=", "name", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "a...
27.5625
0.002193
def replace_data(self, chart_data): """ Use the categories and series values in the |ChartData| object *chart_data* to replace those in the XML and Excel worksheet for this chart. """ rewriter = SeriesXmlRewriterFactory(self.chart_type, chart_data) rewriter.replac...
[ "def", "replace_data", "(", "self", ",", "chart_data", ")", ":", "rewriter", "=", "SeriesXmlRewriterFactory", "(", "self", ".", "chart_type", ",", "chart_data", ")", "rewriter", ".", "replace_series_data", "(", "self", ".", "_chartSpace", ")", "self", ".", "_w...
45.555556
0.004785
def email_login(request, *, email, **kwargs): """ Given a request, an email and optionally some additional data, ensure that a user with the email address exists, and authenticate & login them right away if the user is active. Returns a tuple consisting of ``(user, created)`` upon success or ``(Non...
[ "def", "email_login", "(", "request", ",", "*", ",", "email", ",", "*", "*", "kwargs", ")", ":", "_u", ",", "created", "=", "auth", ".", "get_user_model", "(", ")", ".", "_default_manager", ".", "get_or_create", "(", "email", "=", "email", ")", "user",...
43.533333
0.002999
def _resolve(value, model_instance=None, context=None): """ Resolves any template references in the given value. """ if isinstance(value, basestring) and "{" in value: if context is None: context = Context() if model_instance is not None: context[model_instance._met...
[ "def", "_resolve", "(", "value", ",", "model_instance", "=", "None", ",", "context", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "basestring", ")", "and", "\"{\"", "in", "value", ":", "if", "context", "is", "None", ":", "context", "="...
36.909091
0.004808
def _wrap_callback_parse_stream_data(subscription, on_data, message): """ Wraps an (optional) user callback to parse StreamData from a WebSocket data message """ if (message.type == message.DATA and message.data.type == yamcs_pb2.STREAM_DATA): stream_data = getattr(message.data, ...
[ "def", "_wrap_callback_parse_stream_data", "(", "subscription", ",", "on_data", ",", "message", ")", ":", "if", "(", "message", ".", "type", "==", "message", ".", "DATA", "and", "message", ".", "data", ".", "type", "==", "yamcs_pb2", ".", "STREAM_DATA", ")",...
40.666667
0.002674
def change_kernel(self, kernel): """ Change the droplet's kernel :param kernel: a kernel ID or `Kernel` object representing the new kernel :type kernel: integer or `Kernel` :return: an `Action` representing the in-progress operation on the droplet ...
[ "def", "change_kernel", "(", "self", ",", "kernel", ")", ":", "if", "isinstance", "(", "kernel", ",", "Kernel", ")", ":", "kernel", "=", "kernel", ".", "id", "return", "self", ".", "act", "(", "type", "=", "'change_kernel'", ",", "kernel", "=", "kernel...
35.6
0.00365
def oauth_token_exchange_cli(client_id, client_secret, redirect_uri, base_url=OH_BASE_URL, code=None, refresh_token=None): """ Command line function for obtaining the refresh token/code. For more information visit :func:`oauth2_token_exchange<oha...
[ "def", "oauth_token_exchange_cli", "(", "client_id", ",", "client_secret", ",", "redirect_uri", ",", "base_url", "=", "OH_BASE_URL", ",", "code", "=", "None", ",", "refresh_token", "=", "None", ")", ":", "print", "(", "oauth2_token_exchange", "(", "client_id", "...
48.6
0.00202
def find_run(): """Finds the last good run of the given name for a release.""" build = g.build last_good_release, last_good_run = _find_last_good_run(build) if last_good_run: return flask.jsonify( success=True, build_id=build.id, release_name=last_good_releas...
[ "def", "find_run", "(", ")", ":", "build", "=", "g", ".", "build", "last_good_release", ",", "last_good_run", "=", "_find_last_good_run", "(", "build", ")", "if", "last_good_run", ":", "return", "flask", ".", "jsonify", "(", "success", "=", "True", ",", "b...
33.5
0.001613
def regular_tasks(self): """Do some housekeeping (cache expiration, timeout handling). This method should be called periodically from the application's main loop. :Return: suggested delay (in seconds) before the next call to this ...
[ "def", "regular_tasks", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "ret", "=", "self", ".", "_iq_response_handlers", ".", "expire", "(", ")", "if", "ret", "is", "None", ":", "return", "1", "else", ":", "return", "min", "(", "1", ",", ...
34.1875
0.003559
def open_sensor( self, input_source: str, extra_cmd: Optional[str] = None ) -> Coroutine: """Open FFmpeg process a video stream for motion detection. Return a coroutine. """ command = [ "-an", "-filter:v", "select=gt(scene\\,{0})".format(s...
[ "def", "open_sensor", "(", "self", ",", "input_source", ":", "str", ",", "extra_cmd", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Coroutine", ":", "command", "=", "[", "\"-an\"", ",", "\"-filter:v\"", ",", "\"select=gt(scene\\\\,{0})\"", ".", ...
27.636364
0.004769
def acceptEdit(self): """ Accepts the current edit for this label. """ if not self._lineEdit: return self.setText(self._lineEdit.text()) self._lineEdit.hide() if not self.signalsBlocked(): self.editingFinished.e...
[ "def", "acceptEdit", "(", "self", ")", ":", "if", "not", "self", ".", "_lineEdit", ":", "return", "self", ".", "setText", "(", "self", ".", "_lineEdit", ".", "text", "(", ")", ")", "self", ".", "_lineEdit", ".", "hide", "(", ")", "if", "not", "self...
27.916667
0.011561
def diff(var, key): '''calculate differences between values''' global last_diff ret = 0 if not key in last_diff: last_diff[key] = var return 0 ret = var - last_diff[key] last_diff[key] = var return ret
[ "def", "diff", "(", "var", ",", "key", ")", ":", "global", "last_diff", "ret", "=", "0", "if", "not", "key", "in", "last_diff", ":", "last_diff", "[", "key", "]", "=", "var", "return", "0", "ret", "=", "var", "-", "last_diff", "[", "key", "]", "l...
23.6
0.008163
def add_elementwise(self, name, input_names, output_name, mode, alpha = None): """ Add an element-wise operation layer to the model. Parameters ---------- The name of this layer name: str input_names: [str] A list of input blob names of this layer...
[ "def", "add_elementwise", "(", "self", ",", "name", ",", "input_names", ",", "output_name", ",", "mode", ",", "alpha", "=", "None", ")", ":", "spec", "=", "self", ".", "spec", "nn_spec", "=", "self", ".", "nn_spec", "spec_layer", "=", "nn_spec", ".", "...
40.986111
0.004302
def _get_cached_stats(self, app_stats): """ Process: * cached_host_check_stats * cached_service_check_stats """ stats = {} app_keys = [ "cached_host_check_stats", "cached_service_check_stats", ] for app_key in app_keys: ...
[ "def", "_get_cached_stats", "(", "self", ",", "app_stats", ")", ":", "stats", "=", "{", "}", "app_keys", "=", "[", "\"cached_host_check_stats\"", ",", "\"cached_service_check_stats\"", ",", "]", "for", "app_key", "in", "app_keys", ":", "if", "app_key", "not", ...
30.363636
0.002903
def get_field(self, field, default=None): """Returns a value from the operation for a specific set of field names. Args: field: a dsub-specific job metadata key default: default value to return if field does not exist or is empty. Returns: A text string for the field or a list for 'input...
[ "def", "get_field", "(", "self", ",", "field", ",", "default", "=", "None", ")", ":", "value", "=", "None", "if", "field", "==", "'internal-id'", ":", "value", "=", "self", ".", "_op", "[", "'name'", "]", "elif", "field", "==", "'user-project'", ":", ...
40.268116
0.007552
def concat(args): """ >>> concat([1,2,3,4,5] , [1,2,3,4,5]]) [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] """ import pdb pdb.set_trace() t = [matlabarray(a) for a in args] return np.concatenate(t)
[ "def", "concat", "(", "args", ")", ":", "import", "pdb", "pdb", ".", "set_trace", "(", ")", "t", "=", "[", "matlabarray", "(", "a", ")", "for", "a", "in", "args", "]", "return", "np", ".", "concatenate", "(", "t", ")" ]
22.888889
0.004673
def get_http(base_url, function, opts): """HTTP request generator.""" url = (os.path.join(base_url, function) + '/?' + urlencode(opts)) data = urlopen(url) if data.code != 200: raise ValueError("Random.rg returned server code: " + str(data.code)) return data.read()
[ "def", "get_http", "(", "base_url", ",", "function", ",", "opts", ")", ":", "url", "=", "(", "os", ".", "path", ".", "join", "(", "base_url", ",", "function", ")", "+", "'/?'", "+", "urlencode", "(", "opts", ")", ")", "data", "=", "urlopen", "(", ...
35.875
0.003401
def reports(self): """ Find all the runs in the path. Create an object to store the metadata for each run: run name, path, name of reports, etc. :return: a list of metadata objects """ printtime('Finding reports', self.start) # Initialise a list of runs and a list...
[ "def", "reports", "(", "self", ")", ":", "printtime", "(", "'Finding reports'", ",", "self", ".", "start", ")", "# Initialise a list of runs and a list of all the metadata objects", "runs", "=", "list", "(", ")", "samples", "=", "list", "(", ")", "# Glob all the ass...
53.291667
0.003455
def _deploy_a_clone(self, si, logger, app_name, template_name, other_params, vcenter_data_model, reservation_id, cancellation_context, snapshot=''): """ :rtype DeployAppResult: """ # generate unique name vm_name = self.name_generato...
[ "def", "_deploy_a_clone", "(", "self", ",", "si", ",", "logger", ",", "app_name", ",", "template_name", ",", "other_params", ",", "vcenter_data_model", ",", "reservation_id", ",", "cancellation_context", ",", "snapshot", "=", "''", ")", ":", "# generate unique nam...
56.708333
0.006139
def basen_to_integer(self, X, cols, base): """ Convert basen code as integers. Parameters ---------- X : DataFrame encoded data cols : list-like Column names in the DataFrame that be encoded base : int The base of transform ...
[ "def", "basen_to_integer", "(", "self", ",", "X", ",", "cols", ",", "base", ")", ":", "out_cols", "=", "X", ".", "columns", ".", "values", ".", "tolist", "(", ")", "for", "col", "in", "cols", ":", "col_list", "=", "[", "col0", "for", "col0", "in", ...
30
0.004748
def components(self): """ Returns full :class:`dict` of :class:`Component` instances, after a successful :meth:`build` :return: dict of named :class:`Component` instances :rtype: :class:`dict` For more information read about the :ref:`parts_assembly-build-cycle` . ...
[ "def", "components", "(", "self", ")", ":", "if", "self", ".", "_components", "is", "None", ":", "self", ".", "build", "(", "recursive", "=", "False", ")", "return", "self", ".", "_components" ]
32.538462
0.004598
def generate_menu(): """Generate ``menu`` with the rebuild link. :return: HTML fragment :rtype: str """ if db is not None: needs_rebuild = db.get('site:needs_rebuild') else: needs_rebuild = site.coil_needs_rebuild if needs_rebuild not in (u'0', u'-1', b'0', b'-1'): r...
[ "def", "generate_menu", "(", ")", ":", "if", "db", "is", "not", "None", ":", "needs_rebuild", "=", "db", ".", "get", "(", "'site:needs_rebuild'", ")", "else", ":", "needs_rebuild", "=", "site", ".", "coil_needs_rebuild", "if", "needs_rebuild", "not", "in", ...
36.470588
0.001572
def tick(self, d): """ ticks come in on every block """ if self.test_blocks: if not (self.counter["blocks"] or 0) % self.test_blocks: self.test() self.counter["blocks"] += 1
[ "def", "tick", "(", "self", ",", "d", ")", ":", "if", "self", ".", "test_blocks", ":", "if", "not", "(", "self", ".", "counter", "[", "\"blocks\"", "]", "or", "0", ")", "%", "self", ".", "test_blocks", ":", "self", ".", "test", "(", ")", "self", ...
33
0.008439
def read(filename): """ Get the long description from a file. """ fname = os.path.join(here, filename) with codecs.open(fname, encoding='utf-8') as f: return f.read()
[ "def", "read", "(", "filename", ")", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "here", ",", "filename", ")", "with", "codecs", ".", "open", "(", "fname", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "return", "f", ".", "rea...
26.857143
0.005155
def filter_slaves(selfie, slaves): """ Remove slaves that are in an ODOWN or SDOWN state also remove slaves that do not have 'ok' master-link-status """ return [(s['ip'], s['port']) for s in slaves if not s['is_odown'] and not s['is_sdown'] and ...
[ "def", "filter_slaves", "(", "selfie", ",", "slaves", ")", ":", "return", "[", "(", "s", "[", "'ip'", "]", ",", "s", "[", "'port'", "]", ")", "for", "s", "in", "slaves", "if", "not", "s", "[", "'is_odown'", "]", "and", "not", "s", "[", "'is_sdown...
39.666667
0.005479
def remove(self, entity): """ Remove entity from the MatchBox. :param object entity: """ empty_traits = set() self.mismatch_unknown.discard(entity) for trait, entities in self.index.items(): entities.discard(entity) if not entities: ...
[ "def", "remove", "(", "self", ",", "entity", ")", ":", "empty_traits", "=", "set", "(", ")", "self", ".", "mismatch_unknown", ".", "discard", "(", "entity", ")", "for", "trait", ",", "entities", "in", "self", ".", "index", ".", "items", "(", ")", ":"...
28.066667
0.004598
def sizeHint(self, option, index): """Size based on component duration and a fixed height""" # calculate size by data component component = index.internalPointer() width = self.component.duration() * self.pixelsPerms*1000 return QtCore.QSize(width, 50)
[ "def", "sizeHint", "(", "self", ",", "option", ",", "index", ")", ":", "# calculate size by data component", "component", "=", "index", ".", "internalPointer", "(", ")", "width", "=", "self", ".", "component", ".", "duration", "(", ")", "*", "self", ".", "...
47.833333
0.006849
def run_script(self, script_id, params=None): """ Runs a stored script. script_id:= id of stored script. params:= up to 10 parameters required by the script. ... s = pi.run_script(sid, [par1, par2]) s = pi.run_script(sid) s = pi.run_script(sid, [1, 2,...
[ "def", "run_script", "(", "self", ",", "script_id", ",", "params", "=", "None", ")", ":", "# I p1 script id", "# I p2 0", "# I p3 params * 4 (0-10 params)", "# (optional) extension", "# I[] params", "if", "params", "is", "not", "None", ":", "ext", "=", "bytearray", ...
28.46875
0.002123
def balance_matrix(A): """ Balance matrix, i.e. finds such similarity transformation of the original matrix A: A = T * bA * T^{-1}, where norms of columns of bA and of rows of bA are as close as possible. It is usually used as a preprocessing step in eigenvalue calculation routine. It is useful als...
[ "def", "balance_matrix", "(", "A", ")", ":", "if", "len", "(", "A", ".", "shape", ")", "!=", "2", "or", "(", "A", ".", "shape", "[", "0", "]", "!=", "A", ".", "shape", "[", "1", "]", ")", ":", "raise", "ValueError", "(", "'balance_matrix: Expecti...
32.935065
0.0134
def create_record(marcxml=None, verbose=CFG_BIBRECORD_DEFAULT_VERBOSE_LEVEL, correct=CFG_BIBRECORD_DEFAULT_CORRECT, parser='', sort_fields_by_indicators=False, keep_singletons=CFG_BIBRECORD_KEEP_SINGLETONS): """Create a record object from the marcxml description...
[ "def", "create_record", "(", "marcxml", "=", "None", ",", "verbose", "=", "CFG_BIBRECORD_DEFAULT_VERBOSE_LEVEL", ",", "correct", "=", "CFG_BIBRECORD_DEFAULT_CORRECT", ",", "parser", "=", "''", ",", "sort_fields_by_indicators", "=", "False", ",", "keep_singletons", "="...
44.464789
0.00031
def avl_new_top(t1, t2, top, direction=0): """ if direction == 0: (t1, t2) is (left, right) if direction == 1: (t1, t2) is (right, left) """ top.parent = None assert top.parent is None, str(top.parent.value) top.set_child(direction, t1) top.set_child(1 - direction, t2) ...
[ "def", "avl_new_top", "(", "t1", ",", "t2", ",", "top", ",", "direction", "=", "0", ")", ":", "top", ".", "parent", "=", "None", "assert", "top", ".", "parent", "is", "None", ",", "str", "(", "top", ".", "parent", ".", "value", ")", "top", ".", ...
28.461538
0.002618
def set_pin_mode(self, pin, mode, pin_type, cb=None): """ This method sets a pin to the desired pin mode for the pin_type. It automatically enables data reporting. NOTE: DO NOT CALL THIS METHOD FOR I2C. See i2c_config(). :param pin: Pin number (for analog use the analog number, ...
[ "def", "set_pin_mode", "(", "self", ",", "pin", ",", "mode", ",", "pin_type", ",", "cb", "=", "None", ")", ":", "command", "=", "[", "self", ".", "_command_handler", ".", "SET_PIN_MODE", ",", "pin", ",", "mode", "]", "self", ".", "_command_handler", "....
44.465116
0.005118
async def viewers_js(request): ''' Viewers determines the viewers installed based on settings, then uses the conversion infrastructure to convert all these JS files into a single JS bundle, that is then served. As with media, it will simply serve a cached version if necessary. ''' # Generate...
[ "async", "def", "viewers_js", "(", "request", ")", ":", "# Generates single bundle as such:", "# BytesResource -> ViewerNodePackageBuilder -> nodepackage -> ... -> min.js", "response", "=", "singletons", ".", "server", ".", "response", "# Create a viewers resource, which is simply a ...
37.65
0.000647
def move(self, source, destination): """ the semantic should be like unix 'mv' command """ if source.isfile(): source.copy(destination) source.remove() else: source.copy(destination, recursive=True) source.remove('r')
[ "def", "move", "(", "self", ",", "source", ",", "destination", ")", ":", "if", "source", ".", "isfile", "(", ")", ":", "source", ".", "copy", "(", "destination", ")", "source", ".", "remove", "(", ")", "else", ":", "source", ".", "copy", "(", "dest...
29.6
0.006557
def run_edisgo_twice(run_args): """ Run grid analysis twice on same grid: once w/ and once w/o new generators First run without connection of new generators approves sufficient grid hosting capacity. Otherwise, grid is reinforced. Second run assessment grid extension needs in terms of RES integrati...
[ "def", "run_edisgo_twice", "(", "run_args", ")", ":", "# base case with no generator import", "edisgo_grid", ",", "costs_before_geno_import", ",", "grid_issues_before_geno_import", "=", "run_edisgo_basic", "(", "*", "run_args", ")", "if", "edisgo_grid", ":", "# clear the py...
35.791667
0.002833
def register_column(self, column, expr, deltas=None, checkpoints=None, odo_kwargs=None): """Explicitly map a single bound column to a collection of blaze expressions. The expressions n...
[ "def", "register_column", "(", "self", ",", "column", ",", "expr", ",", "deltas", "=", "None", ",", "checkpoints", "=", "None", ",", "odo_kwargs", "=", "None", ")", ":", "self", ".", "_table_expressions", "[", "column", "]", "=", "ExprData", "(", "expr",...
32
0.006434
def push_dcp(event, callback, position='right'): """Push a callable for :class:`~flask_pluginkit.PluginManager`, :func:`push_dcp`. Example usage:: push_dcp('demo', lambda:'Hello dcp') .. versionadded:: 2.1.0 """ ctx = stack.top ctx.app.extensions.get('pluginkit').push_dcp(event, callb...
[ "def", "push_dcp", "(", "event", ",", "callback", ",", "position", "=", "'right'", ")", ":", "ctx", "=", "stack", ".", "top", "ctx", ".", "app", ".", "extensions", ".", "get", "(", "'pluginkit'", ")", ".", "push_dcp", "(", "event", ",", "callback", "...
29.454545
0.005988
def local_position_ned_send(self, time_boot_ms, x, y, z, vx, vy, vz, force_mavlink1=False): ''' The filtered local position (e.g. fused computer vision and accelerometers). Coordinate frame is right-handed, Z-axis down (aeronautical frame, NED / north-east...
[ "def", "local_position_ned_send", "(", "self", ",", "time_boot_ms", ",", "x", ",", "y", ",", "z", ",", "vx", ",", "vy", ",", "vz", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "local_position_ned_encode"...
56.294118
0.005139
def handle_startendtag(self, tag, attrs): """ Called when Cssparser finds a tag that does not have a closing tag, such as <meta>, or <link>. These tags have no data, so we just pass them forward. @param <string> tag The HTML tag we're currently parsing @param ...
[ "def", "handle_startendtag", "(", "self", ",", "tag", ",", "attrs", ")", ":", "dattrs", "=", "dict", "(", "attrs", ")", "if", "tag", ".", "lower", "(", ")", "==", "'link'", ":", "#print \"Found link\"", "if", "all", "(", "k", "in", "dattrs", "for", "...
47.884615
0.007874
def save_into_qrcode(text, out_filepath, color='', box_size=10, pixel_size=1850): """ Save `text` in a qrcode svg image file. Parameters ---------- text: str The string to be codified in the QR image. out_filepath: str Path to the output file color: str A RGB color exp...
[ "def", "save_into_qrcode", "(", "text", ",", "out_filepath", ",", "color", "=", "''", ",", "box_size", "=", "10", ",", "pixel_size", "=", "1850", ")", ":", "try", ":", "qr", "=", "qrcode", ".", "QRCode", "(", "version", "=", "1", ",", "error_correction...
30.71875
0.003945
def is_prime(n, rnd=default_pseudo_random, k=DEFAULT_ITERATION, algorithm=None): '''Test if n is a prime number m - the integer to test rnd - the random number generator to use for the probalistic primality algorithms, k - the number of iterations to use for the probabilist...
[ "def", "is_prime", "(", "n", ",", "rnd", "=", "default_pseudo_random", ",", "k", "=", "DEFAULT_ITERATION", ",", "algorithm", "=", "None", ")", ":", "if", "algorithm", "is", "None", ":", "algorithm", "=", "PRIME_ALGO", "if", "algorithm", "==", "'gmpy-miller-r...
36
0.000933
def fetchUser(self, username, rawResults = False) : """Returns a single user. if rawResults, the result will be a list of python dicts instead of User objects""" url = "%s/%s" % (self.URL, username) r = self.connection.session.get(url) if r.status_code == 200 : data = r.json...
[ "def", "fetchUser", "(", "self", ",", "username", ",", "rawResults", "=", "False", ")", ":", "url", "=", "\"%s/%s\"", "%", "(", "self", ".", "URL", ",", "username", ")", "r", "=", "self", ".", "connection", ".", "session", ".", "get", "(", "url", "...
38.214286
0.018248
def bivrandom (x0, y0, sx, sy, cxy, size=None): """Compute random values distributed according to the specified bivariate distribution. Inputs: * x0: the center of the x distribution (i.e. its intended mean) * y0: the center of the y distribution * sx: standard deviation (not variance) of x va...
[ "def", "bivrandom", "(", "x0", ",", "y0", ",", "sx", ",", "sy", ",", "cxy", ",", "size", "=", "None", ")", ":", "from", "numpy", ".", "random", "import", "multivariate_normal", "as", "mvn", "p0", "=", "np", ".", "asarray", "(", "[", "x0", ",", "y...
34.96
0.005568
def _clear_cache(tgt=None, tgt_type='glob', clear_pillar_flag=False, clear_grains_flag=False, clear_mine_flag=False, clear_mine_func_flag=None): ''' Clear the cached data/files for the targeted minions. ''' if tgt is No...
[ "def", "_clear_cache", "(", "tgt", "=", "None", ",", "tgt_type", "=", "'glob'", ",", "clear_pillar_flag", "=", "False", ",", "clear_grains_flag", "=", "False", ",", "clear_mine_flag", "=", "False", ",", "clear_mine_func_flag", "=", "None", ")", ":", "if", "t...
51.809524
0.001805
def get_neighborhood_at_voxel(image, center, kernel, physical_coordinates=False): """ Get a hypercube neighborhood at a voxel. Get the values in a local neighborhood of an image. ANTsR function: `getNeighborhoodAtVoxel` Arguments --------- image : ANTsImage image to get values...
[ "def", "get_neighborhood_at_voxel", "(", "image", ",", "center", ",", "kernel", ",", "physical_coordinates", "=", "False", ")", ":", "if", "not", "isinstance", "(", "image", ",", "iio", ".", "ANTsImage", ")", ":", "raise", "ValueError", "(", "'image must be AN...
33.25
0.009737
def immediateAspects(self, ID, aspList): """ Returns the last separation and next application considering a list of possible aspects. """ asps = self.aspectsByCat(ID, aspList) applications = asps[const.APPLICATIVE] separations = asps[const.SEPARATIVE] exact = as...
[ "def", "immediateAspects", "(", "self", ",", "ID", ",", "aspList", ")", ":", "asps", "=", "self", ".", "aspectsByCat", "(", "ID", ",", "aspList", ")", "applications", "=", "asps", "[", "const", ".", "APPLICATIVE", "]", "separations", "=", "asps", "[", ...
33.227273
0.00266
def get(self, instance, **kwargs): """Returns a list of Analyses assigned to this AR Return a list of catalog brains unless `full_objects=True` is passed. Other keyword arguments are passed to bika_analysis_catalog :param instance: Analysis Request object :param kwargs: Keyword...
[ "def", "get", "(", "self", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "catalog", "=", "getToolByName", "(", "instance", ",", "CATALOG_ANALYSIS_LISTING", ")", "query", "=", "dict", "(", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "i...
41.65
0.002347
def remove_entry_listener(self, registration_id): """ Removes the specified entry listener. Returns silently if there is no such listener added before. :param registration_id: (str), id of registered listener. :return: (bool), ``true`` if registration is removed, ``false`` otherwise. ...
[ "def", "remove_entry_listener", "(", "self", ",", "registration_id", ")", ":", "return", "self", ".", "_stop_listening", "(", "registration_id", ",", "lambda", "i", ":", "multi_map_remove_entry_listener_codec", ".", "encode_request", "(", "self", ".", "name", ",", ...
54.222222
0.010081
def psd(ts, nperseg=1500, noverlap=1200, plot=True): """plot Welch estimate of power spectral density, using nperseg samples per segment, with noverlap samples overlap and Hamming window.""" ts = ts.squeeze() if ts.ndim is 1: ts = ts.reshape((-1, 1)) fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts...
[ "def", "psd", "(", "ts", ",", "nperseg", "=", "1500", ",", "noverlap", "=", "1200", ",", "plot", "=", "True", ")", ":", "ts", "=", "ts", ".", "squeeze", "(", ")", "if", "ts", ".", "ndim", "is", "1", ":", "ts", "=", "ts", ".", "reshape", "(", ...
43.130435
0.000986
def sortby(self, ntd): """Return function for sorting.""" if 'reldepth' in self.grprobj.gosubdag.prt_attr['flds']: return [ntd.NS, -1*ntd.dcnt, ntd.reldepth] else: return [ntd.NS, -1*ntd.dcnt, ntd.depth]
[ "def", "sortby", "(", "self", ",", "ntd", ")", ":", "if", "'reldepth'", "in", "self", ".", "grprobj", ".", "gosubdag", ".", "prt_attr", "[", "'flds'", "]", ":", "return", "[", "ntd", ".", "NS", ",", "-", "1", "*", "ntd", ".", "dcnt", ",", "ntd", ...
41
0.007968
def join(self, *args): """Returns the arguments in the list joined by STR. FIRST,JOIN_BY,ARG_1,...,ARG_N %{JOIN: ,A,...,F} -> 'A B C ... F' """ call_args = list(args) joiner = call_args.pop(0) self.random.shuffle(call_args) return joiner.join(call_arg...
[ "def", "join", "(", "self", ",", "*", "args", ")", ":", "call_args", "=", "list", "(", "args", ")", "joiner", "=", "call_args", ".", "pop", "(", "0", ")", "self", ".", "random", ".", "shuffle", "(", "call_args", ")", "return", "joiner", ".", "join"...
31.3
0.006211
def commit(**kwargs): ''' To commit the changes loaded in the candidate configuration. dev_timeout : 30 The NETCONF RPC timeout (in seconds) comment Provide a comment for the commit confirm Provide time in minutes for commit confirmation. If this option is specified, the...
[ "def", "commit", "(", "*", "*", "kwargs", ")", ":", "conn", "=", "__proxy__", "[", "'junos.conn'", "]", "(", ")", "ret", "=", "{", "}", "op", "=", "dict", "(", ")", "if", "'__pub_arg'", "in", "kwargs", ":", "if", "kwargs", "[", "'__pub_arg'", "]", ...
30
0.000768
def _build_host_list(self, host_list_str): ''' This internal function takes the host string from the config file and turns it into a list :return: LIST host list ''' host_list = [] if isinstance(host_list_str, str): host_list = host_list_str.replace('...
[ "def", "_build_host_list", "(", "self", ",", "host_list_str", ")", ":", "host_list", "=", "[", "]", "if", "isinstance", "(", "host_list_str", ",", "str", ")", ":", "host_list", "=", "host_list_str", ".", "replace", "(", "' '", ",", "''", ")", ".", "split...
38.8
0.003356
def load_from_path(path): """ Load a spec from a given path, discovering specs if a directory is given. """ if os.path.isdir(path): paths = discover(path) else: paths = [path] for path in paths: name = os.path.basename(os.path.splitext(path)[0]) imp.load_source...
[ "def", "load_from_path", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "paths", "=", "discover", "(", "path", ")", "else", ":", "paths", "=", "[", "path", "]", "for", "path", "in", "paths", ":", "name", "=",...
22.785714
0.003012
def connect(self,soft_reset=False,**options): """ This just creates the websocket connection """ self._state = STATE_CONNECTING logger.debug("About to connect to {}".format(self.url)) m = re.search('(ws+)://([\w\.]+)(:?:(\d+))?',self.url) options['subprotocols'] = ['wam...
[ "def", "connect", "(", "self", ",", "soft_reset", "=", "False", ",", "*", "*", "options", ")", ":", "self", ".", "_state", "=", "STATE_CONNECTING", "logger", ".", "debug", "(", "\"About to connect to {}\"", ".", "format", "(", "self", ".", "url", ")", ")...
39.830986
0.005176
def silence(self, seq_set: SequenceSet, flag_set: AbstractSet[Flag], flag_op: FlagOp) -> None: """Runs the flags update against the cached flags, to prevent untagged FETCH responses unless other updates have occurred. For example, if a session adds ``\\Deleted`` and calls this m...
[ "def", "silence", "(", "self", ",", "seq_set", ":", "SequenceSet", ",", "flag_set", ":", "AbstractSet", "[", "Flag", "]", ",", "flag_op", ":", "FlagOp", ")", "->", "None", ":", "session_flags", "=", "self", ".", "session_flags", "permanent_flag_set", "=", ...
48.518519
0.002246
def update_file(self, value, relativePath, name=None, description=False, klass=False, dump=False, pull=False, ACID=None, verbose=False): """ Update the value and the utc timestamp of a file that is already in the Repository.\n...
[ "def", "update_file", "(", "self", ",", "value", ",", "relativePath", ",", "name", "=", "None", ",", "description", "=", "False", ",", "klass", "=", "False", ",", "dump", "=", "False", ",", "pull", "=", "False", ",", "ACID", "=", "None", ",", "verbos...
52.977011
0.007455
def deleteLogicalInterface(self, logicalInterfaceId): """ Deletes a logical interface. Parameters: logicalInterfaceId (string). Throws APIException on failure. """ req = ApiClient.oneLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId) resp = requests.d...
[ "def", "deleteLogicalInterface", "(", "self", ",", "logicalInterfaceId", ")", ":", "req", "=", "ApiClient", ".", "oneLogicalInterfaceUrl", "%", "(", "self", ".", "host", ",", "\"/draft\"", ",", "logicalInterfaceId", ")", "resp", "=", "requests", ".", "delete", ...
45.846154
0.006579
def add_new_data_port(self): """Add a new port with default values and select it""" try: new_data_port_ids = gui_helper_state_machine.add_data_port_to_selected_states('OUTPUT', int, [self.model]) if new_data_port_ids: self.select_entry(new_data_port_ids[self.model...
[ "def", "add_new_data_port", "(", "self", ")", ":", "try", ":", "new_data_port_ids", "=", "gui_helper_state_machine", ".", "add_data_port_to_selected_states", "(", "'OUTPUT'", ",", "int", ",", "[", "self", ".", "model", "]", ")", "if", "new_data_port_ids", ":", "...
45.625
0.008065
def service_count(self, block_identifier: BlockSpecification) -> int: """Get the number of registered services""" result = self.proxy.contract.functions.serviceCount().call( block_identifier=block_identifier, ) return result
[ "def", "service_count", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ")", "->", "int", ":", "result", "=", "self", ".", "proxy", ".", "contract", ".", "functions", ".", "serviceCount", "(", ")", ".", "call", "(", "block_identifier", "=", ...
43.833333
0.007463
def parse_genotype(variant, ind, pos): """Get the genotype information in the proper format Sv specific format fields: ##FORMAT=<ID=DV,Number=1,Type=Integer, Description="Number of paired-ends that support the event"> ##FORMAT=<ID=PE,Number=1,Type=Integer, Description="Number of paired-ends t...
[ "def", "parse_genotype", "(", "variant", ",", "ind", ",", "pos", ")", ":", "gt_call", "=", "{", "}", "ind_id", "=", "ind", "[", "'individual_id'", "]", "gt_call", "[", "'individual_id'", "]", "=", "ind_id", "gt_call", "[", "'display_name'", "]", "=", "in...
30.659218
0.001059
def constraint(self): """Constraint string""" constraint_arr = [] if self._not_null: constraint_arr.append("PRIMARY KEY" if self._pk else "NOT NULL") if self._unique: constraint_arr.append("UNIQUE") return " ".join(constraint_arr)
[ "def", "constraint", "(", "self", ")", ":", "constraint_arr", "=", "[", "]", "if", "self", ".", "_not_null", ":", "constraint_arr", ".", "append", "(", "\"PRIMARY KEY\"", "if", "self", ".", "_pk", "else", "\"NOT NULL\"", ")", "if", "self", ".", "_unique", ...
31.888889
0.00678
def copy_helper(app_or_project, name, directory, dist, template_dir, noadmin): """ Replacement for django copy_helper Copies a Django project layout template into the specified distribution directory """ import shutil if not re.search(r'^[_a-zA-Z]\w*$', name): # If it's not a valid direct...
[ "def", "copy_helper", "(", "app_or_project", ",", "name", ",", "directory", ",", "dist", ",", "template_dir", ",", "noadmin", ")", ":", "import", "shutil", "if", "not", "re", ".", "search", "(", "r'^[_a-zA-Z]\\w*$'", ",", "name", ")", ":", "# If it's not a v...
42.795918
0.005128
def register_package(pkg): """ Allow to register packages by loading and exposing: templates, static, and exceptions for abort() Structure of package root | $package_name | __init__.py | | exceptions.py | ...
[ "def", "register_package", "(", "pkg", ")", ":", "root_pkg_dir", "=", "pkg", "if", "not", "os", ".", "path", ".", "isdir", "(", "pkg", ")", "and", "\".\"", "in", "pkg", ":", "root_pkg_dir", "=", "utils", ".", "get_pkg_resources_filename", "(", "pkg", ")"...
31.217391
0.000675
def _fixSize(self): """Fix the menu size. Commonly called when the font is changed""" self.height = 0 for o in self.options: text = o['label'] font = o['font'] ren = font.render(text, 1, (0, 0, 0)) if ren.get_width() > self.width: s...
[ "def", "_fixSize", "(", "self", ")", ":", "self", ".", "height", "=", "0", "for", "o", "in", "self", ".", "options", ":", "text", "=", "o", "[", "'label'", "]", "font", "=", "o", "[", "'font'", "]", "ren", "=", "font", ".", "render", "(", "text...
38.3
0.005102
def _fetch_langs(): """Fetch (scrape) languages from Google Translate. Google Translate loads a JavaScript Array of 'languages codes' that can be spoken. We intersect this list with all the languages Google Translate provides to get the ones that support text-to-speech. Returns: dict: A di...
[ "def", "_fetch_langs", "(", ")", ":", "# Load HTML", "page", "=", "requests", ".", "get", "(", "URL_BASE", ")", "soup", "=", "BeautifulSoup", "(", "page", ".", "content", ",", "'html.parser'", ")", "# JavaScript URL", "# The <script src=''> path can change, but not ...
42.875
0.00171
def extract_forward_and_reverse_complement( self, forward_reads_to_extract, reverse_reads_to_extract, database_fasta_file, output_file): '''As per extract except also reverse complement the sequences.''' self.extract(forward_reads_to_extract, database_fasta_file, output_file) ...
[ "def", "extract_forward_and_reverse_complement", "(", "self", ",", "forward_reads_to_extract", ",", "reverse_reads_to_extract", ",", "database_fasta_file", ",", "output_file", ")", ":", "self", ".", "extract", "(", "forward_reads_to_extract", ",", "database_fasta_file", ","...
52
0.005814
def integrate(self, dim, datetime_unit=None): """ integrate the array with the trapezoidal rule. .. note:: This feature is limited to simple cartesian geometry, i.e. coord must be one dimensional. Parameters ---------- dim: str, or a sequence of str ...
[ "def", "integrate", "(", "self", ",", "dim", ",", "datetime_unit", "=", "None", ")", ":", "ds", "=", "self", ".", "_to_temp_dataset", "(", ")", ".", "integrate", "(", "dim", ",", "datetime_unit", ")", "return", "self", ".", "_from_temp_dataset", "(", "ds...
30.978261
0.001361
def _format_human(self, payload): """Convert the payload into an ASCII table suitable for printing on screen and return it. """ page = None total_pages = None # What are the columns we will show? columns = [field.name for field in self.resource.fields ...
[ "def", "_format_human", "(", "self", ",", "payload", ")", ":", "page", "=", "None", "total_pages", "=", "None", "# What are the columns we will show?", "columns", "=", "[", "field", ".", "name", "for", "field", "in", "self", ".", "resource", ".", "fields", "...
39.525862
0.000426
def service( state, host, *args, **kwargs ): ''' Manage the state of services. This command checks for the presence of all the init systems pyinfra can handle and executes the relevant operation. See init system sepcific operation for arguments. ''' if host.fact.which('systemctl'): ...
[ "def", "service", "(", "state", ",", "host", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "host", ".", "fact", ".", "which", "(", "'systemctl'", ")", ":", "yield", "systemd", "(", "state", ",", "host", ",", "*", "args", ",", "*", ...
26.6
0.003628
def build_routes(iface, **settings): ''' Build a route script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_routes eth0 <settings> ''' template = 'rh6_route_eth.jinja' try: if int(__grains__['osrelease'][0]) < 6: template = 'rout...
[ "def", "build_routes", "(", "iface", ",", "*", "*", "settings", ")", ":", "template", "=", "'rh6_route_eth.jinja'", "try", ":", "if", "int", "(", "__grains__", "[", "'osrelease'", "]", "[", "0", "]", ")", "<", "6", ":", "template", "=", "'route_eth.jinja...
29.092593
0.000616
def is_default_port(self): """A check for default port. Return True if port is default for specified scheme, e.g. 'http://python.org' or 'http://python.org:80', False otherwise. """ if self.port is None: return False default = DEFAULT_PORTS.get(self....
[ "def", "is_default_port", "(", "self", ")", ":", "if", "self", ".", "port", "is", "None", ":", "return", "False", "default", "=", "DEFAULT_PORTS", ".", "get", "(", "self", ".", "scheme", ")", "if", "default", "is", "None", ":", "return", "False", "retu...
28.785714
0.004808
def _note_reply_pending(self, option, state): """Record the status of requested Telnet options.""" if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() self.telnet_opt_dict[option].reply_pending = state
[ "def", "_note_reply_pending", "(", "self", ",", "option", ",", "state", ")", ":", "if", "not", "self", ".", "telnet_opt_dict", ".", "has_key", "(", "option", ")", ":", "self", ".", "telnet_opt_dict", "[", "option", "]", "=", "TelnetOption", "(", ")", "se...
54.4
0.01087
def log(lines, log_file=None): """Output log message.""" err = False for line in lines: print(line) if log_file is not None: UtilClass.writelog(log_file, line, 'append') if 'BAD TERMINATION' in line.upper(): err = True ...
[ "def", "log", "(", "lines", ",", "log_file", "=", "None", ")", ":", "err", "=", "False", "for", "line", "in", "lines", ":", "print", "(", "line", ")", "if", "log_file", "is", "not", "None", ":", "UtilClass", ".", "writelog", "(", "log_file", ",", "...
36.166667
0.006742
def add(self, operator): '''Add an operation to this pump. Parameters ---------- operator : BaseTaskTransformer, FeatureExtractor The operation to add Raises ------ ParameterError if `op` is not of a correct type ''' if no...
[ "def", "add", "(", "self", ",", "operator", ")", ":", "if", "not", "isinstance", "(", "operator", ",", "(", "BaseTaskTransformer", ",", "FeatureExtractor", ")", ")", ":", "raise", "ParameterError", "(", "'operator={} must be one of '", "'(BaseTaskTransformer, Featur...
33.48
0.002323
def replace(self, year=None, month=None, day=None): """Return a new date with new values for the specified fields.""" if year is None: year = self._year if month is None: month = self._month if day is None: day = self._day _check_date_fields(ye...
[ "def", "replace", "(", "self", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ")", ":", "if", "year", "is", "None", ":", "year", "=", "self", ".", "_year", "if", "month", "is", "None", ":", "month", "=", "self", "...
36.4
0.005362
def run(): """ Run loop """ while NonBlockingStreamReader._run_flag: # Wait for streams to appear if not NonBlockingStreamReader._streams: time.sleep(0.2) continue # Try to get correct select/poll method for this OS ...
[ "def", "run", "(", ")", ":", "while", "NonBlockingStreamReader", ".", "_run_flag", ":", "# Wait for streams to appear", "if", "not", "NonBlockingStreamReader", ".", "_streams", ":", "time", ".", "sleep", "(", "0.2", ")", "continue", "# Try to get correct select/poll m...
35.9
0.002712
def validate_uses_tls_for_glance(audit_options): """Verify that TLS is used to communicate with Glance.""" section = _config_section(audit_options, 'glance') assert section is not None, "Missing section 'glance'" assert not section.get('insecure') and \ "https://" in section.get("api_servers"), ...
[ "def", "validate_uses_tls_for_glance", "(", "audit_options", ")", ":", "section", "=", "_config_section", "(", "audit_options", ",", "'glance'", ")", "assert", "section", "is", "not", "None", ",", "\"Missing section 'glance'\"", "assert", "not", "section", ".", "get...
50.285714
0.002793
def _post_login_page(self): """Login to Janrain.""" # Prepare post data data = { "form": "signInForm", "client_id": JANRAIN_CLIENT_ID, "redirect_uri": "https://www.fido.ca/pages/#/", "response_type": "token", "locale": "en-US", ...
[ "def", "_post_login_page", "(", "self", ")", ":", "# Prepare post data", "data", "=", "{", "\"form\"", ":", "\"signInForm\"", ",", "\"client_id\"", ":", "JANRAIN_CLIENT_ID", ",", "\"redirect_uri\"", ":", "\"https://www.fido.ca/pages/#/\"", ",", "\"response_type\"", ":",...
35.863636
0.002469
def writeInput(self, session, directory, name): """ Write only input files for a GSSHA project from the database to file. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database directory (str): Directory where t...
[ "def", "writeInput", "(", "self", ",", "session", ",", "directory", ",", "name", ")", ":", "self", ".", "project_directory", "=", "directory", "with", "tmp_chdir", "(", "directory", ")", ":", "# Get param file for writing", "replaceParamFile", "=", "self", ".", ...
53.68
0.005857
def handler(self, path='/app', mode='debug'): """ Handler that executes the application build based on its platform (using the ``project`` package). param: path(str): the project source code path, default is '/app'. param: target(str): the platform target, android-23 is the default for android platform...
[ "def", "handler", "(", "self", ",", "path", "=", "'/app'", ",", "mode", "=", "'debug'", ")", ":", "options", "=", "{", "'path'", ":", "path", "}", "project", "=", "builds", ".", "from_path", "(", "path", ")", "project", ".", "prepare", "(", ")", "p...
33.882353
0.005068
def validate(self, instance): """Validates the given document against this schema. Raises a ValidationException if there are any failures.""" errors = {} self._validate_instance(instance, errors) if len(errors) > 0: raise ValidationException(errors)
[ "def", "validate", "(", "self", ",", "instance", ")", ":", "errors", "=", "{", "}", "self", ".", "_validate_instance", "(", "instance", ",", "errors", ")", "if", "len", "(", "errors", ")", ">", "0", ":", "raise", "ValidationException", "(", "errors", "...
36.875
0.006623
def user_context(self, worker_ctx, exc_info): """ Merge any user context to include in the sentry payload. Extracts user identifiers from the worker context data by matching context keys with """ user = {} for key in worker_ctx.context_data: for matcher in se...
[ "def", "user_context", "(", "self", ",", "worker_ctx", ",", "exc_info", ")", ":", "user", "=", "{", "}", "for", "key", "in", "worker_ctx", ".", "context_data", ":", "for", "matcher", "in", "self", ".", "user_type_context_keys", ":", "if", "re", ".", "sea...
36
0.003868
def port_profile_qos_profile_qos_flowcontrol_pfc_pfc_cos(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") name_key = ET.SubElement(port_profile, "name"...
[ "def", "port_profile_qos_profile_qos_flowcontrol_pfc_pfc_cos", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "port_profile", "=", "ET", ".", "SubElement", "(", "config", ",", "\"port-profile\"", ",",...
46.875
0.003922
def toHTML(self, pathogenPanelFilename=None, minProteinFraction=0.0, pathogenType='viral', sampleIndexFilename=None, pathogenIndexFilename=None): """ Produce an HTML string representation of the pathogen summary. @param pathogenPanelFilename: If not C{None}, a C{st...
[ "def", "toHTML", "(", "self", ",", "pathogenPanelFilename", "=", "None", ",", "minProteinFraction", "=", "0.0", ",", "pathogenType", "=", "'viral'", ",", "sampleIndexFilename", "=", "None", ",", "pathogenIndexFilename", "=", "None", ")", ":", "if", "pathogenType...
40.359494
0.000245
def authenticate(self): """authenticate the user with the Kaggle API. This method will generate a configuration, first checking the environment for credential variables, and falling back to looking for the .kaggle/kaggle.json configuration file. """ config_data ...
[ "def", "authenticate", "(", "self", ")", ":", "config_data", "=", "{", "}", "# Step 1: try getting username/password from environment", "config_data", "=", "self", ".", "read_config_environment", "(", "config_data", ")", "# Step 2: if credentials were not in env read in configu...
44
0.001854
def find_files(directory, pattern, recursively=True): """ Yield a list of files with their base directories, recursively or not. Returns: A list of (base_directory, filename) Args: directory: base directory to start the search. pattern: fnmatch pattern for filenames. co...
[ "def", "find_files", "(", "directory", ",", "pattern", ",", "recursively", "=", "True", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "directory", ")", ":", "for", "basename", "in", "files", ":", "if", "fnmatch", "...
30.8
0.001575