text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_input(self, name, ds): """ Retrieves the content of an input given a DataSource. The input acts like a filter over the outputs of the DataSource. Args: name (str): The name of the input. ds (openflow.DataSource): The DataSource that will feed the data. R...
[ "def", "get_input", "(", "self", ",", "name", ",", "ds", ")", ":", "columns", "=", "self", ".", "inputs", ".", "get", "(", "name", ")", "df", "=", "ds", ".", "get_dataframe", "(", ")", "# set defaults", "for", "column", "in", "columns", ":", "if", ...
31.35
21.55
def list(self): """Parse a list (tuple) which can contain any combination of types.""" start = self.tokens.matched.start if self.tokens.accept(common_grammar.rbracket): return ast.Tuple(start=start, end=self.tokens.matched.end, source=self.original) ...
[ "def", "list", "(", "self", ")", ":", "start", "=", "self", ".", "tokens", ".", "matched", ".", "start", "if", "self", ".", "tokens", ".", "accept", "(", "common_grammar", ".", "rbracket", ")", ":", "return", "ast", ".", "Tuple", "(", "start", "=", ...
38.875
19.875
def sequence(self, struct, size=1000, tree_depth=1, append_callable=None): """ Generates random values for sequence-like objects @struct: the sequence-like structure you want to fill with random data @size: #int number of random values to include in each @tree_depth ...
[ "def", "sequence", "(", "self", ",", "struct", ",", "size", "=", "1000", ",", "tree_depth", "=", "1", ",", "append_callable", "=", "None", ")", ":", "if", "not", "tree_depth", ":", "return", "self", ".", "_map_type", "(", ")", "_struct", "=", "struct",...
38.527778
19.694444
def export_project(self): """ Processes groups and misc options specific for eclipse, and run generator """ output = copy.deepcopy(self.generated_project) data_for_make = self.workspace.copy() self.exporter.process_data_for_makefile(data_for_make) output['path'], output['files'...
[ "def", "export_project", "(", "self", ")", ":", "output", "=", "copy", ".", "deepcopy", "(", "self", ".", "generated_project", ")", "data_for_make", "=", "self", ".", "workspace", ".", "copy", "(", ")", "self", ".", "exporter", ".", "process_data_for_makefil...
50
27.782609
def experiment_property(prop): """Get a property of the experiment by name.""" exp = Experiment(session) try: value = exp.public_properties[prop] except KeyError: abort(404) return success_response(**{prop: value})
[ "def", "experiment_property", "(", "prop", ")", ":", "exp", "=", "Experiment", "(", "session", ")", "try", ":", "value", "=", "exp", ".", "public_properties", "[", "prop", "]", "except", "KeyError", ":", "abort", "(", "404", ")", "return", "success_respons...
30.375
12.75
def solve_limited(self, assumptions=[]): """ Solve internal formula using given budgets for conflicts and propagations. """ if self.maplesat: if self.use_timer: start_time = time.clock() # saving default SIGINT handler ...
[ "def", "solve_limited", "(", "self", ",", "assumptions", "=", "[", "]", ")", ":", "if", "self", ".", "maplesat", ":", "if", "self", ".", "use_timer", ":", "start_time", "=", "time", ".", "clock", "(", ")", "# saving default SIGINT handler", "def_sigint_handl...
32.826087
21.434783
def _on_key_pressed(self, event): """ Auto indent if the released key is the return key. :param event: the key event """ if not event.isAccepted(): if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter: cursor = self.editor.textCursor() ...
[ "def", "_on_key_pressed", "(", "self", ",", "event", ")", ":", "if", "not", "event", ".", "isAccepted", "(", ")", ":", "if", "event", ".", "key", "(", ")", "==", "Qt", ".", "Key_Return", "or", "event", ".", "key", "(", ")", "==", "Qt", ".", "Key_...
41.190476
10.904762
def right(self, expand=None): """ Returns a new Region right of the current region with a width of ``expand`` pixels. Does not include the current region. If range is omitted, it reaches to the right border of the screen. The new region has the same height and y-position as the current region. ...
[ "def", "right", "(", "self", ",", "expand", "=", "None", ")", ":", "if", "expand", "==", "None", ":", "x", "=", "self", ".", "x", "+", "self", ".", "w", "y", "=", "self", ".", "y", "w", "=", "self", ".", "getScreen", "(", ")", ".", "getBounds...
37.529412
20
def export(self, nidm_version, export_dir): """ Create prov entities and activities. """ if nidm_version['major'] < 1 or \ (nidm_version['major'] == 1 and nidm_version['minor'] < 3): self.type = NIDM_DATA_SCALING # Create "Data" entity # FIXME: gra...
[ "def", "export", "(", "self", ",", "nidm_version", ",", "export_dir", ")", ":", "if", "nidm_version", "[", "'major'", "]", "<", "1", "or", "(", "nidm_version", "[", "'major'", "]", "==", "1", "and", "nidm_version", "[", "'minor'", "]", "<", "3", ")", ...
40.636364
10.818182
def append(self, lines): """ Args: lines (list): List of line strings to append to the end of the editor """ if isinstance(lines, list): self._lines = self._lines + lines elif isinstance(lines, str): lines = lines.split('\n') self._...
[ "def", "append", "(", "self", ",", "lines", ")", ":", "if", "isinstance", "(", "lines", ",", "list", ")", ":", "self", ".", "_lines", "=", "self", ".", "_lines", "+", "lines", "elif", "isinstance", "(", "lines", ",", "str", ")", ":", "lines", "=", ...
36.083333
14.583333
def decompose(miz_file: Path, output_folder: Path): """ Decompose this Miz into json Args: output_folder: folder to output the json structure as a Path miz_file: MIZ file path as a Path """ mission_folder, assets_folder = NewMiz._get_subfolders(output_fol...
[ "def", "decompose", "(", "miz_file", ":", "Path", ",", "output_folder", ":", "Path", ")", ":", "mission_folder", ",", "assets_folder", "=", "NewMiz", ".", "_get_subfolders", "(", "output_folder", ")", "NewMiz", ".", "_wipe_folders", "(", "mission_folder", ",", ...
43.826087
23.478261
def killJobs(self, jobsToKill): """ Kills the given set of jobs and then sends them for processing """ if len(jobsToKill) > 0: self.batchSystem.killBatchJobs(jobsToKill) for jobBatchSystemID in jobsToKill: self.processFinishedJob(jobBatchSystemID, ...
[ "def", "killJobs", "(", "self", ",", "jobsToKill", ")", ":", "if", "len", "(", "jobsToKill", ")", ">", "0", ":", "self", ".", "batchSystem", ".", "killBatchJobs", "(", "jobsToKill", ")", "for", "jobBatchSystemID", "in", "jobsToKill", ":", "self", ".", "p...
39.375
11.125
def get_image(dockerRequirement, # type: Dict[Text, Text] pull_image, # type: bool force_pull=False # type: bool ): # type: (...) -> bool """ Acquire the software container image in the specified dockerRequirement using Sin...
[ "def", "get_image", "(", "dockerRequirement", ",", "# type: Dict[Text, Text]", "pull_image", ",", "# type: bool", "force_pull", "=", "False", "# type: bool", ")", ":", "# type: (...) -> bool", "found", "=", "False", "candidates", "=", "[", "]", "if", "\"dockerImageId\...
49.852941
21.470588
def update(self, data: Union[Mapping, str, bytes], layer: str=None, source: str=None): """Adds additional data into the ConfigTree. Parameters ---------- data : source data layer : layer to load data into. If none is supplied the outermost one is used ...
[ "def", "update", "(", "self", ",", "data", ":", "Union", "[", "Mapping", ",", "str", ",", "bytes", "]", ",", "layer", ":", "str", "=", "None", ",", "source", ":", "str", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ...
37.222222
22.583333
def tostream(func, module_name=None): """ Decorator to convert the function output into a Stream. Useful for generator functions. Note ---- Always use the ``module_name`` input when "decorating" a function that was defined in other module. """ @wraps(func) def new_func(*args, **kwargs): return...
[ "def", "tostream", "(", "func", ",", "module_name", "=", "None", ")", ":", "@", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "Stream", "(", "func", "(", "*", "args", ",", "*", "*", ...
24.705882
18.705882
def format(self, tokensource, outfile): """ Format ``tokensource``, an iterable of ``(tokentype, tokenstring)`` tuples and write it into ``outfile``. """ if self.encoding: # wrap the outfile in a StreamWriter outfile = codecs.lookup(self.encoding)[3](outfi...
[ "def", "format", "(", "self", ",", "tokensource", ",", "outfile", ")", ":", "if", "self", ".", "encoding", ":", "# wrap the outfile in a StreamWriter", "outfile", "=", "codecs", ".", "lookup", "(", "self", ".", "encoding", ")", "[", "3", "]", "(", "outfile...
41.555556
11.555556
def job_started(self, job, queue): """ Called just before the execution of the job """ job.hmset(start=str(datetime.utcnow()), status=STATUSES.RUNNING) job.tries.hincrby(1) self.log(self.job_started_message(job, queue)) if hasattr(job, 'on_started'): j...
[ "def", "job_started", "(", "self", ",", "job", ",", "queue", ")", ":", "job", ".", "hmset", "(", "start", "=", "str", "(", "datetime", ".", "utcnow", "(", ")", ")", ",", "status", "=", "STATUSES", ".", "RUNNING", ")", "job", ".", "tries", ".", "h...
36.888889
9.333333
def take_snapshot(self, entity_id, lt=None, lte=None): """ Takes a snapshot of the entity as it existed after the most recent event, optionally less than, or less than or equal to, a particular position. """ snapshot = None if self._snapshot_strategy: # Get th...
[ "def", "take_snapshot", "(", "self", ",", "entity_id", ",", "lt", "=", "None", ",", "lte", "=", "None", ")", ":", "snapshot", "=", "None", "if", "self", ".", "_snapshot_strategy", ":", "# Get the latest event (optionally until a particular position).", "latest_event...
47.386364
23.840909
def append(self, symbol, metadata, start_time=None): """ Update metadata entry for `symbol` Parameters ---------- symbol : `str` symbol name for the item metadata : `dict` to be persisted start_time : `datetime.datetime` when m...
[ "def", "append", "(", "self", ",", "symbol", ",", "metadata", ",", "start_time", "=", "None", ")", ":", "if", "start_time", "is", "None", ":", "start_time", "=", "dt", ".", "utcnow", "(", ")", "old_metadata", "=", "self", ".", "find_one", "(", "{", "...
42.909091
22
def _open_sqlite(db_file): """Opens database connection.""" db_file = os.path.expanduser(db_file) try: with open(db_file): # test that the file can be accessed pass return sqlite3.connect(db_file, detect_types=sqlite3.PARSE_DECLTYPES) except (IOError, sqlite3.Erro...
[ "def", "_open_sqlite", "(", "db_file", ")", ":", "db_file", "=", "os", ".", "path", ".", "expanduser", "(", "db_file", ")", "try", ":", "with", "open", "(", "db_file", ")", ":", "# test that the file can be accessed", "pass", "return", "sqlite3", ".", "conne...
37.6
14.6
def get(cls, group_id, db_session=None): """ Fetch row using primary key - will use existing object in session if already present :param group_id: :param db_session: :return: """ db_session = get_db_session(db_session) return db_session.query(cls....
[ "def", "get", "(", "cls", ",", "group_id", ",", "db_session", "=", "None", ")", ":", "db_session", "=", "get_db_session", "(", "db_session", ")", "return", "db_session", ".", "query", "(", "cls", ".", "model", ")", ".", "get", "(", "group_id", ")" ]
30
12.909091
def list_group_maintainers(self, name): """ Get the maintainers of a group. Args: name (string): Name of group to query. Returns: (list[string]): List of maintainer names. Raises: requests.HTTPError on failure. """ self.proje...
[ "def", "list_group_maintainers", "(", "self", ",", "name", ")", ":", "self", ".", "project_service", ".", "set_auth", "(", "self", ".", "_token_project", ")", "return", "self", ".", "project_service", ".", "list_group_maintainers", "(", "name", ")" ]
27.4
17.666667
def _init_depth_texture_draw(self): """Initialize geometry and shader for drawing FBO layers""" from demosys import geometry if not TextureHelper._quad: TextureHelper._quad = geometry.quad_fs() # Shader for drawing depth layers TextureHelper._depth_shader = ...
[ "def", "_init_depth_texture_draw", "(", "self", ")", ":", "from", "demosys", "import", "geometry", "if", "not", "TextureHelper", ".", "_quad", ":", "TextureHelper", ".", "_quad", "=", "geometry", ".", "quad_fs", "(", ")", "# Shader for drawing depth layers\r", "Te...
31.954545
15.75
def run_with_router(func, *args, **kwargs): """ Arrange for `func(router, *args, **kwargs)` to run with a temporary :class:`mitogen.master.Router`, ensuring the Router and Broker are correctly shut down during normal or exceptional return. :returns: `func`'s return value. """ broker...
[ "def", "run_with_router", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "broker", "=", "mitogen", ".", "master", ".", "Broker", "(", ")", "router", "=", "mitogen", ".", "master", ".", "Router", "(", "broker", ")", "try", ":", "r...
30.5625
16.5625
def check(degree, knot_vector, num_ctrlpts): """ Checks the validity of the input knot vector. Please refer to The NURBS Book (2nd Edition), p.50 for details. :param degree: degree of the curve or the surface :type degree: int :param knot_vector: knot vector to be checked :type knot_vector: li...
[ "def", "check", "(", "degree", ",", "knot_vector", ",", "num_ctrlpts", ")", ":", "try", ":", "if", "knot_vector", "is", "None", "or", "len", "(", "knot_vector", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Input knot vector cannot be empty\"", ")", "e...
30.685714
18.742857
def _model_exists_step(self, model, should_exist): """ Test for the existence of a model matching the given data. """ model = get_model(model) data = guess_types(self.hashes) queryset = model.objects try: existence_check = _TEST_MODEL[model] except KeyError: existence_...
[ "def", "_model_exists_step", "(", "self", ",", "model", ",", "should_exist", ")", ":", "model", "=", "get_model", "(", "model", ")", "data", "=", "guess_types", "(", "self", ".", "hashes", ")", "queryset", "=", "model", ".", "objects", "try", ":", "exist...
27.162791
19.116279
def array_extents(self, array_name, **kwargs): """ Return a list of lower and upper extents for the given array_name. .. code-block:: python cube.register("uvw", ("ntime", "na", 3), np.float64) (lt, ut), (la, ua), (_, _) = cube.array_extents("uvw") Par...
[ "def", "array_extents", "(", "self", ",", "array_name", ",", "*", "*", "kwargs", ")", ":", "A", "=", "self", ".", "array", "(", "array_name", ",", "reify", "=", "False", ")", "return", "self", ".", "dim_extents", "(", "*", "A", ".", "shape", ",", "...
24.142857
23.071429
def compilemessages(application): """ Compiles locale messages """ from django.core.management import call_command with work_in(application): if DJANGO_1_11: call_command('compilemessages', all=True) else: call_command('compilemessages')
[ "def", "compilemessages", "(", "application", ")", ":", "from", "django", ".", "core", ".", "management", "import", "call_command", "with", "work_in", "(", "application", ")", ":", "if", "DJANGO_1_11", ":", "call_command", "(", "'compilemessages'", ",", "all", ...
26.181818
12.727273
def get_closest_points(self, max_distance=None, origin_index=0, origin_raw=None): """ Get closest points to a given origin. Returns a list of 2 element tuples where first element is the destination and the second is the distance. """ if not self.dict_response['distance']['value']: ...
[ "def", "get_closest_points", "(", "self", ",", "max_distance", "=", "None", ",", "origin_index", "=", "0", ",", "origin_raw", "=", "None", ")", ":", "if", "not", "self", ".", "dict_response", "[", "'distance'", "]", "[", "'value'", "]", ":", "self", ".",...
42.684211
26.368421
def build(self, builder): """Build XML by appending to builder""" params = dict(OID=self.oid, Name=self.name) if self.unit_dictionary_name: params["mdsol:UnitDictionaryName"] = self.unit_dictionary_name for suffix in ["A", "B", "C", "K"]: val = getattr(self, "c...
[ "def", "build", "(", "self", ",", "builder", ")", ":", "params", "=", "dict", "(", "OID", "=", "self", ".", "oid", ",", "Name", "=", "self", ".", "name", ")", "if", "self", ".", "unit_dictionary_name", ":", "params", "[", "\"mdsol:UnitDictionaryName\"", ...
33.789474
19.105263
def _conn_key(self, instance, db_key, db_name=None): ''' Return a key to use for the connection cache ''' dsn, host, username, password, database, driver = self._get_access_info(instance, db_key, db_name) return '{}:{}:{}:{}:{}:{}'.format(dsn, host, username, password, database, driver)
[ "def", "_conn_key", "(", "self", ",", "instance", ",", "db_key", ",", "db_name", "=", "None", ")", ":", "dsn", ",", "host", ",", "username", ",", "password", ",", "database", ",", "driver", "=", "self", ".", "_get_access_info", "(", "instance", ",", "d...
63
34.6
def get_ini(self, incl_unset=False): """Return the config dictionary in INI format Args: incl_unset (bool): include variables with no defaults. Returns: str: string of the config file in INI format """ configp = configparser.ConfigParser(allow_no_value=...
[ "def", "get_ini", "(", "self", ",", "incl_unset", "=", "False", ")", ":", "configp", "=", "configparser", ".", "ConfigParser", "(", "allow_no_value", "=", "True", ")", "configp", ".", "read_dict", "(", "self", ".", "_config", ")", "with", "StringIO", "(", ...
33.291667
15.958333
def timeout(self, duration=3600): """ Timeout the uploader of this file """ self.room.check_owner() self.conn.make_call("timeoutFile", self.fid, duration)
[ "def", "timeout", "(", "self", ",", "duration", "=", "3600", ")", ":", "self", ".", "room", ".", "check_owner", "(", ")", "self", ".", "conn", ".", "make_call", "(", "\"timeoutFile\"", ",", "self", ".", "fid", ",", "duration", ")" ]
43.75
9.5
def _read_postmaster_pidfile(data_dir): """Reads and parses postmaster.pid from the data directory :returns dictionary of values if successful, empty dictionary otherwise """ pid_line_names = ['pid', 'data_dir', 'start_time', 'port', 'socket_dir', 'listen_addr', 'shmem_key'] try...
[ "def", "_read_postmaster_pidfile", "(", "data_dir", ")", ":", "pid_line_names", "=", "[", "'pid'", ",", "'data_dir'", ",", "'start_time'", ",", "'port'", ",", "'socket_dir'", ",", "'listen_addr'", ",", "'shmem_key'", "]", "try", ":", "with", "open", "(", "os",...
47
26.363636
def get_labs(format): """Gets Lab data from makery.info.""" labs_json = data_from_makery_info(makery_info_labs_api_url) labs = {} # Load all the FabLabs for i in labs_json["labs"]: current_lab = MakeryLab() current_lab.address_1 = i["address_1"] current_lab.address_2 = i["a...
[ "def", "get_labs", "(", "format", ")", ":", "labs_json", "=", "data_from_makery_info", "(", "makery_info_labs_api_url", ")", "labs", "=", "{", "}", "# Load all the FabLabs", "for", "i", "in", "labs_json", "[", "\"labs\"", "]", ":", "current_lab", "=", "MakeryLab...
38.034884
13.860465
def parse_tax_lvl(entry, tax_lvl_depth=[]): """ Parse a single kraken-report entry and return a dictionary of taxa for its named ranks. :type entry: dict :param entry: attributes of a single kraken-report row. :type tax_lvl_depth: list :param tax_lvl_depth: running record of taxon levels en...
[ "def", "parse_tax_lvl", "(", "entry", ",", "tax_lvl_depth", "=", "[", "]", ")", ":", "# How deep in the hierarchy are we currently? Each two spaces of", "# indentation is one level deeper. Also parse the scientific name at this", "# level.", "depth_and_name", "=", "re", ".", "m...
41.6
19.76
def close(self): """ Deletes all static mask objects. """ for key in self.masklist.keys(): self.masklist[key] = None self.masklist = {}
[ "def", "close", "(", "self", ")", ":", "for", "key", "in", "self", ".", "masklist", ".", "keys", "(", ")", ":", "self", ".", "masklist", "[", "key", "]", "=", "None", "self", ".", "masklist", "=", "{", "}" ]
27.833333
13.5
def sign(self, h): """ Return a der-encoded signature for a hash h. Will throw a RuntimeError if this key is not a private key """ if not self.is_private(): raise RuntimeError("Key must be private to be able to sign") val = from_bytes_32(h) r, s = self...
[ "def", "sign", "(", "self", ",", "h", ")", ":", "if", "not", "self", ".", "is_private", "(", ")", ":", "raise", "RuntimeError", "(", "\"Key must be private to be able to sign\"", ")", "val", "=", "from_bytes_32", "(", "h", ")", "r", ",", "s", "=", "self"...
39.1
13.9
def analyze(self, input_directory, output_directory, **kwargs): """ Run all the analysis saved in self._analyses, sorted by test_id. This is useful when Naarad() is used by other programs and multiple analyses are run In naarad CLI mode, len(_analyses) == 1 :param: input_directory: location of log f...
[ "def", "analyze", "(", "self", ",", "input_directory", ",", "output_directory", ",", "*", "*", "kwargs", ")", ":", "is_api_call", "=", "True", "if", "len", "(", "self", ".", "_analyses", ")", "==", "0", ":", "if", "'config'", "not", "in", "kwargs", "."...
43
17.046512
def deleteSelected(self): 'Delete all selected rows.' ndeleted = self.deleteBy(self.isSelected) nselected = len(self._selectedRows) self._selectedRows.clear() if ndeleted != nselected: error('expected %s' % nselected)
[ "def", "deleteSelected", "(", "self", ")", ":", "ndeleted", "=", "self", ".", "deleteBy", "(", "self", ".", "isSelected", ")", "nselected", "=", "len", "(", "self", ".", "_selectedRows", ")", "self", ".", "_selectedRows", ".", "clear", "(", ")", "if", ...
37.571429
7
def claim(self, ttl, grace, count=None): """ Claims up to `count` unclaimed messages from this queue. If count is not specified, the default is to claim 10 messages. The `ttl` parameter specifies how long the server should wait before releasing the claim. The ttl value MUST be b...
[ "def", "claim", "(", "self", ",", "ttl", ",", "grace", ",", "count", "=", "None", ")", ":", "if", "count", "is", "None", ":", "qs", "=", "\"\"", "else", ":", "qs", "=", "\"?limit=%s\"", "%", "count", "uri", "=", "\"/%s%s\"", "%", "(", "self", "."...
44.228571
21.085714
def __convert_node(node, default_value='', default_flags=vsflags()): """Converts a XML node to a JSON equivalent.""" name = __get_attribute(node, 'Name') logging.debug('Found %s named %s', node.tagName, name) converted = {} converted['name'] = name converted['switch'] = __get_attribute(node, 'S...
[ "def", "__convert_node", "(", "node", ",", "default_value", "=", "''", ",", "default_flags", "=", "vsflags", "(", ")", ")", ":", "name", "=", "__get_attribute", "(", "node", ",", "'Name'", ")", "logging", ".", "debug", "(", "'Found %s named %s'", ",", "nod...
30.681818
21.363636
def has_api_scopes(self, *api_scopes): """ Test if all given API scopes are authorized. :type api_scopes: list[str] :param api_scopes: The API scopes to test :rtype: bool|None :return: True or False, if the API Token has the API scopes field set, oth...
[ "def", "has_api_scopes", "(", "self", ",", "*", "api_scopes", ")", ":", "if", "self", ".", "_authorized_api_scopes", "is", "None", ":", "return", "None", "return", "all", "(", "(", "x", "in", "self", ".", "_authorized_api_scopes", ")", "for", "x", "in", ...
31.733333
16.8
def read_projection_from_fits(fitsfile, extname=None): """ Load a WCS or HPX projection. """ f = fits.open(fitsfile) nhdu = len(f) # Try and get the energy bounds try: ebins = find_and_read_ebins(f) except: ebins = None if extname is None: # If there is an im...
[ "def", "read_projection_from_fits", "(", "fitsfile", ",", "extname", "=", "None", ")", ":", "f", "=", "fits", ".", "open", "(", "fitsfile", ")", "nhdu", "=", "len", "(", "f", ")", "# Try and get the energy bounds", "try", ":", "ebins", "=", "find_and_read_eb...
34.230769
15.730769
def get_parent(self): """ Get the parent resource from the database The get, create & update methods will populate the parent for you. Use this method in the cases where parent has not been populated. """ if not self._parent: self._parent = yield self.parent_...
[ "def", "get_parent", "(", "self", ")", ":", "if", "not", "self", ".", "_parent", ":", "self", ".", "_parent", "=", "yield", "self", ".", "parent_resource", ".", "get", "(", "self", ".", "parent_id", ")", "raise", "Return", "(", "self", ".", "_parent", ...
34
20.545455
def create(self, resource, id=None, timeout=-1): """ Adds the specified trap forwarding destination. The trap destination associated with the specified id will be created if trap destination with that id does not exists. The id can only be an integer greater than 0. Args: ...
[ "def", "create", "(", "self", ",", "resource", ",", "id", "=", "None", ",", "timeout", "=", "-", "1", ")", ":", "if", "not", "id", ":", "available_id", "=", "self", ".", "__get_first_available_id", "(", ")", "uri", "=", "'%s/%s'", "%", "(", "self", ...
39.818182
24.727273
def call_async(self, fn, *args, **kwargs): """ Arrange for `fn(*args, **kwargs)` to be invoked on the context's main thread. :param fn: A free function in module scope or a class method of a class directly reachable from module scope: .. code-block::...
[ "def", "call_async", "(", "self", ",", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "LOG", ".", "debug", "(", "'%r.call_async(): %r'", ",", "self", ",", "CallSpec", "(", "fn", ",", "args", ",", "kwargs", ")", ")", "return", "self", "....
36.690909
21.345455
def import_from_dict(session, data, sync=[]): """Imports databases and druid clusters from dictionary""" if isinstance(data, dict): logging.info('Importing %d %s', len(data.get(DATABASES_KEY, [])), DATABASES_KEY) for database in data.get(DATABASES_KEY, [...
[ "def", "import_from_dict", "(", "session", ",", "data", ",", "sync", "=", "[", "]", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "logging", ".", "info", "(", "'Importing %d %s'", ",", "len", "(", "data", ".", "get", "(", "DATABAS...
43.941176
14.882353
def _save_file(self, filename, contents): """write the html file contents to disk""" with open(filename, 'w') as f: f.write(contents)
[ "def", "_save_file", "(", "self", ",", "filename", ",", "contents", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "contents", ")" ]
39.5
3.5
def peek(self): """ Peek at the next item in the queue """ # Ammortized O(1) _heap = self._heap _dict = self._dict val, key = _heap[0] # Remove items marked for lazy deletion as they are encountered while key not in _dict or _dict[key] != val: ...
[ "def", "peek", "(", "self", ")", ":", "# Ammortized O(1)", "_heap", "=", "self", ".", "_heap", "_dict", "=", "self", ".", "_dict", "val", ",", "key", "=", "_heap", "[", "0", "]", "# Remove items marked for lazy deletion as they are encountered", "while", "key", ...
30.153846
12.307692
def message_callback_remove(self, sub): """Remove a message callback previously registered with message_callback_add().""" if sub is None: raise ValueError("sub must defined.") self._callback_mutex.acquire() for i in range(0, len(self.on_message_filtered)): ...
[ "def", "message_callback_remove", "(", "self", ",", "sub", ")", ":", "if", "sub", "is", "None", ":", "raise", "ValueError", "(", "\"sub must defined.\"", ")", "self", ".", "_callback_mutex", ".", "acquire", "(", ")", "for", "i", "in", "range", "(", "0", ...
39.153846
10.153846
def login(self, access_token=""): """ Configure and save {prog} authentication credentials. This command may open a browser window to ask for your consent to use web service authentication credentials. """ if access_token: credentials = argparse.Namespace(tok...
[ "def", "login", "(", "self", ",", "access_token", "=", "\"\"", ")", ":", "if", "access_token", ":", "credentials", "=", "argparse", ".", "Namespace", "(", "token", "=", "access_token", ",", "refresh_token", "=", "None", ",", "id_token", "=", "None", ")", ...
51.708333
28.291667
def find_segments(self, query=None, version=None, callback=None, recurse=True, throw=False): """Yields an iterable of all matching segments. :param query: Either a str or class specifying a segment type (such as 'HNHBK', or :class:`~fints.segments.message.HNHBK3`), or a list or tuple of strings or clas...
[ "def", "find_segments", "(", "self", ",", "query", "=", "None", ",", "version", "=", "None", ",", "callback", "=", "None", ",", "recurse", "=", "True", ",", "throw", "=", "False", ")", ":", "found_something", "=", "False", "if", "query", "is", "None", ...
51.851064
34.021277
def rpc_get_account_tokens(self, address, **con_info): """ Get the types of tokens that an account owns Returns the list on success """ if not check_account_address(address): return {'error': 'Invalid address', 'http_status': 400} # must be b58 if is_...
[ "def", "rpc_get_account_tokens", "(", "self", ",", "address", ",", "*", "*", "con_info", ")", ":", "if", "not", "check_account_address", "(", "address", ")", ":", "return", "{", "'error'", ":", "'Invalid address'", ",", "'http_status'", ":", "400", "}", "# m...
34.25
14.375
def good(txt): """Print, emphasized 'good', the given 'txt' message""" print("%s# %s%s%s" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC)) sys.stdout.flush()
[ "def", "good", "(", "txt", ")", ":", "print", "(", "\"%s# %s%s%s\"", "%", "(", "PR_GOOD_CC", ",", "get_time_stamp", "(", ")", ",", "txt", ",", "PR_NC", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
32.6
22.4
def _main_loop(self): ''' Continuous loop that reads from a kafka topic and tries to validate incoming messages ''' self.logger.debug("Processing messages") old_time = 0 while True: self._process_messages() if self.settings['STATS_DUMP'] !=...
[ "def", "_main_loop", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Processing messages\"", ")", "old_time", "=", "0", "while", "True", ":", "self", ".", "_process_messages", "(", ")", "if", "self", ".", "settings", "[", "'STATS_DUMP'"...
35.333333
16.333333
def user_list(self, params=None): """Lists all users within the tenant.""" uri = 'openstack/users' if params: uri += '?%s' % urllib.urlencode(params) resp, body = self.get(uri) self.expected_success(200, resp.status) body = json.loads(body) return re...
[ "def", "user_list", "(", "self", ",", "params", "=", "None", ")", ":", "uri", "=", "'openstack/users'", "if", "params", ":", "uri", "+=", "'?%s'", "%", "urllib", ".", "urlencode", "(", "params", ")", "resp", ",", "body", "=", "self", ".", "get", "(",...
31.272727
14.727273
def validate(self): """Apply validation rules for loaded settings.""" if self.GROUP_ATTRIBUTES and self.GROUPNAME_FIELD not in self.GROUP_ATTRIBUTES.values(): raise ImproperlyConfigured("LDAP_SYNC_GROUP_ATTRIBUTES must contain '%s'" % self.GROUPNAME_FIELD) if not self.model._meta.ge...
[ "def", "validate", "(", "self", ")", ":", "if", "self", ".", "GROUP_ATTRIBUTES", "and", "self", ".", "GROUPNAME_FIELD", "not", "in", "self", ".", "GROUP_ATTRIBUTES", ".", "values", "(", ")", ":", "raise", "ImproperlyConfigured", "(", "\"LDAP_SYNC_GROUP_ATTRIBUTE...
65.9
44.4
def connect(self): '''Establish a connection.''' _logger.debug(__('Connecting to {0}.', self._address)) if self._state != ConnectionState.ready: raise Exception('Closed connection must be reset before reusing.') if self._sock: connection_future = asyncio.open_co...
[ "def", "connect", "(", "self", ")", ":", "_logger", ".", "debug", "(", "__", "(", "'Connecting to {0}.'", ",", "self", ".", "_address", ")", ")", "if", "self", ".", "_state", "!=", "ConnectionState", ".", "ready", ":", "raise", "Exception", "(", "'Closed...
33.878788
19.636364
def save_bt_addr(self, packet, bt_addr): """Add to the list of mappings.""" if isinstance(packet, EddystoneUIDFrame): # remove out old mapping new_mappings = [m for m in self.eddystone_mappings if m[0] != bt_addr] new_mappings.append((bt_addr, packet.properties)) ...
[ "def", "save_bt_addr", "(", "self", ",", "packet", ",", "bt_addr", ")", ":", "if", "isinstance", "(", "packet", ",", "EddystoneUIDFrame", ")", ":", "# remove out old mapping", "new_mappings", "=", "[", "m", "for", "m", "in", "self", ".", "eddystone_mappings", ...
51.428571
12.285714
def set_property(self, **kwargs): """ set any property of the underlying nparray object """ if not isinstance(self._value, nparray.ndarray): raise ValueError("value is not a nparray object") for property, value in kwargs.items(): setattr(self._value, prop...
[ "def", "set_property", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "self", ".", "_value", ",", "nparray", ".", "ndarray", ")", ":", "raise", "ValueError", "(", "\"value is not a nparray object\"", ")", "for", "property", ...
36
12.888889
def _fake_designspace(self, ufos): """Build a fake designspace with the given UFOs as sources, so that all builder functions can rely on the presence of a designspace. """ designspace = designspaceLib.DesignSpaceDocument() ufo_to_location = defaultdict(dict) # Make weig...
[ "def", "_fake_designspace", "(", "self", ",", "ufos", ")", ":", "designspace", "=", "designspaceLib", ".", "DesignSpaceDocument", "(", ")", "ufo_to_location", "=", "defaultdict", "(", "dict", ")", "# Make weight and width axis if relevant", "for", "info_key", ",", "...
43.142857
19.238095
def setup_html_filter(portal): """Setup HTML filtering for resultsinterpretations """ logger.info("*** Setup HTML Filter ***") # bypass the broken API from portal_transforms adapter = IFilterSchema(portal) style_whitelist = adapter.style_whitelist for style in ALLOWED_STYLES: logger....
[ "def", "setup_html_filter", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"*** Setup HTML Filter ***\"", ")", "# bypass the broken API from portal_transforms", "adapter", "=", "IFilterSchema", "(", "portal", ")", "style_whitelist", "=", "adapter", ".", "style_w...
39.666667
5.083333
def sessions(status, access_key, id_only, all): ''' List and manage compute sessions. ''' fields = [ ('Session ID', 'sess_id'), ] with Session() as session: if is_admin(session): fields.append(('Owner', 'access_key')) if not id_only: fields.extend([ ...
[ "def", "sessions", "(", "status", ",", "access_key", ",", "id_only", ",", "all", ")", ":", "fields", "=", "[", "(", "'Session ID'", ",", "'sess_id'", ")", ",", "]", "with", "Session", "(", ")", "as", "session", ":", "if", "is_admin", "(", "session", ...
34.790909
17.5
def update_pzone(**kwargs): """Update pzone data in the DB""" pzone = PZone.objects.get(**kwargs) # get the data and loop through operate_on, applying them if necessary when = timezone.now() data = pzone.data for operation in pzone.operations.filter(when__lte=when, applied=False): data...
[ "def", "update_pzone", "(", "*", "*", "kwargs", ")", ":", "pzone", "=", "PZone", ".", "objects", ".", "get", "(", "*", "*", "kwargs", ")", "# get the data and loop through operate_on, applying them if necessary", "when", "=", "timezone", ".", "now", "(", ")", ...
29.105263
19.894737
def do_map(input_dict, feature_format, positive_class=None): ''' Maps a new example to a set of features. ''' # Context of the unseen example(s) train_context = input_dict['train_ctx'] test_context = input_dict['test_ctx'] # Currently known examples & background knowledge features = inp...
[ "def", "do_map", "(", "input_dict", ",", "feature_format", ",", "positive_class", "=", "None", ")", ":", "# Context of the unseen example(s)", "train_context", "=", "input_dict", "[", "'train_ctx'", "]", "test_context", "=", "input_dict", "[", "'test_ctx'", "]", "# ...
37.125
16.125
def find_version(filename): """ Search for assignment of __version__ string in given file and return what it is assigned to. """ with open(filename, "r") as filep: version_file = filep.read() version_match = re.search( r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, ...
[ "def", "find_version", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "filep", ":", "version_file", "=", "filep", ".", "read", "(", ")", "version_match", "=", "re", ".", "search", "(", "r\"^__version__ = ['\\\"]([^'\\\"]...
34.692308
11.769231
def _ns_var( py_ns_var: str = _NS_VAR, lisp_ns_var: str = LISP_NS_VAR, lisp_ns_ns: str = CORE_NS ) -> ast.Assign: """Assign a Python variable named `ns_var` to the value of the current namespace.""" return ast.Assign( targets=[ast.Name(id=py_ns_var, ctx=ast.Store())], value=ast.Call( ...
[ "def", "_ns_var", "(", "py_ns_var", ":", "str", "=", "_NS_VAR", ",", "lisp_ns_var", ":", "str", "=", "LISP_NS_VAR", ",", "lisp_ns_ns", ":", "str", "=", "CORE_NS", ")", "->", "ast", ".", "Assign", ":", "return", "ast", ".", "Assign", "(", "targets", "="...
33
19.684211
def restore(self, state): '''Restore the camera state, passed as a *state* dictionary. You can obtain a previous state from the method `Camera.state`. ''' self.a = np.array(state['a']).copy() self.b = np.array(state['b']).copy() self.c = np.array(state['c']).copy...
[ "def", "restore", "(", "self", ",", "state", ")", ":", "self", ".", "a", "=", "np", ".", "array", "(", "state", "[", "'a'", "]", ")", ".", "copy", "(", ")", "self", ".", "b", "=", "np", ".", "array", "(", "state", "[", "'b'", "]", ")", ".",...
38.545455
16.909091
def release(version): """ Move all new blurbs to a single blurb file for the release. This is used by the release manager when cutting a new release. """ if version == ".": # harvest version number from dirname of repo # I remind you, we're in the Misc subdir right now version = os....
[ "def", "release", "(", "version", ")", ":", "if", "version", "==", "\".\"", ":", "# harvest version number from dirname of repo", "# I remind you, we're in the Misc subdir right now", "version", "=", "os", ".", "path", ".", "basename", "(", "root", ")", "existing_filena...
31.196429
21.303571
def assert_pickle_idempotent(obj): '''Assert that obj does not change (w.r.t. ==) under repeated picklings ''' from six.moves.cPickle import dumps, loads obj1 = loads(dumps(obj)) obj2 = loads(dumps(obj1)) obj3 = loads(dumps(obj2)) assert_equivalent(obj, obj1) assert_equivalent(obj, obj2)...
[ "def", "assert_pickle_idempotent", "(", "obj", ")", ":", "from", "six", ".", "moves", ".", "cPickle", "import", "dumps", ",", "loads", "obj1", "=", "loads", "(", "dumps", "(", "obj", ")", ")", "obj2", "=", "loads", "(", "dumps", "(", "obj1", ")", ")"...
34.363636
13.090909
def getList(self, listtype): ''' listtype must be a Zooborg constant ''' if listtype not in [ZooConst.CLIENT, ZooConst.WORKER, ZooConst.BROKER]: raise Exception('Zooborg.getList: invalid type') self.initconn() return self.zk.get_children('/distark/' + listtype...
[ "def", "getList", "(", "self", ",", "listtype", ")", ":", "if", "listtype", "not", "in", "[", "ZooConst", ".", "CLIENT", ",", "ZooConst", ".", "WORKER", ",", "ZooConst", ".", "BROKER", "]", ":", "raise", "Exception", "(", "'Zooborg.getList: invalid type'", ...
40.5
22.25
def InitSpecCheck(self): """make an interactive grid in which users can edit specimen names as well as which sample a specimen belongs to""" self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER) #import wx.lib.scrolledpanel as libpanel # does not work well #self.panel = libpanel.S...
[ "def", "InitSpecCheck", "(", "self", ")", ":", "self", ".", "panel", "=", "wx", ".", "Panel", "(", "self", ",", "style", "=", "wx", ".", "SIMPLE_BORDER", ")", "#import wx.lib.scrolledpanel as libpanel # does not work well", "#self.panel = libpanel.ScrolledPanel(self, st...
46.74359
27.769231
def _get_query(self, **query_dict): """Perform a GET query against Solr and return the response as a Python dict.""" param_dict = query_dict.copy() return self._send_query(do_post=False, **param_dict)
[ "def", "_get_query", "(", "self", ",", "*", "*", "query_dict", ")", ":", "param_dict", "=", "query_dict", ".", "copy", "(", ")", "return", "self", ".", "_send_query", "(", "do_post", "=", "False", ",", "*", "*", "param_dict", ")" ]
55.25
6.75
def _getFullPathName(self, containingNodes): """ Returns the full node hierarchy rooted at module name. The list representing the full path through containing nodes (starting with the module itself) is returned. """ assert isinstance(containingNodes, list) return...
[ "def", "_getFullPathName", "(", "self", ",", "containingNodes", ")", ":", "assert", "isinstance", "(", "containingNodes", ",", "list", ")", "return", "[", "(", "self", ".", "options", ".", "fullPathNamespace", ",", "'module'", ")", "]", "+", "containingNodes" ...
41.666667
17
def _fileMoved(self, oldPathName: str, file: 'File'): """ File Moved Drop the old file name from the dictionary and add the new file name. @param oldPathName: Previous dictionary path name. @param file: File name. @type oldPathName: String @type file: File """ ...
[ "def", "_fileMoved", "(", "self", ",", "oldPathName", ":", "str", ",", "file", ":", "'File'", ")", ":", "self", ".", "_files", ".", "pop", "(", "oldPathName", ")", "self", ".", "_files", "[", "file", ".", "pathName", "]", "=", "file" ]
29.692308
17.307692
def autopilot(self): """ Access the Autopilot Twilio Domain :returns: Autopilot Twilio Domain :rtype: twilio.rest.autopilot.Autopilot """ if self._autopilot is None: from twilio.rest.autopilot import Autopilot self._autopilot = Autopilot(self) ...
[ "def", "autopilot", "(", "self", ")", ":", "if", "self", ".", "_autopilot", "is", "None", ":", "from", "twilio", ".", "rest", ".", "autopilot", "import", "Autopilot", "self", ".", "_autopilot", "=", "Autopilot", "(", "self", ")", "return", "self", ".", ...
30.636364
9.545455
def handle(self): "The actual service to which the user has connected." if self.TELNET_ISSUE: self.writeline(self.TELNET_ISSUE) if not self.authentication_ok(): return if self.DOECHO: self.writeline(self.WELCOME) self.session_start() w...
[ "def", "handle", "(", "self", ")", ":", "if", "self", ".", "TELNET_ISSUE", ":", "self", ".", "writeline", "(", "self", ".", "TELNET_ISSUE", ")", "if", "not", "self", ".", "authentication_ok", "(", ")", ":", "return", "if", "self", ".", "DOECHO", ":", ...
38.821429
13.535714
def ugettext(message, context=None): """Always return a stripped string, localized if possible""" stripped = strip_whitespace(message) message = add_context(context, stripped) if context else stripped ret = django_ugettext(message) # If the context isn't found, we need to return the string withou...
[ "def", "ugettext", "(", "message", ",", "context", "=", "None", ")", ":", "stripped", "=", "strip_whitespace", "(", "message", ")", "message", "=", "add_context", "(", "context", ",", "stripped", ")", "if", "context", "else", "stripped", "ret", "=", "djang...
36.2
19.8
def set_timezone(data, tz=None, from_local=False): """ change the timeozone to specified one without converting """ # pandas object? if isinstance(data, pd.DataFrame) | isinstance(data, pd.Series): try: try: data.index = data.index.tz_convert(tz) except Except...
[ "def", "set_timezone", "(", "data", ",", "tz", "=", "None", ",", "from_local", "=", "False", ")", ":", "# pandas object?", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", "|", "isinstance", "(", "data", ",", "pd", ".", "Series", ")",...
32.586207
19.344828
def _MainThreadProc(self): """Entry point for the worker thread.""" registration_required = True while not self._shutdown: if registration_required: service = self._BuildService() registration_required, delay = self._RegisterDebuggee(service) if not registration_required: ...
[ "def", "_MainThreadProc", "(", "self", ")", ":", "registration_required", "=", "True", "while", "not", "self", ".", "_shutdown", ":", "if", "registration_required", ":", "service", "=", "self", ".", "_BuildService", "(", ")", "registration_required", ",", "delay...
30.5625
17.8125
def send(self, value, error=False): """Send the response. If `error` is True, it will be sent as an error. """ if error: resp = [1, self._request_id, value, None] else: resp = [1, self._request_id, None, value] debug('sending response to request %...
[ "def", "send", "(", "self", ",", "value", ",", "error", "=", "False", ")", ":", "if", "error", ":", "resp", "=", "[", "1", ",", "self", ".", "_request_id", ",", "value", ",", "None", "]", "else", ":", "resp", "=", "[", "1", ",", "self", ".", ...
34.636364
15.727273
def reset(self, commit='HEAD', working_tree=False, paths=None, head=False, **kwargs): """Reset the index to reflect the tree at the given commit. This will not adjust our HEAD reference as opposed to HEAD.reset by default. :param commit: Revision, Reference or Commit specifying the ...
[ "def", "reset", "(", "self", ",", "commit", "=", "'HEAD'", ",", "working_tree", "=", "False", ",", "paths", "=", "None", ",", "head", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# what we actually want to do is to merge the tree into our existing", "# inde...
41.439394
24.136364
def get_routes(self, viewset): """ DREST routes injection, overrides DRF's get_routes() method, which gets called for each registered viewset. """ routes = super(DynamicRouter, self).get_routes(viewset) routes += self.get_relation_routes(viewset) return routes
[ "def", "get_routes", "(", "self", ",", "viewset", ")", ":", "routes", "=", "super", "(", "DynamicRouter", ",", "self", ")", ".", "get_routes", "(", "viewset", ")", "routes", "+=", "self", ".", "get_relation_routes", "(", "viewset", ")", "return", "routes" ...
38.625
13.125
def validate_windows_cred(host, username='Administrator', password=None, retries=10, retry_delay=1): ''' Check if the windows credentials are valid ''' for i in range(retries): ret_code = 1 ...
[ "def", "validate_windows_cred", "(", "host", ",", "username", "=", "'Administrator'", ",", "password", "=", "None", ",", "retries", "=", "10", ",", "retry_delay", "=", "1", ")", ":", "for", "i", "in", "range", "(", "retries", ")", ":", "ret_code", "=", ...
32.9
16.5
def cmd(): '''Handler for command line invocation''' # Try to handle any reasonable thing thrown at this. # Consume '-f' and '-o' as input/output, allow '-' for stdin/stdout # and treat any subsequent arguments as a space separated string to # be titlecased (so it still works if people forget quote...
[ "def", "cmd", "(", ")", ":", "# Try to handle any reasonable thing thrown at this.", "# Consume '-f' and '-o' as input/output, allow '-' for stdin/stdout", "# and treat any subsequent arguments as a space separated string to", "# be titlecased (so it still works if people forget quotes)", "parser"...
31
17.761905
def parse_time_indices(s): """Parse a string as time indices. Args: s: A valid slicing string for time indices. E.g., '-1', '[:]', ':', '2:10' Returns: A slice object. Raises: ValueError: If `s` does not represent valid time indices. """ if not s.startswith('['): s = '[' + s + ']' parse...
[ "def", "parse_time_indices", "(", "s", ")", ":", "if", "not", "s", ".", "startswith", "(", "'['", ")", ":", "s", "=", "'['", "+", "s", "+", "']'", "parsed", "=", "command_parser", ".", "_parse_slices", "(", "s", ")", "if", "len", "(", "parsed", ")"...
24.5
23.55
def hide_intf_loopback_holder_interface_loopback_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_intf_loopback_holder = ET.SubElement(config, "hide-intf-loopback-holder", xmlns="urn:brocade.com:mgmt:brocade-intf-loopback") interface = ET.SubEleme...
[ "def", "hide_intf_loopback_holder_interface_loopback_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "hide_intf_loopback_holder", "=", "ET", ".", "SubElement", "(", "config", ",", "\"hide-intf-loopb...
48
20.916667
def __validInputs(self): """Validates the inputs of the constructor.""" #if not isinstance(self.__column, Column): # raise Sitools2Exception("column must be an instance of Column") if self.__type not in self.__TYPE: raise Sitools2Exception("Type must be one of these value...
[ "def", "__validInputs", "(", "self", ")", ":", "#if not isinstance(self.__column, Column):", "# raise Sitools2Exception(\"column must be an instance of Column\") ", "if", "self", ".", "__type", "not", "in", "self", ".", "__TYPE", ":", "raise", "Sitools2Exception", "(", "...
63.25
25.5
def sign_digest(sock, keygrip, digest, sp=subprocess, environ=None): """Sign a digest using specified key using GPG agent.""" hash_algo = 8 # SHA256 assert len(digest) == 32 assert communicate(sock, 'RESET').startswith(b'OK') ttyname = check_output(args=['tty'], sp=sp).strip() options = ['tty...
[ "def", "sign_digest", "(", "sock", ",", "keygrip", ",", "digest", ",", "sp", "=", "subprocess", ",", "environ", "=", "None", ")", ":", "hash_algo", "=", "8", "# SHA256", "assert", "len", "(", "digest", ")", "==", "32", "assert", "communicate", "(", "so...
34.825
19.975
def mark(self, value=1): """Record an event with the derive. :param value: counter value to record """ last = self.last.get_and_set(value) if last <= value: value = value - last super(Derive, self).mark(value)
[ "def", "mark", "(", "self", ",", "value", "=", "1", ")", ":", "last", "=", "self", ".", "last", ".", "get_and_set", "(", "value", ")", "if", "last", "<=", "value", ":", "value", "=", "value", "-", "last", "super", "(", "Derive", ",", "self", ")",...
29.111111
9.777778
def tag_remove(self, *tags): """ Return a view with the specified tags removed """ return View({**self.spec, 'tag': list(set(self.tags) - set(tags))})
[ "def", "tag_remove", "(", "self", ",", "*", "tags", ")", ":", "return", "View", "(", "{", "*", "*", "self", ".", "spec", ",", "'tag'", ":", "list", "(", "set", "(", "self", ".", "tags", ")", "-", "set", "(", "tags", ")", ")", "}", ")" ]
54.666667
15.666667
def last_version(): """ Fetch the last version from pypi and return it. On successful fetch from pypi, the response is cached 24h, on error, it is cached 10 min. :return: the last django-cas-server version :rtype: unicode """ try: last_update, version, success = last...
[ "def", "last_version", "(", ")", ":", "try", ":", "last_update", ",", "version", ",", "success", "=", "last_version", ".", "_cache", "except", "AttributeError", ":", "last_update", "=", "0", "version", "=", "None", "success", "=", "False", "cache_delta", "="...
35.69697
20.121212
def movie(self, cycles, plotstyle='',movname='',fps=12,**kwargs): from matplotlib import animation ''' Make an interactive movie in the matplotlib window for a number of different plot types: Plot types ---------- 'iso_abund' : abundance distr...
[ "def", "movie", "(", "self", ",", "cycles", ",", "plotstyle", "=", "''", ",", "movname", "=", "''", ",", "fps", "=", "12", ",", "*", "*", "kwargs", ")", ":", "from", "matplotlib", "import", "animation", "modelself", "=", "self", "supported_styles", "="...
45.985577
18.081731
def check_and_reset(self, value=None): """ Combination of #check() and #reset(). """ if self.check(): self.reset(value) return True return False
[ "def", "check_and_reset", "(", "self", ",", "value", "=", "None", ")", ":", "if", "self", ".", "check", "(", ")", ":", "self", ".", "reset", "(", "value", ")", "return", "True", "return", "False" ]
18.777778
14.111111
def answer_callback_query(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None): """ Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. ...
[ "def", "answer_callback_query", "(", "self", ",", "callback_query_id", ",", "text", "=", "None", ",", "show_alert", "=", "None", ",", "url", "=", "None", ",", "cache_time", "=", "None", ")", ":", "return", "apihelper", ".", "answer_callback_query", "(", "sel...
53.4
32.2
def id_pools_vmac_ranges(self): """ Gets the IdPoolsRanges API Client for VMAC Ranges. Returns: IdPoolsRanges: """ if not self.__id_pools_vmac_ranges: self.__id_pools_vmac_ranges = IdPoolsRanges('vmac', self.__connection) return self.__id_pools_vm...
[ "def", "id_pools_vmac_ranges", "(", "self", ")", ":", "if", "not", "self", ".", "__id_pools_vmac_ranges", ":", "self", ".", "__id_pools_vmac_ranges", "=", "IdPoolsRanges", "(", "'vmac'", ",", "self", ".", "__connection", ")", "return", "self", ".", "__id_pools_v...
32
15.2
def flushall(self, async_op=False): """ Remove all keys from all databases. :param async_op: lets the entire dataset to be freed asynchronously. \ Defaults to False """ if async_op: fut = self.execute(b'FLUSHALL', b'ASYNC') else: fut = sel...
[ "def", "flushall", "(", "self", ",", "async_op", "=", "False", ")", ":", "if", "async_op", ":", "fut", "=", "self", ".", "execute", "(", "b'FLUSHALL'", ",", "b'ASYNC'", ")", "else", ":", "fut", "=", "self", ".", "execute", "(", "b'FLUSHALL'", ")", "r...
29.916667
14.75
def get_multi_word_keywords(features): """This returns an OrderedDict containing the multi word keywords in order of length. This is so the tokenizer will match the longer matches before the shorter matches """ keys = { 'is not': Token(TokenTypes.NOT_EQUAL, 'is not'), ...
[ "def", "get_multi_word_keywords", "(", "features", ")", ":", "keys", "=", "{", "'is not'", ":", "Token", "(", "TokenTypes", ".", "NOT_EQUAL", ",", "'is not'", ")", ",", "}", "return", "OrderedDict", "(", "sorted", "(", "list", "(", "keys", ".", "items", ...
51.125
22.375
def emit(self, signal, *args): """ Emits the given signal with the inputted args. This will go through its list of connected callback slots and call them. :param signal | <variant> *args | variables """ callbacks = self._callbacks.get(s...
[ "def", "emit", "(", "self", ",", "signal", ",", "*", "args", ")", ":", "callbacks", "=", "self", ".", "_callbacks", ".", "get", "(", "signal", ",", "[", "]", ")", "new_callbacks", "=", "[", "]", "for", "callback", "in", "callbacks", ":", "# clear out...
31.304348
15.043478