text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_all_notificants(self, **kwargs): # noqa: E501 """Get all notification targets for a customer # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_all_n...
[ "def", "get_all_notificants", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "get_all_notificants_wit...
40.772727
18.454545
def vote_cast(vote: Vote, choice_index: int, inputs: dict, change_address: str) -> bytes: '''vote cast transaction''' network_params = net_query(vote.deck.network) vote_cast_addr = vote.vote_choice_address[choice_index] tx_fee = network_params.min_tx_fee # settle for min tx fee for now ...
[ "def", "vote_cast", "(", "vote", ":", "Vote", ",", "choice_index", ":", "int", ",", "inputs", ":", "dict", ",", "change_address", ":", "str", ")", "->", "bytes", ":", "network_params", "=", "net_query", "(", "vote", ".", "deck", ".", "network", ")", "v...
38.4
25.5
def writeFile(self, fname = None): """Writes the `RecordCollection` to a file, the written file's format is identical to those download from WOS. The order of `Records` written is random. # Parameters _fname_ : `optional [str]` > Default `None`, if given the output file will written t...
[ "def", "writeFile", "(", "self", ",", "fname", "=", "None", ")", ":", "if", "len", "(", "self", ".", "_collectedTypes", ")", "<", "2", ":", "recEncoding", "=", "self", ".", "peek", "(", ")", ".", "encoding", "(", ")", "else", ":", "recEncoding", "=...
42.1
21.133333
def snmp_server_group_group_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") group = ET.SubElement(snmp_server, "group") group_version_key = ET.SubE...
[ "def", "snmp_server_group_group_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "snmp_server", "=", "ET", ".", "SubElement", "(", "config", ",", "\"snmp-server\"", ",", "xmlns", "=", "\"ur...
45.923077
16.923077
def knock_out(self): """Knockout gene by marking it as non-functional and setting all associated reactions bounds to zero. The change is reverted upon exit if executed within the model as context. """ self.functional = False for reaction in self.reactions: ...
[ "def", "knock_out", "(", "self", ")", ":", "self", ".", "functional", "=", "False", "for", "reaction", "in", "self", ".", "reactions", ":", "if", "not", "reaction", ".", "functional", ":", "reaction", ".", "bounds", "=", "(", "0", ",", "0", ")" ]
34.909091
11.909091
def activate_line(self, lines=None, bitmask=None, leave_remaining_lines=False): """ Triggers an output line on StimTracker. There are 8 output lines on StimTracker that can be raised in any combination. To raise lines 1 and 7, for example, you pass in the ...
[ "def", "activate_line", "(", "self", ",", "lines", "=", "None", ",", "bitmask", "=", "None", ",", "leave_remaining_lines", "=", "False", ")", ":", "if", "lines", "is", "None", "and", "bitmask", "is", "None", ":", "raise", "ValueError", "(", "'Must set one ...
37.338462
24.076923
def has_roles(self, *requirements): """ Return True if the user has all of the specified roles. Return False otherwise. has_roles() accepts a list of requirements: has_role(requirement1, requirement2, requirement3). Each requirement is either a role_name, or a tuple_of_...
[ "def", "has_roles", "(", "self", ",", "*", "requirements", ")", ":", "# Translates a list of role objects to a list of role_names", "user_manager", "=", "current_app", ".", "user_manager", "role_names", "=", "user_manager", ".", "db_manager", ".", "get_user_roles", "(", ...
47.5
21.113636
def glob(patterns, parent=None, excludes=None, include_dotfiles=False, ignore_false_excludes=False): """ Wrapper for #glob2.glob() that accepts an arbitrary number of patterns and matches them. The paths are normalized with #norm(). Relative patterns are automaticlly joined with *parent*. If the par...
[ "def", "glob", "(", "patterns", ",", "parent", "=", "None", ",", "excludes", "=", "None", ",", "include_dotfiles", "=", "False", ",", "ignore_false_excludes", "=", "False", ")", ":", "if", "not", "glob2", ":", "raise", "glob2_ext", "if", "isinstance", "(",...
33.530303
21.136364
def on_mouse_wheel(self, event): '''handle mouse wheel zoom changes''' rotation = event.GetWheelRotation() / event.GetWheelDelta() if rotation > 0: zoom = 1.0/(1.1 * rotation) elif rotation < 0: zoom = 1.1 * (-rotation) self.change_zoom(zoom) self....
[ "def", "on_mouse_wheel", "(", "self", ",", "event", ")", ":", "rotation", "=", "event", ".", "GetWheelRotation", "(", ")", "/", "event", ".", "GetWheelDelta", "(", ")", "if", "rotation", ">", "0", ":", "zoom", "=", "1.0", "/", "(", "1.1", "*", "rotat...
36
11.111111
def get_absolute_path(self, path): ''' Returns the absolute path of the ``path`` argument. If ``path`` is already absolute, nothing changes. If the ``path`` is relative, then the BASEDIR will be prepended. ''' if os.path.isabs(path): return path else:...
[ "def", "get_absolute_path", "(", "self", ",", "path", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "path", "else", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "s...
35.090909
23.636364
def to_136_array(tiles): """ Convert 34 array to the 136 tiles array """ temp = [] results = [] for x in range(0, 34): if tiles[x]: temp_value = [x * 4] * tiles[x] for tile in temp_value: if tile in results: ...
[ "def", "to_136_array", "(", "tiles", ")", ":", "temp", "=", "[", "]", "results", "=", "[", "]", "for", "x", "in", "range", "(", "0", ",", "34", ")", ":", "if", "tiles", "[", "x", "]", ":", "temp_value", "=", "[", "x", "*", "4", "]", "*", "t...
33.1
12
def handle_unexpected_exception(exc): # type: (BaseException) -> str """Return an error message and write a log file if logging was not enabled. Args: exc: The unexpected exception. Returns: A message to display to the user concerning the unexpected exception. """ try: ...
[ "def", "handle_unexpected_exception", "(", "exc", ")", ":", "# type: (BaseException) -> str", "try", ":", "write_logfile", "(", ")", "addendum", "=", "'Please see the log file for more information.'", "except", "IOError", ":", "addendum", "=", "'Unable to write log file.'", ...
31.95
19.95
def _reaction_representer(dumper, data): """Generate a parsable reaction representation to the YAML parser. Check the number of compounds in the reaction, if it is larger than 10, then transform the reaction data into a list of directories with all attributes in the reaction; otherwise, just return the...
[ "def", "_reaction_representer", "(", "dumper", ",", "data", ")", ":", "if", "len", "(", "data", ".", "compounds", ")", ">", "_MAX_REACTION_LENGTH", ":", "def", "dict_make", "(", "compounds", ")", ":", "for", "compound", ",", "value", "in", "compounds", ":"...
36.515152
15.454545
def _assign_clusters(X, centers): """ Assignment Step: assign each point to the closet cluster center """ dist2cents = scipy.spatial.distance.cdist(X, centers, metric='seuclidean') membs = np.argmin(dist2cents, axis=1) return(membs)
[ "def", "_assign_clusters", "(", "X", ",", "centers", ")", ":", "dist2cents", "=", "scipy", ".", "spatial", ".", "distance", ".", "cdist", "(", "X", ",", "centers", ",", "metric", "=", "'seuclidean'", ")", "membs", "=", "np", ".", "argmin", "(", "dist2c...
32.125
15.75
def get_servers(self, topic): """We're assuming that the static list of servers can serve the given topic, since we have to preexisting knowledge about them. """ return (nsq.node.ServerNode(sh) for sh in self.__server_hosts)
[ "def", "get_servers", "(", "self", ",", "topic", ")", ":", "return", "(", "nsq", ".", "node", ".", "ServerNode", "(", "sh", ")", "for", "sh", "in", "self", ".", "__server_hosts", ")" ]
42.166667
17.666667
def _load_countryfile(self, url="https://www.country-files.com/cty/cty.plist", country_mapping_filename="countryfilemapping.json", cty_file=None): """ Load and process the ClublogXML file either as a download or from file """ ...
[ "def", "_load_countryfile", "(", "self", ",", "url", "=", "\"https://www.country-files.com/cty/cty.plist\"", ",", "country_mapping_filename", "=", "\"countryfilemapping.json\"", ",", "cty_file", "=", "None", ")", ":", "cwdFile", "=", "os", ".", "path", ".", "abspath",...
42.30303
23.121212
def center_of_mass(self): """ Center of mass of molecule. """ center = np.zeros(3) total_weight = 0 for site in self: wt = site.species.weight center += site.coords * wt total_weight += wt return center / total_weight
[ "def", "center_of_mass", "(", "self", ")", ":", "center", "=", "np", ".", "zeros", "(", "3", ")", "total_weight", "=", "0", "for", "site", "in", "self", ":", "wt", "=", "site", ".", "species", ".", "weight", "center", "+=", "site", ".", "coords", "...
27.181818
7.545455
def register_dispatch_wrapper(wrapper): """Register a dispatch wrapper for servers The wrapper must have this exact signature: (func, *args, **kwargs) """ signature = inspect.getargspec(wrapper) if any([len(signature.args) != 1, signature.varargs is None, signature...
[ "def", "register_dispatch_wrapper", "(", "wrapper", ")", ":", "signature", "=", "inspect", ".", "getargspec", "(", "wrapper", ")", "if", "any", "(", "[", "len", "(", "signature", ".", "args", ")", "!=", "1", ",", "signature", ".", "varargs", "is", "None"...
28.32
13.08
def listurl_get(self, q, **kwargs): '''taobao.taobaoke.listurl.get 淘宝客关键词搜索URL 淘宝客关键词搜索URL''' request = TOPRequest('taobao.taobaoke.listurl.get') request['q'] = q for k, v in kwargs.iteritems(): if k not in ('nick', 'outer_code', 'pid') and v==None: continue ...
[ "def", "listurl_get", "(", "self", ",", "q", ",", "*", "*", "kwargs", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.taobaoke.listurl.get'", ")", "request", "[", "'q'", "]", "=", "q", "for", "k", ",", "v", "in", "kwargs", ".", "iteritems", "(", ...
43.454545
20.363636
def start(self): """ Start the worker processes. TODO: Move task receiving to a thread """ start = time.time() self._kill_event = threading.Event() self.procs = {} for worker_id in range(self.worker_count): p = multiprocessing.Process(target=worker, ...
[ "def", "start", "(", "self", ")", ":", "start", "=", "time", ".", "time", "(", ")", "self", ".", "_kill_event", "=", "threading", ".", "Event", "(", ")", "self", ".", "procs", "=", "{", "}", "for", "worker_id", "in", "range", "(", "self", ".", "w...
43.38
22.98
def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False, pred_contribs=False, approx_contribs=False, pred_interactions=False, validate_features=True): """ Predict with data. .. note:: This function is not thread safe. For each boost...
[ "def", "predict", "(", "self", ",", "data", ",", "output_margin", "=", "False", ",", "ntree_limit", "=", "0", ",", "pred_leaf", "=", "False", ",", "pred_contribs", "=", "False", ",", "approx_contribs", "=", "False", ",", "pred_interactions", "=", "False", ...
42.953704
26.675926
def get_by_entityid(self, entityid): """ Returns the entity with the given entity ID as a dict """ data = self.list(entityid=entityid) if len(data) == 0: return None eid = int( next(iter(data)) ) entity = self.get(eid) self.debug(0x01,entity) return entity
[ "def", "get_by_entityid", "(", "self", ",", "entityid", ")", ":", "data", "=", "self", ".", "list", "(", "entityid", "=", "entityid", ")", "if", "len", "(", "data", ")", "==", "0", ":", "return", "None", "eid", "=", "int", "(", "next", "(", "iter",...
20.615385
16.461538
def satisfyDependenciesRecursive( self, available_components = None, search_dirs = None, update_installed = False, traverse_links = False, target = None, test = False ...
[ "def", "satisfyDependenciesRecursive", "(", "self", ",", "available_components", "=", "None", ",", "search_dirs", "=", "None", ",", "update_installed", "=", "False", ",", "traverse_links", "=", "False", ",", "target", "=", "None", ",", "test", "=", "False", ")...
41.03125
20.78125
def plot_bargraph( self, rank="auto", normalize="auto", top_n="auto", threshold="auto", title=None, xlabel=None, ylabel=None, tooltip=None, return_chart=False, haxis=None, legend="auto", label=None, ): ""...
[ "def", "plot_bargraph", "(", "self", ",", "rank", "=", "\"auto\"", ",", "normalize", "=", "\"auto\"", ",", "top_n", "=", "\"auto\"", ",", "threshold", "=", "\"auto\"", ",", "title", "=", "None", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", "...
38.020305
24.634518
def save(self, *args, **kwargs): """ Save object in database, updating the datetimes accordingly. """ # Now in UTC now_datetime = timezone.now() # If we are in a creation, assigns creation_datetime if not self.id: self.creation_datetime = now_datetime # Las update datetime is always updated se...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Now in UTC", "now_datetime", "=", "timezone", ".", "now", "(", ")", "# If we are in a creation, assigns creation_datetime", "if", "not", "self", ".", "id", ":", "self", ".", ...
28.458333
16.375
def initialize(self, init=initializer.Uniform(), ctx=None, verbose=False, force_reinit=False): """Initializes :py:class:`Parameter` s of this :py:class:`Block` and its children. Equivalent to ``block.collect_params().initialize(...)`` Parameters ---------- ini...
[ "def", "initialize", "(", "self", ",", "init", "=", "initializer", ".", "Uniform", "(", ")", ",", "ctx", "=", "None", ",", "verbose", "=", "False", ",", "force_reinit", "=", "False", ")", ":", "self", ".", "collect_params", "(", ")", ".", "initialize",...
50.444444
20.611111
def getCodecList(self): """Query Asterisk Manager Interface for defined codecs. CLI Command - core show codecs @return: Dictionary - Short Name -> (Type, Long Name) """ if self.checkVersion('1.4'): cmd = "core show codecs" else: ...
[ "def", "getCodecList", "(", "self", ")", ":", "if", "self", ".", "checkVersion", "(", "'1.4'", ")", ":", "cmd", "=", "\"core show codecs\"", "else", ":", "cmd", "=", "\"show codecs\"", "cmdresp", "=", "self", ".", "executeCommand", "(", "cmd", ")", "info_d...
34
16.3
def authenticate_user(self, request, user): """ returns ``True`` if the password value supplied is a valid user password or a valid user token can be overridden to implement more complex checks """ return user.check_password(request.data.get('password')) or \ ...
[ "def", "authenticate_user", "(", "self", ",", "request", ",", "user", ")", ":", "return", "user", ".", "check_password", "(", "request", ".", "data", ".", "get", "(", "'password'", ")", ")", "or", "self", ".", "check_user_token", "(", "request", ",", "us...
44
11.25
def get_eff_gain(base_std, base_std_unc, meth_std, meth_std_unc, adjust=1): r"""Calculates efficiency gain for a new method compared to a base method. Given the variation in repeated calculations' results using the two methods, the efficiency gain is: .. math:: \mathrm{efficiency\,gain} ...
[ "def", "get_eff_gain", "(", "base_std", ",", "base_std_unc", ",", "meth_std", ",", "meth_std_unc", ",", "adjust", "=", "1", ")", ":", "ratio", "=", "base_std", "/", "meth_std", "ratio_unc", "=", "array_ratio_std", "(", "base_std", ",", "base_std_unc", ",", "...
28.076923
20.358974
def putintopackageroot(target, source, env, pkgroot, honor_install_location=1): """ Uses the CopyAs builder to copy all source files to the directory given in pkgroot. If honor_install_location is set and the copied source file has an PACKAGING_INSTALL_LOCATION attribute, the PACKAGING_INSTALL_LOCATION...
[ "def", "putintopackageroot", "(", "target", ",", "source", ",", "env", ",", "pkgroot", ",", "honor_install_location", "=", "1", ")", ":", "# make sure the packageroot is a Dir object.", "if", "SCons", ".", "Util", ".", "is_String", "(", "pkgroot", ")", ":", "pkg...
37.833333
22.277778
def _headers(self, name, is_file=False): """ Returns the header of the encoding of this parameter. Args: name (str): Field name Kwargs: is_file (bool): If true, this is a file field Returns: array. Headers """ ...
[ "def", "_headers", "(", "self", ",", "name", ",", "is_file", "=", "False", ")", ":", "value", "=", "self", ".", "_files", "[", "name", "]", "if", "is_file", "else", "self", ".", "_data", "[", "name", "]", "_boundary", "=", "self", ".", "boundary", ...
30.35
24.85
def range(self, channels=None): """ Get the range of the specified channel(s). The range is a two-element list specifying the smallest and largest values that an event in a channel should have. Note that with floating point data, some events could have values outside the ...
[ "def", "range", "(", "self", ",", "channels", "=", "None", ")", ":", "# Check default", "if", "channels", "is", "None", ":", "channels", "=", "self", ".", "_channels", "# Get numerical indices of channels", "channels", "=", "self", ".", "_name_to_index", "(", ...
34.073171
20.560976
def enter_password_change(self, username=None, old_password=None): """ Responds to a forced password change via `passwd` prompts due to password expiration. """ from fabric.state import connections from fabric.network import disconnect_all r = self.local_renderer # ...
[ "def", "enter_password_change", "(", "self", ",", "username", "=", "None", ",", "old_password", "=", "None", ")", ":", "from", "fabric", ".", "state", "import", "connections", "from", "fabric", ".", "network", "import", "disconnect_all", "r", "=", "self", "....
50.465517
20.534483
def mag_scale_rel_to_hazardlib(mag_scale_rel, use_default=False): """ Returns the magnitude scaling relation in a format readable by openquake.hazardlib """ if isinstance(mag_scale_rel, BaseMSR): return mag_scale_rel elif isinstance(mag_scale_rel, str): if not mag_scale_rel in SC...
[ "def", "mag_scale_rel_to_hazardlib", "(", "mag_scale_rel", ",", "use_default", "=", "False", ")", ":", "if", "isinstance", "(", "mag_scale_rel", ",", "BaseMSR", ")", ":", "return", "mag_scale_rel", "elif", "isinstance", "(", "mag_scale_rel", ",", "str", ")", ":"...
37.052632
15.684211
def _create_linked_clone(self): """ Creates a new linked clone. """ gns3_snapshot_exists = False vm_info = yield from self._get_vm_info() for entry, value in vm_info.items(): if entry.startswith("SnapshotName") and value == "GNS3 Linked Base for clones": ...
[ "def", "_create_linked_clone", "(", "self", ")", ":", "gns3_snapshot_exists", "=", "False", "vm_info", "=", "yield", "from", "self", ".", "_get_vm_info", "(", ")", "for", "entry", ",", "value", "in", "vm_info", ".", "items", "(", ")", ":", "if", "entry", ...
40.977273
22.886364
def install(cls, handler, fmt=None, use_chroot=True, style=DEFAULT_FORMAT_STYLE): """ Install the :class:`HostNameFilter` on a log handler (only if needed). :param fmt: The log format string to check for ``%(hostname)``. :param style: One of the characters ``%``, ``{`` or ``$`` (default...
[ "def", "install", "(", "cls", ",", "handler", ",", "fmt", "=", "None", ",", "use_chroot", "=", "True", ",", "style", "=", "DEFAULT_FORMAT_STYLE", ")", ":", "if", "fmt", ":", "parser", "=", "FormatStringParser", "(", "style", "=", "style", ")", "if", "n...
46.315789
24
def get_method(self, name, descriptor): """ Get the method by name and descriptor, or create a new one if the requested method does not exists. :param name: method name :param descriptor: method descriptor, for example `'(I)V'` :return: :class:`ExternalMethod` ""...
[ "def", "get_method", "(", "self", ",", "name", ",", "descriptor", ")", ":", "key", "=", "name", "+", "str", "(", "descriptor", ")", "if", "key", "not", "in", "self", ".", "methods", ":", "self", ".", "methods", "[", "key", "]", "=", "ExternalMethod",...
35.071429
14.357143
def find_loops(self, _path=None): """Crappy function that finds a single loop in the tree""" if _path is None: _path = [] if self in _path: return _path + [self] elif self._children == []: return None else: for child in self._chil...
[ "def", "find_loops", "(", "self", ",", "_path", "=", "None", ")", ":", "if", "_path", "is", "None", ":", "_path", "=", "[", "]", "if", "self", "in", "_path", ":", "return", "_path", "+", "[", "self", "]", "elif", "self", ".", "_children", "==", "...
28.384615
15.923077
def _parse_svc_config(self, json_dic, view = None): """ Parse a json-decoded ApiServiceConfig dictionary into a 2-tuple. @param json_dic: The json dictionary with the config data. @param view: View to materialize. @return: 2-tuple (service config dictionary, role type configurations) """ sv...
[ "def", "_parse_svc_config", "(", "self", ",", "json_dic", ",", "view", "=", "None", ")", ":", "svc_config", "=", "json_to_config", "(", "json_dic", ",", "view", "==", "'full'", ")", "rt_configs", "=", "{", "}", "if", "json_dic", ".", "has_key", "(", "ROL...
38.125
15.75
def dequantize(arr, min_val, max_val, levels, dtype=np.float64): """Dequantize an array. Args: arr (ndarray): Input array. min_val (scalar): Minimum value to be clipped. max_val (scalar): Maximum value to be clipped. levels (int): Quantization levels. dtype (np.type): Th...
[ "def", "dequantize", "(", "arr", ",", "min_val", ",", "max_val", ",", "levels", ",", "dtype", "=", "np", ".", "float64", ")", ":", "if", "not", "(", "isinstance", "(", "levels", ",", "int", ")", "and", "levels", ">", "1", ")", ":", "raise", "ValueE...
32.92
18.36
def start(self, *args, **kwargs):#pylint:disable=unused-argument """ Launch the method. :param restart: Restart the method if it ends. :type restart: bool :rtype: None """ restart = kwargs.get('restart', True) return self.run(restart)
[ "def", "start", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#pylint:disable=unused-argument", "restart", "=", "kwargs", ".", "get", "(", "'restart'", ",", "True", ")", "return", "self", ".", "run", "(", "restart", ")" ]
32.222222
10.888889
def load_from_buffer(self, buf, password=None, keyfile=None, readonly=False): """ Load a database from passed-in buffer (bytes). :param buf: A string (bytes) of the database contents. :type buf: str :param password: The password for the database. :type password: str ...
[ "def", "load_from_buffer", "(", "self", ",", "buf", ",", "password", "=", "None", ",", "keyfile", "=", "None", ",", "readonly", "=", "False", ")", ":", "if", "password", "is", "None", "and", "keyfile", "is", "None", ":", "raise", "ValueError", "(", "\"...
51.805556
27.75
def parse_from_dict(json_dict): """ Given a Unified Uploader message, parse the contents and return a MarketHistoryList instance. :param dict json_dict: A Unified Uploader message as a dict. :rtype: MarketOrderList :returns: An instance of MarketOrderList, containing the orders within. ...
[ "def", "parse_from_dict", "(", "json_dict", ")", ":", "history_columns", "=", "json_dict", "[", "'columns'", "]", "history_list", "=", "MarketHistoryList", "(", "upload_keys", "=", "json_dict", "[", "'uploadKeys'", "]", ",", "history_generator", "=", "json_dict", ...
33.552632
18.605263
def set_owner_params(self, uid=None, gid=None): """Drop http router privileges to specified user and group. :param str|unicode|int uid: Set uid to the specified username or uid. :param str|unicode|int gid: Set gid to the specified groupname or gid. """ self._set_aliased('uid',...
[ "def", "set_owner_params", "(", "self", ",", "uid", "=", "None", ",", "gid", "=", "None", ")", ":", "self", ".", "_set_aliased", "(", "'uid'", ",", "uid", ")", "self", ".", "_set_aliased", "(", "'gid'", ",", "gid", ")", "return", "self" ]
31.083333
22.416667
def get_attribute(self, attribute): """ :param attribute: requested attributes. :return: attribute value. :raise TgnError: if invalid attribute. """ value = self.api.getAttribute(self.obj_ref(), attribute) # IXN returns '::ixNet::OK' for invalid attributes. We wan...
[ "def", "get_attribute", "(", "self", ",", "attribute", ")", ":", "value", "=", "self", ".", "api", ".", "getAttribute", "(", "self", ".", "obj_ref", "(", ")", ",", "attribute", ")", "# IXN returns '::ixNet::OK' for invalid attributes. We want error.", "if", "value...
41.636364
12.909091
def future_import2(feature, node): """ An alternative to future_import() which might not work ... """ root = find_root(node) if does_tree_import(u"__future__", feature, node): return insert_pos = 0 for idx, node in enumerate(root.children): if node.type == syms.simple_stmt ...
[ "def", "future_import2", "(", "feature", ",", "node", ")", ":", "root", "=", "find_root", "(", "node", ")", "if", "does_tree_import", "(", "u\"__future__\"", ",", "feature", ",", "node", ")", ":", "return", "insert_pos", "=", "0", "for", "idx", ",", "nod...
28.354839
20.677419
def cast_object(self, interface_object, interface_class): """Cast the obj to the interface class :rtype: interface_class(interface_object) """ name = interface_class.__name__ i = self.manager.queryInterface(interface_object._i, name) return interface_class(interface=i)
[ "def", "cast_object", "(", "self", ",", "interface_object", ",", "interface_class", ")", ":", "name", "=", "interface_class", ".", "__name__", "i", "=", "self", ".", "manager", ".", "queryInterface", "(", "interface_object", ".", "_i", ",", "name", ")", "ret...
38.875
12
def muscle_seqs(seqs, add_seq_names=False, out_filename=None, input_handler=None, params={}, WorkingDir=tempfile.gettempdir(), SuppressStderr=None, SuppressStdout=None): """Muscle align list of seq...
[ "def", "muscle_seqs", "(", "seqs", ",", "add_seq_names", "=", "False", ",", "out_filename", "=", "None", ",", "input_handler", "=", "None", ",", "params", "=", "{", "}", ",", "WorkingDir", "=", "tempfile", ".", "gettempdir", "(", ")", ",", "SuppressStderr"...
41.666667
21.263158
def from_json(cls, json_data): """Create an uploader given (parsed) JSON data. Note that this is a JSON-formatted key file downloaded from Google when the service account key is created, *NOT* a json-encoded oauth2client.client.SignedJwtAssertionCredentials object. Args: json_data: Dict cont...
[ "def", "from_json", "(", "cls", ",", "json_data", ")", ":", "return", "cls", "(", "user", "=", "json_data", "[", "'client_email'", "]", ",", "keydata", "=", "json_data", "[", "'private_key'", "]", ",", "token_uri", "=", "json_data", "[", "'token_uri'", "]"...
34.4375
19.4375
def history_table_min(self): '区间交易历史的table' if len(self.history_min) > 0: lens = len(self.history_min[0]) else: lens = len(self._history_headers) return pd.DataFrame( data=self.history_min, columns=self._history_headers[:lens] ).so...
[ "def", "history_table_min", "(", "self", ")", ":", "if", "len", "(", "self", ".", "history_min", ")", ">", "0", ":", "lens", "=", "len", "(", "self", ".", "history_min", "[", "0", "]", ")", "else", ":", "lens", "=", "len", "(", "self", ".", "_his...
29.090909
13.818182
def iter(self, count=0): '''Iterator of infinite dice rolls. :param count: [0] Return list of ``count`` sums ''' while True: yield super(FuncRoll, self).roll(count, self._func)
[ "def", "iter", "(", "self", ",", "count", "=", "0", ")", ":", "while", "True", ":", "yield", "super", "(", "FuncRoll", ",", "self", ")", ".", "roll", "(", "count", ",", "self", ".", "_func", ")" ]
35.833333
17.833333
def get_diagnosis(self, remediation_id=None): ''' Reach out to the platform and fetch a diagnosis. Spirtual successor to --to-json from the old client. ''' # this uses machine id as identifier instead of inventory id diag_url = self.base_url + '/remediations/v1/di...
[ "def", "get_diagnosis", "(", "self", ",", "remediation_id", "=", "None", ")", ":", "# this uses machine id as identifier instead of inventory id", "diag_url", "=", "self", ".", "base_url", "+", "'/remediations/v1/diagnosis/'", "+", "generate_machine_id", "(", ")", "params...
43.695652
20.652174
def raw_request(self, method, resource, access_token=None, **kwargs): """ Makes a HTTP request and returns the raw :class:`~requests.Response` object. """ headers = self._pop_headers(kwargs) headers['Authorization'] = self._get_authorization_header(access_token) ...
[ "def", "raw_request", "(", "self", ",", "method", ",", "resource", ",", "access_token", "=", "None", ",", "*", "*", "kwargs", ")", ":", "headers", "=", "self", ".", "_pop_headers", "(", "kwargs", ")", "headers", "[", "'Authorization'", "]", "=", "self", ...
44.7
18.5
def scanning_template(self): "Path to {ScanningTemplate}name.xml of experiment." tmpl = glob(_pattern(self.path, _additional_data, _scanning_template, extension='*.xml')) if tmpl: return tmpl[0] else: return ''
[ "def", "scanning_template", "(", "self", ")", ":", "tmpl", "=", "glob", "(", "_pattern", "(", "self", ".", "path", ",", "_additional_data", ",", "_scanning_template", ",", "extension", "=", "'*.xml'", ")", ")", "if", "tmpl", ":", "return", "tmpl", "[", "...
35.375
19.375
def ResolvePrefix(self, subject, attribute_prefix, timestamp=None, limit=None): """Resolve all attributes for a subject starting with a prefix.""" subject = utils.SmartUnicode(subject) if timestamp in [None, self.NEWEST_TIMESTAMP, self.ALL_TIMESTAMPS]: start, end = 0, (2**63) - 1 ...
[ "def", "ResolvePrefix", "(", "self", ",", "subject", ",", "attribute_prefix", ",", "timestamp", "=", "None", ",", "limit", "=", "None", ")", ":", "subject", "=", "utils", ".", "SmartUnicode", "(", "subject", ")", "if", "timestamp", "in", "[", "None", ","...
37.904762
19.714286
def t_RSQBR(self, t): r"\]" t.endlexpos = t.lexpos + len(t.value) return t
[ "def", "t_RSQBR", "(", "self", ",", "t", ")", ":", "t", ".", "endlexpos", "=", "t", ".", "lexpos", "+", "len", "(", "t", ".", "value", ")", "return", "t" ]
23.75
18.75
def from_env(cls): """Create a service instance from an environment variable.""" token = getenv(cls.TOKEN_ENV_VAR) if token is None: msg = 'missing environment variable: {!r}'.format(cls.TOKEN_ENV_VAR) raise ValueError(msg) return cls(api_token=token)
[ "def", "from_env", "(", "cls", ")", ":", "token", "=", "getenv", "(", "cls", ".", "TOKEN_ENV_VAR", ")", "if", "token", "is", "None", ":", "msg", "=", "'missing environment variable: {!r}'", ".", "format", "(", "cls", ".", "TOKEN_ENV_VAR", ")", "raise", "Va...
43
12.857143
def levenshtein_distance(word1, word2): """ Computes the Levenshtein distance. [Reference]: https://en.wikipedia.org/wiki/Levenshtein_distance [Article]: Levenshtein, Vladimir I. (February 1966). "Binary codes capable of correcting deletions, insertions,and reversals". Soviet Physics Doklady 10...
[ "def", "levenshtein_distance", "(", "word1", ",", "word2", ")", ":", "if", "len", "(", "word1", ")", "<", "len", "(", "word2", ")", ":", "return", "levenshtein_distance", "(", "word2", ",", "word1", ")", "if", "len", "(", "word2", ")", "==", "0", ":"...
34.965517
21.862069
def long_to_hex(l, size): """Encode a long value as a hex string, 0-padding to size. Note that size is the size of the resulting hex string. So, for a 32Byte long size should be 64 (two hex characters per byte".""" f_str = "{0:0%sx}" % size return ensure_bytes(f_str.format(l).lower())
[ "def", "long_to_hex", "(", "l", ",", "size", ")", ":", "f_str", "=", "\"{0:0%sx}\"", "%", "size", "return", "ensure_bytes", "(", "f_str", ".", "format", "(", "l", ")", ".", "lower", "(", ")", ")" ]
42.857143
15.714286
def loadFromDisk(self, calculation): """ Read the spectra from the files generated by Quanty and store them as a list of spectum objects. """ suffixes = { 'Isotropic': 'iso', 'Circular Dichroism (R-L)': 'cd', 'Right Polarized (R)': 'r', ...
[ "def", "loadFromDisk", "(", "self", ",", "calculation", ")", ":", "suffixes", "=", "{", "'Isotropic'", ":", "'iso'", ",", "'Circular Dichroism (R-L)'", ":", "'cd'", ",", "'Right Polarized (R)'", ":", "'r'", ",", "'Left Polarized (L)'", ":", "'l'", ",", "'Linear ...
35.303371
17.235955
def parse_attributes(s): """ Parses the ``attribute`` string of a GFF/GTF annotation. Parameters ---------- s : str The attribute string. Returns ------- dict A dictionary containing attribute name/value pairs. Notes ----- The ``attribute`` string is the 9th fi...
[ "def", "parse_attributes", "(", "s", ")", ":", "# use regular expression with negative lookbehind to make sure we don't", "# split on escaped semicolons (\"\\;\")", "attr_sep", "=", "re", ".", "compile", "(", "r'(?<!\\\\)\\s*;\\s*'", ")", "attr", "=", "{", "}", "atts", "=",...
25.46875
21.5625
def get_bright(mask, image, ret_data="avg,sd"): """Compute avg and/or std of the event brightness The event brightness is defined by the gray-scale values of the image data within the event mask area. Parameters ---------- mask: ndarray or list of ndarrays of shape (M,N) and dtype bool ...
[ "def", "get_bright", "(", "mask", ",", "image", ",", "ret_data", "=", "\"avg,sd\"", ")", ":", "# This method is based on a pull request by Maik Herbig.", "ret_avg", "=", "\"avg\"", "in", "ret_data", "ret_std", "=", "\"sd\"", "in", "ret_data", "if", "ret_avg", "+", ...
28.635135
19.364865
def LoadGDAL(filename, no_data=None): """Read a GDAL file. Opens any file GDAL can read, selects the first raster band, and loads it and its metadata into a RichDEM array of the appropriate data type. If you need to do something more complicated, look at the source of this function. Args: ...
[ "def", "LoadGDAL", "(", "filename", ",", "no_data", "=", "None", ")", ":", "if", "not", "GDAL_AVAILABLE", ":", "raise", "Exception", "(", "\"richdem.LoadGDAL() requires GDAL.\"", ")", "allowed_types", "=", "{", "gdal", ".", "GDT_Byte", ",", "gdal", ".", "GDT_I...
35.520833
30.166667
def _worker_thread_transfer(self): # type: (Uploader) -> None """Worker thread transfer :param Uploader self: this """ while not self.termination_check: try: ud, ase, offsets, data = self._transfer_queue.get( block=False, timeout=0....
[ "def", "_worker_thread_transfer", "(", "self", ")", ":", "# type: (Uploader) -> None", "while", "not", "self", ".", "termination_check", ":", "try", ":", "ud", ",", "ase", ",", "offsets", ",", "data", "=", "self", ".", "_transfer_queue", ".", "get", "(", "bl...
35.375
9.875
def _process_mrk_acc_view(self): """ Use this table to create the idmap between the internal marker id and the public mgiid. No triples are produced in this process :return: """ # make a pass through the table first, # to create the mapping between the e...
[ "def", "_process_mrk_acc_view", "(", "self", ")", ":", "# make a pass through the table first,", "# to create the mapping between the external and internal identifiers", "line_counter", "=", "0", "LOG", ".", "info", "(", "\"mapping markers to internal identifiers\"", ")", "raw", ...
37.5
19.55
def write_to_conll_eval_file(prediction_file: TextIO, gold_file: TextIO, verb_index: Optional[int], sentence: List[str], prediction: List[str], gold_labels: List[str]): ""...
[ "def", "write_to_conll_eval_file", "(", "prediction_file", ":", "TextIO", ",", "gold_file", ":", "TextIO", ",", "verb_index", ":", "Optional", "[", "int", "]", ",", "sentence", ":", "List", "[", "str", "]", ",", "prediction", ":", "List", "[", "str", "]", ...
41
15.325581
def bytes2fsn(data, encoding="utf-8"): """ Args: data (bytes): The data to convert encoding (`str`): encoding used for Windows Returns: `fsnative` Raises: TypeError: If no `bytes` path is passed ValueError: If decoding fails or the encoding is invalid Turns `...
[ "def", "bytes2fsn", "(", "data", ",", "encoding", "=", "\"utf-8\"", ")", ":", "if", "not", "isinstance", "(", "data", ",", "bytes", ")", ":", "raise", "TypeError", "(", "\"data needs to be bytes\"", ")", "if", "is_win", ":", "if", "encoding", "is", "None",...
30.4
19.25
def _safe_get_element_date(self, path, root=None): """Safe get elemnent date. Get element as datetime.date or None, :param root: Lxml element. :param path: String path (i.e. 'Items.Item.Offers.Offer'). :return: datetime.date or None. "...
[ "def", "_safe_get_element_date", "(", "self", ",", "path", ",", "root", "=", "None", ")", ":", "value", "=", "self", ".", "_safe_get_element_text", "(", "path", "=", "path", ",", "root", "=", "root", ")", "if", "value", "is", "not", "None", ":", "try",...
29.380952
15.52381
def design_list(self): """ List all design documents for the current bucket. :return: A :class:`~couchbase.result.HttpResult` containing a dict, with keys being the ID of the design document. .. note:: This information is derived using the ``pools/d...
[ "def", "design_list", "(", "self", ")", ":", "ret", "=", "self", ".", "_http_request", "(", "type", "=", "_LCB", ".", "LCB_HTTP_TYPE_MANAGEMENT", ",", "path", "=", "\"/pools/default/buckets/{0}/ddocs\"", ".", "format", "(", "self", ".", "_cb", ".", "bucket", ...
34.792453
24.603774
def update_dependency(self, tile, depinfo, destdir=None): """Attempt to install or update a dependency to the latest version. Args: tile (IOTile): An IOTile object describing the tile that has the dependency depinfo (dict): a dictionary from tile.dependencies specifying the depe...
[ "def", "update_dependency", "(", "self", ",", "tile", ",", "depinfo", ",", "destdir", "=", "None", ")", ":", "if", "destdir", "is", "None", ":", "destdir", "=", "os", ".", "path", ".", "join", "(", "tile", ".", "folder", ",", "'build'", ",", "'deps'"...
31.362319
21.507246
def _set_auth(self, v, load=False): """ Setter method for auth, mapped from YANG variable /rbridge_id/fcsp/auth (container) If this variable is read-only (config: false) in the source YANG file, then _set_auth is considered as a private method. Backends looking to populate this variable should d...
[ "def", "_set_auth", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
72.090909
33.5
def reset_counters(self): """ Resets all counters, truth and classification masks. """ self.truth_masks = None self.classification_masks = None self.pixel_truth_counts = None self.pixel_classification_counts = None self.pixel_truth_sum = None self....
[ "def", "reset_counters", "(", "self", ")", ":", "self", ".", "truth_masks", "=", "None", "self", ".", "classification_masks", "=", "None", "self", ".", "pixel_truth_counts", "=", "None", "self", ".", "pixel_classification_counts", "=", "None", "self", ".", "pi...
33.5
6.833333
def word(self, _id, padding=75): """ Get words """ word = self.words[_id][2] vec = word_to_vector(word) vec += [-1] * (padding - len(vec)) return np.array(vec, dtype=np.int32)
[ "def", "word", "(", "self", ",", "_id", ",", "padding", "=", "75", ")", ":", "word", "=", "self", ".", "words", "[", "_id", "]", "[", "2", "]", "vec", "=", "word_to_vector", "(", "word", ")", "vec", "+=", "[", "-", "1", "]", "*", "(", "paddin...
28
6.25
def get_base(vpc, **conn): """ The base will return: - ARN - Region - Name - Id - Tags - IsDefault - InstanceTenancy - CidrBlock - CidrBlockAssociationSet - Ipv6CidrBlockAssociationSet - DhcpOptionsId - Attributes - _version :param bucket_name: :param...
[ "def", "get_base", "(", "vpc", ",", "*", "*", "conn", ")", ":", "# Get the base:", "base_result", "=", "describe_vpcs", "(", "VpcIds", "=", "[", "vpc", "[", "\"id\"", "]", "]", ",", "*", "*", "conn", ")", "[", "0", "]", "# The name of the VPC is in the t...
28.677966
21.491525
def add_access_list(self, loadbalancer, access_list): """ Adds the access list provided to the load balancer. The 'access_list' should be a list of dicts in the following format: [{"address": "192.0.43.10", "type": "DENY"}, {"address": "192.0.43.11", "type": "ALLOW"}, ...
[ "def", "add_access_list", "(", "self", ",", "loadbalancer", ",", "access_list", ")", ":", "req_body", "=", "{", "\"accessList\"", ":", "access_list", "}", "uri", "=", "\"/loadbalancers/%s/accesslist\"", "%", "utils", ".", "get_id", "(", "loadbalancer", ")", "res...
38.631579
21.894737
def delete_dispatch(self, dispatch_id): """ Deleting an existing dispatch :param dispatch_id: is the dispatch that the client wants to delete """ self._validate_uuid(dispatch_id) url = "/notification/v1/dispatch/{}".format(dispatch_id) response = NWS_DAO().delete...
[ "def", "delete_dispatch", "(", "self", ",", "dispatch_id", ")", ":", "self", ".", "_validate_uuid", "(", "dispatch_id", ")", "url", "=", "\"/notification/v1/dispatch/{}\"", ".", "format", "(", "dispatch_id", ")", "response", "=", "NWS_DAO", "(", ")", ".", "del...
37.076923
16.923077
def purge_objects(self, request): """ Removes all objects in this table. This action first displays a confirmation page; next, it deletes all objects and redirects back to the change list. """ def truncate_table(model): if settings.TRUNCATE_TABLE_SQL_STATEMEN...
[ "def", "purge_objects", "(", "self", ",", "request", ")", ":", "def", "truncate_table", "(", "model", ")", ":", "if", "settings", ".", "TRUNCATE_TABLE_SQL_STATEMENT", ":", "from", "django", ".", "db", "import", "connection", "sql", "=", "settings", ".", "TRU...
40.470588
21.960784
def ls(**params): ''' List devices in Server Density Results will be filtered by any params passed to this function. For more information, see the API docs on listing_ and searching_. .. _listing: https://apidocs.serverdensity.com/Inventory/Devices/Listing .. _searching: https://apidocs.server...
[ "def", "ls", "(", "*", "*", "params", ")", ":", "params", "=", "_clean_salt_variables", "(", "params", ")", "endpoint", "=", "'devices'", "# Change endpoint if there are params to filter by:", "if", "params", ":", "endpoint", "=", "'resources'", "# Convert all ints to...
33.24
24.04
def check(self, request, response, secret): """Checks the response for the appropriate signature. Returns True if the signature matches the expected value. Keyword arguments: request -- A request object which can be consumed by this API. response -- A requests response object or compati...
[ "def", "check", "(", "self", ",", "request", ",", "response", ",", "secret", ")", ":", "auth", "=", "request", ".", "get_header", "(", "'Authorization'", ")", "if", "auth", "==", "''", ":", "raise", "KeyError", "(", "'Authorization header is required for the r...
53.235294
22.764706
def is_ordered_dict(d): """ Predicate checking for ordered dictionaries. OrderedDict is always ordered, and vanilla Python dictionaries are ordered for Python 3.6+ """ py3_ordered_dicts = (sys.version_info.major == 3) and (sys.version_info.minor >= 6) vanilla_odicts = (sys.version_info.major > 3...
[ "def", "is_ordered_dict", "(", "d", ")", ":", "py3_ordered_dicts", "=", "(", "sys", ".", "version_info", ".", "major", "==", "3", ")", "and", "(", "sys", ".", "version_info", ".", "minor", ">=", "6", ")", "vanilla_odicts", "=", "(", "sys", ".", "versio...
52.25
24.75
def transform_cell(self, cell): """Process and translate a cell of input. """ self.reset() self.push(cell) return self.source_reset()
[ "def", "transform_cell", "(", "self", ",", "cell", ")", ":", "self", ".", "reset", "(", ")", "self", ".", "push", "(", "cell", ")", "return", "self", ".", "source_reset", "(", ")" ]
28
8.666667
def handle_exec_method(self, msg): """ Handle data returned by silent executions of kernel methods This is based on the _handle_exec_callback of RichJupyterWidget. Therefore this is licensed BSD. """ user_exp = msg['content'].get('user_expressions') if not user_e...
[ "def", "handle_exec_method", "(", "self", ",", "msg", ")", ":", "user_exp", "=", "msg", "[", "'content'", "]", ".", "get", "(", "'user_expressions'", ")", "if", "not", "user_exp", ":", "return", "for", "expression", "in", "user_exp", ":", "if", "expression...
46.6875
15.875
def stop(self): """ Shut the tunnel down. .. note:: This **had** to be handled with care before ``0.1.0``: - if a port redirection is opened - the destination is not reachable - we attempt a connection to that tunnel (``SYN`` is sent and acknow...
[ "def", "stop", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "'Closing all open connections...'", ")", "opened_address_text", "=", "', '", ".", "join", "(", "(", "address_to_str", "(", "k", ".", "local_address", ")", "for", "k", "in", "se...
40.192308
19.807692
def inspect_phone(self, gps_lat_long = [137.0000,100.0000], moving = False, move_dist_2_mn = 4, on_charge = True, screen_saver = False): """ FUNCTION STUB - TODO The intention is to get data from the mobile in the format: gps_lat = 137.000 gps_lng = 100.00...
[ "def", "inspect_phone", "(", "self", ",", "gps_lat_long", "=", "[", "137.0000", ",", "100.0000", "]", ",", "moving", "=", "False", ",", "move_dist_2_mn", "=", "4", ",", "on_charge", "=", "True", ",", "screen_saver", "=", "False", ")", ":", "self", ".", ...
39.44186
11.953488
def write_info_file(resource, path, dataset_name, original_fname): """Write the INFO file next to local file. Although the method is synchronized, there is still a risk two processes running at the same time overlap here. Risk accepted, since potentially lost data (`dataset_name`) is only for human consumption...
[ "def", "write_info_file", "(", "resource", ",", "path", ",", "dataset_name", ",", "original_fname", ")", ":", "info_path", "=", "_get_info_path", "(", "path", ")", "info", "=", "_read_info", "(", "info_path", ")", "or", "{", "}", "urls", "=", "set", "(", ...
43.555556
17.148148
def resumption_token(parent, pagination, **kwargs): """Attach resumption token element to a parent.""" # Do not add resumptionToken if all results fit to the first page. if pagination.page == 1 and not pagination.has_next: return token = serialize(pagination, **kwargs) e_resumptionToken = S...
[ "def", "resumption_token", "(", "parent", ",", "pagination", ",", "*", "*", "kwargs", ")", ":", "# Do not add resumptionToken if all results fit to the first page.", "if", "pagination", ".", "page", "==", "1", "and", "not", "pagination", ".", "has_next", ":", "retur...
38.52
20.6
def change_site(self, new_name, new_location=None, new_er_data=None, new_pmag_data=None, replace_data=False): """ Update a site's name, location, er_data, and pmag_data. By default, new data will be added in to pre-existing data, overwriting existing values. If replac...
[ "def", "change_site", "(", "self", ",", "new_name", ",", "new_location", "=", "None", ",", "new_er_data", "=", "None", ",", "new_pmag_data", "=", "None", ",", "replace_data", "=", "False", ")", ":", "self", ".", "name", "=", "new_name", "if", "new_location...
52
22.363636
def open_in_browser(doc, encoding=None): """ Open the HTML document in a web browser, saving it to a temporary file to open it. Note that this does not delete the file after use. This is mainly meant for debugging. """ import os import webbrowser import tempfile if not isinstance(d...
[ "def", "open_in_browser", "(", "doc", ",", "encoding", "=", "None", ")", ":", "import", "os", "import", "webbrowser", "import", "tempfile", "if", "not", "isinstance", "(", "doc", ",", "etree", ".", "_ElementTree", ")", ":", "doc", "=", "etree", ".", "Ele...
35.047619
17.714286
def AddATR(self, readernode, atr): """Add an ATR to a reader node.""" capchild = self.AppendItem(readernode, atr) self.SetPyData(capchild, None) self.SetItemImage( capchild, self.cardimageindex, wx.TreeItemIcon_Normal) self.SetItemImage( capchild, self.car...
[ "def", "AddATR", "(", "self", ",", "readernode", ",", "atr", ")", ":", "capchild", "=", "self", ".", "AppendItem", "(", "readernode", ",", "atr", ")", "self", ".", "SetPyData", "(", "capchild", ",", "None", ")", "self", ".", "SetItemImage", "(", "capch...
40.3
12.9
def _get_heron_support_processes(self): """ Get a map from all daemon services' name to the command to start them """ retval = {} retval[self.heron_shell_ids[self.shard]] = Command([ '%s' % self.heron_shell_binary, '--port=%s' % self.shell_port, '--log_file_prefix=%s/heron-shell-%s....
[ "def", "_get_heron_support_processes", "(", "self", ")", ":", "retval", "=", "{", "}", "retval", "[", "self", ".", "heron_shell_ids", "[", "self", ".", "shard", "]", "]", "=", "Command", "(", "[", "'%s'", "%", "self", ".", "heron_shell_binary", ",", "'--...
38.363636
18.636364
def get_table_column_names(self, exclude=None): """Get column names and types from a table""" query = 'SELECT * FROM "{schema}"."{table}" limit 0'.format(table=self.table_name, schema=self.schema) columns = get_column_names(self.cc, query).keys() if exclude and isinstance(exclude, list)...
[ "def", "get_table_column_names", "(", "self", ",", "exclude", "=", "None", ")", ":", "query", "=", "'SELECT * FROM \"{schema}\".\"{table}\" limit 0'", ".", "format", "(", "table", "=", "self", ".", "table_name", ",", "schema", "=", "self", ".", "schema", ")", ...
43.666667
24
def orientation(self): """ The member of the ``WD_ORIENTATION`` enumeration corresponding to the value of the ``orient`` attribute of the ``<w:pgSz>`` child element, or ``WD_ORIENTATION.PORTRAIT`` if not present. """ pgSz = self.pgSz if pgSz is None: r...
[ "def", "orientation", "(", "self", ")", ":", "pgSz", "=", "self", ".", "pgSz", "if", "pgSz", "is", "None", ":", "return", "WD_ORIENTATION", ".", "PORTRAIT", "return", "pgSz", ".", "orient" ]
36.7
15.3
def split_text(text: str, length: int = MAX_MESSAGE_LENGTH) -> typing.List[str]: """ Split long text :param text: :param length: :return: list of parts :rtype: :obj:`typing.List[str]` """ return [text[i:i + length] for i in range(0, len(text), length)]
[ "def", "split_text", "(", "text", ":", "str", ",", "length", ":", "int", "=", "MAX_MESSAGE_LENGTH", ")", "->", "typing", ".", "List", "[", "str", "]", ":", "return", "[", "text", "[", "i", ":", "i", "+", "length", "]", "for", "i", "in", "range", ...
27.6
19.4
def keyword_tokenize(text_string): ''' Extracts keywords from text_string using NLTK's list of English stopwords, ignoring words of a length smaller than 3, and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs sh...
[ "def", "keyword_tokenize", "(", "text_string", ")", ":", "if", "text_string", "is", "None", "or", "text_string", "==", "\"\"", ":", "return", "\"\"", "elif", "isinstance", "(", "text_string", ",", "str", ")", ":", "return", "\" \"", ".", "join", "(", "[", ...
34.947368
29.789474
def guess_parameters(next_line): """ Attempt to guess parameters based on the presence of a parenthesized group of identifiers. If successful, returns a list of parameter names; otherwise, returns None. """ match = re.search('\(([\w\s,]+)\)', next_line) if match: return [arg.strip()...
[ "def", "guess_parameters", "(", "next_line", ")", ":", "match", "=", "re", ".", "search", "(", "'\\(([\\w\\s,]+)\\)'", ",", "next_line", ")", "if", "match", ":", "return", "[", "arg", ".", "strip", "(", ")", "for", "arg", "in", "match", ".", "group", "...
34.363636
18.363636
def clear(self): """ Clear the Screen of all content. Note that this will instantly clear the Screen and reset all buffers to the default state, without waiting for you to call :py:meth:`~.Screen.refresh`. """ # Clear the actual terminal self.reset() self...
[ "def", "clear", "(", "self", ")", ":", "# Clear the actual terminal", "self", ".", "reset", "(", ")", "self", ".", "_change_colours", "(", "Screen", ".", "COLOUR_WHITE", ",", "0", ",", "0", ")", "self", ".", "_clear", "(", ")" ]
34.090909
19
def list_skus(access_token, subscription_id, location, publisher, offer): '''List available VM image skus for a publisher offer. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. location (str): Azure data center location. E.g. w...
[ "def", "list_skus", "(", "access_token", ",", "subscription_id", ",", "location", ",", "publisher", ",", "offer", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/p...
44.190476
20.571429
def get_base_equivalent(self, unit_system=None): """Create and return dimensionally-equivalent units in a specified base. >>> from unyt import g, cm >>> (g/cm**3).get_base_equivalent('mks') kg/m**3 >>> (g/cm**3).get_base_equivalent('solar') Mearth/AU**3 """ ...
[ "def", "get_base_equivalent", "(", "self", ",", "unit_system", "=", "None", ")", ":", "from", "unyt", ".", "unit_registry", "import", "_sanitize_unit_system", "unit_system", "=", "_sanitize_unit_system", "(", "unit_system", ",", "self", ")", "try", ":", "conv_data...
39.192308
18.538462
def get_name(value) -> str: """Return a best guess at the qualified name for a class or function. :param value: A class or function object. :type value: class or function :returns str: """ if value.__module__ == '__builtin__': return value.__name__ else: return '.'.join((val...
[ "def", "get_name", "(", "value", ")", "->", "str", ":", "if", "value", ".", "__module__", "==", "'__builtin__'", ":", "return", "value", ".", "__name__", "else", ":", "return", "'.'", ".", "join", "(", "(", "value", ".", "__module__", ",", "value", "."...
31
13.545455
def get_reporting_links_by_link_type(self, project=None, link_types=None, types=None, continuation_token=None, start_date_time=None): """GetReportingLinksByLinkType. [Preview API] Get a batch of work item links :param str project: Project ID or project name :param [str] link_types: A lis...
[ "def", "get_reporting_links_by_link_type", "(", "self", ",", "project", "=", "None", ",", "link_types", "=", "None", ",", "types", "=", "None", ",", "continuation_token", "=", "None", ",", "start_date_time", "=", "None", ")", ":", "route_values", "=", "{", "...
76.533333
41.4