text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def transform(self, X): """ After the fit step, it is known which features are relevant, Only extract those from the time series handed in with the function :func:`~set_timeseries_container`. If filter_only_tsfresh_features is False, also delete the irrelevant, already present features ...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "if", "self", ".", "feature_selector", ".", "relevant_features", "is", "None", ":", "raise", "RuntimeError", "(", "\"You have to call fit before.\"", ")", "if", "self", ".", "timeseries_container", "is", "None...
63.692308
44.076923
def formats(self, value): """ Setter for **self.__formats** attribute. :param value: Attribute value. :type value: FormatsTree """ if value is not None: assert type(value) is FormatsTree, "'{0}' attribute: '{1}' type is not 'FormatsTree'!".format( ...
[ "def", "formats", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "FormatsTree", ",", "\"'{0}' attribute: '{1}' type is not 'FormatsTree'!\"", ".", "format", "(", "\"formats\"", ",", "val...
30.25
17.25
async def executescript(self, sql_script: str) -> None: """Execute a user script.""" await self._execute(self._cursor.executescript, sql_script)
[ "async", "def", "executescript", "(", "self", ",", "sql_script", ":", "str", ")", "->", "None", ":", "await", "self", ".", "_execute", "(", "self", ".", "_cursor", ".", "executescript", ",", "sql_script", ")" ]
52.666667
14
def simxGetObjectParent(clientID, childObjectHandle, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' parentObjectHandle = ct.c_int() return c_GetObjectParent(clientID, childObjectHandle, ct.byref(parentObjectHandle), operationMode), pare...
[ "def", "simxGetObjectParent", "(", "clientID", ",", "childObjectHandle", ",", "operationMode", ")", ":", "parentObjectHandle", "=", "ct", ".", "c_int", "(", ")", "return", "c_GetObjectParent", "(", "clientID", ",", "childObjectHandle", ",", "ct", ".", "byref", "...
47.714286
39.428571
def load_weight(weight_file: str, weight_name: str, weight_file_cache: Dict[str, Dict]) -> mx.nd.NDArray: """ Load wight fron a file or the cache if it was loaded before. :param weight_file: Weight file. :param weight_name: Weight name. :param weight_file_cache: Cach...
[ "def", "load_weight", "(", "weight_file", ":", "str", ",", "weight_name", ":", "str", ",", "weight_file_cache", ":", "Dict", "[", "str", ",", "Dict", "]", ")", "->", "mx", ".", "nd", ".", "NDArray", ":", "logger", ".", "info", "(", "'Loading input weight...
41.318182
14.954545
def _check_for_supported_vendor(self, profile): """Checks if the port belongs to a supported vendor. Returns True for supported_pci_devs. """ vendor_info = profile.get('pci_vendor_info') if not vendor_info: return False if vendor_info not in self.supported_pc...
[ "def", "_check_for_supported_vendor", "(", "self", ",", "profile", ")", ":", "vendor_info", "=", "profile", ".", "get", "(", "'pci_vendor_info'", ")", "if", "not", "vendor_info", ":", "return", "False", "if", "vendor_info", "not", "in", "self", ".", "supported...
32.909091
13
def acquire(self): """ Attempt to acquire the lock every `delay` seconds until the lock is acquired or until `timeout` has expired. Raises FileLockTimeout if the timeout is exceeded. Errors opening the lock file (other than if it exists) are passed through. """ ...
[ "def", "acquire", "(", "self", ")", ":", "self", ".", "lock", "=", "retry_call", "(", "self", ".", "_attempt", ",", "retries", "=", "float", "(", "'inf'", ")", ",", "trap", "=", "zc", ".", "lockfile", ".", "LockError", ",", "cleanup", "=", "functools...
32.9375
19.1875
def send(self, s): """ Send data to the channel. Returns the number of bytes sent, or 0 if the channel stream is closed. Applications are responsible for checking that all data has been sent: if only some of the data was transmitted, the application needs to attempt delivery of...
[ "def", "send", "(", "self", ",", "s", ")", ":", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "cMSG_CHANNEL_DATA", ")", "m", ".", "add_int", "(", "self", ".", "remote_chanid", ")", "return", "self", ".", "_send", "(", "s", ",", "m", "...
35.736842
22.052632
def set_group_add_request(self, *, flag, type, approve=True, reason=None): """ 处理加群请求、群组成员邀请 ------------ :param str flag: 加群请求的 flag(需从上报的数据中获得) :param str type: `add` 或 `invite`,请求类型(需要和上报消息中的 `sub_type` 字段相符) :param bool approve: 是否同意请求/邀请 :param str reason: ...
[ "def", "set_group_add_request", "(", "self", ",", "*", ",", "flag", ",", "type", ",", "approve", "=", "True", ",", "reason", "=", "None", ")", ":", "return", "super", "(", ")", ".", "__getattr__", "(", "'set_group_add_request'", ")", "(", "flag", "=", ...
33.533333
18.733333
def get_users(self, channel=None): """get list of users and channel access information (helper) :param channel: number [1:7] :return: name: (str) uid: (int) channel: (int) access: callback (bool) link_auth (bool) ...
[ "def", "get_users", "(", "self", ",", "channel", "=", "None", ")", ":", "if", "channel", "is", "None", ":", "channel", "=", "self", ".", "get_network_channel", "(", ")", "names", "=", "{", "}", "max_ids", "=", "self", ".", "get_channel_max_user_count", "...
33.92
15.8
def get_version_of_tools(): """ get versions of tools reactor is using (specified in constants.TOOLS_USED) :returns list of dicts, [{"name": "docker-py", "version": "1.2.3"}, ...] """ response = [] for tool in TOOLS_USED: pkg_name = tool["pkg_name"] try: tool_module ...
[ "def", "get_version_of_tools", "(", ")", ":", "response", "=", "[", "]", "for", "tool", "in", "TOOLS_USED", ":", "pkg_name", "=", "tool", "[", "\"pkg_name\"", "]", "try", ":", "tool_module", "=", "import_module", "(", "pkg_name", ")", "except", "ImportError"...
35.791667
18.458333
def read(self, max_length): """ Reads data from the TLS-wrapped socket :param max_length: The number of bytes to read - output may be less than this :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-rel...
[ "def", "read", "(", "self", ",", "max_length", ")", ":", "if", "not", "isinstance", "(", "max_length", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n max_length must be an integer, not %s\n '''", ",", ...
37.341463
19.731707
def getWindowByPID(self, pid, order=0): """ Returns a handle for the first window that matches the provided PID """ if pid <= 0: return None EnumWindowsProc = ctypes.WINFUNCTYPE( ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.py_object) ...
[ "def", "getWindowByPID", "(", "self", ",", "pid", ",", "order", "=", "0", ")", ":", "if", "pid", "<=", "0", ":", "return", "None", "EnumWindowsProc", "=", "ctypes", ".", "WINFUNCTYPE", "(", "ctypes", ".", "c_bool", ",", "ctypes", ".", "POINTER", "(", ...
46
14.619048
def sset_loop(args): ''' Loop over all sample sets in a workspace, performing a func ''' # Ensure that the requested action is a valid fiss_cmd fiss_func = __cmd_to_func(args.action) if not fiss_func: eprint("invalid FISS cmd '" + args.action + "'") return 1 # First get the sample s...
[ "def", "sset_loop", "(", "args", ")", ":", "# Ensure that the requested action is a valid fiss_cmd", "fiss_func", "=", "__cmd_to_func", "(", "args", ".", "action", ")", "if", "not", "fiss_func", ":", "eprint", "(", "\"invalid FISS cmd '\"", "+", "args", ".", "action...
35.933333
20
def clean(self, text, **kwargs): """Create a more clean, but still user-facing version of an instance of the type.""" text = stringify(text) if text is not None: return self.clean_text(text, **kwargs)
[ "def", "clean", "(", "self", ",", "text", ",", "*", "*", "kwargs", ")", ":", "text", "=", "stringify", "(", "text", ")", "if", "text", "is", "not", "None", ":", "return", "self", ".", "clean_text", "(", "text", ",", "*", "*", "kwargs", ")" ]
39.833333
6.666667
def check(self): """check whether all attributes are setted and have the right dtype""" for name, valItem, dtype in self.values: val = valItem.text() if dtype: try: val = dtype(val) except: msgBox = Q...
[ "def", "check", "(", "self", ")", ":", "for", "name", ",", "valItem", ",", "dtype", "in", "self", ".", "values", ":", "val", "=", "valItem", ".", "text", "(", ")", "if", "dtype", ":", "try", ":", "val", "=", "dtype", "(", "val", ")", "except", ...
38.266667
11.666667
def plot(self, xmin=-1, xmax=1, center=0, resolution_outside=20, resolution_inside=200): """ Return arrays x, y for plotting the Heaviside function H(x-`center`) on [`xmin`, `xmax`]. For the exact Heaviside function, ``x = [xmin, center, xmax]; y = [0, 0, 1]``, ...
[ "def", "plot", "(", "self", ",", "xmin", "=", "-", "1", ",", "xmax", "=", "1", ",", "center", "=", "0", ",", "resolution_outside", "=", "20", ",", "resolution_inside", "=", "200", ")", ":", "if", "self", ".", "eps", "==", "0", ":", "return", "[",...
45.545455
17
def unset(self, key): """ Delete object indexed by <key> """ try: try: self.bucket.delete(key) except couchbase.exception.MemcachedError, inst: if str(inst) == "Memcached error #1: Not found": # for some reason the py cb client raises an error when # a ...
[ "def", "unset", "(", "self", ",", "key", ")", ":", "try", ":", "try", ":", "self", ".", "bucket", ".", "delete", "(", "key", ")", "except", "couchbase", ".", "exception", ".", "MemcachedError", ",", "inst", ":", "if", "str", "(", "inst", ")", "==",...
23.736842
21.315789
def drag_drop_cb(self, viewer, urls): """Punt drag-drops to the ginga shell. """ channel = self.fv.get_current_channel() if channel is None: return self.fv.open_uris(urls, chname=channel.name, bulk_add=True) return True
[ "def", "drag_drop_cb", "(", "self", ",", "viewer", ",", "urls", ")", ":", "channel", "=", "self", ".", "fv", ".", "get_current_channel", "(", ")", "if", "channel", "is", "None", ":", "return", "self", ".", "fv", ".", "open_uris", "(", "urls", ",", "c...
34
11.625
def validate(style, value, vectorized=True): """ Validates a style and associated value. Arguments --------- style: str The style to validate (e.g. 'color', 'size' or 'marker') value: The style value to validate vectorized: bool Whether validator should allow vectorized...
[ "def", "validate", "(", "style", ",", "value", ",", "vectorized", "=", "True", ")", ":", "validator", "=", "get_validator", "(", "style", ")", "if", "validator", "is", "None", ":", "return", "None", "if", "isinstance", "(", "value", ",", "(", "np", "."...
26.535714
18.678571
def galcenrect_to_XYZ_jac(*args,**kwargs): """ NAME: galcenrect_to_XYZ_jac PURPOSE: calculate the Jacobian of the Galactocentric rectangular to Galactic coordinates INPUT: X,Y,Z- Galactocentric rectangular coordinates vX, vY, vZ- Galactocentric rectangular velocities ...
[ "def", "galcenrect_to_XYZ_jac", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "Xsun", "=", "kwargs", ".", "get", "(", "'Xsun'", ",", "1.", ")", "dgc", "=", "nu", ".", "sqrt", "(", "Xsun", "**", "2.", "+", "kwargs", ".", "get", "(", "'Zsun'...
21.854167
21.645833
def check_compressed_file_type(filepath): """Check if filename is a compressed file supported by the tool. This function uses magic numbers (first four bytes) to determine the type of the file. Supported types are 'gz' and 'bz2'. When the filetype is not supported, the function returns `None`. :pa...
[ "def", "check_compressed_file_type", "(", "filepath", ")", ":", "def", "compressed_file_type", "(", "content", ")", ":", "magic_dict", "=", "{", "b'\\x1f\\x8b\\x08'", ":", "'gz'", ",", "b'\\x42\\x5a\\x68'", ":", "'bz2'", ",", "b'PK\\x03\\x04'", ":", "'zip'", "}", ...
31.185185
17.37037
def _jobs(): ''' Return the currently configured jobs. ''' response = salt.utils.http.query( "{0}/scheduler/jobs".format(_base_url()), decode_type='json', decode=True, ) jobs = {} for job in response['dict']: jobs[job.pop('name')] = job return jobs
[ "def", "_jobs", "(", ")", ":", "response", "=", "salt", ".", "utils", ".", "http", ".", "query", "(", "\"{0}/scheduler/jobs\"", ".", "format", "(", "_base_url", "(", ")", ")", ",", "decode_type", "=", "'json'", ",", "decode", "=", "True", ",", ")", "...
23.076923
18.461538
def percentage(self, percentage): """ Sets the percentage of this OrderLineItemTax. The percentage of the tax, as a string representation of a decimal number. A value of `7.25` corresponds to a percentage of 7.25%. :param percentage: The percentage of this OrderLineItemTax. :ty...
[ "def", "percentage", "(", "self", ",", "percentage", ")", ":", "if", "percentage", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `percentage`, must not be `None`\"", ")", "if", "len", "(", "percentage", ")", ">", "10", ":", "raise", "ValueE...
40.4
26.933333
def load_config_file(self): """Parse configuration file and get config values.""" config_parser = SafeConfigParser() config_parser.read(self.CONFIG_FILE) if config_parser.has_section('handlers'): self._config['handlers_package'] = config_parser.get('handlers', 'package') ...
[ "def", "load_config_file", "(", "self", ")", ":", "config_parser", "=", "SafeConfigParser", "(", ")", "config_parser", ".", "read", "(", "self", ".", "CONFIG_FILE", ")", "if", "config_parser", ".", "has_section", "(", "'handlers'", ")", ":", "self", ".", "_c...
53.08
31.44
def contains_array(store, path=None): """Return True if the store contains an array at the given logical path.""" path = normalize_storage_path(path) prefix = _path_to_prefix(path) key = prefix + array_meta_key return key in store
[ "def", "contains_array", "(", "store", ",", "path", "=", "None", ")", ":", "path", "=", "normalize_storage_path", "(", "path", ")", "prefix", "=", "_path_to_prefix", "(", "path", ")", "key", "=", "prefix", "+", "array_meta_key", "return", "key", "in", "sto...
40.833333
5.666667
def plot_residual(self, x, y1, y2, label1='Raw data', label2='Fit/theory', xlabel=None, ylabel=None, show_legend=True, **kws): """plot after clearing current plot """ panel = self.get_panel('top') panel.plot(x, y1, label=label1, **kws) panel = self.get_panel('...
[ "def", "plot_residual", "(", "self", ",", "x", ",", "y1", ",", "y2", ",", "label1", "=", "'Raw data'", ",", "label2", "=", "'Fit/theory'", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "show_legend", "=", "True", ",", "*", "*", "kws", ...
42.1875
16.875
def extract_cookiejar(self): """ Extract cookies that pycurl instance knows. Returns `CookieJar` object. """ # Example of line: # www.google.com\tFALSE\t/accounts/\tFALSE\t0' # \tGoogleAccountsLocale_session\ten # Fields: # * domain # * w...
[ "def", "extract_cookiejar", "(", "self", ")", ":", "# Example of line:", "# www.google.com\\tFALSE\\t/accounts/\\tFALSE\\t0'", "# \\tGoogleAccountsLocale_session\\ten", "# Fields:", "# * domain", "# * whether or not all machines under that domain can", "# read the cookie's information.", "...
32.232558
13.627907
def depth_first_iter(self, self_first=True): """ Iterate over nodes below this node, optionally yielding children before self. """ if self_first: yield self for child in list(self.children): for i in child.depth_first_iter(self_first): ...
[ "def", "depth_first_iter", "(", "self", ",", "self_first", "=", "True", ")", ":", "if", "self_first", ":", "yield", "self", "for", "child", "in", "list", "(", "self", ".", "children", ")", ":", "for", "i", "in", "child", ".", "depth_first_iter", "(", "...
30.833333
14.333333
def _alter_umask(self): """Temporarily alter umask to custom setting, if applicable""" if self.umask is None: yield # nothing to do else: prev_umask = os.umask(self.umask) try: yield finally: os.umask(prev_umask)
[ "def", "_alter_umask", "(", "self", ")", ":", "if", "self", ".", "umask", "is", "None", ":", "yield", "# nothing to do", "else", ":", "prev_umask", "=", "os", ".", "umask", "(", "self", ".", "umask", ")", "try", ":", "yield", "finally", ":", "os", "....
30.8
13.2
def _build_verb_statement_mapping(): """Build the mapping between ISI verb strings and INDRA statement classes. Looks up the INDRA statement class name, if any, in a resource file, and resolves this class name to a class. Returns ------- verb_to_statement_type : dict Dictionary mapping...
[ "def", "_build_verb_statement_mapping", "(", ")", ":", "path_this", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "map_path", "=", "os", ".", "path", ".", "join", "(", "path_this", ",", "'isi...
35.875
15.96875
def create_option( self, name, value, label, selected, index, subindex=None, attrs=None): """Patch to use nicer ids.""" index = str(index) if subindex is None else "%s%s%s" % ( index, self.id_separator, subindex) if attrs is None: attrs = {} ...
[ "def", "create_option", "(", "self", ",", "name", ",", "value", ",", "label", ",", "selected", ",", "index", ",", "subindex", "=", "None", ",", "attrs", "=", "None", ")", ":", "index", "=", "str", "(", "index", ")", "if", "subindex", "is", "None", ...
35.909091
12.181818
def get_data(filename, subset, url): """Get a dataset with from a url with local caching. Parameters ---------- filename : str Name of the file, for caching. subset : str To what subset the file belongs (e.g. 'ray_transform'). Each subset is saved in a separate subfolder. ...
[ "def", "get_data", "(", "filename", ",", "subset", ",", "url", ")", ":", "# check if this data set has been already downloaded", "data_dir", "=", "join", "(", "get_data_dir", "(", ")", ",", "subset", ")", "if", "not", "exists", "(", "data_dir", ")", ":", "os",...
29.292683
17.804878
def get_data_xls(file_name, file_contents=None, on_demand=False): ''' Loads the old excel format files. New format files will automatically get loaded as well. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. ...
[ "def", "get_data_xls", "(", "file_name", ",", "file_contents", "=", "None", ",", "on_demand", "=", "False", ")", ":", "def", "tuple_to_iso_date", "(", "tuple_date", ")", ":", "'''\n Turns a gregorian (year, month, day, hour, minute, nearest_second) into a\n stan...
44.439394
26.287879
def discovery(self, discovery_address: Address) -> Discovery: """ Return a proxy to interact with the discovery. """ if not is_binary_address(discovery_address): raise ValueError('discovery_address must be a valid address') with self._discovery_creation_lock: if discover...
[ "def", "discovery", "(", "self", ",", "discovery_address", ":", "Address", ")", "->", "Discovery", ":", "if", "not", "is_binary_address", "(", "discovery_address", ")", ":", "raise", "ValueError", "(", "'discovery_address must be a valid address'", ")", "with", "sel...
47.714286
20.857143
def _add_q(self, q_object): """Add a Q-object to the current filter.""" self._criteria = self._criteria._combine(q_object, q_object.connector)
[ "def", "_add_q", "(", "self", ",", "q_object", ")", ":", "self", ".", "_criteria", "=", "self", ".", "_criteria", ".", "_combine", "(", "q_object", ",", "q_object", ".", "connector", ")" ]
52
17
def var(self): """ Variance value as a result of an uncertainty calculation """ mn = self.mean vr = np.mean((self._mcpts - mn) ** 2) return vr
[ "def", "var", "(", "self", ")", ":", "mn", "=", "self", ".", "mean", "vr", "=", "np", ".", "mean", "(", "(", "self", ".", "_mcpts", "-", "mn", ")", "**", "2", ")", "return", "vr" ]
26.285714
13.714286
def rnn(bptt, vocab_size, num_embed, nhid, num_layers, dropout, num_proj, batch_size): """ word embedding + LSTM Projected """ state_names = [] data = S.var('data') weight = S.var("encoder_weight", stype='row_sparse') embed = S.sparse.Embedding(data=data, weight=weight, input_dim=vocab_size, ...
[ "def", "rnn", "(", "bptt", ",", "vocab_size", ",", "num_embed", ",", "nhid", ",", "num_layers", ",", "dropout", ",", "num_proj", ",", "batch_size", ")", ":", "state_names", "=", "[", "]", "data", "=", "S", ".", "var", "(", "'data'", ")", "weight", "=...
52.807692
22.769231
def _check_kafka_disconnect(self): """Checks the kafka connection is still valid""" for node_id in self.consumer._client._conns: conn = self.consumer._client._conns[node_id] if conn.state == ConnectionStates.DISCONNECTED or \ conn.state == ConnectionStates.DIS...
[ "def", "_check_kafka_disconnect", "(", "self", ")", ":", "for", "node_id", "in", "self", ".", "consumer", ".", "_client", ".", "_conns", ":", "conn", "=", "self", ".", "consumer", ".", "_client", ".", "_conns", "[", "node_id", "]", "if", "conn", ".", "...
50
14.25
def send_voice_message(self, user_id, media_id): """ 发送语音消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID, 就是你收到的 WechatMessage 的 source :param media_id: 发送的语音的媒体ID。 可以通过 :func:`upload_media` 上传。 :return: 返回的 JSON 数据包 ...
[ "def", "send_voice_message", "(", "self", ",", "user_id", ",", "media_id", ")", ":", "return", "self", ".", "request", ".", "post", "(", "url", "=", "'https://api.weixin.qq.com/cgi-bin/message/custom/send'", ",", "data", "=", "{", "'touser'", ":", "user_id", ","...
34.444444
16.666667
def _run(self, tree): """ Run a query from a parse tree """ if tree.throttle: limiter = self._parse_throttle(tree.table, tree.throttle) self._query_rate_limit = limiter del tree["throttle"] return self._run(tree) if tree.action == "SELECT": ...
[ "def", "_run", "(", "self", ",", "tree", ")", ":", "if", "tree", ".", "throttle", ":", "limiter", "=", "self", ".", "_parse_throttle", "(", "tree", ".", "table", ",", "tree", ".", "throttle", ")", "self", ".", "_query_rate_limit", "=", "limiter", "del"...
38.314286
7.714286
def logger(self): """:class:`logging.Logger` of this plotter""" try: return self.data.psy.logger.getChild(self.__class__.__name__) except AttributeError: name = '%s.%s' % (self.__module__, self.__class__.__name__) return logging.getLogger(name)
[ "def", "logger", "(", "self", ")", ":", "try", ":", "return", "self", ".", "data", ".", "psy", ".", "logger", ".", "getChild", "(", "self", ".", "__class__", ".", "__name__", ")", "except", "AttributeError", ":", "name", "=", "'%s.%s'", "%", "(", "se...
42.571429
18.142857
def components(self, visible=True): """ Return the component notes of chord :param bool visible: returns the name of notes if True else list of int :rtype: list[(str or int)] :return: component notes of chord """ if self._on: self._quality.append_on_chord(sel...
[ "def", "components", "(", "self", ",", "visible", "=", "True", ")", ":", "if", "self", ".", "_on", ":", "self", ".", "_quality", ".", "append_on_chord", "(", "self", ".", "on", ",", "self", ".", "root", ")", "return", "self", ".", "_quality", ".", ...
36.818182
19
def AddHeader(self, header, value): '''Add a header to send. ''' self.user_headers.append((header, value)) return self
[ "def", "AddHeader", "(", "self", ",", "header", ",", "value", ")", ":", "self", ".", "user_headers", ".", "append", "(", "(", "header", ",", "value", ")", ")", "return", "self" ]
29.2
14.4
def bytes2NativeString(x, encoding='utf-8'): """ Convert C{bytes} to a native C{str}. On Python 3 and higher, str and bytes are not equivalent. In this case, decode the bytes, and return a native string. On Python 2 and lower, str and bytes are equivalent. In this case, just just ret...
[ "def", "bytes2NativeString", "(", "x", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "x", ",", "bytes", ")", "and", "str", "!=", "bytes", ":", "return", "x", ".", "decode", "(", "encoding", ")", "return", "x" ]
29.473684
10.526316
def barh(*args, **kwargs): """ Creates a bar plot, with white outlines and a fill color that defaults to the first teal-ish green in ColorBrewer's Set2. Optionally accepts grid='y' or grid='x' to draw a white grid over the bars, to show the scale. Almost like "erasing" some of the plot, but ...
[ "def", "barh", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ax", ",", "args", ",", "kwargs", "=", "maybe_get_ax", "(", "*", "args", ",", "*", "*", "kwargs", ")", "kwargs", ".", "setdefault", "(", "'color'", ",", "set2", "[", "0", "]", ...
35.22973
17.932432
def _initialize_cfg(self): """ Re-create the DiGraph """ self.kb.functions = FunctionManager(self.kb) self._jobs_to_analyze_per_function = defaultdict(set) self._completed_functions = set()
[ "def", "_initialize_cfg", "(", "self", ")", ":", "self", ".", "kb", ".", "functions", "=", "FunctionManager", "(", "self", ".", "kb", ")", "self", ".", "_jobs_to_analyze_per_function", "=", "defaultdict", "(", "set", ")", "self", ".", "_completed_functions", ...
25.666667
15.444444
def add_type_struct_or_union(self, name, interp, node): """Store the node with the name. When it is instantiated, the node itself will be handled. :name: name of the typedefd struct/union :node: the union/struct node :interp: the 010 interpreter """ self.add_type...
[ "def", "add_type_struct_or_union", "(", "self", ",", "name", ",", "interp", ",", "node", ")", ":", "self", ".", "add_type_class", "(", "name", ",", "StructUnionDef", "(", "name", ",", "interp", ",", "node", ")", ")" ]
40
11.111111
def _iter_all_paths(start, end, rand=False, path=tuple()): """Iterate through all paths from start to end.""" path = path + (start, ) if start is end: yield path else: nodes = [start.lo, start.hi] if rand: # pragma: no cover random.shuffle(nodes) for node in n...
[ "def", "_iter_all_paths", "(", "start", ",", "end", ",", "rand", "=", "False", ",", "path", "=", "tuple", "(", ")", ")", ":", "path", "=", "path", "+", "(", "start", ",", ")", "if", "start", "is", "end", ":", "yield", "path", "else", ":", "nodes"...
34.416667
13.916667
def waitStarted(self): """wait until name server is started.""" started = False while not started: if self.starter != None: started = self.starter.waitUntilStarted(0.5)
[ "def", "waitStarted", "(", "self", ")", ":", "started", "=", "False", "while", "not", "started", ":", "if", "self", ".", "starter", "!=", "None", ":", "started", "=", "self", ".", "starter", ".", "waitUntilStarted", "(", "0.5", ")" ]
35.833333
12.166667
def bbox2path(xmin, xmax, ymin, ymax): """Converts a bounding box 4-tuple to a Path object.""" b = Line(xmin + 1j*ymin, xmax + 1j*ymin) t = Line(xmin + 1j*ymax, xmax + 1j*ymax) r = Line(xmax + 1j*ymin, xmax + 1j*ymax) l = Line(xmin + 1j*ymin, xmin + 1j*ymax) return Path(b, r, t.reversed(), l.rev...
[ "def", "bbox2path", "(", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", ")", ":", "b", "=", "Line", "(", "xmin", "+", "1j", "*", "ymin", ",", "xmax", "+", "1j", "*", "ymin", ")", "t", "=", "Line", "(", "xmin", "+", "1j", "*", "ymax", ",", "...
46
3.857143
def address_lookup(hypervisor, address_pool): """Retrieves a valid and available network IP address.""" address_pool = set(address_pool) active_addresses = set(active_network_addresses(hypervisor)) try: return random.choice(tuple(address_pool - active_addresses)) except IndexError: ...
[ "def", "address_lookup", "(", "hypervisor", ",", "address_pool", ")", ":", "address_pool", "=", "set", "(", "address_pool", ")", "active_addresses", "=", "set", "(", "active_network_addresses", "(", "hypervisor", ")", ")", "try", ":", "return", "random", ".", ...
40.111111
18.666667
def __add_bgedge(self, bgedge, merge=True): """ Adds supplied :class:`bg.edge.BGEdge` object to current instance of :class:`BreakpointGraph`. Checks that vertices in supplied :class:`bg.edge.BGEdge` instance actually are present in current :class:`BreakpointGraph` if **merge** option of provided. Other...
[ "def", "__add_bgedge", "(", "self", ",", "bgedge", ",", "merge", "=", "True", ")", ":", "if", "bgedge", ".", "vertex1", "in", "self", ".", "bg", "and", "bgedge", ".", "vertex2", "in", "self", ".", "bg", "[", "bgedge", ".", "vertex1", "]", "and", "m...
74.842105
45.052632
def deserialize_by_field(value, field): """ Some types get serialized to JSON, as strings. If we know what they are supposed to be, we can deserialize them """ if isinstance(field, forms.DateTimeField): value = parse_datetime(value) elif isinstance(field, forms.DateField): value ...
[ "def", "deserialize_by_field", "(", "value", ",", "field", ")", ":", "if", "isinstance", "(", "field", ",", "forms", ".", "DateTimeField", ")", ":", "value", "=", "parse_datetime", "(", "value", ")", "elif", "isinstance", "(", "field", ",", "forms", ".", ...
35.333333
7.833333
def _exec_cmd(self, command, **kwargs): """Create a new method as command has specific requirements. There is a handful of the TMSH global commands supported, so this method requires them as a parameter. :raises: InvalidCommand """ kwargs['command'] = command s...
[ "def", "_exec_cmd", "(", "self", ",", "command", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'command'", "]", "=", "command", "self", ".", "_check_exclusive_parameters", "(", "*", "*", "kwargs", ")", "requests_params", "=", "self", ".", "_handle_req...
38.238095
16.952381
def get_image_tags(self): """ Fetches image labels (repository / tags) from Docker. :return: A dictionary, with image name and tags as the key and the image id as value. :rtype: dict """ current_images = self.images() tags = {tag: i['Id'] for i in current_images ...
[ "def", "get_image_tags", "(", "self", ")", ":", "current_images", "=", "self", ".", "images", "(", ")", "tags", "=", "{", "tag", ":", "i", "[", "'Id'", "]", "for", "i", "in", "current_images", "for", "tag", "in", "i", "[", "'RepoTags'", "]", "}", "...
35.6
21
def migration_creatr(migration_file, create, table): """Name of the migration file""" if not check(): click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:migration command') return migration = CreateMigration() if table is None: table = snake_case(migrat...
[ "def", "migration_creatr", "(", "migration_file", ",", "create", ",", "table", ")", ":", "if", "not", "check", "(", ")", ":", "click", ".", "echo", "(", "Fore", ".", "RED", "+", "'ERROR: Ensure you are in a bast app to run the create:migration command'", ")", "ret...
43.181818
24.090909
def _make_repr(class_name, *args, **kwargs): """ Generate a repr string. Positional arguments should be the positional arguments used to construct the class. Keyword arguments should consist of tuples of the attribute value and default. If the value is the default, then it won't be rendered in ...
[ "def", "_make_repr", "(", "class_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "arguments", "=", "[", "repr", "(", "arg", ")", "for", "arg", "in", "args", "]", "arguments", ".", "extend", "(", "\"{}={!r}\"", ".", "format", "(", "name", ...
31.44
20.88
def _split_generators(self, dl_manager): """Returns splits.""" # Download images and annotations that come in separate archives. # Note, that the extension of archives is .tar.gz even though the actual # archives format is uncompressed tar. dl_paths = dl_manager.download_and_extract({ "image...
[ "def", "_split_generators", "(", "self", ",", "dl_manager", ")", ":", "# Download images and annotations that come in separate archives.", "# Note, that the extension of archives is .tar.gz even though the actual", "# archives format is uncompressed tar.", "dl_paths", "=", "dl_manager", ...
38.421053
18.605263
def reqfile(filepath): """Turns a text file into a list (one element per line)""" result = [] import re url_re = re.compile(".+:.+#egg=(.+)") with open(filepath, "r") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continu...
[ "def", "reqfile", "(", "filepath", ")", ":", "result", "=", "[", "]", "import", "re", "url_re", "=", "re", ".", "compile", "(", "\".+:.+#egg=(.+)\"", ")", "with", "open", "(", "filepath", ",", "\"r\"", ")", "as", "f", ":", "for", "line", "in", "f", ...
30.6
12.066667
def response(self, text, response_type='ephemeral', attachments=None): """Return a response with json format :param text: the text returned to the client :param response_type: optional. When `in_channel` is assigned, both the response message and the initial ...
[ "def", "response", "(", "self", ",", "text", ",", "response_type", "=", "'ephemeral'", ",", "attachments", "=", "None", ")", ":", "from", "flask", "import", "jsonify", "if", "attachments", "is", "None", ":", "attachments", "=", "[", "]", "data", "=", "{"...
41.541667
18.291667
def plot_channel_sweep(proxy, start_channel): ''' Parameters ---------- proxy : DMFControlBoard start_channel : int Channel number from which to start a channel sweep (should be a multiple of 40, e.g., 0, 40, 80). Returns ------- pandas.DataFrame See description ...
[ "def", "plot_channel_sweep", "(", "proxy", ",", "start_channel", ")", ":", "test_loads", "=", "TEST_LOADS", ".", "copy", "(", ")", "test_loads", ".", "index", "+=", "start_channel", "results", "=", "sweep_channels", "(", "proxy", ",", "test_loads", ")", "norma...
35.62069
20.103448
def logging_level_verbosity(logging_verbosity): """Converts logging_level into TensorFlow logging verbosity value Args: logging_level: String value representing logging level: 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL' """ name_to_level = { 'FATAL': tf.logging.FATAL, 'ERROR': tf.logging.ERROR, ...
[ "def", "logging_level_verbosity", "(", "logging_verbosity", ")", ":", "name_to_level", "=", "{", "'FATAL'", ":", "tf", ".", "logging", ".", "FATAL", ",", "'ERROR'", ":", "tf", ".", "logging", ".", "ERROR", ",", "'WARN'", ":", "tf", ".", "logging", ".", "...
29.95
19.15
def get_tags(): """get tags.""" tags = getattr(flask.g, 'bukudb', get_bukudb()).get_tag_all() result = { 'tags': tags[0] } if request.path.startswith('/api/'): res = jsonify(result) else: res = render_template('bukuserver/tags.html', result=result) return res
[ "def", "get_tags", "(", ")", ":", "tags", "=", "getattr", "(", "flask", ".", "g", ",", "'bukudb'", ",", "get_bukudb", "(", ")", ")", ".", "get_tag_all", "(", ")", "result", "=", "{", "'tags'", ":", "tags", "[", "0", "]", "}", "if", "request", "."...
27.363636
20.363636
def for_model(self, fn): """Apply the given function to a single model replica. Returns: Result from applying the function. """ return ray.get(self.workers[0].for_model.remote(fn))
[ "def", "for_model", "(", "self", ",", "fn", ")", ":", "return", "ray", ".", "get", "(", "self", ".", "workers", "[", "0", "]", ".", "for_model", ".", "remote", "(", "fn", ")", ")" ]
31.285714
15.142857
def put(self, data, **kwargs): """Put data in GridFS as a new file. Equivalent to doing:: try: f = new_file(**kwargs) f.write(data) finally: f.close() `data` can be either an instance of :class:`str` (:class:`bytes` in pyth...
[ "def", "put", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "grid_file", "=", "GridIn", "(", "self", ".", "__collection", ",", "*", "*", "kwargs", ")", "try", ":", "grid_file", ".", "write", "(", "data", ")", "finally", ":", "grid_fi...
35
21.763158
def awd_lstm_lm_1150(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""3-layer LSTM language model with weight-drop, variational dropout, and tied weights. Embedding size is 400, and hidden layer size is 1150. Param...
[ "def", "awd_lstm_lm_1150", "(", "dataset_name", "=", "None", ",", "vocab", "=", "None", ",", "pretrained", "=", "False", ",", "ctx", "=", "cpu", "(", ")", ",", "root", "=", "os", ".", "path", ".", "join", "(", "get_home_dir", "(", ")", ",", "'models'...
46.043478
18.456522
def clone(self): """ Create a complete copy of self. :returns: A MaterialPackage that is identical to self. """ result = copy.copy(self) result.size_class_masses = copy.deepcopy(self.size_class_masses) return result
[ "def", "clone", "(", "self", ")", ":", "result", "=", "copy", ".", "copy", "(", "self", ")", "result", ".", "size_class_masses", "=", "copy", ".", "deepcopy", "(", "self", ".", "size_class_masses", ")", "return", "result" ]
26.4
18.6
def abs_horz_pos(self, amount): '''Calling this function sets the absoulte print position for the next data, this is the position from the left margin. Args: amount: desired positioning. Can be a number from 0 to 2362. The actual positioning is calculated as (amo...
[ "def", "abs_horz_pos", "(", "self", ",", "amount", ")", ":", "n1", "=", "amount", "%", "256", "n2", "=", "amount", "/", "256", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "'${n1}{n2}'", ".", "format", "(", "n1", "=", "chr", "(", "n1", ...
35.866667
26.266667
def kill_conditional_comments(self, doc): """ IE conditional comments basically embed HTML that the parser doesn't normally see. We can't allow anything like that, so we'll kill any comments that could be conditional. """ bad = [] self._kill_elements( ...
[ "def", "kill_conditional_comments", "(", "self", ",", "doc", ")", ":", "bad", "=", "[", "]", "self", ".", "_kill_elements", "(", "doc", ",", "lambda", "el", ":", "_conditional_comment_re", ".", "search", "(", "el", ".", "text", ")", ",", "etree", ".", ...
39.5
15.3
def plot_cells(cell_1, cell_2, cell_3): """Plots three cells""" fig, ((ax1, ax2, ax3)) = plt.subplots(1, 3, figsize=(12, 5)) for ax in [ax1, ax2, ax3]: ax.grid(False) ax.set_xticks([]) ax.set_yticks([]) ax1.set_title("Type 1") ax1.imshow(cell_1) ax2.set_title("Type 2") ...
[ "def", "plot_cells", "(", "cell_1", ",", "cell_2", ",", "cell_3", ")", ":", "fig", ",", "(", "(", "ax1", ",", "ax2", ",", "ax3", ")", ")", "=", "plt", ".", "subplots", "(", "1", ",", "3", ",", "figsize", "=", "(", "12", ",", "5", ")", ")", ...
28.785714
13.714286
def _format_years(years): """Format a list of ints into a string including ranges Source: https://stackoverflow.com/a/9471386/1307974 """ def sub(x): return x[1] - x[0] ranges = [] for k, iterable in groupby(enumerate(sorted(years)), sub): rng = list(iterable) if len(rn...
[ "def", "_format_years", "(", "years", ")", ":", "def", "sub", "(", "x", ")", ":", "return", "x", "[", "1", "]", "-", "x", "[", "0", "]", "ranges", "=", "[", "]", "for", "k", ",", "iterable", "in", "groupby", "(", "enumerate", "(", "sorted", "("...
27.352941
17.705882
def __load_unique_identities(self, uidentities, matcher, match_new, reset, verbose): """Load unique identities""" self.new_uids.clear() n = 0 if reset: self.__reset_unique_identities() self.log("Loading unique identities...") ...
[ "def", "__load_unique_identities", "(", "self", ",", "uidentities", ",", "matcher", ",", "match_new", ",", "reset", ",", "verbose", ")", ":", "self", ".", "new_uids", ".", "clear", "(", ")", "n", "=", "0", "if", "reset", ":", "self", ".", "__reset_unique...
35.608696
24.173913
def get_sngl_bank_chisqs(self, instruments=None): """ Get the single-detector \chi^2 for each row in the table. """ if len(self) and instruments is None: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) elif instruments is None: instruments = [] return dict((ifo, sel...
[ "def", "get_sngl_bank_chisqs", "(", "self", ",", "instruments", "=", "None", ")", ":", "if", "len", "(", "self", ")", "and", "instruments", "is", "None", ":", "instruments", "=", "map", "(", "str", ",", "instrument_set_from_ifos", "(", "self", "[", "0", ...
34.181818
9.818182
def annualization_factor(period, annualization): """ Return annualization factor from period entered or if a custom value is passed in. Parameters ---------- period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annua...
[ "def", "annualization_factor", "(", "period", ",", "annualization", ")", ":", "if", "annualization", "is", "None", ":", "try", ":", "factor", "=", "ANNUALIZATION_FACTORS", "[", "period", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"Period canno...
28.315789
20.894737
def instance_path(cls, project, instance): """Return a fully-qualified instance string.""" return google.api_core.path_template.expand( "projects/{project}/instances/{instance}", project=project, instance=instance, )
[ "def", "instance_path", "(", "cls", ",", "project", ",", "instance", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/instances/{instance}\"", ",", "project", "=", "project", ",", "instance", "=", "in...
38.571429
11.571429
def queue(self): """An ordered list of upcoming events. Events are named tuples with fields for: time, priority, action, arguments """ # Use heapq to sort the queue rather than using 'sorted(self._queue)'. # With heapq, two events scheduled at the same time will show ...
[ "def", "queue", "(", "self", ")", ":", "# Use heapq to sort the queue rather than using 'sorted(self._queue)'.", "# With heapq, two events scheduled at the same time will show in", "# the actual order they would be retrieved.", "events", "=", "self", ".", "_queue", "[", ":", "]", "...
45.3
14.2
def make_transaction(self): """Create the transaction for this RecurredCost May only be used to create the RecurredCost's initial transaction. Returns: Transaction: The created transaction, also assigned to self.transaction. None if the amount is zero. """ if self.p...
[ "def", "make_transaction", "(", "self", ")", ":", "if", "self", ".", "pk", ":", "raise", "CannotRecreateTransactionOnRecurredCost", "(", "'The transaction for this recurred cost has already been created. You cannot create it again.'", ")", "amount", "=", "self", ".", "recurri...
40.061224
24.22449
def write(self, data): """Write data. Args: data: actual data yielded from handler. Type is writer-specific. """ ctx = context.get() if len(data) != 2: logging.error("Got bad tuple of length %d (2-tuple expected): %s", len(data), data) try: key = str(data[...
[ "def", "write", "(", "self", ",", "data", ")", ":", "ctx", "=", "context", ".", "get", "(", ")", "if", "len", "(", "data", ")", "!=", "2", ":", "logging", ".", "error", "(", "\"Got bad tuple of length %d (2-tuple expected): %s\"", ",", "len", "(", "data"...
31.852941
21.117647
def is_random_accessible(self): """ Check if self._is_random_accessible is set to true and if all the random access strategies are implemented. Returns ------- bool : Returns True if random accessible via strategies and False otherwise. """ return self._is_random_...
[ "def", "is_random_accessible", "(", "self", ")", ":", "return", "self", ".", "_is_random_accessible", "and", "not", "isinstance", "(", "self", ".", "ra_itraj_cuboid", ",", "NotImplementedRandomAccessStrategy", ")", "and", "not", "isinstance", "(", "self", ".", "ra...
57.416667
32.083333
def list_all_refund_operations(cls, **kwargs): """List RefundOperations Return a list of RefundOperations This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_refund_operations(async=True)...
[ "def", "list_all_refund_operations", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_list_all_refund_operations_with_http_in...
38.782609
15.347826
def seed(cache_dir=CACHE_DIR, product=DEFAULT_PRODUCT, bounds=None, max_download_tiles=9, **kwargs): """Seed the DEM to given bounds. :param cache_dir: Root of the DEM cache folder. :param product: DEM product choice. :param bounds: Output bounds in 'left bottom right top' order. :param max_downloa...
[ "def", "seed", "(", "cache_dir", "=", "CACHE_DIR", ",", "product", "=", "DEFAULT_PRODUCT", ",", "bounds", "=", "None", ",", "max_download_tiles", "=", "9", ",", "*", "*", "kwargs", ")", ":", "datasource_root", ",", "spec", "=", "ensure_setup", "(", "cache_...
50
23.954545
def image(self, name, x=None, y=None, w=0,h=0,type='',link=''): "Put an image on the page" if not name in self.images: #First use of image, get info if(type==''): pos=name.rfind('.') if(not pos): self.error('image file has no ex...
[ "def", "image", "(", "self", ",", "name", ",", "x", "=", "None", ",", "y", "=", "None", ",", "w", "=", "0", ",", "h", "=", "0", ",", "type", "=", "''", ",", "link", "=", "''", ")", ":", "if", "not", "name", "in", "self", ".", "images", ":...
39.430769
13.738462
def export(self, swf, force_stroke=False): """ Exports the specified SWF to SVG. @param swf The SWF. @param force_stroke Whether to force strokes on non-stroked fills. """ self.svg = self._e.svg(version=SVG_VERSION) self.force_stroke = force_stroke self.defs = s...
[ "def", "export", "(", "self", ",", "swf", ",", "force_stroke", "=", "False", ")", ":", "self", ".", "svg", "=", "self", ".", "_e", ".", "svg", "(", "version", "=", "SVG_VERSION", ")", "self", ".", "force_stroke", "=", "force_stroke", "self", ".", "de...
39.818182
16.545455
def generate_set_partitions(set_): """Generate all of the partitions of a set. This is a helper function that utilizes the restricted growth strings from :py:func:`generate_set_partition_strings`. The partitions are returned in lexicographic order. Parameters ---------- set_ : :py:...
[ "def", "generate_set_partitions", "(", "set_", ")", ":", "set_", "=", "scipy", ".", "asarray", "(", "set_", ")", "strings", "=", "generate_set_partition_strings", "(", "len", "(", "set_", ")", ")", "partitions", "=", "[", "]", "for", "string", "in", "strin...
36.419355
21.258065
def endpoint_get(auth=None, **kwargs): ''' Get a single endpoint CLI Example: .. code-block:: bash salt '*' keystoneng.endpoint_get id=02cffaa173b2460f98e40eda3748dae5 ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.get_endpoint(**kwargs)
[ "def", "endpoint_get", "(", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cloud", "=", "get_operator_cloud", "(", "auth", ")", "kwargs", "=", "_clean_kwargs", "(", "*", "*", "kwargs", ")", "return", "cloud", ".", "get_endpoint", "(", "*", "*...
23.384615
22.153846
def p_expr_id_substr(p): """ string : ID substr """ entry = SYMBOL_TABLE.access_var(p[1], p.lineno(1), default_type=TYPE.string) p[0] = None if entry is None: return entry.accessed = True p[0] = make_strslice(p.lineno(1), entry, p[2][0], p[2][1])
[ "def", "p_expr_id_substr", "(", "p", ")", ":", "entry", "=", "SYMBOL_TABLE", ".", "access_var", "(", "p", "[", "1", "]", ",", "p", ".", "lineno", "(", "1", ")", ",", "default_type", "=", "TYPE", ".", "string", ")", "p", "[", "0", "]", "=", "None"...
27.4
20.3
def get_plain_text_content(primary_text=None, secondary_text=None, tertiary_text=None): # type: (str, str, str) -> TextContent """Responsible for building plain text content object using ask-sdk-model in Alexa skills kit display interface. https://developer.amazon.com/docs/custom-skills/display-interfac...
[ "def", "get_plain_text_content", "(", "primary_text", "=", "None", ",", "secondary_text", "=", "None", ",", "tertiary_text", "=", "None", ")", ":", "# type: (str, str, str) -> TextContent", "return", "get_text_content", "(", "primary_text", "=", "primary_text", ",", "...
50.142857
19.190476
def _key(key=''): ''' Returns a Datastore key object, prefixed with the NAMESPACE. ''' if not isinstance(key, datastore.Key): # Switchboard uses ':' to denote one thing (parent-child) and datastore # uses it for another, so replace ':' in the datastore version of the # key. ...
[ "def", "_key", "(", "key", "=", "''", ")", ":", "if", "not", "isinstance", "(", "key", ",", "datastore", ".", "Key", ")", ":", "# Switchboard uses ':' to denote one thing (parent-child) and datastore", "# uses it for another, so replace ':' in the datastore version of the", ...
38.454545
24.090909
def const(const): '''Convenience wrapper to yield the value of a constant''' try: return getattr(_c, const) except AttributeError: raise FSQEnvError(errno.EINVAL, u'No such constant:'\ u' {0}'.format(const)) except TypeError: raise TypeError(errno.E...
[ "def", "const", "(", "const", ")", ":", "try", ":", "return", "getattr", "(", "_c", ",", "const", ")", "except", "AttributeError", ":", "raise", "FSQEnvError", "(", "errno", ".", "EINVAL", ",", "u'No such constant:'", "u' {0}'", ".", "format", "(", "const"...
42.454545
19.727273
def network_lpf_contingency(network, snapshots=None, branch_outages=None): """ Computes linear power flow for a selection of branch outages. Parameters ---------- snapshots : list-like|single snapshot A subset or an elements of network.snapshots on which to run the power flow, defau...
[ "def", "network_lpf_contingency", "(", "network", ",", "snapshots", "=", "None", ",", "branch_outages", "=", "None", ")", ":", "if", "snapshots", "is", "None", ":", "snapshots", "=", "network", ".", "snapshots", "if", "isinstance", "(", "snapshots", ",", "co...
29.264706
24.647059
def pattern_to_regex(cls, *args, **kw): """ Warn about deprecation. """ cls._deprecated() return super(GitIgnorePattern, cls).pattern_to_regex(*args, **kw)
[ "def", "pattern_to_regex", "(", "cls", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "cls", ".", "_deprecated", "(", ")", "return", "super", "(", "GitIgnorePattern", ",", "cls", ")", ".", "pattern_to_regex", "(", "*", "args", ",", "*", "*", "kw", ...
26.666667
10.666667
def evaluate_at(self, vals): """Evaluate the derivative at a specific point""" new_vals = self._vals.copy() new_vals.update(vals) return self.__class__(self.operand, derivs=self._derivs, vals=new_vals)
[ "def", "evaluate_at", "(", "self", ",", "vals", ")", ":", "new_vals", "=", "self", ".", "_vals", ".", "copy", "(", ")", "new_vals", ".", "update", "(", "vals", ")", "return", "self", ".", "__class__", "(", "self", ".", "operand", ",", "derivs", "=", ...
45.8
13.2
def _finalize_ticks(self, axis, element, xticks, yticks, zticks): """ Apply ticks with appropriate offsets. """ yalignments = None if xticks is not None: ticks, labels, yalignments = zip(*sorted(xticks, key=lambda x: x[0])) xticks = (list(ticks), list(labe...
[ "def", "_finalize_ticks", "(", "self", ",", "axis", ",", "element", ",", "xticks", ",", "yticks", ",", "zticks", ")", ":", "yalignments", "=", "None", "if", "xticks", "is", "not", "None", ":", "ticks", ",", "labels", ",", "yalignments", "=", "zip", "("...
42.833333
16.833333
def add(self, tool): """ Adds a Tool to the list, logs the reference and TODO """ self.lstTools.append(tool) self.lg.record_process(self._get_tool_str(tool))
[ "def", "add", "(", "self", ",", "tool", ")", ":", "self", ".", "lstTools", ".", "append", "(", "tool", ")", "self", ".", "lg", ".", "record_process", "(", "self", ".", "_get_tool_str", "(", "tool", ")", ")" ]
32
10.333333
def drop(self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise'): """ Drop specified labels from rows or columns. Remove rows or columns by specifying label names and corresponding axis, or by specifying directly index or column names...
[ "def", "drop", "(", "self", ",", "labels", "=", "None", ",", "axis", "=", "0", ",", "index", "=", "None", ",", "columns", "=", "None", ",", "level", "=", "None", ",", "inplace", "=", "False", ",", "errors", "=", "'raise'", ")", ":", "return", "su...
34.566929
19.748031
def section_end_info(template, tag_key, state, index): """ Given the tag key of an opening section tag, find the corresponding closing tag (if it exists) and return information about that match. """ state.section.push(tag_key) match = None matchinfo = None search_index = index whil...
[ "def", "section_end_info", "(", "template", ",", "tag_key", ",", "state", ",", "index", ")", ":", "state", ".", "section", ".", "push", "(", "tag_key", ")", "match", "=", "None", "matchinfo", "=", "None", "search_index", "=", "index", "while", "state", "...
35.848485
20.454545
def _write_jsonl(filepath, data, kwargs): """See documentation of mpu.io.write.""" with io_stl.open(filepath, 'w', encoding='utf8') as outfile: kwargs['indent'] = None # JSON has to be on one line! if 'sort_keys' not in kwargs: kwargs['sort_keys'] = True if 'separators' not ...
[ "def", "_write_jsonl", "(", "filepath", ",", "data", ",", "kwargs", ")", ":", "with", "io_stl", ".", "open", "(", "filepath", ",", "'w'", ",", "encoding", "=", "'utf8'", ")", "as", "outfile", ":", "kwargs", "[", "'indent'", "]", "=", "None", "# JSON ha...
40.8
7.866667
def regenerate_storage_keys(kwargs=None, conn=None, call=None): ''' .. versionadded:: 2015.8.0 Regenerate storage account keys. Requires a key_type ("primary" or "secondary") to be specified. CLI Example: .. code-block:: bash salt-cloud -f regenerate_storage_keys my-azure name=my_sto...
[ "def", "regenerate_storage_keys", "(", "kwargs", "=", "None", ",", "conn", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The show_storage function must be called with -f or --function.'",...
32.236842
28.710526
def _sitesettings_files(): """ Get a list of sitesettings files settings.py can be prefixed with a subdomain and underscore so with example.com site: sitesettings/settings.py would be the example.com settings file and sitesettings/admin_settings.py would be the admin.example.com settings file ...
[ "def", "_sitesettings_files", "(", ")", ":", "settings_files", "=", "[", "]", "sitesettings_path", "=", "os", ".", "path", ".", "join", "(", "env", ".", "project_package_name", ",", "'sitesettings'", ")", "if", "os", ".", "path", ".", "exists", "(", "sites...
42.944444
17.277778