text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _before_valid_time_range(self): """ In case of uncertainty (times not specified), we assume that we are in a valid range. """ if self.start_time is not None: try: if self.time < self.start_time: return True except TypeError:...
[ "def", "_before_valid_time_range", "(", "self", ")", ":", "if", "self", ".", "start_time", "is", "not", "None", ":", "try", ":", "if", "self", ".", "time", "<", "self", ".", "start_time", ":", "return", "True", "except", "TypeError", ":", "return", "Fals...
32.727273
0.008108
def get_suggestion(self, front_path): """ Returns suggestions for a path. Used in tab completion from the command line. """ if '/' in front_path: # transverse the manifest, return the new manifest, then # get those suggestions with the remaining word ...
[ "def", "get_suggestion", "(", "self", ",", "front_path", ")", ":", "if", "'/'", "in", "front_path", ":", "# transverse the manifest, return the new manifest, then", "# get those suggestions with the remaining word", "splitted", "=", "front_path", ".", "split", "(", "'/'", ...
36.576923
0.002049
def display_weyl(decomps): """Construct and display 3D plot of canonical coordinates""" tx, ty, tz = list(zip(*decomps)) rcParams['axes.labelsize'] = 24 rcParams['font.family'] = 'serif' rcParams['font.serif'] = ['Computer Modern Roman'] rcParams['text.usetex'] = True fig = pyplot.figure() ...
[ "def", "display_weyl", "(", "decomps", ")", ":", "tx", ",", "ty", ",", "tz", "=", "list", "(", "zip", "(", "*", "decomps", ")", ")", "rcParams", "[", "'axes.labelsize'", "]", "=", "24", "rcParams", "[", "'font.family'", "]", "=", "'serif'", "rcParams",...
35.904762
0.00043
def readGif(filename, asNumpy=True): """ readGif(filename, asNumpy=True) Read images from an animated GIF file. Returns a list of numpy arrays, or, if asNumpy is false, a list if PIL images. """ # Check PIL if PIL is None: raise RuntimeError("Need PIL to read animated gif files.") ...
[ "def", "readGif", "(", "filename", ",", "asNumpy", "=", "True", ")", ":", "# Check PIL", "if", "PIL", "is", "None", ":", "raise", "RuntimeError", "(", "\"Need PIL to read animated gif files.\"", ")", "# Check Numpy", "if", "np", "is", "None", ":", "raise", "Ru...
26.270833
0.001529
async def set_property_value(self, turn_context: TurnContext, property_name: str, value: object) -> None: """ Deletes a property from the state cache in the turn context. :param turn_context: The context object for this turn. :param property_name: The value to set on the propert...
[ "async", "def", "set_property_value", "(", "self", ",", "turn_context", ":", "TurnContext", ",", "property_name", ":", "str", ",", "value", ":", "object", ")", "->", "None", ":", "if", "turn_context", "==", "None", ":", "raise", "TypeError", "(", "'BotState....
47.4
0.009655
def inbreeding_coefficient(g, fill=np.nan): """Calculate the inbreeding coefficient for each variant. Parameters ---------- g : array_like, int, shape (n_variants, n_samples, ploidy) Genotype array. fill : float, optional Use this value for variants where the expected heterozygosit...
[ "def", "inbreeding_coefficient", "(", "g", ",", "fill", "=", "np", ".", "nan", ")", ":", "# check inputs", "if", "not", "hasattr", "(", "g", ",", "'count_het'", ")", "or", "not", "hasattr", "(", "g", ",", "'count_called'", ")", ":", "g", "=", "Genotype...
28.557692
0.000651
def boundary(ax, scale, axes_colors=None, **kwargs): """ Plots the boundary of the simplex. Creates and returns matplotlib axis if none given. Parameters ---------- ax: Matplotlib AxesSubplot, None The subplot to draw on. scale: float Simplex scale size. kwargs: ...
[ "def", "boundary", "(", "ax", ",", "scale", ",", "axes_colors", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Set default color as black.", "if", "axes_colors", "is", "None", ":", "axes_colors", "=", "dict", "(", ")", "for", "_axis", "in", "[", "'l'...
31.827586
0.001052
def confirm_email(self, request, email_address): """ Marks the email address as confirmed on the db """ email_address.verified = True email_address.set_as_primary(conditional=True) email_address.save()
[ "def", "confirm_email", "(", "self", ",", "request", ",", "email_address", ")", ":", "email_address", ".", "verified", "=", "True", "email_address", ".", "set_as_primary", "(", "conditional", "=", "True", ")", "email_address", ".", "save", "(", ")" ]
34.714286
0.008032
def astype(self, dtype): """Return a copy of this space with new ``dtype``. Parameters ---------- dtype : Scalar data type of the returned space. Can be provided in any way the `numpy.dtype` constructor understands, e.g. as built-in type or as a strin...
[ "def", "astype", "(", "self", ",", "dtype", ")", ":", "if", "dtype", "is", "None", ":", "# Need to filter this out since Numpy iterprets it as 'float'", "raise", "ValueError", "(", "'`None` is not a valid data type'", ")", "dtype", "=", "np", ".", "dtype", "(", "dty...
35.815789
0.001431
def get_objective_banks_by_activity(self, *args, **kwargs): """Pass through to provider ActivityObjectiveBankSession.get_objective_banks_by_activity""" # Implemented from kitosid template for - # osid.resource.ResourceBinSession.get_bins_by_resource catalogs = self._get_provider_session(...
[ "def", "get_objective_banks_by_activity", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.ResourceBinSession.get_bins_by_resource", "catalogs", "=", "self", ".", "_get_provider_session", "(", "'...
65.444444
0.008375
def power_cycle_vm(virtual_machine, action='on'): ''' Powers on/off a virtual machine specified by it's name. virtual_machine vim.VirtualMachine object to power on/off virtual machine action Operation option to power on/off the machine ''' if action == 'on': try: ...
[ "def", "power_cycle_vm", "(", "virtual_machine", ",", "action", "=", "'on'", ")", ":", "if", "action", "==", "'on'", ":", "try", ":", "task", "=", "virtual_machine", ".", "PowerOn", "(", ")", "task_name", "=", "'power on'", "except", "vim", ".", "fault", ...
39.061224
0.001529
def get_simple_date(datestring): """Transforms a datestring into shorter date 7.9.2017 > 07.09 Expects the datestring to be format 07.09.2017. If this is not the case, returns string "Failed". Keyword arguments: datestring -- a string Returns: String -- The date in format "dd.MM." or "Fai...
[ "def", "get_simple_date", "(", "datestring", ")", ":", "simple_date", "=", "re", ".", "compile", "(", "r\"\\d{1,2}(\\.)\\d{1,2}\"", ")", "date", "=", "simple_date", ".", "search", "(", "datestring", ")", "if", "date", ":", "dates", "=", "date", ".", "group",...
29.208333
0.001381
def psnr(test, ref, mask=None): """Peak Signal-to-Noise Ratio (PSNR) Calculate the PSNR between a test image and a reference image. Parameters ---------- ref : np.ndarray the reference image test : np.ndarray the tested image mask : np.ndarray, optional the mask for...
[ "def", "psnr", "(", "test", ",", "ref", ",", "mask", "=", "None", ")", ":", "test", ",", "ref", ",", "mask", "=", "_preprocess_input", "(", "test", ",", "ref", ",", "mask", ")", "if", "mask", "is", "not", "None", ":", "test", "=", "mask", "*", ...
19.176471
0.00146
def add_op_create_erasure_pool(self, name, erasure_profile=None, weight=None, group=None, app_name=None, max_bytes=None, max_objects=None): """Adds an operation to create a erasure coded pool. :param name: Name of pool to create ...
[ "def", "add_op_create_erasure_pool", "(", "self", ",", "name", ",", "erasure_profile", "=", "None", ",", "weight", "=", "None", ",", "group", "=", "None", ",", "app_name", "=", "None", ",", "max_bytes", "=", "None", ",", "max_objects", "=", "None", ")", ...
52.15625
0.002353
def parse_cell(self, cell, coords, cell_mode=CellMode.cooked): """Parses a cell according to its cell.value_type.""" # pylint: disable=too-many-return-statements if cell_mode == CellMode.cooked: if cell.covered or cell.value_type is None or cell.value is None: return None vtype = cell.v...
[ "def", "parse_cell", "(", "self", ",", "cell", ",", "coords", ",", "cell_mode", "=", "CellMode", ".", "cooked", ")", ":", "# pylint: disable=too-many-return-statements", "if", "cell_mode", "==", "CellMode", ".", "cooked", ":", "if", "cell", ".", "covered", "or...
34.15625
0.009786
def __error_message(self,stanza): """Process an error message from a MUC room. :Parameters: - `stanza`: the stanza received. :Types: - `stanza`: `Message` :return: `True` if the message was properly recognized as directed to one of the managed rooms,...
[ "def", "__error_message", "(", "self", ",", "stanza", ")", ":", "fr", "=", "stanza", ".", "get_from", "(", ")", "key", "=", "fr", ".", "bare", "(", ")", ".", "as_unicode", "(", ")", "rs", "=", "self", ".", "rooms", ".", "get", "(", "key", ")", ...
30.722222
0.010526
def psdump(self, filename=None, **kargs): """ psdump(filename=None, layer_shift=0, rebuild=1) Creates an EPS file describing a packet. If filename is not provided a temporary file is created and gs is called. :param filename: the file's filename """ from scapy.c...
[ "def", "psdump", "(", "self", ",", "filename", "=", "None", ",", "*", "*", "kargs", ")", ":", "from", "scapy", ".", "config", "import", "conf", "from", "scapy", ".", "utils", "import", "get_temp_file", ",", "ContextManagerSubprocess", "canvas", "=", "self"...
38.913043
0.002181
def _execute(self) -> None: '''Run Fixture actions (setup, run, check). Core test loop for Fixture. Executes setup, run, and check in order. ''' if hasattr(self, '_last_resolver_exception'): logger.warning('last exception from %s.%s:', self.__class__.__name__, self._last_...
[ "def", "_execute", "(", "self", ")", "->", "None", ":", "if", "hasattr", "(", "self", ",", "'_last_resolver_exception'", ")", ":", "logger", ".", "warning", "(", "'last exception from %s.%s:'", ",", "self", ".", "__class__", ".", "__name__", ",", "self", "."...
33.615385
0.011136
def _getOpenID1SessionType(self, assoc_response): """Given an association response message, extract the OpenID 1.X session type. This function mostly takes care of the 'no-encryption' default behavior in OpenID 1. If the association type is plain-text, this function will ...
[ "def", "_getOpenID1SessionType", "(", "self", ",", "assoc_response", ")", ":", "# If it's an OpenID 1 message, allow session_type to default", "# to None (which signifies \"no-encryption\")", "session_type", "=", "assoc_response", ".", "getArg", "(", "OPENID1_NS", ",", "'session_...
38.594595
0.002049
def get_container_info(self, obj): """Returns the info for a Container """ info = self.get_base_info(obj) info.update({}) return info
[ "def", "get_container_info", "(", "self", ",", "obj", ")", ":", "info", "=", "self", ".", "get_base_info", "(", "obj", ")", "info", ".", "update", "(", "{", "}", ")", "return", "info" ]
28
0.011561
def _evaluate(self,R,z,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at R,z, phi INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,...
[ "def", "_evaluate", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "#Cylindrical distance", "Rdist", "=", "_cylR", "(", "R", ",", "phi", ",", "self", ".", "_orb", ".", "R", "(", "t", ")", ",", "self", "...
31.952381
0.02026
def deploy(target): """Deploys the package and documentation. Proceeds in the following steps: 1. Ensures proper environment variables are set and checks that we are on Circle CI 2. Tags the repository with the new version 3. Creates a standard distribution and a wheel 4. Updates version.py to...
[ "def", "deploy", "(", "target", ")", ":", "# Ensure proper environment", "if", "not", "os", ".", "getenv", "(", "CIRCLECI_ENV_VAR", ")", ":", "# pragma: no cover", "raise", "EnvironmentError", "(", "'Must be on CircleCI to run this script'", ")", "current_branch", "=", ...
39.768293
0.002095
def Likelihood(self, data, hypo): """The likelihood of the data under the hypothesis. data: string cookie type hypo: string bowl ID """ mix = self.loci[hypo] like = mix[data] return like
[ "def", "Likelihood", "(", "self", ",", "data", ",", "hypo", ")", ":", "mix", "=", "self", ".", "loci", "[", "hypo", "]", "like", "=", "mix", "[", "data", "]", "return", "like" ]
29.375
0.008264
def t_STATE(self, token): ur'-\s\((?P<state>[A-Z]{2}):(?P<continent>[_A-Za-z ]+)(:(?P<friendly_id>[A-Za-z_]+))?\)\s(?P<name>[A-Z].+?[^ ])\n' state = token.lexer.lexmatch.group("state").decode("utf8") continent = token.lexer.lexmatch.group("continent").decode("utf8") name = token.lexer.le...
[ "def", "t_STATE", "(", "self", ",", "token", ")", ":", "state", "=", "token", ".", "lexer", ".", "lexmatch", ".", "group", "(", "\"state\"", ")", ".", "decode", "(", "\"utf8\"", ")", "continent", "=", "token", ".", "lexer", ".", "lexmatch", ".", "gro...
51.615385
0.010249
def _update_data(self, name, value, timestamp, interval, config, conn): '''Support function for insert. Should be called within a transaction''' i_time = config['i_calc'].to_bucket(timestamp) if not config['coarse']: r_time = config['r_calc'].to_bucket(timestamp) else: r_time = None stmt...
[ "def", "_update_data", "(", "self", ",", "name", ",", "value", ",", "timestamp", ",", "interval", ",", "config", ",", "conn", ")", ":", "i_time", "=", "config", "[", "'i_calc'", "]", ".", "to_bucket", "(", "timestamp", ")", "if", "not", "config", "[", ...
37.4375
0.014658
def update_backend(self, service_id, version_number, name_key, **kwargs): """Update the backend for a particular service and version.""" body = self._formdata(kwargs, FastlyBackend.FIELDS) content = self._fetch("/service/%s/version/%d/backend/%s" % (service_id, version_number, name_key), method="PUT", body=body) ...
[ "def", "update_backend", "(", "self", ",", "service_id", ",", "version_number", ",", "name_key", ",", "*", "*", "kwargs", ")", ":", "body", "=", "self", ".", "_formdata", "(", "kwargs", ",", "FastlyBackend", ".", "FIELDS", ")", "content", "=", "self", "....
70.6
0.019608
def get_last_activity(session): """ Get the last activity datetime string from the session and return the python datetime object. """ try: return datetime.strptime(session['_session_security'], '%Y-%m-%dT%H:%M:%S.%f') except AttributeError: #######################...
[ "def", "get_last_activity", "(", "session", ")", ":", "try", ":", "return", "datetime", ".", "strptime", "(", "session", "[", "'_session_security'", "]", ",", "'%Y-%m-%dT%H:%M:%S.%f'", ")", "except", "AttributeError", ":", "##############################################...
41.178571
0.001695
def partition_horizontal_twice(thelist, numbers): """ numbers is split on a comma to n and n2. Break a list into peices each peice alternating between n and n2 items long ``partition_horizontal_twice(range(14), "3,4")`` gives:: [[0, 1, 2], [3, 4, 5, 6], [7, 8, 9], ...
[ "def", "partition_horizontal_twice", "(", "thelist", ",", "numbers", ")", ":", "n", ",", "n2", "=", "numbers", ".", "split", "(", "','", ")", "try", ":", "n", "=", "int", "(", "n", ")", "n2", "=", "int", "(", "n2", ")", "thelist", "=", "list", "(...
26.37037
0.00813
def delete_namespaced_endpoints(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_endpoints # noqa: E501 delete Endpoints # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >...
[ "def", "delete_namespaced_endpoints", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "retur...
94.535714
0.000748
def ds9_objects_to_string(regions, coordsys='fk5', fmt='.6f', radunit='deg'): """ Converts a `list` of `~regions.Region` to DS9 region string. Parameters ---------- regions : `list` List of `~regions.Region` objects coordsys : `str`, optional This overrides the coordinate system...
[ "def", "ds9_objects_to_string", "(", "regions", ",", "coordsys", "=", "'fk5'", ",", "fmt", "=", "'.6f'", ",", "radunit", "=", "'deg'", ")", ":", "shapelist", "=", "to_shape_list", "(", "regions", ",", "coordsys", ")", "return", "shapelist", ".", "to_ds9", ...
33.542857
0.000828
def current_parameters(self): """ Obtains an array with the current parameters """ current = [] for core_param in range(len(self.q)): for approx_param in range(self.q[core_param].param_no): current.append(self.q[core_param].vi_return_param(approx_param...
[ "def", "current_parameters", "(", "self", ")", ":", "current", "=", "[", "]", "for", "core_param", "in", "range", "(", "len", "(", "self", ".", "q", ")", ")", ":", "for", "approx_param", "in", "range", "(", "self", ".", "q", "[", "core_param", "]", ...
38.555556
0.008451
def _repr_html_(self): """Generates the HTML representation. """ parts = [] if self._class: parts.append('<div id="hh_%s" class="%s">%s</div>' % (self._id, self._class, self._markup)) else: parts.append('<div id="hh_%s">%s</div>' % (self._id, self._markup)) if len(self._script) != 0...
[ "def", "_repr_html_", "(", "self", ")", ":", "parts", "=", "[", "]", "if", "self", ".", "_class", ":", "parts", ".", "append", "(", "'<div id=\"hh_%s\" class=\"%s\">%s</div>'", "%", "(", "self", ".", "_id", ",", "self", ".", "_class", ",", "self", ".", ...
32.47619
0.018519
def execute(self, args, kwargs): ''' Dispatch a call. Call the first function whose type signature matches the arguemts. ''' return self.lookup_explicit(args, kwargs)(*args, **kwargs)
[ "def", "execute", "(", "self", ",", "args", ",", "kwargs", ")", ":", "return", "self", ".", "lookup_explicit", "(", "args", ",", "kwargs", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
36.333333
0.008969
def randpath(self): """ -> a random URI-like #str path """ return '/'.join( gen_rand_str(3, 10, use=self.random, keyspace=list(self.keyspace)) for _ in range(self.random.randint(0, 3)))
[ "def", "randpath", "(", "self", ")", ":", "return", "'/'", ".", "join", "(", "gen_rand_str", "(", "3", ",", "10", ",", "use", "=", "self", ".", "random", ",", "keyspace", "=", "list", "(", "self", ".", "keyspace", ")", ")", "for", "_", "in", "ran...
44.2
0.008889
def sign_request(private_key, method, endpoint, body_bytes, headers): """ :type private_key: RSA.RsaKey :type method: str :type endpoint: str :type body_bytes: bytes :type headers: dict[str, str] :rtype: str """ head_bytes = _generate_request_head_bytes(method, endpoint, headers) ...
[ "def", "sign_request", "(", "private_key", ",", "method", ",", "endpoint", ",", "body_bytes", ",", "headers", ")", ":", "head_bytes", "=", "_generate_request_head_bytes", "(", "method", ",", "endpoint", ",", "headers", ")", "bytes_to_sign", "=", "head_bytes", "+...
26.473684
0.001919
def chain(cls, *iterables): """ Similar to #itertools.chain.from_iterable(). """ def generator(): for it in iterables: for element in it: yield element return cls(generator())
[ "def", "chain", "(", "cls", ",", "*", "iterables", ")", ":", "def", "generator", "(", ")", ":", "for", "it", "in", "iterables", ":", "for", "element", "in", "it", ":", "yield", "element", "return", "cls", "(", "generator", "(", ")", ")" ]
21.1
0.013636
def get(ns, dburl=None): ''' Get a default dones object for ns. If no dones object exists for ns yet, a DbDones object will be created, cached, and returned. ''' if dburl is None: dburl = DONES_DB_URL cache_key = (ns, dburl) if ns not in DONES_CACHE: dones_ns = 'dones_{}'.f...
[ "def", "get", "(", "ns", ",", "dburl", "=", "None", ")", ":", "if", "dburl", "is", "None", ":", "dburl", "=", "DONES_DB_URL", "cache_key", "=", "(", "ns", ",", "dburl", ")", "if", "ns", "not", "in", "DONES_CACHE", ":", "dones_ns", "=", "'dones_{}'", ...
29.857143
0.00232
def _handle_exception(ignore_callback_errors, print_callback_errors, obj, cb_event=None, node=None): """Helper for prining errors in callbacks See EventEmitter._invoke_callback for a use example. """ if not hasattr(obj, '_vispy_err_registry'): obj._vispy_err_registry = {} ...
[ "def", "_handle_exception", "(", "ignore_callback_errors", ",", "print_callback_errors", ",", "obj", ",", "cb_event", "=", "None", ",", "node", "=", "None", ")", ":", "if", "not", "hasattr", "(", "obj", ",", "'_vispy_err_registry'", ")", ":", "obj", ".", "_v...
36.389831
0.000454
def _get_a1_value(bbar, dbar, slip, beta, mmax): """ Returns the A1 value defined in I.9 (Table 2) """ return ((dbar - bbar) / dbar) * (slip / beta) *\ np.exp(-(dbar / 2.) * mmax)
[ "def", "_get_a1_value", "(", "bbar", ",", "dbar", ",", "slip", ",", "beta", ",", "mmax", ")", ":", "return", "(", "(", "dbar", "-", "bbar", ")", "/", "dbar", ")", "*", "(", "slip", "/", "beta", ")", "*", "np", ".", "exp", "(", "-", "(", "dbar...
36.333333
0.008969
def write(self, filename, filetype=None, **kwargs): """Write the coverage data in the MOC object to a file. The filetype can be given or left to be inferred as for the read method. Any additional keyword arguments (kwargs) are passed on to the corresponding pymoc.io write funct...
[ "def", "write", "(", "self", ",", "filename", ",", "filetype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "filetype", "is", "not", "None", ":", "filetype", "=", "filetype", ".", "lower", "(", ")", "else", ":", "filetype", "=", "self", "....
36.5625
0.001665
def run(self, sensor_graph, model): """Run this optimization pass on the sensor graph If necessary, information on the device model being targeted can be found in the associated model argument. Args: sensor_graph (SensorGraph): The sensor graph to optimize model...
[ "def", "run", "(", "self", ",", "sensor_graph", ",", "model", ")", ":", "# This check can be done if there is 1 input and it is count == 1", "# and the stream type is input or unbuffered", "for", "node", ",", "inputs", ",", "outputs", "in", "sensor_graph", ".", "iterate_bfs...
32.861111
0.002463
def tex_parse(string): """ Renders some basic TeX math to HTML. """ string = string.replace('{', '').replace('}', '') def tex_replace(match): return \ sub(r'\^(\w)', r'<sup>\1</sup>', sub(r'\^\{(.*?)\}', r'<sup>\1</sup>', sub(r'\_(\w)', r'<sub>\1</sub>', sub(r'\_\{(.*?)\}', r'<sub>\1</sub>', sub(...
[ "def", "tex_parse", "(", "string", ")", ":", "string", "=", "string", ".", "replace", "(", "'{'", ",", "''", ")", ".", "replace", "(", "'}'", ",", "''", ")", "def", "tex_replace", "(", "match", ")", ":", "return", "sub", "(", "r'\\^(\\w)'", ",", "r...
31
0.040268
def _make_image(tensor): """Converts an NDArray type image to Image protobuf""" assert isinstance(tensor, NDArray) if Image is None: raise ImportError('need to install PIL for visualizing images') height, width, channel = tensor.shape tensor = _make_numpy_array(tensor) image = Image.from...
[ "def", "_make_image", "(", "tensor", ")", ":", "assert", "isinstance", "(", "tensor", ",", "NDArray", ")", "if", "Image", "is", "None", ":", "raise", "ImportError", "(", "'need to install PIL for visualizing images'", ")", "height", ",", "width", ",", "channel",...
40.857143
0.001709
def Overlay_setShowScrollBottleneckRects(self, show): """ Function path: Overlay.setShowScrollBottleneckRects Domain: Overlay Method name: setShowScrollBottleneckRects Parameters: Required arguments: 'show' (type: boolean) -> True for showing scroll bottleneck rects No return value. De...
[ "def", "Overlay_setShowScrollBottleneckRects", "(", "self", ",", "show", ")", ":", "assert", "isinstance", "(", "show", ",", "(", "bool", ",", ")", ")", ",", "\"Argument 'show' must be of type '['bool']'. Received type: '%s'\"", "%", "type", "(", "show", ")", "subdo...
32.684211
0.042254
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): """Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows ...
[ "def", "ExtractEvents", "(", "self", ",", "parser_mediator", ",", "registry_key", ",", "*", "*", "kwargs", ")", ":", "network_info", "=", "{", "}", "signatures", "=", "registry_key", ".", "GetSubkeyByName", "(", "'Signatures'", ")", "if", "signatures", ":", ...
38.728571
0.009712
def updatePassword(self, user, currentPassword, newPassword): """Change the password of a user.""" return self.__post('/api/updatePassword', data={ 'user': user, ...
[ "def", "updatePassword", "(", "self", ",", "user", ",", "currentPassword", ",", "newPassword", ")", ":", "return", "self", ".", "__post", "(", "'/api/updatePassword'", ",", "data", "=", "{", "'user'", ":", "user", ",", "'currentPassword'", ":", "currentPasswor...
40.818182
0.010893
def gp_rapp(): """rho in-medium ratios by Rapp (based on protected data)""" inDir, outDir = getWorkDirs() # prepare data yields = {} for infile in os.listdir(inDir): energy = re.compile('\d+').search(infile).group() medium = np.loadtxt(open(os.path.join(inDir, infile), 'rb')) getMassRangesSums(ene...
[ "def", "gp_rapp", "(", ")", ":", "inDir", ",", "outDir", "=", "getWorkDirs", "(", ")", "# prepare data", "yields", "=", "{", "}", "for", "infile", "in", "os", ".", "listdir", "(", "inDir", ")", ":", "energy", "=", "re", ".", "compile", "(", "'\\d+'",...
33.571429
0.040331
def commit_buy(self, buy_id, **params): """https://developers.coinbase.com/api/v2#commit-a-buy""" return self.api_client.commit_buy(self.id, buy_id, **params)
[ "def", "commit_buy", "(", "self", ",", "buy_id", ",", "*", "*", "params", ")", ":", "return", "self", ".", "api_client", ".", "commit_buy", "(", "self", ".", "id", ",", "buy_id", ",", "*", "*", "params", ")" ]
57.333333
0.011494
def create(gandi, vhost, paas, ssl, private_key, alter_zone, poll_cert, background): """ Create a new vhost. """ if not gandi.hostedcert.activate_ssl(vhost, ssl, private_key, poll_cert): return paas_info = gandi.paas.info(paas) result = gandi.vhost.create(paas_info, vhost, alter_zone...
[ "def", "create", "(", "gandi", ",", "vhost", ",", "paas", ",", "ssl", ",", "private_key", ",", "alter_zone", ",", "poll_cert", ",", "background", ")", ":", "if", "not", "gandi", ".", "hostedcert", ".", "activate_ssl", "(", "vhost", ",", "ssl", ",", "pr...
30.307692
0.002463
def is_self(addr): ''' check if this host is this addr ''' ips = [] for i in netifaces.interfaces(): entry = netifaces.ifaddresses(i) if netifaces.AF_INET in entry: for ipv4 in entry[netifaces.AF_INET]: if "addr" in ipv4: ips.append(ipv4["addr"]) return addr in ips or addr ==...
[ "def", "is_self", "(", "addr", ")", ":", "ips", "=", "[", "]", "for", "i", "in", "netifaces", ".", "interfaces", "(", ")", ":", "entry", "=", "netifaces", ".", "ifaddresses", "(", "i", ")", "if", "netifaces", ".", "AF_INET", "in", "entry", ":", "fo...
27.416667
0.020588
def _eventloop_changed(self, name, old, new): """schedule call to eventloop from IOLoop""" loop = ioloop.IOLoop.instance() loop.add_timeout(time.time()+0.1, self.enter_eventloop)
[ "def", "_eventloop_changed", "(", "self", ",", "name", ",", "old", ",", "new", ")", ":", "loop", "=", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", "loop", ".", "add_timeout", "(", "time", ".", "time", "(", ")", "+", "0.1", ",", "self", ".", ...
49.75
0.009901
def filter_directories(self): """Filter the directories to show""" index = self.get_index('.spyproject') if index is not None: self.setRowHidden(index.row(), index.parent(), True)
[ "def", "filter_directories", "(", "self", ")", ":", "index", "=", "self", ".", "get_index", "(", "'.spyproject'", ")", "if", "index", "is", "not", "None", ":", "self", ".", "setRowHidden", "(", "index", ".", "row", "(", ")", ",", "index", ".", "parent"...
43
0.009132
def _get_or_open_file(filename): '''If ``filename`` is a string or bytes object, open the ``filename`` and return the file object. If ``filename`` is file-like (i.e., it has 'read' and 'write' attributes, return ``filename``. Parameters ---------- filename : str,...
[ "def", "_get_or_open_file", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "(", "str", ",", "bytes", ")", ")", ":", "f", "=", "open", "(", "filename", ")", "elif", "hasattr", "(", "filename", ",", "'read'", ")", "and", "hasattr", ...
31.923077
0.002339
def auc_score( model, test_interactions, train_interactions=None, user_features=None, item_features=None, preserve_rows=False, num_threads=1, check_intersections=True, ): """ Measure the ROC AUC metric for a model: the probability that a randomly chosen positive example has a...
[ "def", "auc_score", "(", "model", ",", "test_interactions", ",", "train_interactions", "=", "None", ",", "user_features", "=", "None", ",", "item_features", "=", "None", ",", "preserve_rows", "=", "False", ",", "num_threads", "=", "1", ",", "check_intersections"...
36.860465
0.002151
def all(script, face=True, vert=True): """ Select all the faces of the current mesh Args: script: the FilterScript object or script filename to write the filter to. faces (bool): If True the filter will select all the faces. verts (bool): If True the filter will select all t...
[ "def", "all", "(", "script", ",", "face", "=", "True", ",", "vert", "=", "True", ")", ":", "filter_xml", "=", "''", ".", "join", "(", "[", "' <filter name=\"Select All\">\\n'", ",", "' <Param name=\"allFaces\" '", ",", "'value=\"{}\" '", ".", "format", "("...
29.387097
0.001063
def simBirth(self,which_agents): ''' Makes new consumers for the given indices. Slightly extends base method by also setting pLvlErrNow = 1.0 for new agents, indicating that they correctly perceive their productivity. Parameters ---------- which_agents : np.array(Bool) ...
[ "def", "simBirth", "(", "self", ",", "which_agents", ")", ":", "AggShockConsumerType", ".", "simBirth", "(", "self", ",", "which_agents", ")", "if", "hasattr", "(", "self", ",", "'pLvlErrNow'", ")", ":", "self", ".", "pLvlErrNow", "[", "which_agents", "]", ...
34.947368
0.01173
def parse_transaction_bytes(tx_bytes): """Parses base64data into a map with the following keys: tx - a StellarSignTx describing the transaction header operations - an array of protobuf message objects for each operation """ tx = messages.StellarSignTx() unpacker = xdrlib.Unpacker(tx_byte...
[ "def", "parse_transaction_bytes", "(", "tx_bytes", ")", ":", "tx", "=", "messages", ".", "StellarSignTx", "(", ")", "unpacker", "=", "xdrlib", ".", "Unpacker", "(", "tx_bytes", ")", "tx", ".", "source_account", "=", "_xdr_read_address", "(", "unpacker", ")", ...
36.9
0.001056
def atleast(cls, lits, weights=None, bound=1, top_id=None, encoding=EncType.best): """ A synonym for :meth:`PBEnc.geq`. """ return cls.geq(lits, weights, bound, top_id, encoding)
[ "def", "atleast", "(", "cls", ",", "lits", ",", "weights", "=", "None", ",", "bound", "=", "1", ",", "top_id", "=", "None", ",", "encoding", "=", "EncType", ".", "best", ")", ":", "return", "cls", ".", "geq", "(", "lits", ",", "weights", ",", "bo...
31.571429
0.008811
def get_creation_date_tags(url, domain, as_dicts=False): """ Put together all data sources in this module and return it's output. Args: url (str): URL of the web. With relative paths and so on. domain (str): Just the domain of the web. as_dicts (bool, default False): Convert output ...
[ "def", "get_creation_date_tags", "(", "url", ",", "domain", ",", "as_dicts", "=", "False", ")", ":", "creation_date_tags", "=", "[", "mementoweb_api_tags", "(", "url", ")", ",", "get_whois_tags", "(", "domain", ")", ",", "]", "creation_date_tags", "=", "sorted...
26.433333
0.001217
def get_image_hash(image_path, level=None,level_filter=None, include_files=None, skip_files=None, version=None): '''get_image_hash will generate a sha1 hash of an image, depending on a level of reproducibility specified by the user. (s...
[ "def", "get_image_hash", "(", "image_path", ",", "level", "=", "None", ",", "level_filter", "=", "None", ",", "include_files", "=", "None", ",", "skip_files", "=", "None", ",", "version", "=", "None", ")", ":", "# First get a level dictionary, with description and...
36.515152
0.008485
def compute_layout(self, data): """ Compute layout """ msg = "{} should implement this method." raise NotImplementedError( msg.format(self.__class.__name__))
[ "def", "compute_layout", "(", "self", ",", "data", ")", ":", "msg", "=", "\"{} should implement this method.\"", "raise", "NotImplementedError", "(", "msg", ".", "format", "(", "self", ".", "__class", ".", "__name__", ")", ")" ]
29
0.009569
def quickinfo(self): """ Returns a short string describing some of the options of the actor. :return: the info, None if not available :rtype: str """ return "search: " + base.to_commandline(self.config["search"]) + ", eval: " \ + base.to_commandline(self.c...
[ "def", "quickinfo", "(", "self", ")", ":", "return", "\"search: \"", "+", "base", ".", "to_commandline", "(", "self", ".", "config", "[", "\"search\"", "]", ")", "+", "\", eval: \"", "+", "base", ".", "to_commandline", "(", "self", ".", "config", "[", "\...
36.222222
0.008982
def cache2errors(function, cache, disp=0, ftol=0.05): """ This function will attempt to identify 1 sigma errors, assuming your function is a chi^2. For this, the 1-sigma is bracketed. If you were smart enough to build a cache list of [x,y] into your function, you can pass it here. The values bracketing 1 sigma w...
[ "def", "cache2errors", "(", "function", ",", "cache", ",", "disp", "=", "0", ",", "ftol", "=", "0.05", ")", ":", "vals", "=", "numpy", ".", "array", "(", "sorted", "(", "cache", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", ")",...
29.98913
0.04807
def to_bytes(self): ''' Create bytes from properties ''' # Verify that the properties make sense self.sanitize() # Write the version bitstream = BitStream('uint:4=%d' % self.version) # Write the traffic class bitstream += BitStream('uint:8=%d' % ...
[ "def", "to_bytes", "(", "self", ")", ":", "# Verify that the properties make sense", "self", ".", "sanitize", "(", ")", "# Write the version", "bitstream", "=", "BitStream", "(", "'uint:4=%d'", "%", "self", ".", "version", ")", "# Write the traffic class", "bitstream"...
32.363636
0.001818
def transform(self, X): ''' :X: numpy ndarray ''' noise = self._noise_func(*self._args, size=X.shape) results = X + noise self.relative_noise_size_ = self.relative_noise_size(X, results) return results
[ "def", "transform", "(", "self", ",", "X", ")", ":", "noise", "=", "self", ".", "_noise_func", "(", "*", "self", ".", "_args", ",", "size", "=", "X", ".", "shape", ")", "results", "=", "X", "+", "noise", "self", ".", "relative_noise_size_", "=", "s...
31.375
0.011628
def report_numbers2marc(self, key, value): """Populate the ``037`` MARC field.""" def _get_mangled_source(source): if source == 'arXiv': return 'arXiv:reportnumber' return source source = _get_mangled_source(value.get('source')) if value.get('hidden'): return { ...
[ "def", "report_numbers2marc", "(", "self", ",", "key", ",", "value", ")", ":", "def", "_get_mangled_source", "(", "source", ")", ":", "if", "source", "==", "'arXiv'", ":", "return", "'arXiv:reportnumber'", "return", "source", "source", "=", "_get_mangled_source"...
23.315789
0.002169
def notify_user( self, msg, level="error", rate_limit=None, module_name="", icon=None, title="py3status", ): """ Display notification to user via i3-nagbar or send-notify We also make sure to log anything to keep trace of it. N...
[ "def", "notify_user", "(", "self", ",", "msg", ",", "level", "=", "\"error\"", ",", "rate_limit", "=", "None", ",", "module_name", "=", "\"\"", ",", "icon", "=", "None", ",", "title", "=", "\"py3status\"", ",", ")", ":", "dbus", "=", "self", ".", "co...
37.605263
0.002387
def shutdown(self): """Gracefully shutdown the consumer Consumer will complete any outstanding processing, commit its current offsets (if so configured) and stop. Returns deferred which callbacks with a tuple of: (last processed offset, last committed offset) if it was able to ...
[ "def", "shutdown", "(", "self", ")", ":", "def", "_handle_shutdown_commit_success", "(", "result", ")", ":", "\"\"\"Handle the result of the commit attempted by shutdown\"\"\"", "self", ".", "_shutdown_d", ",", "d", "=", "None", ",", "self", ".", "_shutdown_d", "self"...
42.151515
0.000702
def _set_names(self, values, level=None): """ Set new names on index. Each name has to be a hashable type. Parameters ---------- values : str or sequence name(s) to set level : int, level name, or sequence of int/level names (default None) If the ...
[ "def", "_set_names", "(", "self", ",", "values", ",", "level", "=", "None", ")", ":", "if", "not", "is_list_like", "(", "values", ")", ":", "raise", "ValueError", "(", "'Names must be a list-like'", ")", "if", "len", "(", "values", ")", "!=", "1", ":", ...
35.758621
0.001878
def middleware(self, middleware_or_request): '''Decorate and register middleware to be called before a request. Can either be called as @app.middleware or @app.middleware('request') ''' def register_middleware(middleware, attach_to='request'): if attach_to == 'request': ...
[ "def", "middleware", "(", "self", ",", "middleware_or_request", ")", ":", "def", "register_middleware", "(", "middleware", ",", "attach_to", "=", "'request'", ")", ":", "if", "attach_to", "==", "'request'", ":", "self", ".", "request_middleware", ".", "append", ...
44.277778
0.002457
def _process_cell(i, state, finite=False): """Process 3 cells and return a value from 0 to 7. """ op_1 = state[i - 1] op_2 = state[i] if i == len(state) - 1: if finite: op_3 = state[0] else: op_3 = 0 else: op_3 = state[i + 1] result = 0 for i, ...
[ "def", "_process_cell", "(", "i", ",", "state", ",", "finite", "=", "False", ")", ":", "op_1", "=", "state", "[", "i", "-", "1", "]", "op_2", "=", "state", "[", "i", "]", "if", "i", "==", "len", "(", "state", ")", "-", "1", ":", "if", "finite...
25.1875
0.002392
def GatewayHeterogenity_metric(bpmn_graph): """ Returns the value of the Gateway Heterogenity metric ("Number of different types of gateways used in a mode") for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. """ gateway_counts = ...
[ "def", "GatewayHeterogenity_metric", "(", "bpmn_graph", ")", ":", "gateway_counts", "=", "get_gateway_counts", "(", "bpmn_graph", ")", "present_gateways", "=", "[", "gateway_name", "for", "gateway_name", ",", "count", "in", "gateway_counts", ".", "items", "(", ")", ...
34.6
0.001876
def register_hooks(app): """Register hooks.""" @app.before_request def before_request(): g.user = get_current_user() if g.user and g.user.is_admin: g._before_request_time = time.time() @app.after_request def after_request(response): if hasattr(g, '_before_reques...
[ "def", "register_hooks", "(", "app", ")", ":", "@", "app", ".", "before_request", "def", "before_request", "(", ")", ":", "g", ".", "user", "=", "get_current_user", "(", ")", "if", "g", ".", "user", "and", "g", ".", "user", ".", "is_admin", ":", "g",...
30.466667
0.002123
def pyeapi_call(method, *args, **kwargs): ''' .. versionadded:: 2019.2.0 Invoke an arbitrary method from the ``pyeapi`` library. This function forwards the existing connection details to the :mod:`pyeapi.run_commands <salt.module.arista_pyeapi.run_commands>` execution function. method ...
[ "def", "pyeapi_call", "(", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pyeapi_kwargs", "=", "pyeapi_nxos_api_args", "(", "*", "*", "kwargs", ")", "return", "__salt__", "[", "'pyeapi.call'", "]", "(", "method", ",", "*", "args", ",", ...
30.375
0.00133
def sample_dimension(trajs, dimension, n_frames, scheme="linear"): """Sample a dimension of the data. This method uses one of 3 schemes. All other dimensions are ignored, so this might result in a really "jumpy" sampled trajectory. Parameters ---------- trajs : dictionary of np.ndarray ...
[ "def", "sample_dimension", "(", "trajs", ",", "dimension", ",", "n_frames", ",", "scheme", "=", "\"linear\"", ")", ":", "fixed_indices", "=", "list", "(", "trajs", ".", "keys", "(", ")", ")", "trajs", "=", "[", "trajs", "[", "k", "]", "[", ":", ",", ...
39.166667
0.001557
def global_registry(self): """Global Registry NOTE: Parses main conf files (/etc/fwissr/fwissr.json and ~/.fwissr/fwissr.json) then uses 'fwissr_sources' setting to setup additional sources Example of /etc/fwissr/fwissr.json file: { 'fwissr_sources': ...
[ "def", "global_registry", "(", "self", ")", ":", "if", "self", ".", "_global_registry", "is", "None", ":", "if", "'fwissr_refresh_period'", "in", "self", ".", "main_conf", ":", "result", "=", "Registry", "(", "refresh_period", "=", "self", ".", "main_conf", ...
35.604167
0.001139
def outputToFiles(stdout=None, stderr=None): """ Redirect stdout and stderr to named files. Records the file names so that a future call to reopenOutputFiles() can open the same files. Installs a SIGHUP handler that will reopen the output files. Note that stderr is opened unbuffered, so if it ...
[ "def", "outputToFiles", "(", "stdout", "=", "None", ",", "stderr", "=", "None", ")", ":", "global", "_stdout", ",", "_stderr", ",", "_old_hup_handler", "_stdout", ",", "_stderr", "=", "stdout", ",", "stderr", "reopenOutputFiles", "(", ")", "def", "sighup", ...
33.571429
0.000827
def _populate_issue(self, graph: TraceGraph, instance_id: int) -> None: """Adds an issue to the trace graph along with relevant information pertaining to the issue (e.g. instance, fix_info, sources/sinks) The issue is identified by its corresponding instance's ID in the input trace graph...
[ "def", "_populate_issue", "(", "self", ",", "graph", ":", "TraceGraph", ",", "instance_id", ":", "int", ")", "->", "None", ":", "instance", "=", "graph", ".", "_issue_instances", "[", "instance_id", "]", "issue", "=", "graph", ".", "_issues", "[", "instanc...
50.875
0.002412
def crawl_links(self, seed_url=None): """Find new links given a seed URL and follow them breadth-first. Save page responses as PART.html files. Return the PART.html filenames created during crawling. """ if seed_url is not None: self.seed_url = seed_url if s...
[ "def", "crawl_links", "(", "self", ",", "seed_url", "=", "None", ")", ":", "if", "seed_url", "is", "not", "None", ":", "self", ".", "seed_url", "=", "seed_url", "if", "self", ".", "seed_url", "is", "None", ":", "sys", ".", "stderr", ".", "write", "("...
39.764706
0.002406
def bootstrap( repositories, name, packages=None, additional_packages=None, tag="latest", prefix=constants.CONU_ARTIFACT_TAG, packager=None): """ bootstrap Image from scratch. It creates new image based on giver dnf repositories and package setts :param repositories:list...
[ "def", "bootstrap", "(", "repositories", ",", "name", ",", "packages", "=", "None", ",", "additional_packages", "=", "None", ",", "tag", "=", "\"latest\"", ",", "prefix", "=", "constants", ".", "CONU_ARTIFACT_TAG", ",", "packager", "=", "None", ")", ":", "...
45.325
0.002429
def save_metadata(self, data_dir, feature_name=None): """See base class for details.""" # Save names if defined if self._str2int is not None: names_filepath = _get_names_filepath(data_dir, feature_name) _write_names_to_file(names_filepath, self.names)
[ "def", "save_metadata", "(", "self", ",", "data_dir", ",", "feature_name", "=", "None", ")", ":", "# Save names if defined", "if", "self", ".", "_str2int", "is", "not", "None", ":", "names_filepath", "=", "_get_names_filepath", "(", "data_dir", ",", "feature_nam...
45
0.010909
def touch(self, key, ttl=0): """Update a key's expiration time :param string key: The key whose expiration time should be modified :param int ttl: The new expiration time. If the expiration time is `0` then the key never expires (and any existing expiration i...
[ "def", "touch", "(", "self", ",", "key", ",", "ttl", "=", "0", ")", ":", "return", "_Base", ".", "touch", "(", "self", ",", "key", ",", "ttl", "=", "ttl", ")" ]
34.26087
0.002469
def _pool_connect(self, agg): """ `agg` should be (host, port) Returns a live connection from the connection pool """ return self._pool.connect(agg[0], agg[1], self._user, self._password, self._database)
[ "def", "_pool_connect", "(", "self", ",", "agg", ")", ":", "return", "self", ".", "_pool", ".", "connect", "(", "agg", "[", "0", "]", ",", "agg", "[", "1", "]", ",", "self", ".", "_user", ",", "self", ".", "_password", ",", "self", ".", "_databas...
47
0.012552
def open_csv(csv_file, mode='r'): """ Get mode depending on Python version Based on: http://stackoverflow.com/questions/29840849/writing-a-csv-file-in-python-that-works-for-both-python-2-7-and-python-3-3-in """ # noqa if version_info[0] == 2: # Not named on 2.6 access = '{0}b'.format(mode)...
[ "def", "open_csv", "(", "csv_file", ",", "mode", "=", "'r'", ")", ":", "# noqa", "if", "version_info", "[", "0", "]", "==", "2", ":", "# Not named on 2.6", "access", "=", "'{0}b'", ".", "format", "(", "mode", ")", "kwargs", "=", "{", "}", "else", ":"...
34.846154
0.002151
def _generate_presence_token(self, channel_name): """Generate a presence token. :param str channel_name: Name of the channel to generate a signature for. :rtype: str """ subject = "{}:{}:{}".format(self.connection.socket_id, channel_name, json.dumps(self.user_data)) h = ...
[ "def", "_generate_presence_token", "(", "self", ",", "channel_name", ")", ":", "subject", "=", "\"{}:{}:{}\"", ".", "format", "(", "self", ".", "connection", ".", "socket_id", ",", "channel_name", ",", "json", ".", "dumps", "(", "self", ".", "user_data", ")"...
42.272727
0.010526
def pmag_angle(D1,D2): # use this """ finds the angle between lists of two directions D1,D2 """ D1 = numpy.array(D1) if len(D1.shape) > 1: D1 = D1[:,0:2] # strip off intensity else: D1 = D1[:2] D2 = numpy.array(D2) if len(D2.shape) > 1: D2 = D2[:,0:2] # strip o...
[ "def", "pmag_angle", "(", "D1", ",", "D2", ")", ":", "# use this ", "D1", "=", "numpy", ".", "array", "(", "D1", ")", "if", "len", "(", "D1", ".", "shape", ")", ">", "1", ":", "D1", "=", "D1", "[", ":", ",", "0", ":", "2", "]", "# strip off i...
34.1
0.025678
def remote_command(task: Task, command: str) -> Result: """ Executes a command remotely on the host Arguments: command (``str``): command to execute Returns: Result object with the following attributes set: * result (``str``): stderr or stdout * stdout (``str``): st...
[ "def", "remote_command", "(", "task", ":", "Task", ",", "command", ":", "str", ")", "->", "Result", ":", "client", "=", "task", ".", "host", ".", "get_connection", "(", "\"paramiko\"", ",", "task", ".", "nornir", ".", "config", ")", "connection_state", "...
29.789474
0.001711
def get_user_permissions(user): '''Returns the queryset of permissions for the given user.''' permissions = SeedPermission.objects.all() # User must be on a team that grants the permission permissions = permissions.filter(seedteam__users=user) # The team must be active permissions = permissions....
[ "def", "get_user_permissions", "(", "user", ")", ":", "permissions", "=", "SeedPermission", ".", "objects", ".", "all", "(", ")", "# User must be on a team that grants the permission", "permissions", "=", "permissions", ".", "filter", "(", "seedteam__users", "=", "use...
45.636364
0.001953
def clear(self): """ Clear the samples. """ self.__init__(size=self.size, alpha=self.alpha, clock=self.clock)
[ "def", "clear", "(", "self", ")", ":", "self", ".", "__init__", "(", "size", "=", "self", ".", "size", ",", "alpha", "=", "self", ".", "alpha", ",", "clock", "=", "self", ".", "clock", ")" ]
38.333333
0.008547
def addWriter(self, writer): """Add a FileDescriptor for notification of data available to write. """ self._sendToThread(self.writes.__setitem__, writer, 1) self.wakeUp()
[ "def", "addWriter", "(", "self", ",", "writer", ")", ":", "self", ".", "_sendToThread", "(", "self", ".", "writes", ".", "__setitem__", ",", "writer", ",", "1", ")", "self", ".", "wakeUp", "(", ")" ]
39.6
0.009901
def plot_2(data, *args): """Plot 2. Running best score (scatter plot)""" df_all = pd.DataFrame(data) df_params = nonconstant_parameters(data) x = [df_all['id'][0]] y = [df_all['mean_test_score'][0]] params = [df_params.loc[0]] for i in range(len(df_all)): if df_all['mean_test_score']...
[ "def", "plot_2", "(", "data", ",", "*", "args", ")", ":", "df_all", "=", "pd", ".", "DataFrame", "(", "data", ")", "df_params", "=", "nonconstant_parameters", "(", "data", ")", "x", "=", "[", "df_all", "[", "'id'", "]", "[", "0", "]", "]", "y", "...
39.357143
0.001773
def GetReportDownloadHeaders(self, **kwargs): """Returns a dictionary of headers for a report download request. Note that the given keyword arguments will override any settings configured from the googleads.yaml file. Args: **kwargs: Optional keyword arguments. Keyword Arguments: clie...
[ "def", "GetReportDownloadHeaders", "(", "self", ",", "*", "*", "kwargs", ")", ":", "headers", "=", "self", ".", "_adwords_client", ".", "oauth2_client", ".", "CreateHttpHeader", "(", ")", "headers", ".", "update", "(", "{", "'Content-type'", ":", "self", "."...
41.948276
0.00241
def resize_dimension(self, dimension, size): """ Resize a dimension to a certain size. It will pad with the underlying HDF5 data sets' fill values (usually zero) where necessary. """ if self.dimensions[dimension] is not None: raise ValueError("Dimension '%s' ...
[ "def", "resize_dimension", "(", "self", ",", "dimension", ",", "size", ")", ":", "if", "self", ".", "dimensions", "[", "dimension", "]", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Dimension '%s' is not unlimited and thus \"", "\"cannot be resized.\"", ...
37.346154
0.002008
def trans_new(name, transform, inverse, breaks=None, minor_breaks=None, _format=None, domain=(-np.inf, np.inf), doc='', **kwargs): """ Create a transformation class object Parameters ---------- name : str Name of the transformation transform : callable ``f(x)...
[ "def", "trans_new", "(", "name", ",", "transform", ",", "inverse", ",", "breaks", "=", "None", ",", "minor_breaks", "=", "None", ",", "_format", "=", "None", ",", "domain", "=", "(", "-", "np", ".", "inf", ",", "np", ".", "inf", ")", ",", "doc", ...
29.296875
0.000516
def gradient(self): """Gradient operator of the functional. The functional is not differentiable in ``x=0``. However, when evaluating the gradient operator in this point it will return 0. """ functional = self if self.exponent == 1: class L1Gradient(Operator...
[ "def", "gradient", "(", "self", ")", ":", "functional", "=", "self", "if", "self", ".", "exponent", "==", "1", ":", "class", "L1Gradient", "(", "Operator", ")", ":", "\"\"\"The gradient operator of this functional.\"\"\"", "def", "__init__", "(", "self", ")", ...
33.481481
0.001075
def pathFromIndex( self, index ): """ Returns the full path from the inputed index on. :param index | <QModelIndex> :return <str> """ item = self.model().itemFromIndex(index) return self.model().itemPath(item)
[ "def", "pathFromIndex", "(", "self", ",", "index", ")", ":", "item", "=", "self", ".", "model", "(", ")", ".", "itemFromIndex", "(", "index", ")", "return", "self", ".", "model", "(", ")", ".", "itemPath", "(", "item", ")" ]
28.3
0.020548
def returnAllChips(self,extname=None,exclude=None): """ Returns a list containing all the chips which match the extname given minus those specified for exclusion (if any). """ extensions = self._findExtnames(extname=extname,exclude=exclude) chiplist = [] for i in rang...
[ "def", "returnAllChips", "(", "self", ",", "extname", "=", "None", ",", "exclude", "=", "None", ")", ":", "extensions", "=", "self", ".", "_findExtnames", "(", "extname", "=", "extname", ",", "exclude", "=", "exclude", ")", "chiplist", "=", "[", "]", "...
48.75
0.013836
def statuses_home_timeline(self, count=None, since_id=None, max_id=None, trim_user=None, exclude_replies=None, contributor_details=None, include_entities=None): """ Returns a collection of the most recent Tweets...
[ "def", "statuses_home_timeline", "(", "self", ",", "count", "=", "None", ",", "since_id", "=", "None", ",", "max_id", "=", "None", ",", "trim_user", "=", "None", ",", "exclude_replies", "=", "None", ",", "contributor_details", "=", "None", ",", "include_enti...
43.040816
0.002318
async def detach(self, device, force=False): """ Detach a device after unmounting all its mounted filesystems. :param device: device object, block device path or mount path :param bool force: remove child devices before trying to detach :returns: whether the operation succeeded ...
[ "async", "def", "detach", "(", "self", ",", "device", ",", "force", "=", "False", ")", ":", "device", "=", "self", ".", "_find_device", "(", "device", ")", "if", "not", "self", ".", "is_handleable", "(", "device", ")", ":", "self", ".", "_log", ".", ...
40.454545
0.002195
def tag(tagname, content='', attrs=None): """ Helper for programmatically building HTML tags. Note that this barely does any escaping, and will happily spit out dangerous user input if used as such. :param tagname: Tag name of the DOM element we want to return. :param content: Opt...
[ "def", "tag", "(", "tagname", ",", "content", "=", "''", ",", "attrs", "=", "None", ")", ":", "attrs_str", "=", "attrs", "and", "' '", ".", "join", "(", "_generate_dom_attrs", "(", "attrs", ")", ")", "open_tag", "=", "tagname", "if", "attrs_str", ":", ...
38.375
0.001271