text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _get_desktop_size(): """Get the desktop size.""" if platform.system() == "Linux": try: xrandr_query = subprocess.check_output(["xrandr", "--query"]) sizes = re.findall(r"\bconnected primary (\d+)x(\d+)", str(xrandr_query)) if sizes[0]: return point.Point(int(sizes[0][0]), int(sizes...
[ "def", "_get_desktop_size", "(", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "\"Linux\"", ":", "try", ":", "xrandr_query", "=", "subprocess", ".", "check_output", "(", "[", "\"xrandr\"", ",", "\"--query\"", "]", ")", "sizes", "=", "re", "....
42.285714
19.928571
def is_remote_allowed(remote): """ Check if `remote` is allowed to make a CORS request. """ if settings.debug: return True if not remote: return False for domain_pattern in settings.node['cors_whitelist_domains']: if domain_pattern.match(remote): return True return False
[ "def", "is_remote_allowed", "(", "remote", ")", ":", "if", "settings", ".", "debug", ":", "return", "True", "if", "not", "remote", ":", "return", "False", "for", "domain_pattern", "in", "settings", ".", "node", "[", "'cors_whitelist_domains'", "]", ":", "if"...
24.333333
16.166667
def zero(duration: int, name: str = None) -> SamplePulse: """Generates zero-sampled `SamplePulse`. Args: duration: Duration of pulse. Must be greater than zero. name: Name of pulse. """ return _sampled_zero_pulse(duration, name=name)
[ "def", "zero", "(", "duration", ":", "int", ",", "name", ":", "str", "=", "None", ")", "->", "SamplePulse", ":", "return", "_sampled_zero_pulse", "(", "duration", ",", "name", "=", "name", ")" ]
32.375
16.75
def all_neighbors(graph, node, t=None): """ Returns all of the neighbors of a node in the graph at time t. If the graph is directed returns predecessors as well as successors. Parameters ---------- graph : DyNetx graph Graph to find neighbors. node : node ...
[ "def", "all_neighbors", "(", "graph", ",", "node", ",", "t", "=", "None", ")", ":", "if", "graph", ".", "is_directed", "(", ")", ":", "values", "=", "chain", "(", "graph", ".", "predecessors", "(", "node", ",", "t", "=", "t", ")", ",", "graph", "...
26.571429
22.392857
def drop_duplicates_agg(df,colsgroupby,cols2aggf,test=False): """ colsgroupby: unique names ~index cols2aggf: rest of the cols `unique_dropna_str` for categories """ if test: print(df.shape) print(df.drop_duplicates(subset=colsgroupby).shape) #ddup aggregated dfdupagg=df.loc[...
[ "def", "drop_duplicates_agg", "(", "df", ",", "colsgroupby", ",", "cols2aggf", ",", "test", "=", "False", ")", ":", "if", "test", ":", "print", "(", "df", ".", "shape", ")", "print", "(", "df", ".", "drop_duplicates", "(", "subset", "=", "colsgroupby", ...
33.368421
18.736842
def note_deletion(self, key): """ Notes the deletion of a field. """ # If we'rew deleting a key we previously added, then there is no diff if key in self._added: self._added.remove(key) else: # If the deleted key was previously changed, use the ori...
[ "def", "note_deletion", "(", "self", ",", "key", ")", ":", "# If we'rew deleting a key we previously added, then there is no diff", "if", "key", "in", "self", ".", "_added", ":", "self", ".", "_added", ".", "remove", "(", "key", ")", "else", ":", "# If the deleted...
37.714286
13.571429
def modify(self, SQL, params='', verbose=True): """ Wrapper for CRUD operations to make them distinct from queries and automatically pass commit() method to cursor. Parameters ---------- SQL: str The SQL query to execute params: sequence Mimics th...
[ "def", "modify", "(", "self", ",", "SQL", ",", "params", "=", "''", ",", "verbose", "=", "True", ")", ":", "# Make sure the database isn't locked", "self", ".", "conn", ".", "commit", "(", ")", "if", "SQL", ".", "lower", "(", ")", ".", "startswith", "(...
35.73913
20.956522
def setup_left_panel(self): """Setup the UI for left panel. Generate all exposure, combobox, and edit button. """ hazard = self.parent.step_kw_subcategory.selected_subcategory() left_panel_heading = QLabel(tr('Classifications')) left_panel_heading.setFont(big_font) ...
[ "def", "setup_left_panel", "(", "self", ")", ":", "hazard", "=", "self", ".", "parent", ".", "step_kw_subcategory", ".", "selected_subcategory", "(", ")", "left_panel_heading", "=", "QLabel", "(", "tr", "(", "'Classifications'", ")", ")", "left_panel_heading", "...
45.289855
18.521739
def headers_to_str_headers(headers): ''' Converts dict or tuple-based headers of bytes or str to tuple-based headers of str, which is the python norm (pep 3333) ''' ret = [] if isinstance(headers, collections_abc.Mapping): h = headers.items() else: h = headers if six.PY...
[ "def", "headers_to_str_headers", "(", "headers", ")", ":", "ret", "=", "[", "]", "if", "isinstance", "(", "headers", ",", "collections_abc", ".", "Mapping", ")", ":", "h", "=", "headers", ".", "items", "(", ")", "else", ":", "h", "=", "headers", "if", ...
25.217391
20.173913
def rotate_root_iam_credentials(self, mount_point=DEFAULT_MOUNT_POINT): """Rotate static root IAM credentials. When you have configured Vault with static credentials, you can use this endpoint to have Vault rotate the access key it used. Note that, due to AWS eventual consistency, after calling...
[ "def", "rotate_root_iam_credentials", "(", "self", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "api_path", "=", "'/v1/{mount_point}/config/rotate-root'", ".", "format", "(", "mount_point", "=", "mount_point", ")", "response", "=", "self", ".", "_adapter"...
50.272727
34.227273
def get_cachedir_bsig(self): """ Return the signature for a cached file, including its children. It adds the path of the cached file to the cache signature, because multiple targets built by the same action will all have the same build signature, and we have to different...
[ "def", "get_cachedir_bsig", "(", "self", ")", ":", "try", ":", "return", "self", ".", "cachesig", "except", "AttributeError", ":", "pass", "# Collect signatures for all children", "children", "=", "self", ".", "children", "(", ")", "sigs", "=", "[", "n", ".", ...
34.36
15.8
def _default_static_lib(self, obj_files): """Create a static library (i.e. a ``.a`` / ``.lib`` file). Args: obj_files (List[str]): List of paths of compiled object files. """ c_compiler = self.F90_COMPILER.c_compiler static_lib_dir = os.path.join(self.build_lib, "bez...
[ "def", "_default_static_lib", "(", "self", ",", "obj_files", ")", ":", "c_compiler", "=", "self", ".", "F90_COMPILER", ".", "c_compiler", "static_lib_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "build_lib", ",", "\"bezier\"", ",", "\"lib\"",...
42.761905
15.142857
def _handle_shift(self, other: Union[int, "BitVec"], operator: Callable) -> "BitVec": """ Handles shift :param other: The other BitVector :param operator: The shift operator :return: the resulting output """ if isinstance(other, BitVecFunc): return ope...
[ "def", "_handle_shift", "(", "self", ",", "other", ":", "Union", "[", "int", ",", "\"BitVec\"", "]", ",", "operator", ":", "Callable", ")", "->", "\"BitVec\"", ":", "if", "isinstance", "(", "other", ",", "BitVecFunc", ")", ":", "return", "operator", "(",...
40.266667
12.533333
def pillar(tgt, delimiter=DEFAULT_TARGET_DELIM): ''' Return True if the minion matches the given pillar target. The ``delimiter`` argument can be used to specify a different delimiter. CLI Example: .. code-block:: bash salt '*' match.pillar 'cheese:foo' salt '*' match.pillar 'clon...
[ "def", "pillar", "(", "tgt", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ")", ":", "matchers", "=", "salt", ".", "loader", ".", "matchers", "(", "__opts__", ")", "try", ":", "return", "matchers", "[", "'pillar_match.match'", "]", "(", "tgt", ",", "delim...
29.586207
27.103448
def _input_as_lines(self, data): """Writes data to tempfile and sets -i parameter data -- list of lines, ready to be written to file """ if data: self.Parameters['-i']\ .on(super(CD_HIT,self)._input_as_lines(data)) return ''
[ "def", "_input_as_lines", "(", "self", ",", "data", ")", ":", "if", "data", ":", "self", ".", "Parameters", "[", "'-i'", "]", ".", "on", "(", "super", "(", "CD_HIT", ",", "self", ")", ".", "_input_as_lines", "(", "data", ")", ")", "return", "''" ]
32.111111
16
def change_id(self, new_id): """Change the id of this content.""" self._load_raw_content() self._id = new_id self.get_filename(renew=True) self.get_filepath(renew=True) return
[ "def", "change_id", "(", "self", ",", "new_id", ")", ":", "self", ".", "_load_raw_content", "(", ")", "self", ".", "_id", "=", "new_id", "self", ".", "get_filename", "(", "renew", "=", "True", ")", "self", ".", "get_filepath", "(", "renew", "=", "True"...
31
9.571429
def dump(self, name, obj, context=None): """Serialize data to primitive types. Raises :exc:`~lollipop.errors.ValidationError` if data is invalid. :param str name: Name of attribute to serialize. :param obj: Application object to extract serialized value from. :returns: Serialize...
[ "def", "dump", "(", "self", ",", "name", ",", "obj", ",", "context", "=", "None", ")", ":", "value", "=", "self", ".", "get_value", "(", "name", ",", "obj", ",", "context", "=", "context", ")", "return", "self", ".", "field_type", ".", "dump", "(",...
45.909091
15.818182
def _send(self, ip, port, data): """ Send an UDP message :param ip: Ip to send to :type ip: str :param port: Port to send to :type port: int :return: Number of bytes sent :rtype: int """ return self._listen_socket.sendto(data, (ip, port))
[ "def", "_send", "(", "self", ",", "ip", ",", "port", ",", "data", ")", ":", "return", "self", ".", "_listen_socket", ".", "sendto", "(", "data", ",", "(", "ip", ",", "port", ")", ")" ]
25.666667
12.666667
def later(periods=10.0, precision=2.0, offset=0.0, check_interval=0.1, only_run_once=True): """ **注意:会阻塞程序运行, 如果后台运行, 请放置于线程中** 这个会阻塞程序运行, 如果不是这个目的, 请确保待装饰程序以线程方式运行 * periods 是正常提供的参数, 如 10s, 则函数每10s 运行一次 * precision 精度, * 如3s, 则 0~3s 内都可以触发运行 * 如果是0s, 则函数可在 ```sleep check_interva...
[ "def", "later", "(", "periods", "=", "10.0", ",", "precision", "=", "2.0", ",", "offset", "=", "0.0", ",", "check_interval", "=", "0.1", ",", "only_run_once", "=", "True", ")", ":", "def", "dec_fn", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")"...
30.605634
17.28169
def reveal(input_image: Union[str, IO[bytes]]): """ Find a message in an image. Check the red portion of an pixel (r, g, b) tuple for hidden message characters (ASCII values). The red value of the first pixel is used for message_length of string. """ img = tools.open_image(input_image) ...
[ "def", "reveal", "(", "input_image", ":", "Union", "[", "str", ",", "IO", "[", "bytes", "]", "]", ")", ":", "img", "=", "tools", ".", "open_image", "(", "input_image", ")", "width", ",", "height", "=", "img", ".", "size", "message", "=", "\"\"", "i...
31.521739
12.913043
def _universal_newlines(fp): """ Wrap a file to convert newlines regardless of whether the file was opened with the "universal newlines" option or not. """ # if file was opened with universal newline support we don't need to convert if 'U' in getattr(fp, 'mode', ''): for line in fp: yield line...
[ "def", "_universal_newlines", "(", "fp", ")", ":", "# if file was opened with universal newline support we don't need to convert", "if", "'U'", "in", "getattr", "(", "fp", ",", "'mode'", ",", "''", ")", ":", "for", "line", "in", "fp", ":", "yield", "line", "else",...
32.642857
17.5
def write_str2file(pathname, astr): """writes a string to file""" fname = pathname fhandle = open(fname, 'wb') fhandle.write(astr) fhandle.close()
[ "def", "write_str2file", "(", "pathname", ",", "astr", ")", ":", "fname", "=", "pathname", "fhandle", "=", "open", "(", "fname", ",", "'wb'", ")", "fhandle", ".", "write", "(", "astr", ")", "fhandle", ".", "close", "(", ")" ]
26.833333
12
def filter(cls, datetimes, number, now=None, **options): """Return a set of datetimes, after filtering ``datetimes``. The result will be the ``datetimes`` which are ``number`` of units before ``now``, until ``now``, with approximately one unit between each of them. The first datetime f...
[ "def", "filter", "(", "cls", ",", "datetimes", ",", "number", ",", "now", "=", "None", ",", "*", "*", "options", ")", ":", "if", "not", "isinstance", "(", "number", ",", "int", ")", "or", "number", "<", "0", ":", "raise", "ValueError", "(", "'Inval...
35.355556
21.688889
def default(session): """Default unit test session. This is intended to be run **without** an interpreter set, so that the current ``python`` (on the ``PATH``) or the version of Python corresponding to the ``nox`` binary the ``PATH`` can run the tests. """ # Install all test dependencies, t...
[ "def", "default", "(", "session", ")", ":", "# Install all test dependencies, then install local packages in-place.", "session", ".", "install", "(", "\"mock\"", ",", "\"pytest\"", ",", "\"pytest-cov\"", ")", "for", "local_dep", "in", "LOCAL_DEPS", ":", "session", ".", ...
30.083333
16.527778
def _auto_adjust_panel_spans(dashboard): '''Adjust panel spans to take up the available width. For each group of panels that would be laid out on the same level, scale up the unspecified panel spans to fill up the level. ''' for row in dashboard.get('rows', []): levels = [] current_...
[ "def", "_auto_adjust_panel_spans", "(", "dashboard", ")", ":", "for", "row", "in", "dashboard", ".", "get", "(", "'rows'", ",", "[", "]", ")", ":", "levels", "=", "[", "]", "current_level", "=", "[", "]", "levels", ".", "append", "(", "current_level", ...
43
18.375
def fig2bmp(figure, width, height, dpi, zoom): """Returns wx.Bitmap from matplotlib chart Parameters ---------- fig: Object \tMatplotlib figure width: Integer \tImage width in pixels height: Integer \tImage height in pixels dpi = Float \tDC resolution """ dpi *= fl...
[ "def", "fig2bmp", "(", "figure", ",", "width", ",", "height", ",", "dpi", ",", "zoom", ")", ":", "dpi", "*=", "float", "(", "zoom", ")", "figure", ".", "set_figwidth", "(", "width", "/", "dpi", ")", "figure", ".", "set_figheight", "(", "height", "/",...
22.1
21.025
def postMetrics(self, name, suffix, description, default_value, **kwargs): '''Create a new metric. :param name: Name of metric :param suffix: Measurments in :param description: Description of what the metric is measuring :param default_value: The default value to use when a poin...
[ "def", "postMetrics", "(", "self", ",", "name", ",", "suffix", ",", "description", ",", "default_value", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'name'", "]", "=", "name", "kwargs", "[", "'suffix'", "]", "=", "suffix", "kwargs", "[", "'descr...
41.941176
19.705882
def Remove(self,directory,filename): """Deletes post from wordpress""" db = self._loadDB(directory) logger.debug("wp: Attempting to remove %s from wp"%(filename)) # See if this already exists in our DB if db.has_key(filename): pid=db[filename] logger.de...
[ "def", "Remove", "(", "self", ",", "directory", ",", "filename", ")", ":", "db", "=", "self", ".", "_loadDB", "(", "directory", ")", "logger", ".", "debug", "(", "\"wp: Attempting to remove %s from wp\"", "%", "(", "filename", ")", ")", "# See if this already ...
28.086957
20.217391
def registry_comparison(registry0, registry1): """Compares two dictionaries of registry keys returning their difference.""" comparison = {'created_keys': {}, 'deleted_keys': [], 'created_values': {}, 'deleted_values': {}, 'modified_values':...
[ "def", "registry_comparison", "(", "registry0", ",", "registry1", ")", ":", "comparison", "=", "{", "'created_keys'", ":", "{", "}", ",", "'deleted_keys'", ":", "[", "]", ",", "'created_values'", ":", "{", "}", ",", "'deleted_values'", ":", "{", "}", ",", ...
37.142857
15.785714
def encrypt(clear_text) -> str: """ Use config.json key to encrypt """ if not isinstance(clear_text, bytes): clear_text = str.encode(clear_text) cipher = Fernet(current_app.config['KEY']) return cipher.encrypt(clear_text).decode("utf-8")
[ "def", "encrypt", "(", "clear_text", ")", "->", "str", ":", "if", "not", "isinstance", "(", "clear_text", ",", "bytes", ")", ":", "clear_text", "=", "str", ".", "encode", "(", "clear_text", ")", "cipher", "=", "Fernet", "(", "current_app", ".", "config",...
46.833333
8.333333
def _read_function(schema): """Add a write method for named schema to a class. """ def func( filename, seq_label='sequence', alphabet=None, use_uids=True, **kwargs): # Use generic write class to write data. return _read( filename=filename, ...
[ "def", "_read_function", "(", "schema", ")", ":", "def", "func", "(", "filename", ",", "seq_label", "=", "'sequence'", ",", "alphabet", "=", "None", ",", "use_uids", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# Use generic write class to write data.", ...
25.333333
15
def stop(self, spider_name=None): """Stop the named running spider, or the first spider found, if spider_name is None""" if spider_name is None: spider_name = self.spider_name else: self.spider_name = spider_name if self.spider_name is None: self.spide...
[ "def", "stop", "(", "self", ",", "spider_name", "=", "None", ")", ":", "if", "spider_name", "is", "None", ":", "spider_name", "=", "self", ".", "spider_name", "else", ":", "self", ".", "spider_name", "=", "spider_name", "if", "self", ".", "spider_name", ...
48.444444
12.888889
def credit_card_security_code(self, card_type=None): """ Returns a security code string. """ sec_len = self._credit_card_type(card_type).security_code_length return self.numerify('#' * sec_len)
[ "def", "credit_card_security_code", "(", "self", ",", "card_type", "=", "None", ")", ":", "sec_len", "=", "self", ".", "_credit_card_type", "(", "card_type", ")", ".", "security_code_length", "return", "self", ".", "numerify", "(", "'#'", "*", "sec_len", ")" ]
53.5
11.75
def deepvalidation(self): """Perform deep validation of this element. Raises: :class:`DeepValidationError` """ if self.doc and self.doc.deepvalidation and self.set and self.set[0] != '_': try: self.doc.setdefinitions[self.set].testclass(self.cls) ...
[ "def", "deepvalidation", "(", "self", ")", ":", "if", "self", ".", "doc", "and", "self", ".", "doc", ".", "deepvalidation", "and", "self", ".", "set", "and", "self", ".", "set", "[", "0", "]", "!=", "'_'", ":", "try", ":", "self", ".", "doc", "."...
44.555556
20.888889
def get_publications(context, template='publications/publications.html'): """ Get all publications. """ types = Type.objects.filter(hidden=False) publications = Publication.objects.select_related() publications = publications.filter(external=False, type__in=types) publications = publications.order_by('-year', '...
[ "def", "get_publications", "(", "context", ",", "template", "=", "'publications/publications.html'", ")", ":", "types", "=", "Type", ".", "objects", ".", "filter", "(", "hidden", "=", "False", ")", "publications", "=", "Publication", ".", "objects", ".", "sele...
29.235294
23.235294
def _get_dependent_value(tag_values, dependent_tag_id): '''Extract (float) value of dependent tag or None if absent.''' try: values = tag_values[dependent_tag_id].split(",") return max([float(value) for value in values]) except KeyError: return None ex...
[ "def", "_get_dependent_value", "(", "tag_values", ",", "dependent_tag_id", ")", ":", "try", ":", "values", "=", "tag_values", "[", "dependent_tag_id", "]", ".", "split", "(", "\",\"", ")", "return", "max", "(", "[", "float", "(", "value", ")", "for", "valu...
39.111111
19.555556
async def create_text_channel(self, name, *, overwrites=None, category=None, reason=None, **options): """|coro| Creates a :class:`TextChannel` for the guild. Note that you need the :attr:`~Permissions.manage_channels` permission to create the channel. The ``overwrites`` parame...
[ "async", "def", "create_text_channel", "(", "self", ",", "name", ",", "*", ",", "overwrites", "=", "None", ",", "category", "=", "None", ",", "reason", "=", "None", ",", "*", "*", "options", ")", ":", "data", "=", "await", "self", ".", "_create_channel...
37.452381
25.428571
def get_calling_file(file_path=None, result='name'): """ Retrieve file_name or file_path of calling Python script """ # Get full path of calling python script if file_path is None: path = inspect.stack()[1][1] else: path = file_path name = path.split('/')[-1].split('.')[0] ...
[ "def", "get_calling_file", "(", "file_path", "=", "None", ",", "result", "=", "'name'", ")", ":", "# Get full path of calling python script", "if", "file_path", "is", "None", ":", "path", "=", "inspect", ".", "stack", "(", ")", "[", "1", "]", "[", "1", "]"...
25.294118
15.529412
def from_xy_array(cls, xy, shape): """ Convert an array (N,2) with a given image shape to a KeypointsOnImage object. Parameters ---------- xy : (N, 2) ndarray Coordinates of ``N`` keypoints on the original image, given as ``(N,2)`` array of xy-coordinates...
[ "def", "from_xy_array", "(", "cls", ",", "xy", ",", "shape", ")", ":", "keypoints", "=", "[", "Keypoint", "(", "x", "=", "coord", "[", "0", "]", ",", "y", "=", "coord", "[", "1", "]", ")", "for", "coord", "in", "xy", "]", "return", "KeypointsOnIm...
32.666667
23.047619
def undo(ui, repo, clname, **opts): """undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description. """ if repo[None].branch() != "default": raise hg_util.Abort("cannot run hg undo outsi...
[ "def", "undo", "(", "ui", ",", "repo", ",", "clname", ",", "*", "*", "opts", ")", ":", "if", "repo", "[", "None", "]", ".", "branch", "(", ")", "!=", "\"default\"", ":", "raise", "hg_util", ".", "Abort", "(", "\"cannot run hg undo outside default branch\...
35.333333
14.916667
def open_local_resource(cls, uri): """ Open a local resource. The container calls this method when it receives a request for a resource on a URL which was generated by Runtime.local_resource_url(). It will pass the URI from the original call to local_resource_url() back ...
[ "def", "open_local_resource", "(", "cls", ",", "uri", ")", ":", "if", "isinstance", "(", "uri", ",", "six", ".", "binary_type", ")", ":", "uri", "=", "uri", ".", "decode", "(", "'utf-8'", ")", "# If no resources_dir is set, then this XBlock cannot serve local reso...
50.621622
29.972973
def _script_to_har_entry(cls, script, url): ''' Return entry for embed script ''' entry = { 'request': {'url': url}, 'response': {'url': url, 'content': {'text': script}} } cls._set_entry_type(entry, INLINE_SCRIPT_ENTRY) return entry
[ "def", "_script_to_har_entry", "(", "cls", ",", "script", ",", "url", ")", ":", "entry", "=", "{", "'request'", ":", "{", "'url'", ":", "url", "}", ",", "'response'", ":", "{", "'url'", ":", "url", ",", "'content'", ":", "{", "'text'", ":", "script",...
29
20.6
def _convert_xml_to_shares(response): ''' <?xml version="1.0" encoding="utf-8"?> <EnumerationResults AccountName="https://myaccount.file.core.windows.net"> <Prefix>string-value</Prefix> <Marker>string-value</Marker> <MaxResults>int-value</MaxResults> <Shares> <Share> ...
[ "def", "_convert_xml_to_shares", "(", "response", ")", ":", "if", "response", "is", "None", "or", "response", ".", "body", "is", "None", ":", "return", "None", "shares", "=", "_list", "(", ")", "list_element", "=", "ETree", ".", "fromstring", "(", "respons...
32.491803
20.622951
def archive(self): """Archives an experiment""" pipe = self.redis.pipeline(transaction=True) pipe.srem(ACTIVE_EXPERIMENTS_REDIS_KEY, self.name) pipe.sadd(ARCHIVED_EXPERIMENTS_REDIS_KEY, self.name) pipe.execute()
[ "def", "archive", "(", "self", ")", ":", "pipe", "=", "self", ".", "redis", ".", "pipeline", "(", "transaction", "=", "True", ")", "pipe", ".", "srem", "(", "ACTIVE_EXPERIMENTS_REDIS_KEY", ",", "self", ".", "name", ")", "pipe", ".", "sadd", "(", "ARCHI...
41
15
def load_image(cls, filename, height=1, array=False, bounds=None, bare=False, **kwargs): """ Returns an raster element or raw numpy array from a PNG image file, using matplotlib. The specified height determines the bounds of the raster object in sheet coordinates: by default the...
[ "def", "load_image", "(", "cls", ",", "filename", ",", "height", "=", "1", ",", "array", "=", "False", ",", "bounds", "=", "None", ",", "bare", "=", "False", ",", "*", "*", "kwargs", ")", ":", "try", ":", "from", "matplotlib", "import", "pyplot", "...
39.914286
21.742857
def extract_row(self, row): """ get row number 'row' """ new_row = [] for col in range(self.get_grid_width()): new_row.append(self.get_tile(row, col)) return new_row
[ "def", "extract_row", "(", "self", ",", "row", ")", ":", "new_row", "=", "[", "]", "for", "col", "in", "range", "(", "self", ".", "get_grid_width", "(", ")", ")", ":", "new_row", ".", "append", "(", "self", ".", "get_tile", "(", "row", ",", "col", ...
27.875
10.625
def generateLowerBoundList(confidence, numUniqueFeatures, numLocationsPerObject, maxNumObjects): """ Metric: How unique is each object's most unique feature? Calculate the probabilistic lower bound for the number of occurrences of an object's most unique feature. For example, if confi...
[ "def", "generateLowerBoundList", "(", "confidence", ",", "numUniqueFeatures", ",", "numLocationsPerObject", ",", "maxNumObjects", ")", ":", "# We're choosing a location, checking its feature, and checking how many", "# *other* occurrences there are of this feature. So we check n - 1 locati...
48.541667
24.791667
def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): """Override this method to use values from the parsed uri to initialize the expected target. """ raise NotImplementedError("load_target...
[ "def", "load_target", "(", "cls", ",", "scheme", ",", "path", ",", "fragment", ",", "username", ",", "password", ",", "hostname", ",", "port", ",", "query", ",", "load_method", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", "\"lo...
41.75
13.5
def show(ndarray, min_val=None, max_val=None): """ Display an image. :param ndarray: The image as an ndarray :param min_val: The minimum pixel value in the image format :param max_val: The maximum pixel valie in the image format If min_val and max_val are not specified, attempts to infer whether the i...
[ "def", "show", "(", "ndarray", ",", "min_val", "=", "None", ",", "max_val", "=", "None", ")", ":", "# Create a temporary file with the suffix '.png'.", "fd", ",", "path", "=", "mkstemp", "(", "suffix", "=", "'.png'", ")", "os", ".", "close", "(", "fd", ")"...
36.705882
13.176471
def main(): """ Phenologs """ parser = argparse.ArgumentParser(description='Phenologs' """ By default, ontologies are cached locally and synced from a remote sparql endpoint ...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Phenologs'", "\"\"\"\n By default, ontologies are cached locally and synced from a remote sparql endpoint\n ...
40.95
21.2375
async def parse_headers(fp, _class=HTTPMessage): """Parses only RFC2822 headers from a file pointer. email Parser wants to see strings rather than bytes. But a TextIOWrapper around self.rfile would buffer too many bytes from the stream, bytes which we later need to read as bytes. So we read the corr...
[ "async", "def", "parse_headers", "(", "fp", ",", "_class", "=", "HTTPMessage", ")", ":", "headers", "=", "[", "]", "while", "True", ":", "line", "=", "await", "fp", ".", "readline", "(", ")", "headers", ".", "append", "(", "line", ")", "if", "len", ...
41.888889
16.111111
def moving_average(self, data, days): """ 計算移動平均數 :rtype: 序列 舊→新 """ result = [] data = data[:] for dummy in range(len(data) - int(days) + 1): result.append(round(sum(data[-days:]) / days, 2)) data.pop() result.reverse() return...
[ "def", "moving_average", "(", "self", ",", "data", ",", "days", ")", ":", "result", "=", "[", "]", "data", "=", "data", "[", ":", "]", "for", "dummy", "in", "range", "(", "len", "(", "data", ")", "-", "int", "(", "days", ")", "+", "1", ")", "...
26.333333
15.333333
def get_revision(): """ GET THE CURRENT GIT REVISION """ proc = Process("git log", ["git", "log", "-1"]) try: while True: line = proc.stdout.pop().strip().decode('utf8') if not line: continue if line.startswith("commit "): ...
[ "def", "get_revision", "(", ")", ":", "proc", "=", "Process", "(", "\"git log\"", ",", "[", "\"git\"", ",", "\"log\"", ",", "\"-1\"", "]", ")", "try", ":", "while", "True", ":", "line", "=", "proc", ".", "stdout", ".", "pop", "(", ")", ".", "strip"...
24.375
15.5
def most_common(self, n=None): '''List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abcdeabcdabcaba').most_common(3) [('a', 5), ('b', 4), ('c', 3)] ''' # Emulate Bag.sortedByCoun...
[ "def", "most_common", "(", "self", ",", "n", "=", "None", ")", ":", "# Emulate Bag.sortedByCount from Smalltalk", "if", "n", "is", "None", ":", "return", "sorted", "(", "self", ".", "items", "(", ")", ",", "key", "=", "_itemgetter", "(", "1", ")", ",", ...
40.75
24.083333
def slugs_camera_order_encode(self, target, pan, tilt, zoom, moveHome): ''' Orders generated to the SLUGS camera mount. target : The system reporting the action (uint8_t) pan : Order the mount to pan: -1 left, 0 No...
[ "def", "slugs_camera_order_encode", "(", "self", ",", "target", ",", "pan", ",", "tilt", ",", "zoom", ",", "moveHome", ")", ":", "return", "MAVLink_slugs_camera_order_message", "(", "target", ",", "pan", ",", "tilt", ",", "zoom", ",", "moveHome", ")" ]
67.916667
48.25
def find_detrend_keyword(header, type): """Search through header and find the elixir formated string(s) that match the the input 'type'. header is a FITS HDU. Elixir formated strings are crunid.type.filter/exptime.chipid.version. """ import re, string value='NULL' #print type fo...
[ "def", "find_detrend_keyword", "(", "header", ",", "type", ")", ":", "import", "re", ",", "string", "value", "=", "'NULL'", "#print type", "for", "h", "in", "header", ":", "g", "=", "str", "(", "h", ")", "if", "(", "string", ".", "find", "(", "g", ...
30.529412
17.235294
def get_lateration_parameters(all_points, indices, index, edm, W=None): """ Get parameters relevant for lateration from full all_points, edm and W. """ if W is None: W = np.ones(edm.shape) # delete points that are not considered anchors anchors = np.delete(all_points, indices, axis=0) r...
[ "def", "get_lateration_parameters", "(", "all_points", ",", "indices", ",", "index", ",", "edm", ",", "W", "=", "None", ")", ":", "if", "W", "is", "None", ":", "W", "=", "np", ".", "ones", "(", "edm", ".", "shape", ")", "# delete points that are not cons...
39.65625
13.78125
def _get_resource_hash(zone_name, record): """Returns the last ten digits of the sha256 hash of the combined arguments. Useful for generating unique resource IDs Args: zone_name (`str`): The name of the DNS Zone the record belongs to record (`dict`): A record dict to gen...
[ "def", "_get_resource_hash", "(", "zone_name", ",", "record", ")", ":", "record_data", "=", "defaultdict", "(", "int", ",", "record", ")", "if", "type", "(", "record_data", "[", "'GeoLocation'", "]", ")", "==", "dict", ":", "record_data", "[", "'GeoLocation'...
35.142857
19.285714
def decode_bytes(data: bytes, encoding: str = DEFAULT_CODING, errors: str = 'strict') -> str: """ 集中调用 decode """ return data.decode(encoding, errors)
[ "def", "decode_bytes", "(", "data", ":", "bytes", ",", "encoding", ":", "str", "=", "DEFAULT_CODING", ",", "errors", ":", "str", "=", "'strict'", ")", "->", "str", ":", "return", "data", ".", "decode", "(", "encoding", ",", "errors", ")" ]
32.4
15.6
def allowed_extension(*allowed): ''' refs: http://zhuoqiang.me/a/restful-pyramid Custom predict checking if the the file extension of the request URI is in the allowed set. ''' def predicate(info, request): log.debug(request.path) ext = os.path.splitext(request.path)[1] r...
[ "def", "allowed_extension", "(", "*", "allowed", ")", ":", "def", "predicate", "(", "info", ",", "request", ")", ":", "log", ".", "debug", "(", "request", ".", "path", ")", "ext", "=", "os", ".", "path", ".", "splitext", "(", "request", ".", "path", ...
30.071429
15.642857
def make_key(table_name, objid): """Create an object key for storage.""" key = datastore.Key() path = key.path_element.add() path.kind = table_name path.name = str(objid) return key
[ "def", "make_key", "(", "table_name", ",", "objid", ")", ":", "key", "=", "datastore", ".", "Key", "(", ")", "path", "=", "key", ".", "path_element", ".", "add", "(", ")", "path", ".", "kind", "=", "table_name", "path", ".", "name", "=", "str", "("...
28.428571
12
def from_data(data): """ Construct a Prettytable from list of rows. """ if len(data) == 0: # pragma: no cover return None else: ptable = PrettyTable() ptable.field_names = data[0].keys() for row in data: ptable.add_row(row) return ptable
[ "def", "from_data", "(", "data", ")", ":", "if", "len", "(", "data", ")", "==", "0", ":", "# pragma: no cover", "return", "None", "else", ":", "ptable", "=", "PrettyTable", "(", ")", "ptable", ".", "field_names", "=", "data", "[", "0", "]", ".", "key...
24.916667
11.416667
def get_all_static(): """ Get all the static files directories found by ``STATICFILES_FINDERS`` :return: set of paths (top-level folders only) """ static_dirs = set() for finder in settings.STATICFILES_FINDERS: finder = finders.get_finder(finder) if hasattr(finder, 'storages')...
[ "def", "get_all_static", "(", ")", ":", "static_dirs", "=", "set", "(", ")", "for", "finder", "in", "settings", ".", "STATICFILES_FINDERS", ":", "finder", "=", "finders", ".", "get_finder", "(", "finder", ")", "if", "hasattr", "(", "finder", ",", "'storage...
27.526316
18.052632
def modify_db_instance(name, allocated_storage=None, allow_major_version_upgrade=None, apply_immediately=None, auto_minor_version_upgrade=None, backup_retention_period=None, ca_certi...
[ "def", "modify_db_instance", "(", "name", ",", "allocated_storage", "=", "None", ",", "allow_major_version_upgrade", "=", "None", ",", "apply_immediately", "=", "None", ",", "auto_minor_version_upgrade", "=", "None", ",", "backup_retention_period", "=", "None", ",", ...
42.546667
15.613333
def get_default_config(self): """ Returns the default collector settings """ config = super(PhpFpmCollector, self).get_default_config() config.update({ 'host': 'localhost', 'port': 80, 'uri': 'fpm-status', 'byte_unit': ['byte'], ...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "PhpFpmCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'host'", ":", "'localhost'", ",", "'port'", ":", "80", ",", "'u...
28.230769
12.230769
def Substitute(self, pattern): """Formats given pattern with this substitution environment. A pattern can contain placeholders for variables (`%%foo%%`) and scopes (`%%bar.baz%%`) that are replaced with concrete values in this substiution environment (specified in the constructor). Args: pat...
[ "def", "Substitute", "(", "self", ",", "pattern", ")", ":", "if", "isinstance", "(", "pattern", ",", "bytes", ")", ":", "substs", "=", "[", "re", ".", "escape", "(", "subst", ".", "encode", "(", "\"ascii\"", ")", ")", "for", "subst", "in", "self", ...
31.083333
21.666667
def addLocation(self, locationUri, weight): """ add relevant location to the topic page @param locationUri: uri of the location to add @param weight: importance of the provided location (typically in range 1 - 50) """ assert isinstance(weight, (float, int)), "weight value...
[ "def", "addLocation", "(", "self", ",", "locationUri", ",", "weight", ")", ":", "assert", "isinstance", "(", "weight", ",", "(", "float", ",", "int", ")", ")", ",", "\"weight value has to be a positive or negative integer\"", "self", ".", "topicPage", "[", "\"lo...
54.375
21.625
def update(self, E=None, **F): """ Update ContextDict from dict/iterable E and F :return: Nothing :rtype: None """ if E is not None: if hasattr(E, 'keys'): for K in E: self.replace(K, E[K]) elif hasattr(E, 'items...
[ "def", "update", "(", "self", ",", "E", "=", "None", ",", "*", "*", "F", ")", ":", "if", "E", "is", "not", "None", ":", "if", "hasattr", "(", "E", ",", "'keys'", ")", ":", "for", "K", "in", "E", ":", "self", ".", "replace", "(", "K", ",", ...
29.222222
9.111111
def repl( # noqa: C901 old_ctx, prompt_kwargs=None, allow_system_commands=True, allow_internal_commands=True, ): """ Start an interactive shell. All subcommands are available in it. :param old_ctx: The current Click context. :param prompt_kwargs: Parameters passed to :py:func:`...
[ "def", "repl", "(", "# noqa: C901", "old_ctx", ",", "prompt_kwargs", "=", "None", ",", "allow_system_commands", "=", "True", ",", "allow_internal_commands", "=", "True", ",", ")", ":", "# parent should be available, but we're not going to bother if not", "group_ctx", "=",...
28.333333
20.422222
def _fitnesses_to_probabilities(fitnesses): """Return a list of probabilities proportional to fitnesses.""" # Do not allow negative fitness values min_fitness = min(fitnesses) if min_fitness < 0.0: # Make smallest fitness value 0 fitnesses = map(lambda f: f - min_fitness, fitnesses) ...
[ "def", "_fitnesses_to_probabilities", "(", "fitnesses", ")", ":", "# Do not allow negative fitness values", "min_fitness", "=", "min", "(", "fitnesses", ")", "if", "min_fitness", "<", "0.0", ":", "# Make smallest fitness value 0", "fitnesses", "=", "map", "(", "lambda",...
35.48
15.92
def getDate(self): "returns the GMT response datetime or None" date = self.headers.get('date') if date: date = self.convertTimeString(date) return date
[ "def", "getDate", "(", "self", ")", ":", "date", "=", "self", ".", "headers", ".", "get", "(", "'date'", ")", "if", "date", ":", "date", "=", "self", ".", "convertTimeString", "(", "date", ")", "return", "date" ]
31.666667
14.333333
def compute_busiest_date(feed: "Feed", dates: List[str]) -> str: """ Given a list of dates, return the first date that has the maximum number of active trips. Notes ----- Assume the following feed attributes are not ``None``: - Those used in :func:`compute_trip_activity` """ f = f...
[ "def", "compute_busiest_date", "(", "feed", ":", "\"Feed\"", ",", "dates", ":", "List", "[", "str", "]", ")", "->", "str", ":", "f", "=", "feed", ".", "compute_trip_activity", "(", "dates", ")", "s", "=", "[", "(", "f", "[", "c", "]", ".", "sum", ...
28.133333
20.133333
def get_role(self, item, state_root, from_state=False): """ Used to retrieve an identity role. Args: item (string): the name of the role to be fetched state_root(string): The state root of the previous block. from_state (bool): Whether the identity value shoul...
[ "def", "get_role", "(", "self", ",", "item", ",", "state_root", ",", "from_state", "=", "False", ")", ":", "if", "from_state", ":", "# if from state use identity_view and do not add to cache", "if", "self", ".", "_identity_view", "is", "None", ":", "self", ".", ...
41.4
15.16
def __get_output_filenames(self): """ Set up the output filenames. If more than one file is being written out, we need appended filenames. :return: """ # if there is only one file, use the normal filename with nothing appended. if len(self.noaa_data_sorted["Data"]) == 1: ...
[ "def", "__get_output_filenames", "(", "self", ")", ":", "# if there is only one file, use the normal filename with nothing appended.", "if", "len", "(", "self", ".", "noaa_data_sorted", "[", "\"Data\"", "]", ")", "==", "1", ":", "self", ".", "output_filenames", ".", "...
47.866667
24.666667
def use_comparative_assessment_view(self): """Pass through to provider AssessmentLookupSession.use_comparative_assessment_view""" self._object_views['assessment'] = COMPARATIVE # self._get_provider_session('assessment_lookup_session') # To make sure the session is tracked for session in ...
[ "def", "use_comparative_assessment_view", "(", "self", ")", ":", "self", ".", "_object_views", "[", "'assessment'", "]", "=", "COMPARATIVE", "# self._get_provider_session('assessment_lookup_session') # To make sure the session is tracked", "for", "session", "in", "self", ".", ...
52.555556
17.666667
def _correct_splitlines_in_headers(markers, lines): """ Corrects markers by removing splitlines deemed to be inside header blocks. """ updated_markers = "" i = 0 in_header_block = False for m in markers: # Only set in_header_block flag when we hit an 's' and line is a header ...
[ "def", "_correct_splitlines_in_headers", "(", "markers", ",", "lines", ")", ":", "updated_markers", "=", "\"\"", "i", "=", "0", "in_header_block", "=", "False", "for", "m", "in", "markers", ":", "# Only set in_header_block flag when we hit an 's' and line is a header", ...
31.428571
18.714286
def leverages(self, block='X'): """ Calculate the leverages for each observation :return: :rtype: """ # TODO check with matlab and simca try: if block == 'X': return np.dot(self.scores_t, np.dot(np.linalg.inv(np.dot(self.scores_t.T, sel...
[ "def", "leverages", "(", "self", ",", "block", "=", "'X'", ")", ":", "# TODO check with matlab and simca", "try", ":", "if", "block", "==", "'X'", ":", "return", "np", ".", "dot", "(", "self", ".", "scores_t", ",", "np", ".", "dot", "(", "np", ".", "...
40.3125
22.0625
def _lookup_first(dictionary, key): ''' Lookup the first value given a key. Returns the first value if the key refers to a list or the value itself. :param dict dictionary: The dictionary to search :param str key: The key to get :return: Returns the first value available for the key :rtyp...
[ "def", "_lookup_first", "(", "dictionary", ",", "key", ")", ":", "value", "=", "dictionary", "[", "key", "]", "if", "type", "(", "value", ")", "==", "list", ":", "return", "value", "[", "0", "]", "else", ":", "return", "value" ]
25.235294
22.411765
def loaddfits(fitsname, coordtype='azel', loadtype='temperature', starttime=None, endtime=None, pixelids=None, scantypes=None, mode=0, **kwargs): """Load a decode array from a DFITS file. Args: fitsname (str): Name of DFITS file. coordtype (str): Coordinate type included into a de...
[ "def", "loaddfits", "(", "fitsname", ",", "coordtype", "=", "'azel'", ",", "loadtype", "=", "'temperature'", ",", "starttime", "=", "None", ",", "endtime", "=", "None", ",", "pixelids", "=", "None", ",", "scantypes", "=", "None", ",", "mode", "=", "0", ...
41.620253
20.059072
def load_file(cls, file_path): """Load a Sudoku from file. :param file_path: The path to the file to load_file. :type file_path: str, unicode :return: A Sudoku instance with the parsed information from the file. :rtype: :py:class:`dlxsudoku.sudoku.Sudoku` ...
[ "def", "load_file", "(", "cls", ",", "file_path", ")", ":", "with", "open", "(", "os", ".", "path", ".", "abspath", "(", "file_path", ")", ",", "'rt'", ")", "as", "f", ":", "s", "=", "Sudoku", "(", "f", ".", "read", "(", ")", ".", "strip", "(",...
33.076923
13.692308
def fit_from_cfg(cls, df, cfgname, debug=False, min_segment_size=None, outcfgname=None): """ Parameters ---------- df : DataFrame The dataframe which contains the columns to use for the estimation. cfgname : string The name of the yaml config file which de...
[ "def", "fit_from_cfg", "(", "cls", ",", "df", ",", "cfgname", ",", "debug", "=", "False", ",", "min_segment_size", "=", "None", ",", "outcfgname", "=", "None", ")", ":", "logger", ".", "debug", "(", "'start: fit from configuration {}'", ".", "format", "(", ...
42.064516
20.322581
def mainswitch_state(frames): """parse a mainswitch.state message""" reader = MessageReader(frames) res = reader.string("command").bool("state").assert_end().get() if res.command != "mainswitch.state": raise MessageParserError("Command is not 'mainswitch.state'") retu...
[ "def", "mainswitch_state", "(", "frames", ")", ":", "reader", "=", "MessageReader", "(", "frames", ")", "res", "=", "reader", ".", "string", "(", "\"command\"", ")", ".", "bool", "(", "\"state\"", ")", ".", "assert_end", "(", ")", ".", "get", "(", ")",...
47
13.571429
def sample_less_than_condition(choices_in, condition): """Creates a random sample from choices without replacement, subject to the condition that each element of the output is greater than the corresponding element of the condition array. condition should be in ascending order. """ output = np....
[ "def", "sample_less_than_condition", "(", "choices_in", ",", "condition", ")", ":", "output", "=", "np", ".", "zeros", "(", "min", "(", "condition", ".", "shape", "[", "0", "]", ",", "choices_in", ".", "shape", "[", "0", "]", ")", ")", "choices", "=", ...
44.176471
13.470588
def index(): """Show the landing page.""" gene_lists = app.db.gene_lists() if app.config['STORE_ENABLED'] else [] queries = app.db.gemini_queries() if app.config['STORE_ENABLED'] else [] case_groups = {} for case in app.db.cases(): key = (case.variant_source, case.variant_type, case.variant...
[ "def", "index", "(", ")", ":", "gene_lists", "=", "app", ".", "db", ".", "gene_lists", "(", ")", "if", "app", ".", "config", "[", "'STORE_ENABLED'", "]", "else", "[", "]", "queries", "=", "app", ".", "db", ".", "gemini_queries", "(", ")", "if", "ap...
39.571429
22
def wait_for_batches(self, batch_ids, timeout=None): """Locks until a list of batch ids is committed to the block chain or a timeout is exceeded. Returns the statuses of those batches. Args: batch_ids (list of str): The ids of the batches to wait for timeout(int): Maximu...
[ "def", "wait_for_batches", "(", "self", ",", "batch_ids", ",", "timeout", "=", "None", ")", ":", "self", ".", "_batch_tracker", ".", "watch_statuses", "(", "self", ",", "batch_ids", ")", "timeout", "=", "timeout", "or", "DEFAULT_TIMEOUT", "start_time", "=", ...
40.925926
22
def find_version_by_regex(file_source): # type: (str)->Optional[str] """ Regex for dunder version """ if not file_source: return None version_match = re.search(r"^version=['\"]([^'\"]*)['\"]", file_source, re.M) if version_match: return version_match.group(1) return None
[ "def", "find_version_by_regex", "(", "file_source", ")", ":", "# type: (str)->Optional[str]", "if", "not", "file_source", ":", "return", "None", "version_match", "=", "re", ".", "search", "(", "r\"^version=['\\\"]([^'\\\"]*)['\\\"]\"", ",", "file_source", ",", "re", "...
30.7
16.7
def plot_powerlaw(exp, startx, starty, width=None, **kwargs): r''' Plot a power-law. :arguments: **exp** (``float``) The power-law exponent. **startx, starty** (``float``) Start coordinates. :options: **width, height, endx, endy** (``float``) Definition of the end coordinate (only on of these o...
[ "def", "plot_powerlaw", "(", "exp", ",", "startx", ",", "starty", ",", "width", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# get options/defaults", "endx", "=", "kwargs", ".", "pop", "(", "'endx'", ",", "None", ")", "endy", "=", "kwargs", ".", ...
25.819444
24.375
def predict(self, data): """ Predict new data for each group in the segmentation. Parameters ---------- data : pandas.DataFrame Data to use for prediction. Must have a column with the same name as `segmentation_col`. Returns ------- ...
[ "def", "predict", "(", "self", ",", "data", ")", ":", "with", "log_start_finish", "(", "'predicting models in group {}'", ".", "format", "(", "self", ".", "name", ")", ",", "logger", ")", ":", "results", "=", "[", "self", ".", "models", "[", "name", "]",...
33.347826
20.565217
def median(data, channels=None): """ Calculate the median of the events in an FCSData object. Parameters ---------- data : FCSData or numpy array NxD flow cytometry data where N is the number of events and D is the number of parameters (aka channels). channels : int or str or li...
[ "def", "median", "(", "data", ",", "channels", "=", "None", ")", ":", "# Slice data to take statistics from", "if", "channels", "is", "None", ":", "data_stats", "=", "data", "else", ":", "data_stats", "=", "data", "[", ":", ",", "channels", "]", "# Calculate...
28.37037
19.851852
def clean_proced(self, proced): """Small helper function to delete the features from the final dictionary. These features are mostly interesting for debugging but won't be relevant for most users. """ for loc in proced: try: del loc['all_countries'] ...
[ "def", "clean_proced", "(", "self", ",", "proced", ")", ":", "for", "loc", "in", "proced", ":", "try", ":", "del", "loc", "[", "'all_countries'", "]", "except", "KeyError", ":", "pass", "try", ":", "del", "loc", "[", "'matrix'", "]", "except", "KeyErro...
28.558824
15.411765
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(sel...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'text'", ")", "and", "self", ".", "text", "is", "not", "None", ":", "_dict", "[", "'text'", "]", "=", "self", ".", "text", "if", "hasattr", "(",...
47.2
18.1
def hour_match(data, hours): """ matching of days in time columns for data filtering """ hours = [hours] if isinstance(hours, int) else hours return data.isin(hours)
[ "def", "hour_match", "(", "data", ",", "hours", ")", ":", "hours", "=", "[", "hours", "]", "if", "isinstance", "(", "hours", ",", "int", ")", "else", "hours", "return", "data", ".", "isin", "(", "hours", ")" ]
30
9.333333
def CleanseRawStrings(raw_lines): """Removes C++11 raw strings from lines. Before: static const char kData[] = R"( multi-line string )"; After: static const char kData[] = "" (replaced by blank line) ""; Args: raw_lines: list of raw lines. Return...
[ "def", "CleanseRawStrings", "(", "raw_lines", ")", ":", "delimiter", "=", "None", "lines_without_raw_strings", "=", "[", "]", "for", "line", "in", "raw_lines", ":", "if", "delimiter", ":", "# Inside a raw string, look for the end", "end", "=", "line", ".", "find",...
33.972973
19.986486
def add_access_controller(self, name: str, func: Callable, endpoint: bool = False): """Add an access controller. If `name` is None it is added at application level, else if is considered as a blueprint name. If `endpoint` is True then it is considered as an endpoint. """ ...
[ "def", "add_access_controller", "(", "self", ",", "name", ":", "str", ",", "func", ":", "Callable", ",", "endpoint", ":", "bool", "=", "False", ")", ":", "auth_state", "=", "self", ".", "extensions", "[", "auth_service", ".", "name", "]", "adder", "=", ...
39.411765
20.647059
def make_wire_commands(*ids): """Assemble the commands.""" cmd_to_wire = { cmd: sum(ord(c) << (i * 8) for i, c in enumerate(cmd)) for cmd in ids } wire_to_cmd = {wire: cmd for cmd, wire in six.iteritems(cmd_to_wire)} return cmd_to_wire, wire_to_cmd
[ "def", "make_wire_commands", "(", "*", "ids", ")", ":", "cmd_to_wire", "=", "{", "cmd", ":", "sum", "(", "ord", "(", "c", ")", "<<", "(", "i", "*", "8", ")", "for", "i", ",", "c", "in", "enumerate", "(", "cmd", ")", ")", "for", "cmd", "in", "...
36.857143
20.571429
def add_to_groups(self, groups=None, all_groups=False, group_type=None): """ Add user to some (typically PLC) groups. Note that, if you add to no groups, the effect is simply to do an "add to organization Everybody group", so we let that be done. :param groups: list of group names the u...
[ "def", "add_to_groups", "(", "self", ",", "groups", "=", "None", ",", "all_groups", "=", "False", ",", "group_type", "=", "None", ")", ":", "if", "all_groups", ":", "if", "groups", "or", "group_type", ":", "raise", "ArgumentError", "(", "\"When adding to all...
53.541667
24.625
def resultsFor( self, ps ): """Retrieve a list of all results associated with the given parameters. :param ps: the parameters :returns: a list of results, which may be empty""" k = self._parametersAsIndex(ps) if k in self._results.keys(): # filter out pending job ids...
[ "def", "resultsFor", "(", "self", ",", "ps", ")", ":", "k", "=", "self", ".", "_parametersAsIndex", "(", "ps", ")", "if", "k", "in", "self", ".", "_results", ".", "keys", "(", ")", ":", "# filter out pending job ids, which can be anything except dicts", "retur...
42
16.818182
def addpackage(sys_sitedir, pthfile, known_dirs): """ Wrapper for site.addpackage Try and work out which directories are added by the .pth and add them to the known_dirs set :param sys_sitedir: system site-packages directory :param pthfile: path file to add :param known_dirs: set of known ...
[ "def", "addpackage", "(", "sys_sitedir", ",", "pthfile", ",", "known_dirs", ")", ":", "with", "open", "(", "join", "(", "sys_sitedir", ",", "pthfile", ")", ")", "as", "f", ":", "for", "n", ",", "line", "in", "enumerate", "(", "f", ")", ":", "if", "...
36.444444
13.277778
def path_complete(self, text: str, line: str, begidx: int, endidx: int, path_filter: Optional[Callable[[str], bool]] = None) -> List[str]: """Performs completion of local file system paths :param text: the string prefix we are attempting to match (all returned matches must begin w...
[ "def", "path_complete", "(", "self", ",", "text", ":", "str", ",", "line", ":", "str", ",", "begidx", ":", "int", ",", "endidx", ":", "int", ",", "path_filter", ":", "Optional", "[", "Callable", "[", "[", "str", "]", ",", "bool", "]", "]", "=", "...
41.307692
23.167832
def verify_existence_and_get(id, table, name=None, get_id=False): """Verify the existence of a resource in the database and then return it if it exists, according to the condition, or raise an exception. :param id: id of the resource :param table: the table object :param name: the name of the r...
[ "def", "verify_existence_and_get", "(", "id", ",", "table", ",", "name", "=", "None", ",", "get_id", "=", "False", ")", ":", "where_clause", "=", "table", ".", "c", ".", "id", "==", "id", "if", "name", ":", "where_clause", "=", "table", ".", "c", "."...
31.714286
19.892857