text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def send_put(self, mri, attribute_name, value): """Abstract method to dispatch a Put to the server Args: mri (str): The mri of the Block attribute_name (str): The name of the Attribute within the Block value: The value to put """ path = attribute_name...
[ "def", "send_put", "(", "self", ",", "mri", ",", "attribute_name", ",", "value", ")", ":", "path", "=", "attribute_name", "+", "\".value\"", "typ", ",", "value", "=", "convert_to_type_tuple_value", "(", "serialize_object", "(", "value", ")", ")", "if", "isin...
39.2
0.001992
def iter_qs(qs, adapter): '''Safely iterate over a DB QuerySet yielding ES documents''' for obj in qs.no_cache().no_dereference().timeout(False): if adapter.is_indexable(obj): try: doc = adapter.from_model(obj).to_dict(include_meta=True) yield doc ...
[ "def", "iter_qs", "(", "qs", ",", "adapter", ")", ":", "for", "obj", "in", "qs", ".", "no_cache", "(", ")", ".", "no_dereference", "(", ")", ".", "timeout", "(", "False", ")", ":", "if", "adapter", ".", "is_indexable", "(", "obj", ")", ":", "try", ...
45.909091
0.001942
def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None): """This is used by the interact() method. """ while self.isalive(): r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], []) if self.child_fd in r: da...
[ "def", "__interact_copy", "(", "self", ",", "escape_character", "=", "None", ",", "input_filter", "=", "None", ",", "output_filter", "=", "None", ")", ":", "while", "self", ".", "isalive", "(", ")", ":", "r", ",", "w", ",", "e", "=", "self", ".", "__...
43.73913
0.013619
def import_package(rel_path_to_package, package_name): """Imports a python package into the current namespace. Parameters ---------- rel_path_to_package : str Path to the package containing director relative from this script's directory. package_name : str The name of the pa...
[ "def", "import_package", "(", "rel_path_to_package", ",", "package_name", ")", ":", "try", ":", "curr_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", "except", "NameError", ":", "curr_dir", ...
30.36
0.001277
def create_incidence_matrix(self, weights=None, fmt='coo', drop_zeros=False): r""" Creates a weighted incidence matrix in the desired sparse format Parameters ---------- weights : array_like, optional An array containing the throat val...
[ "def", "create_incidence_matrix", "(", "self", ",", "weights", "=", "None", ",", "fmt", "=", "'coo'", ",", "drop_zeros", "=", "False", ")", ":", "# Check if provided data is valid", "if", "weights", "is", "None", ":", "weights", "=", "sp", ".", "ones", "(", ...
37.604938
0.00096
def _eval_call(self, node): """ Evaluate a function call :param node: Node to eval :return: Result of node """ try: func = self.functions[node.func.id] except KeyError: raise NameError(node.func.id) value = func( *(sel...
[ "def", "_eval_call", "(", "self", ",", "node", ")", ":", "try", ":", "func", "=", "self", ".", "functions", "[", "node", ".", "func", ".", "id", "]", "except", "KeyError", ":", "raise", "NameError", "(", "node", ".", "func", ".", "id", ")", "value"...
23.173913
0.003604
def evalPDF(self, u_values): '''Returns the PDF of the uncertain parameter evaluated at the values provided in u_values. :param iterable u_values: values of the uncertain parameter at which to evaluate the PDF *Example Usage* :: >>> u = UniformParameter() ...
[ "def", "evalPDF", "(", "self", ",", "u_values", ")", ":", "if", "isinstance", "(", "u_values", ",", "np", ".", "ndarray", ")", ":", "return", "self", ".", "_evalPDF", "(", "u_values", ")", "else", ":", "try", ":", "iter", "(", "u_values", ")", "retur...
29.391304
0.004298
def format_py2js(cls, datetime_format): """Convert python datetime format to moment datetime format.""" for js_format, py_format in cls.format_map: datetime_format = datetime_format.replace(py_format, js_format) return datetime_format
[ "def", "format_py2js", "(", "cls", ",", "datetime_format", ")", ":", "for", "js_format", ",", "py_format", "in", "cls", ".", "format_map", ":", "datetime_format", "=", "datetime_format", ".", "replace", "(", "py_format", ",", "js_format", ")", "return", "datet...
53.2
0.007407
def get_catalog_by_name(name): """ Grabs a catalog by name, if its there on the api key. Otherwise, an error is thrown (mirroring the API) """ kwargs = { 'name' : name, } result = util.callm("%s/%s" % ('catalog', 'profile'), kwargs) return Catalog(**util.fix(result['respo...
[ "def", "get_catalog_by_name", "(", "name", ")", ":", "kwargs", "=", "{", "'name'", ":", "name", ",", "}", "result", "=", "util", ".", "callm", "(", "\"%s/%s\"", "%", "(", "'catalog'", ",", "'profile'", ")", ",", "kwargs", ")", "return", "Catalog", "(",...
32.9
0.005917
def distribution_files(self) -> Iterator[str]: """Find distribution packages.""" # This is verbatim from flake8 if self.distribution.packages: package_dirs = self.distribution.package_dir or {} for package in self.distribution.packages: pkg_dir = package ...
[ "def", "distribution_files", "(", "self", ")", "->", "Iterator", "[", "str", "]", ":", "# This is verbatim from flake8", "if", "self", ".", "distribution", ".", "packages", ":", "package_dirs", "=", "self", ".", "distribution", ".", "package_dir", "or", "{", "...
43.166667
0.002519
def _do_report(self, report, in_port, msg): """the process when the querier received a REPORT message.""" datapath = msg.datapath ofproto = datapath.ofproto parser = datapath.ofproto_parser if ofproto.OFP_VERSION == ofproto_v1_0.OFP_VERSION: size = 65535 else...
[ "def", "_do_report", "(", "self", ",", "report", ",", "in_port", ",", "msg", ")", ":", "datapath", "=", "msg", ".", "datapath", "ofproto", "=", "datapath", ".", "ofproto", "parser", "=", "datapath", ".", "ofproto_parser", "if", "ofproto", ".", "OFP_VERSION...
36.185185
0.001994
def _find_detections(cum_net_resp, nodes, threshold, thresh_type, samp_rate, realstations, length): """ Find detections within the cumulative network response. :type cum_net_resp: numpy.ndarray :param cum_net_resp: Array of cumulative network response for nodes :type nodes: lis...
[ "def", "_find_detections", "(", "cum_net_resp", ",", "nodes", ",", "threshold", ",", "thresh_type", ",", "samp_rate", ",", "realstations", ",", "length", ")", ":", "cum_net_resp", "=", "np", ".", "nan_to_num", "(", "cum_net_resp", ")", "# Force no NaNs", "if", ...
43.253968
0.000359
def _message_hostgroup_parse(self, message): """ Parse given message and return list of group names and socket information. Socket information is parsed in :meth:`.WBeaconGouverneurMessenger._message_address_parse` method :param message: bytes :return: tuple of list of group names and WIPV4SocketInfo """ s...
[ "def", "_message_hostgroup_parse", "(", "self", ",", "message", ")", ":", "splitter_count", "=", "message", ".", "count", "(", "WHostgroupBeaconMessenger", ".", "__message_groups_splitter__", ")", "if", "splitter_count", "==", "0", ":", "return", "[", "]", ",", ...
49.1
0.024975
def get_env(): """ Read environment from ENV and mangle it to a (lower case) representation Note: gcdt.utils get_env() is used in many cloudformation.py templates :return: Environment as lower case string (or None if not matched) """ env = os.getenv('ENV', os.getenv('env', None)) if env: ...
[ "def", "get_env", "(", ")", ":", "env", "=", "os", ".", "getenv", "(", "'ENV'", ",", "os", ".", "getenv", "(", "'env'", ",", "None", ")", ")", "if", "env", ":", "env", "=", "env", ".", "lower", "(", ")", "return", "env" ]
34.8
0.002801
def UpdateAcqEraEndDate(self, acquisition_era_name ="", end_date=0): """ Input dictionary has to have the following keys: acquisition_era_name, end_date. """ if acquisition_era_name =="" or end_date==0: dbsExceptionHandler('dbsException-invalid-input', "acquisition_er...
[ "def", "UpdateAcqEraEndDate", "(", "self", ",", "acquisition_era_name", "=", "\"\"", ",", "end_date", "=", "0", ")", ":", "if", "acquisition_era_name", "==", "\"\"", "or", "end_date", "==", "0", ":", "dbsExceptionHandler", "(", "'dbsException-invalid-input'", ",",...
39.75
0.018433
def store_policy(self, pol_id, policy): """Store the policy. Policy is maintained as a dictionary of pol ID. """ if pol_id not in self.policies: self.policies[pol_id] = policy self.policy_cnt += 1
[ "def", "store_policy", "(", "self", ",", "pol_id", ",", "policy", ")", ":", "if", "pol_id", "not", "in", "self", ".", "policies", ":", "self", ".", "policies", "[", "pol_id", "]", "=", "policy", "self", ".", "policy_cnt", "+=", "1" ]
30.75
0.007905
def InitMapping(self, values): """Initializes with a map from value to probability. values: map from value to probability """ for value, prob in values.iteritems(): self.Set(value, prob)
[ "def", "InitMapping", "(", "self", ",", "values", ")", ":", "for", "value", ",", "prob", "in", "values", ".", "iteritems", "(", ")", ":", "self", ".", "Set", "(", "value", ",", "prob", ")" ]
32.142857
0.008658
def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can ea...
[ "def", "compare_networks", "(", "self", ",", "other", ")", ":", "if", "self", ".", "_version", "<", "other", ".", "_version", ":", "return", "-", "1", "if", "self", ".", "_version", ">", "other", ".", "_version", ":", "return", "1", "# self._version == o...
36.58
0.001065
def record_list_projects(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /record-xxxx/listProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects """ return DXHTTPRequest('/%s/listProjec...
[ "def", "record_list_projects", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/listProjects'", "%", "object_id", ",", "input_params", ",", "always_...
54.428571
0.010336
def add_tip_labels_to_axes(self): """ Add text offset from tips of tree with correction for orientation, and fixed_order which is usually used in multitree plotting. """ # get tip-coords and replace if using fixed_order if self.style.orient in ("up", "down"): ...
[ "def", "add_tip_labels_to_axes", "(", "self", ")", ":", "# get tip-coords and replace if using fixed_order", "if", "self", ".", "style", ".", "orient", "in", "(", "\"up\"", ",", "\"down\"", ")", ":", "ypos", "=", "np", ".", "zeros", "(", "self", ".", "ntips", ...
41.27027
0.003199
def clear_rtag(opts): ''' Remove the rtag file ''' try: os.remove(rtag(opts)) except OSError as exc: if exc.errno != errno.ENOENT: # Using __str__() here to get the fully-formatted error message # (error number, error message, path) log.warning('En...
[ "def", "clear_rtag", "(", "opts", ")", ":", "try", ":", "os", ".", "remove", "(", "rtag", "(", "opts", ")", ")", "except", "OSError", "as", "exc", ":", "if", "exc", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "# Using __str__() here to get the fully...
32.727273
0.002703
def setbit(self, name, offset, value): """ Flag the ``offset`` in the key as ``value``. Returns a boolean indicating the previous value of ``offset``. :param name: str the name of the redis key :param offset: int :param value: :return: Future() """ ...
[ "def", "setbit", "(", "self", ",", "name", ",", "offset", ",", "value", ")", ":", "with", "self", ".", "pipe", "as", "pipe", ":", "return", "pipe", ".", "setbit", "(", "self", ".", "redis_key", "(", "name", ")", ",", "offset", ",", "value", ")" ]
33.916667
0.004785
def _overwrite(self, filename, func, force=False): """Overwrite a file with the specified contents. Write times are tracked, too-frequent overwrites are skipped, for performance reasons. :param filename: The path under the html dir to write to. :param func: A no-arg function that returns the contents ...
[ "def", "_overwrite", "(", "self", ",", "filename", ",", "func", ",", "force", "=", "False", ")", ":", "now", "=", "int", "(", "time", ".", "time", "(", ")", "*", "1000", ")", "last_overwrite_time", "=", "self", ".", "_last_overwrite_time", ".", "get", ...
49.647059
0.00814
def compute(self): """ This method can be used for computing one MaxSAT solution, i.e. for computing an assignment satisfying all hard clauses of the input formula and maximizing the sum of weights of satisfied soft clauses. It is a wrapper for the int...
[ "def", "compute", "(", "self", ")", ":", "# simply apply MaxSAT only once", "res", "=", "self", ".", "compute_", "(", ")", "if", "res", ":", "# extracting a model", "self", ".", "model", "=", "self", ".", "oracle", ".", "get_model", "(", ")", "self", ".", ...
38.470588
0.001491
def get_doc_id(document_pb, expected_prefix): """Parse a document ID from a document protobuf. Args: document_pb (google.cloud.proto.firestore.v1beta1.\ document_pb2.Document): A protobuf for a document that was created in a ``CreateDocument`` RPC. expected_prefix (str):...
[ "def", "get_doc_id", "(", "document_pb", ",", "expected_prefix", ")", ":", "prefix", ",", "document_id", "=", "document_pb", ".", "name", ".", "rsplit", "(", "DOCUMENT_PATH_DELIMITER", ",", "1", ")", "if", "prefix", "!=", "expected_prefix", ":", "raise", "Valu...
32.038462
0.001166
def run(self, background=False): """ Method to start the worker. Parameters ---------- background: bool If set to False (Default). the worker is executed in the current thread. If True, a new daemon thread is created that runs the worker. This is useful in a single worker scenario/when the com...
[ "def", "run", "(", "self", ",", "background", "=", "False", ")", ":", "if", "background", ":", "self", ".", "worker_id", "+=", "str", "(", "threading", ".", "get_ident", "(", ")", ")", "self", ".", "thread", "=", "threading", ".", "Thread", "(", "tar...
30.315789
0.040404
def _prepare_if_args(stmt): """Removes parentheses from an "if" directive's arguments""" args = stmt['args'] if args and args[0].startswith('(') and args[-1].endswith(')'): args[0] = args[0][1:].lstrip() args[-1] = args[-1][:-1].rstrip() start = int(not args[0]) end = len(arg...
[ "def", "_prepare_if_args", "(", "stmt", ")", ":", "args", "=", "stmt", "[", "'args'", "]", "if", "args", "and", "args", "[", "0", "]", ".", "startswith", "(", "'('", ")", "and", "args", "[", "-", "1", "]", ".", "endswith", "(", "')'", ")", ":", ...
40.888889
0.00266
def size(self): """Calculate and return the file size in bytes.""" old = self.__file.tell() # old position self.__file.seek(0, 2) # end of file n_bytes = self.__file.tell() # file size in bytes self.__file.seek(old) # back to old position r...
[ "def", "size", "(", "self", ")", ":", "old", "=", "self", ".", "__file", ".", "tell", "(", ")", "# old position", "self", ".", "__file", ".", "seek", "(", "0", ",", "2", ")", "# end of file", "n_bytes", "=", "self", ".", "__file", ".", "tell", "(",...
32.4
0.006006
def parse_logical_form(self, logical_form: str, remove_var_function: bool = True) -> Expression: """ Takes a logical form as a string, maps its tokens using the mapping and returns a parsed expression. Parameters ---------- l...
[ "def", "parse_logical_form", "(", "self", ",", "logical_form", ":", "str", ",", "remove_var_function", ":", "bool", "=", "True", ")", "->", "Expression", ":", "if", "not", "logical_form", ".", "startswith", "(", "\"(\"", ")", ":", "logical_form", "=", "f\"({...
54.066667
0.006663
def __expand_meta_datas(meta_datas, meta_datas_expanded): """ expand meta_datas to one level Args: meta_datas (dict/list): maybe in nested format Returns: list: expanded list in one level Examples: >>> meta_datas = [ [ dict1, ...
[ "def", "__expand_meta_datas", "(", "meta_datas", ",", "meta_datas_expanded", ")", ":", "if", "isinstance", "(", "meta_datas", ",", "dict", ")", ":", "meta_datas_expanded", ".", "append", "(", "meta_datas", ")", "elif", "isinstance", "(", "meta_datas", ",", "list...
27.357143
0.001261
def server_bind(self): """ Called by constructor to bind the socket. """ if self.allow_reuse_address: self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address)
[ "def", "server_bind", "(", "self", ")", ":", "if", "self", ".", "allow_reuse_address", ":", "self", ".", "socket", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEADDR", ",", "1", ")", "self", ".", "socket", ".", "bind",...
31.375
0.007752
def undelay(self): '''resolves all delayed arguments''' i = 0 while i < len(self): op = self[i] i += 1 if hasattr(op, 'arg1'): if isinstance(op.arg1,DelayedArg): op.arg1 = op.arg1.resolve() if isinst...
[ "def", "undelay", "(", "self", ")", ":", "i", "=", "0", "while", "i", "<", "len", "(", "self", ")", ":", "op", "=", "self", "[", "i", "]", "i", "+=", "1", "if", "hasattr", "(", "op", ",", "'arg1'", ")", ":", "if", "isinstance", "(", "op", "...
33.909091
0.010444
def choice(self, question, choices, default=None, attempts=None, multiple=False): """ Give the user a single choice from an list of answers. """ question = ChoiceQuestion(question, choices, default) question.set_max_attempts(attempts) question.set_multi_select(multiple) ...
[ "def", "choice", "(", "self", ",", "question", ",", "choices", ",", "default", "=", "None", ",", "attempts", "=", "None", ",", "multiple", "=", "False", ")", ":", "question", "=", "ChoiceQuestion", "(", "question", ",", "choices", ",", "default", ")", ...
35.8
0.008174
def _return_response_and_status_code(response, json_results=True): """ Output the requests response content or content as json and status code :rtype : dict :param response: requests response object :param json_results: Should return JSON or raw content :return: dict containing the response content...
[ "def", "_return_response_and_status_code", "(", "response", ",", "json_results", "=", "True", ")", ":", "if", "response", ".", "status_code", "==", "requests", ".", "codes", ".", "ok", ":", "return", "dict", "(", "results", "=", "response", ".", "json", "(",...
50.884615
0.005193
def serialize_dict(self, attr, dict_type, **kwargs): """Serialize a dictionary of objects. :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. :param bool required: Whether the objects in the dictionary must not be None or empty. ...
[ "def", "serialize_dict", "(", "self", ",", "attr", ",", "dict_type", ",", "*", "*", "kwargs", ")", ":", "serialization_ctxt", "=", "kwargs", ".", "get", "(", "\"serialization_ctxt\"", ",", "{", "}", ")", "serialized", "=", "{", "}", "for", "key", ",", ...
36.757576
0.001606
def disable_host_event_handler(self, host): """Disable event handlers for a host Format of the line that triggers function call:: DISABLE_HOST_EVENT_HANDLER;<host_name> :param host: host to edit :type host: alignak.objects.host.Host :return: None """ if ...
[ "def", "disable_host_event_handler", "(", "self", ",", "host", ")", ":", "if", "host", ".", "event_handler_enabled", ":", "host", ".", "modified_attributes", "|=", "DICT_MODATTR", "[", "\"MODATTR_EVENT_HANDLER_ENABLED\"", "]", ".", "value", "host", ".", "event_handl...
38.357143
0.005455
def make_wheelfile_inner(base_name, base_dir='.'): """Create a whl file from all the files under 'base_dir'. Places .dist-info at the end of the archive.""" zip_filename = base_name + ".whl" log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) # XXX support bz2, xz when availa...
[ "def", "make_wheelfile_inner", "(", "base_name", ",", "base_dir", "=", "'.'", ")", ":", "zip_filename", "=", "base_name", "+", "\".whl\"", "log", ".", "info", "(", "\"creating '%s' and adding '%s' to it\"", ",", "zip_filename", ",", "base_dir", ")", "# XXX support b...
28.621622
0.000913
def isdir(self, path, follow_symlinks=True): """Determine if path identifies a directory. Args: path: Path to filesystem object. Returns: `True` if path points to a directory (following symlinks). Raises: TypeError: if path is None. """ ...
[ "def", "isdir", "(", "self", ",", "path", ",", "follow_symlinks", "=", "True", ")", ":", "return", "self", ".", "_is_of_type", "(", "path", ",", "S_IFDIR", ",", "follow_symlinks", ")" ]
28.230769
0.005277
def _set_cam_share(self, v, load=False): """ Setter method for cam_share, mapped from YANG variable /hardware/profile/tcam/cam_share (container) If this variable is read-only (config: false) in the source YANG file, then _set_cam_share is considered as a private method. Backends looking to populate ...
[ "def", "_set_cam_share", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base...
73.227273
0.006127
def load_module(name, globals_dict=None, symb_list=None): """Loads a Scapy module to make variables, objects and functions available globally. """ _load("scapy.modules." + name, globals_dict=globals_dict, symb_list=symb_list)
[ "def", "load_module", "(", "name", ",", "globals_dict", "=", "None", ",", "symb_list", "=", "None", ")", ":", "_load", "(", "\"scapy.modules.\"", "+", "name", ",", "globals_dict", "=", "globals_dict", ",", "symb_list", "=", "symb_list", ")" ]
35.142857
0.003968
def url_mod(url: str, new_params: dict) -> str: """ Modifies existing URL by setting/overriding specified query string parameters. Note: Does not support multiple querystring parameters with identical name. :param url: Base URL/path to modify :param new_params: Querystring parameters to set/override...
[ "def", "url_mod", "(", "url", ":", "str", ",", "new_params", ":", "dict", ")", "->", "str", ":", "from", "urllib", ".", "parse", "import", "urlparse", ",", "parse_qsl", ",", "urlunparse", ",", "urlencode", "res", "=", "urlparse", "(", "url", ")", "quer...
38.263158
0.002685
def _post_start(self): """Set stdout to non-blocking VLC does not always return a newline when reading status so in order to be lazy and still use the read API without caring about how much output there is we switch stdout to nonblocking mode and just read a large chunk of datin...
[ "def", "_post_start", "(", "self", ")", ":", "flags", "=", "fcntl", ".", "fcntl", "(", "self", ".", "_process", ".", "stdout", ",", "fcntl", ".", "F_GETFL", ")", "fcntl", ".", "fcntl", "(", "self", ".", "_process", ".", "stdout", ",", "fcntl", ".", ...
53.833333
0.003044
def multiplyQuats(q1, q2): """q1, q2 must be [scalar, x, y, z] but those may be arrays or scalars""" return np.array([ q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3], q1[2]*q2[3] - q2[2]*q1[3] + q1[0]*q2[1] + q2[0]*q1[1], q1[3]*q2[1] - q2[3]*q1[1] + q1[0]*q2[2] + q2[0]...
[ "def", "multiplyQuats", "(", "q1", ",", "q2", ")", ":", "return", "np", ".", "array", "(", "[", "q1", "[", "0", "]", "*", "q2", "[", "0", "]", "-", "q1", "[", "1", "]", "*", "q2", "[", "1", "]", "-", "q1", "[", "2", "]", "*", "q2", "[",...
55.571429
0.002532
def _update_position(self, change): """ Keep position in sync with x,y,z """ if change['type']!='update': return pt = gp_Pnt(self.x,self.y,self.z) if not pt.IsEqual(self.position,self.tolerance): self.position = pt
[ "def", "_update_position", "(", "self", ",", "change", ")", ":", "if", "change", "[", "'type'", "]", "!=", "'update'", ":", "return", "pt", "=", "gp_Pnt", "(", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "z", ")", "if", "not", "pt"...
38.571429
0.021739
def _get_nadir_pixel(earth_mask, sector): """Find the nadir pixel Args: earth_mask: Mask identifying earth and space pixels sector: Specifies the scanned sector Returns: nadir row, nadir column """ if sector == FULL_DISC: logger.de...
[ "def", "_get_nadir_pixel", "(", "earth_mask", ",", "sector", ")", ":", "if", "sector", "==", "FULL_DISC", ":", "logger", ".", "debug", "(", "'Computing nadir pixel'", ")", "# The earth is not centered in the image, compute bounding box", "# of the earth disc first", "rmin",...
32.26087
0.002618
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ engine = create_engine( neutron_config.database.connection, poolclass=pool.NullPool) connection = engine.connect() ...
[ "def", "run_migrations_online", "(", ")", ":", "engine", "=", "create_engine", "(", "neutron_config", ".", "database", ".", "connection", ",", "poolclass", "=", "pool", ".", "NullPool", ")", "connection", "=", "engine", ".", "connect", "(", ")", "context", "...
24.761905
0.001852
def _prt_line_detail(self, prt, line, lnum=""): """Print each field and its value.""" data = zip(self.flds, line.split('\t')) txt = ["{:2}) {:13} {}".format(i, hdr, val) for i, (hdr, val) in enumerate(data)] prt.write("{LNUM}\n{TXT}\n".format(LNUM=lnum, TXT='\n'.join(txt)))
[ "def", "_prt_line_detail", "(", "self", ",", "prt", ",", "line", ",", "lnum", "=", "\"\"", ")", ":", "data", "=", "zip", "(", "self", ".", "flds", ",", "line", ".", "split", "(", "'\\t'", ")", ")", "txt", "=", "[", "\"{:2}) {:13} {}\"", ".", "forma...
60.4
0.009804
def get_indices(self, axis=0, index_func=None, old_blocks=None): """This gets the internal indices stored in the partitions. Note: These are the global indices of the object. This is mostly useful when you have deleted rows/columns internally, but do not know which ones were del...
[ "def", "get_indices", "(", "self", ",", "axis", "=", "0", ",", "index_func", "=", "None", ",", "old_blocks", "=", "None", ")", ":", "ErrorMessage", ".", "catch_bugs_and_request_email", "(", "not", "callable", "(", "index_func", ")", ")", "func", "=", "self...
47.203125
0.003243
def _handle_invite(self, room_id: _RoomID, state: dict): """ Join rooms invited by whitelisted partners """ if self._stop_event.ready(): return self.log.debug('Got invite', room_id=room_id) invite_events = [ event for event in state['events'] ...
[ "def", "_handle_invite", "(", "self", ",", "room_id", ":", "_RoomID", ",", "state", ":", "dict", ")", ":", "if", "self", ".", "_stop_event", ".", "ready", "(", ")", ":", "return", "self", ".", "log", ".", "debug", "(", "'Got invite'", ",", "room_id", ...
37.28125
0.00245
def invert(self): """Inverts the layer. """ alpha = self.img.split()[3] self.img = self.img.convert("RGB") self.img = ImageOps.invert(self.img) self.img = self.img.convert("RGBA") self.img.putalpha(alpha)
[ "def", "invert", "(", "self", ")", ":", "alpha", "=", "self", ".", "img", ".", "split", "(", ")", "[", "3", "]", "self", ".", "img", "=", "self", ".", "img", ".", "convert", "(", "\"RGB\"", ")", "self", ".", "img", "=", "ImageOps", ".", "invert...
24.090909
0.018182
def path_url(self): """Build the path URL to use.""" url = [] p = urlsplit(self.full_url) # Proxies use full URLs. if p.scheme in self.proxies: return self.full_url path = p.path if not path: path = '/' url.append(path) ...
[ "def", "path_url", "(", "self", ")", ":", "url", "=", "[", "]", "p", "=", "urlsplit", "(", "self", ".", "full_url", ")", "# Proxies use full URLs.", "if", "p", ".", "scheme", "in", "self", ".", "proxies", ":", "return", "self", ".", "full_url", "path",...
19.090909
0.004535
def thread_exists(self, thread_id): """Check if a thread exists or has 404'd. Args: thread_id (int): Thread ID Returns: bool: Whether the given thread exists on this board. """ return self._requests_session.head( self._url.thread_api_url( ...
[ "def", "thread_exists", "(", "self", ",", "thread_id", ")", ":", "return", "self", ".", "_requests_session", ".", "head", "(", "self", ".", "_url", ".", "thread_api_url", "(", "thread_id", "=", "thread_id", ")", ")", ".", "ok" ]
26.428571
0.005222
def write_numpy_to_dense_tensor(file, array, labels=None): """Writes a numpy array to a dense tensor""" # Validate shape of array and labels, resolve array and label types if not len(array.shape) == 2: raise ValueError("Array must be a Matrix") if labels is not None: if not len(labels.s...
[ "def", "write_numpy_to_dense_tensor", "(", "file", ",", "array", ",", "labels", "=", "None", ")", ":", "# Validate shape of array and labels, resolve array and label types", "if", "not", "len", "(", "array", ".", "shape", ")", "==", "2", ":", "raise", "ValueError", ...
45.391304
0.001876
def to_geojson(products): """Return the products from a query response as a GeoJSON with the values in their appropriate Python types. """ feature_list = [] for i, (product_id, props) in enumerate(products.items()): props = props.copy() props['id'] = produ...
[ "def", "to_geojson", "(", "products", ")", ":", "feature_list", "=", "[", "]", "for", "i", ",", "(", "product_id", ",", "props", ")", "in", "enumerate", "(", "products", ".", "items", "(", ")", ")", ":", "props", "=", "props", ".", "copy", "(", ")"...
43.315789
0.003567
def get_loaded_project(self, project_id): """ Returns a project or raise a 404 error. If project is not finished to load wait for it """ project = self.get_project(project_id) yield from project.wait_loaded() return project
[ "def", "get_loaded_project", "(", "self", ",", "project_id", ")", ":", "project", "=", "self", ".", "get_project", "(", "project_id", ")", "yield", "from", "project", ".", "wait_loaded", "(", ")", "return", "project" ]
30.222222
0.007143
def check_modpath_has_init(path, mod_path): """check there are some __init__.py all along the way""" modpath = [] for part in mod_path: modpath.append(part) path = os.path.join(path, part) if not _has_init(path): old_namespace = util.is_namespace(".".join(modpath)) ...
[ "def", "check_modpath_has_init", "(", "path", ",", "mod_path", ")", ":", "modpath", "=", "[", "]", "for", "part", "in", "mod_path", ":", "modpath", ".", "append", "(", "part", ")", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "part"...
34.727273
0.002551
def info_player(self,pid): '''' Get info football player using a ID @return: [name,position,team,points,price] ''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent} ...
[ "def", "info_player", "(", "self", ",", "pid", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "'Referer'", ":", "'http://'", "+", "self", ".", "domain", "+", "'/team...
51.076923
0.016272
def language(self, lang): """ Set the language to use; attempts to change the API URL """ lang = lang.lower() if self._lang == lang: return url = self._api_url tmp = url.replace("/{0}.".format(self._lang), "/{0}.".format(lang)) self._api_url = tmp se...
[ "def", "language", "(", "self", ",", "lang", ")", ":", "lang", "=", "lang", ".", "lower", "(", ")", "if", "self", ".", "_lang", "==", "lang", ":", "return", "url", "=", "self", ".", "_api_url", "tmp", "=", "url", ".", "replace", "(", "\"/{0}.\"", ...
29.5
0.005479
def convert_svg_transform(self, transform): """ Converts a string representing a SVG transform into AffineTransform fields. See https://www.w3.org/TR/SVG/coords.html#TransformAttribute for the specification of the transform strings. skewX and skewY are not supported. ...
[ "def", "convert_svg_transform", "(", "self", ",", "transform", ")", ":", "tr", ",", "args", "=", "transform", "[", ":", "-", "1", "]", ".", "split", "(", "'('", ")", "a", "=", "map", "(", "float", ",", "args", ".", "split", "(", "' '", ")", ")", ...
30.673913
0.001374
def _get_specifications(specifications): """ Computes the list of strings corresponding to the given specifications :param specifications: A string, a class or a list of specifications :return: A list of strings :raise ValueError: Invalid specification found """ if not specifications or spe...
[ "def", "_get_specifications", "(", "specifications", ")", ":", "if", "not", "specifications", "or", "specifications", "is", "object", ":", "raise", "ValueError", "(", "\"No specifications given\"", ")", "elif", "inspect", ".", "isclass", "(", "specifications", ")", ...
34.787234
0.000595
def poly(self, return_coeffs=False): """returns the quadratic as a Polynomial object.""" p = self.bpoints() coeffs = (p[0] - 2*p[1] + p[2], 2*(p[1] - p[0]), p[0]) if return_coeffs: return coeffs else: return np.poly1d(coeffs)
[ "def", "poly", "(", "self", ",", "return_coeffs", "=", "False", ")", ":", "p", "=", "self", ".", "bpoints", "(", ")", "coeffs", "=", "(", "p", "[", "0", "]", "-", "2", "*", "p", "[", "1", "]", "+", "p", "[", "2", "]", ",", "2", "*", "(", ...
35.25
0.00692
def get_shebang(tokens): """ Returns the shebang string in *tokens* if it exists. None if not. """ # This (short) loop preserves shebangs and encoding strings: for tok in tokens[0:4]: # Will always be in the first four tokens line = tok[4] # Save the first comment line if it starts ...
[ "def", "get_shebang", "(", "tokens", ")", ":", "# This (short) loop preserves shebangs and encoding strings:", "for", "tok", "in", "tokens", "[", "0", ":", "4", "]", ":", "# Will always be in the first four tokens", "line", "=", "tok", "[", "4", "]", "# Save the first...
40.181818
0.006637
def set_color(self, color, alpha = 1): """set active color. You can use hex colors like "#aaa", or you can use normalized RGB tripplets (where every value is in range 0..1), or you can do the same thing in range 0..65535. also consider skipping this operation and specify the color on str...
[ "def", "set_color", "(", "self", ",", "color", ",", "alpha", "=", "1", ")", ":", "color", "=", "self", ".", "colors", ".", "parse", "(", "color", ")", "# parse whatever we have there into a normalized triplet", "if", "len", "(", "color", ")", "==", "4", "a...
50.166667
0.011419
def data_ptr(self): """ Returns the address of the payload of the chunk. """ raise NotImplementedError("%s not implemented for %s" % (self.data_ptr.__func__.__name__, self.__class__.__name__))
[ "def", "data_ptr", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"%s not implemented for %s\"", "%", "(", "self", ".", "data_ptr", ".", "__func__", ".", "__name__", ",", "self", ".", "__class__", ".", "__name__", ")", ")" ]
47.333333
0.013841
def read_params(filename, asheader=False, verbosity=0) -> Dict[str, Union[int, float, bool, str, None]]: """Read parameter dictionary from text file. Assumes that parameters are specified in the format: par1 = value1 par2 = value2 Comments that start with '#' are allowed. Parameters ...
[ "def", "read_params", "(", "filename", ",", "asheader", "=", "False", ",", "verbosity", "=", "0", ")", "->", "Dict", "[", "str", ",", "Union", "[", "int", ",", "float", ",", "bool", ",", "str", ",", "None", "]", "]", ":", "filename", "=", "str", ...
31.96875
0.001898
def _get_biodata(base_file, args): """Retrieve biodata genome targets customized by install parameters. """ with open(base_file) as in_handle: config = yaml.safe_load(in_handle) config["install_liftover"] = False config["genome_indexes"] = args.aligners ann_groups = config.pop("annotatio...
[ "def", "_get_biodata", "(", "base_file", ",", "args", ")", ":", "with", "open", "(", "base_file", ")", "as", "in_handle", ":", "config", "=", "yaml", ".", "safe_load", "(", "in_handle", ")", "config", "[", "\"install_liftover\"", "]", "=", "False", "config...
45.181818
0.003945
def cut_selection(self): """ Return a (:class:`.Document`, :class:`.ClipboardData`) tuple, where the document represents the new document when the selection is cut, and the clipboard data, represents whatever has to be put on the clipboard. """ if self.selection: ...
[ "def", "cut_selection", "(", "self", ")", ":", "if", "self", ".", "selection", ":", "cut_parts", "=", "[", "]", "remaining_parts", "=", "[", "]", "new_cursor_position", "=", "self", ".", "cursor_position", "last_to", "=", "0", "for", "from_", ",", "to", ...
39.030303
0.00303
def correct(text: str, matches: [Match]) -> str: """Automatically apply suggestions to the text.""" ltext = list(text) matches = [match for match in matches if match.replacements] errors = [ltext[match.offset:match.offset + match.errorlength] for match in matches] correct_offset = 0 ...
[ "def", "correct", "(", "text", ":", "str", ",", "matches", ":", "[", "Match", "]", ")", "->", "str", ":", "ltext", "=", "list", "(", "text", ")", "matches", "=", "[", "match", "for", "match", "in", "matches", "if", "match", ".", "replacements", "]"...
43.8125
0.001397
def format_endpoint(schema, addr, port, api_version): """Return a formatted keystone endpoint @param schema: http or https @param addr: ipv4/ipv6 host of the keystone service @param port: port of the keystone service @param api_version: 2 or 3 @returns a fully formatted keystone endpoint """...
[ "def", "format_endpoint", "(", "schema", ",", "addr", ",", "port", ",", "api_version", ")", ":", "return", "'{}://{}:{}/{}/'", ".", "format", "(", "schema", ",", "addr", ",", "port", ",", "get_api_suffix", "(", "api_version", ")", ")" ]
43
0.002278
def srfcss(code, bodstr, srflen=_default_len_out): """ Translate a surface ID code, together with a body string, to the corresponding surface name. If no such surface name exists, return a string representation of the surface ID code. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/...
[ "def", "srfcss", "(", "code", ",", "bodstr", ",", "srflen", "=", "_default_len_out", ")", ":", "code", "=", "ctypes", ".", "c_int", "(", "code", ")", "bodstr", "=", "stypes", ".", "stringToCharP", "(", "bodstr", ")", "srfstr", "=", "stypes", ".", "stri...
39.708333
0.007172
def segwit_addr_encode(witprog_bin, hrp=bech32_prefix, witver=bech32_witver): """ Encode a segwit script hash to a bech32 address. Returns the bech32-encoded string on success """ witprog_bytes = [ord(c) for c in witprog_bin] ret = bech32_encode(hrp, [int(witver)] + convertbits(witprog_bytes, 8,...
[ "def", "segwit_addr_encode", "(", "witprog_bin", ",", "hrp", "=", "bech32_prefix", ",", "witver", "=", "bech32_witver", ")", ":", "witprog_bytes", "=", "[", "ord", "(", "c", ")", "for", "c", "in", "witprog_bin", "]", "ret", "=", "bech32_encode", "(", "hrp"...
43.444444
0.002506
def remove_row(self, row_num=None): """ Remove a row from the grid """ #DeleteRows(self, pos, numRows, updateLabel if not row_num and row_num != 0: row_num = self.GetNumberRows() - 1 label = self.GetCellValue(row_num, 0) self.DeleteRows(pos=row_num, nu...
[ "def", "remove_row", "(", "self", ",", "row_num", "=", "None", ")", ":", "#DeleteRows(self, pos, numRows, updateLabel", "if", "not", "row_num", "and", "row_num", "!=", "0", ":", "row_num", "=", "self", ".", "GetNumberRows", "(", ")", "-", "1", "label", "=", ...
36
0.00369
def assertFileTypeNotEqual(self, filename, extension, msg=None): '''Fail if ``filename`` has the given ``extension`` as determined by the ``!=`` operator. Parameters ---------- filename : str, bytes, file-like extension : str, bytes msg : str If not p...
[ "def", "assertFileTypeNotEqual", "(", "self", ",", "filename", ",", "extension", ",", "msg", "=", "None", ")", ":", "ftype", "=", "self", ".", "_get_file_type", "(", "filename", ")", "self", ".", "assertNotEqual", "(", "ftype", ",", "extension", ",", "msg"...
32.5
0.00299
def set_value(self, visual_property, value): """Set a single Visual Property Value :param visual_property: Visual Property ID :param value: New value for the VP :return: None """ if visual_property is None or value is None: raise ValueError('Both VP and value...
[ "def", "set_value", "(", "self", ",", "visual_property", ",", "value", ")", ":", "if", "visual_property", "is", "None", "or", "value", "is", "None", ":", "raise", "ValueError", "(", "'Both VP and value are required.'", ")", "new_value", "=", "[", "{", "'visual...
31.705882
0.003604
def to_gnuplot_datafile(self, datafilepath): """Dumps the TimeSeries into a gnuplot compatible data file. :param string datafilepath: Path used to create the file. If that file already exists, it will be overwritten! :return: Returns :py:const:`True` if the data could be writt...
[ "def", "to_gnuplot_datafile", "(", "self", ",", "datafilepath", ")", ":", "try", ":", "datafile", "=", "file", "(", "datafilepath", ",", "\"wb\"", ")", "except", "Exception", ":", "return", "False", "if", "self", ".", "_timestampFormat", "is", "None", ":", ...
34.862069
0.00385
def get_artists(self, limit=50, cacheable=True): """ Returns a sequence of Album objects if limit==None it will return all (may take a while) """ seq = [] for node in _collect_nodes( limit, self, self.ws_prefix + ".getArtists", cacheable ): ...
[ "def", "get_artists", "(", "self", ",", "limit", "=", "50", ",", "cacheable", "=", "True", ")", ":", "seq", "=", "[", "]", "for", "node", "in", "_collect_nodes", "(", "limit", ",", "self", ",", "self", ".", "ws_prefix", "+", "\".getArtists\"", ",", "...
31.166667
0.00519
def confirmation_pdf(self, confirmation_id): """ Opens a pdf of a confirmation :param confirmation_id: the confirmation id :return: dict """ return self._create_get_request(resource=CONFIRMATIONS, billomat_id=confirmation_id, command=PDF)
[ "def", "confirmation_pdf", "(", "self", ",", "confirmation_id", ")", ":", "return", "self", ".", "_create_get_request", "(", "resource", "=", "CONFIRMATIONS", ",", "billomat_id", "=", "confirmation_id", ",", "command", "=", "PDF", ")" ]
35
0.010453
def write_layout(_path): """ Write a valid gentoo layout file to :path:. Args: path - The output path of the layout.conf """ path.mkdir_uchroot("/etc/portage/metadata") path.mkfile_uchroot("/etc/portage/metadata/layout.conf") with open(_path, 'w') as layoutconf: lines = '''...
[ "def", "write_layout", "(", "_path", ")", ":", "path", ".", "mkdir_uchroot", "(", "\"/etc/portage/metadata\"", ")", "path", ".", "mkfile_uchroot", "(", "\"/etc/portage/metadata/layout.conf\"", ")", "with", "open", "(", "_path", ",", "'w'", ")", "as", "layoutconf",...
27.615385
0.002695
def return_markers(self): """Return all the markers (also called triggers or events). Returns ------- list of dict where each dict contains 'name' as str, 'start' and 'end' as float in seconds from the start of the recordings, and 'chan' as list of st...
[ "def", "return_markers", "(", "self", ")", ":", "markers", "=", "[", "]", "for", "v", "in", "self", ".", "mrk", "[", "'Marker Infos'", "]", ".", "values", "(", ")", ":", "if", "v", "[", "0", "]", "==", "'New Segment'", ":", "continue", "markers", "...
33.181818
0.002663
def _ixor(self, other): """Set self to the symmetric difference between the sets. if isinstance(other, _basebag): This runs in O(other.num_unique_elements()) else: This runs in O(len(other)) """ if isinstance(other, _basebag): for elem, other_count in other.counts(): count = abs(self.count(elem)...
[ "def", "_ixor", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "_basebag", ")", ":", "for", "elem", ",", "other_count", "in", "other", ".", "counts", "(", ")", ":", "count", "=", "abs", "(", "self", ".", "count", "(", ...
31.913043
0.030423
def remix(self, remix_dictionary=None, num_output_channels=None): '''Remix the channels of an audio file. Note: volume options are not yet implemented Parameters ---------- remix_dictionary : dict or None Dictionary mapping output channel to list of input channel(s)...
[ "def", "remix", "(", "self", ",", "remix_dictionary", "=", "None", ",", "num_output_channels", "=", "None", ")", ":", "if", "not", "(", "isinstance", "(", "remix_dictionary", ",", "dict", ")", "or", "remix_dictionary", "is", "None", ")", ":", "raise", "Val...
37.810127
0.000653
def create(self, name, **kwds): """ Endpoint: /album/create.json Creates a new album and returns it. """ result = self._client.post("/album/create.json", name=name, **kwds)["result"] return Album(self._client, result)
[ "def", "create", "(", "self", ",", "name", ",", "*", "*", "kwds", ")", ":", "result", "=", "self", ".", "_client", ".", "post", "(", "\"/album/create.json\"", ",", "name", "=", "name", ",", "*", "*", "kwds", ")", "[", "\"result\"", "]", "return", "...
32.555556
0.006645
def program_unitary(program, n_qubits): """ Return the unitary of a pyQuil program. :param program: A program consisting only of :py:class:`Gate`.: :return: a unitary corresponding to the composition of the program's gates. """ umat = np.eye(2 ** n_qubits) for instruction in program: ...
[ "def", "program_unitary", "(", "program", ",", "n_qubits", ")", ":", "umat", "=", "np", ".", "eye", "(", "2", "**", "n_qubits", ")", "for", "instruction", "in", "program", ":", "if", "isinstance", "(", "instruction", ",", "Gate", ")", ":", "unitary", "...
38.466667
0.003384
def rgb_to_hsl(r, g=None, b=None): """Convert the color from RGB coordinates to HSL. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, l) tuple in the range: h[0...360],...
[ "def", "rgb_to_hsl", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "minVal", "=", "min", "(", "r", ",", "g", ...
19.723404
0.023638
def _check_vpcs_version(self): """ Checks if the VPCS executable version is >= 0.8b or == 0.6.1. """ try: output = yield from subprocess_check_output(self._vpcs_path(), "-v", cwd=self.working_dir) match = re.search("Welcome to Virtual PC Simulator, version ([0-9a-...
[ "def", "_check_vpcs_version", "(", "self", ")", ":", "try", ":", "output", "=", "yield", "from", "subprocess_check_output", "(", "self", ".", "_vpcs_path", "(", ")", ",", "\"-v\"", ",", "cwd", "=", "self", ".", "working_dir", ")", "match", "=", "re", "."...
54.375
0.00904
def turn_on_switch(self, device_id, name): """Create the message to turn switch on.""" msg = "!%sF1|Turn On|%s" % (device_id, name) self._send_message(msg)
[ "def", "turn_on_switch", "(", "self", ",", "device_id", ",", "name", ")", ":", "msg", "=", "\"!%sF1|Turn On|%s\"", "%", "(", "device_id", ",", "name", ")", "self", ".", "_send_message", "(", "msg", ")" ]
44
0.011173
def values(self): """ Returns an `np.array` of type `self.dtype` containing some values from the domain. For domains where ``is_finite`` is ``True``, all elements of the domain will be yielded exactly once. :rtype: `np.ndarray` """ # This code comes from...
[ "def", "values", "(", "self", ")", ":", "# This code comes from Jared Goguen at http://stackoverflow.com/a/37712597/1082565", "partition_array", "=", "np", ".", "empty", "(", "(", "self", ".", "n_members", ",", "self", ".", "n_elements", ")", ",", "dtype", "=", "int...
40.277778
0.008086
def dotplot(args): """ %prog dotplot map.csv ref.fasta Make dotplot between chromosomes and linkage maps. The input map is csv formatted, for example: ScaffoldID,ScaffoldPosition,LinkageGroup,GeneticPosition scaffold_2707,11508,1,0 scaffold_2707,11525,1,1.2 """ from jcvi.assembly.a...
[ "def", "dotplot", "(", "args", ")", ":", "from", "jcvi", ".", "assembly", ".", "allmaps", "import", "CSVMapLine", "from", "jcvi", ".", "formats", ".", "sizes", "import", "Sizes", "from", "jcvi", ".", "utils", ".", "natsort", "import", "natsorted", "from", ...
32.37931
0.002756
def query(self, expr): """ Query the data with a boolean expression. :param expr: the query string, you can use '@' character refer to environment variables. :return: new collection :rtype: :class:`odps.df.expr.expressions.CollectionExpr` """ from .query import ...
[ "def", "query", "(", "self", ",", "expr", ")", ":", "from", ".", "query", "import", "CollectionVisitor", "if", "not", "isinstance", "(", "expr", ",", "six", ".", "string_types", ")", ":", "raise", "ValueError", "(", "'expr must be a string'", ")", "frame", ...
29.217391
0.004323
def migrate_non_shared(vm_, target, ssh=False): ''' Attempt to execute non-shared storage "all" migration :param vm_: domain name :param target: target libvirt host name :param ssh: True to connect over ssh CLI Example: .. code-block:: bash salt '*' virt.migrate_non_shared <vm na...
[ "def", "migrate_non_shared", "(", "vm_", ",", "target", ",", "ssh", "=", "False", ")", ":", "cmd", "=", "_get_migrate_command", "(", ")", "+", "' --copy-storage-all '", "+", "vm_", "+", "_get_target", "(", "target", ",", "ssh", ")", "stdout", "=", "subproc...
27.78125
0.001087
def get_next_of_type(self, processor_type): """Get the next available processor of a particular type and increment its occupancy counter. Args: processor_type (ProcessorType): The processor type associated with a zmq identity. Returns: (Processor...
[ "def", "get_next_of_type", "(", "self", ",", "processor_type", ")", ":", "with", "self", ".", "_condition", ":", "if", "processor_type", "not", "in", "self", ":", "self", ".", "wait_for_registration", "(", "processor_type", ")", "try", ":", "processor", "=", ...
37.55
0.002597
def uptime(): """Returns uptime in seconds if even remotely possible, or None if not.""" if __boottime is not None: return time.time() - __boottime return {'amiga': _uptime_amiga, 'aros12': _uptime_amiga, 'beos5': _uptime_beos, 'cygwin': _uptime_linux, ...
[ "def", "uptime", "(", ")", ":", "if", "__boottime", "is", "not", "None", ":", "return", "time", ".", "time", "(", ")", "-", "__boottime", "return", "{", "'amiga'", ":", "_uptime_amiga", ",", "'aros12'", ":", "_uptime_amiga", ",", "'beos5'", ":", "_uptime...
42
0.004655
def depth(args): """ %prog depth DP.tsv Plot read depths across all TREDs. """ import seaborn as sns p = OptionParser(depth.__doc__) opts, args, iopts = p.set_image_options(args, figsize="14x14") if len(args) != 1: sys.exit(not p.print_help()) tsvfile, = args fig, ((a...
[ "def", "depth", "(", "args", ")", ":", "import", "seaborn", "as", "sns", "p", "=", "OptionParser", "(", "depth", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"14x14\"", ...
35.383562
0.001883
def normalize_name(name, overrides=None): '''Normalize the key name to title case. For example, ``normalize_name('content-id')`` will become ``Content-Id`` Args: name (str): The name to normalize. overrides (set, sequence): A set or sequence containing keys that should be cased...
[ "def", "normalize_name", "(", "name", ",", "overrides", "=", "None", ")", ":", "normalized_name", "=", "name", ".", "title", "(", ")", "if", "overrides", ":", "override_map", "=", "dict", "(", "[", "(", "name", ".", "title", "(", ")", ",", "name", ")...
31.041667
0.001302
def _get_basin_depth_term(self, C, sites, period): """ In the case of the base model the basin depth term is switched off. Therefore we return an array of zeros. """ return np.zeros(len(sites.vs30), dtype=float)
[ "def", "_get_basin_depth_term", "(", "self", ",", "C", ",", "sites", ",", "period", ")", ":", "return", "np", ".", "zeros", "(", "len", "(", "sites", ".", "vs30", ")", ",", "dtype", "=", "float", ")" ]
41
0.007968
def p_global_var(p): '''global_var : VARIABLE | DOLLAR variable | DOLLAR LBRACE expr RBRACE''' if len(p) == 2: p[0] = ast.Variable(p[1], lineno=p.lineno(1)) elif len(p) == 3: p[0] = ast.Variable(p[2], lineno=p.lineno(1)) else: p[0] = ast.Variab...
[ "def", "p_global_var", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "ast", ".", "Variable", "(", "p", "[", "1", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "elif", "len", "(...
33.9
0.002874
def check_for_cancelled_events(self, d): """Check if any events are cancelled on the given date 'd'.""" for event in self.events: for cn in event.cancellations.all(): if cn.date == d: event.title += ' (CANCELLED)'
[ "def", "check_for_cancelled_events", "(", "self", ",", "d", ")", ":", "for", "event", "in", "self", ".", "events", ":", "for", "cn", "in", "event", ".", "cancellations", ".", "all", "(", ")", ":", "if", "cn", ".", "date", "==", "d", ":", "event", "...
45.333333
0.00722
def _aws_encode_changebatch(o): ''' helper method to process a change batch & encode the bits which need encoding. ''' change_idx = 0 while change_idx < len(o['Changes']): o['Changes'][change_idx]['ResourceRecordSet']['Name'] = aws_encode(o['Changes'][change_idx]['ResourceRecordSet']['Name']...
[ "def", "_aws_encode_changebatch", "(", "o", ")", ":", "change_idx", "=", "0", "while", "change_idx", "<", "len", "(", "o", "[", "'Changes'", "]", ")", ":", "o", "[", "'Changes'", "]", "[", "change_idx", "]", "[", "'ResourceRecordSet'", "]", "[", "'Name'"...
63.125
0.005854
def visitObjectExpr(self, ctx: jsgParser.ObjectExprContext): """ objectExpr: OBRACE membersDef? CBRACE OBRACE (LEXER_ID_REF | ANY)? MAPSTO valueType ebnfSuffix? CBRACE """ if not self._name: self._name = self._context.anon_id() if ctx.membersDef(): ...
[ "def", "visitObjectExpr", "(", "self", ",", "ctx", ":", "jsgParser", ".", "ObjectExprContext", ")", ":", "if", "not", "self", ".", "_name", ":", "self", ".", "_name", "=", "self", ".", "_context", ".", "anon_id", "(", ")", "if", "ctx", ".", "membersDef...
45.866667
0.005698
def get_column_for_modelfield(model_field): """ Return the built-in Column class for a model field class. """ # If the field points to another model, we want to get the pk field of that other model and use # that as the real field. It is possible that a ForeignKey points to a model with table # inheri...
[ "def", "get_column_for_modelfield", "(", "model_field", ")", ":", "# If the field points to another model, we want to get the pk field of that other model and use", "# that as the real field. It is possible that a ForeignKey points to a model with table", "# inheritance, however, so we need to trav...
58.833333
0.005579