text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _handle_command(self, command): """ Handle command. This will run in a separate thread, in order not to block the event loop. """ logger.info('Handle command %r', command) def in_executor(): self.handling_command = True try: if...
[ "def", "_handle_command", "(", "self", ",", "command", ")", ":", "logger", ".", "info", "(", "'Handle command %r'", ",", "command", ")", "def", "in_executor", "(", ")", ":", "self", ".", "handling_command", "=", "True", "try", ":", "if", "self", ".", "ca...
34.857143
0.001994
def delete_connection(): """ Stop and destroy Bloomberg connection """ if _CON_SYM_ in globals(): con = globals().pop(_CON_SYM_) if not getattr(con, '_session').start(): con.stop()
[ "def", "delete_connection", "(", ")", ":", "if", "_CON_SYM_", "in", "globals", "(", ")", ":", "con", "=", "globals", "(", ")", ".", "pop", "(", "_CON_SYM_", ")", "if", "not", "getattr", "(", "con", ",", "'_session'", ")", ".", "start", "(", ")", ":...
29.428571
0.009434
def download(self): """Method which downloads submission to local directory.""" # Structure of the download directory: # submission_dir=LOCAL_SUBMISSIONS_DIR/submission_id # submission_dir/s.ext <-- archived submission # submission_dir/extracted <-- extracted submission # Check whether s...
[ "def", "download", "(", "self", ")", ":", "# Structure of the download directory:", "# submission_dir=LOCAL_SUBMISSIONS_DIR/submission_id", "# submission_dir/s.ext <-- archived submission", "# submission_dir/extracted <-- extracted submission", "# Check whether submission is already there...
45.373737
0.008932
def child_task(self): '''child process - this holds all the GUI elements''' mp_util.child_close_fds() from MAVProxy.modules.lib import wx_processguard from MAVProxy.modules.lib.wx_loader import wx from MAVProxy.modules.mavproxy_map.mp_slipmap_ui import MPSlipMapFrame st...
[ "def", "child_task", "(", "self", ")", ":", "mp_util", ".", "child_close_fds", "(", ")", "from", "MAVProxy", ".", "modules", ".", "lib", "import", "wx_processguard", "from", "MAVProxy", ".", "modules", ".", "lib", ".", "wx_loader", "import", "wx", "from", ...
35.833333
0.002265
def update_login_profile(self, user_name, password): """ Resets the password associated with the user's login profile. :type user_name: string :param user_name: The name of the user :type password: string :param password: The new password for the user """ ...
[ "def", "update_login_profile", "(", "self", ",", "user_name", ",", "password", ")", ":", "params", "=", "{", "'UserName'", ":", "user_name", ",", "'Password'", ":", "password", "}", "return", "self", ".", "get_response", "(", "'UpdateLoginProfile'", ",", "para...
31.928571
0.008696
def choose_intronic_effect_class( variant, nearest_exon, distance_to_exon): """ Infer effect of variant which does not overlap any exon of the given transcript. """ assert distance_to_exon > 0, \ "Expected intronic effect to have distance_to_exon > 0, got %d" % ( ...
[ "def", "choose_intronic_effect_class", "(", "variant", ",", "nearest_exon", ",", "distance_to_exon", ")", ":", "assert", "distance_to_exon", ">", "0", ",", "\"Expected intronic effect to have distance_to_exon > 0, got %d\"", "%", "(", "distance_to_exon", ",", ")", "if", "...
41.265306
0.000483
def list_keys(user=None, gnupghome=None): ''' List keys in GPG keychain user Which user's keychain to access, defaults to user Salt is running as. Passing the user as ``salt`` will set the GnuPG home directory to the ``/etc/salt/gpgkeys``. gnupghome Specify the location...
[ "def", "list_keys", "(", "user", "=", "None", ",", "gnupghome", "=", "None", ")", ":", "_keys", "=", "[", "]", "for", "_key", "in", "_list_keys", "(", "user", ",", "gnupghome", ")", ":", "tmp", "=", "{", "'keyid'", ":", "_key", "[", "'keyid'", "]",...
31.177778
0.001382
def add_from_file(self, filename, handler_decorator=None): """ Wrapper around add() that reads the handlers from the file with the given name. The file is a Python script containing a list named 'commands' of tuples that map command names to handlers. :type filename: st...
[ "def", "add_from_file", "(", "self", ",", "filename", ",", "handler_decorator", "=", "None", ")", ":", "args", "=", "{", "}", "execfile", "(", "filename", ",", "args", ")", "commands", "=", "args", ".", "get", "(", "'commands'", ")", "if", "commands", ...
42.333333
0.001925
def sendNotification(snmpDispatcher, authData, transportTarget, notifyType, *varBinds, **options): """Creates a generator to send one or more SNMP notifications. On each iteration, new SNMP TRAP or INFORM notification is send (:RFC:`1905#section-4,2,6`). The iterator blocks waiting for...
[ "def", "sendNotification", "(", "snmpDispatcher", ",", "authData", ",", "transportTarget", ",", "notifyType", ",", "*", "varBinds", ",", "*", "*", "options", ")", ":", "def", "cbFun", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "response", "[", ...
38.14876
0.001689
def make_archive(self, path): """Create archive of directory and write to ``path``. :param path: Path to archive Ignored:: * build/* - This is used for packing the charm itself and any similar tasks. * */.* - Hidden files are all ignored fo...
[ "def", "make_archive", "(", "self", ",", "path", ")", ":", "zf", "=", "zipfile", ".", "ZipFile", "(", "path", ",", "'w'", ",", "zipfile", ".", "ZIP_DEFLATED", ")", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "se...
41.59375
0.001468
def getgoal(path, opts=None): ''' Return goal(s) for a file or directory CLI Example: .. code-block:: bash salt '*' moosefs.getgoal /path/to/file [-[n][h|H]] salt '*' moosefs.getgoal /path/to/dir/ [-[n][h|H][r]] ''' cmd = 'mfsgetgoal' ret = {} if opts: cmd += '...
[ "def", "getgoal", "(", "path", ",", "opts", "=", "None", ")", ":", "cmd", "=", "'mfsgetgoal'", "ret", "=", "{", "}", "if", "opts", ":", "cmd", "+=", "' -'", "+", "opts", "else", ":", "opts", "=", "''", "cmd", "+=", "' '", "+", "path", "out", "=...
23.947368
0.001056
def geometric_delay(sig, dur, copies, pamp=.5): """ Delay effect by copying data (with Streamix). Parameters ---------- sig: Input signal (an iterable). dur: Duration, in samples. copies: Number of times the signal will be replayed in the given duration. The signal is played copies + 1 ti...
[ "def", "geometric_delay", "(", "sig", ",", "dur", ",", "copies", ",", "pamp", "=", ".5", ")", ":", "out", "=", "Streamix", "(", ")", "sig", "=", "thub", "(", "sig", ",", "copies", "+", "1", ")", "out", ".", "add", "(", "0", ",", "sig", "*", "...
25.777778
0.012465
def get_hash(file_path, checksum='sha1'): """ Generate a hash for the given file Args: file_path (str): Path to the file to generate the hash for checksum (str): hash to apply, one of the supported by hashlib, for example sha1 or sha512 Returns: str: hash for that f...
[ "def", "get_hash", "(", "file_path", ",", "checksum", "=", "'sha1'", ")", ":", "sha", "=", "getattr", "(", "hashlib", ",", "checksum", ")", "(", ")", "with", "open", "(", "file_path", ")", "as", "file_descriptor", ":", "while", "True", ":", "chunk", "=...
27.095238
0.001698
def setup_logger(log_level, log_file=None, logger_name=None): """setup logger @param log_level: debug/info/warning/error/critical @param log_file: log file path @param logger_name: the name of logger, default is 'root' if not specify """ applogger = AppL...
[ "def", "setup_logger", "(", "log_level", ",", "log_file", "=", "None", ",", "logger_name", "=", "None", ")", ":", "applogger", "=", "AppLog", "(", "logger_name", ")", "level", "=", "getattr", "(", "logging", ",", "log_level", ".", "upper", "(", ")", ",",...
37.818182
0.009379
def get_config(config, default_config): '''Load configuration from file if in config, else use default''' if not config: logging.warning('Using default config: %s', default_config) config = default_config try: with open(config, 'r') as config_file: return yaml.load(confi...
[ "def", "get_config", "(", "config", ",", "default_config", ")", ":", "if", "not", "config", ":", "logging", ".", "warning", "(", "'Using default config: %s'", ",", "default_config", ")", "config", "=", "default_config", "try", ":", "with", "open", "(", "config...
38.230769
0.001965
def grab_file_url(file_url, appname='utool', download_dir=None, delay=None, spoof=False, fname=None, verbose=True, redownload=False, check_hash=False): r""" Downloads a file and returns the local path of the file. The resulting file is cached, so multiple calls to this f...
[ "def", "grab_file_url", "(", "file_url", ",", "appname", "=", "'utool'", ",", "download_dir", "=", "None", ",", "delay", "=", "None", ",", "spoof", "=", "False", ",", "fname", "=", "None", ",", "verbose", "=", "True", ",", "redownload", "=", "False", "...
42.717742
0.001845
def add_my_api_key_to_groups(self, body, **kwargs): # noqa: E501 """Add API key to a list of groups. # noqa: E501 An endpoint for adding API key to groups. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586...
[ "def", "add_my_api_key_to_groups", "(", "self", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self", ".", ...
58.904762
0.001591
def _is_trailing_comma(tokens, index): """Check if the given token is a trailing comma :param tokens: Sequence of modules tokens :type tokens: list[tokenize.TokenInfo] :param int index: Index of token under check in tokens :returns: True if the token is a comma which trails an expression :rtype...
[ "def", "_is_trailing_comma", "(", "tokens", ",", "index", ")", ":", "token", "=", "tokens", "[", "index", "]", "if", "token", ".", "exact_type", "!=", "tokenize", ".", "COMMA", ":", "return", "False", "# Must have remaining tokens on the same line such as NEWLINE", ...
39.069767
0.001161
def mt_deconvolve(data_a, data_b, delta, nfft=None, time_bandwidth=None, number_of_tapers=None, weights="adaptive", demean=True, fmax=0.0): """ Deconvolve two time series using multitapers. This uses the eigencoefficients and the weights from the multitaper spectral ...
[ "def", "mt_deconvolve", "(", "data_a", ",", "data_b", ",", "delta", ",", "nfft", "=", "None", ",", "time_bandwidth", "=", "None", ",", "number_of_tapers", "=", "None", ",", "weights", "=", "\"adaptive\"", ",", "demean", "=", "True", ",", "fmax", "=", "0....
32.472441
0.000235
def from_clause(cls, clause): """ Factory method """ [_, field, operator, val] = clause return cls(field, operator, resolve(val))
[ "def", "from_clause", "(", "cls", ",", "clause", ")", ":", "[", "_", ",", "field", ",", "operator", ",", "val", "]", "=", "clause", "return", "cls", "(", "field", ",", "operator", ",", "resolve", "(", "val", ")", ")" ]
37.5
0.013072
def pupatizeElements(self) : """Transform all raba object into pupas""" for i in range(len(self)) : self[i] = self[i].pupa()
[ "def", "pupatizeElements", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ")", ")", ":", "self", "[", "i", "]", "=", "self", "[", "i", "]", ".", "pupa", "(", ")" ]
32
0.053435
def _joinclass(codtuple): """ The opposite of splitclass(). Joins a (service, major, minor) class-of- device tuple into a whole class of device value. """ if not isinstance(codtuple, tuple): raise TypeError("argument must be tuple, was %s" % type(codtuple)) if len(codtuple) != 3: ...
[ "def", "_joinclass", "(", "codtuple", ")", ":", "if", "not", "isinstance", "(", "codtuple", ",", "tuple", ")", ":", "raise", "TypeError", "(", "\"argument must be tuple, was %s\"", "%", "type", "(", "codtuple", ")", ")", "if", "len", "(", "codtuple", ")", ...
38.785714
0.001799
def generate_sitemap(sitemap: typing.Mapping, prefix: list=None): """Create a sitemap template from the given sitemap. The `sitemap` should be a mapping where the key is a string which represents a single URI segment, and the value is either another mapping or a callable (e.g. function) object. Ar...
[ "def", "generate_sitemap", "(", "sitemap", ":", "typing", ".", "Mapping", ",", "prefix", ":", "list", "=", "None", ")", ":", "# Ensures all generated urls are prefixed with a the prefix string", "if", "prefix", "is", "None", ":", "prefix", "=", "[", "]", "for", ...
41.152174
0.001548
def html_to_plain_text(html): """Converts html code into formatted plain text.""" # Use BeautifulSoup to normalize the html soup = BeautifulSoup(html, "html.parser") # Init the parser parser = HTML2PlainParser() parser.feed(str(soup.encode('utf-8'))) # Strip the end of the plain text res...
[ "def", "html_to_plain_text", "(", "html", ")", ":", "# Use BeautifulSoup to normalize the html", "soup", "=", "BeautifulSoup", "(", "html", ",", "\"html.parser\"", ")", "# Init the parser", "parser", "=", "HTML2PlainParser", "(", ")", "parser", ".", "feed", "(", "st...
34
0.001908
def post_report(coverage, args): """Post coverage report to coveralls.io.""" response = requests.post(URL, files={'json_file': json.dumps(coverage)}, verify=(not args.skip_ssl_verify)) try: result = response.json() except ValueError: result = {'error': 'Failu...
[ "def", "post_report", "(", "coverage", ",", "args", ")", ":", "response", "=", "requests", ".", "post", "(", "URL", ",", "files", "=", "{", "'json_file'", ":", "json", ".", "dumps", "(", "coverage", ")", "}", ",", "verify", "=", "(", "not", "args", ...
38
0.001712
def assemble_caption(begin_line, begin_index, end_line, end_index, lines): """ Take the caption of a picture and put it all together in a nice way. If it spans multiple lines, put it on one line. If it contains controlled characters, strip them out. If it has tags we don't want to worry about, ge...
[ "def", "assemble_caption", "(", "begin_line", ",", "begin_index", ",", "end_line", ",", "end_index", ",", "lines", ")", ":", "# stuff we don't like", "label_head", "=", "'\\\\label{'", "# reassemble that sucker", "if", "end_line", ">", "begin_line", ":", "# our captio...
39.62
0.000493
def path(self): """str: URL path for the model's APIs.""" return "/projects/%s/datasets/%s/models/%s" % ( self._proto.project_id, self._proto.dataset_id, self._proto.model_id, )
[ "def", "path", "(", "self", ")", ":", "return", "\"/projects/%s/datasets/%s/models/%s\"", "%", "(", "self", ".", "_proto", ".", "project_id", ",", "self", ".", "_proto", ".", "dataset_id", ",", "self", ".", "_proto", ".", "model_id", ",", ")" ]
33
0.008439
def Overlay_highlightQuad(self, quad, **kwargs): """ Function path: Overlay.highlightQuad Domain: Overlay Method name: highlightQuad Parameters: Required arguments: 'quad' (type: DOM.Quad) -> Quad to highlight Optional arguments: 'color' (type: DOM.RGBA) -> The highlight fill color (de...
[ "def", "Overlay_highlightQuad", "(", "self", ",", "quad", ",", "*", "*", "kwargs", ")", ":", "expected", "=", "[", "'color'", ",", "'outlineColor'", "]", "passed_keys", "=", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "assert", "all", "(", "[", ...
38.304348
0.03876
def load_stl_ascii(file_obj): """ Load an ASCII STL file from a file object. Parameters ---------- file_obj: open file- like object Returns ---------- loaded: kwargs for a Trimesh constructor with keys: vertices: (n,3) float, vertices faces: (m,3)...
[ "def", "load_stl_ascii", "(", "file_obj", ")", ":", "# the first line is the header", "header", "=", "file_obj", ".", "readline", "(", ")", "# make sure header is a string, not bytes", "if", "hasattr", "(", "header", ",", "'decode'", ")", ":", "try", ":", "header", ...
31.868852
0.000499
def set_tags(self, tags): """Sets this object's tags to only those tags. * tags: a sequence of tag names or Tag objects. """ c_old_tags = [] old_tags = [] c_new_tags = [] new_tags = [] to_remove = [] to_add = [] tags_on_server = self.get...
[ "def", "set_tags", "(", "self", ",", "tags", ")", ":", "c_old_tags", "=", "[", "]", "old_tags", "=", "[", "]", "c_new_tags", "=", "[", "]", "new_tags", "=", "[", "]", "to_remove", "=", "[", "]", "to_add", "=", "[", "]", "tags_on_server", "=", "self...
26.333333
0.00222
def expr_items(expr): """ Returns a set() of all items (symbols and choices) that appear in the expression 'expr'. """ res = set() def rec(subexpr): if subexpr.__class__ is tuple: # AND, OR, NOT, or relation rec(subexpr[1]) # NOTs only have a singl...
[ "def", "expr_items", "(", "expr", ")", ":", "res", "=", "set", "(", ")", "def", "rec", "(", "subexpr", ")", ":", "if", "subexpr", ".", "__class__", "is", "tuple", ":", "# AND, OR, NOT, or relation", "rec", "(", "subexpr", "[", "1", "]", ")", "# NOTs on...
20.041667
0.001984
def count_characters(root, out): """Count the occurrances of the different characters in the files""" if os.path.isfile(root): with open(root, 'rb') as in_f: for line in in_f: for char in line: if char not in out: out[char] = 0 ...
[ "def", "count_characters", "(", "root", ",", "out", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "root", ")", ":", "with", "open", "(", "root", ",", "'rb'", ")", "as", "in_f", ":", "for", "line", "in", "in_f", ":", "for", "char", "in", ...
40.5
0.002012
def readArray(self): """ Reads an array from the stream. @warning: There is a very specific problem with AMF3 where the first three bytes of an encoded empty C{dict} will mirror that of an encoded C{{'': 1, '2': 2}} """ size = self.readInteger(False) if ...
[ "def", "readArray", "(", "self", ")", ":", "size", "=", "self", ".", "readInteger", "(", "False", ")", "if", "size", "&", "REFERENCE_BIT", "==", "0", ":", "return", "self", ".", "context", ".", "getObject", "(", "size", ">>", "1", ")", "size", ">>=",...
24.615385
0.002004
def get_host(environ): # type: (Dict[str, str]) -> str """Return the host for the given WSGI environment. Yanked from Werkzeug.""" if environ.get("HTTP_HOST"): rv = environ["HTTP_HOST"] if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"): rv = rv[:-3] elif envi...
[ "def", "get_host", "(", "environ", ")", ":", "# type: (Dict[str, str]) -> str", "if", "environ", ".", "get", "(", "\"HTTP_HOST\"", ")", ":", "rv", "=", "environ", "[", "\"HTTP_HOST\"", "]", "if", "environ", "[", "\"wsgi.url_scheme\"", "]", "==", "\"http\"", "a...
36.380952
0.001276
def polfit_residuals_with_sigma_rejection( x, y, deg, times_sigma_reject, color='b', size=75, xlim=None, ylim=None, xlabel=None, ylabel=None, title=None, use_r=None, geometry=(0,0,640,480), debugplot=0): """Polynomial fit with iterative rejection of points. ...
[ "def", "polfit_residuals_with_sigma_rejection", "(", "x", ",", "y", ",", "deg", ",", "times_sigma_reject", ",", "color", "=", "'b'", ",", "size", "=", "75", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "xlabel", "=", "None", ",", "ylabel", ...
42.519774
0.000519
def blob_containers(self): """Instance depends on the API version: * 2018-02-01: :class:`BlobContainersOperations<azure.mgmt.storage.v2018_02_01.operations.BlobContainersOperations>` * 2018-03-01-preview: :class:`BlobContainersOperations<azure.mgmt.storage.v2018_03_01_preview.operations.B...
[ "def", "blob_containers", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'blob_containers'", ")", "if", "api_version", "==", "'2018-02-01'", ":", "from", ".", "v2018_02_01", ".", "operations", "import", "BlobContainersOperations", ...
70.411765
0.008244
def config(self, configlet, plane, **attributes): """Apply config to the device.""" try: config_text = configlet.format(**attributes) except KeyError as exp: raise CommandSyntaxError("Configuration template error: {}".format(str(exp))) return self.driver.config(c...
[ "def", "config", "(", "self", ",", "configlet", ",", "plane", ",", "*", "*", "attributes", ")", ":", "try", ":", "config_text", "=", "configlet", ".", "format", "(", "*", "*", "attributes", ")", "except", "KeyError", "as", "exp", ":", "raise", "Command...
41.375
0.008876
def get_name(): '''Get desktop environment or OS. Get the OS name or desktop environment. **List of Possible Values** +-------------------------+---------------+ | Windows | windows | +-------------------------+---------------+ | Mac OS X | mac | +-------------------------+---------------+ | G...
[ "def", "get_name", "(", ")", ":", "if", "sys", ".", "platform", "in", "[", "'win32'", ",", "'cygwin'", "]", ":", "return", "'windows'", "elif", "sys", ".", "platform", "==", "'darwin'", ":", "return", "'mac'", "else", ":", "desktop_session", "=", "os", ...
27.882353
0.031141
def children(self): """ Returns the children in this group. :return [<QtGui.QListWidgetItem>, ..] """ new_refs = set() output = [] for ref in self._children: item = ref() if item is not None: output.a...
[ "def", "children", "(", "self", ")", ":", "new_refs", "=", "set", "(", ")", "output", "=", "[", "]", "for", "ref", "in", "self", ".", "_children", ":", "item", "=", "ref", "(", ")", "if", "item", "is", "not", "None", ":", "output", ".", "append",...
26.1875
0.009217
def get_catalog(self, locale): """Create Django translation catalogue for `locale`.""" with translation.override(locale): translation_engine = DjangoTranslation(locale, domain=self.domain, localedirs=self.paths) trans_cat = translation_engine._catalog trans_fallback_...
[ "def", "get_catalog", "(", "self", ",", "locale", ")", ":", "with", "translation", ".", "override", "(", "locale", ")", ":", "translation_engine", "=", "DjangoTranslation", "(", "locale", ",", "domain", "=", "self", ".", "domain", ",", "localedirs", "=", "...
49.444444
0.00883
def apply(self, events): """ EventManager.apply(events) -> Takes an object with methods, and applies them to EventManager. Example: class TestEvents(object): @staticmethod def test_method(): pass e = T...
[ "def", "apply", "(", "self", ",", "events", ")", ":", "for", "method", "in", "dir", "(", "events", ")", ":", "# Skip attributes\r", "if", "not", "callable", "(", "getattr", "(", "events", ",", "method", ")", ")", ":", "continue", "# Skip \"trash\" function...
34.222222
0.002105
def _get_session_for_table(self, base_session): """ Only present session for modeling when doses were dropped if it's succesful; otherwise show the original modeling session. """ if base_session.recommended_model is None and base_session.doses_dropped > 0: return base...
[ "def", "_get_session_for_table", "(", "self", ",", "base_session", ")", ":", "if", "base_session", ".", "recommended_model", "is", "None", "and", "base_session", ".", "doses_dropped", ">", "0", ":", "return", "base_session", ".", "doses_dropped_sessions", "[", "0"...
46.875
0.010471
def translate_table(data): """ Translates data where data["Type"]=="Table" """ headers = sorted(data.get("Headers", [])) table = '\\FloatBarrier \n \\section{$NAME} \n'.replace('$NAME', data.get("Title", "table")) table += '\\begin{table}[!ht] \n \\begin{center}' # Set the number of columns n_c...
[ "def", "translate_table", "(", "data", ")", ":", "headers", "=", "sorted", "(", "data", ".", "get", "(", "\"Headers\"", ",", "[", "]", ")", ")", "table", "=", "'\\\\FloatBarrier \\n \\\\section{$NAME} \\n'", ".", "replace", "(", "'$NAME'", ",", "data", ".", ...
38.952381
0.009547
def set_layout_settings(self, settings): """Restore layout state""" size = settings.get('size') if size is not None: self.resize( QSize(*size) ) self.window_size = self.size() pos = settings.get('pos') if pos is not None: self.move( QPo...
[ "def", "set_layout_settings", "(", "self", ",", "settings", ")", ":", "size", "=", "settings", ".", "get", "(", "'size'", ")", "if", "size", "is", "not", "None", ":", "self", ".", "resize", "(", "QSize", "(", "*", "size", ")", ")", "self", ".", "wi...
43.3
0.00904
def duration(self, value): """ Setter for **self.__duration** attribute. :param value: Attribute value. :type value: int """ if value is not None: assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format("duration", value) as...
[ "def", "duration", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "int", ",", "\"'{0}' attribute: '{1}' type is not 'int'!\"", ".", "format", "(", "\"duration\"", ",", "value", ")", ...
36.416667
0.008929
def flush(self): """Flushes the current queue by notifying the :func:`sender` via the :func:`flush_notification` event. """ self._flush_notification.set() if self.sender: self.sender.start()
[ "def", "flush", "(", "self", ")", ":", "self", ".", "_flush_notification", ".", "set", "(", ")", "if", "self", ".", "sender", ":", "self", ".", "sender", ".", "start", "(", ")" ]
38.166667
0.012821
def get_session(key=None, username=None, password=None, cache=True, cache_expiry=datetime.timedelta(days=7), cookie_path=COOKIE_PATH, backend='memory', version=VERSION_GLOBAL): """Get Voobly API session.""" class VooblyAuth(AuthBase): # pylint: disable=too-few-public-methods ...
[ "def", "get_session", "(", "key", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "cache", "=", "True", ",", "cache_expiry", "=", "datetime", ".", "timedelta", "(", "days", "=", "7", ")", ",", "cookie_path", "=", "COOKIE_P...
39.433333
0.002475
def _convert_num(self, sign): """ Converts number registered in get_number_from_sign. input = ["a2", "☉", "be3"] output = ["a₂", "☉", "be₃"] :param sign: string :return sign: string """ # Check if there's a number at the end new_sign, num = self....
[ "def", "_convert_num", "(", "self", ",", "sign", ")", ":", "# Check if there's a number at the end", "new_sign", ",", "num", "=", "self", ".", "_get_number_from_sign", "(", "sign", ")", "if", "num", "<", "2", ":", "# \"ab\" -> \"ab\"", "return", "new_sign", ".",...
40.558824
0.002125
def post_status(self, body="", id="", parentid="", stashid=""): """Post a status :param username: The body of the status :param id: The id of the object you wish to share :param parentid: The parentid of the object you wish to share :param stashid: The stashid of the object you...
[ "def", "post_status", "(", "self", ",", "body", "=", "\"\"", ",", "id", "=", "\"\"", ",", "parentid", "=", "\"\"", ",", "stashid", "=", "\"\"", ")", ":", "if", "self", ".", "standard_grant_type", "is", "not", "\"authorization_code\"", ":", "raise", "Devi...
36.571429
0.008883
def titles2marc(self, key, values): """Populate the ``246`` MARC field. Also populates the ``245`` MARC field through side effects. """ first, rest = values[0], values[1:] self.setdefault('245', []).append({ 'a': first.get('title'), 'b': first.get('subtitle'), '9': first.ge...
[ "def", "titles2marc", "(", "self", ",", "key", ",", "values", ")", ":", "first", ",", "rest", "=", "values", "[", "0", "]", ",", "values", "[", "1", ":", "]", "self", ".", "setdefault", "(", "'245'", ",", "[", "]", ")", ".", "append", "(", "{",...
24.65
0.001953
def basis(self, n): """ Chebyshev basis functions T_n. """ if n == 0: return self(np.array([1.])) vals = np.ones(n+1) vals[1::2] = -1 return self(vals)
[ "def", "basis", "(", "self", ",", "n", ")", ":", "if", "n", "==", "0", ":", "return", "self", "(", "np", ".", "array", "(", "[", "1.", "]", ")", ")", "vals", "=", "np", ".", "ones", "(", "n", "+", "1", ")", "vals", "[", "1", ":", ":", "...
23.444444
0.009132
def _subprocess_method(self, command): """Use the subprocess module to execute ipmitool commands and and set status """ p = subprocess.Popen([self._ipmitool_path] + self.args + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.output, self.error = p.communicate() ...
[ "def", "_subprocess_method", "(", "self", ",", "command", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "self", ".", "_ipmitool_path", "]", "+", "self", ".", "args", "+", "command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stder...
49.142857
0.008571
def max(self, default=None): """ Calculate the maximum value over the time series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the maximum value or `None`. """ return numpy.asscalar(numpy.max(self.value...
[ "def", "max", "(", "self", ",", "default", "=", "None", ")", ":", "return", "numpy", ".", "asscalar", "(", "numpy", ".", "max", "(", "self", ".", "values", ")", ")", "if", "self", ".", "values", "else", "default" ]
43
0.011396
def _make_container_root(name): ''' Make the container root directory ''' path = _root(name) if os.path.exists(path): __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL raise CommandExecutionError( 'Container {0} already exists'.format(name) ) el...
[ "def", "_make_container_root", "(", "name", ")", ":", "path", "=", "_root", "(", "name", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "__context__", "[", "'retcode'", "]", "=", "salt", ".", "defaults", ".", "exitcodes", ".", "S...
29.473684
0.00173
def get_without_extra(marker): """Build a new marker without the `extra == ...` part. The implementation relies very deep into packaging's internals, but I don't have a better way now (except implementing the whole thing myself). This could return `None` if the `extra == ...` part is the only one in t...
[ "def", "get_without_extra", "(", "marker", ")", ":", "# TODO: Why is this very deep in the internals? Why is a better solution", "# implementing it yourself when someone is already maintaining a codebase", "# for this? It's literally a grammar implementation that is required to", "# meet the deman...
37.238095
0.001247
def _cb_inform_interface_change(self, msg): """Update the sensors and requests available.""" self._logger.debug('cb_inform_interface_change(%s)', msg) self._interface_changed.set()
[ "def", "_cb_inform_interface_change", "(", "self", ",", "msg", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'cb_inform_interface_change(%s)'", ",", "msg", ")", "self", ".", "_interface_changed", ".", "set", "(", ")" ]
50.25
0.009804
def doit(self): """Do (most of) it function of the model class.""" print(' . doit') lines = Lines() lines.add(1, 'cpdef inline void doit(self, int idx) %s:' % _nogil) lines.add(2, 'self.idx_sim = idx') if getattr(self.model.sequences, 'inputs', None) is not...
[ "def", "doit", "(", "self", ")", ":", "print", "(", "' . doit'", ")", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "1", ",", "'cpdef inline void doit(self, int idx) %s:'", "%", "_nogil", ")", "lines", ".", "add", "(", "2", ",",...
42.315789
0.002433
def _getEngineVersionHash(self): """ Computes the SHA-256 hash of the JSON version details for the latest installed version of UE4 """ versionDetails = self._getEngineVersionDetails() hash = hashlib.sha256() hash.update(json.dumps(versionDetails, sort_keys=True, indent=0).encode('utf-8')) return hash.hexd...
[ "def", "_getEngineVersionHash", "(", "self", ")", ":", "versionDetails", "=", "self", ".", "_getEngineVersionDetails", "(", ")", "hash", "=", "hashlib", ".", "sha256", "(", ")", "hash", ".", "update", "(", "json", ".", "dumps", "(", "versionDetails", ",", ...
40
0.033639
def read_all(self): """Fetches all messages in the database. :rtype: Generator[can.Message] """ result = self._cursor.execute("SELECT * FROM {}".format(self.table_name)).fetchall() return (SqliteReader._assemble_message(frame) for frame in result)
[ "def", "read_all", "(", "self", ")", ":", "result", "=", "self", ".", "_cursor", ".", "execute", "(", "\"SELECT * FROM {}\"", ".", "format", "(", "self", ".", "table_name", ")", ")", ".", "fetchall", "(", ")", "return", "(", "SqliteReader", ".", "_assemb...
40.285714
0.010417
def clear(self): """ Clear all contents in the relay memory """ self.states[:] = 0 self.actions[:] = 0 self.rewards[:] = 0 self.terminate_flags[:] = 0 self.top = 0 self.size = 0
[ "def", "clear", "(", "self", ")", ":", "self", ".", "states", "[", ":", "]", "=", "0", "self", ".", "actions", "[", ":", "]", "=", "0", "self", ".", "rewards", "[", ":", "]", "=", "0", "self", ".", "terminate_flags", "[", ":", "]", "=", "0", ...
24
0.008032
def has_publish_permission(self, request, obj=None): """ Determines if the user has permissions to publish. :param request: Django request object. :param obj: The object to determine if the user has permissions to publish. :return: Boolean. """ # If auto-...
[ "def", "has_publish_permission", "(", "self", ",", "request", ",", "obj", "=", "None", ")", ":", "# If auto-publishing is enabled, no user has \"permission\" to publish", "# because it happens automatically", "if", "is_automatic_publishing_enabled", "(", "self", ".", "model", ...
41.821429
0.001669
def write_frame(self): """ Writes a single frame to the movie file """ if not hasattr(self, 'mwriter'): raise AssertionError('This plotter has not opened a movie or GIF file.') self.mwriter.append_data(self.image)
[ "def", "write_frame", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'mwriter'", ")", ":", "raise", "AssertionError", "(", "'This plotter has not opened a movie or GIF file.'", ")", "self", ".", "mwriter", ".", "append_data", "(", "self", ".",...
49
0.012048
def _convert_schema(bundle): """ Converts schema of the dataset to resource dict ready to save to CKAN. """ # http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.resource_create schema_csv = None for f in bundle.dataset.files: if f.path.endswith('schema.csv'): contents = f.u...
[ "def", "_convert_schema", "(", "bundle", ")", ":", "# http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.resource_create", "schema_csv", "=", "None", "for", "f", "in", "bundle", ".", "dataset", ".", "files", ":", "if", "f", ".", "path", ".", "endswith", "(...
33.04
0.002353
def unsubscribe_list(self, list_id): """ Unsubscribe to a list :param list_id: list ID number :return: :class:`~responsebot.models.List` object """ return List(tweepy_list_to_json(self._client.unsubscribe_list(list_id=list_id)))
[ "def", "unsubscribe_list", "(", "self", ",", "list_id", ")", ":", "return", "List", "(", "tweepy_list_to_json", "(", "self", ".", "_client", ".", "unsubscribe_list", "(", "list_id", "=", "list_id", ")", ")", ")" ]
33.75
0.01083
def mslike(pop, **kwargs): """ Function to establish default parameters for a single-locus simulation for standard pop-gen modeling scenarios. :params pop: An instance of :class:`fwdpy11.DiploidPopulation` :params kwargs: Keyword arguments. """ import fwdpy11 if isinstance(pop, fwdp...
[ "def", "mslike", "(", "pop", ",", "*", "*", "kwargs", ")", ":", "import", "fwdpy11", "if", "isinstance", "(", "pop", ",", "fwdpy11", ".", "DiploidPopulation", ")", "is", "False", ":", "raise", "ValueError", "(", "\"incorrect pop type: \"", "+", "str", "(",...
35.97619
0.000644
def match_host(host, pattern): ''' Match a host string against a pattern Args: host (str) A hostname to compare to the given pattern pattern (str) A string representing a hostname pattern, possibly including wildcards for ip address octets or ports. Thi...
[ "def", "match_host", "(", "host", ",", "pattern", ")", ":", "if", "':'", "in", "host", ":", "host", ",", "host_port", "=", "host", ".", "rsplit", "(", "':'", ",", "1", ")", "else", ":", "host_port", "=", "None", "if", "':'", "in", "pattern", ":", ...
25.571429
0.000489
def maybe_convert_to_index_date_type(index, date): """Convert a datetime-like object to the index's date type. Datetime indexing in xarray can be done using either a pandas DatetimeIndex or a CFTimeIndex. Both support partial-datetime string indexing regardless of the calendar type of the underlying d...
[ "def", "maybe_convert_to_index_date_type", "(", "index", ",", "date", ")", ":", "if", "isinstance", "(", "date", ",", "str", ")", ":", "return", "date", "if", "isinstance", "(", "index", ",", "pd", ".", "DatetimeIndex", ")", ":", "if", "isinstance", "(", ...
36.148936
0.000573
def measure(self, geometry): """Measure the length or the area of a geometry. :param geometry: The geometry. :type geometry: QgsGeometry :return: The geometric size in the expected exposure unit. :rtype: float """ message = 'Size with NaN value : geometry valid=...
[ "def", "measure", "(", "self", ",", "geometry", ")", ":", "message", "=", "'Size with NaN value : geometry valid={valid}, WKT={wkt}'", "feature_size", "=", "0", "if", "geometry", ".", "isMultipart", "(", ")", ":", "# Be careful, the size calculator is not working well on a"...
39.73913
0.001068
def parse_path(path): """ Get database name and database schema from path. :param path: "/"-delimited path, parsed as "/<database name>/<database schema>" :return: tuple with (database or None, schema or None) """ if path is None: raise ValueError("path must be a string") part...
[ "def", "parse_path", "(", "path", ")", ":", "if", "path", "is", "None", ":", "raise", "ValueError", "(", "\"path must be a string\"", ")", "parts", "=", "path", ".", "strip", "(", "\"/\"", ")", ".", "split", "(", "\"/\"", ")", "database", "=", "unquote_p...
28
0.002033
def getCocktailSum(e0, e1, eCocktail, uCocktail): """get the cocktail sum for a given data bin range""" # get mask and according indices mask = (eCocktail >= e0) & (eCocktail <= e1) # data bin range wider than single cocktail bin if np.any(mask): idx = getMaskIndices(mask) # determine coinciding flags...
[ "def", "getCocktailSum", "(", "e0", ",", "e1", ",", "eCocktail", ",", "uCocktail", ")", ":", "# get mask and according indices", "mask", "=", "(", "eCocktail", ">=", "e0", ")", "&", "(", "eCocktail", "<=", "e1", ")", "# data bin range wider than single cocktail bi...
43.666667
0.011946
def compute_actor_handle_id(actor_handle_id, num_forks): """Deterministically compute an actor handle ID. A new actor handle ID is generated when it is forked from another actor handle. The new handle ID is computed as hash(old_handle_id || num_forks). Args: actor_handle_id (common.ObjectID): ...
[ "def", "compute_actor_handle_id", "(", "actor_handle_id", ",", "num_forks", ")", ":", "assert", "isinstance", "(", "actor_handle_id", ",", "ActorHandleID", ")", "handle_id_hash", "=", "hashlib", ".", "sha1", "(", ")", "handle_id_hash", ".", "update", "(", "actor_h...
38.8
0.001258
def from_dict(cls: typing.Type[T], dikt) -> T: """Returns the dict as a model""" return util.deserialize_model(dikt, cls)
[ "def", "from_dict", "(", "cls", ":", "typing", ".", "Type", "[", "T", "]", ",", "dikt", ")", "->", "T", ":", "return", "util", ".", "deserialize_model", "(", "dikt", ",", "cls", ")" ]
45
0.014599
def set_translation(lang): """Set the translation used by (some) pywws modules. This sets the translation object ``pywws.localisation.translation`` to use a particular language. The ``lang`` parameter can be any string of the form ``en``, ``en_GB`` or ``en_GB.UTF-8``. Anything after a ``.`` charac...
[ "def", "set_translation", "(", "lang", ")", ":", "global", "translation", "# make list of possible languages, in order of preference", "langs", "=", "list", "(", ")", "if", "lang", ":", "if", "'.'", "in", "lang", ":", "lang", "=", "lang", ".", "split", "(", "'...
33.025641
0.000754
def get_operation_type(self, operation_name): # type: (Optional[str]) -> Optional[str] """ Returns the operation type ('query', 'mutation', 'subscription' or None) for the given operation_name. If no operation_name is provided (and only one operation exists) it will return the ...
[ "def", "get_operation_type", "(", "self", ",", "operation_name", ")", ":", "# type: (Optional[str]) -> Optional[str]", "operations_map", "=", "self", ".", "operations_map", "if", "not", "operation_name", "and", "len", "(", "operations_map", ")", "==", "1", ":", "ret...
47.5
0.008606
def GetIPAddresses(self): """Return a list of IP addresses.""" results = [] for address in self.addresses: human_readable_address = address.human_readable_address if human_readable_address is not None: results.append(human_readable_address) return results
[ "def", "GetIPAddresses", "(", "self", ")", ":", "results", "=", "[", "]", "for", "address", "in", "self", ".", "addresses", ":", "human_readable_address", "=", "address", ".", "human_readable_address", "if", "human_readable_address", "is", "not", "None", ":", ...
31.555556
0.010274
def getColors_Triad(hue=None, sat = 1, val = 1, spread = 60): """ Create a palette with one main color and two opposite color evenly spread apart from the main one. :param hue: A 0-1 float with the starting hue value. :param sat: A 0-1 float with the palette saturation. :param val: A 0-1 float with the palette v...
[ "def", "getColors_Triad", "(", "hue", "=", "None", ",", "sat", "=", "1", ",", "val", "=", "1", ",", "spread", "=", "60", ")", ":", "palette", "=", "list", "(", ")", "if", "hue", "==", "None", ":", "leadHue", "=", "randFloat", "(", "0", ",", "1"...
39.894737
0.051546
def save_license(license_code): """ Grab license, save to LICENSE/LICENSE.txt file """ desc = _get_license_description(license_code) fname = "LICENSE" if sys.platform == "win32": fname += ".txt" # Windows and file exts with open(os.path.join(os.getcwd(), fname), "w") as afile: afile.write(desc)
[ "def", "save_license", "(", "license_code", ")", ":", "desc", "=", "_get_license_description", "(", "license_code", ")", "fname", "=", "\"LICENSE\"", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "fname", "+=", "\".txt\"", "# Windows and file exts", "with"...
38.375
0.019108
def meta(self, meta): '''Extract model metadata for lua script stdnet/lib/lua/odm.lua''' data = meta.as_dict() data['namespace'] = self.basekey(meta) return data
[ "def", "meta", "(", "self", ",", "meta", ")", ":", "data", "=", "meta", ".", "as_dict", "(", ")", "data", "[", "'namespace'", "]", "=", "self", ".", "basekey", "(", "meta", ")", "return", "data" ]
38.6
0.010152
def warnify(self, message, duration=3000, notification_clicked_slot=None, **kwargs): """ Displays an Application notification warning. :param message: Notification message. :type message: unicode :param duration: Notification display duration. :type duration: int ...
[ "def", "warnify", "(", "self", ",", "message", ",", "duration", "=", "3000", ",", "notification_clicked_slot", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "notify", "(", "message", ",", "duration", ",", "notification_clicked_slot",...
39.5
0.009269
def astype(self, dtype, copy=True): """ Cast to a NumPy array or IntegerArray with 'dtype'. Parameters ---------- dtype : str or dtype Typecode or data-type to which the array is cast. copy : bool, default True Whether to copy the data, even if no...
[ "def", "astype", "(", "self", ",", "dtype", ",", "copy", "=", "True", ")", ":", "# if we are astyping to an existing IntegerDtype we can fastpath", "if", "isinstance", "(", "dtype", ",", "_IntegerDtype", ")", ":", "result", "=", "self", ".", "_data", ".", "astyp...
32.545455
0.001808
def Nu_cylinder_Perkins_Leppert_1964(Re, Pr, mu=None, muw=None): r'''Calculates Nusselt number for crossflow across a single tube as shown in [1]_ at a specified `Re` and `Pr`, both evaluated at the free stream temperature. Recommends a viscosity exponent correction of 0.25, which is applied only if pro...
[ "def", "Nu_cylinder_Perkins_Leppert_1964", "(", "Re", ",", "Pr", ",", "mu", "=", "None", ",", "muw", "=", "None", ")", ":", "Nu", "=", "(", "0.31", "*", "Re", "**", "0.5", "+", "0.11", "*", "Re", "**", "0.67", ")", "*", "Pr", "**", "0.4", "if", ...
35.692308
0.000524
def gather_readme(self): """ Return the readme file. """ if not os.path.exists(self.paths["readme"]): return "" return utils.file_to_string(self.paths["readme"])
[ "def", "gather_readme", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "paths", "[", "\"readme\"", "]", ")", ":", "return", "\"\"", "return", "utils", ".", "file_to_string", "(", "self", ".", "paths", "[", "\"...
25.875
0.009346
def register_hook(self, event, hook): """Properly register a hook.""" if event not in self.hooks: raise ValueError('Unsupported event specified, with event name "%s"' % (event)) if isinstance(hook, Callable): self.hooks[event].append(hook) elif hasattr(hook, '__...
[ "def", "register_hook", "(", "self", ",", "event", ",", "hook", ")", ":", "if", "event", "not", "in", "self", ".", "hooks", ":", "raise", "ValueError", "(", "'Unsupported event specified, with event name \"%s\"'", "%", "(", "event", ")", ")", "if", "isinstance...
40.1
0.009756
def verify_space_available(self, search_pattern=r"(\d+) \w+ free"): """Verify sufficient space is available on destination file system (return boolean).""" if self.direction == "put": space_avail = self.remote_space_available(search_pattern=search_pattern) elif self.direction == "get...
[ "def", "verify_space_available", "(", "self", ",", "search_pattern", "=", "r\"(\\d+) \\w+ free\"", ")", ":", "if", "self", ".", "direction", "==", "\"put\"", ":", "space_avail", "=", "self", ".", "remote_space_available", "(", "search_pattern", "=", "search_pattern"...
50.555556
0.008639
def call_api(self, method_type, method_name, valid_status_codes, resource, data, uid, **kwargs): """ Make HTTP calls. Args: method_type: The HTTP method method_name: The name of the python method making the HTTP call valid_st...
[ "def", "call_api", "(", "self", ",", "method_type", ",", "method_name", ",", "valid_status_codes", ",", "resource", ",", "data", ",", "uid", ",", "*", "*", "kwargs", ")", ":", "url", "=", "resource", ".", "get_resource_url", "(", "resource", ",", "base_url...
38.255814
0.002371
def attr_fill_null(args): """ Assign the null sentinel value for all entities which do not have a value for the given attributes. see gs://broad-institute-gdac/GDAC_FC_NULL for more details """ NULL_SENTINEL = "gs://broad-institute-gdac/GDAC_FC_NULL" attrs = args.attributes if not attr...
[ "def", "attr_fill_null", "(", "args", ")", ":", "NULL_SENTINEL", "=", "\"gs://broad-institute-gdac/GDAC_FC_NULL\"", "attrs", "=", "args", ".", "attributes", "if", "not", "attrs", ":", "print", "(", "\"Error: provide at least one attribute to set\"", ")", "return", "1", ...
39.274336
0.000879
def gen_reaction(args, resource, depletable=0): """ Returns a line of text to add to an environment file, initializing a reaction that uses the resource specified in the first argument to perform the associated task (resource names are expected to be of the form "resTASK#" where "TASK" corresponds ...
[ "def", "gen_reaction", "(", "args", ",", "resource", ",", "depletable", "=", "0", ")", ":", "task", "=", "resource", ".", "lower", "(", ")", "if", "task", "[", ":", "3", "]", "==", "\"res\"", ":", "task", "=", "task", "[", "3", ":", "]", "while",...
48.125
0.000849
def template_gen(method, lowcut, highcut, samp_rate, filt_order, length, prepick, swin, process_len=86400, all_horiz=False, delayed=True, plot=False, debug=0, return_event=False, min_snr=None, parallel=False, num_cores=False, save_progress=False, **kwa...
[ "def", "template_gen", "(", "method", ",", "lowcut", ",", "highcut", ",", "samp_rate", ",", "filt_order", ",", "length", ",", "prepick", ",", "swin", ",", "process_len", "=", "86400", ",", "all_horiz", "=", "False", ",", "delayed", "=", "True", ",", "plo...
44.110368
0.000074
def new_tag(self, name: str, category: str=None) -> models.Tag: """Create a new tag.""" new_tag = self.Tag(name=name, category=category) return new_tag
[ "def", "new_tag", "(", "self", ",", "name", ":", "str", ",", "category", ":", "str", "=", "None", ")", "->", "models", ".", "Tag", ":", "new_tag", "=", "self", ".", "Tag", "(", "name", "=", "name", ",", "category", "=", "category", ")", "return", ...
43
0.022857
def get_solarposition(self, times, pressure=None, temperature=12, **kwargs): """ Uses the :py:func:`solarposition.get_solarposition` function to calculate the solar zenith, azimuth, etc. at this location. Parameters ---------- times : DatetimeIn...
[ "def", "get_solarposition", "(", "self", ",", "times", ",", "pressure", "=", "None", ",", "temperature", "=", "12", ",", "*", "*", "kwargs", ")", ":", "if", "pressure", "is", "None", ":", "pressure", "=", "atmosphere", ".", "alt2pres", "(", "self", "."...
40.96875
0.002235
def tool(self): """The tool that was in use during this event. If the caller keeps a reference to a tool, the tool object will compare equal to the previously obtained tool object. Note: Physical tool tracking requires hardware support. If unavailable, libinput creates one tool per type per tablet. See ...
[ "def", "tool", "(", "self", ")", ":", "htablettool", "=", "self", ".", "_libinput", ".", "libinput_event_tablet_tool_get_tool", "(", "self", ".", "_handle", ")", "return", "TabletTool", "(", "htablettool", ",", "self", ".", "_libinput", ")" ]
33.470588
0.025641
def render_value(self, value, **options): """Render value""" renderer = self.renderers.get(type(value), lambda value, **options: value) return renderer(value, **options)
[ "def", "render_value", "(", "self", ",", "value", ",", "*", "*", "options", ")", ":", "renderer", "=", "self", ".", "renderers", ".", "get", "(", "type", "(", "value", ")", ",", "lambda", "value", ",", "*", "*", "options", ":", "value", ")", "retur...
47.5
0.015544
def rm(path, recursive=False): """Delete a specified file or directory. This function does not recursively delete by default. >>> if rm('/tmp/build', recursive=True): ... print('OK') OK """ try: if recursive: if os.path.isfile(path): os.remove(p...
[ "def", "rm", "(", "path", ",", "recursive", "=", "False", ")", ":", "try", ":", "if", "recursive", ":", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "os", ".", "remove", "(", "path", ")", "else", ":", "shutil", ".", "rmtree", ...
26.913043
0.00156
def _ldtpize_accessible(self, acc): """ Get LDTP format accessibile name @param acc: Accessible handle @type acc: object @return: object type, stripped object name (associated / direct), associated label @rtype: tuple """ actual_r...
[ "def", "_ldtpize_accessible", "(", "self", ",", "acc", ")", ":", "actual_role", "=", "self", ".", "_get_role", "(", "acc", ")", "label", "=", "self", ".", "_get_title", "(", "acc", ")", "if", "re", ".", "match", "(", "\"AXWindow\"", ",", "actual_role", ...
37.310345
0.001802
def make_parser(func_sig, description, epilog, add_nos): ''' Given the signature of a function, create an ArgumentParser ''' parser = ArgumentParser(description=description, epilog=epilog) used_char_args = {'h'} # Arange the params so that single-character arguments are first. This # esnur...
[ "def", "make_parser", "(", "func_sig", ",", "description", ",", "epilog", ",", "add_nos", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "description", ",", "epilog", "=", "epilog", ")", "used_char_args", "=", "{", "'h'", "}", "# Arange ...
33.842105
0.001513
def get_grade_systems_by_search(self, grade_system_query, grade_system_search): """Pass through to provider GradeSystemSearchSession.get_grade_systems_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self....
[ "def", "get_grade_systems_by_search", "(", "self", ",", "grade_system_query", ",", "grade_system_search", ")", ":", "# Implemented from azosid template for -", "# osid.resource.ResourceSearchSession.get_resources_by_search_template", "if", "not", "self", ".", "_can", "(", "'searc...
67.571429
0.008351
def _misalign_split(self,alns): """Requires alignment strings have been set so for each exon we have query, target and query_quality _has_quality will specify whether or not the quality is meaningful """ total = [] z = 0 for x in alns: z += 1 exon_num = z if self._ali...
[ "def", "_misalign_split", "(", "self", ",", "alns", ")", ":", "total", "=", "[", "]", "z", "=", "0", "for", "x", "in", "alns", ":", "z", "+=", "1", "exon_num", "=", "z", "if", "self", ".", "_alignment", ".", "strand", "==", "'-'", ":", "exon_num"...
39.234043
0.037566
def all(cls, sort=None, limit=None): """Returns all objects of this type. Alias for where() (without filter arguments). See `where` for documentation on the `sort` and `limit` parameters. """ return cls.where(sort=sort, limit=limit)
[ "def", "all", "(", "cls", ",", "sort", "=", "None", ",", "limit", "=", "None", ")", ":", "return", "cls", ".", "where", "(", "sort", "=", "sort", ",", "limit", "=", "limit", ")" ]
43.333333
0.011321
def mass_integral(self, x, axis_ratio): """Routine to integrate an elliptical light profiles - set axis ratio to 1 to compute the luminosity within a \ circle""" r = x * axis_ratio return 2 * np.pi * r * self.convergence_func(x)
[ "def", "mass_integral", "(", "self", ",", "x", ",", "axis_ratio", ")", ":", "r", "=", "x", "*", "axis_ratio", "return", "2", "*", "np", ".", "pi", "*", "r", "*", "self", ".", "convergence_func", "(", "x", ")" ]
51.2
0.011538
def _fix(node): """Fix the naive construction of the adjont. See `fixes.py` for details. This function also returns the result of reaching definitions analysis so that `split` mode can use this to carry over the state from primal to adjoint. Args: node: A module with the primal and adjoint function d...
[ "def", "_fix", "(", "node", ")", ":", "# Do reaching definitions analysis on primal and adjoint", "pri_cfg", "=", "cfg", ".", "CFG", ".", "build_cfg", "(", "node", ".", "body", "[", "0", "]", ")", "defined", "=", "cfg", ".", "Defined", "(", ")", "defined", ...
35
0.01283