text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def initialize_plugs(self, plug_types=None): """Instantiate required plugs. Instantiates plug types and saves the instances in self._plugs_by_type for use in provide_plugs(). Args: plug_types: Plug types may be specified here rather than passed into the constructor (this is use...
[ "def", "initialize_plugs", "(", "self", ",", "plug_types", "=", "None", ")", ":", "types", "=", "plug_types", "if", "plug_types", "is", "not", "None", "else", "self", ".", "_plug_types", "for", "plug_type", "in", "types", ":", "# Create a logger for this plug. A...
42.479167
0.008629
def _normalize_field_name(value): """Normalizing value string used as key and field name. :param value: String to normalize :type value: str :return: normalized string :rtype: str """ # Replace non word/letter character return_value = re.sub(r'[^\w\s-]+', '', value) # Replaces whit...
[ "def", "_normalize_field_name", "(", "value", ")", ":", "# Replace non word/letter character", "return_value", "=", "re", ".", "sub", "(", "r'[^\\w\\s-]+'", ",", "''", ",", "value", ")", "# Replaces whitespace with underscores", "return_value", "=", "re", ".", "sub", ...
29.642857
0.002336
def _passes_filter(self, proxy): ''' avoid redudant and space consuming calls to 'self' ''' ''' validate proxy based on provided filters ''' if self.allowed_countries is not None and proxy['country'] not in self.allowed_countries: return False if self.denied_countr...
[ "def", "_passes_filter", "(", "self", ",", "proxy", ")", ":", "''' validate proxy based on provided filters '''", "if", "self", ".", "allowed_countries", "is", "not", "None", "and", "proxy", "[", "'country'", "]", "not", "in", "self", ".", "allowed_countries", ":"...
34.647059
0.013223
def discover_master(self, service_name): """ Asks sentinel servers for the Redis master's address corresponding to the service labeled ``service_name``. Returns a pair (address, port) or raises MasterNotFoundError if no master is found. """ for sentinel_no, senti...
[ "def", "discover_master", "(", "self", ",", "service_name", ")", ":", "for", "sentinel_no", ",", "sentinel", "in", "enumerate", "(", "self", ".", "sentinels", ")", ":", "try", ":", "masters", "=", "sentinel", ".", "sentinel_masters", "(", ")", "except", "(...
45.1
0.002172
def load_commands(self, obj): """ Load commands defined on an arbitrary object. All functions decorated with the :func:`subparse.command` decorator attached the specified object will be loaded. The object may be a dictionary, an arbitrary python object, or a dotted path. ...
[ "def", "load_commands", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "str", ")", ":", "if", "obj", ".", "startswith", "(", "'.'", ")", "or", "obj", ".", "startswith", "(", "':'", ")", ":", "package", "=", "caller_package", ...
40.714286
0.002286
def assemble(cls, header_json, metadata_json, content_json): ''' Creates a new message, assembled from JSON fragments. Args: header_json (``JSON``) : metadata_json (``JSON``) : content_json (``JSON``) : Returns: Message subclass Raises...
[ "def", "assemble", "(", "cls", ",", "header_json", ",", "metadata_json", ",", "content_json", ")", ":", "try", ":", "header", "=", "json_decode", "(", "header_json", ")", "except", "ValueError", ":", "raise", "MessageError", "(", "\"header could not be decoded\"",...
24.15
0.00199
def mtxmg(m1, m2, ncol1, nr1r2, ncol2): """ Multiply the transpose of a matrix with another matrix, both of arbitrary size. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxmg_c.html :param m1: nr1r2 X ncol1 double precision matrix. :type m1: NxM-Element Array of floats :param m2...
[ "def", "mtxmg", "(", "m1", ",", "m2", ",", "ncol1", ",", "nr1r2", ",", "ncol2", ")", ":", "m1", "=", "stypes", ".", "toDoubleMatrix", "(", "m1", ")", "m2", "=", "stypes", ".", "toDoubleMatrix", "(", "m2", ")", "mout", "=", "stypes", ".", "emptyDoub...
35.571429
0.000978
def observe(self, C, obs_mesh_new, obs_vals_new, mean_under=None): """ Synchronizes self's observation status with C's. Values of observation are given by obs_vals. obs_mesh_new and obs_vals_new should already have been sliced, as Covariance.observe(..., output_type='o') does. ...
[ "def", "observe", "(", "self", ",", "C", ",", "obs_mesh_new", ",", "obs_vals_new", ",", "mean_under", "=", "None", ")", ":", "self", ".", "C", "=", "C", "self", ".", "obs_mesh", "=", "C", ".", "obs_mesh", "self", ".", "obs_len", "=", "C", ".", "obs...
31.555556
0.001366
def temp_copy_extracted_submission(self): """Creates a temporary copy of extracted submission. When executed, submission is allowed to modify it's own directory. So to ensure that submission does not pass any data between runs, new copy of the submission is made before each run. After a run temporary c...
[ "def", "temp_copy_extracted_submission", "(", "self", ")", ":", "tmp_copy_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "submission_dir", ",", "'tmp_copy'", ")", "shell_call", "(", "[", "'cp'", ",", "'-R'", ",", "os", ".", "path", ".", "jo...
40.133333
0.001623
def classify_comment(comment, cls=None): """ If 'reported' class is provided no training occures, the comment's class is simply set as such and removed. If no class is provided a lookup is done to see if the comment has been reported by users as abusive. If indicated as abusive class is set as ...
[ "def", "classify_comment", "(", "comment", ",", "cls", "=", "None", ")", ":", "if", "cls", "not", "in", "[", "'spam'", ",", "'ham'", ",", "'unsure'", ",", "'reported'", ",", "None", "]", ":", "raise", "Exception", "(", "\"Unrecognized classifications.\"", ...
33.923077
0.000441
def is_root_path(self, filename): """Determines if 'filename' corresponds to a directory on this device.""" test_filename = filename + '/' for root_dir in self.root_dirs: if test_filename.startswith(root_dir): return True return False
[ "def", "is_root_path", "(", "self", ",", "filename", ")", ":", "test_filename", "=", "filename", "+", "'/'", "for", "root_dir", "in", "self", ".", "root_dirs", ":", "if", "test_filename", ".", "startswith", "(", "root_dir", ")", ":", "return", "True", "ret...
41.142857
0.010204
def map_foreign2exact_invoice_numbers(self, foreign_invoice_numbers=None): """ Optionally supply a list of foreign (your) invoice numbers. Returns a dictionary of your invoice numbers (YourRef) to Exact Online invoice numbers. """ # Quick, select all. Not the most nice t...
[ "def", "map_foreign2exact_invoice_numbers", "(", "self", ",", "foreign_invoice_numbers", "=", "None", ")", ":", "# Quick, select all. Not the most nice to the server though.", "if", "foreign_invoice_numbers", "is", "None", ":", "ret", "=", "self", ".", "filter", "(", "sel...
47.171429
0.001187
def named_config(name: str, config_dict: typing.Mapping) -> None: """Adds a named config to the config registry. The first argument may either be a string or a collection of strings. This function should be called in a .konchrc file. """ names = ( name if isinstance(name, Iterable) ...
[ "def", "named_config", "(", "name", ":", "str", ",", "config_dict", ":", "typing", ".", "Mapping", ")", "->", "None", ":", "names", "=", "(", "name", "if", "isinstance", "(", "name", ",", "Iterable", ")", "and", "not", "isinstance", "(", "name", ",", ...
34.615385
0.002165
def _compute_std_dev(self, X): """Computes the standard deviation of a Gaussian Distribution with mean vector X[i]""" self._sigma = [] if X.shape[0] <= 1: self._sigma = [0.0] else: for x_mean in range(X.shape[0]): std_dev = np.sqrt(sum([np.linalg....
[ "def", "_compute_std_dev", "(", "self", ",", "X", ")", ":", "self", ".", "_sigma", "=", "[", "]", "if", "X", ".", "shape", "[", "0", "]", "<=", "1", ":", "self", ".", "_sigma", "=", "[", "0.0", "]", "else", ":", "for", "x_mean", "in", "range", ...
36.5
0.008909
def generate_file_rst(fname, target_dir, src_dir, gallery_conf): """Generate the rst file for a given example. Parameters ---------- fname : str Filename of python script target_dir : str Absolute path to directory in documentation where examples are saved src_dir : str ...
[ "def", "generate_file_rst", "(", "fname", ",", "target_dir", ",", "src_dir", ",", "gallery_conf", ")", ":", "src_file", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "src_dir", ",", "fname", ")", ")", "target_file", ...
35.375
0.000382
def lab_to_rgb(l, a, b): """ Converts CIE Lab to RGB components. First we have to convert to XYZ color space. Conversion involves using a white point, in this case D65 which represents daylight illumination. Algorithms adopted from: http://www.easyrgb.com/math.php """ ...
[ "def", "lab_to_rgb", "(", "l", ",", "a", ",", "b", ")", ":", "y", "=", "(", "l", "+", "16", ")", "/", "116.0", "x", "=", "a", "/", "500.0", "+", "y", "z", "=", "y", "-", "b", "/", "200.0", "v", "=", "[", "x", ",", "y", ",", "z", "]", ...
24.902439
0.01885
def make_payment(self, recipient, amount, description=None): """ make_payment allows for automated payments. A use case includes the ability to trigger a payment to a customer who requires a refund for example. You only need to provide the recipient and the amount to be transfere...
[ "def", "make_payment", "(", "self", ",", "recipient", ",", "amount", ",", "description", "=", "None", ")", ":", "self", ".", "br", ".", "open", "(", "self", ".", "MOBILE_WEB_URL", "%", "{", "'accountno'", ":", "self", ".", "account", "}", ")", "try", ...
44.958333
0.002268
def merge_strings(list_of_strings: Union[List[str], Tuple[str]]) -> dict: """ Pack the list of strings into two arrays: the concatenated chars and the \ individual string lengths. :func:`split_strings()` does the inverse. :param list_of_strings: The :class:`tuple` or :class:`list` of :class:`str`-s \ ...
[ "def", "merge_strings", "(", "list_of_strings", ":", "Union", "[", "List", "[", "str", "]", ",", "Tuple", "[", "str", "]", "]", ")", "->", "dict", ":", "if", "not", "isinstance", "(", "list_of_strings", ",", "(", "tuple", ",", "list", ")", ")", ":", ...
47.060606
0.001893
def get_modscag_fn_list(dem_dt, tile_list=('h08v04', 'h09v04', 'h10v04', 'h08v05', 'h09v05'), pad_days=7): """Function to fetch and process MODSCAG fractional snow cover products for input datetime Products are tiled in MODIS sinusoidal projection example url: https://snow-data.jpl.nasa.gov/modscag-histor...
[ "def", "get_modscag_fn_list", "(", "dem_dt", ",", "tile_list", "=", "(", "'h08v04'", ",", "'h09v04'", ",", "'h10v04'", ",", "'h08v05'", ",", "'h09v05'", ")", ",", "pad_days", "=", "7", ")", ":", "#Could also use global MODIS 500 m snowcover grids, 8 day", "#http://n...
48.703704
0.008199
def extract_oembeds(text, args=None): """ Extract oembed resources from a block of text. Returns a list of dictionaries. Max width & height can be specified: {% for embed in block_of_text|extract_oembeds:"400x300" %} Resource type can be specified: {% for photo_embed in block_of_text|extr...
[ "def", "extract_oembeds", "(", "text", ",", "args", "=", "None", ")", ":", "resource_type", "=", "width", "=", "height", "=", "None", "if", "args", ":", "dimensions", "=", "args", ".", "lower", "(", ")", ".", "split", "(", "'x'", ")", "if", "len", ...
31.24
0.001242
def uniform(graph, vartype, low=0.0, high=1.0, cls=BinaryQuadraticModel, seed=None): """Generate a bqm with random biases and offset. Biases and offset are drawn from a uniform distribution range (low, high). Args: graph (int/tuple[nodes, edges]/:obj:`~networkx.Graph`): The...
[ "def", "uniform", "(", "graph", ",", "vartype", ",", "low", "=", "0.0", ",", "high", "=", "1.0", ",", "cls", "=", "BinaryQuadraticModel", ",", "seed", "=", "None", ")", ":", "if", "seed", "is", "None", ":", "seed", "=", "numpy", ".", "random", ".",...
33.269231
0.002246
def error(self, interface_id, errorcode, msg): """When some error occurs the CCU / Homegear will send it's error message here""" LOG.debug("RPCFunctions.error: interface_id = %s, errorcode = %i, message = %s" % ( interface_id, int(errorcode), str(msg))) if self.systemcallback: ...
[ "def", "error", "(", "self", ",", "interface_id", ",", "errorcode", ",", "msg", ")", ":", "LOG", ".", "debug", "(", "\"RPCFunctions.error: interface_id = %s, errorcode = %i, message = %s\"", "%", "(", "interface_id", ",", "int", "(", "errorcode", ")", ",", "str", ...
56.857143
0.009901
def load_mnist_dataset(mode='supervised', one_hot=True): """Load the MNIST handwritten digits dataset. :param mode: 'supervised' or 'unsupervised' mode :param one_hot: whether to get one hot encoded labels :return: train, validation, test data: for (X, y) if 'supervised', for (X...
[ "def", "load_mnist_dataset", "(", "mode", "=", "'supervised'", ",", "one_hot", "=", "True", ")", ":", "mnist", "=", "input_data", ".", "read_data_sets", "(", "\"MNIST_data/\"", ",", "one_hot", "=", "one_hot", ")", "# Training set", "trX", "=", "mnist", ".", ...
27.392857
0.001259
def reconnect(self, query = None, log_reconnect = False): """ Reconnect to the database. """ uri = list(urisup.uri_help_split(self.sqluri)) if uri[1]: authority = list(uri[1]) if authority[1]: authority[1] = None uri[1] =...
[ "def", "reconnect", "(", "self", ",", "query", "=", "None", ",", "log_reconnect", "=", "False", ")", ":", "uri", "=", "list", "(", "urisup", ".", "uri_help_split", "(", "self", ".", "sqluri", ")", ")", "if", "uri", "[", "1", "]", ":", "authority", ...
33.785714
0.018519
def plotImagesWithNoise(suite, noise_values, plotPath): """ Plot Sample MNIST images with noise :param suite: The configured experiment suite. Must call `parse_opt` and ` parse_cfg` before calling this functions :param noise: list of noise values to plot """ datadir = suite.cfgparser.default...
[ "def", "plotImagesWithNoise", "(", "suite", ",", "noise_values", ",", "plotPath", ")", ":", "datadir", "=", "suite", ".", "cfgparser", ".", "defaults", "(", ")", "[", "\"datadir\"", "]", "transform", "=", "transforms", ".", "Compose", "(", "[", "transforms",...
35.28125
0.015517
def mcycle(return_X_y=True): """motorcyle acceleration dataset Parameters ---------- return_X_y : bool, if True, returns a model-ready tuple of data (X, y) otherwise, returns a Pandas DataFrame Returns ------- model-ready tuple of data (X, y) OR Pandas DataFrame...
[ "def", "mcycle", "(", "return_X_y", "=", "True", ")", ":", "# y is real", "# recommend LinearGAM", "motor", "=", "pd", ".", "read_csv", "(", "PATH", "+", "'/mcycle.csv'", ",", "index_col", "=", "0", ")", "if", "return_X_y", ":", "X", "=", "motor", ".", "...
22.709677
0.001362
def date_cast(date): ''' Casts any object into a datetime.datetime object date any datetime, time string representation... ''' if date is None: return datetime.datetime.now() elif isinstance(date, datetime.datetime): return date # fuzzy date try: if isinst...
[ "def", "date_cast", "(", "date", ")", ":", "if", "date", "is", "None", ":", "return", "datetime", ".", "datetime", ".", "now", "(", ")", "elif", "isinstance", "(", "date", ",", "datetime", ".", "datetime", ")", ":", "return", "date", "# fuzzy date", "t...
29.222222
0.00184
def send_figure(fig): """Draw the given figure and send it as a PNG payload. """ fmt = InlineBackend.instance().figure_format data = print_figure(fig, fmt) # print_figure will return None if there's nothing to draw: if data is None: return mimetypes = { 'png' : 'image/png', 'svg' : '...
[ "def", "send_figure", "(", "fig", ")", ":", "fmt", "=", "InlineBackend", ".", "instance", "(", ")", ".", "figure_format", "data", "=", "print_figure", "(", "fig", ",", "fmt", ")", "# print_figure will return None if there's nothing to draw:", "if", "data", "is", ...
38.352941
0.010479
def create_namespaced_pod_eviction(self, name, namespace, body, **kwargs): # noqa: E501 """create_namespaced_pod_eviction # noqa: E501 create eviction of a Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asyn...
[ "def", "create_namespaced_pod_eviction", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ...
64.153846
0.001181
def setvalue(self, value): """ .. _setvalue: Set the signed value of the Integer. """ self._value = abs(value) self._sign = 0 if(value < 0): self._sign = 1
[ "def", "setvalue", "(", "self", ",", "value", ")", ":", "self", ".", "_value", "=", "abs", "(", "value", ")", "self", ".", "_sign", "=", "0", "if", "(", "value", "<", "0", ")", ":", "self", ".", "_sign", "=", "1" ]
16.4
0.057803
def describe_change_set(awsclient, change_set_name, stack_name): """Print out the change_set to console. This needs to run create_change_set first. :param awsclient: :param change_set_name: :param stack_name: """ client = awsclient.get_client('cloudformation') status = None while s...
[ "def", "describe_change_set", "(", "awsclient", ",", "change_set_name", ",", "stack_name", ")", ":", "client", "=", "awsclient", ".", "get_client", "(", "'cloudformation'", ")", "status", "=", "None", "while", "status", "not", "in", "[", "'CREATE_COMPLETE'", ","...
34.681818
0.001276
def is_configured(self, project, **kwargs): """ Check if plugin is configured. """ params = self.get_option return bool(params('server_host', project) and params('server_port', project))
[ "def", "is_configured", "(", "self", ",", "project", ",", "*", "*", "kwargs", ")", ":", "params", "=", "self", ".", "get_option", "return", "bool", "(", "params", "(", "'server_host'", ",", "project", ")", "and", "params", "(", "'server_port'", ",", "pro...
36.833333
0.013274
def clean(self, ): """Reimplemented from :class:`models.Model`. Check if startframe is before endframe :returns: None :rtype: None :raises: ValidationError """ if self.startframe > self.endframe: raise ValidationError("Shot starts before it ends: Framerange(%...
[ "def", "clean", "(", "self", ",", ")", ":", "if", "self", ".", "startframe", ">", "self", ".", "endframe", ":", "raise", "ValidationError", "(", "\"Shot starts before it ends: Framerange(%s - %s)\"", "%", "(", "self", ".", "startframe", ",", "self", ".", "endf...
39.555556
0.010989
def only_for(theme, redirect_to='/', raise_error=None): """ Decorator for restrict access to views according by list of themes. Params: * ``theme`` - string or list of themes where decorated view must be * ``redirect_to`` - url or name of url pattern for redirect if CURRENT_THEME n...
[ "def", "only_for", "(", "theme", ",", "redirect_to", "=", "'/'", ",", "raise_error", "=", "None", ")", ":", "def", "check_theme", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "theme", ",", "six", ".", "string_types", ...
25.076923
0.000984
def get_connectware_id(self, use_cached=True): """Get the connectware id of this device (primary key)""" device_json = self.get_device_json(use_cached) return device_json.get("devConnectwareId")
[ "def", "get_connectware_id", "(", "self", ",", "use_cached", "=", "True", ")", ":", "device_json", "=", "self", ".", "get_device_json", "(", "use_cached", ")", "return", "device_json", ".", "get", "(", "\"devConnectwareId\"", ")" ]
53.75
0.009174
def handle_response(self, msg, address): """Deal with incoming response packets. All answers are held in the cache, and listeners are notified.""" now = current_time_millis() sigs = [] precache = [] for record in msg.answers: if isinstance(record, DNSSignat...
[ "def", "handle_response", "(", "self", ",", "msg", ",", "address", ")", ":", "now", "=", "current_time_millis", "(", ")", "sigs", "=", "[", "]", "precache", "=", "[", "]", "for", "record", "in", "msg", ".", "answers", ":", "if", "isinstance", "(", "r...
38.882353
0.002361
def Conectar(self, cache=None, wsdl=None, proxy="", wrapper=None, cacert=None, timeout=30, soap_server=None): "Conectar cliente soap del web service" try: # analizar transporte y servidor proxy: if wrapper: Http = set_http_wrapper(wrapper) self.Ver...
[ "def", "Conectar", "(", "self", ",", "cache", "=", "None", ",", "wsdl", "=", "None", ",", "proxy", "=", "\"\"", ",", "wrapper", "=", "None", ",", "cacert", "=", "None", ",", "timeout", "=", "30", ",", "soap_server", "=", "None", ")", ":", "try", ...
52.649351
0.009201
def p_field_optional2_3(self, p): """ field : name arguments directives """ p[0] = Field(name=p[1], arguments=p[2], directives=p[3])
[ "def", "p_field_optional2_3", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Field", "(", "name", "=", "p", "[", "1", "]", ",", "arguments", "=", "p", "[", "2", "]", ",", "directives", "=", "p", "[", "3", "]", ")" ]
32
0.012195
def locate_point(nodes, x_val, y_val): r"""Find the parameter corresponding to a point on a curve. .. note:: This assumes that the curve :math:`B(s, t)` defined by ``nodes`` lives in :math:`\mathbf{R}^2`. Args: nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve. ...
[ "def", "locate_point", "(", "nodes", ",", "x_val", ",", "y_val", ")", ":", "# First, reduce to the true degree of x(s) and y(s).", "zero1", "=", "_curve_helpers", ".", "full_reduce", "(", "nodes", "[", "[", "0", "]", ",", ":", "]", ")", "-", "x_val", "zero2", ...
40.047619
0.00058
def prefork(self, options, options_bootstrapper): """Runs all pre-fork logic in the process context of the daemon. :returns: `(LegacyGraphSession, TargetRoots, exit_code)` """ # If any nodes exist in the product graph, wait for the initial watchman event to avoid # racing watchman startup vs invali...
[ "def", "prefork", "(", "self", ",", "options", ",", "options_bootstrapper", ")", ":", "# If any nodes exist in the product graph, wait for the initial watchman event to avoid", "# racing watchman startup vs invalidation events.", "graph_len", "=", "self", ".", "_scheduler", ".", ...
43.318182
0.008214
def create_device_role(role, color): ''' .. versionadded:: 2019.2.0 Create a device role role String of device role, e.g., ``router`` CLI Example: .. code-block:: bash salt myminion netbox.create_device_role router ''' nb_role = get_('dcim', 'device-roles', name=role...
[ "def", "create_device_role", "(", "role", ",", "color", ")", ":", "nb_role", "=", "get_", "(", "'dcim'", ",", "'device-roles'", ",", "name", "=", "role", ")", "if", "nb_role", ":", "return", "False", "else", ":", "payload", "=", "{", "'name'", ":", "ro...
23.16
0.001658
def find_executable_files(): """ Find max 5 executables that are responsible for this repo. """ files = glob.glob("*") + glob.glob("*/*") + glob.glob('*/*/*') files = filter(lambda f: os.path.isfile(f), files) executable = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH final = [] for filenam...
[ "def", "find_executable_files", "(", ")", ":", "files", "=", "glob", ".", "glob", "(", "\"*\"", ")", "+", "glob", ".", "glob", "(", "\"*/*\"", ")", "+", "glob", ".", "glob", "(", "'*/*/*'", ")", "files", "=", "filter", "(", "lambda", "f", ":", "os"...
33.411765
0.001712
def validate_json(data, validator): """Validate data against a given JSON schema (see https://json-schema.org). data: JSON-serializable data to validate. validator (jsonschema.DraftXValidator): The validator. RETURNS (list): A list of error messages, if available. """ errors = [] for err in...
[ "def", "validate_json", "(", "data", ",", "validator", ")", ":", "errors", "=", "[", "]", "for", "err", "in", "sorted", "(", "validator", ".", "iter_errors", "(", "data", ")", ",", "key", "=", "lambda", "e", ":", "e", ".", "path", ")", ":", "if", ...
41.894737
0.002457
def initialize(self, name, reuse=False): """Create an empty Sorting Hat registry. This method creates a new database including the schema of Sorting Hat. Any attempt to create a new registry over an existing instance will produce an error, except if reuse=True. In that case, the ...
[ "def", "initialize", "(", "self", ",", "name", ",", "reuse", "=", "False", ")", ":", "user", "=", "self", ".", "_kwargs", "[", "'user'", "]", "password", "=", "self", ".", "_kwargs", "[", "'password'", "]", "host", "=", "self", ".", "_kwargs", "[", ...
37.05
0.001315
def ipi_name_number(name=None): """ IPI Name Number field. An IPI Name Number is composed of eleven digits. So, for example, an IPI Name Number code field can contain 00014107338. :param name: name for the field :return: a parser for the IPI Name Number field """ if name is None: ...
[ "def", "ipi_name_number", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'IPI Name Number Field'", "field", "=", "basic", ".", "numeric", "(", "11", ")", "field", ".", "setName", "(", "name", ")", "return", "field", ...
21.95
0.002183
def candle_lighting(self): """Return the time for candle lighting, or None if not applicable.""" today = HDate(gdate=self.date, diaspora=self.location.diaspora) tomorrow = HDate(gdate=self.date + dt.timedelta(days=1), diaspora=self.location.diaspora) # If today...
[ "def", "candle_lighting", "(", "self", ")", ":", "today", "=", "HDate", "(", "gdate", "=", "self", ".", "date", ",", "diaspora", "=", "self", ".", "location", ".", "diaspora", ")", "tomorrow", "=", "HDate", "(", "gdate", "=", "self", ".", "date", "+"...
45.842105
0.00225
def parse_transdos(path_dir, efermi, dos_spin=1, trim_dos=False): """ Parses .transdos (total DOS) and .transdos_x_y (partial DOS) files Args: path_dir: (str) dir containing DOS files efermi: (float) Fermi energy dos_spin: (int) -1 for spin down, +1 for spin ...
[ "def", "parse_transdos", "(", "path_dir", ",", "efermi", ",", "dos_spin", "=", "1", ",", "trim_dos", "=", "False", ")", ":", "data_dos", "=", "{", "'total'", ":", "[", "]", ",", "'partial'", ":", "{", "}", "}", "# parse the total DOS data", "## format is e...
42.909091
0.000888
def expand(self, a=None, f=None, lmax=None, lmax_calc=None, normal_gravity=True, sampling=2): """ Create 2D cylindrical maps on a flattened and rotating ellipsoid of all three components of the gravity field, the gravity disturbance, and the gravitational potential, and re...
[ "def", "expand", "(", "self", ",", "a", "=", "None", ",", "f", "=", "None", ",", "lmax", "=", "None", ",", "lmax_calc", "=", "None", ",", "normal_gravity", "=", "True", ",", "sampling", "=", "2", ")", ":", "if", "a", "is", "None", ":", "a", "="...
43.891304
0.000727
def latcyl(radius, lon, lat): """ Convert from latitudinal coordinates to cylindrical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latcyl_c.html :param radius: Distance of a point from the origin. :type radius: :param lon: Angle of the point from the XZ plane in radians...
[ "def", "latcyl", "(", "radius", ",", "lon", ",", "lat", ")", ":", "radius", "=", "ctypes", ".", "c_double", "(", "radius", ")", "lon", "=", "ctypes", ".", "c_double", "(", "lon", ")", "lat", "=", "ctypes", ".", "c_double", "(", "lat", ")", "r", "...
34.227273
0.001292
def do_list_modules(self, long_output=None,sort_order=None): """Display a list of loaded modules. Config items: - shutit.list_modules['long'] If set, also print each module's run order value - shutit.list_modules['sort'] Select the column by which the list is ordered: - id: sort the list by mo...
[ "def", "do_list_modules", "(", "self", ",", "long_output", "=", "None", ",", "sort_order", "=", "None", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "# list of module ids and other details"...
39.968421
0.034695
def _fn_with_meta(f, meta: Optional[lmap.Map]): """Return a new function with the given meta. If the function f already has a meta map, then merge the """ if not isinstance(meta, lmap.Map): raise TypeError("meta must be a map") if inspect.iscoroutinefunction(f): @functools.wraps(f) ...
[ "def", "_fn_with_meta", "(", "f", ",", "meta", ":", "Optional", "[", "lmap", ".", "Map", "]", ")", ":", "if", "not", "isinstance", "(", "meta", ",", "lmap", ".", "Map", ")", ":", "raise", "TypeError", "(", "\"meta must be a map\"", ")", "if", "inspect"...
29.538462
0.001261
def rowCount(self, parentIndex=QtCore.QModelIndex()): """ Returns the number of rows under the given parent. When the parent is valid it means that rowCount is returning the number of children of parent. Note: When implementing a table based model, rowCount() should return 0 when the pa...
[ "def", "rowCount", "(", "self", ",", "parentIndex", "=", "QtCore", ".", "QModelIndex", "(", ")", ")", ":", "parentItem", "=", "self", ".", "getItem", "(", "parentIndex", ",", "altItem", "=", "self", ".", "invisibleRootItem", ")", "return", "parentItem", "....
51.888889
0.008421
def num_samples(self): """ Return the total number of samples. """ with self.container.open_if_needed(mode='r') as cnt: return cnt.get(self.key)[0].shape[0]
[ "def", "num_samples", "(", "self", ")", ":", "with", "self", ".", "container", ".", "open_if_needed", "(", "mode", "=", "'r'", ")", "as", "cnt", ":", "return", "cnt", ".", "get", "(", "self", ".", "key", ")", "[", "0", "]", ".", "shape", "[", "0"...
32.5
0.01
def top_k_softmax(x, k): """Calculate softmax(x), select top-k and rescale to sum to 1.""" x = tf.nn.softmax(x) top_x, _ = tf.nn.top_k(x, k=k+1) min_top = tf.reduce_min(top_x, axis=-1, keepdims=True) x = tf.nn.relu((x - min_top) + 1e-12) x /= tf.reduce_sum(x, axis=-1, keepdims=True) return x, tf.reduce_ma...
[ "def", "top_k_softmax", "(", "x", ",", "k", ")", ":", "x", "=", "tf", ".", "nn", ".", "softmax", "(", "x", ")", "top_x", ",", "_", "=", "tf", ".", "nn", ".", "top_k", "(", "x", ",", "k", "=", "k", "+", "1", ")", "min_top", "=", "tf", ".",...
41.25
0.023739
def is_initialised( self ): """ Check whether the simulation has been initialised. Args: None Returns: None """ if not self.lattice: raise AttributeError('Running a simulation needs the lattice to be initialised') if not self....
[ "def", "is_initialised", "(", "self", ")", ":", "if", "not", "self", ".", "lattice", ":", "raise", "AttributeError", "(", "'Running a simulation needs the lattice to be initialised'", ")", "if", "not", "self", ".", "atoms", ":", "raise", "AttributeError", "(", "'R...
35.125
0.012132
def next(self): """ Get the next child. @return: The next child. @rtype: L{Element} @raise StopIterator: At the end. """ try: child = self.children[self.pos] self.pos += 1 return child except: raise StopItera...
[ "def", "next", "(", "self", ")", ":", "try", ":", "child", "=", "self", ".", "children", "[", "self", ".", "pos", "]", "self", ".", "pos", "+=", "1", "return", "child", "except", ":", "raise", "StopIteration", "(", ")" ]
24.153846
0.009202
def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str """ safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # ...
[ "def", "requote_uri", "(", "uri", ")", ":", "safe_with_percent", "=", "\"!#$%&'()*+,/:;=?@[]~\"", "safe_without_percent", "=", "\"!#$&'()*+,/:;=?@[]~\"", "try", ":", "# Unquote only the unreserved characters", "# Then quote only illegal characters (do not quote reserved,", "# unreser...
40.05
0.00122
def acquisition_function(self, x): """ Returns the value of the acquisition function at x. """ return self._penalized_acquisition(x, self.model, self.X_batch, self.r_x0, self.s_x0)
[ "def", "acquisition_function", "(", "self", ",", "x", ")", ":", "return", "self", ".", "_penalized_acquisition", "(", "x", ",", "self", ".", "model", ",", "self", ".", "X_batch", ",", "self", ".", "r_x0", ",", "self", ".", "s_x0", ")" ]
34.666667
0.014085
def create_route_long_name(relation, short_name): """Create a meaningful route name.""" if relation.tags.get('from') and relation.tags.get('to'): return "{0}-to-{1}".format(relation.tags.get('from'), relation.tags.get('to')) name = relation.tags.get('name') or\ ...
[ "def", "create_route_long_name", "(", "relation", ",", "short_name", ")", ":", "if", "relation", ".", "tags", ".", "get", "(", "'from'", ")", "and", "relation", ".", "tags", ".", "get", "(", "'to'", ")", ":", "return", "\"{0}-to-{1}\"", ".", "format", "(...
41.142857
0.001698
def do_eval(self, inputs, ctx): """Evalute ourselves.""" return cwltool.expression.do_eval( self.expr, inputs, self.req, None, None, {}, context=ctx)
[ "def", "do_eval", "(", "self", ",", "inputs", ",", "ctx", ")", ":", "return", "cwltool", ".", "expression", ".", "do_eval", "(", "self", ".", "expr", ",", "inputs", ",", "self", ".", "req", ",", "None", ",", "None", ",", "{", "}", ",", "context", ...
43.5
0.011299
def js_click(self, selector, by=By.CSS_SELECTOR): """ Clicks an element using pure JS. Does not use jQuery. """ selector, by = self.__recalculate_selector(selector, by) if by == By.LINK_TEXT: message = ( "Pure JavaScript doesn't support clicking by Link Text. " ...
[ "def", "js_click", "(", "self", ",", "selector", ",", "by", "=", "By", ".", "CSS_SELECTOR", ")", ":", "selector", ",", "by", "=", "self", ".", "__recalculate_selector", "(", "selector", ",", "by", ")", "if", "by", "==", "By", ".", "LINK_TEXT", ":", "...
53.521739
0.001596
def prepare_env(cls): """Prepares current environment and returns Python binary name. This adds some virtualenv friendliness so that we try use uwsgi from it. :rtype: str|unicode """ os.environ['PATH'] = cls.get_env_path() return os.path.basename(Finder.python())
[ "def", "prepare_env", "(", "cls", ")", ":", "os", ".", "environ", "[", "'PATH'", "]", "=", "cls", ".", "get_env_path", "(", ")", "return", "os", ".", "path", ".", "basename", "(", "Finder", ".", "python", "(", ")", ")" ]
33.888889
0.009585
def parse_content_type_header(value): """ maintype "/" subtype *( ";" parameter ) The maintype and substype are tokens. Theoretically they could be checked against the official IANA list + x-token, but we don't do that. """ ctype = ContentType() recover = False if not value: ct...
[ "def", "parse_content_type_header", "(", "value", ")", ":", "ctype", "=", "ContentType", "(", ")", "recover", "=", "False", "if", "not", "value", ":", "ctype", ".", "defects", ".", "append", "(", "errors", ".", "HeaderMissingRequiredValue", "(", "\"Missing con...
40.017857
0.000436
def import_translations(request, language): """ Importa las traducciones a partir de un archivo PO. Ten en cuenta que el archivo PO ha de ser generado desde esta aplicación, de forma que los comentarios sirvan como id de traducción (lo metemos nosotros en la exportación). """ def _import_po_file(uploadedfile, la...
[ "def", "import_translations", "(", "request", ",", "language", ")", ":", "def", "_import_po_file", "(", "uploadedfile", ",", "lang", ")", ":", "lines", "=", "[", "]", "for", "line", "in", "uploadedfile", ":", "lines", ".", "append", "(", "line", ")", "nu...
35.134328
0.036364
def delete(self, string): """ Delete a string from the AutoCompleter index. Returns 1 if the string was found and deleted, 0 otherwise """ return self.redis.execute_command(AutoCompleter.SUGDEL_COMMAND, self.key, string)
[ "def", "delete", "(", "self", ",", "string", ")", ":", "return", "self", ".", "redis", ".", "execute_command", "(", "AutoCompleter", ".", "SUGDEL_COMMAND", ",", "self", ".", "key", ",", "string", ")" ]
42.5
0.011538
def _migrate0to1(previous: Mapping[str, Any]) -> SettingsMap: """ Migrate to version 1 of the feature flags file. Replaces old IDs with new IDs and sets any False values to None """ next: SettingsMap = {} for s in settings: id = s.id old_id = s.old_id if previous.get(id...
[ "def", "_migrate0to1", "(", "previous", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "SettingsMap", ":", "next", ":", "SettingsMap", "=", "{", "}", "for", "s", "in", "settings", ":", "id", "=", "s", ".", "id", "old_id", "=", "s", ".", ...
24.736842
0.002049
def create_swarm_spec(self, *args, **kwargs): """ Create a :py:class:`docker.types.SwarmSpec` instance that can be used as the ``swarm_spec`` argument in :py:meth:`~docker.api.swarm.SwarmApiMixin.init_swarm`. Args: task_history_retention_limit (int): Maximum number o...
[ "def", "create_swarm_spec", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ext_ca", "=", "kwargs", ".", "pop", "(", "'external_ca'", ",", "None", ")", "if", "ext_ca", ":", "kwargs", "[", "'external_cas'", "]", "=", "[", "ext_ca", ...
47.066667
0.000694
def glymur_config(): """ Try to ascertain locations of openjp2, openjpeg libraries. Returns ------- tuple tuple of library handles """ handles = (load_openjpeg_library(x) for x in ['openjp2', 'openjpeg']) handles = tuple(handles) if all(handle is None for handle in handles)...
[ "def", "glymur_config", "(", ")", ":", "handles", "=", "(", "load_openjpeg_library", "(", "x", ")", "for", "x", "in", "[", "'openjp2'", ",", "'openjpeg'", "]", ")", "handles", "=", "tuple", "(", "handles", ")", "if", "all", "(", "handle", "is", "None",...
27
0.002237
def cli(env): """Summary info about tickets.""" mask = ('openTicketCount, closedTicketCount, ' 'openBillingTicketCount, openOtherTicketCount, ' 'openSalesTicketCount, openSupportTicketCount, ' 'openAccountingTicketCount') account = env.client['Account'].getObject(mask=ma...
[ "def", "cli", "(", "env", ")", ":", "mask", "=", "(", "'openTicketCount, closedTicketCount, '", "'openBillingTicketCount, openOtherTicketCount, '", "'openSalesTicketCount, openSupportTicketCount, '", "'openAccountingTicketCount'", ")", "account", "=", "env", ".", "client", "[",...
42.272727
0.001052
def sens_power_encode(self, adc121_vspb_volt, adc121_cspb_amp, adc121_cs1_amp, adc121_cs2_amp): ''' Voltage and current sensor data adc121_vspb_volt : Power board voltage sensor reading in volts (float) adc121_cspb_amp : Power board cur...
[ "def", "sens_power_encode", "(", "self", ",", "adc121_vspb_volt", ",", "adc121_cspb_amp", ",", "adc121_cs1_amp", ",", "adc121_cs2_amp", ")", ":", "return", "MAVLink_sens_power_message", "(", "adc121_vspb_volt", ",", "adc121_cspb_amp", ",", "adc121_cs1_amp", ",", "adc121...
60.454545
0.011852
def params(self): """ Read self params from configuration. """ parser = JinjaInterpolationNamespace() parser.read(self.configuration) return dict(parser['params'] or {})
[ "def", "params", "(", "self", ")", ":", "parser", "=", "JinjaInterpolationNamespace", "(", ")", "parser", ".", "read", "(", "self", ".", "configuration", ")", "return", "dict", "(", "parser", "[", "'params'", "]", "or", "{", "}", ")" ]
39.4
0.00995
def conf(self, key): '''get config''' return self.__conf[key] if key in self.__conf else _YunpianConf.YP_CONF.get(key)
[ "def", "conf", "(", "self", ",", "key", ")", ":", "return", "self", ".", "__conf", "[", "key", "]", "if", "key", "in", "self", ".", "__conf", "else", "_YunpianConf", ".", "YP_CONF", ".", "get", "(", "key", ")" ]
44
0.022388
def remove(args): """Remove a file from the project's storage. The first part of the remote path is interpreted as the name of the storage provider. If there is no match the default (osfstorage) is used. """ osf = _setup_osf(args) if osf.username is None or osf.password is None: sys...
[ "def", "remove", "(", "args", ")", ":", "osf", "=", "_setup_osf", "(", "args", ")", "if", "osf", ".", "username", "is", "None", "or", "osf", ".", "password", "is", "None", ":", "sys", ".", "exit", "(", "'To remove a file you need to provide a username and'",...
31.3
0.00155
def lfsr_next_one_seed(seed_iter, min_value_shift): """High-quality seeding for LFSR generators. The LFSR generator components discard a certain number of their lower bits when generating each output. The significant bits of their state must not all be zero. We must ensure that when seeding the gen...
[ "def", "lfsr_next_one_seed", "(", "seed_iter", ",", "min_value_shift", ")", ":", "try", ":", "seed", "=", "seed_iter", ".", "next", "(", ")", "except", "StopIteration", ":", "return", "0xFFFFFFFF", "else", ":", "if", "seed", "is", "None", ":", "return", "0...
41.2
0.002372
def remove_lock(lock, key, session=None): """Remove a lock (no matter what it's connected to). """ return _request('get', '/remove/lock/{0}'.format(lock), params={'key': key}, session=session)
[ "def", "remove_lock", "(", "lock", ",", "key", ",", "session", "=", "None", ")", ":", "return", "_request", "(", "'get'", ",", "'/remove/lock/{0}'", ".", "format", "(", "lock", ")", ",", "params", "=", "{", "'key'", ":", "key", "}", ",", "session", "...
50.25
0.009804
def add_update_resources(self, resources, ignore_datasetid=False): # type: (List[Union[hdx.data.resource.Resource,Dict,str]], bool) -> None """Add new or update existing resources with new metadata to the dataset Args: resources (List[Union[hdx.data.resource.Resource,Dict,str]]): A ...
[ "def", "add_update_resources", "(", "self", ",", "resources", ",", "ignore_datasetid", "=", "False", ")", ":", "# type: (List[Union[hdx.data.resource.Resource,Dict,str]], bool) -> None", "if", "not", "isinstance", "(", "resources", ",", "list", ")", ":", "raise", "HDXEr...
50.066667
0.00915
def from_settings(cls, settings): """ Creates a :class:`~explauto.experiment.experiment.Experiment` object thanks to the given settings. """ env_cls, env_configs, _ = environments[settings.environment] config = env_configs[settings.environment_config] if settings.context_mode is None: ...
[ "def", "from_settings", "(", "cls", ",", "settings", ")", ":", "env_cls", ",", "env_configs", ",", "_", "=", "environments", "[", "settings", ".", "environment", "]", "config", "=", "env_configs", "[", "settings", ".", "environment_config", "]", "if", "setti...
54.033333
0.009091
def render(template, **kwargs): """ Renders the HTML containing provided summaries. The summary has to be an instance of summary.Summary, or at least contain similar properties: title, image, url, description and collections: titles, images, descriptions. """ import jinja2 imp...
[ "def", "render", "(", "template", ",", "*", "*", "kwargs", ")", ":", "import", "jinja2", "import", "os", ".", "path", "as", "path", "searchpath", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "__file__", ")", ",", "\"templates\"", ")", ...
32.277778
0.008361
def validate_categories_equal_entities(categories, entities, message=None, exception=MatrixError): """Validate that the matrix has equal number of entities and categories.""" nb_categories = len(categories) nb_entities = len(entities) if message is None: me...
[ "def", "validate_categories_equal_entities", "(", "categories", ",", "entities", ",", "message", "=", "None", ",", "exception", "=", "MatrixError", ")", ":", "nb_categories", "=", "len", "(", "categories", ")", "nb_entities", "=", "len", "(", "entities", ")", ...
50
0.001965
def output(stream): """Write the contents of the given stream to stdout.""" while True: content = stream.read(1024) if len(content) == 0: break sys.stdout.write(content)
[ "def", "output", "(", "stream", ")", ":", "while", "True", ":", "content", "=", "stream", ".", "read", "(", "1024", ")", "if", "len", "(", "content", ")", "==", "0", ":", "break", "sys", ".", "stdout", ".", "write", "(", "content", ")" ]
32.666667
0.00995
def create(self, destination, mask, next_hops=[]): """Create route to {destination} {mask} using {next_hops} expressed as (gateway, distance)""" payload = { "rib": self._build_payload(destination, mask, next_hops) } return self._post(self.url_prefix, payload)
[ "def", "create", "(", "self", ",", "destination", ",", "mask", ",", "next_hops", "=", "[", "]", ")", ":", "payload", "=", "{", "\"rib\"", ":", "self", ".", "_build_payload", "(", "destination", ",", "mask", ",", "next_hops", ")", "}", "return", "self",...
42.571429
0.009868
def get(self, filter=False): """ Returns a dictionary with the values of the model. Note that the values of the leafs are YANG classes. Args: filter (bool): If set to ``True``, show only values that have been set. Returns: dict: A dictionary with the val...
[ "def", "get", "(", "self", ",", "filter", "=", "False", ")", ":", "result", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "elements", "(", ")", ".", "items", "(", ")", ":", "intermediate", "=", "v", ".", "get", "(", "filter", "=", "...
31.136364
0.002123
def lag_plot(series, lag=1, ax=None, **kwds): """Lag plot for time series. Parameters ---------- series : Time series lag : lag of the scatter plot, default 1 ax : Matplotlib axis object, optional kwds : Matplotlib scatter method keyword arguments, optional Returns ------- clas...
[ "def", "lag_plot", "(", "series", ",", "lag", "=", "1", ",", "ax", "=", "None", ",", "*", "*", "kwds", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "# workaround because `c='b'` is hardcoded in matplotlibs scatter method", "kwds", ".", "setdefau...
25.928571
0.001328
def extract(fileobj, keywords, comment_tags, options): """Extracts translation messages from underscore template files. This method does also extract django templates. If a template does not contain any django translation tags we always fallback to underscore extraction. This is a plugin to Babel, wri...
[ "def", "extract", "(", "fileobj", ",", "keywords", ",", "comment_tags", ",", "options", ")", ":", "encoding", "=", "options", ".", "get", "(", "'encoding'", ",", "'utf-8'", ")", "original_position", "=", "fileobj", ".", "tell", "(", ")", "text", "=", "fi...
35.64
0.001092
def _clashes(self, startTime, duration): """ verifies that this measurement does not clash with an already scheduled measurement. :param startTime: the start time. :param duration: the duration. :return: true if the measurement is allowed. """ return [m for m in s...
[ "def", "_clashes", "(", "self", ",", "startTime", ",", "duration", ")", ":", "return", "[", "m", "for", "m", "in", "self", ".", "activeMeasurements", "if", "m", ".", "overlapsWith", "(", "startTime", ",", "duration", ")", "]" ]
46.875
0.010471
def value(self): """ Return current value for the metric """ if self.buffer: return np.quantile(self.buffer, self.quantile) else: return 0.0
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "buffer", ":", "return", "np", ".", "quantile", "(", "self", ".", "buffer", ",", "self", ".", "quantile", ")", "else", ":", "return", "0.0" ]
30.5
0.010638
def walk(self, mtop, topdown=True): """`os.walk(path)` for a directory in Manta. A somewhat limited form in that some of the optional args to `os.walk` are not supported. Also, instead of dir *names* and file *names*, the dirents for those are returned. E.g.: >>> for dirpat...
[ "def", "walk", "(", "self", ",", "mtop", ",", "topdown", "=", "True", ")", ":", "dirents", "=", "self", ".", "ls", "(", "mtop", ")", "mdirs", ",", "mnondirs", "=", "[", "]", ",", "[", "]", "for", "dirent", "in", "sorted", "(", "dirents", ".", "...
35.05
0.002082
def rename(python_data: LdapObject, new_base_dn: str = None, database: Optional[Database] = None, **kwargs) -> LdapObject: """ Move/rename a LdapObject in the database. """ table = type(python_data) dn = python_data.get_as_single('dn') assert dn is not None database = get_database(databa...
[ "def", "rename", "(", "python_data", ":", "LdapObject", ",", "new_base_dn", ":", "str", "=", "None", ",", "database", ":", "Optional", "[", "Database", "]", "=", "None", ",", "*", "*", "kwargs", ")", "->", "LdapObject", ":", "table", "=", "type", "(", ...
23.627451
0.000797
def role_write(self, fail_on_found=False, disassociate=False, **kwargs): """Re-implementation of the parent `write` method specific to roles. Adds a grantee (user or team) to the resource's role.""" # Get the role, using only the resource data data, self.endpoint = self.data_endpoint(kw...
[ "def", "role_write", "(", "self", ",", "fail_on_found", "=", "False", ",", "disassociate", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Get the role, using only the resource data", "data", ",", "self", ".", "endpoint", "=", "self", ".", "data_endpoint", ...
44.510204
0.000897
def do_action(self, action): """Execute action, add a new tile, update the score & return the reward.""" temp_state = np.rot90(self._state, action) reward = self._do_action_left(temp_state) self._state = np.rot90(temp_state, -action) self._score += reward self.add_rando...
[ "def", "do_action", "(", "self", ",", "action", ")", ":", "temp_state", "=", "np", ".", "rot90", "(", "self", ".", "_state", ",", "action", ")", "reward", "=", "self", ".", "_do_action_left", "(", "temp_state", ")", "self", ".", "_state", "=", "np", ...
31
0.008547
def quad_genz_keister_18(order): """ Hermite Genz-Keister 18 rule. Args: order (int): The quadrature order. Must be in the interval (0, 8). Returns: (:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]): Abscissas and weights Examples: >>> abscissas...
[ "def", "quad_genz_keister_18", "(", "order", ")", ":", "order", "=", "sorted", "(", "GENZ_KEISTER_18", ".", "keys", "(", ")", ")", "[", "order", "]", "abscissas", ",", "weights", "=", "GENZ_KEISTER_18", "[", "order", "]", "abscissas", "=", "numpy", ".", ...
26.206897
0.001269
def handle_subscribe(self, request): # type: (Subscribe) -> CallbackResponses """Handle a Subscribe request from outside. Called with lock taken""" ret = self._tree.handle_subscribe(request, request.path[1:]) self._subscription_keys[request.generate_key()] = request return ret
[ "def", "handle_subscribe", "(", "self", ",", "request", ")", ":", "# type: (Subscribe) -> CallbackResponses", "ret", "=", "self", ".", "_tree", ".", "handle_subscribe", "(", "request", ",", "request", ".", "path", "[", "1", ":", "]", ")", "self", ".", "_subs...
52
0.009464
def generate_phrase_detection_function(cls, min_token_count, max_phrases, exclude_ngram_filter=None): """ This is a factory function for generating a phrase detection function :param cls: the class :param min_token_count: tokens that appear less than this will be ignored in the phrase de...
[ "def", "generate_phrase_detection_function", "(", "cls", ",", "min_token_count", ",", "max_phrases", ",", "exclude_ngram_filter", "=", "None", ")", ":", "#if exclude_ngram_filter is None and cls.exclude_ngram_filter:", "# exclude_ngram_filter = cls.exclude_ngram_filter", "def", ...
55.666667
0.008094
def users_for_perm( cls, instance, perm_name, user_ids=None, group_ids=None, limit_group_permissions=False, skip_group_perms=False, db_session=None, ): """ return PermissionTuples for users AND groups that have given permission ...
[ "def", "users_for_perm", "(", "cls", ",", "instance", ",", "perm_name", ",", "user_ids", "=", "None", ",", "group_ids", "=", "None", ",", "limit_group_permissions", "=", "False", ",", "skip_group_perms", "=", "False", ",", "db_session", "=", "None", ",", ")"...
35.086207
0.001912
def getTrackedDeviceClass(self, unDeviceIndex): """ Returns the device class of a tracked device. If there has not been a device connected in this slot since the application started this function will return TrackedDevice_Invalid. For previous detected devices the function will return th...
[ "def", "getTrackedDeviceClass", "(", "self", ",", "unDeviceIndex", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getTrackedDeviceClass", "result", "=", "fn", "(", "unDeviceIndex", ")", "return", "result" ]
55.692308
0.01087
def set_settings(instance=None): """Pick correct settings instance and set it to a global variable.""" global settings settings = None if instance: settings = import_settings(instance) elif "INSTANCE_FOR_DYNACONF" in os.environ: settings = import_settings(os.environ["INSTANCE_FOR...
[ "def", "set_settings", "(", "instance", "=", "None", ")", ":", "global", "settings", "settings", "=", "None", "if", "instance", ":", "settings", "=", "import_settings", "(", "instance", ")", "elif", "\"INSTANCE_FOR_DYNACONF\"", "in", "os", ".", "environ", ":",...
31.081633
0.000637
def from_json(cls, json_data): """Tries to convert a JSON representation to an object of the same type as self A class can provide a _fromJSON implementation in order to do specific type checking or other custom implementation details. This method will throw a ValueError for inv...
[ "def", "from_json", "(", "cls", ",", "json_data", ")", ":", "data", "=", "json", ".", "loads", "(", "json_data", ")", "result", "=", "cls", "(", "data", ")", "if", "hasattr", "(", "result", ",", "\"_from_json\"", ")", ":", "result", ".", "_from_json", ...
39.15
0.002494
def copy(self, *args, **kw): """Load the configuration if necessary and forward the call to the parent.""" if not self._loaded: self.load_config() return super(FedmsgConfig, self).copy(*args, **kw)
[ "def", "copy", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "not", "self", ".", "_loaded", ":", "self", ".", "load_config", "(", ")", "return", "super", "(", "FedmsgConfig", ",", "self", ")", ".", "copy", "(", "*", "args", ...
45.8
0.012876
def parse_classified_by(content, normalize=True): """\ Returns the classificationist or ``None`` if the classificationist cannot be extracted. `content` The cable's content. """ names = [] m = _CLIST_CONTENT_PATTERN.search(content) if not m: return () m = _CLSIST_PAT...
[ "def", "parse_classified_by", "(", "content", ",", "normalize", "=", "True", ")", ":", "names", "=", "[", "]", "m", "=", "_CLIST_CONTENT_PATTERN", ".", "search", "(", "content", ")", "if", "not", "m", ":", "return", "(", ")", "m", "=", "_CLSIST_PATTERN",...
32.791667
0.002469
def get_home_dir(): """ Return user home directory """ try: # expanduser() returns a raw byte string which needs to be # decoded with the codec that the OS is using to represent # file paths. path = encoding.to_unicode_from_fs(osp.expanduser('~')) except Exce...
[ "def", "get_home_dir", "(", ")", ":", "try", ":", "# expanduser() returns a raw byte string which needs to be\r", "# decoded with the codec that the OS is using to represent\r", "# file paths.\r", "path", "=", "encoding", ".", "to_unicode_from_fs", "(", "osp", ".", "expanduser", ...
36.066667
0.0009