text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def __truncate(self, line_arr, max_width): ''' Cut tuple of line chunks according to it's wisible lenght ''' def is_space(chunk): return all([True if i == ' ' else False for i in chunk]) def is_empty(chunks, markups): result = [] for chunk in chunks: ...
[ "def", "__truncate", "(", "self", ",", "line_arr", ",", "max_width", ")", ":", "def", "is_space", "(", "chunk", ")", ":", "return", "all", "(", "[", "True", "if", "i", "==", "' '", "else", "False", "for", "i", "in", "chunk", "]", ")", "def", "is_em...
37.971429
0.002201
def _fetch(self, path, etag_file, target_path, force): """ returns (str): path to new egg. None if no update. """ url = self.connection.base_url + path # Searched for cached etag information current_etag = None if os.path.isfile(etag_file): with op...
[ "def", "_fetch", "(", "self", ",", "path", ",", "etag_file", ",", "target_path", ",", "force", ")", ":", "url", "=", "self", ".", "connection", ".", "base_url", "+", "path", "# Searched for cached etag information", "current_etag", "=", "None", "if", "os", "...
40.25
0.001213
def formatException(type, value, tb): """ Format traceback, darkening entries from global site-packages directories and user-specific site-packages directory. https://stackoverflow.com/a/46071447/5156190 """ # Absolute paths to site-packages packages = tuple(join(abspath(p), "") for p in s...
[ "def", "formatException", "(", "type", ",", "value", ",", "tb", ")", ":", "# Absolute paths to site-packages", "packages", "=", "tuple", "(", "join", "(", "abspath", "(", "p", ")", ",", "\"\"", ")", "for", "p", "in", "sys", ".", "path", "[", "1", ":", ...
39.285714
0.002367
def run_crate( version, env=None, setting=None, crate_root=None, keep_data=False, disable_java_magic=False, ): """Launch a crate instance. Supported version specifications: - Concrete version like "0.55.0" or with wildcard: "1.1.x" - An alias (one...
[ "def", "run_crate", "(", "version", ",", "env", "=", "None", ",", "setting", "=", "None", ",", "crate_root", "=", "None", ",", "keep_data", "=", "False", ",", "disable_java_magic", "=", "False", ",", ")", ":", "with", "create_node", "(", "version", ",", ...
29.886364
0.000736
def recv(self, buffersize, flags=0): ''' Receive data on the socket. The buffersize and flags arguments are currently ignored. Only returns the data. ''' _,_,data = self._recv(buffersize) return data
[ "def", "recv", "(", "self", ",", "buffersize", ",", "flags", "=", "0", ")", ":", "_", ",", "_", ",", "data", "=", "self", ".", "_recv", "(", "buffersize", ")", "return", "data" ]
34.714286
0.016064
def set_payload(self, payload): """Set stanza payload to a single item. All current stanza content of will be dropped. Marks the stanza dirty. :Parameters: - `payload`: XML element or stanza payload object to use :Types: - `payload`: :etree:`ElementTree....
[ "def", "set_payload", "(", "self", ",", "payload", ")", ":", "if", "isinstance", "(", "payload", ",", "ElementClass", ")", ":", "self", ".", "_payload", "=", "[", "XMLPayload", "(", "payload", ")", "]", "elif", "isinstance", "(", "payload", ",", "StanzaP...
34.333333
0.009449
def stop_instance(self, fast=False): """ I attempt to stop a running VM. I make sure any connection to the worker is removed. If the VM was using a cloned image, I remove the clone When everything is tidied up, I ask that bbot looks for work to do """ log.msg("Att...
[ "def", "stop_instance", "(", "self", ",", "fast", "=", "False", ")", ":", "log", ".", "msg", "(", "\"Attempting to stop '%s'\"", "%", "self", ".", "workername", ")", "if", "self", ".", "domain", "is", "None", ":", "log", ".", "msg", "(", "\"I don't think...
34.945946
0.002257
def get_hyperedge_id(self, nodes): """From a set of nodes, returns the ID of the hyperedge that this set comprises. :param nodes: iterable container of references to nodes in the the hyperedge to be added :returns: str -- ID of the hyperedge that has that the specifi...
[ "def", "get_hyperedge_id", "(", "self", ",", "nodes", ")", ":", "frozen_nodes", "=", "frozenset", "(", "nodes", ")", "if", "not", "self", ".", "has_hyperedge", "(", "frozen_nodes", ")", ":", "raise", "ValueError", "(", "\"No such hyperedge exists.\"", ")", "re...
35.222222
0.002047
def add_features(self, kept_indices, new_indices, new_state_vec, new_state_cov, new_noise_var): '''Add new features to the state kept_indices - the mapping from all indices in the state to new indices in the new version new_indices - the indices of t...
[ "def", "add_features", "(", "self", ",", "kept_indices", ",", "new_indices", ",", "new_state_vec", ",", "new_state_cov", ",", "new_noise_var", ")", ":", "assert", "len", "(", "kept_indices", ")", "==", "len", "(", "self", ".", "state_vec", ")", "assert", "le...
41.976744
0.001624
def from_native(cls, t): """ Convert from a native Python `datetime.time` value. """ second = (1000000 * t.second + t.microsecond) / 1000000 return Time(t.hour, t.minute, second, t.tzinfo)
[ "def", "from_native", "(", "cls", ",", "t", ")", ":", "second", "=", "(", "1000000", "*", "t", ".", "second", "+", "t", ".", "microsecond", ")", "/", "1000000", "return", "Time", "(", "t", ".", "hour", ",", "t", ".", "minute", ",", "second", ",",...
43.2
0.009091
def iscomplete(self, atype=None, avalue=None): """Check if the command is complete Check if all required arguments have been encountered. For commands that allow an undefined number of arguments, this method always returns False. :return: True if command is complete, False othe...
[ "def", "iscomplete", "(", "self", ",", "atype", "=", "None", ",", "avalue", "=", "None", ")", ":", "if", "self", ".", "variable_args_nb", ":", "return", "False", "if", "self", ".", "required_args", "==", "-", "1", ":", "self", ".", "required_args", "="...
39.083333
0.002081
def rpc_start( working_dir, port, subdomain_index=None, thread=True ): """ Start the global RPC server thread Returns the RPC server thread """ rpc_srv = BlockstackdRPCServer( working_dir, port, subdomain_index=subdomain_index ) log.debug("Starting RPC on port {}".format(port)) if thread: ...
[ "def", "rpc_start", "(", "working_dir", ",", "port", ",", "subdomain_index", "=", "None", ",", "thread", "=", "True", ")", ":", "rpc_srv", "=", "BlockstackdRPCServer", "(", "working_dir", ",", "port", ",", "subdomain_index", "=", "subdomain_index", ")", "log",...
29.25
0.016575
def _separate_header_and_content(self, text_lines): """ From a given Org text, return the header separate from the content. The given text must be separate line by line and be a list. The return is a list of two items: header and content. Theses two items are text separate line b...
[ "def", "_separate_header_and_content", "(", "self", ",", "text_lines", ")", ":", "no_more_header", "=", "False", "expr_metadata", "=", "re", ".", "compile", "(", "r'^#\\+[a-zA-Z]+:.*'", ")", "header", "=", "[", "]", "content", "=", "[", "]", "for", "line", "...
38.538462
0.001947
def get_enum(self, property, enum, datas): """Factory enum type """ str_property = str(datas[property]).lower() if str_property not in enum: raise ValueError("Unknow enum \"%s\" for \"%s\"." % (str_property, property)) return enum(str_property)
[ "def", "get_enum", "(", "self", ",", "property", ",", "enum", ",", "datas", ")", ":", "str_property", "=", "str", "(", "datas", "[", "property", "]", ")", ".", "lower", "(", ")", "if", "str_property", "not", "in", "enum", ":", "raise", "ValueError", ...
41.428571
0.010135
def __get_base_bundle_url(self): """Returns ``{rest api url}/{serviceInstanceId}/v2/bundles`` """ return self.__serviceAccount.get_url() + '/' + \ self.__serviceAccount.get_instance_id() + self.__BUNDLES_PATH
[ "def", "__get_base_bundle_url", "(", "self", ")", ":", "return", "self", ".", "__serviceAccount", ".", "get_url", "(", ")", "+", "'/'", "+", "self", ".", "__serviceAccount", ".", "get_instance_id", "(", ")", "+", "self", ".", "__BUNDLES_PATH" ]
59
0.008368
def _mergeKerningDictionaries(kerningDictionaries): """ Merge all of the kerning dictionaries found into one flat dictionary. """ # work through the dictionaries backwards since # this uses an update to load the kerning. this # will ensure that the script order is honored. kerning = {} ...
[ "def", "_mergeKerningDictionaries", "(", "kerningDictionaries", ")", ":", "# work through the dictionaries backwards since", "# this uses an update to load the kerning. this", "# will ensure that the script order is honored.", "kerning", "=", "{", "}", "for", "dictionaryGroup", "in", ...
34
0.002045
def get_maven_id(jar_path): """Extract Maven coordinates from a given JAR file, if possible. JARs build by Maven (most popular Java build system) contain 'pom.properties' file. We can extract Maven coordinates from there. """ props = {} try: with zip...
[ "def", "get_maven_id", "(", "jar_path", ")", ":", "props", "=", "{", "}", "try", ":", "with", "zipfile", ".", "ZipFile", "(", "jar_path", ")", "as", "f", ":", "r", "=", "re", ".", "compile", "(", "\"META-INF/maven/[^/]+/[^/]+/pom.properties$\"", ")", "resu...
41.75
0.001672
def _handle_request(self, request): """Process the headers and get the file""" # Check if this is a persistent connection. if request['version'] == 'HTTP/1.1': self.keepalive = not request.get('Connection') == 'close' elif request['version'] == 'HTTP/1.0': self.k...
[ "def", "_handle_request", "(", "self", ",", "request", ")", ":", "# Check if this is a persistent connection.", "if", "request", "[", "'version'", "]", "==", "'HTTP/1.1'", ":", "self", ".", "keepalive", "=", "not", "request", ".", "get", "(", "'Connection'", ")"...
38.055556
0.000711
def _fetch_all(cls, api_key, endpoint=None, offset=0, limit=25, **kwargs): """ Call `self._fetch_page` for as many pages as exist. TODO: should be extended to do async page fetches if API allows it via exposing total value. Returns a list of `cls` instances. """ ...
[ "def", "_fetch_all", "(", "cls", ",", "api_key", ",", "endpoint", "=", "None", ",", "offset", "=", "0", ",", "limit", "=", "25", ",", "*", "*", "kwargs", ")", ":", "output", "=", "[", "]", "qp", "=", "kwargs", ".", "copy", "(", ")", "limit", "=...
31.538462
0.001577
def _filtdim(items, shape, dim, nsl): """Return items, shape filtered by a dimension slice.""" normshape = tuple(stop - start for start, stop in shape) nsl_type = type(nsl) newitems = list() # Number of groups num = reduce(operator.mul, normshape[:dim+1]) # Size of each group size = len(...
[ "def", "_filtdim", "(", "items", ",", "shape", ",", "dim", ",", "nsl", ")", ":", "normshape", "=", "tuple", "(", "stop", "-", "start", "for", "start", ",", "stop", "in", "shape", ")", "nsl_type", "=", "type", "(", "nsl", ")", "newitems", "=", "list...
37.878049
0.000628
def get_settings(application, force_instance=False): """ Retrieve the media type settings for a application. :param tornado.web.Application application: :keyword bool force_instance: if :data:`True` then create the instance if it does not exist :return: the content settings instance :r...
[ "def", "get_settings", "(", "application", ",", "force_instance", "=", "False", ")", ":", "try", ":", "return", "application", ".", "settings", "[", "SETTINGS_KEY", "]", "except", "KeyError", ":", "if", "not", "force_instance", ":", "return", "None", "return",...
30.055556
0.001792
def _handle_star(self, i, current): """Handle star.""" if self.pathname: if self.after_start and not self.dot: star = self.path_star_dot2 globstar = self.path_gstar_dot2 elif self.after_start: star = self.path_star_dot1 ...
[ "def", "_handle_star", "(", "self", ",", "i", ",", "current", ")", ":", "if", "self", ".", "pathname", ":", "if", "self", ".", "after_start", "and", "not", "self", ".", "dot", ":", "star", "=", "self", ".", "path_star_dot2", "globstar", "=", "self", ...
36.351648
0.001177
def process_pfa_results(network, pypsa, timesteps): """ Assing values from PyPSA to :meth:`results <edisgo.grid.network.Network.results>` Parameters ---------- network : Network The eDisGo grid topology model overall container pypsa : :pypsa:`pypsa.Network<network>` The PyPS...
[ "def", "process_pfa_results", "(", "network", ",", "pypsa", ",", "timesteps", ")", ":", "# get the absolute losses in the system", "# subtracting total generation (including slack) from total load", "grid_losses", "=", "{", "'p'", ":", "1e3", "*", "(", "pypsa", ".", "gene...
42.947368
0.001078
def _total_counts(seqs, seqL, aligned=False): """ Counts total seqs after each step """ total = Counter() if isinstance(seqs, list): if not aligned: l = len([total.update(seqL[s].freq) for s in seqs]) else: l = len([total.update(seqL[s].freq) for s in seqs if ...
[ "def", "_total_counts", "(", "seqs", ",", "seqL", ",", "aligned", "=", "False", ")", ":", "total", "=", "Counter", "(", ")", "if", "isinstance", "(", "seqs", ",", "list", ")", ":", "if", "not", "aligned", ":", "l", "=", "len", "(", "[", "total", ...
35.285714
0.009862
def diff_compute(self, text1, text2, checklines, deadline): """Find the differences between two texts. Assumes that the texts do not have any common prefix or suffix. Args: text1: Old string to be diffed. text2: New string to be diffed. checklines: Speedup flag. If false, then don't r...
[ "def", "diff_compute", "(", "self", ",", "text1", ",", "text2", ",", "checklines", ",", "deadline", ")", ":", "if", "not", "text1", ":", "# Just add some text (speedup).", "return", "[", "(", "self", ".", "DIFF_INSERT", ",", "text2", ")", "]", "if", "not",...
37.603448
0.010277
def rename_file(db, user_id, old_api_path, new_api_path): """ Rename a file. """ # Overwriting existing files is disallowed. if file_exists(db, user_id, new_api_path): raise FileExists(new_api_path) old_dir, old_name = split_api_filepath(old_api_path) new_dir, new_name = split_api_...
[ "def", "rename_file", "(", "db", ",", "user_id", ",", "old_api_path", ",", "new_api_path", ")", ":", "# Overwriting existing files is disallowed.", "if", "file_exists", "(", "db", ",", "user_id", ",", "new_api_path", ")", ":", "raise", "FileExists", "(", "new_api_...
27.060606
0.001081
def compute_node_deps(): """ - returns the full dependency graph of ALL ops and ALL tensors Map<string,list<string>> where key=node name, values=list of dependency names If an Op takes in a placeholder tensor that is the ouput of a PythonOp, we need to replace that Placeholder with the PythonOp. """ deps={} g...
[ "def", "compute_node_deps", "(", ")", ":", "deps", "=", "{", "}", "g", "=", "tf", ".", "get_default_graph", "(", ")", "for", "op", "in", "g", ".", "get_operations", "(", ")", ":", "d", "=", "set", "(", "[", "i", ".", "name", "for", "i", "in", "...
25.166667
0.047194
def tell(self): """Returns the current position of read head. """ pos = ctypes.c_size_t() check_call(_LIB.MXRecordIOReaderTell(self.handle, ctypes.byref(pos))) return pos.value
[ "def", "tell", "(", "self", ")", ":", "pos", "=", "ctypes", ".", "c_size_t", "(", ")", "check_call", "(", "_LIB", ".", "MXRecordIOReaderTell", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "pos", ")", ")", ")", "return", "pos", ".", ...
35.166667
0.009259
def formfield_for_manytomany(self, db_field, request, **kwargs): ''' Not all Admin subclasses use get_field_queryset here, so we will use it explicitly ''' db = kwargs.get('using') kwargs['queryset'] = kwargs.get('queryset', self.get_field_queryset(db, db_field, request)) ...
[ "def", "formfield_for_manytomany", "(", "self", ",", "db_field", ",", "request", ",", "*", "*", "kwargs", ")", ":", "db", "=", "kwargs", ".", "get", "(", "'using'", ")", "kwargs", "[", "'queryset'", "]", "=", "kwargs", ".", "get", "(", "'queryset'", ",...
58.142857
0.012107
def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" cursor = self._db.execute("""SELECT * FROM %s WHERE msg_id==?"""%self.table, (msg_id,)) line = cursor.fetchone() if line is None: raise KeyError("No such msg: %r"%msg_id) return self._list_to_d...
[ "def", "get_record", "(", "self", ",", "msg_id", ")", ":", "cursor", "=", "self", ".", "_db", ".", "execute", "(", "\"\"\"SELECT * FROM %s WHERE msg_id==?\"\"\"", "%", "self", ".", "table", ",", "(", "msg_id", ",", ")", ")", "line", "=", "cursor", ".", "...
46.142857
0.015198
def getOneMessage ( self ): """ I pull one complete message off the buffer and return it decoded as a dict. If there is no complete message in the buffer, I return None. Note that the buffer can contain more than once message. You should therefore call me in a loop until...
[ "def", "getOneMessage", "(", "self", ")", ":", "(", "mbytes", ",", "hbytes", ")", "=", "self", ".", "_findMessageBytes", "(", "self", ".", "buffer", ")", "if", "not", "mbytes", ":", "return", "None", "msgdata", "=", "self", ".", "buffer", "[", ":", "...
37.341463
0.017823
def iter_links_by_attrib(self, element): '''Iterate an element by looking at its attributes for links.''' for attrib_name in element.attrib.keys(): attrib_value = element.attrib.get(attrib_name) if attrib_name in self.LINK_ATTRIBUTES: if self.javascript_scraper a...
[ "def", "iter_links_by_attrib", "(", "self", ",", "element", ")", ":", "for", "attrib_name", "in", "element", ".", "attrib", ".", "keys", "(", ")", ":", "attrib_value", "=", "element", ".", "attrib", ".", "get", "(", "attrib_name", ")", "if", "attrib_name",...
42.806452
0.001474
def format_time(self, sec): """ Pretty-formats a given time in a readable manner @sec: #int or #float seconds -> #str formatted time """ # µsec if sec < 0.001: return "{}{}".format( colorize(round(sec*1000000, 2), "purple"), bold("µs")...
[ "def", "format_time", "(", "self", ",", "sec", ")", ":", "# µsec", "if", "sec", "<", "0.001", ":", "return", "\"{}{}\"", ".", "format", "(", "colorize", "(", "round", "(", "sec", "*", "1000000", ",", "2", ")", ",", "\"purple\"", ")", ",", "bold", "...
32.72
0.002375
def latex(source: str): """ Add a mathematical equation in latex math-mode syntax to the display. Instead of the traditional backslash escape character, the @ character is used instead to prevent backslash conflicts with Python strings. For example, \\delta would be @delta. :param source: ...
[ "def", "latex", "(", "source", ":", "str", ")", ":", "r", "=", "_get_report", "(", ")", "if", "'katex'", "not", "in", "r", ".", "library_includes", ":", "r", ".", "library_includes", ".", "append", "(", "'katex'", ")", "r", ".", "append_body", "(", "...
38.3125
0.001592
def next_data(): "simulated data" t0 = time.time() lt = time.localtime(t0) tmin, tsec = lt[4],lt[5] u = np.random.random() v = np.random.random() x = np.sin( (u + tsec)/3.0) + tmin/30. + v/5.0 return t0, x
[ "def", "next_data", "(", ")", ":", "t0", "=", "time", ".", "time", "(", ")", "lt", "=", "time", ".", "localtime", "(", "t0", ")", "tmin", ",", "tsec", "=", "lt", "[", "4", "]", ",", "lt", "[", "5", "]", "u", "=", "np", ".", "random", ".", ...
25.444444
0.012658
def map_recursive(fn, iterable, output_type=None): """ Apply a function of a potentially nested list of lists. Parameters ---------- fn : callable The function to apply to each element (and sub elements) in iterable iterable : iterable An iterable, sequence, sequence of sequence...
[ "def", "map_recursive", "(", "fn", ",", "iterable", ",", "output_type", "=", "None", ")", ":", "def", "applyormap", "(", "it", ")", ":", "if", "issequence", "(", "it", ")", ":", "return", "map_recursive", "(", "fn", ",", "it", ",", "output_type", ")", ...
35.317073
0.000672
def mexican(lb, ub, n): r"""Generate the mexican hat wavelet The Mexican wavelet is: .. math:: w[x] = \cos{5x} \exp^{-x^2/2} :param lb: lower bound :param ub: upper bound :param int n: waveform data samples :return: the waveform .. plot:: :include-source: :width: 80%...
[ "def", "mexican", "(", "lb", ",", "ub", ",", "n", ")", ":", "if", "n", "<=", "0", ":", "raise", "ValueError", "(", "\"n must be strictly positive\"", ")", "x", "=", "numpy", ".", "linspace", "(", "lb", ",", "ub", ",", "n", ")", "psi", "=", "(", "...
22.333333
0.00159
def get(self, name=None, plugin=None): """ Returns commands, which can be filtered by name or plugin. :param name: name of the command :type name: str :param plugin: plugin object, which registers the commands :type plugin: instance of GwBasePattern :return: None...
[ "def", "get", "(", "self", ",", "name", "=", "None", ",", "plugin", "=", "None", ")", ":", "if", "plugin", "is", "not", "None", ":", "if", "name", "is", "None", ":", "command_list", "=", "{", "}", "for", "key", "in", "self", ".", "_commands", "."...
36.060606
0.001637
def init_pipette(): """ Finds pipettes attached to the robot currently and chooses the correct one to add to the session. :return: The pipette type and mount chosen for deck calibration """ global session pipette_info = set_current_mount(session.adapter, session) pipette = pipette_info[...
[ "def", "init_pipette", "(", ")", ":", "global", "session", "pipette_info", "=", "set_current_mount", "(", "session", ".", "adapter", ",", "session", ")", "pipette", "=", "pipette_info", "[", "'pipette'", "]", "res", "=", "{", "}", "if", "pipette", ":", "se...
32.32
0.001202
def unescape(s): """Unescapes html. Taken from https://wiki.python.org/moin/EscapingHtml""" s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s
[ "def", "unescape", "(", "s", ")", ":", "s", "=", "s", ".", "replace", "(", "\"&lt;\"", ",", "\"<\"", ")", "s", "=", "s", ".", "replace", "(", "\"&gt;\"", ",", "\">\"", ")", "# this has to be last:", "s", "=", "s", ".", "replace", "(", "\"&amp;\"", ...
30.142857
0.032258
def pythons(): '''Install latest pythons with pyenv. The python version will be activated in the projects base dir. Will skip already installed latest python versions. ''' if not _pyenv_exists(): print('\npyenv is not installed. You can install it with fabsetup ' '(https://gi...
[ "def", "pythons", "(", ")", ":", "if", "not", "_pyenv_exists", "(", ")", ":", "print", "(", "'\\npyenv is not installed. You can install it with fabsetup '", "'(https://github.com/theno/fabsetup):\\n\\n '", "+", "cyan", "(", "'mkdir ~/repos && cd ~/repos\\n '", "'git clon...
40.121212
0.000737
def create_admin_by_sis_id(self, sis_account_id, user_id, role): """ Flag an existing user as an admin within the account sis id. """ return self.create_admin(self._sis_id(sis_account_id), user_id, role)
[ "def", "create_admin_by_sis_id", "(", "self", ",", "sis_account_id", ",", "user_id", ",", "role", ")", ":", "return", "self", ".", "create_admin", "(", "self", ".", "_sis_id", "(", "sis_account_id", ")", ",", "user_id", ",", "role", ")" ]
46.2
0.008511
def _add_two_way_unqualified_edge(self, u: BaseEntity, v: BaseEntity, relation: str) -> str: """Add an unqualified edge both ways.""" self.add_unqualified_edge(v, u, relation) return self.add_unqualified_edge(u, v, relation)
[ "def", "_add_two_way_unqualified_edge", "(", "self", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "relation", ":", "str", ")", "->", "str", ":", "self", ".", "add_unqualified_edge", "(", "v", ",", "u", ",", "relation", ")", "return", "s...
61.25
0.012097
def main(self, configuration): """ :type configuration Configuration """ _custom_func_arguments = {"conf"} filename = os.path.basename(os.path.abspath(sys.argv[0])) default_arg_list = [item for item in configuration.get("default") if len(item.strip()) != 0] if len(default_arg_list) == 0: ...
[ "def", "main", "(", "self", ",", "configuration", ")", ":", "_custom_func_arguments", "=", "{", "\"conf\"", "}", "filename", "=", "os", ".", "path", ".", "basename", "(", "os", ".", "path", ".", "abspath", "(", "sys", ".", "argv", "[", "0", "]", ")",...
35
0.011525
def dist_docs(): "create a documentation bundle" dist_dir = path("dist") docs_package = path("%s/%s-%s-docs.zip" % (dist_dir.abspath(), options.setup.name, options.setup.version)) dist_dir.exists() or dist_dir.makedirs() docs_package.exists() and docs_package.remove() sh(r'cd build/apidocs && ...
[ "def", "dist_docs", "(", ")", ":", "dist_dir", "=", "path", "(", "\"dist\"", ")", "docs_package", "=", "path", "(", "\"%s/%s-%s-docs.zip\"", "%", "(", "dist_dir", ".", "abspath", "(", ")", ",", "options", ".", "setup", ".", "name", ",", "options", ".", ...
36.923077
0.00813
def mounts(cls): """ Return tuple of current mount points :return: tuple of WMountPoint """ result = [] with open(cls.__mounts_file__) as f: for mount_record in f: result.append(WMountPoint(mount_record)) return tuple(result)
[ "def", "mounts", "(", "cls", ")", ":", "result", "=", "[", "]", "with", "open", "(", "cls", ".", "__mounts_file__", ")", "as", "f", ":", "for", "mount_record", "in", "f", ":", "result", ".", "append", "(", "WMountPoint", "(", "mount_record", ")", ")"...
23.6
0.040816
def task_coverage(): """show coverage for all modules including tests""" cov = Coverage( [PythonPackage('import_deps', 'tests')], config={'branch':True,}, ) yield cov.all() # create task `coverage` yield cov.src()
[ "def", "task_coverage", "(", ")", ":", "cov", "=", "Coverage", "(", "[", "PythonPackage", "(", "'import_deps'", ",", "'tests'", ")", "]", ",", "config", "=", "{", "'branch'", ":", "True", ",", "}", ",", ")", "yield", "cov", ".", "all", "(", ")", "#...
30.25
0.016064
def connect_discussion_signals(): """ Connect all the signals on the Comment model to maintains a valid discussion count on each entries when an action is done with the comments. """ post_save.connect( count_discussions_handler, sender=comment_model, dispatch_uid=COMMENT_PS_COUNT...
[ "def", "connect_discussion_signals", "(", ")", ":", "post_save", ".", "connect", "(", "count_discussions_handler", ",", "sender", "=", "comment_model", ",", "dispatch_uid", "=", "COMMENT_PS_COUNT_DISCUSSIONS", ")", "post_delete", ".", "connect", "(", "count_discussions_...
41.583333
0.000979
def trim_extrema(im, h, mode='maxima'): r""" Trims local extrema in greyscale values by a specified amount. This essentially decapitates peaks and/or floods valleys. Parameters ---------- im : ND-array The image whose extrema are to be removed h : float The height to remov...
[ "def", "trim_extrema", "(", "im", ",", "h", ",", "mode", "=", "'maxima'", ")", ":", "result", "=", "im", "if", "mode", "in", "[", "'maxima'", ",", "'extrema'", "]", ":", "result", "=", "reconstruction", "(", "seed", "=", "im", "-", "h", ",", "mask"...
27.969697
0.001047
def notification_redirect(request, ctx): """ Helper to handle HTTP response after an action is performed on notification :param request: HTTP request context of the notification :param ctx: context to be returned when a AJAX call is made. :returns: Either JSON for AJAX or redirects to the calcula...
[ "def", "notification_redirect", "(", "request", ",", "ctx", ")", ":", "if", "request", ".", "is_ajax", "(", ")", ":", "return", "JsonResponse", "(", "ctx", ")", "else", ":", "next_page", "=", "request", ".", "POST", ".", "get", "(", "'next'", ",", "rev...
36.1
0.00135
def execute_or_create_resource(self, device_id, _resource_path, **kwargs): # noqa: E501 """Execute a function on a Resource or create new Object instance # noqa: E501 With this API, you can [execute a function](/docs/current/connecting/handle-resource-webapp.html#the-execute-operation) on an existing...
[ "def", "execute_or_create_resource", "(", "self", ",", "device_id", ",", "_resource_path", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", "...
131.416667
0.00063
def _provision_network(self, port_id, net_uuid, network_type, physical_network, segmentation_id): """Provision the network with the received information.""" LOG.info("Provisioning network %s", net_uuid) vswitch_name = self._get_vswitch_name(network_type, physical_netw...
[ "def", "_provision_network", "(", "self", ",", "port_id", ",", "net_uuid", ",", "network_type", ",", "physical_network", ",", "segmentation_id", ")", ":", "LOG", ".", "info", "(", "\"Provisioning network %s\"", ",", "net_uuid", ")", "vswitch_name", "=", "self", ...
44.387097
0.002134
def get_process_deferred_code_breakpoints(self, dwProcessId): """ Returns a list of deferred code breakpoints. @type dwProcessId: int @param dwProcessId: Process ID. @rtype: tuple of (int, str, callable, bool) @return: Tuple containing the following elements: ...
[ "def", "get_process_deferred_code_breakpoints", "(", "self", ",", "dwProcessId", ")", ":", "return", "[", "(", "label", ",", "action", ",", "oneshot", ")", "for", "(", "label", ",", "(", "action", ",", "oneshot", ")", ")", "in", "compat", ".", "iteritems",...
42.375
0.008658
def distance_matrix(client, origins, destinations, mode=None, language=None, avoid=None, units=None, departure_time=None, arrival_time=None, transit_mode=None, transit_routing_preference=None, traffic_model=None, region=None): """ Gets travel distance and ...
[ "def", "distance_matrix", "(", "client", ",", "origins", ",", "destinations", ",", "mode", "=", "None", ",", "language", "=", "None", ",", "avoid", "=", "None", ",", "units", "=", "None", ",", "departure_time", "=", "None", ",", "arrival_time", "=", "Non...
40.321739
0.000421
def right_to_left(self): """This is for text that flows Right to Left""" self._entry_mode &= ~Command.MODE_INCREMENT self.command(self._entry_mode)
[ "def", "right_to_left", "(", "self", ")", ":", "self", ".", "_entry_mode", "&=", "~", "Command", ".", "MODE_INCREMENT", "self", ".", "command", "(", "self", ".", "_entry_mode", ")" ]
42
0.011696
def _add_expansion_to_acronym_dict(acronym, expansion, level, dictionary): """Add an acronym to the dictionary. Takes care of avoiding duplicates and keeping the expansion marked with the best score. """ if len(acronym) >= len(expansion) or acronym in expansion: return for punctuation ...
[ "def", "_add_expansion_to_acronym_dict", "(", "acronym", ",", "expansion", ",", "level", ",", "dictionary", ")", ":", "if", "len", "(", "acronym", ")", ">=", "len", "(", "expansion", ")", "or", "acronym", "in", "expansion", ":", "return", "for", "punctuation...
34.333333
0.001717
def _reExec(regex, string): '''This returns [full match, group1, group2, ...], just like JS.''' m = regex.search(string) if not m: return None return [m.group()] + list(m.groups())
[ "def", "_reExec", "(", "regex", ",", "string", ")", ":", "m", "=", "regex", ".", "search", "(", "string", ")", "if", "not", "m", ":", "return", "None", "return", "[", "m", ".", "group", "(", ")", "]", "+", "list", "(", "m", ".", "groups", "(", ...
38.4
0.010204
def get_next_base26(prev=None): """Increment letter-based IDs. Generates IDs like ['a', 'b', ..., 'z', 'aa', ab', ..., 'az', 'ba', ...] Returns: str: Next base-26 ID. """ if not prev: return 'a' r = re.compile("^[a-z]*$") if not r.match(prev): raise ValueError("Inv...
[ "def", "get_next_base26", "(", "prev", "=", "None", ")", ":", "if", "not", "prev", ":", "return", "'a'", "r", "=", "re", ".", "compile", "(", "\"^[a-z]*$\"", ")", "if", "not", "r", ".", "match", "(", "prev", ")", ":", "raise", "ValueError", "(", "\...
23.263158
0.002174
def find_or_upsert(self, constructor, props, *, comp=None, return_status=False): """This finds or upserts a model with an auto primary key, and is a bit more flexible than find_or_create. First it looks for the model matching either comp, or props if comp is None. If not found, it will try to upsert t...
[ "def", "find_or_upsert", "(", "self", ",", "constructor", ",", "props", ",", "*", ",", "comp", "=", "None", ",", "return_status", "=", "False", ")", ":", "model", "=", "self", ".", "find_model", "(", "constructor", ",", "comp", "or", "props", ")", "sta...
49.342105
0.01046
def do(self): """Executes the request represented by this object. The requests library will be used for this purpose. Returns an instance of requests.Response. """ data = None if self.body is not None and self.body != b'': data = self.body return requests.requ...
[ "def", "do", "(", "self", ")", ":", "data", "=", "None", "if", "self", ".", "body", "is", "not", "None", "and", "self", ".", "body", "!=", "b''", ":", "data", "=", "self", ".", "body", "return", "requests", ".", "request", "(", "self", ".", "meth...
47
0.010444
def load_feather(protein_feather, length_filter_pid=None, copynum_scale=False, copynum_df=None): """Load a feather of amino acid counts for a protein. Args: protein_feather (str): path to feather file copynum_scale (bool): if counts should be multiplied by protein copy number copynum_df...
[ "def", "load_feather", "(", "protein_feather", ",", "length_filter_pid", "=", "None", ",", "copynum_scale", "=", "False", ",", "copynum_df", "=", "None", ")", ":", "protein_df", "=", "pd", ".", "read_feather", "(", "protein_feather", ")", ".", "set_index", "("...
59.044118
0.010044
def memo_add(self, tid, memo, session, flag=None): '''taobao.trade.memo.add 对一笔交易添加备注 根据登录用户的身份(买家或卖家),自动添加相应的交易备注,不能重复调用些接口添加备注,需要更新备注请用taobao.trade.memo.update''' request = TOPRequest('taobao.trade.memo.add') request['tid'] = tid request['memo'] = memo if flag!...
[ "def", "memo_add", "(", "self", ",", "tid", ",", "memo", ",", "session", ",", "flag", "=", "None", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.trade.memo.add'", ")", "request", "[", "'tid'", "]", "=", "tid", "request", "[", "'memo'", "]", "="...
42.1
0.016279
def announce(self, number): """ Announce an indicator change on both channels. """ self.client.publish(self.keys.internal, self.keys.key(number)) self.message('{} granted'.format(number))
[ "def", "announce", "(", "self", ",", "number", ")", ":", "self", ".", "client", ".", "publish", "(", "self", ".", "keys", ".", "internal", ",", "self", ".", "keys", ".", "key", "(", "number", ")", ")", "self", ".", "message", "(", "'{} granted'", "...
52
0.009479
def trigger_event(name, event, value1=None, value2=None, value3=None ): ''' Trigger an event in IFTTT .. code-block:: yaml ifttt-event: ifttt.trigger_event: - event: TestEvent ...
[ "def", "trigger_event", "(", "name", ",", "event", ",", "value1", "=", "None", ",", "value2", "=", "None", ",", "value3", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False",...
23.918033
0.001317
def mean_loss_ratios_with_steps(self, steps): """ Split the mean loss ratios, producing a new set of loss ratios. The new set of loss ratios always includes 0.0 and 1.0 :param int steps: the number of steps we make to go from one loss ratio to the next. For examp...
[ "def", "mean_loss_ratios_with_steps", "(", "self", ",", "steps", ")", ":", "loss_ratios", "=", "self", ".", "mean_loss_ratios", "if", "min", "(", "loss_ratios", ")", ">", "0.0", ":", "# prepend with a zero", "loss_ratios", "=", "numpy", ".", "concatenate", "(", ...
37.32
0.00209
def abs_paths(self): """ :API: public """ for relpath in self._rel_paths: yield os.path.join(self._root, relpath)
[ "def", "abs_paths", "(", "self", ")", ":", "for", "relpath", "in", "self", ".", "_rel_paths", ":", "yield", "os", ".", "path", ".", "join", "(", "self", ".", "_root", ",", "relpath", ")" ]
21.666667
0.014815
def _create_snippet_actions(self): """Add mock Qt actions for snippet keystrokes. Used to enable snippet mode. """ # One action per allowed character. for i, char in enumerate(self._snippet_chars): def _make_func(char): def callback(): ...
[ "def", "_create_snippet_actions", "(", "self", ")", ":", "# One action per allowed character.", "for", "i", ",", "char", "in", "enumerate", "(", "self", ".", "_snippet_chars", ")", ":", "def", "_make_func", "(", "char", ")", ":", "def", "callback", "(", ")", ...
36.642857
0.001899
def json_encode(obj, serialize): """ Handle encoding complex types. """ if hasattr(obj, 'to_dict'): return obj.to_dict(serialize=serialize) elif isinstance(obj, datetime): return obj.date().isoformat() elif isinstance(obj, date): return obj.isoformat() elif isinstance(obj, Pr...
[ "def", "json_encode", "(", "obj", ",", "serialize", ")", ":", "if", "hasattr", "(", "obj", ",", "'to_dict'", ")", ":", "return", "obj", ".", "to_dict", "(", "serialize", "=", "serialize", ")", "elif", "isinstance", "(", "obj", ",", "datetime", ")", ":"...
33.571429
0.00207
def init_exporter(extract_images, execute, **exporter_config): """ Returns an initialized exporter. """ config = Config(InteractExporter=exporter_config) preprocessors = [] if extract_images: # Use ExtractOutputPreprocessor to extract the images to separate files preprocessors.a...
[ "def", "init_exporter", "(", "extract_images", ",", "execute", ",", "*", "*", "exporter_config", ")", ":", "config", "=", "Config", "(", "InteractExporter", "=", "exporter_config", ")", "preprocessors", "=", "[", "]", "if", "extract_images", ":", "# Use ExtractO...
33.904762
0.001366
def objectMD5(obj): '''Get md5 of an object''' if hasattr(obj, 'target_name'): return obj.target_name() try: return textMD5(pickle.dumps(obj)) except: return ''
[ "def", "objectMD5", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'target_name'", ")", ":", "return", "obj", ".", "target_name", "(", ")", "try", ":", "return", "textMD5", "(", "pickle", ".", "dumps", "(", "obj", ")", ")", "except", ":", ...
24.125
0.01
def option_vip_by_environment_vip_type(self, environment_vip_id, type_option): """ List option vip. param environment_vip_id: Id of Environment Vip Param type_option: type option vip """ uri = "api/v3/option-vip/environment-vip/%s/type-option/%s/" % (environment_vip_id, ...
[ "def", "option_vip_by_environment_vip_type", "(", "self", ",", "environment_vip_id", ",", "type_option", ")", ":", "uri", "=", "\"api/v3/option-vip/environment-vip/%s/type-option/%s/\"", "%", "(", "environment_vip_id", ",", "type_option", ")", "return", "self", ".", "get"...
35.3
0.008287
def check_output_command(file_path, head=None, tail=None): '''call check_output command to read content from a file''' if os.path.exists(file_path): if sys.platform == 'win32': cmds = ['powershell.exe', 'type', file_path] if head: cmds += ['|', 'select', '-first',...
[ "def", "check_output_command", "(", "file_path", ",", "head", "=", "None", ",", "tail", "=", "None", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "cmds", "=", "[", ...
41.55
0.001176
def get_matches(pattern, language, max_count=8): """ take a word pattern or a Python regexp and a language name, and return a list of all matching words. """ if str(pattern) == pattern: pattern = compile_pattern(pattern) results = [] if not dicts.exists(language): print("Th...
[ "def", "get_matches", "(", "pattern", ",", "language", ",", "max_count", "=", "8", ")", ":", "if", "str", "(", "pattern", ")", "==", "pattern", ":", "pattern", "=", "compile_pattern", "(", "pattern", ")", "results", "=", "[", "]", "if", "not", "dicts",...
27.708333
0.001453
def dispatch(self, event): """ Dispatch file system event. Callback called when there is a file system event. Hooked at 2KGRW. This function overrides `FileSystemEventHandler.dispatch`. :param event: File system event object. :return: None. ...
[ "def", "dispatch", "(", "self", ",", "event", ")", ":", "# Get file path", "file_path", "=", "event", ".", "src_path", "# If the file path is in extra paths", "if", "file_path", "in", "self", ".", "_extra_paths", ":", "# Call `reload`", "self", ".", "reload", "(",...
29.194444
0.001842
def fetch_country_by_ip(ip): """ Fetches country code by IP Returns empty string if the request fails in non-200 code. Uses the ipdata.co service which has the following rules: * Max 1500 requests per day See: https://ipdata.co/docs.html#python-library """ iplookup = ipdata.ipdata() ...
[ "def", "fetch_country_by_ip", "(", "ip", ")", ":", "iplookup", "=", "ipdata", ".", "ipdata", "(", ")", "data", "=", "iplookup", ".", "lookup", "(", "ip", ")", "if", "data", ".", "get", "(", "'status'", ")", "!=", "200", ":", "return", "''", "return",...
24.777778
0.00216
def NewFromJSON(data): """ Create a new SharedFile instance from a JSON dict. Args: data (dict): JSON dictionary representing a SharedFile. Returns: A SharedFile instance. """ return SharedFile( sharekey=data.get('sharekey', None), ...
[ "def", "NewFromJSON", "(", "data", ")", ":", "return", "SharedFile", "(", "sharekey", "=", "data", ".", "get", "(", "'sharekey'", ",", "None", ")", ",", "name", "=", "data", ".", "get", "(", "'name'", ",", "None", ")", ",", "user", "=", "User", "."...
36.3
0.001789
def _get_kvc(kv_arg): '''Returns a tuple keys, values, count for kv_arg (which can be a dict or a tuple containing keys, values and optinally count.''' if isinstance(kv_arg, Mapping): return six.iterkeys(kv_arg), six.itervalues(kv_arg), len(kv_arg) assert 2 <= len(kv_arg) <= 3, \ 'Ar...
[ "def", "_get_kvc", "(", "kv_arg", ")", ":", "if", "isinstance", "(", "kv_arg", ",", "Mapping", ")", ":", "return", "six", ".", "iterkeys", "(", "kv_arg", ")", ",", "six", ".", "itervalues", "(", "kv_arg", ")", ",", "len", "(", "kv_arg", ")", "assert"...
43.727273
0.002037
def search_proxy_for_facet(self, facet, **kwargs): # noqa: E501 """Lists the values of a specific facet over the customer's non-deleted proxies # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_...
[ "def", "search_proxy_for_facet", "(", "self", ",", "facet", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "se...
45.5
0.001957
def sortedJSONDumpS(obj): """ Return a JSON representation of obj with sorted keys on any embedded dicts. This insures that the same object will always be represented by the same string even if it contains dicts (where the sort order of the keys is normally undefined). """ itemStrs = [] if isinstance(...
[ "def", "sortedJSONDumpS", "(", "obj", ")", ":", "itemStrs", "=", "[", "]", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "items", "=", "obj", ".", "items", "(", ")", "items", ".", "sort", "(", ")", "for", "key", ",", "value", "in", "item...
28
0.011511
def set_scenario_role_names(self): """Populates the list of scenario role names in this deployment and populates the scenario_master with the master role Gets a list of deployment properties containing "isMaster" because there is exactly one per scenario host, containing the role name ...
[ "def", "set_scenario_role_names", "(", "self", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.set_scenario_role_names'", ")", "is_master_props", "=", "self", ".", "get_matching_property_names", "(", "'isMaster'", ")", "f...
47.380952
0.00197
def _InstallImportHookBySuffix(): """Lazily installs import hook.""" global _real_import if _real_import: return # Import hook already installed _real_import = getattr(builtins, '__import__') assert _real_import builtins.__import__ = _ImportHookBySuffix if six.PY3: # In Python 2, importlib.imp...
[ "def", "_InstallImportHookBySuffix", "(", ")", ":", "global", "_real_import", "if", "_real_import", ":", "return", "# Import hook already installed", "_real_import", "=", "getattr", "(", "builtins", ",", "'__import__'", ")", "assert", "_real_import", "builtins", ".", ...
32.789474
0.014041
def get_item(item, **kwargs): """ API versioning for each OpenStack service is independent. Generically capture the public members (non-routine and non-private) of the OpenStack SDK objects. Note the lack of the modify_output decorator. Preserving the field naming allows us to reconstruct o...
[ "def", "get_item", "(", "item", ",", "*", "*", "kwargs", ")", ":", "_item", "=", "{", "}", "for", "k", ",", "v", "in", "inspect", ".", "getmembers", "(", "item", ",", "lambda", "a", ":", "not", "(", "inspect", ".", "isroutine", "(", "a", ")", "...
40
0.012216
def _calc_fwhm(volume, mask, voxel_size=[1.0, 1.0, 1.0], ): """ Calculate the FWHM of a volume Estimates the FWHM (mm) of a volume's non-masked voxels Parameters ---------- volume : 3 dimensional array Functional data to have the FWHM measured. ...
[ "def", "_calc_fwhm", "(", "volume", ",", "mask", ",", "voxel_size", "=", "[", "1.0", ",", "1.0", ",", "1.0", "]", ",", ")", ":", "# What are the dimensions of the volume", "dimensions", "=", "volume", ".", "shape", "# Iterate through the TRs, creating a FWHM for eac...
30.537736
0.000299
def push_group_with_content(self, content): """Temporarily redirects drawing to an intermediate surface known as a group. The redirection lasts until the group is completed by a call to :meth:`pop_group` or :meth:`pop_group_to_source`. These calls provide the result of any drawin...
[ "def", "push_group_with_content", "(", "self", ",", "content", ")", ":", "cairo", ".", "cairo_push_group_with_content", "(", "self", ".", "_pointer", ",", "content", ")", "self", ".", "_check_status", "(", ")" ]
42.2
0.002317
def from_string(cls, action_str): """ Creates a new Action instance from the given string. The given string **must** match one of those patterns: * module.function * module.function() * module.function(arg1=value1, arg2=value2) Any other form will t...
[ "def", "from_string", "(", "cls", ",", "action_str", ")", ":", "args", "=", "{", "}", "try", ":", "mod_obj", "=", "ast", ".", "parse", "(", "action_str", ")", "except", "(", "SyntaxError", ",", "ValueError", ")", "as", "e", ":", "raise", "e", "else",...
37.647887
0.000729
def abfFname_Save(abfFname): """return the path of the last loaded ABF.""" fname=userFolder()+"/abfFname.ini" with open(fname,'w') as f: f.write(os.path.abspath(abfFname)) return
[ "def", "abfFname_Save", "(", "abfFname", ")", ":", "fname", "=", "userFolder", "(", ")", "+", "\"/abfFname.ini\"", "with", "open", "(", "fname", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "os", ".", "path", ".", "abspath", "(", "abfFnam...
32.833333
0.014851
def prev(self): """ Return the previous window """ prev_index = self.index - 1 prev_handle = self._browser.driver.window_handles[prev_index] return Window(self._browser, prev_handle)
[ "def", "prev", "(", "self", ")", ":", "prev_index", "=", "self", ".", "index", "-", "1", "prev_handle", "=", "self", ".", "_browser", ".", "driver", ".", "window_handles", "[", "prev_index", "]", "return", "Window", "(", "self", ".", "_browser", ",", "...
42
0.009346
def _generate_pl_dataset(n, m, outfile, useDirichlet): """ Description: Generate a Plackett-Luce dataset and save it to disk. Parameters: n: number of votes to generate m: number of alternatives outfile: open file object to which the...
[ "def", "_generate_pl_dataset", "(", "n", ",", "m", ",", "outfile", ",", "useDirichlet", ")", ":", "gamma", ",", "votes", "=", "generate_pl_dataset", "(", "n", ",", "m", ",", "useDirichlet", ")", "outfile", ".", "write", "(", "str", "(", "len", "(", "ga...
38.333333
0.001414
def get_PSL(self,min_intron_size=68): """Get a PSL object representation of the alignment. :returns: PSL representation :rtype: PSL """ from seqtools.format.psl import PSL matches = sum([x[0].length for x in self.alignment_ranges]) # 1. Matches - Number of matching bases that aren't repeats ...
[ "def", "get_PSL", "(", "self", ",", "min_intron_size", "=", "68", ")", ":", "from", "seqtools", ".", "format", ".", "psl", "import", "PSL", "matches", "=", "sum", "(", "[", "x", "[", "0", "]", ".", "length", "for", "x", "in", "self", ".", "alignmen...
37.2
0.03143
def hash(path, hash_function=hashlib.sha512): # @ReservedAssignment ''' Hash file or directory. Parameters ---------- path : ~pathlib.Path File or directory to hash. hash_function : ~typing.Callable[[], hash object] Function which creates a hashlib hash object when called. Defa...
[ "def", "hash", "(", "path", ",", "hash_function", "=", "hashlib", ".", "sha512", ")", ":", "# @ReservedAssignment", "hash_", "=", "hash_function", "(", ")", "if", "path", ".", "is_dir", "(", ")", ":", "for", "directory", ",", "directories", ",", "files", ...
35.857143
0.002424
def channels_add_moderator(self, room_id, user_id, **kwargs): """Gives the role of moderator for a user in the current channel.""" return self.__call_api_post('channels.addModerator', roomId=room_id, userId=user_id, kwargs=kwargs)
[ "def", "channels_add_moderator", "(", "self", ",", "room_id", ",", "user_id", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__call_api_post", "(", "'channels.addModerator'", ",", "roomId", "=", "room_id", ",", "userId", "=", "user_id", ",", "kwa...
81.333333
0.012195
def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" @functools.wraps(func) def new_func(*args, **kwargs): if PY3K: func_code = func.__code__ else: ...
[ "def", "deprecated", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "PY3K", ":", "func_code", "=", "func", ".", "__code__", "else", ":", "func_c...
28.818182
0.001527
def get_tensors(object_): """ Get all tensors associated with ``object_`` Args: object_ (any): Any object to look for tensors. Returns: (list of torch.tensor): List of tensors that are associated with ``object_``. """ if torch.is_tensor(object_): return [object_] elif i...
[ "def", "get_tensors", "(", "object_", ")", ":", "if", "torch", ".", "is_tensor", "(", "object_", ")", ":", "return", "[", "object_", "]", "elif", "isinstance", "(", "object_", ",", "(", "str", ",", "float", ",", "int", ")", ")", ":", "return", "[", ...
29.566667
0.002183
def cli(env, package_keyname): """List Datacenters a package can be ordered in. Use the location Key Name to place orders """ manager = ordering.OrderingManager(env.client) table = formatting.Table(COLUMNS) locations = manager.package_locations(package_keyname) for region in locations: ...
[ "def", "cli", "(", "env", ",", "package_keyname", ")", ":", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "locations", "=", "manager", ".", "package_locati...
32
0.001686
def run_lsm_rapid_process(rapid_executable_location, lsm_data_location, rapid_io_files_location=None, rapid_input_location=None, rapid_output_location=None, simulation_start_datetime=None, ...
[ "def", "run_lsm_rapid_process", "(", "rapid_executable_location", ",", "lsm_data_location", ",", "rapid_io_files_location", "=", "None", ",", "rapid_input_location", "=", "None", ",", "rapid_output_location", "=", "None", ",", "simulation_start_datetime", "=", "None", ","...
44.024
0.000044
def fold(H, columns=None): """ Fold a design to reduce confounding effects. Parameters ---------- H : 2d-array The design matrix to be folded. columns : array Indices of of columns to fold (Default: None). If ``columns=None`` is used, then all columns will ...
[ "def", "fold", "(", "H", ",", "columns", "=", "None", ")", ":", "H", "=", "np", ".", "array", "(", "H", ")", "assert", "len", "(", "H", ".", "shape", ")", "==", "2", ",", "'Input design matrix must be 2d.'", "if", "columns", "is", "None", ":", "col...
23.325
0.015432
def request(self, method, resource, all_pages=False, **kwargs): """ Makes a request to the given endpoint. Keyword arguments are passed to the :meth:`~requests.request` method. If the content type of the response is JSON, it will be decoded automatically and a dictionary will be ...
[ "def", "request", "(", "self", ",", "method", ",", "resource", ",", "all_pages", "=", "False", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "raw_request", "(", "method", ",", "resource", ",", "*", "*", "kwargs", ")", "if", "not", ...
41.21875
0.001481
def permissions_for(self, user): """Handles permission resolution for a :class:`User`. This function is there for compatibility with other channel types. Actual direct messages do not really have the concept of permissions. This returns all the Text related permissions set to true exc...
[ "def", "permissions_for", "(", "self", ",", "user", ")", ":", "base", "=", "Permissions", ".", "text", "(", ")", "base", ".", "send_tts_messages", "=", "False", "base", ".", "manage_messages", "=", "False", "base", ".", "mention_everyone", "=", "True", "if...
29.235294
0.001947
def get(self, uid=None, key_wrapping_specification=None): """ Get a managed object from a KMIP appliance. Args: uid (string): The unique ID of the managed object to retrieve. key_wrapping_specification (dict): A dictionary containing various settings to b...
[ "def", "get", "(", "self", ",", "uid", "=", "None", ",", "key_wrapping_specification", "=", "None", ")", ":", "# Check input", "if", "uid", "is", "not", "None", ":", "if", "not", "isinstance", "(", "uid", ",", "six", ".", "string_types", ")", ":", "rai...
47.75
0.000604
def time(lancet, issue): """ Start an Harvest timer for the given issue. This command takes care of linking the timer with the issue tracker page for the given issue. If the issue is not passed to command it's taken from currently active branch. """ issue = get_issue(lancet, issue) wit...
[ "def", "time", "(", "lancet", ",", "issue", ")", ":", "issue", "=", "get_issue", "(", "lancet", ",", "issue", ")", "with", "taskstatus", "(", "\"Starting harvest timer\"", ")", "as", "ts", ":", "lancet", ".", "timer", ".", "start", "(", "issue", ")", "...
32.769231
0.002283