text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def annotate(self, sequence: Seq=None, locus: str=None, nseqs: int=20, alignseqs: int=10, skip: List=[], rerun: bool=True, full: bool=True) -> Annotation: """ annotate - method for annotating a BioPython sequence :param sequenc...
[ "def", "annotate", "(", "self", ",", "sequence", ":", "Seq", "=", "None", ",", "locus", ":", "str", "=", "None", ",", "nseqs", ":", "int", "=", "20", ",", "alignseqs", ":", "int", "=", "10", ",", "skip", ":", "List", "=", "[", "]", ",", "rerun"...
44.664352
21.69213
def list_upgrades(refresh=True, backtrack=3, **kwargs): # pylint: disable=W0613 ''' List all available package upgrades. refresh Whether or not to sync the portage tree before checking for upgrades. backtrack Specifies an integer number of times to backtrack if dependency calc...
[ "def", "list_upgrades", "(", "refresh", "=", "True", ",", "backtrack", "=", "3", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "if", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "refresh", ")", ":", "refresh_db", "(", ")", "r...
26.304348
25.869565
def dependency_images(self, for_running=False): """ What images does this one require Taking into account parent image, and those in link and volumes.share_with options """ candidates = [] detach = dict((candidate, not options.attached) for candidate, options in self.dep...
[ "def", "dependency_images", "(", "self", ",", "for_running", "=", "False", ")", ":", "candidates", "=", "[", "]", "detach", "=", "dict", "(", "(", "candidate", ",", "not", "options", ".", "attached", ")", "for", "candidate", ",", "options", "in", "self",...
40.153846
24
def insert(self, index, child): """insert a child node""" self.children.insert(index, child) child.parent = self
[ "def", "insert", "(", "self", ",", "index", ",", "child", ")", ":", "self", ".", "children", ".", "insert", "(", "index", ",", "child", ")", "child", ".", "parent", "=", "self" ]
33.25
6
def delete_rule(name=None, localport=None, protocol=None, dir=None, remoteip=None): ''' .. versionadded:: 2015.8.0 Delete an existing firewall rule identified by name and optionally by ports, protocols, direction, and remote IP. Args:...
[ "def", "delete_rule", "(", "name", "=", "None", ",", "localport", "=", "None", ",", "protocol", "=", "None", ",", "dir", "=", "None", ",", "remoteip", "=", "None", ")", ":", "cmd", "=", "[", "'netsh'", ",", "'advfirewall'", ",", "'firewall'", ",", "'...
30.591549
24.169014
def release(self, *args, **kwargs): """ GitHub release Event When a GitHub release event is posted it will be broadcast on this exchange with the designated `organization` and `repository` in the routing-key along with event specific metadata in the payload. This exchan...
[ "def", "release", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ref", "=", "{", "'exchange'", ":", "'release'", ",", "'name'", ":", "'release'", ",", "'routingKey'", ":", "[", "{", "'constant'", ":", "'primary'", ",", "'multipleWor...
43.184211
31.184211
def assemble_component(self, into_component, using_components): """ Assemble a list of already defined components into a structual hirearchy """ if not isinstance(using_components, list) or len(using_components) == 0: raise Exception('Must supply list of ComponentDefinitions'...
[ "def", "assemble_component", "(", "self", ",", "into_component", ",", "using_components", ")", ":", "if", "not", "isinstance", "(", "using_components", ",", "list", ")", "or", "len", "(", "using_components", ")", "==", "0", ":", "raise", "Exception", "(", "'...
50.163636
24.054545
def minimumBelow(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by a constant n. Draws only the metrics with a minimum value below n. Example:: &target=minimumBelow(system.interface.eth*.packetsSent,1000) This would only display interfaces which sen...
[ "def", "minimumBelow", "(", "requestContext", ",", "seriesList", ",", "n", ")", ":", "results", "=", "[", "]", "for", "series", "in", "seriesList", ":", "val", "=", "safeMin", "(", "series", ")", "if", "val", "is", "None", "or", "val", "<=", "n", ":"...
29.111111
20
def _call_linker_cb(env, callback, args, result = None): """Returns the result of env['LINKCALLBACKS'][callback](*args) if env['LINKCALLBACKS'] is a dictionary and env['LINKCALLBACKS'][callback] is callable. If these conditions are not met, return the value provided as the *result* argument. This functi...
[ "def", "_call_linker_cb", "(", "env", ",", "callback", ",", "args", ",", "result", "=", "None", ")", ":", "Verbose", "=", "False", "if", "Verbose", ":", "print", "(", "'_call_linker_cb: args=%r'", "%", "args", ")", "print", "(", "'_call_linker_cb: callback=%r'...
43.724138
25.931034
def _rest_format_section(stream, section, options, doc=None): """format an options section using as ReST formatted output""" if section: print("%s\n%s" % (section, "'" * len(section)), file=stream) if doc: print(normalize_text(doc, line_len=79, indent=""), file=stream) print(file=str...
[ "def", "_rest_format_section", "(", "stream", ",", "section", ",", "options", ",", "doc", "=", "None", ")", ":", "if", "section", ":", "print", "(", "\"%s\\n%s\"", "%", "(", "section", ",", "\"'\"", "*", "len", "(", "section", ")", ")", ",", "file", ...
45.235294
18.176471
def create_rules(aes, value): """Create a Rules instance for a single aesthetic value. Parameter --------- aes: str The name of the aesthetic value: str or list The value associated with any aesthetic """ if isinstance(value, six.string_types): return Rules(aes) ...
[ "def", "create_rules", "(", "aes", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "Rules", "(", "aes", ")", "else", ":", "rules", "=", "Rules", "(", ")", "for", "idx", ",", "(", "patte...
28.058824
17.176471
def _z2deriv(self,R,z,phi=0.,t=0.): """ NAME: _z2deriv PURPOSE: evaluate the second vertical derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUT...
[ "def", "_z2deriv", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "a", "=", "self", ".", "_a", "return", "self", ".", "_denom", "(", "R", ",", "z", ")", "**", "-", "1.5", "-", "3.", "*", "(", "a", ...
29.666667
17.333333
def taxon_table(self): """ Returns the .tests list of taxa as a pandas dataframe. By auto-generating this table from tests it means that the table itself cannot be modified unless it is returned and saved. """ if self.tests: keys = sorted(self.test...
[ "def", "taxon_table", "(", "self", ")", ":", "if", "self", ".", "tests", ":", "keys", "=", "sorted", "(", "self", ".", "tests", "[", "0", "]", ".", "keys", "(", ")", ")", "if", "isinstance", "(", "self", ".", "tests", ",", "list", ")", ":", "ld...
36.611111
15.611111
def load_snippet(self, name, package): """Starts the snippet apk with the given package name and connects. Examples: .. code-block:: python ad.load_snippet( name='maps', package='com.google.maps.snippets') ad.maps.activateZoom('3') Args: ...
[ "def", "load_snippet", "(", "self", ",", "name", ",", "package", ")", ":", "# Should not load snippet with an existing attribute.", "if", "hasattr", "(", "self", ",", "name", ")", ":", "raise", "SnippetError", "(", "self", ",", "'Attribute \"%s\" already exists, pleas...
35.444444
22.777778
def contains_text_tokens(self, text_tokens): """ Returns true if a phrase in the dictionary matches the list of text tokens :param text_tokens: a list of tokens. Each token a string of text. :return: True/False """ id_run = [] for token in text_tokens: ...
[ "def", "contains_text_tokens", "(", "self", ",", "text_tokens", ")", ":", "id_run", "=", "[", "]", "for", "token", "in", "text_tokens", ":", "id", "=", "self", ".", "word_list", ".", "get", "(", "token", ",", "None", ")", "if", "id", "is", "None", ":...
42.615385
17.230769
def add_x509_key_descriptors(metadata, cert=None, add_encryption=True): """ Adds the x509 descriptors (sign/encryption) to the metadata The same cert will be used for sign/encrypt :param metadata: SAML Metadata XML :type metadata: string :param cert: x509 cert :...
[ "def", "add_x509_key_descriptors", "(", "metadata", ",", "cert", "=", "None", ",", "add_encryption", "=", "True", ")", ":", "if", "cert", "is", "None", "or", "cert", "==", "''", ":", "return", "metadata", "try", ":", "xml", "=", "parseString", "(", "meta...
41.767857
26.910714
def insert(self, s): ''' Insert string @s at the current cursor location. ''' for c in s: self.text.insert(self.cursor_loc, c) self.cursor_loc += 1
[ "def", "insert", "(", "self", ",", "s", ")", ":", "for", "c", "in", "s", ":", "self", ".", "text", ".", "insert", "(", "self", ".", "cursor_loc", ",", "c", ")", "self", ".", "cursor_loc", "+=", "1" ]
28.142857
18.714286
def putParamset(self, remote, address, paramset, value): """Set paramsets manually""" try: return self.proxies["%s-%s" % (self._interface_id, remote)].putParamset(address, paramset, value) except Exception as err: LOG.debug("ServerThread.putParamset: Exception: %s" % str(...
[ "def", "putParamset", "(", "self", ",", "remote", ",", "address", ",", "paramset", ",", "value", ")", ":", "try", ":", "return", "self", ".", "proxies", "[", "\"%s-%s\"", "%", "(", "self", ".", "_interface_id", ",", "remote", ")", "]", ".", "putParamse...
53.333333
26
def check_sufficient_inputs(self): '''Method to an exception if none of the pairs (T, P), (T, V), or (P, V) are given. ''' if not ((self.T and self.P) or (self.T and self.V) or (self.P and self.V)): raise Exception('Either T and P, or T and V, or P and V are required')
[ "def", "check_sufficient_inputs", "(", "self", ")", ":", "if", "not", "(", "(", "self", ".", "T", "and", "self", ".", "P", ")", "or", "(", "self", ".", "T", "and", "self", ".", "V", ")", "or", "(", "self", ".", "P", "and", "self", ".", "V", "...
60.4
27.2
def remove_vote(self, issue): """Remove the current authenticated user's vote from an issue. :param issue: ID or key of the issue to remove vote on """ url = self._get_url('issue/' + str(issue) + '/votes') self._session.delete(url)
[ "def", "remove_vote", "(", "self", ",", "issue", ")", ":", "url", "=", "self", ".", "_get_url", "(", "'issue/'", "+", "str", "(", "issue", ")", "+", "'/votes'", ")", "self", ".", "_session", ".", "delete", "(", "url", ")" ]
38
14.428571
def gamma_automatic(kpts=(1, 1, 1), shift=(0, 0, 0)): """ Convenient static constructor for an automatic Gamma centered Kpoint grid. Args: kpts: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors. Defaults to (1,1,1) shift: Shift to be...
[ "def", "gamma_automatic", "(", "kpts", "=", "(", "1", ",", "1", ",", "1", ")", ",", "shift", "=", "(", "0", ",", "0", ",", "0", ")", ")", ":", "return", "Kpoints", "(", "\"Automatic kpoint scheme\"", ",", "0", ",", "Kpoints", ".", "supported_modes", ...
35.5
20.625
def enum_sigma_rho(cutoff, r_axis, ratio_alpha): """ Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in rhombohedral system. The algorithm for this code is from reference, Acta Cryst, A45,505(1989). Args: ...
[ "def", "enum_sigma_rho", "(", "cutoff", ",", "r_axis", ",", "ratio_alpha", ")", ":", "sigmas", "=", "{", "}", "# transform four index notation to three index notation", "if", "len", "(", "r_axis", ")", "==", "4", ":", "u1", "=", "r_axis", "[", "0", "]", "v1"...
55.605634
24.492958
def level_matches(self, level, consumer_level): """ >>> l = Logger([]) >>> l.level_matches(3, 4) False >>> l.level_matches(3, 2) True >>> l.level_matches(slice(None, 3), 3) False >>> l.level_matches(slice(None, 3), 2) True >>> l.lev...
[ "def", "level_matches", "(", "self", ",", "level", ",", "consumer_level", ")", ":", "if", "isinstance", "(", "level", ",", "slice", ")", ":", "start", ",", "stop", "=", "level", ".", "start", ",", "level", ".", "stop", "if", "start", "is", "not", "No...
30.08
13.6
def read(cls, source, *args, **kwargs): """Read data from a source into a `gwpy.timeseries` object. This method is just the internal worker for `TimeSeries.read`, and `TimeSeriesDict.read`, and isn't meant to be called directly. """ # if reading a cache, read it now and sieve if io_cache.is_cac...
[ "def", "read", "(", "cls", ",", "source", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# if reading a cache, read it now and sieve", "if", "io_cache", ".", "is_cache", "(", "source", ")", ":", "from", ".", "cache", "import", "preformat_cache", "sour...
38.15
16.75
def bundle(context, name): """Add a new bundle.""" if context.obj['db'].bundle(name): click.echo(click.style('bundle name already exists', fg='yellow')) context.abort() new_bundle = context.obj['db'].new_bundle(name) context.obj['db'].add_commit(new_bundle) # add default version ...
[ "def", "bundle", "(", "context", ",", "name", ")", ":", "if", "context", ".", "obj", "[", "'db'", "]", ".", "bundle", "(", "name", ")", ":", "click", ".", "echo", "(", "click", ".", "style", "(", "'bundle name already exists'", ",", "fg", "=", "'yell...
40.428571
20.357143
def from_flags(flags, ednsflags): """Return the rcode value encoded by flags and ednsflags. @param flags: the DNS flags @type flags: int @param ednsflags: the EDNS flags @type ednsflags: int @raises ValueError: rcode is < 0 or > 4095 @rtype: int """ value = (flags & 0x000f) | ((edn...
[ "def", "from_flags", "(", "flags", ",", "ednsflags", ")", ":", "value", "=", "(", "flags", "&", "0x000f", ")", "|", "(", "(", "ednsflags", ">>", "20", ")", "&", "0xff0", ")", "if", "value", "<", "0", "or", "value", ">", "4095", ":", "raise", "Val...
29.2
15.6
def _process_args(self, analysis, args): """ When Naarad is run in CLI mode, get the CL arguments and update the analysis :param: analysis: The analysis being processed :param: args: Command Line Arguments received by naarad """ if args.exit_code: self.return_exit_code = args.exit_code ...
[ "def", "_process_args", "(", "self", ",", "analysis", ",", "args", ")", ":", "if", "args", ".", "exit_code", ":", "self", ".", "return_exit_code", "=", "args", ".", "exit_code", "if", "args", ".", "no_plots", ":", "self", ".", "skip_plots", "=", "args", ...
39.235294
17.352941
def start_file(filename): """ Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Returns True if successfull, otherwise returns False. """ from qtpy.QtCore import QUrl from qtpy.QtGui import QDesktopServices ...
[ "def", "start_file", "(", "filename", ")", ":", "from", "qtpy", ".", "QtCore", "import", "QUrl", "from", "qtpy", ".", "QtGui", "import", "QDesktopServices", "# We need to use setUrl instead of setPath because this is the only\r", "# cross-platform way to open external files. se...
33.944444
19.055556
def suggest_move(self, position): """Used for playing a single game. For parallel play, use initialize_move, select_leaf, incorporate_results, and pick_move """ start = time.time() if self.timed_match: while time.time() - start < self.seconds_per_move: ...
[ "def", "suggest_move", "(", "self", ",", "position", ")", ":", "start", "=", "time", ".", "time", "(", ")", "if", "self", ".", "timed_match", ":", "while", "time", ".", "time", "(", ")", "-", "start", "<", "self", ".", "seconds_per_move", ":", "self"...
33.444444
16
def get_counts_array_index(self, value): '''Return the index in the counts array for a given value ''' if value < 0: raise ValueError("Histogram recorded value cannot be negative.") bucket_index = self._get_bucket_index(value) sub_bucket_index = self._get_sub_bucket_...
[ "def", "get_counts_array_index", "(", "self", ",", "value", ")", ":", "if", "value", "<", "0", ":", "raise", "ValueError", "(", "\"Histogram recorded value cannot be negative.\"", ")", "bucket_index", "=", "self", ".", "_get_bucket_index", "(", "value", ")", "sub_...
56.1875
27.1875
def user_info(name, **client_args): ''' Get information about given user. name Name of the user for which to get information. CLI Example: .. code-block:: bash salt '*' influxdb.user_info <name> ''' matching_users = (user for user in list_users(**client_args) ...
[ "def", "user_info", "(", "name", ",", "*", "*", "client_args", ")", ":", "matching_users", "=", "(", "user", "for", "user", "in", "list_users", "(", "*", "*", "client_args", ")", "if", "user", ".", "get", "(", "'user'", ")", "==", "name", ")", "try",...
21.2
23.8
def install_host(trg_queue, *hosts, **kwargs): ''' Atomically install host queues ''' user = kwargs.pop('user', None) group = kwargs.pop('group', None) mode = kwargs.pop('mode', None) item_user = kwargs.pop('item_user', None) item_group = kwargs.pop('item_group', None) item_mode = kwargs.pop...
[ "def", "install_host", "(", "trg_queue", ",", "*", "hosts", ",", "*", "*", "kwargs", ")", ":", "user", "=", "kwargs", ".", "pop", "(", "'user'", ",", "None", ")", "group", "=", "kwargs", ".", "pop", "(", "'group'", ",", "None", ")", "mode", "=", ...
43.866667
16.9
def wrap_rethink_errors(func_, *args, **kwargs): """ Wraps rethinkdb specific errors as builtin/Brain errors :param func_: <function> to call :param args: <tuple> positional arguments :param kwargs: <dict> keyword arguments :return: inherits from the called function """ try: re...
[ "def", "wrap_rethink_errors", "(", "func_", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func_", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "WRAP_RETHINK_ERRORS", "as", "reql_err", ":", "raise", "ValueError",...
32.230769
9.615385
def clean(inputline, strip=True, rem_indents=True, encoding_errors="replace"): """Clean and strip a line.""" stdout_encoding = get_encoding(sys.stdout) inputline = str(inputline) if rem_indents: inputline = inputline.replace(openindent, "").replace(closeindent, "") if strip: inputlin...
[ "def", "clean", "(", "inputline", ",", "strip", "=", "True", ",", "rem_indents", "=", "True", ",", "encoding_errors", "=", "\"replace\"", ")", ":", "stdout_encoding", "=", "get_encoding", "(", "sys", ".", "stdout", ")", "inputline", "=", "str", "(", "input...
46.555556
20.888889
def run_flat(file_struct, bounds_module, labels_module, frame_times, config, annotator_id): """Runs the flat algorithms with the specified identifiers on the audio_file. See run_algorithm for more information. """ # Get features to make code nicer features = config["features"].features ...
[ "def", "run_flat", "(", "file_struct", ",", "bounds_module", ",", "labels_module", ",", "frame_times", ",", "config", ",", "annotator_id", ")", ":", "# Get features to make code nicer", "features", "=", "config", "[", "\"features\"", "]", ".", "features", "# Segment...
42.387755
17.040816
def execd_submodule_paths(command, execd_dir=None): """Generate a list of full paths to the specified command within exec_dir. """ for module_path in execd_module_paths(execd_dir): path = os.path.join(module_path, command) if os.access(path, os.X_OK) and os.path.isfile(path): yie...
[ "def", "execd_submodule_paths", "(", "command", ",", "execd_dir", "=", "None", ")", ":", "for", "module_path", "in", "execd_module_paths", "(", "execd_dir", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "module_path", ",", "command", ")", "if...
45.857143
10.285714
def wrap(self, filename, boxes=None): """Create a new JP2/JPX file wrapped in a new set of JP2 boxes. This method is primarily aimed at wrapping a raw codestream in a set of of JP2 boxes (turning it into a JP2 file instead of just a raw codestream), or rewrapping a codestream in a JP2 f...
[ "def", "wrap", "(", "self", ",", "filename", ",", "boxes", "=", "None", ")", ":", "if", "boxes", "is", "None", ":", "boxes", "=", "self", ".", "_get_default_jp2_boxes", "(", ")", "self", ".", "_validate_jp2_box_sequence", "(", "boxes", ")", "with", "open...
33.957447
20.340426
def _perform_validation(self, path, value, results): """ Validates a given value against the schema and configured validation rules. :param path: a dot notation path to the value. :param value: a value to be validated. :param results: a list with validation results to add new ...
[ "def", "_perform_validation", "(", "self", ",", "path", ",", "value", ",", "results", ")", ":", "name", "=", "path", "if", "path", "!=", "None", "else", "\"value\"", "if", "value", "==", "None", ":", "# Check for required values", "if", "self", ".", "requi...
32.5625
16.0625
def remove_hook(self, repo_id, name): """Remove repository hook.""" ghrepo = self.api.repository_with_id(repo_id) if ghrepo: hooks = (h for h in ghrepo.hooks() if h.config.get('url', '') == self.webhook_url) hook = next(hooks, None) if not...
[ "def", "remove_hook", "(", "self", ",", "repo_id", ",", "name", ")", ":", "ghrepo", "=", "self", ".", "api", ".", "repository_with_id", "(", "repo_id", ")", "if", "ghrepo", ":", "hooks", "=", "(", "h", "for", "h", "in", "ghrepo", ".", "hooks", "(", ...
41.307692
11.076923
def msg_debug(message): """ Log a debug message :param message: the message to be logged """ if _log_lvl == logging.DEBUG: to_stdout(" (*) {message}".format(message=message), colorf=cyan) if _logger: _logger.debug(message)
[ "def", "msg_debug", "(", "message", ")", ":", "if", "_log_lvl", "==", "logging", ".", "DEBUG", ":", "to_stdout", "(", "\" (*) {message}\"", ".", "format", "(", "message", "=", "message", ")", ",", "colorf", "=", "cyan", ")", "if", "_logger", ":", "_logge...
26.2
14.4
def accept(self): """Accept a connection. The socket must be bound to an address and listening for connections. The return value is a new socket object usable to send and receive data on the connection.""" socket = Socket(self._llc, None) socket._tco = self.llc.accept(sel...
[ "def", "accept", "(", "self", ")", ":", "socket", "=", "Socket", "(", "self", ".", "_llc", ",", "None", ")", "socket", ".", "_tco", "=", "self", ".", "llc", ".", "accept", "(", "self", ".", "_tco", ")", "return", "socket" ]
42.75
11.75
def ltrimboth (l,proportiontocut): """ Slices off the passed proportion of items from BOTH ends of the passed list (i.e., with proportiontocut=0.1, slices 'leftmost' 10% AND 'rightmost' 10% of scores. Assumes list is sorted by magnitude. Slices off LESS if proportion results in a non-integer slice index (i.e., co...
[ "def", "ltrimboth", "(", "l", ",", "proportiontocut", ")", ":", "lowercut", "=", "int", "(", "proportiontocut", "*", "len", "(", "l", ")", ")", "uppercut", "=", "len", "(", "l", ")", "-", "lowercut", "return", "l", "[", "lowercut", ":", "uppercut", "...
38.214286
15.071429
def str_matcher(mode): """ generate token strings' cache """ def f_raw(inp_str, pos): return unique_literal_cache_pool[mode] if inp_str.startswith(mode, pos) else None def f_collection(inp_str, pos): for each in mode: if inp_str.startswith(each, pos): ...
[ "def", "str_matcher", "(", "mode", ")", ":", "def", "f_raw", "(", "inp_str", ",", "pos", ")", ":", "return", "unique_literal_cache_pool", "[", "mode", "]", "if", "inp_str", ".", "startswith", "(", "mode", ",", "pos", ")", "else", "None", "def", "f_collec...
23.681818
19.863636
def outline(dataset, generate_faces=False): """Produces an outline of the full extent for the input dataset. Parameters ---------- generate_faces : bool, optional Generate solid faces for the box. This is off by default """ alg = vtk.vtkOutlineFilter() ...
[ "def", "outline", "(", "dataset", ",", "generate_faces", "=", "False", ")", ":", "alg", "=", "vtk", ".", "vtkOutlineFilter", "(", ")", "alg", ".", "SetInputDataObject", "(", "dataset", ")", "alg", ".", "SetGenerateFaces", "(", "generate_faces", ")", "alg", ...
32.5
13.714286
def _get_json(self, url): """ Get json from url """ self.log.info(u"/GET " + url) r = requests.get(url) if hasattr(r, 'from_cache'): if r.from_cache: self.log.info("(from cache)") if r.status_code != 200: throw_request_err(r) ...
[ "def", "_get_json", "(", "self", ",", "url", ")", ":", "self", ".", "log", ".", "info", "(", "u\"/GET \"", "+", "url", ")", "r", "=", "requests", ".", "get", "(", "url", ")", "if", "hasattr", "(", "r", ",", "'from_cache'", ")", ":", "if", "r", ...
27.25
10.25
def can_query_state_for_block(self, block_identifier: BlockSpecification) -> bool: """ Returns if the provided block identifier is safe enough to query chain state for. If it's close to the state pruning blocks then state should not be queried. More info: https://github.com/raide...
[ "def", "can_query_state_for_block", "(", "self", ",", "block_identifier", ":", "BlockSpecification", ")", "->", "bool", ":", "latest_block_number", "=", "self", ".", "block_number", "(", ")", "preconditions_block", "=", "self", ".", "web3", ".", "eth", ".", "get...
56.583333
24.25
def cnvlPwBoxCarFn(aryNrlTc, varNumVol, varTr, tplPngSize, varNumMtDrctn, switchHrfSet, lgcOldSchoolHrf, varPar,): """Create 2D Gaussian kernel. Parameters ---------- aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol] Description of input 1. varNu...
[ "def", "cnvlPwBoxCarFn", "(", "aryNrlTc", ",", "varNumVol", ",", "varTr", ",", "tplPngSize", ",", "varNumMtDrctn", ",", "switchHrfSet", ",", "lgcOldSchoolHrf", ",", "varPar", ",", ")", ":", "print", "(", "'------Convolve every pixel box car function with hrf function(s)...
32.113043
18.33913
def proper_round(n): """ rounds float to closest int :rtype: int :param n: float """ return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0
[ "def", "proper_round", "(", "n", ")", ":", "return", "int", "(", "n", ")", "+", "(", "n", "/", "abs", "(", "n", ")", ")", "*", "int", "(", "abs", "(", "n", "-", "int", "(", "n", ")", ")", ">=", "0.5", ")", "if", "n", "!=", "0", "else", ...
25.428571
16.285714
def create_or_get_from_request(request): """Returns `RequestInfo` instance. If object was already created during ``request`` it is returned. Otherwise new instance is created with details populated from ``request``. New instance is then cached for reuse on subsequential calls. ...
[ "def", "create_or_get_from_request", "(", "request", ")", ":", "saved", "=", "getattr", "(", "request", ",", "REQUEST_CACHE_FIELD", ",", "None", ")", "if", "isinstance", "(", "saved", ",", "RequestInfo", ")", ":", "return", "saved", "req", "=", "RequestInfo", ...
42.045455
14.727273
def connection(self, shareable=True): """Get a steady, cached DB-API 2 connection from the pool. If shareable is set and the underlying DB-API 2 allows it, then the connection may be shared with other threads. """ if shareable and self._maxshared: self._lock.acquire...
[ "def", "connection", "(", "self", ",", "shareable", "=", "True", ")", ":", "if", "shareable", "and", "self", ".", "_maxshared", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "while", "(", "not", "self", ".", "_shared_cache", "and", ...
48.362069
17.517241
def get_element_mfr_dictionary(self): """ Determine the mass flow rates of elements in the stream and return as a dictionary. :returns: Dictionary of element symbols and mass flow rates. [kg/h] """ element_symbols = self.material.elements element_mfrs = self.get...
[ "def", "get_element_mfr_dictionary", "(", "self", ")", ":", "element_symbols", "=", "self", ".", "material", ".", "elements", "element_mfrs", "=", "self", ".", "get_element_mfrs", "(", ")", "result", "=", "dict", "(", ")", "for", "s", ",", "mfr", "in", "zi...
32.428571
18.142857
def SetRowsCustomProperties(self, rows, custom_properties): """Sets the custom properties for given row(s). Can accept a single row or an iterable of rows. Sets the given custom properties for all specified rows. Args: rows: The row, or rows, to set the custom properties for. custom_proper...
[ "def", "SetRowsCustomProperties", "(", "self", ",", "rows", ",", "custom_properties", ")", ":", "if", "not", "hasattr", "(", "rows", ",", "\"__iter__\"", ")", ":", "rows", "=", "[", "rows", "]", "for", "row", "in", "rows", ":", "self", ".", "__data", "...
36.133333
20.533333
def parse_stack_pointer(sp): """ Convert multiple supported forms of stack pointer representations into stack offsets. :param sp: A stack pointer representation. :return: A stack pointer offset. :rtype: int """ if isinstance(sp, int): return sp if isinstance(sp, StackBa...
[ "def", "parse_stack_pointer", "(", "sp", ")", ":", "if", "isinstance", "(", "sp", ",", "int", ")", ":", "return", "sp", "if", "isinstance", "(", "sp", ",", "StackBaseOffset", ")", ":", "return", "sp", ".", "offset", "if", "isinstance", "(", "sp", ",", ...
28.75
17.583333
def has_reduction(expr): """Does `expr` contain a reduction? Parameters ---------- expr : ibis.expr.types.Expr An ibis expression Returns ------- truth_value : bool Whether or not there's at least one reduction in `expr` Notes ----- The ``isinstance(op, ops.Tab...
[ "def", "has_reduction", "(", "expr", ")", ":", "def", "fn", "(", "expr", ")", ":", "op", "=", "expr", ".", "op", "(", ")", "if", "isinstance", "(", "op", ",", "ops", ".", "TableNode", ")", ":", "# don't go below any table nodes", "return", "lin", ".", ...
25.933333
21.666667
def load_config(filename=None): """Load a configuration from a file or stdin. If `filename` is `None` or "-", then configuration gets read from stdin. Returns: A `ConfigDict`. Raises: ConfigError: If there is an error loading the config. """ try: with _config_stream(filename) as handl...
[ "def", "load_config", "(", "filename", "=", "None", ")", ":", "try", ":", "with", "_config_stream", "(", "filename", ")", "as", "handle", ":", "filename", "=", "handle", ".", "name", "return", "deserialize_config", "(", "handle", ".", "read", "(", ")", "...
35.625
21.25
def _parse_entry_record(self, lines): """Parse a single entry record from a list of lines.""" dn = None entry = OrderedDict() for line in lines: attr_type, attr_value = self._parse_attr(line) if attr_type == 'dn': self._check_dn(dn, attr_value) ...
[ "def", "_parse_entry_record", "(", "self", ",", "lines", ")", ":", "dn", "=", "None", "entry", "=", "OrderedDict", "(", ")", "for", "line", "in", "lines", ":", "attr_type", ",", "attr_value", "=", "self", ".", "_parse_attr", "(", "line", ")", "if", "at...
37.08
16.64
def or_filter(self, filter_or_string, *args, **kwargs): """ Adds a list of :class:`~es_fluent.filters.core.Or` clauses, automatically generating the an :class:`~es_fluent.filters.core.Or` filter if it does not exist. """ or_filter = self.find_filter(Or) if or_fil...
[ "def", "or_filter", "(", "self", ",", "filter_or_string", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "or_filter", "=", "self", ".", "find_filter", "(", "Or", ")", "if", "or_filter", "is", "None", ":", "or_filter", "=", "Or", "(", ")", "self...
30.294118
19
def find_module(self, fullname, submodule_path=None): """ We have to see if fullname refers to a module we can import. Some care is needed here because: import xxx # tries to load xxx.so from any of the python import paths import aaa.bbb.xxx # tries to load aaa/bbb/xxx.so from...
[ "def", "find_module", "(", "self", ",", "fullname", ",", "submodule_path", "=", "None", ")", ":", "# first see if we have this particular so has been loaded by", "# turicreate's extension library before", "ret", "=", "self", ".", "try_find_module", "(", "fullname", ",", "...
39.333333
19
def read_etotals(self, unit="Ha"): """ Reads the total energy from the GSR file produced by the task. Return a numpy array with the total energies in Hartree The array element is set to np.inf if an exception is raised while reading the GSR file. """ if not self.all_done...
[ "def", "read_etotals", "(", "self", ",", "unit", "=", "\"Ha\"", ")", ":", "if", "not", "self", ".", "all_done", ":", "raise", "self", ".", "Error", "(", "\"Some task is still in running/submitted state\"", ")", "etotals", "=", "[", "]", "for", "task", "in", ...
35.136364
20.590909
def get_page_access_token(self, app_id, app_secret, user_token): """Returns a dictionary of never expired page token indexed by page names. :param str app_id: Application ID :param str app_secret: Application secret :param str user_token: User short-lived token :rtype: dict ...
[ "def", "get_page_access_token", "(", "self", ",", "app_id", ",", "app_secret", ",", "user_token", ")", ":", "url_extend", "=", "(", "self", ".", "_url_base", "+", "'/oauth/access_token?grant_type=fb_exchange_token&'", "'client_id=%(app_id)s&client_secret=%(app_secret)s&fb_exc...
42.521739
32.130435
def process_item(self, item, spider): # pylint: disable=unused-argument "Check for DRF urls." url = URLObject(item["url"]) if url.path.startswith("/api/"): raise DropItem(u"Dropping DRF url {url}".format(url=url)) else: return item
[ "def", "process_item", "(", "self", ",", "item", ",", "spider", ")", ":", "# pylint: disable=unused-argument", "url", "=", "URLObject", "(", "item", "[", "\"url\"", "]", ")", "if", "url", ".", "path", ".", "startswith", "(", "\"/api/\"", ")", ":", "raise",...
40.285714
17.142857
def _setup_container(container_name): """ Try and find a container in a variety of methods """ for meth in (database.load_container, load_new_labware, _load_weird_container): log.debug( f"Trying to load container {container_name} via {meth.__name__}") ...
[ "def", "_setup_container", "(", "container_name", ")", ":", "for", "meth", "in", "(", "database", ".", "load_container", ",", "load_new_labware", ",", "_load_weird_container", ")", ":", "log", ".", "debug", "(", "f\"Trying to load container {container_name} via {meth.__...
35.322581
18.806452
def _process_project_transfer(self, action, transfer_id, status_comment): """ Send PUT request to one of the project transfer action endpoints :param action: str name of the action (reject/accept/cancel) :param transfer_id: str uuid of the project_transfer :param status_comment: ...
[ "def", "_process_project_transfer", "(", "self", ",", "action", ",", "transfer_id", ",", "status_comment", ")", ":", "data", "=", "{", "}", "if", "status_comment", ":", "data", "[", "\"status_comment\"", "]", "=", "status_comment", "path", "=", "\"/project_trans...
50.846154
21
def goto(self, rules, symbol): """Computes the next closure for rules based on the symbol we got. Args: rules - an iterable of DottedRules symbol - a string denoting the symbol we've just seen Returns: frozenset of DottedRules """ return self.closure( ...
[ "def", "goto", "(", "self", ",", "rules", ",", "symbol", ")", ":", "return", "self", ".", "closure", "(", "{", "rule", ".", "move_dot", "(", ")", "for", "rule", "in", "rules", "if", "not", "rule", ".", "at_end", "and", "rule", ".", "rhs", "[", "r...
33
17.230769
def translate( self, message: str, plural_message: str = None, count: int = None ) -> str: """Returns the translation for the given message for this locale. If ``plural_message`` is given, you must also provide ``count``. We return ``plural_message`` when ``count != 1``, and...
[ "def", "translate", "(", "self", ",", "message", ":", "str", ",", "plural_message", ":", "str", "=", "None", ",", "count", ":", "int", "=", "None", ")", "->", "str", ":", "raise", "NotImplementedError", "(", ")" ]
39.727273
20.272727
def PublicIPs(self): """Returns PublicIPs object associated with the server. """ if not self.public_ips: self.public_ips = clc.v2.PublicIPs(server=self,public_ips_lst=self.ip_addresses,session=self.session) return(self.public_ips)
[ "def", "PublicIPs", "(", "self", ")", ":", "if", "not", "self", ".", "public_ips", ":", "self", ".", "public_ips", "=", "clc", ".", "v2", ".", "PublicIPs", "(", "server", "=", "self", ",", "public_ips_lst", "=", "self", ".", "ip_addresses", ",", "sessi...
33.571429
29
def onMouseOver(self, event, grid): """ Displays a tooltip over any cell in a certain column """ x, y = grid.CalcUnscrolledPosition(event.GetX(), event.GetY()) coords = grid.XYToCell(x, y) col = coords[1] row = coords[0] # creates tooltip message for cell...
[ "def", "onMouseOver", "(", "self", ",", "event", ",", "grid", ")", ":", "x", ",", "y", "=", "grid", ".", "CalcUnscrolledPosition", "(", "event", ".", "GetX", "(", ")", ",", "event", ".", "GetY", "(", ")", ")", "coords", "=", "grid", ".", "XYToCell"...
38.4375
17.6875
def packstr(instr, textwidth=160, breakchars=' ', break_words=True, newline_prefix='', indentation='', nlprefix=None, wordsep=' ', remove_newlines=True): """ alias for pack_into. has more up to date kwargs """ if not isinstance(instr, six.string_types): instr = repr(instr) if...
[ "def", "packstr", "(", "instr", ",", "textwidth", "=", "160", ",", "breakchars", "=", "' '", ",", "break_words", "=", "True", ",", "newline_prefix", "=", "''", ",", "indentation", "=", "''", ",", "nlprefix", "=", "None", ",", "wordsep", "=", "' '", ","...
44.153846
14.692308
def update(self, data): """ Performs actual encrypton/decrypion @param data - part of the plain text/ciphertext to process @returns - part of ciphercext/plain text Passed chunk of text doesn't need to contain full ciher blocks. If neccessery, part of passed data would b...
[ "def", "update", "(", "self", ",", "data", ")", ":", "if", "self", ".", "cipher_finalized", ":", "raise", "CipherError", "(", "\"No updates allowed\"", ")", "if", "not", "isinstance", "(", "data", ",", "bintype", ")", ":", "raise", "TypeError", "(", "\"A b...
38.592593
16.222222
def mouse_click(self, widget, event=None): """Triggered when mouse click is pressed in the history tree. The method shows all scoped data for an execution step as tooltip or fold and unfold the tree by double-click and select respective state for double clicked element. """ if ev...
[ "def", "mouse_click", "(", "self", ",", "widget", ",", "event", "=", "None", ")", ":", "if", "event", ".", "type", "==", "Gdk", ".", "EventType", ".", "_2BUTTON_PRESS", "and", "event", ".", "get_button", "(", ")", "[", "1", "]", "==", "1", ":", "("...
56.132653
30.459184
def _request_remaining_placeholders( self): """ *request remaining placeholders needing populated from the user* """ self.log.info( 'starting the ``_request_remaining_placeholders`` method') phNeeded = False for k, v in self.phDict.iteritems(): ...
[ "def", "_request_remaining_placeholders", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``_request_remaining_placeholders`` method'", ")", "phNeeded", "=", "False", "for", "k", ",", "v", "in", "self", ".", "phDict", ".", "iteritems", ...
28.076923
19.923077
def get_namespace(self, key): """ Returns a :class:`~bang.util.SharedNamespace` for the given :attr:`key`. These are used by :class:`~bang.deployers.deployer.Deployer` objects of the same ``deployer_class`` to coordinate control over multiple deployed instances of like r...
[ "def", "get_namespace", "(", "self", ",", "key", ")", ":", "namespace", "=", "self", ".", "shared_namespaces", ".", "get", "(", "key", ")", "if", "namespace", ":", "return", "namespace", "ns", "=", "SharedNamespace", "(", "self", ".", "manager", ")", "se...
45.521739
20.73913
def _selection_for_character(self, position): """ Convenience method for selecting a character. """ selection = QtGui.QTextEdit.ExtraSelection() cursor = self._text_edit.textCursor() cursor.setPosition(position) cursor.movePosition(QtGui.QTextCursor.NextCharacter, ...
[ "def", "_selection_for_character", "(", "self", ",", "position", ")", ":", "selection", "=", "QtGui", ".", "QTextEdit", ".", "ExtraSelection", "(", ")", "cursor", "=", "self", ".", "_text_edit", ".", "textCursor", "(", ")", "cursor", ".", "setPosition", "(",...
41.636364
8
def get_quart_iter(tups): """ returns an iterator to grab four lines at a time """ if tups[0].endswith(".gz"): ofunc = gzip.open else: ofunc = open ## create iterators ofile1 = ofunc(tups[0], 'r') fr1 = iter(ofile1) quart1 = itertools.izip(fr1, fr1, fr1, fr1) if tups[...
[ "def", "get_quart_iter", "(", "tups", ")", ":", "if", "tups", "[", "0", "]", ".", "endswith", "(", "\".gz\"", ")", ":", "ofunc", "=", "gzip", ".", "open", "else", ":", "ofunc", "=", "open", "## create iterators ", "ofile1", "=", "ofunc", "(", "tups", ...
25.896552
17.413793
def ready(self): """Validate config and connect signals.""" super(ElasticAppConfig, self).ready() _validate_config(settings.get_setting("strict_validation")) _connect_signals()
[ "def", "ready", "(", "self", ")", ":", "super", "(", "ElasticAppConfig", ",", "self", ")", ".", "ready", "(", ")", "_validate_config", "(", "settings", ".", "get_setting", "(", "\"strict_validation\"", ")", ")", "_connect_signals", "(", ")" ]
40.8
14
def _update_from_raw_data(self, raw_data, data_type_id=None, name=None, description=None): """ Upload already serialized raw data and replace the existing dataset. Parameters ---------- raw_data: bytes Dataset contents to upload. ...
[ "def", "_update_from_raw_data", "(", "self", ",", "raw_data", ",", "data_type_id", "=", "None", ",", "name", "=", "None", ",", "description", "=", "None", ")", ":", "_not_none", "(", "'raw_data'", ",", "raw_data", ")", "if", "data_type_id", "is", "None", "...
35.108108
14.783784
def readc(prompt, default=None, valid=None, question_mark=True): """Return a single character read from keyboard Parameters ---------- prompt : str Prompt string. default : str Default value. valid : str String providing valid characters. If None, all characters are ...
[ "def", "readc", "(", "prompt", ",", "default", "=", "None", ",", "valid", "=", "None", ",", "question_mark", "=", "True", ")", ":", "cresult", "=", "None", "# Avoid PyCharm warning", "# question mark", "if", "question_mark", ":", "cquestion_mark", "=", "' ? '"...
26.213115
21.098361
def register_job(self, id, job): """ Registers a new job or updates an existing job https://www.nomadproject.io/docs/http/job.html arguments: - id returns: dict raises: - nomad.api.exceptions.BaseNomadException - nomad.ap...
[ "def", "register_job", "(", "self", ",", "id", ",", "job", ")", ":", "return", "self", ".", "request", "(", "id", ",", "json", "=", "job", ",", "method", "=", "\"post\"", ")", ".", "json", "(", ")" ]
32.461538
18.538462
def delete_lifecycle(self, policy=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-delete-lifecycle.html>`_ :arg policy: The name of the index lifecycle policy """ return self.transport.perform_request( "DELETE", _make_pat...
[ "def", "delete_lifecycle", "(", "self", ",", "policy", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"DELETE\"", ",", "_make_path", "(", "\"_ilm\"", ",", "\"policy\"", ",", "policy", "...
40.444444
22.666667
def _check_trace_id(self, trace_id): """Check the format of the trace_id to ensure it is 32-character hex value representing a 128-bit number. If trace_id is invalid, returns a randomly generated trace id :type trace_id: str :param trace_id: :rtype: str :returns...
[ "def", "_check_trace_id", "(", "self", ",", "trace_id", ")", ":", "assert", "isinstance", "(", "trace_id", ",", "six", ".", "string_types", ")", "if", "trace_id", "is", "_INVALID_TRACE_ID", ":", "logging", ".", "warning", "(", "'Trace_id {} is invalid (cannot be a...
33.8
17.433333
def _get_specific_dir(dir_type): """Get a specific directory, using some XDG base, with sensible default.""" if SNAP_BASEDIR_NAME in os.environ: logger.debug("Getting base dir information from SNAP_BASEDIR_NAME env var.") direct = os.path.join(os.environ[SNAP_BASEDIR_NAME], dir_type) else: ...
[ "def", "_get_specific_dir", "(", "dir_type", ")", ":", "if", "SNAP_BASEDIR_NAME", "in", "os", ".", "environ", ":", "logger", ".", "debug", "(", "\"Getting base dir information from SNAP_BASEDIR_NAME env var.\"", ")", "direct", "=", "os", ".", "path", ".", "join", ...
40.65
17.7
def legacy_all_punctuation(): # pragma: no cover b/c tested but Coveralls: ¯\_(ツ)_/¯ """Match all punctuation. Use as only tokenizer case to mimic gTTS 1.x tokenization. """ punc = symbols.ALL_PUNC return RegexBuilder( pattern_args=punc, pattern_func=lambda x: u"{}".format(x)).rege...
[ "def", "legacy_all_punctuation", "(", ")", ":", "# pragma: no cover b/c tested but Coveralls: ¯\\_(ツ)_/¯", "punc", "=", "symbols", ".", "ALL_PUNC", "return", "RegexBuilder", "(", "pattern_args", "=", "punc", ",", "pattern_func", "=", "lambda", "x", ":", "u\"{}\"", "."...
34.777778
18.111111
def main(): """ NAME grab_magic_key.py DESCRIPTION picks out key and saves to file SYNTAX grab_magic_key.py [command line optins] OPTIONS -h prints help message and quits -f FILE: specify input magic format file -key KEY: specify key to print to sta...
[ "def", "main", "(", ")", ":", "dir_path", "=", "\"./\"", "if", "'-WD'", "in", "sys", ".", "argv", ":", "ind", "=", "sys", ".", "argv", ".", "index", "(", "'-WD'", ")", "dir_path", "=", "sys", ".", "argv", "[", "ind", "+", "1", "]", "if", "'-h'"...
22.555556
18.2
def get_traceback(f): """ Multiprocessing doesn't forward exception traceback information. This does. From: http://pragmaticpython.com/2017/02/19/ """ @functools.wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except Exception, ex: ret = '#' * 60 ret += "\nExc...
[ "def", "get_traceback", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except...
25.285714
15.666667
def fade_out(self, segment, duration, fade_type="linear"): """Adds a fade out to a segment in the composition :param segment: Segment to fade out :type segment: :py:class:`radiotool.composer.Segment` :param duration: Duration of fade-out (in seconds) :type duration: float ...
[ "def", "fade_out", "(", "self", ",", "segment", ",", "duration", ",", "fade_type", "=", "\"linear\"", ")", ":", "score_loc_in_seconds", "=", "segment", ".", "comp_location_in_seconds", "+", "segment", ".", "duration_in_seconds", "-", "duration", "f", "=", "Fade"...
41.8
17.15
def output_lines(self): """Return a sequence of lines, suitable for printing or comparing answers. """ if self.exception: return [self.EXCEPTION_HEADERS[0], ' ...'] + self.exception_detail else: return self.output
[ "def", "output_lines", "(", "self", ")", ":", "if", "self", ".", "exception", ":", "return", "[", "self", ".", "EXCEPTION_HEADERS", "[", "0", "]", ",", "' ...'", "]", "+", "self", ".", "exception_detail", "else", ":", "return", "self", ".", "output" ]
33.875
16.375
def execute(self, result=None): """ Execution 'wrapper' to make sure that it return a result :return: Execution result :rtype: kser.result.Result """ try: return self.unsafe_execute(result=result) except Exception as exc: return self._onerror(Resu...
[ "def", "execute", "(", "self", ",", "result", "=", "None", ")", ":", "try", ":", "return", "self", ".", "unsafe_execute", "(", "result", "=", "result", ")", "except", "Exception", "as", "exc", ":", "return", "self", ".", "_onerror", "(", "Result", ".",...
35
14.7
def factory(cls, config, db): """ Given a configuration and database, select and return an appropriate instance of a subclass of GetBucketKey. This will ensure that both client and server support are available for the Lua script feature of Redis, and if not, a lock will be ...
[ "def", "factory", "(", "cls", ",", "config", ",", "db", ")", ":", "# Make sure that the client supports register_script()", "if", "not", "hasattr", "(", "db", ",", "'register_script'", ")", ":", "LOG", ".", "debug", "(", "\"Redis client does not support register_scrip...
41.466667
22.333333
def softplus(x, scale=1.0, name=None): """Computes softplus with a scale factor to sharpen of the hinge. This is an alternate non-linearity to relu. It has a similar shape, but it has a smooth transition from the linear part to 0. Args: x: A tensor. scale: A float that sharpens the curve. name: Op...
[ "def", "softplus", "(", "x", ",", "scale", "=", "1.0", ",", "name", "=", "None", ")", ":", "if", "scale", "==", "1", ":", "return", "tf", ".", "nn", ".", "softplus", "(", "x", ")", "else", ":", "with", "tf", ".", "name_scope", "(", "name", ",",...
29.35
19.25
def register(self, name, description, obj, plugin): """ Registers a new shared object. :param name: Unique name for shared object :type name: str :param description: Description of shared object :type description: str :param obj: The object, which shall be shared...
[ "def", "register", "(", "self", ",", "name", ",", "description", ",", "obj", ",", "plugin", ")", ":", "if", "name", "in", "self", ".", "_shared_objects", ".", "keys", "(", ")", ":", "raise", "SharedObjectExistException", "(", "\"Shared Object %s already regist...
43.3
19.2
def value(self): """returns the object as dictionary""" if self._outline is None: return { "type" : "esriSMS", "style" : self._style, "color" : self._color.value, "size" : self._size, "angle" : self._angle, ...
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "_outline", "is", "None", ":", "return", "{", "\"type\"", ":", "\"esriSMS\"", ",", "\"style\"", ":", "self", ".", "_style", ",", "\"color\"", ":", "self", ".", "_color", ".", "value", ",", "\"...
33.423077
9.5
def get_induced_subhypergraph(self, nodes): """Gives a new hypergraph that is the subhypergraph of the current hypergraph induced by the provided set of nodes. That is, the induced subhypergraph's node set corresponds precisely to the nodes provided, and the coressponding hyperedges in t...
[ "def", "get_induced_subhypergraph", "(", "self", ",", "nodes", ")", ":", "sub_H", "=", "self", ".", "copy", "(", ")", "sub_H", ".", "remove_nodes", "(", "sub_H", ".", "get_node_set", "(", ")", "-", "set", "(", "nodes", ")", ")", "return", "sub_H" ]
47.0625
23.25
def multi_lpop(self, queue, number, transaction=False): ''' Pops multiple elements from a list ''' try: self._multi_lpop_pipeline(self, queue, number) except: raise
[ "def", "multi_lpop", "(", "self", ",", "queue", ",", "number", ",", "transaction", "=", "False", ")", ":", "try", ":", "self", ".", "_multi_lpop_pipeline", "(", "self", ",", "queue", ",", "number", ")", "except", ":", "raise" ]
35.333333
20
def to_xy_array(self): """ Convert keypoint coordinates to ``(N,2)`` array. Returns ------- (N, 2) ndarray Array containing the coordinates of all keypoints. Shape is ``(N,2)`` with coordinates in xy-form. """ result = np.zeros((len(self....
[ "def", "to_xy_array", "(", "self", ")", ":", "result", "=", "np", ".", "zeros", "(", "(", "len", "(", "self", ".", "keypoints", ")", ",", "2", ")", ",", "dtype", "=", "np", ".", "float32", ")", "for", "i", ",", "keypoint", "in", "enumerate", "(",...
30.625
18.125
def check_date_str_format(s, default_time="00:00:00"): """Check the format of date string""" try: str_fmt = s if ":" not in s: str_fmt = '{} {}'.format(s, default_time) dt_obj = datetime.strptime(str_fmt, "%Y-%m-%d %H:%M:%S") return RET_OK, dt_obj except ValueE...
[ "def", "check_date_str_format", "(", "s", ",", "default_time", "=", "\"00:00:00\"", ")", ":", "try", ":", "str_fmt", "=", "s", "if", "\":\"", "not", "in", "s", ":", "str_fmt", "=", "'{} {}'", ".", "format", "(", "s", ",", "default_time", ")", "dt_obj", ...
29.642857
21.428571
def _handshake(self): """ Perform an initial TLS handshake """ self._ssl = None self._rbio = None self._wbio = None try: self._ssl = libssl.SSL_new(self._session._ssl_ctx) if is_null(self._ssl): self._ssl = None ...
[ "def", "_handshake", "(", "self", ")", ":", "self", ".", "_ssl", "=", "None", "self", ".", "_rbio", "=", "None", "self", ".", "_wbio", "=", "None", "try", ":", "self", ".", "_ssl", "=", "libssl", ".", "SSL_new", "(", "self", ".", "_session", ".", ...
40.915254
19.966102
def on_board(self, *args): """Draw myself for the first time as soon as I have the properties I need to do so. """ if None in ( self.board, self.origin, self.destination ): Clock.schedule_once(self.on_board, 0) ...
[ "def", "on_board", "(", "self", ",", "*", "args", ")", ":", "if", "None", "in", "(", "self", ".", "board", ",", "self", ".", "origin", ",", "self", ".", "destination", ")", ":", "Clock", ".", "schedule_once", "(", "self", ".", "on_board", ",", "0",...
26.923077
15
def register_variant(cls): """ Registers the RADIUS attributes defined in this module. """ if hasattr(cls, "val"): cls.registered_attributes[cls.val] = cls else: cls.registered_attributes[cls.type.default] = cls
[ "def", "register_variant", "(", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "\"val\"", ")", ":", "cls", ".", "registered_attributes", "[", "cls", ".", "val", "]", "=", "cls", "else", ":", "cls", ".", "registered_attributes", "[", "cls", ".", "ty...
29.777778
16.222222
def url(value, allow_empty = False, allow_special_ips = False, **kwargs): """Validate that ``value`` is a valid URL. .. note:: URL validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 1738 <https://tools.ietf.org/ht...
[ "def", "url", "(", "value", ",", "allow_empty", "=", "False", ",", "allow_special_ips", "=", "False", ",", "*", "*", "kwargs", ")", ":", "is_recursive", "=", "kwargs", ".", "pop", "(", "'is_recursive'", ",", "False", ")", "if", "not", "value", "and", "...
35.604396
22.648352
def load_css_templates(): """Loads 2 css templates to demonstrate the feature""" print('Creating default CSS templates') obj = db.session.query(CssTemplate).filter_by(template_name='Flat').first() if not obj: obj = CssTemplate(template_name='Flat') css = textwrap.dedent("""\ .gridster d...
[ "def", "load_css_templates", "(", ")", ":", "print", "(", "'Creating default CSS templates'", ")", "obj", "=", "db", ".", "session", ".", "query", "(", "CssTemplate", ")", ".", "filter_by", "(", "template_name", "=", "'Flat'", ")", ".", "first", "(", ")", ...
27.28866
21.865979