text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def matchToString(aaMatch, read1, read2, indent='', offsets=None): """ Format amino acid sequence match as a string. @param aaMatch: A C{dict} returned by C{compareAaReads}. @param read1: A C{Read} instance or an instance of one of its subclasses. @param read2: A C{Read} instance or an instance of ...
[ "def", "matchToString", "(", "aaMatch", ",", "read1", ",", "read2", ",", "indent", "=", "''", ",", "offsets", "=", "None", ")", ":", "match", "=", "aaMatch", "[", "'match'", "]", "matchCount", "=", "match", "[", "'matchCount'", "]", "gapMismatchCount", "...
42.309091
0.00042
def numeric(_, n): """ NBASE = 1000 ndigits = total number of base-NBASE digits weight = base-NBASE weight of first digit sign = 0x0000 if positive, 0x4000 if negative, 0xC000 if nan dscale = decimal digits after decimal place """ try: nt = n.as_tuple() except AttributeError:...
[ "def", "numeric", "(", "_", ",", "n", ")", ":", "try", ":", "nt", "=", "n", ".", "as_tuple", "(", ")", "except", "AttributeError", ":", "raise", "TypeError", "(", "'numeric field requires Decimal value (got %r)'", "%", "n", ")", "digits", "=", "[", "]", ...
31.166667
0.000864
def partition_varied_cfg_list(cfg_list, default_cfg=None, recursive=False): r""" Separates varied from non-varied parameters in a list of configs TODO: partition nested configs CommandLine: python -m utool.util_gridsearch --exec-partition_varied_cfg_list:0 Example: >>> # ENABLE_DO...
[ "def", "partition_varied_cfg_list", "(", "cfg_list", ",", "default_cfg", "=", "None", ",", "recursive", "=", "False", ")", ":", "import", "utool", "as", "ut", "if", "default_cfg", "is", "None", ":", "nonvaried_cfg", "=", "reduce", "(", "ut", ".", "dict_inter...
49.309091
0.001446
def make_dbsource(**kwargs): """Returns a mapnik PostGIS or SQLite Datasource.""" if 'spatialite' in connection.settings_dict.get('ENGINE'): kwargs.setdefault('file', connection.settings_dict['NAME']) return mapnik.SQLite(wkb_format='spatialite', **kwargs) names = (('dbname', 'NAME'), ('user...
[ "def", "make_dbsource", "(", "*", "*", "kwargs", ")", ":", "if", "'spatialite'", "in", "connection", ".", "settings_dict", ".", "get", "(", "'ENGINE'", ")", ":", "kwargs", ".", "setdefault", "(", "'file'", ",", "connection", ".", "settings_dict", "[", "'NA...
47.166667
0.001733
def get_bibtex(arxiv_id): """ Get a BibTeX entry for a given arXiv ID. .. note:: Using awesome https://pypi.python.org/pypi/arxiv2bib/ module. :param arxiv_id: The canonical arXiv id to get BibTeX from. :returns: A BibTeX string or ``None``. >>> get_bibtex('1506.06690') "@article...
[ "def", "get_bibtex", "(", "arxiv_id", ")", ":", "# Fetch bibtex using arxiv2bib module", "try", ":", "bibtex", "=", "arxiv2bib", ".", "arxiv2bib", "(", "[", "arxiv_id", "]", ")", "except", "HTTPError", ":", "bibtex", "=", "[", "]", "for", "bib", "in", "bibte...
106.774194
0.000898
def set_collection_name(self, value): """Set the name of the collection, return old value""" old = self.collection self.collection = str(value) return old
[ "def", "set_collection_name", "(", "self", ",", "value", ")", ":", "old", "=", "self", ".", "collection", "self", ".", "collection", "=", "str", "(", "value", ")", "return", "old" ]
36.4
0.010753
def __getBio(self, web): """Scrap the bio from a GitHub profile. :param web: parsed web. :type web: BeautifulSoup node. """ bio = web.find_all("div", {"class": "user-profile-bio"}) if bio: try: bio = bio[0].text if bio and Git...
[ "def", "__getBio", "(", "self", ",", "web", ")", ":", "bio", "=", "web", ".", "find_all", "(", "\"div\"", ",", "{", "\"class\"", ":", "\"user-profile-bio\"", "}", ")", "if", "bio", ":", "try", ":", "bio", "=", "bio", "[", "0", "]", ".", "text", "...
37.416667
0.002172
def corners(bounds): """ Given a pair of axis aligned bounds, return all 8 corners of the bounding box. Parameters ---------- bounds : (2,3) or (2,2) float Axis aligned bounds Returns ---------- corners : (8,3) float Corner vertices of the cube """ bounds = np....
[ "def", "corners", "(", "bounds", ")", ":", "bounds", "=", "np", ".", "asanyarray", "(", "bounds", ",", "dtype", "=", "np", ".", "float64", ")", "if", "util", ".", "is_shape", "(", "bounds", ",", "(", "2", ",", "2", ")", ")", ":", "bounds", "=", ...
29.457143
0.000939
def value(self): """ Current value of the Node """ if self.root.stale: self.root.update(self.root.now, None) return self._value
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "root", ".", "stale", ":", "self", ".", "root", ".", "update", "(", "self", ".", "root", ".", "now", ",", "None", ")", "return", "self", ".", "_value" ]
24.714286
0.011173
def amplifier_gain(self, channels=None): """ Get the amplifier gain used for the specified channel(s). The amplifier gain for channel "n" is extracted from the $PnG parameter, if available. Parameters ---------- channels : int, str, list of int, list of str ...
[ "def", "amplifier_gain", "(", "self", ",", "channels", "=", "None", ")", ":", "# Check default", "if", "channels", "is", "None", ":", "channels", "=", "self", ".", "_channels", "# Get numerical indices of channels", "channels", "=", "self", ".", "_name_to_index", ...
33.771429
0.001645
def do_kill(self, arg): """ [~process] kill - kill a process [~thread] kill - kill a thread kill - kill the current process kill * - kill all debugged processes kill <processes and/or threads...> - kill the given processes and threads """ if arg: ...
[ "def", "do_kill", "(", "self", ",", "arg", ")", ":", "if", "arg", ":", "if", "arg", "==", "'*'", ":", "target_pids", "=", "self", ".", "debug", ".", "get_debugee_pids", "(", ")", "target_tids", "=", "list", "(", ")", "else", ":", "target_pids", "=", ...
43.969697
0.002359
def comparator(self, x, y): ''' simple comparator method ''' indX=0 indY=0 for i in range(len(self.stable_names)): if self.stable_names[i] == x[0].split('-')[0]: indX=i if self.stable_names[i] == y[0].split('-')[0]: ...
[ "def", "comparator", "(", "self", ",", "x", ",", "y", ")", ":", "indX", "=", "0", "indY", "=", "0", "for", "i", "in", "range", "(", "len", "(", "self", ".", "stable_names", ")", ")", ":", "if", "self", ".", "stable_names", "[", "i", "]", "==", ...
22.05
0.019565
def _refresh(self): """Refreshes the cursor with more data from Mongo. Returns the length of self.__data after refresh. Will exit early if self.__data is already non-empty. Raises OperationFailure when the cursor cannot be refreshed due to an error on the query. """ if l...
[ "def", "_refresh", "(", "self", ")", ":", "if", "len", "(", "self", ".", "__data", ")", "or", "self", ".", "__killed", ":", "return", "len", "(", "self", ".", "__data", ")", "if", "not", "self", ".", "__session", ":", "self", ".", "__session", "=",...
46.964912
0.001098
def grad(self, X, lenscale=None): r""" Get the gradients of this basis w.r.t.\ the length scales. Parameters ---------- X: ndarray (N, d) array of observations where N is the number of samples, and d is the dimensionality of X. lenscale: scalar or...
[ "def", "grad", "(", "self", ",", "X", ",", "lenscale", "=", "None", ")", ":", "N", ",", "D", "=", "X", ".", "shape", "lenscale", "=", "self", ".", "_check_dim", "(", "D", ",", "lenscale", ")", "[", ":", ",", "np", ".", "newaxis", "]", "WX", "...
35.314286
0.001575
def surround_previous_word(input_str): ''' Surround last word in string with parentheses. If last non-whitespace character is delimiter, do nothing ''' start = None end = None for i, char in enumerate(reversed(input_str)): if start is None: if char in '{}()[]<>?|': ...
[ "def", "surround_previous_word", "(", "input_str", ")", ":", "start", "=", "None", "end", "=", "None", "for", "i", ",", "char", "in", "enumerate", "(", "reversed", "(", "input_str", ")", ")", ":", "if", "start", "is", "None", ":", "if", "char", "in", ...
27.242424
0.002148
def save(self, event): """Saves a file that is specified in event.attr Parameters ---------- event.attr: Dict \tkey filepath contains file path of file to be saved """ filepath = event.attr["filepath"] try: filetype = event.attr["filetype"]...
[ "def", "save", "(", "self", ",", "event", ")", ":", "filepath", "=", "event", ".", "attr", "[", "\"filepath\"", "]", "try", ":", "filetype", "=", "event", ".", "attr", "[", "\"filetype\"", "]", "except", "KeyError", ":", "filetype", "=", "\"pys\"", "# ...
28.385965
0.001195
def updateStateText(self): '''Updates the mode and colours red or green depending on arm state.''' self.modeText.set_position((self.leftPos+(self.vertSize/10.0),0.97)) self.modeText.set_text(self.mode) self.modeText.set_size(1.5*self.fontSize) if self.armed: self.mode...
[ "def", "updateStateText", "(", "self", ")", ":", "self", ".", "modeText", ".", "set_position", "(", "(", "self", ".", "leftPos", "+", "(", "self", ".", "vertSize", "/", "10.0", ")", ",", "0.97", ")", ")", "self", ".", "modeText", ".", "set_text", "("...
54.352941
0.010638
def bulk_lookup_rdap(addresses=None, inc_raw=False, retry_count=3, depth=0, excluded_entities=None, rate_limit_timeout=60, socket_timeout=10, asn_timeout=240, proxy_openers=None): """ The function for bulk retrieving and parsing whois information for a list of IP ad...
[ "def", "bulk_lookup_rdap", "(", "addresses", "=", "None", ",", "inc_raw", "=", "False", ",", "retry_count", "=", "3", ",", "depth", "=", "0", ",", "excluded_entities", "=", "None", ",", "rate_limit_timeout", "=", "60", ",", "socket_timeout", "=", "10", ","...
39.431884
0.000072
def execute(self, eopatch): """ Execute method takes EOPatch and changes the specified feature """ feature_type, feature_name = next(self.feature(eopatch)) eopatch[feature_type][feature_name] = self.process(eopatch[feature_type][feature_name]) return eopatch
[ "def", "execute", "(", "self", ",", "eopatch", ")", ":", "feature_type", ",", "feature_name", "=", "next", "(", "self", ".", "feature", "(", "eopatch", ")", ")", "eopatch", "[", "feature_type", "]", "[", "feature_name", "]", "=", "self", ".", "process", ...
37.5
0.009772
def create_actor_tri(pts, tris, color, **kwargs): """ Creates a VTK actor for rendering triangulated surface plots. :param pts: points :type pts: vtkFloatArray :param tris: list of triangle indices :type tris: ndarray :param color: actor color :type color: list :return: a VTK actor ...
[ "def", "create_actor_tri", "(", "pts", ",", "tris", ",", "color", ",", "*", "*", "kwargs", ")", ":", "# Keyword arguments", "array_name", "=", "kwargs", ".", "get", "(", "'name'", ",", "\"\"", ")", "array_index", "=", "kwargs", ".", "get", "(", "'index'"...
26.978261
0.000778
def hydrate(self, iterator): """ Pass in an iterator of tweet ids and get back an iterator for the decoded JSON for each corresponding tweet. """ ids = [] url = "https://api.twitter.com/1.1/statuses/lookup.json" # lookup 100 tweets at a time for tweet_id ...
[ "def", "hydrate", "(", "self", ",", "iterator", ")", ":", "ids", "=", "[", "]", "url", "=", "\"https://api.twitter.com/1.1/statuses/lookup.json\"", "# lookup 100 tweets at a time", "for", "tweet_id", "in", "iterator", ":", "tweet_id", "=", "str", "(", "tweet_id", ...
34.676471
0.00165
def getFiles(self,args): """ This is the main method of the class. Given the arguments, the corresponding list of all files (or directories if the -d option is used) are returned. """ fileList = [] if args.recursive: # The list is created by going through the f...
[ "def", "getFiles", "(", "self", ",", "args", ")", ":", "fileList", "=", "[", "]", "if", "args", ".", "recursive", ":", "# The list is created by going through the folder(s) recursively:", "fileList", "=", "self", ".", "createListRecursively", "(", "args", ")", "el...
58.269231
0.01039
def update(self, byts): ''' Update all the hashes in the set with the given bytes. ''' self.size += len(byts) [h[1].update(byts) for h in self.hashes]
[ "def", "update", "(", "self", ",", "byts", ")", ":", "self", ".", "size", "+=", "len", "(", "byts", ")", "[", "h", "[", "1", "]", ".", "update", "(", "byts", ")", "for", "h", "in", "self", ".", "hashes", "]" ]
30.833333
0.010526
def alignment(self): """ The alignment of the type in bytes. """ if self._arch is None: return NotImplemented return self.size // self._arch.byte_width
[ "def", "alignment", "(", "self", ")", ":", "if", "self", ".", "_arch", "is", "None", ":", "return", "NotImplemented", "return", "self", ".", "size", "//", "self", ".", "_arch", ".", "byte_width" ]
28.142857
0.009852
def fetch_exemplars(keyword, outfile, n=50): """ Fetch top lists matching this keyword, then return Twitter screen names along with the number of different lists on which each appers.. """ list_urls = fetch_lists(keyword, n) print('found %d lists for %s' % (len(list_urls), keyword)) counts = Counter...
[ "def", "fetch_exemplars", "(", "keyword", ",", "outfile", ",", "n", "=", "50", ")", ":", "list_urls", "=", "fetch_lists", "(", "keyword", ",", "n", ")", "print", "(", "'found %d lists for %s'", "%", "(", "len", "(", "list_urls", ")", ",", "keyword", ")",...
42.642857
0.001639
def get_new(mserver_url, token, board): '''get node sn and key''' thread = termui.waiting_echo("Getting message from Server...") thread.daemon = True thread.start() try: params = {"name":"node000", "board":board, "access_token":token} r = requests.post("%s%s" %(mserver_url, nodes_cre...
[ "def", "get_new", "(", "mserver_url", ",", "token", ",", "board", ")", ":", "thread", "=", "termui", ".", "waiting_echo", "(", "\"Getting message from Server...\"", ")", "thread", ".", "daemon", "=", "True", "thread", ".", "start", "(", ")", "try", ":", "p...
31.517241
0.009554
async def sendPhoto(self, chat_id, photo, caption=None, parse_mode=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://core.telegram.org/bot...
[ "async", "def", "sendPhoto", "(", "self", ",", "chat_id", ",", "photo", ",", "caption", "=", "None", ",", "parse_mode", "=", "None", ",", "disable_notification", "=", "None", ",", "reply_to_message_id", "=", "None", ",", "reply_markup", "=", "None", ")", "...
46.684211
0.00884
def predict(self, u=None, B=None, F=None, Q=None): """ Predict next state (prior) using the Kalman filter state propagation equations. Parameters ---------- u : np.array Optional control vector. If not `None`, it is multiplied by B to create the ...
[ "def", "predict", "(", "self", ",", "u", "=", "None", ",", "B", "=", "None", ",", "F", "=", "None", ",", "Q", "=", "None", ")", ":", "if", "B", "is", "None", ":", "B", "=", "self", ".", "B", "if", "F", "is", "None", ":", "F", "=", "self",...
29.217391
0.00144
def vterm(Pot,l,deg=True): """ NAME: vterm PURPOSE: calculate the terminal velocity at l in this potential INPUT: Pot - Potential instance l - Galactic longitude [deg/rad; can be Quantity) deg= if True (default), l in de...
[ "def", "vterm", "(", "Pot", ",", "l", ",", "deg", "=", "True", ")", ":", "Pot", "=", "flatten", "(", "Pot", ")", "if", "_APY_LOADED", "and", "isinstance", "(", "l", ",", "units", ".", "Quantity", ")", ":", "l", "=", "l", ".", "to", "(", "units"...
19.578947
0.035851
def _time_to_gps(time): """Convert a `Time` into `LIGOTimeGPS`. This method uses `datetime.datetime` underneath, which restricts to microsecond precision by design. This should probably be fixed... Parameters ---------- time : `~astropy.time.Time` formatted `Time` object to convert ...
[ "def", "_time_to_gps", "(", "time", ")", ":", "time", "=", "time", ".", "utc", "date", "=", "time", ".", "datetime", "micro", "=", "date", ".", "microsecond", "if", "isinstance", "(", "date", ",", "datetime", ".", "datetime", ")", "else", "0", "return"...
28.85
0.001678
def OnDependencies(self, event): """Display dependency dialog""" dlg = DependencyDialog(self.main_window) dlg.ShowModal() dlg.Destroy()
[ "def", "OnDependencies", "(", "self", ",", "event", ")", ":", "dlg", "=", "DependencyDialog", "(", "self", ".", "main_window", ")", "dlg", ".", "ShowModal", "(", ")", "dlg", ".", "Destroy", "(", ")" ]
27.166667
0.011905
def listAcquisitionEras(self, acq=''): """ Returns all acquistion eras in dbs """ try: acq = str(acq) except: dbsExceptionHandler('dbsException-invalid-input', 'acquistion_era_name given is not valid : %s' %acq) conn = self.dbi.connection() ...
[ "def", "listAcquisitionEras", "(", "self", ",", "acq", "=", "''", ")", ":", "try", ":", "acq", "=", "str", "(", "acq", ")", "except", ":", "dbsExceptionHandler", "(", "'dbsException-invalid-input'", ",", "'acquistion_era_name given is not valid : %s'", "%", "acq",...
31.428571
0.015453
def _rows(self, spec): """Parse a collection of rows.""" rows = self.new_row_collection() for row in spec: rows.append(self._row(row)) return rows
[ "def", "_rows", "(", "self", ",", "spec", ")", ":", "rows", "=", "self", ".", "new_row_collection", "(", ")", "for", "row", "in", "spec", ":", "rows", ".", "append", "(", "self", ".", "_row", "(", "row", ")", ")", "return", "rows" ]
30.833333
0.010526
def contextMenuEvent(self, event): """ Handles the default menu options for the orb widget. :param event | <QContextMenuEvent> """ if self.contextMenuPolicy() == Qt.DefaultContextMenu: self.showMenu(event.pos()) else: super(X...
[ "def", "contextMenuEvent", "(", "self", ",", "event", ")", ":", "if", "self", ".", "contextMenuPolicy", "(", ")", "==", "Qt", ".", "DefaultContextMenu", ":", "self", ".", "showMenu", "(", "event", ".", "pos", "(", ")", ")", "else", ":", "super", "(", ...
35.5
0.008242
def lyricscom(song): """ Returns the lyrics found in lyrics.com for the specified mp3 file or an empty string if not found. """ artist = song.artist.lower() artist = normalize(artist, ' ', '+') title = song.title url = 'https://www.lyrics.com/artist/{}'.format(artist) soup = get_url...
[ "def", "lyricscom", "(", "song", ")", ":", "artist", "=", "song", ".", "artist", ".", "lower", "(", ")", "artist", "=", "normalize", "(", "artist", ",", "' '", ",", "'+'", ")", "title", "=", "song", ".", "title", "url", "=", "'https://www.lyrics.com/ar...
25.961538
0.001429
def water_self_diffusion_coefficient(T=None, units=None, warn=True, err_mult=None): """ Temperature-dependent self-diffusion coefficient of water. Parameters ---------- T : float Temperature (default: in Kelvin) units : object (optional) obje...
[ "def", "water_self_diffusion_coefficient", "(", "T", "=", "None", ",", "units", "=", "None", ",", "warn", "=", "True", ",", "err_mult", "=", "None", ")", ":", "if", "units", "is", "None", ":", "K", "=", "1", "m", "=", "1", "s", "=", "1", "else", ...
34.583333
0.000586
def from_urlencoded(self, urlencoded, **kwargs): """ Starting with a string of the application/x-www-form-urlencoded format this method creates a class instance :param urlencoded: The string :return: A class instance or raise an exception on error """ # parse_q...
[ "def", "from_urlencoded", "(", "self", ",", "urlencoded", ",", "*", "*", "kwargs", ")", ":", "# parse_qs returns a dictionary with keys and values. The values are", "# always lists even if there is only one value in the list.", "# keys only appears once.", "if", "isinstance", "(", ...
34.5
0.001458
def scan_file(path): """ Scan `path` for viruses using ``clamd`` or ``clamscan`` (depends on :attr:`settings.USE_CLAMD`. Args: path (str): Relative or absolute path of file/directory you need to scan. Returns: dict: ``{filename: ("FOUND", "virus type")}`` or bla...
[ "def", "scan_file", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "settings", ".", "USE_CLAMD", ":", "return", "clamd", ".", "scan_file", "(", "path", ")", "else", ":", "return", "clamscan", ".", "scan...
28.142857
0.001637
def _missingExtraCheck(given, required, extraException, missingException): """ If the L{sets<set>} C{required} and C{given} do not contain the same elements raise an exception describing how they are different. @param given: The L{set} of elements that was actually given. @param required: The L{set...
[ "def", "_missingExtraCheck", "(", "given", ",", "required", ",", "extraException", ",", "missingException", ")", ":", "extra", "=", "given", "-", "required", "if", "extra", ":", "raise", "extraException", "(", "extra", ")", "missing", "=", "required", "-", "...
35.090909
0.001261
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: clone /api/hostgroups/:hostgroup_id/clone puppetclass_ids /api/hostgroups/:hostgroup_id/puppetclass_ids smart_c...
[ "def", "path", "(", "self", ",", "which", "=", "None", ")", ":", "if", "which", "in", "(", "'clone'", ",", "'puppetclass_ids'", ",", "'smart_class_parameters'", ",", "'smart_variables'", ")", ":", "return", "'{0}/{1}'", ".", "format", "(", "super", "(", "H...
31.925926
0.002252
def discover_by_file(self, start_filepath, top_level_directory=None): """Run test discovery on a single file. Parameters ---------- start_filepath : str The module file in which to start test discovery. top_level_directory : str The path to the top-level ...
[ "def", "discover_by_file", "(", "self", ",", "start_filepath", ",", "top_level_directory", "=", "None", ")", ":", "start_filepath", "=", "os", ".", "path", ".", "abspath", "(", "start_filepath", ")", "start_directory", "=", "os", ".", "path", ".", "dirname", ...
39.965517
0.001685
def wget(ftp, f = False, exclude = False, name = False, md5 = False, tries = 10): """ download files with wget """ # file name if f is False: f = ftp.rsplit('/', 1)[-1] # downloaded file if it does not already exist # check md5s on server (optional) t = 0 while md5check(f, ft...
[ "def", "wget", "(", "ftp", ",", "f", "=", "False", ",", "exclude", "=", "False", ",", "name", "=", "False", ",", "md5", "=", "False", ",", "tries", "=", "10", ")", ":", "# file name", "if", "f", "is", "False", ":", "f", "=", "ftp", ".", "rsplit...
32.208333
0.017588
def get_reference_end_from_cigar(reference_start, cigar): ''' This returns the coordinate just past the last aligned base. This matches the behavior of pysam's reference_end method ''' reference_end = reference_start # iterate through cigartuple for i in ...
[ "def", "get_reference_end_from_cigar", "(", "reference_start", ",", "cigar", ")", ":", "reference_end", "=", "reference_start", "# iterate through cigartuple", "for", "i", "in", "xrange", "(", "len", "(", "cigar", ")", ")", ":", "k", ",", "n", "=", "cigar", "[...
36
0.016667
def _dataset_name_and_kwargs_from_name_str(name_str): """Extract kwargs from name str.""" res = _NAME_REG.match(name_str) if not res: raise ValueError(_NAME_STR_ERR.format(name_str)) name = res.group("dataset_name") kwargs = _kwargs_str_to_kwargs(res.group("kwargs")) try: for attr in ["config", "ver...
[ "def", "_dataset_name_and_kwargs_from_name_str", "(", "name_str", ")", ":", "res", "=", "_NAME_REG", ".", "match", "(", "name_str", ")", "if", "not", "res", ":", "raise", "ValueError", "(", "_NAME_STR_ERR", ".", "format", "(", "name_str", ")", ")", "name", "...
34
0.021084
def _find_usage_networking_sgs(self): """calculate usage for VPC-related things""" logger.debug("Getting usage for EC2 VPC resources") sgs_per_vpc = defaultdict(int) rules_per_sg = defaultdict(int) for sg in self.resource_conn.security_groups.all(): if sg.vpc_id is no...
[ "def", "_find_usage_networking_sgs", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Getting usage for EC2 VPC resources\"", ")", "sgs_per_vpc", "=", "defaultdict", "(", "int", ")", "rules_per_sg", "=", "defaultdict", "(", "int", ")", "for", "sg", "in", "...
41.863636
0.002123
def query_from_file(self, filename, data=None, union=True, limit=None): """ Query your database from a file. Parameters ---------- filename: str A SQL script data: list, dict Optional argument for handlebars-queries. Data will be passed to the ...
[ "def", "query_from_file", "(", "self", ",", "filename", ",", "data", "=", "None", ",", "union", "=", "True", ",", "limit", "=", "None", ")", ":", "with", "open", "(", "filename", ")", "as", "fp", ":", "q", "=", "fp", ".", "read", "(", ")", "retur...
36.338235
0.001182
def read_arg(src, c): """Read the argument from buffer. Advances buffer until right before the end of the argument. :param Buffer src: a buffer of tokens :param str c: argument token (starting token) :return: the parsed argument :rtype: Arg """ content = [c] while src.hasNext(): ...
[ "def", "read_arg", "(", "src", ",", "c", ")", ":", "content", "=", "[", "c", "]", "while", "src", ".", "hasNext", "(", ")", ":", "if", "src", ".", "peek", "(", ")", "in", "ARG_END_TOKENS", ":", "content", ".", "append", "(", "next", "(", "src", ...
26.833333
0.002
def check_hmc_diagnostics(fit, pars=None, verbose=True, per_chain=False, checks=None): """Checks all hmc diagnostics Parameters ---------- fit : StanFit4Model object verbose : bool or int, optional If ``verbose`` is ``False`` or a nonpositive integer, no diagnostic messages are prin...
[ "def", "check_hmc_diagnostics", "(", "fit", ",", "pars", "=", "None", ",", "verbose", "=", "True", ",", "per_chain", "=", "False", ",", "checks", "=", "None", ")", ":", "# For consistency with the individual diagnostic functions", "verbosity", "=", "int", "(", "...
37.673913
0.002249
def add_view(self, path: str, handler: AbstractView, **kwargs: Any) -> AbstractRoute: """ Shortcut for add_route with ANY methods for a class-based view """ return self.add_route(hdrs.METH_ANY, path, handler, **kwargs)
[ "def", "add_view", "(", "self", ",", "path", ":", "str", ",", "handler", ":", "AbstractView", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "AbstractRoute", ":", "return", "self", ".", "add_route", "(", "hdrs", ".", "METH_ANY", ",", "path", ",", "h...
43.666667
0.011236
async def starter_bus_async(loop = None, **kwargs) : "returns a Connection object for the D-Bus starter bus." return \ Connection \ ( await dbus.Connection.bus_get_async(DBUS.BUS_STARTER, private = False, loop = loop) ) \ .register_additional_standard(**kwargs)
[ "async", "def", "starter_bus_async", "(", "loop", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Connection", "(", "await", "dbus", ".", "Connection", ".", "bus_get_async", "(", "DBUS", ".", "BUS_STARTER", ",", "private", "=", "False", ",", "...
38.75
0.0347
def validate_implementation_for_auto_decode_and_soupify(func): """ Validate that :func:`auto_decode_and_soupify` is applicable to this function. If not applicable, a ``NotImplmentedError`` will be raised. """ arg_spec = inspect.getargspec(func) for arg in ["response", "html", "soup"]: if...
[ "def", "validate_implementation_for_auto_decode_and_soupify", "(", "func", ")", ":", "arg_spec", "=", "inspect", ".", "getargspec", "(", "func", ")", "for", "arg", "in", "[", "\"response\"", ",", "\"html\"", ",", "\"soup\"", "]", ":", "if", "arg", "not", "in",...
42.75
0.001908
def download(self, path=''): """Download the data for this asset. :param path: (optional), path where the file should be saved to, default is the filename provided in the headers and will be written in the current directory. it can take a file-like object as well ...
[ "def", "download", "(", "self", ",", "path", "=", "''", ")", ":", "headers", "=", "{", "'Accept'", ":", "'application/octet-stream'", "}", "resp", "=", "self", ".", "_get", "(", "self", ".", "_api", ",", "allow_redirects", "=", "False", ",", "stream", ...
38.724138
0.001738
async def set_pause(self, pause: bool): """ Sets the player's paused state. """ await self._lavalink.ws.send(op='pause', guildId=self.guild_id, pause=pause) self.paused = pause
[ "async", "def", "set_pause", "(", "self", ",", "pause", ":", "bool", ")", ":", "await", "self", ".", "_lavalink", ".", "ws", ".", "send", "(", "op", "=", "'pause'", ",", "guildId", "=", "self", ".", "guild_id", ",", "pause", "=", "pause", ")", "sel...
50
0.014778
def register(self,flag): """Register a new :class:`Flag` instance with the Flags registry.""" super(Flags,self).__setitem__(flag.name,flag)
[ "def", "register", "(", "self", ",", "flag", ")", ":", "super", "(", "Flags", ",", "self", ")", ".", "__setitem__", "(", "flag", ".", "name", ",", "flag", ")" ]
51
0.032258
def children_after_parents(self, piper1, piper2): """ Custom compare function. Returns ``1`` if the first ``Piper`` instance is upstream of the second ``Piper`` instance, ``-1`` if the first ``Piper`` is downstream of the second ``Piper`` and ``0`` if the two ``Pipers`` are in...
[ "def", "children_after_parents", "(", "self", ",", "piper1", ",", "piper2", ")", ":", "if", "piper1", "in", "self", "[", "piper2", "]", ".", "deep_nodes", "(", ")", ":", "return", "1", "elif", "piper2", "in", "self", "[", "piper1", "]", ".", "deep_node...
34.157895
0.011994
def _parse_nationality(self, player_info): """ Parse the player's nationality. The player's nationality is denoted by a flag in the information section with a country code for each nation. The country code needs to pulled and then matched to find the player's home country. Once ...
[ "def", "_parse_nationality", "(", "self", ",", "player_info", ")", ":", "for", "span", "in", "player_info", "(", "'span'", ")", ".", "items", "(", ")", ":", "if", "'class=\"f-i'", "in", "str", "(", "span", ")", ":", "nationality", "=", "span", ".", "te...
40.15
0.002433
def register(model, field_name=None, related_name=None, lookup_method_name='get_follows'): """ This registers any model class to be follow-able. """ if model in registry: return registry.append(model) if not field_name: field_name = 'target_%s' % model._meta.module_nam...
[ "def", "register", "(", "model", ",", "field_name", "=", "None", ",", "related_name", "=", "None", ",", "lookup_method_name", "=", "'get_follows'", ")", ":", "if", "model", "in", "registry", ":", "return", "registry", ".", "append", "(", "model", ")", "if"...
30.409091
0.011594
def add_to_js(self, name, var): """Add an object to Javascript.""" frame = self.page().mainFrame() frame.addToJavaScriptWindowObject(name, var)
[ "def", "add_to_js", "(", "self", ",", "name", ",", "var", ")", ":", "frame", "=", "self", ".", "page", "(", ")", ".", "mainFrame", "(", ")", "frame", ".", "addToJavaScriptWindowObject", "(", "name", ",", "var", ")" ]
41
0.011976
def rename(self, from_, to): """ Rename a table on the schema. """ blueprint = self._create_blueprint(from_) blueprint.rename(to) self._build(blueprint)
[ "def", "rename", "(", "self", ",", "from_", ",", "to", ")", ":", "blueprint", "=", "self", ".", "_create_blueprint", "(", "from_", ")", "blueprint", ".", "rename", "(", "to", ")", "self", ".", "_build", "(", "blueprint", ")" ]
21.555556
0.009901
def check_xups_env_ambient_temp(the_session, the_helper, the_snmp_value, the_unit=1): """ OID .1.3.6.1.4.1.534.1.6.1.0 MIB Excerpt The reading of the ambient temperature in the vicinity of the UPS or SNMP agent. """ the_helper.add_metric( label=the_helper.options.type, ...
[ "def", "check_xups_env_ambient_temp", "(", "the_session", ",", "the_helper", ",", "the_snmp_value", ",", "the_unit", "=", "1", ")", ":", "the_helper", ".", "add_metric", "(", "label", "=", "the_helper", ".", "options", ".", "type", ",", "value", "=", "the_snmp...
31.5
0.011013
def _make_chunk_iter(stream, limit, buffer_size): """Helper for the line and chunk iter functions.""" if isinstance(stream, (bytes, bytearray, text_type)): raise TypeError('Passed a string or byte object instead of ' 'true iterator or stream.') if not hasattr(stream, 'read'):...
[ "def", "_make_chunk_iter", "(", "stream", ",", "limit", ",", "buffer_size", ")", ":", "if", "isinstance", "(", "stream", ",", "(", "bytes", ",", "bytearray", ",", "text_type", ")", ")", ":", "raise", "TypeError", "(", "'Passed a string or byte object instead of ...
35.388889
0.001529
def get(self): """retrieve a result from the pool if nothing is already completed when this method is called, it will block until something comes back if the pool's function exited via exception, that will come back as a result here as well, but will be re-raised in :meth:`get`...
[ "def", "get", "(", "self", ")", ":", "if", "self", ".", "closed", ":", "raise", "PoolClosed", "(", ")", "result", ",", "succeeded", "=", "self", ".", "outq", ".", "get", "(", ")", "if", "not", "succeeded", ":", "klass", ",", "exc", ",", "tb", "="...
32.387097
0.001934
def get_link(self, link_id): """ Return the Link or raise a 404 if the link is unknown """ try: return self._links[link_id] except KeyError: raise aiohttp.web.HTTPNotFound(text="Link ID {} doesn't exist".format(link_id))
[ "def", "get_link", "(", "self", ",", "link_id", ")", ":", "try", ":", "return", "self", ".", "_links", "[", "link_id", "]", "except", "KeyError", ":", "raise", "aiohttp", ".", "web", ".", "HTTPNotFound", "(", "text", "=", "\"Link ID {} doesn't exist\"", "....
34.625
0.010563
def list_metering_labels(self, retrieve_all=True, **_params): """Fetches a list of all metering labels for a project.""" return self.list('metering_labels', self.metering_labels_path, retrieve_all, **_params)
[ "def", "list_metering_labels", "(", "self", ",", "retrieve_all", "=", "True", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "list", "(", "'metering_labels'", ",", "self", ".", "metering_labels_path", ",", "retrieve_all", ",", "*", "*", "_params"...
61.5
0.008032
def perform_permissions_check(self, user, obj, perms): """ Performs the permissions check. """ return self.request.forum_permission_handler.can_update_topics_to_normal_topics(obj, user)
[ "def", "perform_permissions_check", "(", "self", ",", "user", ",", "obj", ",", "perms", ")", ":", "return", "self", ".", "request", ".", "forum_permission_handler", ".", "can_update_topics_to_normal_topics", "(", "obj", ",", "user", ")" ]
66.333333
0.014925
def form_valid(self, form): """After the form is valid lets let people know""" ret = super(ProjectCopy, self).form_valid(form) self.copy_relations() # Good to make note of that messages.add_message(self.request, messages.SUCCESS, 'Project %s copied' % self.object.name) ...
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "ret", "=", "super", "(", "ProjectCopy", ",", "self", ")", ".", "form_valid", "(", "form", ")", "self", ".", "copy_relations", "(", ")", "# Good to make note of that", "messages", ".", "add_message", ...
32.2
0.009063
def compatibility_mode(): """ Use this function to turn on the compatibility mode. The compatibility mode is used to improve compatibility with Pyinotify 0.7.1 (or older) programs. The compatibility mode provides additional variables 'is_dir', 'event_name', 'EventsCodes.IN_*' and 'EventsCodes.ALL_EV...
[ "def", "compatibility_mode", "(", ")", ":", "setattr", "(", "EventsCodes", ",", "'ALL_EVENTS'", ",", "ALL_EVENTS", ")", "for", "evname", "in", "globals", "(", ")", ":", "if", "evname", ".", "startswith", "(", "'IN_'", ")", ":", "setattr", "(", "EventsCodes...
46.533333
0.001404
def get_implemented_interfaces(cls): """ Returns a set of :term:`interfaces <interface>` declared as implemented by class `cls`. """ if hasattr(cls, '__interfaces__'): return cls.__interfaces__ return six.moves.reduce( lambda x, y: x.union(y), map( get_impleme...
[ "def", "get_implemented_interfaces", "(", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "'__interfaces__'", ")", ":", "return", "cls", ".", "__interfaces__", "return", "six", ".", "moves", ".", "reduce", "(", "lambda", "x", ",", "y", ":", "x", ".", ...
25.933333
0.002481
async def init_restart(self, error=None): """ Restart the stream on error Parameters ---------- error : bool, optional Whether to print the error or not """ if error: utils.log_error(logger=logger) if self.state == DISCONNECTI...
[ "async", "def", "init_restart", "(", "self", ",", "error", "=", "None", ")", ":", "if", "error", ":", "utils", ".", "log_error", "(", "logger", "=", "logger", ")", "if", "self", ".", "state", "==", "DISCONNECTION", ":", "if", "self", ".", "_error_timeo...
40.960784
0.000935
def get_colour_handler(extranames: List[str] = None, with_process_id: bool = False, with_thread_id: bool = False, stream: TextIO = None) -> logging.StreamHandler: """ Gets a colour log handler using a standard format. Args: extran...
[ "def", "get_colour_handler", "(", "extranames", ":", "List", "[", "str", "]", "=", "None", ",", "with_process_id", ":", "bool", "=", "False", ",", "with_thread_id", ":", "bool", "=", "False", ",", "stream", ":", "TextIO", "=", "None", ")", "->", "logging...
39.27027
0.000672
def validate_minmax_axis(axis): """ Ensure that the axis argument passed to min, max, argmin, or argmax is zero or None, as otherwise it will be incorrectly ignored. Parameters ---------- axis : int or None Raises ------ ValueError """ ndim = 1 # hard-coded for Index i...
[ "def", "validate_minmax_axis", "(", "axis", ")", ":", "ndim", "=", "1", "# hard-coded for Index", "if", "axis", "is", "None", ":", "return", "if", "axis", ">=", "ndim", "or", "(", "axis", "<", "0", "and", "ndim", "+", "axis", "<", "0", ")", ":", "rai...
27.421053
0.001855
def shutdown(self): """ Shuts down the process. """ if not self._exited: self._exited = True _shutdown_pipe(self._pipe) self._task.stop() raise SystemExit
[ "def", "shutdown", "(", "self", ")", ":", "if", "not", "self", ".", "_exited", ":", "self", ".", "_exited", "=", "True", "_shutdown_pipe", "(", "self", ".", "_pipe", ")", "self", ".", "_task", ".", "stop", "(", ")", "raise", "SystemExit" ]
24.777778
0.008658
def list_out(): """List all themes in a pretty format.""" dark_themes = [theme.name.replace(".json", "") for theme in list_themes()] ligh_themes = [theme.name.replace(".json", "") for theme in list_themes(dark=False)] user_themes = [theme.name.replace(".json", "") ...
[ "def", "list_out", "(", ")", ":", "dark_themes", "=", "[", "theme", ".", "name", ".", "replace", "(", "\".json\"", ",", "\"\"", ")", "for", "theme", "in", "list_themes", "(", ")", "]", "ligh_themes", "=", "[", "theme", ".", "name", ".", "replace", "(...
37.73913
0.001124
def is_fuse_exec(cmd): ''' Returns true if the command passed is a fuse mountable application. CLI Example: .. code-block:: bash salt '*' mount.is_fuse_exec sshfs ''' cmd_path = salt.utils.path.which(cmd) # No point in running ldd on a command that doesn't exist if not cmd_pa...
[ "def", "is_fuse_exec", "(", "cmd", ")", ":", "cmd_path", "=", "salt", ".", "utils", ".", "path", ".", "which", "(", "cmd", ")", "# No point in running ldd on a command that doesn't exist", "if", "not", "cmd_path", ":", "return", "False", "elif", "not", "salt", ...
25.85
0.001866
def set_last_build_date(self): """Parses last build date and set value""" try: self.last_build_date = self.soup.find('lastbuilddate').string except AttributeError: self.last_build_date = None
[ "def", "set_last_build_date", "(", "self", ")", ":", "try", ":", "self", ".", "last_build_date", "=", "self", ".", "soup", ".", "find", "(", "'lastbuilddate'", ")", ".", "string", "except", "AttributeError", ":", "self", ".", "last_build_date", "=", "None" ]
39
0.008368
def parse_qs(qs, keep_blank_values=0, strict_parsing=0): """Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings....
[ "def", "parse_qs", "(", "qs", ",", "keep_blank_values", "=", "0", ",", "strict_parsing", "=", "0", ")", ":", "dict", "=", "{", "}", "for", "name", ",", "value", "in", "parse_qsl", "(", "qs", ",", "keep_blank_values", ",", "strict_parsing", ")", ":", "i...
37.8
0.001032
def write_classifier(self, clf): """ Writes classifier object to pickle file """ with open(os.path.join(self.repopath, 'classifier.pkl'), 'w') as fp: pickle.dump(clf, fp)
[ "def", "write_classifier", "(", "self", ",", "clf", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "repopath", ",", "'classifier.pkl'", ")", ",", "'w'", ")", "as", "fp", ":", "pickle", ".", "dump", "(", "clf", ",",...
39
0.01005
def bld_rafter_deflection(length=-9, force=-9, E_mod_elasticity=-9, I_moment_of_intertia=-9): """ calculate rafter deflections - see test_calc_building_design.py for Sample values for equations below from Structures II course """ if length == -9: length = float(input('enter rafter...
[ "def", "bld_rafter_deflection", "(", "length", "=", "-", "9", ",", "force", "=", "-", "9", ",", "E_mod_elasticity", "=", "-", "9", ",", "I_moment_of_intertia", "=", "-", "9", ")", ":", "if", "length", "==", "-", "9", ":", "length", "=", "float", "(",...
40.769231
0.01659
def _validate_required(self, item, name): """Validate that the item is present if it's required.""" if self.required is True and item is None: raise ArgumentError(name, "This argument is required.")
[ "def", "_validate_required", "(", "self", ",", "item", ",", "name", ")", ":", "if", "self", ".", "required", "is", "True", "and", "item", "is", "None", ":", "raise", "ArgumentError", "(", "name", ",", "\"This argument is required.\"", ")" ]
55.75
0.00885
def masking_noise(data, sess, v): """Apply masking noise to data in X. In other words a fraction v of elements of X (chosen at random) is forced to zero. :param data: array_like, Input data :param sess: TensorFlow session :param v: fraction of elements to distort, float :return: transformed...
[ "def", "masking_noise", "(", "data", ",", "sess", ",", "v", ")", ":", "data_noise", "=", "data", ".", "copy", "(", ")", "rand", "=", "tf", ".", "random_uniform", "(", "data", ".", "shape", ")", "data_noise", "[", "sess", ".", "run", "(", "tf", ".",...
32.533333
0.001992
def _parse_mibs(iLOIP, snmp_credentials): """Parses the MIBs. :param iLOIP: IP address of the server on which SNMP discovery has to be executed. :param snmp_credentials: a Dictionary of SNMP credentials. auth_user: SNMP user auth_protocol: Auth Protocol au...
[ "def", "_parse_mibs", "(", "iLOIP", ",", "snmp_credentials", ")", ":", "result", "=", "{", "}", "usm_user_obj", "=", "_create_usm_user_obj", "(", "snmp_credentials", ")", "try", ":", "for", "(", "errorIndication", ",", "errorStatus", ",", "errorIndex", ",", "v...
44
0.000305
def smooth(polylines): """ smooth every polyline using spline interpolation """ for c in polylines: if len(c) < 9: # smoothing wouldn't make sense here continue x = c[:, 0] y = c[:, 1] t = np.arange(x.shape[0], dtype=float) t /= t[-1] ...
[ "def", "smooth", "(", "polylines", ")", ":", "for", "c", "in", "polylines", ":", "if", "len", "(", "c", ")", "<", "9", ":", "# smoothing wouldn't make sense here", "continue", "x", "=", "c", "[", ":", ",", "0", "]", "y", "=", "c", "[", ":", ",", ...
24.411765
0.00232
def layout(args): """ %prog layout query.subject.simple query.seqids subject.seqids Compute optimal seqids order in a second genome, based on seqids on one genome, given the pairwise blocks in .simple format. """ from jcvi.algorithms.ec import GA_setup, GA_run p = OptionParser(layout.__doc...
[ "def", "layout", "(", "args", ")", ":", "from", "jcvi", ".", "algorithms", ".", "ec", "import", "GA_setup", ",", "GA_run", "p", "=", "OptionParser", "(", "layout", ".", "__doc__", ")", "p", ".", "set_beds", "(", ")", "p", ".", "set_cpus", "(", "cpus"...
31.104167
0.000649
def _insert_common_sphinx_configs(c, *, project_name): """Add common core Sphinx configurations to the state. """ c['project'] = project_name # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: c['source_suffix'] = '.rst' # The encoding of source fi...
[ "def", "_insert_common_sphinx_configs", "(", "c", ",", "*", ",", "project_name", ")", ":", "c", "[", "'project'", "]", "=", "project_name", "# The suffix(es) of source filenames.", "# You can specify multiple suffix as a list of string:", "c", "[", "'source_suffix'", "]", ...
33.615385
0.000741
def serialize(pca, **kwargs): """ Serialize an orientation object to a dict suitable for JSON """ strike, dip, rake = pca.strike_dip_rake() hyp_axes = sampling_axes(pca) return dict( **kwargs, principal_axes = pca.axes.tolist(), hyperbolic_axes = hyp_axes.tolist(), ...
[ "def", "serialize", "(", "pca", ",", "*", "*", "kwargs", ")", ":", "strike", ",", "dip", ",", "rake", "=", "pca", ".", "strike_dip_rake", "(", ")", "hyp_axes", "=", "sampling_axes", "(", "pca", ")", "return", "dict", "(", "*", "*", "kwargs", ",", "...
28.75
0.016842
def invoke_hook_prepare(self): """invoke task hooks for after the spout/bolt's initialize() method""" for task_hook in self.task_hooks: task_hook.prepare(self.get_cluster_config(), self)
[ "def", "invoke_hook_prepare", "(", "self", ")", ":", "for", "task_hook", "in", "self", ".", "task_hooks", ":", "task_hook", ".", "prepare", "(", "self", ".", "get_cluster_config", "(", ")", ",", "self", ")" ]
49.25
0.01
def result(self, result): """ aggregate errors """ if result and len(result[2]) > 0: self.errs.extend([((result[0], result[1]), err) for err in result[2]])
[ "def", "result", "(", "self", ",", "result", ")", ":", "if", "result", "and", "len", "(", "result", "[", "2", "]", ")", ">", "0", ":", "self", ".", "errs", ".", "extend", "(", "[", "(", "(", "result", "[", "0", "]", ",", "result", "[", "1", ...
45
0.016393
def _total_jxn_counts(fns): """Count the total unique coverage junction for junctions in a set of SJ.out.tab files.""" df = pd.read_table(fns[0], header=None, names=COLUMN_NAMES) df.index = (df.chrom + ':' + df.start.astype(int).astype(str) + '-' + df.end.astype(int).astype(str)) cou...
[ "def", "_total_jxn_counts", "(", "fns", ")", ":", "df", "=", "pd", ".", "read_table", "(", "fns", "[", "0", "]", ",", "header", "=", "None", ",", "names", "=", "COLUMN_NAMES", ")", "df", ".", "index", "=", "(", "df", ".", "chrom", "+", "':'", "+"...
49.307692
0.001531
def main(): """function to """ # parse arg to find file(s) parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", help="convert the markdown file to HTML") parser.add_argument("-d", "--directory", help="convert the markdown files in the...
[ "def", "main", "(", ")", ":", "# parse arg to find file(s)", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"-f\"", ",", "\"--file\"", ",", "help", "=", "\"convert the markdown file to HTML\"", ")", "parser", ".",...
35.5
0.002285
def _compute_mean(self, C, g, mag, hypo_depth, dists, imt): """ Compute mean according to equation on Table 2, page 2275. """ delta = 0.00750 * 10 ** (0.507 * mag) # computing R for different values of mag if mag < 6.5: R = np.sqrt(dists.rhypo ** 2 + delta *...
[ "def", "_compute_mean", "(", "self", ",", "C", ",", "g", ",", "mag", ",", "hypo_depth", ",", "dists", ",", "imt", ")", ":", "delta", "=", "0.00750", "*", "10", "**", "(", "0.507", "*", "mag", ")", "# computing R for different values of mag", "if", "mag",...
28.166667
0.002288
def cb_active_plot(self,start_ms,stop_ms,line_color='b'): """ Plot timing information of time spent in the callback. This is similar to what a logic analyzer provides when probing an interrupt. cb_active_plot( start_ms,stop_ms,line_color='b') """ # Find ...
[ "def", "cb_active_plot", "(", "self", ",", "start_ms", ",", "stop_ms", ",", "line_color", "=", "'b'", ")", ":", "# Find bounding k values that contain the [start_ms,stop_ms]\r", "k_min_idx", "=", "np", ".", "nonzero", "(", "np", ".", "ravel", "(", "np", ".", "ar...
42
0.025325
def molecules2symbols(molecules, add_hydrogen=True): """Take a list of molecules and return just a list of atomic symbols, possibly adding hydrogen """ symbols = sorted( list(set( ase.symbols.string2symbols(''.join( map( lambda _x: ...
[ "def", "molecules2symbols", "(", "molecules", ",", "add_hydrogen", "=", "True", ")", ":", "symbols", "=", "sorted", "(", "list", "(", "set", "(", "ase", ".", "symbols", ".", "string2symbols", "(", "''", ".", "join", "(", "map", "(", "lambda", "_x", ":"...
29.611111
0.001818
def split_to_tiles(img, columns, rows): """ Split an image into a specified number of tiles. Args: img (ndarray): The image to split. number_tiles (int): The number of tiles required. Returns: Tuple of tiles """ # validate_image(img, number_tiles) im_w, im_h = img.sh...
[ "def", "split_to_tiles", "(", "img", ",", "columns", ",", "rows", ")", ":", "# validate_image(img, number_tiles)", "im_w", ",", "im_h", "=", "img", ".", "shape", "# columns, rows = calc_columns_rows(number_tiles)", "# extras = (columns * rows) - number_tiles", "tile_w", ","...
35.516129
0.000884
def to_profile_info(self, serialize_credentials=False): """Unlike to_project_config, this dict is not a mirror of any existing on-disk data structure. It's used when creating a new profile from an existing one. :param serialize_credentials bool: If True, serialize the credentials. ...
[ "def", "to_profile_info", "(", "self", ",", "serialize_credentials", "=", "False", ")", ":", "result", "=", "{", "'profile_name'", ":", "self", ".", "profile_name", ",", "'target_name'", ":", "self", ".", "target_name", ",", "'config'", ":", "self", ".", "co...
42.368421
0.00243
def generate_menu_alt(): """Generate ``menu_alt`` with log in/out links. :return: HTML fragment :rtype: str """ if not current_user.is_authenticated(): return ('<li><a href="{0}"><i class="fa fa-fw fa-sign-in"></i> ' 'Log in</a></li>'.format(url_for('login'))) if db is n...
[ "def", "generate_menu_alt", "(", ")", ":", "if", "not", "current_user", ".", "is_authenticated", "(", ")", ":", "return", "(", "'<li><a href=\"{0}\"><i class=\"fa fa-fw fa-sign-in\"></i> '", "'Log in</a></li>'", ".", "format", "(", "url_for", "(", "'login'", ")", ")",...
40.30303
0.000734
def createLabels2D(self): """ 2D labeling at zmax """ logger.debug(" Creating 2D labels...") self.zmax = np.argmax(self.values,axis=1) self.vmax = self.values[np.arange(len(self.pixels),dtype=int),self.zmax] kwargs=dict(pixels=self.pixels,values=self.vmax,nside=self.nside, ...
[ "def", "createLabels2D", "(", "self", ")", ":", "logger", ".", "debug", "(", "\" Creating 2D labels...\"", ")", "self", ".", "zmax", "=", "np", ".", "argmax", "(", "self", ".", "values", ",", "axis", "=", "1", ")", "self", ".", "vmax", "=", "self", ...
50.333333
0.022764
def send_create_list_email(**kargs): """ Send the notification mail kargs' params: user = User object password = list's password listname = list's name """ to = kargs.get('user', None) if not to: return to = [to.email] from_email = settings.COLAB_FROM_ADDRESS...
[ "def", "send_create_list_email", "(", "*", "*", "kargs", ")", ":", "to", "=", "kargs", ".", "get", "(", "'user'", ",", "None", ")", "if", "not", "to", ":", "return", "to", "=", "[", "to", ".", "email", "]", "from_email", "=", "settings", ".", "COLA...
32.588235
0.001754
def prepare_soap_envelope(self, prepared_soap_header, prepared_soap_body): """Prepare the SOAP Envelope for sending. Args: prepared_soap_header (str): A SOAP Header prepared by `prepare_soap_header` prepared_soap_body (str): A SOAP Body prepared by ...
[ "def", "prepare_soap_envelope", "(", "self", ",", "prepared_soap_header", ",", "prepared_soap_body", ")", ":", "# pylint: disable=bad-continuation", "soap_env_template", "=", "(", "'<?xml version=\"1.0\"?>'", "'<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"'", "' s...
36.769231
0.002039
def count(self, objectType, *args, **coolArgs) : """Returns the number of elements satisfying the query""" return self._makeLoadQuery(objectType, *args, **coolArgs).count()
[ "def", "count", "(", "self", ",", "objectType", ",", "*", "args", ",", "*", "*", "coolArgs", ")", ":", "return", "self", ".", "_makeLoadQuery", "(", "objectType", ",", "*", "args", ",", "*", "*", "coolArgs", ")", ".", "count", "(", ")" ]
58
0.028409
def _find(self, key): """Given a key, find the value Vyper will check in the following order: override, arg, env, config file, key/value store, default Vyper will check to see if an alias exists first. """ key = self._real_key(key) # OVERRIDES val = self....
[ "def", "_find", "(", "self", ",", "key", ")", ":", "key", "=", "self", ".", "_real_key", "(", "key", ")", "# OVERRIDES", "val", "=", "self", ".", "_override", ".", "get", "(", "key", ")", "if", "val", "is", "not", "None", ":", "log", ".", "debug"...
36.051546
0.000557