text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def publish(build): """ publish the package itself """ build.packages.install("wheel") build.packages.install("twine") build.executables.run([ "python", "setup.py", "sdist", "bdist_wheel", "--universal", "--release" ]) build.executables.run([ "twine", "upload", "dist/*" ...
[ "def", "publish", "(", "build", ")", ":", "build", ".", "packages", ".", "install", "(", "\"wheel\"", ")", "build", ".", "packages", ".", "install", "(", "\"twine\"", ")", "build", ".", "executables", ".", "run", "(", "[", "\"python\"", ",", "\"setup.py\...
28.636364
14.454545
def CompileReport(self, mediator): """Compiles an analysis report. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. Returns: AnalysisReport: the analysis report. """ lines_of_text = ['Listing do...
[ "def", "CompileReport", "(", "self", ",", "mediator", ")", ":", "lines_of_text", "=", "[", "'Listing domains visited by all users'", "]", "for", "domain", "in", "sorted", "(", "self", ".", "_domains", ")", ":", "lines_of_text", ".", "append", "(", "domain", ")...
32.705882
18.823529
def clean_locals(data): """ Clean up locals dict, remove empty and self/session/params params and convert to camelCase. :param {} data: locals dicts from a function. :returns: dict """ if data.get('params') is not None: return data.get('params') else: return { ...
[ "def", "clean_locals", "(", "data", ")", ":", "if", "data", ".", "get", "(", "'params'", ")", "is", "not", "None", ":", "return", "data", ".", "get", "(", "'params'", ")", "else", ":", "return", "{", "to_camel_case", "(", "k", ")", ":", "v", "for",...
29.933333
19
def main(sample_id, fastq_pair, max_len, kmer, clear): """Main executor of the spades template. Parameters ---------- sample_id : str Sample Identification string. fastq_pair : list Two element list containing the paired FastQ files. max_len : int Maximum read length. Th...
[ "def", "main", "(", "sample_id", ",", "fastq_pair", ",", "max_len", ",", "kmer", ",", "clear", ")", ":", "logger", ".", "info", "(", "\"Starting spades\"", ")", "logger", ".", "info", "(", "\"Setting SPAdes kmers\"", ")", "kmers", "=", "set_kmers", "(", "k...
29.569767
22.348837
def add_vq(self, parser): ''' Add verbose & quiet options ''' group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true")
[ "def", "add_vq", "(", "self", ",", "parser", ")", ":", "group", "=", "parser", ".", "add_mutually_exclusive_group", "(", ")", "group", ".", "add_argument", "(", "\"-v\"", ",", "\"--verbose\"", ",", "action", "=", "\"store_true\"", ")", "group", ".", "add_arg...
50.2
16.2
def get_fd_from_final_mass_spin(template=None, distance=None, **kwargs): """Return frequency domain ringdown with all the modes specified. Parameters ---------- template: object An object that has attached properties. This can be used to substitute for keyword arguments. A common exampl...
[ "def", "get_fd_from_final_mass_spin", "(", "template", "=", "None", ",", "distance", "=", "None", ",", "*", "*", "kwargs", ")", ":", "input_params", "=", "props", "(", "template", ",", "mass_spin_required_args", ",", "*", "*", "kwargs", ")", "# Get required ar...
43.663043
21.097826
def get_cached_output(self, placeholder_name, instance): """ .. versionadded:: 0.9 Return the cached output for a rendered item, or ``None`` if no output is cached. This method can be overwritten to implement custom caching mechanisms. By default, this function generate...
[ "def", "get_cached_output", "(", "self", ",", "placeholder_name", ",", "instance", ")", ":", "cachekey", "=", "self", ".", "get_output_cache_key", "(", "placeholder_name", ",", "instance", ")", "return", "cache", ".", "get", "(", "cachekey", ")" ]
52.363636
28
def _createConnection(self, connections): """ Create GSSHAPY Connection Objects Method """ for c in connections: # Create GSSHAPY Connection object connection = Connection(slinkNumber=c['slinkNumber'], upSjuncNumber=c['upSjunc'...
[ "def", "_createConnection", "(", "self", ",", "connections", ")", ":", "for", "c", "in", "connections", ":", "# Create GSSHAPY Connection object", "connection", "=", "Connection", "(", "slinkNumber", "=", "c", "[", "'slinkNumber'", "]", ",", "upSjuncNumber", "=", ...
37.769231
16.230769
def send_request(self, request): """Send request and store response in self.url_connection.""" # throttle the number of requests to each host self.aggregate.wait_for_host(self.urlparts[1]) kwargs = self.get_request_kwargs() kwargs["allow_redirects"] = False self._send_req...
[ "def", "send_request", "(", "self", ",", "request", ")", ":", "# throttle the number of requests to each host", "self", ".", "aggregate", ".", "wait_for_host", "(", "self", ".", "urlparts", "[", "1", "]", ")", "kwargs", "=", "self", ".", "get_request_kwargs", "(...
48.142857
6.285714
def _fill_row_holes(self): ''' Fill any remaining row title cells that are empty. This must be done after the other passes to avoid preemptively filling in empty cells reserved for other operations. ''' for row_index in range(self.start[0], self.max_title_row): table_...
[ "def", "_fill_row_holes", "(", "self", ")", ":", "for", "row_index", "in", "range", "(", "self", ".", "start", "[", "0", "]", ",", "self", ".", "max_title_row", ")", ":", "table_row", "=", "self", ".", "table", "[", "row_index", "]", "row_start", "=", ...
48.1
22.7
def get_calls(self, job_name): ''' Reads file by given name and returns CallEdge array ''' config = self.file_index.get_by_name(job_name).yaml calls = self.get_calls_from_dict(config, from_name=job_name) return calls
[ "def", "get_calls", "(", "self", ",", "job_name", ")", ":", "config", "=", "self", ".", "file_index", ".", "get_by_name", "(", "job_name", ")", ".", "yaml", "calls", "=", "self", ".", "get_calls_from_dict", "(", "config", ",", "from_name", "=", "job_name",...
25.8
27.4
def _generate_appsecret_proof(self): """ Returns a SHA256 of the oauth_token signed by appsecret. https://developers.facebook.com/docs/graph-api/securing-requests/ """ if six.PY2: key = self.appsecret message = self.oauth_token else: ke...
[ "def", "_generate_appsecret_proof", "(", "self", ")", ":", "if", "six", ".", "PY2", ":", "key", "=", "self", ".", "appsecret", "message", "=", "self", ".", "oauth_token", "else", ":", "key", "=", "bytes", "(", "self", ".", "appsecret", ",", "'utf-8'", ...
35.692308
15.846154
def main(): '''monica helps you order food from the timeline''' arguments = docopt(__doc__, version=__version__) if arguments['configure'] and flag: configure() if arguments['cuisine']: if arguments['list']: cuisine('list') else: cuisine(arguments['<cuisine-id>']) elif arguments['surp...
[ "def", "main", "(", ")", ":", "arguments", "=", "docopt", "(", "__doc__", ",", "version", "=", "__version__", ")", "if", "arguments", "[", "'configure'", "]", "and", "flag", ":", "configure", "(", ")", "if", "arguments", "[", "'cuisine'", "]", ":", "if...
25.821429
16.178571
def ang2pix(nside, theta, phi, nest=False, lonlat=False): """Drop-in replacement for healpy `~healpy.pixelfunc.ang2pix`.""" lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring')
[ "def", "ang2pix", "(", "nside", ",", "theta", ",", "phi", ",", "nest", "=", "False", ",", "lonlat", "=", "False", ")", ":", "lon", ",", "lat", "=", "_healpy_to_lonlat", "(", "theta", ",", "phi", ",", "lonlat", "=", "lonlat", ")", "return", "lonlat_to...
66.5
19.25
def consumer(function): """Decorator that makes a generator function automatically advance to its first yield point when initially called (PEP 342).""" @wraps(function) def wrapper(*args, **kwargs): generator = function(*args, **kwargs) next(generator) return generator return...
[ "def", "consumer", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "generator", "=", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "next", "(", "g...
35.555556
11.555556
def structureOutput(fileUrl, fileName, searchFiles, format=True, space=40): """Formats the output of a list of packages""" #First, remove the filename if format: splitUrls = fileUrl[1:].split('/') fileUrl = "" for splitUrl in splitUrls: # This is a gimmicky fix to make formatting consistent # Cemetech do...
[ "def", "structureOutput", "(", "fileUrl", ",", "fileName", ",", "searchFiles", ",", "format", "=", "True", ",", "space", "=", "40", ")", ":", "#First, remove the filename", "if", "format", ":", "splitUrls", "=", "fileUrl", "[", "1", ":", "]", ".", "split",...
34.416667
20.375
def browse(self, path=None): """ Returns a list of directories matching the path given. Args: path (str): glob pattern. Returns: List[str] """ params = None if path: assert isinstance(path, string_types) params = {'current...
[ "def", "browse", "(", "self", ",", "path", "=", "None", ")", ":", "params", "=", "None", "if", "path", ":", "assert", "isinstance", "(", "path", ",", "string_types", ")", "params", "=", "{", "'current'", ":", "path", "}", "return", "self", ".", "get"...
26
16.214286
def _indexes(arr): """ Returns the list of all indexes of the given array. Currently works for one and two-dimensional arrays """ myarr = np.array(arr) if myarr.ndim == 1: return list(range(len(myarr))) elif myarr.ndim == 2: return tuple(itertools.product(list(range(arr.shape[0...
[ "def", "_indexes", "(", "arr", ")", ":", "myarr", "=", "np", ".", "array", "(", "arr", ")", "if", "myarr", ".", "ndim", "==", "1", ":", "return", "list", "(", "range", "(", "len", "(", "myarr", ")", ")", ")", "elif", "myarr", ".", "ndim", "==",...
34.071429
21.071429
def array_to_img(x, scale=True): """ x should be shape (channels, width, height) """ from PIL import Image if x.ndim != 3: raise Exception('Unsupported shape : ', str(x.shape), '. Need (channels, width, height)') if scale: x += max(-np.min(x), 0) x /= np.max(x) x ...
[ "def", "array_to_img", "(", "x", ",", "scale", "=", "True", ")", ":", "from", "PIL", "import", "Image", "if", "x", ".", "ndim", "!=", "3", ":", "raise", "Exception", "(", "'Unsupported shape : '", ",", "str", "(", "x", ".", "shape", ")", ",", "'. Nee...
31.478261
17.565217
def is_active(self): """ Returns True when the start date is today or in the past and the task has not yet been completed. """ start = self.start_date() return not self.is_completed() and (not start or start <= date.today())
[ "def", "is_active", "(", "self", ")", ":", "start", "=", "self", ".", "start_date", "(", ")", "return", "not", "self", ".", "is_completed", "(", ")", "and", "(", "not", "start", "or", "start", "<=", "date", ".", "today", "(", ")", ")" ]
38
14
def bulk_exports(self): """ :returns: Version bulk_exports of preview :rtype: twilio.rest.preview.bulk_exports.BulkExports """ if self._bulk_exports is None: self._bulk_exports = BulkExports(self) return self._bulk_exports
[ "def", "bulk_exports", "(", "self", ")", ":", "if", "self", ".", "_bulk_exports", "is", "None", ":", "self", ".", "_bulk_exports", "=", "BulkExports", "(", "self", ")", "return", "self", ".", "_bulk_exports" ]
34.375
8.125
def set_attribute_label(span, resource_type, resource_labels, attribute_key, canonical_key=None, label_value_prefix=''): """Set a label to span that can be used for tracing. :param span: Span object :param resource_type: resource type :param resource_labels: collection of labels ...
[ "def", "set_attribute_label", "(", "span", ",", "resource_type", ",", "resource_labels", ",", "attribute_key", ",", "canonical_key", "=", "None", ",", "label_value_prefix", "=", "''", ")", ":", "if", "attribute_key", "in", "resource_labels", ":", "if", "canonical_...
41
17.318182
def get_language(self): """ Get the language parameter from the current request. """ return get_language_parameter(self.request, self.query_language_key, default=self.get_default_language(object=object))
[ "def", "get_language", "(", "self", ")", ":", "return", "get_language_parameter", "(", "self", ".", "request", ",", "self", ".", "query_language_key", ",", "default", "=", "self", ".", "get_default_language", "(", "object", "=", "object", ")", ")" ]
46.2
24.6
def complex_type(name=None): '''Decorator for registering complex types''' def wrapped(cls): ParseType.type_mapping[name or cls.__name__] = cls return cls return wrapped
[ "def", "complex_type", "(", "name", "=", "None", ")", ":", "def", "wrapped", "(", "cls", ")", ":", "ParseType", ".", "type_mapping", "[", "name", "or", "cls", ".", "__name__", "]", "=", "cls", "return", "cls", "return", "wrapped" ]
32
17
def circular_layout(nodes): """ Lay out nodes on a circle and add node index. """ N = len(nodes) if not N: return ([], [], []) circ = np.pi/N*np.arange(N)*2 x = np.cos(circ) y = np.sin(circ) return (x, y, nodes)
[ "def", "circular_layout", "(", "nodes", ")", ":", "N", "=", "len", "(", "nodes", ")", "if", "not", "N", ":", "return", "(", "[", "]", ",", "[", "]", ",", "[", "]", ")", "circ", "=", "np", ".", "pi", "/", "N", "*", "np", ".", "arange", "(", ...
22.272727
13.363636
def to_json(self): """Serializes this MapperSpec into a json-izable object.""" result = { "mapper_handler_spec": self.handler_spec, "mapper_input_reader": self.input_reader_spec, "mapper_params": self.params, "mapper_shard_count": self.shard_count } if self.output_writer_...
[ "def", "to_json", "(", "self", ")", ":", "result", "=", "{", "\"mapper_handler_spec\"", ":", "self", ".", "handler_spec", ",", "\"mapper_input_reader\"", ":", "self", ".", "input_reader_spec", ",", "\"mapper_params\"", ":", "self", ".", "params", ",", "\"mapper_...
36
15.363636
def get_page_tpl_ctx(page, request): """ Возвращает контекст для рендеринга представления текстовой страницы :param page: модель страницы :param request: запрос :return: """ text = Template(page.text).render(Context()) meta = MetaSeo(page) comments = get_object_comments(PageComment, ...
[ "def", "get_page_tpl_ctx", "(", "page", ",", "request", ")", ":", "text", "=", "Template", "(", "page", ".", "text", ")", ".", "render", "(", "Context", "(", ")", ")", "meta", "=", "MetaSeo", "(", "page", ")", "comments", "=", "get_object_comments", "(...
39
18.875
def get_os_file_names(files): """ returns file names :param files: list of strings and\\or :class:`file_configuration_t` instances. :type files: list """ fnames = [] for f in files: if utils.is_str(f): fnames.app...
[ "def", "get_os_file_names", "(", "files", ")", ":", "fnames", "=", "[", "]", "for", "f", "in", "files", ":", "if", "utils", ".", "is_str", "(", "f", ")", ":", "fnames", ".", "append", "(", "f", ")", "elif", "isinstance", "(", "f", ",", "file_config...
30.045455
18.772727
def add_object(self, obj): """Add an object to the local collection.""" if _debug: Application._debug("add_object %r", obj) # extract the object name and identifier object_name = obj.objectName if not object_name: raise RuntimeError("object name required") ob...
[ "def", "add_object", "(", "self", ",", "obj", ")", ":", "if", "_debug", ":", "Application", ".", "_debug", "(", "\"add_object %r\"", ",", "obj", ")", "# extract the object name and identifier", "object_name", "=", "obj", ".", "objectName", "if", "not", "object_n...
44.636364
22.151515
def calculate_windows(self, **kwargs): """ Return the diameters of all windows in a molecule. This function first finds and then measures the diameters of all the window in the molecule. Returns ------- :class:`numpy.array` An array of windows' diame...
[ "def", "calculate_windows", "(", "self", ",", "*", "*", "kwargs", ")", ":", "windows", "=", "find_windows", "(", "self", ".", "elements", ",", "self", ".", "coordinates", ",", "*", "*", "kwargs", ")", "if", "windows", ":", "self", ".", "properties", "....
28.290323
20.354839
def getSensoryAssociatedLocationRepresentation(self): """ Get the location cells in the location layer that were driven by the input layer (or, during learning, were associated with this input.) """ cells = np.array([], dtype="uint32") totalPrevCells = 0 for module in self.L6aModules: ...
[ "def", "getSensoryAssociatedLocationRepresentation", "(", "self", ")", ":", "cells", "=", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "\"uint32\"", ")", "totalPrevCells", "=", "0", "for", "module", "in", "self", ".", "L6aModules", ":", "cells", "...
33.5
17.928571
def fill_x509_data(self, x509_data): """ Fills the X509Data Node :param x509_data: X509Data Node :type x509_data: lxml.etree.Element :return: None """ x509_issuer_serial = x509_data.find( 'ds:X509IssuerSerial', namespaces=constants.NS_MAP ) ...
[ "def", "fill_x509_data", "(", "self", ",", "x509_data", ")", ":", "x509_issuer_serial", "=", "x509_data", ".", "find", "(", "'ds:X509IssuerSerial'", ",", "namespaces", "=", "constants", ".", "NS_MAP", ")", "if", "x509_issuer_serial", "is", "not", "None", ":", ...
40.432432
15.513514
def derivativeY(self,x,y): ''' Evaluate the first derivative with respect to y of the function at given state space points. Parameters ---------- x : np.array First input values. y : np.array Second input values; should be of same shape ...
[ "def", "derivativeY", "(", "self", ",", "x", ",", "y", ")", ":", "xShift", ",", "xShiftDer", "=", "self", ".", "lowerBound", ".", "eval_with_derivative", "(", "y", ")", "dfdy_out", "=", "self", ".", "func", ".", "derivativeY", "(", "x", "-", "xShift", ...
33.333333
25.428571
def _move_begin_to_cxn(self, shape, cxn_pt_idx): """ Move the begin point of this connector to coordinates of the connection point of *shape* specified by *cxn_pt_idx*. """ x, y, cx, cy = shape.left, shape.top, shape.width, shape.height self.begin_x, self.begin_y = { ...
[ "def", "_move_begin_to_cxn", "(", "self", ",", "shape", ",", "cxn_pt_idx", ")", ":", "x", ",", "y", ",", "cx", ",", "cy", "=", "shape", ".", "left", ",", "shape", ".", "top", ",", "shape", ".", "width", ",", "shape", ".", "height", "self", ".", "...
39.666667
10.333333
def filter_inconsequential_acts(stmts_in, whitelist=None, **kwargs): """Filter out Activations that modify inconsequential activities Inconsequential here means that the site is not mentioned / tested in any other statement. In some cases specific activity types should be preserved, for instance, to be...
[ "def", "filter_inconsequential_acts", "(", "stmts_in", ",", "whitelist", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "whitelist", "is", "None", ":", "whitelist", "=", "{", "}", "logger", ".", "info", "(", "'Filtering %d statements to remove'", "%", ...
38.660714
16.892857
def clear_display_name(self): """Clears the display name. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if (self.get_display_name_metadata().is_read_only() or...
[ "def", "clear_display_name", "(", "self", ")", ":", "if", "(", "self", ".", "get_display_name_metadata", "(", ")", ".", "is_read_only", "(", ")", "or", "self", ".", "get_display_name_metadata", "(", ")", ".", "is_required", "(", ")", ")", ":", "raise", "er...
40.083333
18.916667
def _overwrite_special_dates(midnight_utcs, opens_or_closes, special_opens_or_closes): """ Overwrite dates in open_or_closes with corresponding dates in special_opens_or_closes, using midnight_utcs for alignment. """ # Short circuit when noth...
[ "def", "_overwrite_special_dates", "(", "midnight_utcs", ",", "opens_or_closes", ",", "special_opens_or_closes", ")", ":", "# Short circuit when nothing to apply.", "if", "not", "len", "(", "special_opens_or_closes", ")", ":", "return", "len_m", ",", "len_oc", "=", "len...
45.5
24.5
def __username(self, fname, lname): # pragma: no cover """Convert first name + last name into first.last style username.""" self.username = '.'.join([i.lower() for i in [fname, lname]])
[ "def", "__username", "(", "self", ",", "fname", ",", "lname", ")", ":", "# pragma: no cover", "self", ".", "username", "=", "'.'", ".", "join", "(", "[", "i", ".", "lower", "(", ")", "for", "i", "in", "[", "fname", ",", "lname", "]", "]", ")" ]
66.666667
14.666667
def update(gandi, fqdn, name, type, value, ttl, file): """Update record entry for a domain. --file option will ignore other parameters and overwrite current zone content with provided file content. """ domains = gandi.dns.list() domains = [domain['fqdn'] for domain in domains] if fqdn not i...
[ "def", "update", "(", "gandi", ",", "fqdn", ",", "name", ",", "type", ",", "value", ",", "ttl", ",", "file", ")", ":", "domains", "=", "gandi", ".", "dns", ".", "list", "(", ")", "domains", "=", "[", "domain", "[", "'fqdn'", "]", "for", "domain",...
33.833333
21.333333
def apps_installation_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/apps#remove-app-installation" api_path = "/api/v2/apps/installations/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, method="DELETE", **kwargs)
[ "def", "apps_installation_delete", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/apps/installations/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "...
59
19
def delete_pull_request_status(self, repository_id, pull_request_id, status_id, project=None): """DeletePullRequestStatus. [Preview API] Delete pull request status. :param str repository_id: The repository ID of the pull request’s target branch. :param int pull_request_id: ID of the pull...
[ "def", "delete_pull_request_status", "(", "self", ",", "repository_id", ",", "pull_request_id", ",", "status_id", ",", "project", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'",...
56.809524
21.761905
def make_registryitem_text(text, condition='contains', negate=False, preserve_case=False): """ Create a node for RegistryItem/Text :return: A IndicatorItem represented as an Element node """ document = 'RegistryItem' search = 'RegistryItem/Text' content_type = 'string' content = tex...
[ "def", "make_registryitem_text", "(", "text", ",", "condition", "=", "'contains'", ",", "negate", "=", "False", ",", "preserve_case", "=", "False", ")", ":", "document", "=", "'RegistryItem'", "search", "=", "'RegistryItem/Text'", "content_type", "=", "'string'", ...
39.692308
22.153846
def trace(): """ trace finds the line, the filename and error message and returns it to the user """ import traceback, inspect, sys tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] filename = inspect.getfile(inspect.currentframe()) # script name + line numbe...
[ "def", "trace", "(", ")", ":", "import", "traceback", ",", "inspect", ",", "sys", "tb", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "tbinfo", "=", "traceback", ".", "format_tb", "(", "tb", ")", "[", "0", "]", "filename", "=", "inspect", ...
29.125
10.5
def __build_index(self, until=None, flush=False, verbose=False): """ build/expand the index for this file. :param until: expand the index until the record with this hash has been incorporated and then stop. If None, go until the iterator is exhausted. Note that if this h...
[ "def", "__build_index", "(", "self", ",", "until", "=", "None", ",", "flush", "=", "False", ",", "verbose", "=", "False", ")", ":", "assert", "(", "self", ".", "_indexed_file_handle", "is", "not", "None", ")", "if", "flush", ":", "self", ".", "_index",...
39.212121
19.939394
def get_card(cards, term, limit=0, sort=False, ranks=None): """ Get the specified card from the stack. :arg cards: The cards to get from. Can be a ``Stack``, ``Deck`` or ``list``. :arg str term: The card's full name, value, suit, abbreviation, or stack indice. :arg int limit: ...
[ "def", "get_card", "(", "cards", ",", "term", ",", "limit", "=", "0", ",", "sort", "=", "False", ",", "ranks", "=", "None", ")", ":", "got_cards", "=", "[", "]", "try", ":", "indices", "=", "find_card", "(", "cards", ",", "term", ",", "limit", "=...
30.588235
22.352941
def _worker_status(target, worker, activation, profile='default', tgt_type='glob'): ''' Check if the worker is in `activation` state in the targeted load balancers The function will return the following dictionary: result -...
[ "def", "_worker_status", "(", "target", ",", "worker", ",", "activation", ",", "profile", "=", "'default'", ",", "tgt_type", "=", "'glob'", ")", ":", "ret", "=", "{", "'result'", ":", "True", ",", "'errors'", ":", "[", "]", ",", "'wrong_state'", ":", "...
28.769231
20.769231
def FromEvent(cls, service_event): """Creates a service object from an event. Args: service_event (EventObject): event to create a new service object from. Returns: WindowsService: service. """ _, _, name = service_event.key_path.rpartition( WindowsService._REGISTRY_KEY_PATH_SE...
[ "def", "FromEvent", "(", "cls", ",", "service_event", ")", ":", "_", ",", "_", ",", "name", "=", "service_event", ".", "key_path", ".", "rpartition", "(", "WindowsService", ".", "_REGISTRY_KEY_PATH_SEPARATOR", ")", "service_type", "=", "service_event", ".", "r...
37.92
20.12
def Expandkey(key, clen): """ Internal method supporting encryption and decryption functionality. """ import sha from string import join from array import array blocks = (clen + 19) / 20 xkey = [] seed = key for i in xrange(blocks): seed = sha.new(key + seed).digest() xkey.append(seed) j = join...
[ "def", "Expandkey", "(", "key", ",", "clen", ")", ":", "import", "sha", "from", "string", "import", "join", "from", "array", "import", "array", "blocks", "=", "(", "clen", "+", "19", ")", "/", "20", "xkey", "=", "[", "]", "seed", "=", "key", "for",...
24.285714
18.357143
def access_request(pid, record, template, **kwargs): """Create an access request.""" recid = int(pid.pid_value) datastore = LocalProxy( lambda: current_app.extensions['security'].datastore) # Record must be in restricted access mode. if record.get('access_right') != 'restricted' or \ ...
[ "def", "access_request", "(", "pid", ",", "record", ",", "template", ",", "*", "*", "kwargs", ")", ":", "recid", "=", "int", "(", "pid", ".", "pid_value", ")", "datastore", "=", "LocalProxy", "(", "lambda", ":", "current_app", ".", "extensions", "[", "...
33.189655
19.965517
def match_app_version(self, app=None, label=None, version=None, default=False): """Match app version against a semantic version string. Checks if a KE-chain app matches a version comparison. Uses the `semver` matcher to check. `match("2.0.0", ">=1.0.0")` => `True` `match("1.0.0", ">1.0...
[ "def", "match_app_version", "(", "self", ",", "app", "=", "None", ",", "label", "=", "None", ",", "version", "=", "None", ",", "default", "=", "False", ")", ":", "if", "not", "app", "or", "not", "label", "and", "not", "(", "app", "and", "label", ")...
47.777778
29.555556
def append_block(self, node, reverse=False): """Append a statement to the current block. Args: node: The statement to prepend. reverse: When called multiple times, this flag determines whether the statement should be prepended or appended to the already inserted statements. ...
[ "def", "append_block", "(", "self", ",", "node", ",", "reverse", "=", "False", ")", ":", "if", "not", "isinstance", "(", "node", ",", "grammar", ".", "STATEMENTS", ")", ":", "raise", "ValueError", "if", "reverse", ":", "self", ".", "to_append_block", "["...
29.736842
20.157895
def _add_plots_to_output(out, data): """Add CNVkit plots summarizing called copy number values. """ out["plot"] = {} diagram_plot = _add_diagram_plot(out, data) if diagram_plot: out["plot"]["diagram"] = diagram_plot scatter = _add_scatter_plot(out, data) if scatter: out["plot...
[ "def", "_add_plots_to_output", "(", "out", ",", "data", ")", ":", "out", "[", "\"plot\"", "]", "=", "{", "}", "diagram_plot", "=", "_add_diagram_plot", "(", "out", ",", "data", ")", "if", "diagram_plot", ":", "out", "[", "\"plot\"", "]", "[", "\"diagram\...
34.285714
11.214286
def Glyph(actor, glyphObj, orientationArray="", scaleByVectorSize=False, c=None, alpha=1): """ At each vertex of a mesh, another mesh - a `'glyph'` - is shown with various orientation options and coloring. Color can be specfied as a colormap which maps the size of the orientation vec...
[ "def", "Glyph", "(", "actor", ",", "glyphObj", ",", "orientationArray", "=", "\"\"", ",", "scaleByVectorSize", "=", "False", ",", "c", "=", "None", ",", "alpha", "=", "1", ")", ":", "cmap", "=", "None", "# user passing a color map to map orientationArray sizes",...
35.053763
18.258065
def romanNumeral(n): """ >>> romanNumeral(13) 'XIII' >>> romanNumeral(2944) 'MMCMXLIV' """ if 0 > n > 4000: raise ValueError('``n`` must lie between 1 and 3999: %d' % n) roman = 'I IV V IX X XL L XC C CD D CM M'.split() arabic = [1, 4, 5, 9, 10, 40, 50, 90, 10...
[ "def", "romanNumeral", "(", "n", ")", ":", "if", "0", ">", "n", ">", "4000", ":", "raise", "ValueError", "(", "'``n`` must lie between 1 and 3999: %d'", "%", "n", ")", "roman", "=", "'I IV V IX X XL L XC C CD D CM M'", ".", "split", "(", ")", ...
32.1875
19.9375
def get_gecko_params(request, uid=None, days_back=0, cumulative=True, frequency=settings.STATISTIC_FREQUENCY_DAILY, min_val=0, max_val=100, chart_type='standard', percentage='show', sort=False): """ Returns the default GET parameters for a particular Geckoboard view request. """ return { ...
[ "def", "get_gecko_params", "(", "request", ",", "uid", "=", "None", ",", "days_back", "=", "0", ",", "cumulative", "=", "True", ",", "frequency", "=", "settings", ".", "STATISTIC_FREQUENCY_DAILY", ",", "min_val", "=", "0", ",", "max_val", "=", "100", ",", ...
45.75
21.65
def genre(self): """ Cette routine convertit les indications morphologiques, données dans le fichier lemmes.la, pour exprimer le genre du mot dans la langue courante. :return: Genre :rtype: str """ _genre = "" if " m." in self._indMorph: _genre += "m" ...
[ "def", "genre", "(", "self", ")", ":", "_genre", "=", "\"\"", "if", "\" m.\"", "in", "self", ".", "_indMorph", ":", "_genre", "+=", "\"m\"", "if", "\" f.\"", "in", "self", ".", "_indMorph", ":", "_genre", "+=", "\"f\"", "if", "\" n.\"", "in", "self", ...
31
14.8
def set_alias(self, alias_hosted_zone_id, alias_dns_name): """Make this an alias resource record set""" self.alias_hosted_zone_id = alias_hosted_zone_id self.alias_dns_name = alias_dns_name
[ "def", "set_alias", "(", "self", ",", "alias_hosted_zone_id", ",", "alias_dns_name", ")", ":", "self", ".", "alias_hosted_zone_id", "=", "alias_hosted_zone_id", "self", ".", "alias_dns_name", "=", "alias_dns_name" ]
52.5
9.5
def validate_metadata_sign(xml, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False): """ Validates a signature of a EntityDescriptor. :param xml: The element we should validate :type: string | Document :param cert: The pubic cert :type: ...
[ "def", "validate_metadata_sign", "(", "xml", ",", "cert", "=", "None", ",", "fingerprint", "=", "None", ",", "fingerprintalg", "=", "'sha1'", ",", "validatecert", "=", "False", ",", "debug", "=", "False", ")", ":", "if", "xml", "is", "None", "or", "xml",...
39.716418
25.626866
def get_user(self, validated_token): """ Attempts to find and return a user using the given validated token. """ try: user_id = validated_token[api_settings.USER_ID_CLAIM] except KeyError: raise InvalidToken(_('Token contained no recognizable user identifi...
[ "def", "get_user", "(", "self", ",", "validated_token", ")", ":", "try", ":", "user_id", "=", "validated_token", "[", "api_settings", ".", "USER_ID_CLAIM", "]", "except", "KeyError", ":", "raise", "InvalidToken", "(", "_", "(", "'Token contained no recognizable us...
36.5
25.722222
def count(self): """ Return the number of hits matching the query and filters. Note that only the actual number is returned. """ if hasattr(self, '_response'): return self._response.hits.total es = connections.get_connection(self._using) d = self.to_...
[ "def", "count", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_response'", ")", ":", "return", "self", ".", "_response", ".", "hits", ".", "total", "es", "=", "connections", ".", "get_connection", "(", "self", ".", "_using", ")", "d", "...
28.352941
14.588235
def has_special_char(p_str, check_style=charChinese): """ 检查字符串是否含有指定类型字符 :param: * p_str: (string) 需要判断的字符串 * check_style: (string) 需要判断的字符类型,默认为 charChinese (编码仅支持utf-8), 支持 charNum,该参数向后兼容 :return: * True 含有指定类型字符 * False 不含有指定类型字符 举例如下:: print('--- has...
[ "def", "has_special_char", "(", "p_str", ",", "check_style", "=", "charChinese", ")", ":", "if", "check_style", "==", "charChinese", ":", "check_pattern", "=", "re", ".", "compile", "(", "u'[\\u4e00-\\u9fa5]+'", ")", "elif", "check_style", "==", "charNum", ":", ...
24.464286
22.321429
def check_s3_url(self, s3url): """ Check if an S3 URL exists :param s3url: S3 url :type s3url: str :rtype: bool """ bucket, key = S3Hook.parse_s3_url(s3url) if not self.s3_hook.check_for_bucket(bucket_name=bucket): raise AirflowException( ...
[ "def", "check_s3_url", "(", "self", ",", "s3url", ")", ":", "bucket", ",", "key", "=", "S3Hook", ".", "parse_s3_url", "(", "s3url", ")", "if", "not", "self", ".", "s3_hook", ".", "check_for_bucket", "(", "bucket_name", "=", "bucket", ")", ":", "raise", ...
43.545455
19.727273
def printmp(msg): """Print temporarily, until next print overrides it. """ filler = (80 - len(msg)) * ' ' print(msg + filler, end='\r') sys.stdout.flush()
[ "def", "printmp", "(", "msg", ")", ":", "filler", "=", "(", "80", "-", "len", "(", "msg", ")", ")", "*", "' '", "print", "(", "msg", "+", "filler", ",", "end", "=", "'\\r'", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
28.166667
9
def confusion_matrix(self): """Confusion matrix plot """ return plot.confusion_matrix(self.y_true, self.y_pred, self.target_names, ax=_gen_ax())
[ "def", "confusion_matrix", "(", "self", ")", ":", "return", "plot", ".", "confusion_matrix", "(", "self", ".", "y_true", ",", "self", ".", "y_pred", ",", "self", ".", "target_names", ",", "ax", "=", "_gen_ax", "(", ")", ")" ]
40.2
12.8
def on_pause_request(self, py_db, request): ''' :param PauseRequest request: ''' arguments = request.arguments # : :type arguments: PauseArguments thread_id = arguments.threadId self.api.request_suspend_thread(py_db, thread_id=thread_id) response = pydevd_base_...
[ "def", "on_pause_request", "(", "self", ",", "py_db", ",", "request", ")", ":", "arguments", "=", "request", ".", "arguments", "# : :type arguments: PauseArguments", "thread_id", "=", "arguments", ".", "threadId", "self", ".", "api", ".", "request_suspend_thread", ...
36.818182
23
def to_mapping_field(cls, key): # pragma: no mccabe """ Returns a callable instance that will convert a value to a Mapping. :param cls: Valid class type of the items in the Sequence. :param key: Attribute name of the key value in each item of cls instance. :return: instance of the MappingConverter...
[ "def", "to_mapping_field", "(", "cls", ",", "key", ")", ":", "# pragma: no mccabe", "class", "MappingConverter", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "cls", ",", "key", ")", ":", "self", ".", "_cls", "=", "cls", "self", ".", "k...
32.216216
19.891892
def _request(self, url, params=None, timeout=10): """Send a request with parameters.""" rsp = self._session.get(url, params=params, timeout=timeout) rsp.raise_for_status() return rsp.text.strip()
[ "def", "_request", "(", "self", ",", "url", ",", "params", "=", "None", ",", "timeout", "=", "10", ")", ":", "rsp", "=", "self", ".", "_session", ".", "get", "(", "url", ",", "params", "=", "params", ",", "timeout", "=", "timeout", ")", "rsp", "....
44.6
11.2
def deregister(): """ Remove pandas' formatters and converters Removes the custom converters added by :func:`register`. This attempts to set the state of the registry back to the state before pandas registered its own units. Converters for pandas' own types like Timestamp and Period are removed...
[ "def", "deregister", "(", ")", ":", "# Renamed in pandas.plotting.__init__", "for", "type_", ",", "cls", "in", "get_pairs", "(", ")", ":", "# We use type to catch our classes directly, no inheritance", "if", "type", "(", "units", ".", "registry", ".", "get", "(", "t...
37.777778
18.518519
def login_create(login, new_login_password=None, new_login_domain='', new_login_roles=None, new_login_options=None, **kwargs): ''' Creates a new login. Does not update password of existing logins. For Windows authentication, provide ``new_login_domain``. For SQL Server authentication, prvide ``new_lo...
[ "def", "login_create", "(", "login", ",", "new_login_password", "=", "None", ",", "new_login_domain", "=", "''", ",", "new_login_roles", "=", "None", ",", "new_login_options", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# One and only one of password and doma...
36.105263
23.684211
def log(arg1, arg2=None): """Returns the first argument-based logarithm of the second argument. If there is only one argument, then this takes the natural logarithm of the argument. >>> df.select(log(10.0, df.age).alias('ten')).rdd.map(lambda l: str(l.ten)[:7]).collect() ['0.30102', '0.69897'] >>...
[ "def", "log", "(", "arg1", ",", "arg2", "=", "None", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "if", "arg2", "is", "None", ":", "jc", "=", "sc", ".", "_jvm", ".", "functions", ".", "log", "(", "_to_java_column", "(", "arg1", ...
37.352941
24.764706
def _build_request_factory(cls, session: AppSession): '''Create the request factory. A request factory is any callable object that returns a :class:`.http.Request`. The callable must accept the same arguments to Request. Returns: A callable object ''' ...
[ "def", "_build_request_factory", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "def", "request_factory", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "request", "=", "session", ".", "factory", ".", "class_map", "[", "'Request'", "]", "...
33.151515
23.939394
def delete_snapshot(snapshots_ids=None, config="root"): ''' Deletes an snapshot config Configuration name. (Default: root) snapshots_ids List of the snapshots IDs to be deleted. CLI example: .. code-block:: bash salt '*' snapper.delete_snapshot 54 salt '*' sn...
[ "def", "delete_snapshot", "(", "snapshots_ids", "=", "None", ",", "config", "=", "\"root\"", ")", ":", "if", "not", "snapshots_ids", ":", "raise", "CommandExecutionError", "(", "'Error: No snapshot ID has been provided'", ")", "try", ":", "current_snapshots_ids", "=",...
37
23.647059
def twos_comp_repr(val, bitwidth): """ Converts a value to it's two's-complement (positive) integer representation using a given bitwidth (only converts the value if it is negative). For use with Simulation.step() etc. in passing negative numbers, which it does not accept """ correctbw = abs(val...
[ "def", "twos_comp_repr", "(", "val", ",", "bitwidth", ")", ":", "correctbw", "=", "abs", "(", "val", ")", ".", "bit_length", "(", ")", "+", "1", "if", "bitwidth", "<", "correctbw", ":", "raise", "pyrtl", ".", "PyrtlError", "(", "\"please choose a larger ta...
40.230769
19.923077
def check(args, source_code, filename=None, options=None): """Check source code with checker defined with *args* (list) Returns an empty list if checker is not installed""" if args is None: return [] if options is not None: args += options if any(['pyflakes' in arg for arg in ...
[ "def", "check", "(", "args", ",", "source_code", ",", "filename", "=", "None", ",", "options", "=", "None", ")", ":", "if", "args", "is", "None", ":", "return", "[", "]", "if", "options", "is", "not", "None", ":", "args", "+=", "options", "if", "an...
43.065217
17.282609
def plot_contours(self, grid, filled=True, ax=None, labels=None, subplots_kw=dict(), **kwargs): """ Plot equipotentials contours. Computes the potential energy on a grid (specified by the array `grid`). .. warning:: Right now the grid input must be arrays and must ...
[ "def", "plot_contours", "(", "self", ",", "grid", ",", "filled", "=", "True", ",", "ax", "=", "None", ",", "labels", "=", "None", ",", "subplots_kw", "=", "dict", "(", ")", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "...
32.411765
20.058824
def implementation_std(vals_std, vals_std_u, bs_std, bs_std_u, **kwargs): r"""Estimates varaition of results due to implementation-specific effects. See 'nestcheck: diagnostic tests for nested sampling calculations' (Higson et al. 2019) for more details. Uncertainties on the output are calculated numer...
[ "def", "implementation_std", "(", "vals_std", ",", "vals_std_u", ",", "bs_std", ",", "bs_std_u", ",", "*", "*", "kwargs", ")", ":", "nsim", "=", "kwargs", ".", "pop", "(", "'nsim'", ",", "1000000", ")", "random_seed", "=", "kwargs", ".", "pop", "(", "'...
43.606061
18.757576
def qos_queue_scheduler_strict_priority_dwrr_traffic_class0(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") queue = ET.SubElement(qos, "queue") scheduler = ET.SubElement...
[ "def", "qos_queue_scheduler_strict_priority_dwrr_traffic_class0", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "qos", "=", "ET", ".", "SubElement", "(", "config", ",", "\"qos\"", ",", "xmlns", "...
49.384615
20.384615
def parse(self): """ parse the data """ tree = ET.parse(self.getInputFile()) root = tree.getroot() # Building Assay dictionary to query names by id from test results line for as_ref in root.find("Assays").findall("AssayRef"): self._assays[as_ref.get("KEY_Assay...
[ "def", "parse", "(", "self", ")", ":", "tree", "=", "ET", ".", "parse", "(", "self", ".", "getInputFile", "(", ")", ")", "root", "=", "tree", ".", "getroot", "(", ")", "# Building Assay dictionary to query names by id from test results line", "for", "as_ref", ...
40.73913
15.978261
def translate_expression(expression): """ Check if the expression is valid, then check turn it into an expression that can be used for filtering. :return list of lists: One or more matches. Each list has 3 strings. """ logger_ts.info("enter translate_expression") m = re_filter_expr.findall(expre...
[ "def", "translate_expression", "(", "expression", ")", ":", "logger_ts", ".", "info", "(", "\"enter translate_expression\"", ")", "m", "=", "re_filter_expr", ".", "findall", "(", "expression", ")", "matches", "=", "[", "]", "if", "m", ":", "for", "i", "in", ...
38.272727
15.545455
def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" raw_settings = raw_data.get("qosSettings", {}) qos_settings = QosSettings.from_raw_data(raw_settings) raw_data["qosSettings"] = qos_settings return super(PortSettings, cls).process_raw_data(raw_...
[ "def", "process_raw_data", "(", "cls", ",", "raw_data", ")", ":", "raw_settings", "=", "raw_data", ".", "get", "(", "\"qosSettings\"", ",", "{", "}", ")", "qos_settings", "=", "QosSettings", ".", "from_raw_data", "(", "raw_settings", ")", "raw_data", "[", "\...
53.333333
12
def _writeblocks(cls, blocks, available, cont_size, padding_func): """Render metadata block as a byte string.""" # write everything except padding data = bytearray() for block in blocks: if isinstance(block, Padding): continue data += cls._writebl...
[ "def", "_writeblocks", "(", "cls", ",", "blocks", ",", "available", ",", "cont_size", ",", "padding_func", ")", ":", "# write everything except padding", "data", "=", "bytearray", "(", ")", "for", "block", "in", "blocks", ":", "if", "isinstance", "(", "block",...
36.26087
17.521739
def getArguments(parser): "Provides additional validation of the arguments collected by argparse." args = parser.parse_args() if args.width <= 0: raise argparse.ArgumentError(args.width, 'The contour width must be a positive number.') return args
[ "def", "getArguments", "(", "parser", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "width", "<=", "0", ":", "raise", "argparse", ".", "ArgumentError", "(", "args", ".", "width", ",", "'The contour width must be a positive ...
44.166667
26.5
def reach_process_pmc(): """Process PubMedCentral article and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) pmcid = body.get('pmcid') rp = reach.process_pmc(pmcid) return _stmts_from_pr...
[ "def", "reach_process_pmc", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "load...
35.333333
10
def isect_segments__naive(segments): """ Brute force O(n2) version of ``isect_segments`` for test validation. """ isect = [] # order points left -> right if Real is float: segments = [ (s[0], s[1]) if s[0][X] <= s[1][X] else (s[1], s[0]) for s in segm...
[ "def", "isect_segments__naive", "(", "segments", ")", ":", "isect", "=", "[", "]", "# order points left -> right", "if", "Real", "is", "float", ":", "segments", "=", "[", "(", "s", "[", "0", "]", ",", "s", "[", "1", "]", ")", "if", "s", "[", "0", "...
28.054054
17.243243
def thanks(year=None): """ 4rd Thursday in Nov :param year: int :return: Thanksgiving Day """ nov_first = datetime.date(_year, 11, 1) if not year else datetime.date(int(year), 11, 1) weekday_seq = nov_first.weekday() if weekday_seq > 3: current_day = 32 - weekday_seq else: ...
[ "def", "thanks", "(", "year", "=", "None", ")", ":", "nov_first", "=", "datetime", ".", "date", "(", "_year", ",", "11", ",", "1", ")", "if", "not", "year", "else", "datetime", ".", "date", "(", "int", "(", "year", ")", ",", "11", ",", "1", ")"...
30.923077
14.615385
def add_identity(self,item_name,item_category=None,item_type=None): """Add an identity to the `DiscoInfo` object. :Parameters: - `item_name`: name of the item. - `item_category`: category of the item. - `item_type`: type of the item. :Types: - `it...
[ "def", "add_identity", "(", "self", ",", "item_name", ",", "item_category", "=", "None", ",", "item_type", "=", "None", ")", ":", "return", "DiscoIdentity", "(", "self", ",", "item_name", ",", "item_category", ",", "item_type", ")" ]
36.866667
13.933333
def get_central_instances(self, profile_path, central_class=None, scoping_class=None, scoping_path=None, reference_direction='dmtf', try_gci_method=False): """ Return the instance paths of the central instances of ...
[ "def", "get_central_instances", "(", "self", ",", "profile_path", ",", "central_class", "=", "None", ",", "scoping_class", "=", "None", ",", "scoping_path", "=", "None", ",", "reference_direction", "=", "'dmtf'", ",", "try_gci_method", "=", "False", ")", ":", ...
47.268852
24.377049
def remove_send_last_message(self, connection): """Removes a send_last_message function previously registered with the Dispatcher. Args: connection (str): A locally unique identifier provided by the receiver of messages. """ if connection in self._sen...
[ "def", "remove_send_last_message", "(", "self", ",", "connection", ")", ":", "if", "connection", "in", "self", ".", "_send_last_message", ":", "del", "self", ".", "_send_last_message", "[", "connection", "]", "LOGGER", ".", "debug", "(", "\"Removed send_last_messa...
44.117647
16.823529
def tags(self, extra_params=None): """" All Tags in this Space """ return self.api._get_json( Tag, space=self, rel_path=self._build_rel_path('tags'), extra_params=extra_params, )
[ "def", "tags", "(", "self", ",", "extra_params", "=", "None", ")", ":", "return", "self", ".", "api", ".", "_get_json", "(", "Tag", ",", "space", "=", "self", ",", "rel_path", "=", "self", ".", "_build_rel_path", "(", "'tags'", ")", ",", "extra_params"...
25.7
10.6
def random_reset_mutation(random, candidate, args): """Return the mutants produced by randomly choosing new values. This function performs random-reset mutation. It assumes that candidate solutions are composed of discrete values. This function makes use of the bounder function as specified in the EC'...
[ "def", "random_reset_mutation", "(", "random", ",", "candidate", ",", "args", ")", ":", "bounder", "=", "args", "[", "'_ec'", "]", ".", "bounder", "try", ":", "values", "=", "bounder", ".", "values", "except", "AttributeError", ":", "values", "=", "None", ...
36.463415
19.585366
def record(self): """Getter that get content of RECORD file in .whl archive Returns: dict with keys `modules` and `scripts` """ modules = [] scripts = [] if self.get_content_of_file('RECORD'): lines = self.get_content_of_file('RECORD').splitlines(...
[ "def", "record", "(", "self", ")", ":", "modules", "=", "[", "]", "scripts", "=", "[", "]", "if", "self", ".", "get_content_of_file", "(", "'RECORD'", ")", ":", "lines", "=", "self", ".", "get_content_of_file", "(", "'RECORD'", ")", ".", "splitlines", ...
38.478261
16.73913
def get_random(self): """ Returns a random statement from the database. """ import random Statement = self.get_model('statement') session = self.Session() count = self.count() if count < 1: raise self.EmptyDatabaseException() random_...
[ "def", "get_random", "(", "self", ")", ":", "import", "random", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "session", "=", "self", ".", "Session", "(", ")", "count", "=", "self", ".", "count", "(", ")", "if", "count", "<", "...
25.55
19.45
async def cas(self, value: Any, **kwargs) -> bool: """ Checks and sets the specified value for the locked key. If the value has changed since the lock was created, it will raise an :class:`aiocache.lock.OptimisticLockError` exception. :raises: :class:`aiocache.lock.OptimisticLoc...
[ "async", "def", "cas", "(", "self", ",", "value", ":", "Any", ",", "*", "*", "kwargs", ")", "->", "bool", ":", "success", "=", "await", "self", ".", "client", ".", "set", "(", "self", ".", "key", ",", "value", ",", "_cas_token", "=", "self", ".",...
45.416667
26.916667
def Print(self, output_writer): """Prints a human readable version of the filter. Args: output_writer (CLIOutputWriter): output writer. """ if self._extensions: output_writer.Write('\textensions: {0:s}\n'.format( ', '.join(self._extensions)))
[ "def", "Print", "(", "self", ",", "output_writer", ")", ":", "if", "self", ".", "_extensions", ":", "output_writer", ".", "Write", "(", "'\\textensions: {0:s}\\n'", ".", "format", "(", "', '", ".", "join", "(", "self", ".", "_extensions", ")", ")", ")" ]
30.333333
14.111111
def rmdup(args): """ %prog rmdup *.bam > rmdup.cmds Remove PCR duplicates from BAM files, generate a list of commands. """ p = OptionParser(rmdup.__doc__) p.add_option("-S", default=False, action="store_true", help="Treat PE reads as SE in rmdup") opts, args = p.parse_args(...
[ "def", "rmdup", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "rmdup", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"-S\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Treat PE reads as SE in rmdu...
25.92
16.96
def whitespace_before_parameters(logical_line, tokens): r"""Avoid extraneous whitespace. Avoid extraneous whitespace in the following situations: - before the open parenthesis that starts the argument list of a function call. - before the open parenthesis that starts an indexing or slicing. ...
[ "def", "whitespace_before_parameters", "(", "logical_line", ",", "tokens", ")", ":", "prev_type", ",", "prev_text", ",", "__", ",", "prev_end", ",", "__", "=", "tokens", "[", "0", "]", "for", "index", "in", "range", "(", "1", ",", "len", "(", "tokens", ...
38.133333
16.833333
def get_temp_url_key(self, cached=True): """ Returns the current TempURL key, or None if it has not been set. By default the value returned is cached. To force an API call to get the current value on the server, pass `cached=False`. """ meta = self._cached_temp_url_key ...
[ "def", "get_temp_url_key", "(", "self", ",", "cached", "=", "True", ")", ":", "meta", "=", "self", ".", "_cached_temp_url_key", "if", "not", "cached", "or", "not", "meta", ":", "key", "=", "\"temp_url_key\"", "meta", "=", "self", ".", "get_account_metadata",...
38.076923
14.076923
def convert(self, value): """Convert self value.""" try: return convert_to_format(value, self._format) except (ValueError, TypeError): return value
[ "def", "convert", "(", "self", ",", "value", ")", ":", "try", ":", "return", "convert_to_format", "(", "value", ",", "self", ".", "_format", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "value" ]
31.666667
12.833333
def delete_fields(self, form_id, field_ids): """ Remove fields from a form :param form_id: int :param field_ids: list|tuple :return: dict|str """ response = self._client.session.delete( '{url}/{form_id}/fields/delete'.format( url=self...
[ "def", "delete_fields", "(", "self", ",", "form_id", ",", "field_ids", ")", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "delete", "(", "'{url}/{form_id}/fields/delete'", ".", "format", "(", "url", "=", "self", ".", "endpoint_url", ",",...
28
13.625
def save_config_variables(self): """Save the configuration variables in non-volatile memory. This method should be used in conjuction with *write_config_variables*. :rtype: boolean :Example: >>> alpha.save_config_variables() True """ command = 0x43 ...
[ "def", "save_config_variables", "(", "self", ")", ":", "command", "=", "0x43", "byte_list", "=", "[", "0x3F", ",", "0x3C", ",", "0x3F", ",", "0x3C", ",", "0x43", "]", "success", "=", "[", "0xF3", ",", "0x43", ",", "0x3F", ",", "0x3C", ",", "0x3F", ...
26.774194
20.064516