text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_and_update(cls, id, **kwargs): """Returns an updated instance of the service's model class. Args: model: the model to update **kwargs: update parameters """ model = cls.get(id) for k, v in cls._preprocess_params(kwargs).items(): setatt...
[ "def", "get_and_update", "(", "cls", ",", "id", ",", "*", "*", "kwargs", ")", ":", "model", "=", "cls", ".", "get", "(", "id", ")", "for", "k", ",", "v", "in", "cls", ".", "_preprocess_params", "(", "kwargs", ")", ".", "items", "(", ")", ":", "...
31.083333
12
def _read_offset_value(self, f, offset, size): ''' Reads an integer value from file "f" at location "offset". ''' f.seek(offset, 0) if (size == 8): return int.from_bytes(f.read(8), 'big', signed=True) else: return int.from_bytes(f.read(4), 'big', s...
[ "def", "_read_offset_value", "(", "self", ",", "f", ",", "offset", ",", "size", ")", ":", "f", ".", "seek", "(", "offset", ",", "0", ")", "if", "(", "size", "==", "8", ")", ":", "return", "int", ".", "from_bytes", "(", "f", ".", "read", "(", "8...
35.888889
21.888889
def wrap_as_node(self, func): 'wrap a function as a node' name = self.get_name(func) @wraps(func) def wrapped(*args, **kwargs): 'wrapped version of func' message = self.get_message_from_call(*args, **kwargs) self.logger.info('calling "%s" with %r', na...
[ "def", "wrap_as_node", "(", "self", ",", "func", ")", ":", "name", "=", "self", ".", "get_name", "(", "func", ")", "@", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "'wrapped version of func'", "me...
38.4
19.155556
def get_items_of_invoice_per_page(self, invoice_id, per_page=1000, page=1): """ Get invoice items of invoice per page :param invoice_id: the invoice id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list """...
[ "def", "get_items_of_invoice_per_page", "(", "self", ",", "invoice_id", ",", "per_page", "=", "1000", ",", "page", "=", "1", ")", ":", "return", "self", ".", "_get_resource_per_page", "(", "resource", "=", "INVOICE_ITEMS", ",", "per_page", "=", "per_page", ","...
33.133333
13.4
def clone_bs4_elem(el): """Clone a bs4 tag before modifying it. Code from `http://stackoverflow.com/questions/23057631/clone-element-with -beautifulsoup` """ if isinstance(el, NavigableString): return type(el)(el) copy = Tag(None, el.builder, el.name, el.namespace, el.nsprefix) # w...
[ "def", "clone_bs4_elem", "(", "el", ")", ":", "if", "isinstance", "(", "el", ",", "NavigableString", ")", ":", "return", "type", "(", "el", ")", "(", "el", ")", "copy", "=", "Tag", "(", "None", ",", "el", ".", "builder", ",", "el", ".", "name", "...
34.833333
16.166667
def change_options(self, **kwargs): ''' Change one of the track's options in the viewconf ''' new_options = json.loads(json.dumps(self.viewconf['options'])) new_options = {**new_options, **kwargs} return self.change_attributes(options=new_options)
[ "def", "change_options", "(", "self", ",", "*", "*", "kwargs", ")", ":", "new_options", "=", "json", ".", "loads", "(", "json", ".", "dumps", "(", "self", ".", "viewconf", "[", "'options'", "]", ")", ")", "new_options", "=", "{", "*", "*", "new_optio...
36.125
21.875
def coordinates(self, transformed=True, copy=True): """ Return the list of vertex coordinates of the input mesh. Same as `actor.getPoints()`. :param bool transformed: if `False` ignore any previous trasformation applied to the mesh. :param bool copy: if `False` return the reference to t...
[ "def", "coordinates", "(", "self", ",", "transformed", "=", "True", ",", "copy", "=", "True", ")", ":", "poly", "=", "self", ".", "polydata", "(", "transformed", ")", "if", "copy", ":", "return", "np", ".", "array", "(", "vtk_to_numpy", "(", "poly", ...
40.866667
23.533333
def write_nex(data, sidx, pnames): """ write the nexus output file from the tmparr[seqarray] and tmparr[maparr] """ ## grab seq data from tmparr start = time.time() tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name)) with h5py.File(tmparrs, 'r') as io5: s...
[ "def", "write_nex", "(", "data", ",", "sidx", ",", "pnames", ")", ":", "## grab seq data from tmparr", "start", "=", "time", ".", "time", "(", ")", "tmparrs", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "outfiles", ",", "\"tmp-{...
37.285714
20.163265
def Convert(self, metadata, conn, token=None): """Converts NetworkConnection to ExportedNetworkConnection.""" result = ExportedNetworkConnection( metadata=metadata, family=conn.family, type=conn.type, local_address=conn.local_address, remote_address=conn.remote_address, ...
[ "def", "Convert", "(", "self", ",", "metadata", ",", "conn", ",", "token", "=", "None", ")", ":", "result", "=", "ExportedNetworkConnection", "(", "metadata", "=", "metadata", ",", "family", "=", "conn", ".", "family", ",", "type", "=", "conn", ".", "t...
30.846154
12.692308
def _get_header_url(response, header_name): """Get a URL from a header requests. :param requests.Response response: REST call response. :param str header_name: Header name. :returns: URL if not None AND valid, None otherwise """ url = response.headers.get(header_name) try: _validate...
[ "def", "_get_header_url", "(", "response", ",", "header_name", ")", ":", "url", "=", "response", ".", "headers", ".", "get", "(", "header_name", ")", "try", ":", "_validate", "(", "url", ")", "except", "ValueError", ":", "return", "None", "else", ":", "r...
27.428571
15.785714
def raise_405(instance): """Abort the current request with a 405 (Method Not Allowed) response code. Sets the ``Allow`` response header to the return value of the :func:`Resource.get_allowed_methods` function. :param instance: Resource instance (used to access the response) :type instance: :class:`...
[ "def", "raise_405", "(", "instance", ")", ":", "instance", ".", "response", ".", "status", "=", "405", "instance", ".", "response", ".", "headers", "[", "'Allow'", "]", "=", "instance", ".", "get_allowed_methods", "(", ")", "raise", "ResponseException", "(",...
47.166667
17.5
def filter_headers(data): """只设置host content-type 还有x开头的头部. :param data(dict): 所有的头部信息. :return(dict): 计算进签名的头部. """ headers = {} for i in data: if i == 'Content-Type' or i == 'Host' or i[0] == 'x' or i[0] == 'X': headers[i] = data[i] return headers
[ "def", "filter_headers", "(", "data", ")", ":", "headers", "=", "{", "}", "for", "i", "in", "data", ":", "if", "i", "==", "'Content-Type'", "or", "i", "==", "'Host'", "or", "i", "[", "0", "]", "==", "'x'", "or", "i", "[", "0", "]", "==", "'X'",...
26.181818
17.090909
def lookup_statistic(score, stats): """ Finds statistics that correspond to PSM/peptide/protein feature's score. Loops through list of qvality generated scores until it finds values closest to the feature's svm_score.""" if score in stats: return stats[score]['q'], stats[score]['PEP'], None ...
[ "def", "lookup_statistic", "(", "score", ",", "stats", ")", ":", "if", "score", "in", "stats", ":", "return", "stats", "[", "score", "]", "[", "'q'", "]", ",", "stats", "[", "score", "]", "[", "'PEP'", "]", ",", "None", "else", ":", "lower", ",", ...
46
15.304348
def meff_lh_110(self, **kwargs): ''' Returns the light-hole band effective mass in the [110] direction, meff_lh_110, in units of electron mass. ''' return 2. / (2 * self.luttinger1(**kwargs) + self.luttinger2(**kwargs) + 3 * self.luttinger3(**kwargs))
[ "def", "meff_lh_110", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "2.", "/", "(", "2", "*", "self", ".", "luttinger1", "(", "*", "*", "kwargs", ")", "+", "self", ".", "luttinger2", "(", "*", "*", "kwargs", ")", "+", "3", "*", "sel...
43
21.857143
def add_argument(self, *args, **kwargs): """this method overrides the standard in order to create a parallel argument system in both the argparse and configman worlds. Each call to this method returns a standard argparse Action object as well as adding an equivalent configman Option obj...
[ "def", "add_argument", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pull out each of the argument definition components from the args", "# so that we can deal with them one at a time in a well labeled manner", "# In this section, variables beginning with the pre...
42.066116
17.632231
def install_reactor(explicitReactor=None, verbose=False): """ Install Twisted reactor. :param explicitReactor: If provided, install this reactor. Else, install optimal reactor. :type explicitReactor: obj :param verbose: If ``True``, print what happens. :type verbose: bool """ import sys...
[ "def", "install_reactor", "(", "explicitReactor", "=", "None", ",", "verbose", "=", "False", ")", ":", "import", "sys", "if", "explicitReactor", ":", "## install explicitly given reactor", "##", "from", "twisted", ".", "application", ".", "reactors", "import", "in...
33.111111
22.5
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = RelativeLayout(self.get_context(), None, d.style)
[ "def", "create_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "self", ".", "widget", "=", "RelativeLayout", "(", "self", ".", "get_context", "(", ")", ",", "None", ",", "d", ".", "style", ")" ]
29.166667
16.5
def has_colors(stream): """ Determine if the terminal supports ansi colors. """ if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("col...
[ "def", "has_colors", "(", "stream", ")", ":", "if", "not", "hasattr", "(", "stream", ",", "\"isatty\"", ")", ":", "return", "False", "if", "not", "stream", ".", "isatty", "(", ")", ":", "return", "False", "# auto color only on TTYs", "try", ":", "import", ...
24.928571
13.5
def InferUserAndSubjectFromUrn(self): """Infers user name and subject urn from self.urn.""" _, client_id, user, _ = self.urn.Split(4) return (user, rdf_client.ClientURN(client_id))
[ "def", "InferUserAndSubjectFromUrn", "(", "self", ")", ":", "_", ",", "client_id", ",", "user", ",", "_", "=", "self", ".", "urn", ".", "Split", "(", "4", ")", "return", "(", "user", ",", "rdf_client", ".", "ClientURN", "(", "client_id", ")", ")" ]
47.25
4.5
def move_item_down(self, item): """Move an item down in the list. Essentially swap it with the item below it. :param item: The item to be moved. """ next_iter = self._next_iter_for(item) if next_iter is not None: self.model.swap(self._iter_for(item), next_it...
[ "def", "move_item_down", "(", "self", ",", "item", ")", ":", "next_iter", "=", "self", ".", "_next_iter_for", "(", "item", ")", "if", "next_iter", "is", "not", "None", ":", "self", ".", "model", ".", "swap", "(", "self", ".", "_iter_for", "(", "item", ...
31.4
13.4
def dispatch(self, args): """ Calls proper method depending on command-line arguments. """ if not args.list and not args.group: if not args.font and not args.char and not args.block: self.info() return else: args.lis...
[ "def", "dispatch", "(", "self", ",", "args", ")", ":", "if", "not", "args", ".", "list", "and", "not", "args", ".", "group", ":", "if", "not", "args", ".", "font", "and", "not", "args", ".", "char", "and", "not", "args", ".", "block", ":", "self"...
35.1
14.2
def _read_requirements(metadata, extras): """Read wheel metadata to know what it depends on. The `run_requires` attribute contains a list of dict or str specifying requirements. For dicts, it may contain an "extra" key to specify these requirements are for a specific extra. Unfortunately, not all field...
[ "def", "_read_requirements", "(", "metadata", ",", "extras", ")", ":", "extras", "=", "extras", "or", "(", ")", "requirements", "=", "[", "]", "for", "entry", "in", "metadata", ".", "run_requires", ":", "if", "isinstance", "(", "entry", ",", "six", ".", ...
44.5
18.411765
def _delete_wals_before(self, segment_info): """ Delete all WAL files before segment_info. Doesn't delete any base-backup data. """ wal_key_depth = self.layout.wal_directory().count('/') + 1 for key in self._backup_list(prefix=self.layout.wal_directory()): ke...
[ "def", "_delete_wals_before", "(", "self", ",", "segment_info", ")", ":", "wal_key_depth", "=", "self", ".", "layout", ".", "wal_directory", "(", ")", ".", "count", "(", "'/'", ")", "+", "1", "for", "key", "in", "self", ".", "_backup_list", "(", "prefix"...
50.107692
19.984615
def _se_all(self): """Standard errors (SE) for all parameters, including the intercept.""" err = np.expand_dims(self._ms_err, axis=1) t1 = np.diagonal( np.linalg.inv(np.matmul(self.xwins.swapaxes(1, 2), self.xwins)), axis1=1, axis2=2, ) ...
[ "def", "_se_all", "(", "self", ")", ":", "err", "=", "np", ".", "expand_dims", "(", "self", ".", "_ms_err", ",", "axis", "=", "1", ")", "t1", "=", "np", ".", "diagonal", "(", "np", ".", "linalg", ".", "inv", "(", "np", ".", "matmul", "(", "self...
38.777778
17.222222
def _init_dflt(self): """Get a list of namedtuples, one for each annotation.""" nts = [] ntobj = cx.namedtuple('ntanno', self.flds) for itemid, gos in self.id2gos.items(): for goid in gos: nts.append(ntobj(DB_ID=itemid, GO_ID=goid)) return nts
[ "def", "_init_dflt", "(", "self", ")", ":", "nts", "=", "[", "]", "ntobj", "=", "cx", ".", "namedtuple", "(", "'ntanno'", ",", "self", ".", "flds", ")", "for", "itemid", ",", "gos", "in", "self", ".", "id2gos", ".", "items", "(", ")", ":", "for",...
38
14.125
def recover_cfg_all(self, entries, symbols=None, callback=None, arch_mode=None): """Recover CFG for all functions from an entry point and/or symbol table. Args: entries (list): A list of function addresses' to start the CFG recovery process. symbols (dict): Symbol table. ...
[ "def", "recover_cfg_all", "(", "self", ",", "entries", ",", "symbols", "=", "None", ",", "callback", "=", "None", ",", "arch_mode", "=", "None", ")", ":", "# Set architecture in case it wasn't already set.", "if", "arch_mode", "is", "None", ":", "arch_mode", "="...
31.853659
23.073171
def nvmlDeviceGetViolationStatus(device, perfPolicyType): r""" /** * Gets the duration of time during which the device was throttled (lower than requested clocks) due to power * or thermal constraints. * * The method is important to users who are tying to understand if their GPUs throttle at...
[ "def", "nvmlDeviceGetViolationStatus", "(", "device", ",", "perfPolicyType", ")", ":", "c_perfPolicy_type", "=", "_nvmlPerfPolicyType_t", "(", "perfPolicyType", ")", "c_violTime", "=", "c_nvmlViolationTime_t", "(", ")", "fn", "=", "_nvmlGetFunctionPointer", "(", "\"nvml...
52.611111
36.638889
def start(self): # noqa (complexity) """Start the send & recv Threads. Start can be delayed to EG restore requestIds before attaching to the QAPI Note: This function waits for/blocks until amqplink connect(s) and the current sequence number has been obtained from the container (wi...
[ "def", "start", "(", "self", ")", ":", "# noqa (complexity)", "if", "not", "self", ".", "__end", ".", "is_set", "(", ")", ":", "return", "self", ".", "__end", ".", "clear", "(", ")", "try", ":", "self", ".", "__network_retry_queue", "=", "Queue", "(", ...
42.714286
20.877551
def commit(func): '''Used as a decorator for automatically making session commits''' def wrap(**kwarg): with session_withcommit() as session: a = func(**kwarg) session.add(a) return session.query(songs).order_by( songs.song_id.desc()).first().song_id retur...
[ "def", "commit", "(", "func", ")", ":", "def", "wrap", "(", "*", "*", "kwarg", ")", ":", "with", "session_withcommit", "(", ")", "as", "session", ":", "a", "=", "func", "(", "*", "*", "kwarg", ")", "session", ".", "add", "(", "a", ")", "return", ...
35.333333
15.555556
def search_all(self): '''a "show all" search that doesn't require a query''' # This should be your apis url for a search url = '...' # paginte get is what it sounds like, and what you want for multiple # pages of results results = self._paginate_get(url) if len(results) == 0: b...
[ "def", "search_all", "(", "self", ")", ":", "# This should be your apis url for a search", "url", "=", "'...'", "# paginte get is what it sounds like, and what you want for multiple", "# pages of results", "results", "=", "self", ".", "_paginate_get", "(", "url", ")", "if", ...
28.392857
21.607143
def vm_disk_snapshot_create(name, kwargs=None, call=None): ''' Takes a new snapshot of the disk image. .. versionadded:: 2016.3.0 name The name of the VM of which to take the snapshot. disk_id The ID of the disk to save. description The description for the snapshot. ...
[ "def", "vm_disk_snapshot_create", "(", "name", ",", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The vm_disk_snapshot_create action must be called with -a or --action.'", ")", "i...
27.37037
23.592593
def reset_api_key(self, user=None): """ Resets the API key for the specified user, or if no user is specified, for the current user. Returns the newly-created API key. Resetting an API key does not invalidate any authenticated sessions, nor does it revoke any tokens. """...
[ "def", "reset_api_key", "(", "self", ",", "user", "=", "None", ")", ":", "if", "user", "is", "None", ":", "user_id", "=", "utils", ".", "get_id", "(", "self", ")", "else", ":", "user_id", "=", "utils", ".", "get_id", "(", "user", ")", "uri", "=", ...
41.8125
16.6875
def make_i2c_rdwr_data(messages): """Utility function to create and return an i2c_rdwr_ioctl_data structure populated with a list of specified I2C messages. The messages parameter should be a list of tuples which represent the individual I2C messages to send in this transaction. Tuples should contain ...
[ "def", "make_i2c_rdwr_data", "(", "messages", ")", ":", "# Create message array and populate with provided data.", "msg_data_type", "=", "i2c_msg", "*", "len", "(", "messages", ")", "msg_data", "=", "msg_data_type", "(", ")", "for", "i", ",", "message", "in", "enume...
43.8
12.7
def get_content_modified_time(cls, abspath): """Returns the time that ``abspath`` was last modified. May be overridden in subclasses. Should return a `~datetime.datetime` object or None. """ stat_result = os.stat(abspath) modified = datetime.datetime.utcfromtimestamp( ...
[ "def", "get_content_modified_time", "(", "cls", ",", "abspath", ")", ":", "stat_result", "=", "os", ".", "stat", "(", "abspath", ")", "modified", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "stat_result", "[", "stat", ".", "ST_MTIME", "]"...
37.3
13.3
def tops(symbols=None, token='', version=''): '''TOPS provides IEX’s aggregated best quoted bid and offer position in near real time for all securities on IEX’s displayed limit order book. TOPS is ideal for developers needing both quote and trade data. https://iexcloud.io/docs/api/#tops Args: ...
[ "def", "tops", "(", "symbols", "=", "None", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "symbols", "=", "_strToList", "(", "symbols", ")", "if", "symbols", ":", "return", "_getJson", "(", "'tops?symbols='", "+", "','", ".", "join", ...
35.222222
25.555556
def dataframes(self): """ Returns a pandas DataFrame where each row is a representation of the Team class. Rows are indexed by the team abbreviation. """ frames = [] for team in self.__iter__(): frames.append(team.dataframe) return pd.concat(frames)
[ "def", "dataframes", "(", "self", ")", ":", "frames", "=", "[", "]", "for", "team", "in", "self", ".", "__iter__", "(", ")", ":", "frames", ".", "append", "(", "team", ".", "dataframe", ")", "return", "pd", ".", "concat", "(", "frames", ")" ]
34.333333
12.333333
def send_frame(self, cmd, headers=None, body=''): """ Encode and send a stomp frame through the underlying transport: :param str cmd: the protocol command :param dict headers: a map of headers to include in the frame :param body: the content of the message """ ...
[ "def", "send_frame", "(", "self", ",", "cmd", ",", "headers", "=", "None", ",", "body", "=", "''", ")", ":", "if", "cmd", "!=", "CMD_CONNECT", ":", "if", "headers", "is", "None", ":", "headers", "=", "{", "}", "self", ".", "_escape_headers", "(", "...
34.933333
8.933333
def request_param_update(self, complete_name): """ Request an update of the value for the supplied parameter. """ self.param_updater.request_param_update( self.toc.get_element_id(complete_name))
[ "def", "request_param_update", "(", "self", ",", "complete_name", ")", ":", "self", ".", "param_updater", ".", "request_param_update", "(", "self", ".", "toc", ".", "get_element_id", "(", "complete_name", ")", ")" ]
38.833333
8.5
def _stack_from_spec(self, spec, stack=(), seen_names=()): """ Return a tuple of ContextService parameter dictionaries corresponding to the connection described by `spec`, and any connection referenced by its `mitogen_via` or `become` fields. Each element is a dict of the form:: ...
[ "def", "_stack_from_spec", "(", "self", ",", "spec", ",", "stack", "=", "(", ")", ",", "seen_names", "=", "(", ")", ")", ":", "if", "spec", ".", "inventory_name", "(", ")", "in", "seen_names", ":", "raise", "ansible", ".", "errors", ".", "AnsibleConnec...
38.076923
19.115385
def in_coord_list(coord_list, coord, atol=1e-8): """ Tests if a particular coord is within a coord_list. Args: coord_list: List of coords to test coord: Specific coordinates atol: Absolute tolerance. Defaults to 1e-8. Accepts both scalar and array. Returns: ...
[ "def", "in_coord_list", "(", "coord_list", ",", "coord", ",", "atol", "=", "1e-8", ")", ":", "return", "len", "(", "find_in_coord_list", "(", "coord_list", ",", "coord", ",", "atol", "=", "atol", ")", ")", ">", "0" ]
29.928571
18.357143
def getIssuedBatchJobIDs(self): """ Gets the list of jobs issued to parasol in all results files, but not including jobs created by other users. """ issuedJobs = set() for resultsFile in itervalues(self.resultsFiles): issuedJobs.update(self.getJobIDsForResults...
[ "def", "getIssuedBatchJobIDs", "(", "self", ")", ":", "issuedJobs", "=", "set", "(", ")", "for", "resultsFile", "in", "itervalues", "(", "self", ".", "resultsFiles", ")", ":", "issuedJobs", ".", "update", "(", "self", ".", "getJobIDsForResultsFile", "(", "re...
36.2
18.2
def decode(image, symbols=None): """Decodes datamatrix barcodes in `image`. Args: image: `numpy.ndarray`, `PIL.Image` or tuple (pixels, width, height) symbols: iter(ZBarSymbol) the symbol types to decode; if `None`, uses `zbar`'s default behaviour, which is to decode all symbol type...
[ "def", "decode", "(", "image", ",", "symbols", "=", "None", ")", ":", "pixels", ",", "width", ",", "height", "=", "_pixel_data", "(", "image", ")", "results", "=", "[", "]", "with", "_image_scanner", "(", ")", "as", "scanner", ":", "if", "symbols", "...
40.219512
21.512195
def evaluate_inline_tail(self, groups): """Evaluate inline comments at the tail of source code.""" if self.lines: self.line_comments.append([groups['line'][2:].replace('\\\n', ''), self.line_num, self.current_encoding])
[ "def", "evaluate_inline_tail", "(", "self", ",", "groups", ")", ":", "if", "self", ".", "lines", ":", "self", ".", "line_comments", ".", "append", "(", "[", "groups", "[", "'line'", "]", "[", "2", ":", "]", ".", "replace", "(", "'\\\\\\n'", ",", "''"...
48.8
27.2
def run(self): """Build modules, packages, and copy data files to build directory""" if not self.py_modules and not self.packages: return if self.py_modules: self.build_modules() if self.packages: self.build_packages() self.build_package_...
[ "def", "run", "(", "self", ")", ":", "if", "not", "self", ".", "py_modules", "and", "not", "self", ".", "packages", ":", "return", "if", "self", ".", "py_modules", ":", "self", ".", "build_modules", "(", ")", "if", "self", ".", "packages", ":", "self...
34.105263
20.263158
def set_variant(self, identity, experiment_name, variant_name): """ Set the variant for a specific user. :param identity a unique user identifier :param experiment_name the string name of the experiment :param variant_name the string name of the variant """ try: ...
[ "def", "set_variant", "(", "self", ",", "identity", ",", "experiment_name", ",", "variant_name", ")", ":", "try", ":", "experiment", "=", "model", ".", "Experiment", ".", "get_by", "(", "name", "=", "experiment_name", ")", "variant", "=", "model", ".", "Va...
40.708333
15.708333
def get_nameday(self, month=None, day=None): """Return name(s) as a string based on given date and month. If no arguments given, use current date""" if month is None: month = datetime.now().month if day is None: day = datetime.now().day return self.NAMEDAY...
[ "def", "get_nameday", "(", "self", ",", "month", "=", "None", ",", "day", "=", "None", ")", ":", "if", "month", "is", "None", ":", "month", "=", "datetime", ".", "now", "(", ")", ".", "month", "if", "day", "is", "None", ":", "day", "=", "datetime...
41.25
5.5
def get_setting(setting): """ Get the specified django setting, or it's default value """ defaults = { # The context to use for rendering fields 'TEMPLATE_FIELD_CONTEXT': {}, # When this is False, don't do any TemplateField rendering 'TEMPLATE_FIELD_RENDER': True } try: ...
[ "def", "get_setting", "(", "setting", ")", ":", "defaults", "=", "{", "# The context to use for rendering fields", "'TEMPLATE_FIELD_CONTEXT'", ":", "{", "}", ",", "# When this is False, don't do any TemplateField rendering", "'TEMPLATE_FIELD_RENDER'", ":", "True", "}", "try",...
38.307692
16.692308
def long_description(): """ Collates project README and latest changes. """ changes = latest_changes() changes[0] = "`Changes for v{}".format(changes[0][1:]) changes[1] = '-' * len(changes[0]) return "\n\n\n".join([ read_file('README.rst'), '\n'.join(changes), "`Full changelo...
[ "def", "long_description", "(", ")", ":", "changes", "=", "latest_changes", "(", ")", "changes", "[", "0", "]", "=", "\"`Changes for v{}\"", ".", "format", "(", "changes", "[", "0", "]", "[", "1", ":", "]", ")", "changes", "[", "1", "]", "=", "'-'", ...
39.8
12.7
def find_customer(cls, session, mailbox, customer): """Return conversations for a specific customer in a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox to search. customer (helpscout.models.Custo...
[ "def", "find_customer", "(", "cls", ",", "session", ",", "mailbox", ",", "customer", ")", ":", "return", "cls", "(", "'/mailboxes/%d/customers/%s/conversations.json'", "%", "(", "mailbox", ".", "id", ",", "customer", ".", "id", ",", ")", ",", "session", "=",...
36.333333
21
def _download(self, videofile): """ 调用 SubSearcher 搜索并下载字幕 """ basename = os.path.basename(videofile) subinfos = [] for subsearcher in self.subsearcher: self.logger.info( '{0}:开始使用 {1} 搜索字幕'.format(basename, subsearcher)) try: ...
[ "def", "_download", "(", "self", ",", "videofile", ")", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "videofile", ")", "subinfos", "=", "[", "]", "for", "subsearcher", "in", "self", ".", "subsearcher", ":", "self", ".", "logger", ".",...
41.047619
15.214286
def show_open_file_dialog(filetypes): """ Show an open file dialog and return the path of the file selected. Parameters ---------- filetypes : list of tuples Types of file to show on the dialog. Each tuple on the list must have two elements associated with a filetype: the first elem...
[ "def", "show_open_file_dialog", "(", "filetypes", ")", ":", "# The following line is used to Tk's main window is not shown", "Tk", "(", ")", ".", "withdraw", "(", ")", "# OSX ONLY: Call bash script to prevent file select window from sticking", "# after use.", "if", "platform", "....
33.878788
24.121212
def handleMessage(self, lmsg): """Implements the LLRP client state machine.""" logger.debug('LLRPMessage received in state %s: %s', self.state, lmsg) msgName = lmsg.getName() lmsg.proto = self lmsg.peername = self.peername # call per-message callbacks logger.debu...
[ "def", "handleMessage", "(", "self", ",", "lmsg", ")", ":", "logger", ".", "debug", "(", "'LLRPMessage received in state %s: %s'", ",", "self", ".", "state", ",", "lmsg", ")", "msgName", "=", "lmsg", ".", "getName", "(", ")", "lmsg", ".", "proto", "=", "...
43.859589
23.136986
def add_tmpltbank_from_xml_table(self, sngl_table, vary_fupper=False): """ This function will take a sngl_inspiral_table of templates and add them into the partitioned template bank object. Parameters ----------- sngl_table : sngl_inspiral_table List of sngl_...
[ "def", "add_tmpltbank_from_xml_table", "(", "self", ",", "sngl_table", ",", "vary_fupper", "=", "False", ")", ":", "for", "sngl", "in", "sngl_table", ":", "self", ".", "add_point_by_masses", "(", "sngl", ".", "mass1", ",", "sngl", ".", "mass2", ",", "sngl", ...
42.8125
19.5625
def geom_symm_match(g, atwts, ax, theta, do_refl): """ [Revised match factor calculation] .. todo:: Complete geom_symm_match docstring """ # Imports import numpy as np from scipy import linalg as spla # Convert g and atwts to n-D vectors g = make_nd_vec(g, nd=None, t=np.float64, norm...
[ "def", "geom_symm_match", "(", "g", ",", "atwts", ",", "ax", ",", "theta", ",", "do_refl", ")", ":", "# Imports", "import", "numpy", "as", "np", "from", "scipy", "import", "linalg", "as", "spla", "# Convert g and atwts to n-D vectors", "g", "=", "make_nd_vec",...
35.192308
21.641026
def load_data(self, filename, *args, **kwargs): """ load data from text file. :param filename: name of file to read :type filename: str :returns: data read from file using :func:`numpy.genfromtxt` :rtype: dict :raises: :exc:`~simkit.core.exceptions.UnnamedDataErr...
[ "def", "load_data", "(", "self", ",", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# header keys", "header_param", "=", "self", ".", "parameters", ".", "get", "(", "'header'", ")", "# default is None", "# data keys", "data_param", "=", ...
48.023256
19.883721
def is_beating(self): """Is the heartbeat running and responsive (and not paused).""" if self.is_alive() and not self._pause and self._beating: return True else: return False
[ "def", "is_beating", "(", "self", ")", ":", "if", "self", ".", "is_alive", "(", ")", "and", "not", "self", ".", "_pause", "and", "self", ".", "_beating", ":", "return", "True", "else", ":", "return", "False" ]
36.166667
17.333333
def getTransitionMatrix(self,probabilities=True): """ If self.P has been given already, we will reuse it and convert it to a sparse csr matrix if needed. Otherwise, we will generate it using the direct or indirect method. Since most solution methods use a probability matrix, thi...
[ "def", "getTransitionMatrix", "(", "self", ",", "probabilities", "=", "True", ")", ":", "if", "self", ".", "P", "is", "not", "None", ":", "if", "isspmatrix", "(", "self", ".", "P", ")", ":", "if", "not", "isspmatrix_csr", "(", "self", ".", "P", ")", ...
45.37037
25.814815
def orient_directed_graph(self, data, graph): """Run the algorithm on a directed_graph. Args: data (pandas.DataFrame): DataFrame containing the data graph (networkx.DiGraph): Skeleton of the graph to orient Returns: networkx.DiGraph: Solution on the given sk...
[ "def", "orient_directed_graph", "(", "self", ",", "data", ",", "graph", ")", ":", "warnings", ".", "warn", "(", "\"The algorithm is ran on the skeleton of the given graph.\"", ")", "return", "self", ".", "orient_undirected_graph", "(", "data", ",", "nx", ".", "Graph...
35.25
25.375
def as_create_table(self, table_name, overwrite=False): """Reformats the query into the create table as query. Works only for the single select SQL statements, in all other cases the sql query is not modified. :param superset_query: string, sql query that will be executed :param...
[ "def", "as_create_table", "(", "self", ",", "table_name", ",", "overwrite", "=", "False", ")", ":", "exec_sql", "=", "''", "sql", "=", "self", ".", "stripped", "(", ")", "if", "overwrite", ":", "exec_sql", "=", "f'DROP TABLE IF EXISTS {table_name};\\n'", "exec...
43.529412
18.176471
def load(obj, env=None, silent=True, key=None, filename=None): """ Reads and loads in to "obj" a single key or all keys from source file. :param obj: the settings instance :param env: settings current env default='development' :param silent: if errors should raise :param key: if defined load a ...
[ "def", "load", "(", "obj", ",", "env", "=", "None", ",", "silent", "=", "True", ",", "key", "=", "None", ",", "filename", "=", "None", ")", ":", "if", "ConfigObj", "is", "None", ":", "# pragma: no cover", "BaseLoader", ".", "warn_not_installed", "(", "...
35.166667
18.916667
def set_replay(self, sess, replay): """Changes the current replay setting on the graph.""" sess.run(self._set_replay, {self._set_replay_ph: replay})
[ "def", "set_replay", "(", "self", ",", "sess", ",", "replay", ")", ":", "sess", ".", "run", "(", "self", ".", "_set_replay", ",", "{", "self", ".", "_set_replay_ph", ":", "replay", "}", ")" ]
51.333333
8.666667
def create_non_data_file(self, params, file_data): ''' Creates a new file-based dataset with the name provided in the files tuple. A valid file input would be: files = ( {'file': ("gtfs2", open('myfile.zip', 'rb'))} ) ''' api_prefix = '/api/imports2/'...
[ "def", "create_non_data_file", "(", "self", ",", "params", ",", "file_data", ")", ":", "api_prefix", "=", "'/api/imports2/'", "if", "not", "params", ".", "get", "(", "'method'", ",", "None", ")", ":", "params", "[", "'method'", "]", "=", "'blob'", "return"...
34.214286
22.5
def find_nuc_indel(gapped_seq, indel_seq): """ This function finds the entire indel missing in from a gapped sequence compared to the indel_seqeunce. It is assumes that the sequences start with the first position of the gap. """ ref_indel = indel_seq[0] for j in range(1,len(gapped_seq)): ...
[ "def", "find_nuc_indel", "(", "gapped_seq", ",", "indel_seq", ")", ":", "ref_indel", "=", "indel_seq", "[", "0", "]", "for", "j", "in", "range", "(", "1", ",", "len", "(", "gapped_seq", ")", ")", ":", "if", "gapped_seq", "[", "j", "]", "==", "\"-\"",...
33
12.846154
def init(ffi, lib): """Return RingBuffer class using the given CFFI instance.""" class RingBuffer(_RingBufferBase): __doc__ = _RingBufferBase.__doc__ _ffi = ffi _lib = lib return RingBuffer
[ "def", "init", "(", "ffi", ",", "lib", ")", ":", "class", "RingBuffer", "(", "_RingBufferBase", ")", ":", "__doc__", "=", "_RingBufferBase", ".", "__doc__", "_ffi", "=", "ffi", "_lib", "=", "lib", "return", "RingBuffer" ]
24.333333
18.555556
def _replace_layer(self, layer_id, new_layer): """Replace the layer with a new layer.""" old_layer = self.layer_list[layer_id] new_layer.input = old_layer.input new_layer.output = old_layer.output new_layer.output.shape = new_layer.output_shape self.layer_list[layer_id] =...
[ "def", "_replace_layer", "(", "self", ",", "layer_id", ",", "new_layer", ")", ":", "old_layer", "=", "self", ".", "layer_list", "[", "layer_id", "]", "new_layer", ".", "input", "=", "old_layer", ".", "input", "new_layer", ".", "output", "=", "old_layer", "...
45.444444
4.666667
def bind_proxy(values, category=None, field=None, verbose_name=None, help_text='', static=True, readonly=False): """Binds PrefProxy objects to module variables used by apps as preferences. :param list|tuple values: Preference values. :param str|unicode category: Category name the preference belongs to. ...
[ "def", "bind_proxy", "(", "values", ",", "category", "=", "None", ",", "field", "=", "None", ",", "verbose_name", "=", "None", ",", "help_text", "=", "''", ",", "static", "=", "True", ",", "readonly", "=", "False", ")", ":", "addrs", "=", "OrderedDict"...
30.095238
24.15873
def get_config_path(): """Returns the absolute path the the Cloud SDK's configuration directory. Returns: str: The Cloud SDK config path. """ # If the path is explicitly set, return that. try: return os.environ[environment_vars.CLOUD_SDK_CONFIG_DIR] except KeyError: pass...
[ "def", "get_config_path", "(", ")", ":", "# If the path is explicitly set, return that.", "try", ":", "return", "os", ".", "environ", "[", "environment_vars", ".", "CLOUD_SDK_CONFIG_DIR", "]", "except", "KeyError", ":", "pass", "# Non-windows systems store this at ~/.config...
34.607143
18.25
def determine_scale(scale, img, mark): """ Scales an image using a specified ratio, 'F' or 'R'. If `scale` is 'F', the image is scaled to be as big as possible to fit in `img` without falling off the edges. If `scale` is 'R', the watermark resizes to a percentage of minimum size of source image. R...
[ "def", "determine_scale", "(", "scale", ",", "img", ",", "mark", ")", ":", "if", "scale", ":", "try", ":", "scale", "=", "float", "(", "scale", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "pass", "if", "isinstance", "(", "scale", ",...
40.95122
21.731707
def trail(self): """ Get all visitors by IP and then list the pages they visited in order. """ inner = (self.get_query() .select(PageView.ip, PageView.url) .order_by(PageView.timestamp)) return (PageView .select( ...
[ "def", "trail", "(", "self", ")", ":", "inner", "=", "(", "self", ".", "get_query", "(", ")", ".", "select", "(", "PageView", ".", "ip", ",", "PageView", ".", "url", ")", ".", "order_by", "(", "PageView", ".", "timestamp", ")", ")", "return", "(", ...
35.923077
11.461538
def destroy_iam(app='', env='dev', **_): """Destroy IAM Resources. Args: app (str): Spinnaker Application name. env (str): Deployment environment, i.e. dev, stage, prod. Returns: True upon successful completion. """ session = boto3.Session(profile_name=env) client = ses...
[ "def", "destroy_iam", "(", "app", "=", "''", ",", "env", "=", "'dev'", ",", "*", "*", "_", ")", ":", "session", "=", "boto3", ".", "Session", "(", "profile_name", "=", "env", ")", "client", "=", "session", ".", "client", "(", "'iam'", ")", "generat...
35.123457
19.074074
def _republish(self): """ Re-publishes updated message """ mq_channel = self.channel._connect_mq() mq_channel.basic_publish(exchange=self.channel.key, routing_key='', body=json.dumps(self.serialize()))
[ "def", "_republish", "(", "self", ")", ":", "mq_channel", "=", "self", ".", "channel", ".", "_connect_mq", "(", ")", "mq_channel", ".", "basic_publish", "(", "exchange", "=", "self", ".", "channel", ".", "key", ",", "routing_key", "=", "''", ",", "body",...
38.285714
13.142857
def main(): """ NAME di_tilt.py DESCRIPTION rotates geographic coordinate dec, inc data to stratigraphic coordinates using the dip and dip direction (strike+90, dip if dip to right of strike) INPUT FORMAT declination inclination dip_direction dip SYNTAX di_til...
[ "def", "main", "(", ")", ":", "if", "'-h'", "in", "sys", ".", "argv", ":", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "if", "'-F'", "in", "sys", ".", "argv", ":", "ind", "=", "sys", ".", "argv", ".", "index", "("...
29.035088
19.263158
def or_having(self, column, operator=None, value=None): """ Add a "having" clause to the query :param column: The column :type column: str :param operator: The having clause operator :type operator: str :param value: The having clause value :type value:...
[ "def", "or_having", "(", "self", ",", "column", ",", "operator", "=", "None", ",", "value", "=", "None", ")", ":", "return", "self", ".", "having", "(", "column", ",", "operator", ",", "value", ",", "'or'", ")" ]
27.117647
16.529412
def cooccurrence(corpus_or_featureset, featureset_name=None, min_weight=1, edge_attrs=['ayjid', 'date'], filter=None): """ A network of feature elements linked by their joint occurrence in papers. """ if not filter: filter = lambda f, v, c, dc: dc >= min_weight...
[ "def", "cooccurrence", "(", "corpus_or_featureset", ",", "featureset_name", "=", "None", ",", "min_weight", "=", "1", ",", "edge_attrs", "=", "[", "'ayjid'", ",", "'date'", "]", ",", "filter", "=", "None", ")", ":", "if", "not", "filter", ":", "filter", ...
37.872727
22.6
def split_func_name_args_params_handle(tokens): """Process splitting a function into name, params, and args.""" internal_assert(len(tokens) == 2, "invalid function definition splitting tokens", tokens) func_name = tokens[0] func_args = [] func_params = [] for arg in tokens[1]: if len(arg...
[ "def", "split_func_name_args_params_handle", "(", "tokens", ")", ":", "internal_assert", "(", "len", "(", "tokens", ")", "==", "2", ",", "\"invalid function definition splitting tokens\"", ",", "tokens", ")", "func_name", "=", "tokens", "[", "0", "]", "func_args", ...
34.764706
15.411765
def setup(api=None): """Sets up and fills test directory for serving. Using different filetypes to see how they are dealt with. The tempoary directory will clean itself up. """ global tmp_dir_object tmp_dir_object = tempfile.TemporaryDirectory() dir_name = tmp_dir_object.name dir_a =...
[ "def", "setup", "(", "api", "=", "None", ")", ":", "global", "tmp_dir_object", "tmp_dir_object", "=", "tempfile", ".", "TemporaryDirectory", "(", ")", "dir_name", "=", "tmp_dir_object", ".", "name", "dir_a", "=", "os", ".", "path", ".", "join", "(", "dir_n...
36.243243
24.243243
def _handle_tag_definefontalignzones(self): """Handle the DefineFontAlignZones tag.""" obj = _make_object("DefineFontAlignZones") obj.FontId = unpack_ui16(self._src) bc = BitConsumer(self._src) obj.CSMTableHint = bc.u_get(2) obj.Reserved = bc.u_get(6) obj.ZoneTab...
[ "def", "_handle_tag_definefontalignzones", "(", "self", ")", ":", "obj", "=", "_make_object", "(", "\"DefineFontAlignZones\"", ")", "obj", ".", "FontId", "=", "unpack_ui16", "(", "self", ".", "_src", ")", "bc", "=", "BitConsumer", "(", "self", ".", "_src", "...
44.576923
10.346154
async def create( cls, start_ip: str, end_ip: str, *, type: IPRangeType = IPRangeType.RESERVED, comment: str = None, subnet: Union[Subnet, int] = None): """ Create a `IPRange` in MAAS. :param start_ip: First IP address in the range (required). :type s...
[ "async", "def", "create", "(", "cls", ",", "start_ip", ":", "str", ",", "end_ip", ":", "str", ",", "*", ",", "type", ":", "IPRangeType", "=", "IPRangeType", ".", "RESERVED", ",", "comment", ":", "str", "=", "None", ",", "subnet", ":", "Union", "[", ...
38.181818
13.818182
def check_git_unchanged(filename, yes=False): """Check git to avoid overwriting user changes.""" if check_staged(filename): s = 'There are staged changes in {}, overwrite? [y/n] '.format(filename) if yes or input(s) in ('y', 'yes'): return else: raise RuntimeError...
[ "def", "check_git_unchanged", "(", "filename", ",", "yes", "=", "False", ")", ":", "if", "check_staged", "(", "filename", ")", ":", "s", "=", "'There are staged changes in {}, overwrite? [y/n] '", ".", "format", "(", "filename", ")", "if", "yes", "or", "input", ...
45.1875
18.8125
def tokenize_math(text): r"""Prevents math from being tokenized. :param Buffer text: iterator over line, with current position >>> b = Buffer(r'$\min_x$ \command') >>> tokenize_math(b) '$' >>> b = Buffer(r'$$\min_x$$ \command') >>> tokenize_math(b) '$$' """ if text.startswith('...
[ "def", "tokenize_math", "(", "text", ")", ":", "if", "text", ".", "startswith", "(", "'$'", ")", "and", "(", "text", ".", "position", "==", "0", "or", "text", ".", "peek", "(", "-", "1", ")", "!=", "'\\\\'", "or", "text", ".", "endswith", "(", "r...
32.75
19.625
def generate_ngrams(args, parser): """Adds n-grams data to the data store.""" store = utils.get_data_store(args) corpus = utils.get_corpus(args) if args.catalogue: catalogue = utils.get_catalogue(args) else: catalogue = None store.add_ngrams(corpus, args.min_size, args.max_size, ...
[ "def", "generate_ngrams", "(", "args", ",", "parser", ")", ":", "store", "=", "utils", ".", "get_data_store", "(", "args", ")", "corpus", "=", "utils", ".", "get_corpus", "(", "args", ")", "if", "args", ".", "catalogue", ":", "catalogue", "=", "utils", ...
35.777778
12.444444
def validate(self): """ Validate that this instance matches its schema. """ schema = Schema(self.__class__.SCHEMA) resolver = RefResolver.from_schema( schema, store=REGISTRY, ) validate(self, schema, resolver=resolver)
[ "def", "validate", "(", "self", ")", ":", "schema", "=", "Schema", "(", "self", ".", "__class__", ".", "SCHEMA", ")", "resolver", "=", "RefResolver", ".", "from_schema", "(", "schema", ",", "store", "=", "REGISTRY", ",", ")", "validate", "(", "self", "...
26.272727
14.454545
def capitalize(text): """ Capitalizes the word using the normal string capitalization method, however if the word contains only capital letters and numbers, then it will not be affected. :param text | <str> :return <str> """ text = nativestring(t...
[ "def", "capitalize", "(", "text", ")", ":", "text", "=", "nativestring", "(", "text", ")", "if", "EXPR_CAPITALS", ".", "match", "(", "text", ")", ":", "return", "text", "return", "text", ".", "capitalize", "(", ")" ]
28.142857
15.857143
def _compute_radii(self): """Generate RBF radii""" # use supplied radii if present radii = self._get_user_components('radii') # compute radii if (radii is None): centers = self.components_['centers'] n_centers = centers.shape[0] max_dist = n...
[ "def", "_compute_radii", "(", "self", ")", ":", "# use supplied radii if present", "radii", "=", "self", ".", "_get_user_components", "(", "'radii'", ")", "# compute radii", "if", "(", "radii", "is", "None", ")", ":", "centers", "=", "self", ".", "components_", ...
30.333333
18.333333
def __get_wiki_review(email_cnt, idx): ''' Review for wikis. ''' recent_posts = MWiki.query_recent_edited(tools.timestamp() - TIME_LIMIT, kind='2') for recent_post in recent_posts: hist_rec = MWikiHist.get_last(recent_post.uid) if hist_rec: foo_str = ''' ...
[ "def", "__get_wiki_review", "(", "email_cnt", ",", "idx", ")", ":", "recent_posts", "=", "MWiki", ".", "query_recent_edited", "(", "tools", ".", "timestamp", "(", ")", "-", "TIME_LIMIT", ",", "kind", "=", "'2'", ")", "for", "recent_post", "in", "recent_posts...
47
24
def _open_script_interface(self, connection_id, callback): """Enable script streaming interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callba...
[ "def", "_open_script_interface", "(", "self", ",", "connection_id", ",", "callback", ")", ":", "try", ":", "context", "=", "self", ".", "connections", ".", "get_context", "(", "connection_id", ")", "except", "ArgumentError", ":", "callback", "(", "connection_id"...
39.666667
26.809524
def connectivity(measure_names, b, c=None, nfft=512): """Calculate connectivity measures. Parameters ---------- measure_names : str or list of str Name(s) of the connectivity measure(s) to calculate. See :class:`Connectivity` for supported measures. b : array, shape (n_channels, n_c...
[ "def", "connectivity", "(", "measure_names", ",", "b", ",", "c", "=", "None", ",", "nfft", "=", "512", ")", ":", "con", "=", "Connectivity", "(", "b", ",", "c", ",", "nfft", ")", "try", ":", "return", "getattr", "(", "con", ",", "measure_names", ")...
38.375
23.375
async def remove_tracks(self, playlist, *tracks): """Remove one or more tracks from a user’s playlist. Parameters ---------- playlist : Union[str, Playlist] The playlist to modify tracks : Sequence[Union[str, Track]] Tracks to remove from the playlist ...
[ "async", "def", "remove_tracks", "(", "self", ",", "playlist", ",", "*", "tracks", ")", ":", "tracks", "=", "[", "str", "(", "track", ")", "for", "track", "in", "tracks", "]", "data", "=", "await", "self", ".", "http", ".", "remove_playlist_tracks", "(...
33.5
16.444444
def is_cp(self, atol=None, rtol=None): """Test if Choi-matrix is completely-positive (CP)""" choi = _to_choi(self.rep, self._data, *self.dim) return self._is_cp_helper(choi, atol, rtol)
[ "def", "is_cp", "(", "self", ",", "atol", "=", "None", ",", "rtol", "=", "None", ")", ":", "choi", "=", "_to_choi", "(", "self", ".", "rep", ",", "self", ".", "_data", ",", "*", "self", ".", "dim", ")", "return", "self", ".", "_is_cp_helper", "("...
51.5
7.25
def execute_all(self): """ Execute all workflows """ for workflow_id in self.workflows: if self.workflows[workflow_id].online: for interval in self.workflows[workflow_id].requested_intervals: logging.info("Executing workflow {} over interva...
[ "def", "execute_all", "(", "self", ")", ":", "for", "workflow_id", "in", "self", ".", "workflows", ":", "if", "self", ".", "workflows", "[", "workflow_id", "]", ".", "online", ":", "for", "interval", "in", "self", ".", "workflows", "[", "workflow_id", "]...
46
18.888889
def clusters(points, radius): """ Find clusters of points which have neighbours closer than radius Parameters --------- points : (n, d) float Points of dimension d radius : float Max distance between points in a cluster Returns ---------- groups : (m,) sequence of i...
[ "def", "clusters", "(", "points", ",", "radius", ")", ":", "from", ".", "import", "graph", "tree", "=", "cKDTree", "(", "points", ")", "# some versions return pairs as a set of tuples", "pairs", "=", "tree", ".", "query_pairs", "(", "r", "=", "radius", ",", ...
23.461538
19.692308
def findspans(self, type,set=None): """Yields span annotation elements of the specified type that include this word. Arguments: type: The annotation type, can be passed as using any of the :class:`AnnotationType` member, or by passing the relevant :class:`AbstractSpanAnnotation` or :class:`...
[ "def", "findspans", "(", "self", ",", "type", ",", "set", "=", "None", ")", ":", "if", "issubclass", "(", "type", ",", "AbstractAnnotationLayer", ")", ":", "layerclass", "=", "type", "else", ":", "layerclass", "=", "ANNOTATIONTYPE2LAYERCLASS", "[", "type", ...
44.75
27.888889
def request_client_list(self, req, msg): """Request the list of connected clients. The list of clients is sent as a sequence of #client-list informs. Informs ------- addr : str The address of the client as host:port with host in dotted quad notation. If ...
[ "def", "request_client_list", "(", "self", ",", "req", ",", "msg", ")", ":", "# TODO Get list of ClientConnection* instances and implement a standard", "# 'address-print' method in the ClientConnection class", "clients", "=", "self", ".", "_client_conns", "num_clients", "=", "l...
32.189189
21.756757
def targets(tgt, tgt_type='glob', **kwargs): # pylint: disable=W0613 ''' Return the targets from the Salt Masters' minion cache. All targets and matchers are supported. The resulting roster can be configured using ``roster_order`` and ``roster_default``. ''' minions = salt.utils.minions.CkMini...
[ "def", "targets", "(", "tgt", ",", "tgt_type", "=", "'glob'", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "minions", "=", "salt", ".", "utils", ".", "minions", ".", "CkMinions", "(", "__opts__", ")", "_res", "=", "minions", ".", "check_...
30.106383
23
def _do_perform_delete_on_model(self): """ Perform the actual delete query on this model instance. """ if self._force_deleting: return self.with_trashed().where(self.get_key_name(), self.get_key()).force_delete() return self._run_soft_delete()
[ "def", "_do_perform_delete_on_model", "(", "self", ")", ":", "if", "self", ".", "_force_deleting", ":", "return", "self", ".", "with_trashed", "(", ")", ".", "where", "(", "self", ".", "get_key_name", "(", ")", ",", "self", ".", "get_key", "(", ")", ")",...
36.125
16.375
def inspect(self, nids=None, wslice=None, **kwargs): """ Inspect the tasks (SCF iterations, Structural relaxation ...) and produces matplotlib plots. Args: nids: List of node identifiers. wslice: Slice object used to select works. kwargs: keyword argu...
[ "def", "inspect", "(", "self", ",", "nids", "=", "None", ",", "wslice", "=", "None", ",", "*", "*", "kwargs", ")", ":", "figs", "=", "[", "]", "for", "task", "in", "self", ".", "select_tasks", "(", "nids", "=", "nids", ",", "wslice", "=", "wslice...
33.833333
21.033333
def print_new(ctx, name, migration_type): """Prints filename of a new migration""" click.echo(ctx.obj.repository.generate_migration_name(name, migration_type))
[ "def", "print_new", "(", "ctx", ",", "name", ",", "migration_type", ")", ":", "click", ".", "echo", "(", "ctx", ".", "obj", ".", "repository", ".", "generate_migration_name", "(", "name", ",", "migration_type", ")", ")" ]
55
13.666667
def download_structure(inputpdbid): """Given a PDB ID, downloads the corresponding PDB structure. Checks for validity of ID and handles error while downloading. Returns the path of the downloaded file.""" try: if len(inputpdbid) != 4 or extract_pdbid(inputpdbid.lower()) == 'UnknownProtein': ...
[ "def", "download_structure", "(", "inputpdbid", ")", ":", "try", ":", "if", "len", "(", "inputpdbid", ")", "!=", "4", "or", "extract_pdbid", "(", "inputpdbid", ".", "lower", "(", ")", ")", "==", "'UnknownProtein'", ":", "sysexit", "(", "3", ",", "'Invali...
49.647059
19.882353
def cutadapt_length_trimmed_plot (self): """ Generate the trimming length plot """ description = 'This plot shows the number of reads with certain lengths of adapter trimmed. \n\ Obs/Exp shows the raw counts divided by the number expected due to sequencing errors. A defined peak \n\ may...
[ "def", "cutadapt_length_trimmed_plot", "(", "self", ")", ":", "description", "=", "'This plot shows the number of reads with certain lengths of adapter trimmed. \\n\\\n Obs/Exp shows the raw counts divided by the number expected due to sequencing errors. A defined peak \\n\\\n may be r...
47.84
28.6
def main(name, output, font): """ Easily bootstrap an OS project to fool HR departments and pad your resume. """ # The path of the directory where the final files will end up in bootstrapped_directory = os.getcwd() + os.sep + name.lower().replace(' ', '-') + os.sep # Copy the template files to the ta...
[ "def", "main", "(", "name", ",", "output", ",", "font", ")", ":", "# The path of the directory where the final files will end up in", "bootstrapped_directory", "=", "os", ".", "getcwd", "(", ")", "+", "os", ".", "sep", "+", "name", ".", "lower", "(", ")", ".",...
48.846154
33.769231