text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def hist(hist_function, *, options={}, **interact_params): """ Generates an interactive histogram that allows users to change the parameters of the input hist_function. Args: hist_function (Array | (*args -> Array int | Array float)): Function that takes in parameters to interact wi...
[ "def", "hist", "(", "hist_function", ",", "*", ",", "options", "=", "{", "}", ",", "*", "*", "interact_params", ")", ":", "params", "=", "{", "'marks'", ":", "[", "{", "'sample'", ":", "_array_or_placeholder", "(", "hist_function", ")", ",", "'bins'", ...
32.916667
0.000615
def rpc_method(func, doc=None, format='json', request_handler=None): '''A decorator which exposes a function ``func`` as an rpc function. :param func: The function to expose. :param doc: Optional doc string. If not provided the doc string of ``func`` will be used. :param format: Optional output...
[ "def", "rpc_method", "(", "func", ",", "doc", "=", "None", ",", "format", "=", "'json'", ",", "request_handler", "=", "None", ")", ":", "def", "_", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "request", "=", "args", "[", "0"...
36.413793
0.000923
def pcolormesh(x, y, z, ax, infer_intervals=None, **kwargs): """ Pseudocolor plot of 2d DataArray Wraps :func:`matplotlib:matplotlib.pyplot.pcolormesh` """ # decide on a default for infer_intervals (GH781) x = np.asarray(x) if infer_intervals is None: if hasattr(ax, 'projection'): ...
[ "def", "pcolormesh", "(", "x", ",", "y", ",", "z", ",", "ax", ",", "infer_intervals", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# decide on a default for infer_intervals (GH781)", "x", "=", "np", ".", "asarray", "(", "x", ")", "if", "infer_intervals...
33.87234
0.000611
def make_dynamic_fields(pattern_module, dynamic_field_patterns, attrs): """Add some Salesforce fields from a pattern_module models.py Parameters: pattern_module: Module where to search additional fields settings. It is an imported module created by introspection (inspectdb), usua...
[ "def", "make_dynamic_fields", "(", "pattern_module", ",", "dynamic_field_patterns", ",", "attrs", ")", ":", "# pylint:disable=invalid-name,too-many-branches,too-many-locals", "import", "re", "attr_meta", "=", "attrs", "[", "'Meta'", "]", "db_table", "=", "getattr", "(", ...
45.010309
0.002017
def get_option_choices(opt_name, opt_value, default_value, all_choices): """ Generate possible choices for the option `opt_name` limited to `opt_value` value with default value as `default_value` """ choices = [] if isinstance(opt_value, six.string_types): choices = [opt_value] ...
[ "def", "get_option_choices", "(", "opt_name", ",", "opt_value", ",", "default_value", ",", "all_choices", ")", ":", "choices", "=", "[", "]", "if", "isinstance", "(", "opt_value", ",", "six", ".", "string_types", ")", ":", "choices", "=", "[", "opt_value", ...
34.666667
0.00117
def flatten(x): """flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,None)], [4,5], ...
[ "def", "flatten", "(", "x", ")", ":", "for", "el", "in", "x", ":", "if", "hasattr", "(", "el", ",", "\"__iter__\"", ")", "and", "not", "isinstance", "(", "el", ",", "(", "binary", ",", "unicode", ")", ")", ":", "for", "els", "in", "flatten", "(",...
28.7
0.001686
def event_source_mapping_absent(name, EventSourceArn, FunctionName, region=None, key=None, keyid=None, profile=None): ''' Ensure event source mapping with passed properties is absent. name The name of the state definition. EventSourceArn ARN of the event...
[ "def", "event_source_mapping_absent", "(", "name", ",", "EventSourceArn", ",", "FunctionName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "None", ...
30.859375
0.001472
def load_adjusted_array(self, domain, columns, dates, sids, mask): """ Load data from our stored baseline. """ if len(columns) != 1: raise ValueError( "Can't load multiple columns with DataFrameLoader" ) column = columns[0] self._v...
[ "def", "load_adjusted_array", "(", "self", ",", "domain", ",", "columns", ",", "dates", ",", "sids", ",", "mask", ")", ":", "if", "len", "(", "columns", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Can't load multiple columns with DataFrameLoader\"", ")...
33.151515
0.001776
def create_js_edit_address_param(self, accesstoken, **params): """ alpha 暂时不建议使用 这个接口使用起来十分不友好 而且会引起巨大的误解 url 需要带上 code 和 state (url?code=xxx&state=1) code 和state 是 oauth 时候回来的 token 要传用户的 token 这尼玛 你能相信这些支付接口都是腾讯出的? """ params.u...
[ "def", "create_js_edit_address_param", "(", "self", ",", "accesstoken", ",", "*", "*", "params", ")", ":", "params", ".", "update", "(", "{", "'appId'", ":", "self", ".", "appid", ",", "'nonceStr'", ":", "generate_token", "(", "8", ")", ",", "'timeStamp'",...
25.944444
0.002064
def create_collection(cls, target=None, drop=False, indexes=True): """Ensure the collection identified by this document class exists, creating it if not, also creating indexes. **Warning:** enabling the `recreate` option **will drop the collection, erasing all data within**. http://api.mongodb.com/python/cu...
[ "def", "create_collection", "(", "cls", ",", "target", "=", "None", ",", "drop", "=", "False", ",", "indexes", "=", "True", ")", ":", "if", "target", "is", "None", ":", "if", "cls", ".", "__bound__", "is", "None", ":", "raise", "TypeError", "(", "\"T...
33.548387
0.042056
def _parse_query_dict(query_data, model): """ Take a list of query field dict and return data for form initialization """ operator = 'iexact' if query_data['field'] == '_OR': query_data['operator'] = operator return query_data parts = query_data['...
[ "def", "_parse_query_dict", "(", "query_data", ",", "model", ")", ":", "operator", "=", "'iexact'", "if", "query_data", "[", "'field'", "]", "==", "'_OR'", ":", "query_data", "[", "'operator'", "]", "=", "operator", "return", "query_data", "parts", "=", "que...
37.957447
0.001093
def endpoint_create_and_update_params(*args, **kwargs): """ Collection of options consumed by Transfer endpoint create and update operations -- accepts toggle regarding create vs. update that makes display_name required vs. optional. Usage: >>> @endpoint_create_and_update_params(create=True) ...
[ "def", "endpoint_create_and_update_params", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "inner_decorator", "(", "f", ",", "create", "=", "False", ")", ":", "update_help_prefix", "=", "(", "not", "create", "and", "\"New \"", ")", "or", "\"\"...
34.193069
0.000844
def retry_func_accept_retry_state(retry_func): """Wrap "retry" function to accept "retry_state" parameter.""" if not six.callable(retry_func): return retry_func if func_takes_retry_state(retry_func): return retry_func @_utils.wraps(retry_func) def wrapped_retry_func(retry_state): ...
[ "def", "retry_func_accept_retry_state", "(", "retry_func", ")", ":", "if", "not", "six", ".", "callable", "(", "retry_func", ")", ":", "return", "retry_func", "if", "func_takes_retry_state", "(", "retry_func", ")", ":", "return", "retry_func", "@", "_utils", "."...
34.071429
0.002041
def setup_logging(level, console_stream=None, log_dir=None, scope=None, log_name=None, native=None): """Configures logging for a given scope, by default the global scope. :param str level: The logging level to enable, must be one of the level names listed here: https://docs.python.org/2/library...
[ "def", "setup_logging", "(", "level", ",", "console_stream", "=", "None", ",", "log_dir", "=", "None", ",", "scope", "=", "None", ",", "log_name", "=", "None", ",", "native", "=", "None", ")", ":", "# TODO(John Sirois): Consider moving to straight python logging. ...
42.650794
0.014551
def add_subscription(self, channel, callback_function): """ Add a channel to subscribe to and a callback function to run when the channel receives an update. If channel already exists, create a new "subscription" and append another callback function. Args: ch...
[ "def", "add_subscription", "(", "self", ",", "channel", ",", "callback_function", ")", ":", "if", "channel", "not", "in", "CHANNELS", ":", "CHANNELS", ".", "append", "(", "channel", ")", "SUBSCRIPTIONS", "[", "channel", "]", "=", "[", "callback_function", "]...
44.636364
0.001994
def get_kwargs(func): """ Args: func (function): Returns: tuple: keys, is_arbitrary keys (list): kwargs keys is_arbitrary (bool): has generic **kwargs CommandLine: python -m utool.util_inspect --test-get_kwargs Ignore: def func1(a, b, c): ...
[ "def", "get_kwargs", "(", "func", ")", ":", "#if argspec.keywords is None:", "import", "utool", "as", "ut", "argspec", "=", "inspect", ".", "getargspec", "(", "func", ")", "if", "argspec", ".", "defaults", "is", "not", "None", ":", "num_args", "=", "len", ...
28.071429
0.001844
def SetPassword(self,password): """Request change of password. The API request requires supplying the current password. For this we issue a call to retrieve the credentials so note there will be an activity log for retrieving the credentials associated with any SetPassword entry >>> s.SetPassword("newpassw...
[ "def", "SetPassword", "(", "self", ",", "password", ")", ":", "# 0: {op: \"set\", member: \"password\", value: {current: \" r`5Mun/vT:qZ]2?z\", password: \"Savvis123!\"}}", "if", "self", ".", "data", "[", "'status'", "]", "!=", "\"active\"", ":", "raise", "(", "clc", ".",...
46.526316
0.036585
def __shapefileHeader(self, fileObj, headerType='shp'): """Writes the specified header type to the specified file-like object. Several of the shapefile formats are so similar that a single generic method to read or write them is warranted.""" f = self.__getFileObj(fileObj) f...
[ "def", "__shapefileHeader", "(", "self", ",", "fileObj", ",", "headerType", "=", "'shp'", ")", ":", "f", "=", "self", ".", "__getFileObj", "(", "fileObj", ")", "f", ".", "seek", "(", "0", ")", "# File code, Unused bytes\r", "f", ".", "write", "(", "pack"...
49.509804
0.013592
def verify_config_container(object_): """Verify object is a valid config container Valid config containers provide zope.interface.common.mapping.IEnumerableMapping or an iterable of zope.interface.common.mapping.IEnumerableMapping. verification is performed by checking required interfaces attr...
[ "def", "verify_config_container", "(", "object_", ")", ":", "try", ":", "#check for a map", "_verify_map", "(", "object_", ")", "except", "BrokenImplementation", "as", "e", ":", "#check for a iterable of maps", "try", ":", "for", "m", "in", "object_", ":", "_verif...
35.590909
0.00995
def resample_dataset(dataset, destination_area, **kwargs): """Resample *dataset* and return the resampled version. Args: dataset (xarray.DataArray): Data to be resampled. destination_area: The destination onto which to project the data, either a full blown area definition or a string ...
[ "def", "resample_dataset", "(", "dataset", ",", "destination_area", ",", "*", "*", "kwargs", ")", ":", "# call the projection stuff here", "try", ":", "source_area", "=", "dataset", ".", "attrs", "[", "\"area\"", "]", "except", "KeyError", ":", "LOG", ".", "in...
36.3125
0.001676
def _makepass(password, hasher='sha256'): ''' Create a znc compatible hashed password ''' # Setup the hasher if hasher == 'sha256': h = hashlib.sha256(password) elif hasher == 'md5': h = hashlib.md5(password) else: return NotImplemented c = "abcdefghijklmnopqrstu...
[ "def", "_makepass", "(", "password", ",", "hasher", "=", "'sha256'", ")", ":", "# Setup the hasher", "if", "hasher", "==", "'sha256'", ":", "h", "=", "hashlib", ".", "sha256", "(", "password", ")", "elif", "hasher", "==", "'md5'", ":", "h", "=", "hashlib...
23.76
0.001618
def report(scopus_search, label): """Print out an org-mode report for search results. Parameters ---------- scopus_search : scopus.scopus_search.ScopusSearch An object resulting from a ScopusSearch. label : str The label used in the document title ("Report for ..."). """ te...
[ "def", "report", "(", "scopus_search", ",", "label", ")", ":", "text", "=", "\"Development of this class has been suspended; Please use the new\"", "\"package 'scopusreport' (https://scopusreport.readthedocs.io/en/latest/)\"", "\"instead.\"", "warnings", ".", "warn", "(", "text", ...
33.687861
0.001
def send_audio(self, audio: str, reply: Message=None, on_success: callable=None, reply_markup: botapi.ReplyMarkup=None): """ Send audio clip to this peer. :param audio: File path to audio to send. :param reply: Message object or message_id to reply to. :param o...
[ "def", "send_audio", "(", "self", ",", "audio", ":", "str", ",", "reply", ":", "Message", "=", "None", ",", "on_success", ":", "callable", "=", "None", ",", "reply_markup", ":", "botapi", ".", "ReplyMarkup", "=", "None", ")", ":", "self", ".", "twx", ...
43.461538
0.019064
def datatype(self, value): """ Args: value (string): 'uint8', 'uint16', 'uint64' Raises: ValueError """ self._datatype = self.validate_datatype(value) self._cutout_ready = True
[ "def", "datatype", "(", "self", ",", "value", ")", ":", "self", ".", "_datatype", "=", "self", ".", "validate_datatype", "(", "value", ")", "self", ".", "_cutout_ready", "=", "True" ]
26.666667
0.008065
def scene_color(frames): """parse a scene.color message""" # "scene.color" <scene_id> <color> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").uint8_3("color").assert_end().get() if results.command != "scene.color": raise MessagePar...
[ "def", "scene_color", "(", "frames", ")", ":", "# \"scene.color\" <scene_id> <color>", "reader", "=", "MessageReader", "(", "frames", ")", "results", "=", "reader", ".", "string", "(", "\"command\"", ")", ".", "uint32", "(", "\"scene_id\"", ")", ".", "uint8_3", ...
58.125
0.008475
def demote(self, move: chess.Move) -> None: """Moves a variation one down in the list of variations.""" variation = self[move] i = self.variations.index(variation) if i < len(self.variations) - 1: self.variations[i + 1], self.variations[i] = self.variations[i], self.variation...
[ "def", "demote", "(", "self", ",", "move", ":", "chess", ".", "Move", ")", "->", "None", ":", "variation", "=", "self", "[", "move", "]", "i", "=", "self", ".", "variations", ".", "index", "(", "variation", ")", "if", "i", "<", "len", "(", "self"...
53.833333
0.009146
def initialize_aggregate_metric(section, aggr_hosts, aggr_metrics, metrics, outdir_default, resource_path, label, ts_start, ts_end, rule_strings, important_sub_metrics, anomaly_detection_metrics, other_options): """ Initialize aggregate metric :param: section: config section name ...
[ "def", "initialize_aggregate_metric", "(", "section", ",", "aggr_hosts", ",", "aggr_metrics", ",", "metrics", ",", "outdir_default", ",", "resource_path", ",", "label", ",", "ts_start", ",", "ts_end", ",", "rule_strings", ",", "important_sub_metrics", ",", "anomaly_...
52.956522
0.008871
def prune_clusters(clusters, index, n=3): """ Delete clusters with fewer than n elements. """ torem = set(c for c in clusters if c.size < n) pruned_clusters = [c for c in clusters if c.size >= n] terms_torem = [] for term, clusters in index.items(): index[term] = clusters - torem ...
[ "def", "prune_clusters", "(", "clusters", ",", "index", ",", "n", "=", "3", ")", ":", "torem", "=", "set", "(", "c", "for", "c", "in", "clusters", "if", "c", ".", "size", "<", "n", ")", "pruned_clusters", "=", "[", "c", "for", "c", "in", "cluster...
32.5
0.002137
def present(name=None, start_addr=None, end_addr=None, data=None, **api_opts): ''' Ensure range record is present. infoblox_range.present: start_addr: '129.97.150.160', end_addr: '129.97.150.170', Verbose state example: .. code-block:: yaml infoblox_range.present: ...
[ "def", "present", "(", "name", "=", "None", ",", "start_addr", "=", "None", ",", "end_addr", "=", "None", ",", "data", "=", "None", ",", "*", "*", "api_opts", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "...
39.427419
0.001596
def rel_paths(self): """ :API: public """ for root, products in self._rooted_products_by_root.items(): yield root, products.rel_paths()
[ "def", "rel_paths", "(", "self", ")", ":", "for", "root", ",", "products", "in", "self", ".", "_rooted_products_by_root", ".", "items", "(", ")", ":", "yield", "root", ",", "products", ".", "rel_paths", "(", ")" ]
25.333333
0.012739
def get_locpot_along_slab_plot(self, label_energies=True, plt=None, label_fontsize=10): """ Returns a plot of the local potential (eV) vs the position along the c axis of the slab model (Ang) Args: label_energies (bool): Whether to labe...
[ "def", "get_locpot_along_slab_plot", "(", "self", ",", "label_energies", "=", "True", ",", "plt", "=", "None", ",", "label_fontsize", "=", "10", ")", ":", "plt", "=", "pretty_plot", "(", "width", "=", "6", ",", "height", "=", "4", ")", "if", "not", "pl...
37.966102
0.001741
def getConf(cls, settings, options): "updates the options dict to use config options in the settings module" ports = ['http_port', 'https_port', 'cache_port'] for port_name in ports: port = getattr(settings, port_name.upper(), None) # only use the settings ports if the de...
[ "def", "getConf", "(", "cls", ",", "settings", ",", "options", ")", ":", "ports", "=", "[", "'http_port'", ",", "'https_port'", ",", "'cache_port'", "]", "for", "port_name", "in", "ports", ":", "port", "=", "getattr", "(", "settings", ",", "port_name", "...
40.478261
0.002099
def _iterate(self, pipeline, to_process_array, subject_inds, visit_inds): """ Generate nodes that iterate over subjects and visits in the study that need to be processed by the pipeline Parameters ---------- pipeline : Pipeline The pipeline to add iter_nodes ...
[ "def", "_iterate", "(", "self", ",", "pipeline", ",", "to_process_array", ",", "subject_inds", ",", "visit_inds", ")", ":", "# Check to see whether the subject/visit IDs to process (as specified", "# by the 'to_process' array) can be factorized into indepdent nodes,", "# i.e. all sub...
50.512397
0.000321
def get(*dataset, **kwargs): ''' Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children de...
[ "def", "get", "(", "*", "dataset", ",", "*", "*", "kwargs", ")", ":", "## Configure command", "# NOTE: initialize the defaults", "flags", "=", "[", "'-H'", "]", "opts", "=", "{", "}", "# NOTE: set extra config from kwargs", "if", "kwargs", ".", "get", "(", "'d...
32.654206
0.002222
def is_binary(filename): """ :param filename: File to check. :returns: True if it's a binary file, otherwise False. """ logger.debug('is_binary: %(filename)r', locals()) # Check if the file extension is in a list of known binary types binary_extensions = ['pyc', 'iso', 'zip', 'pdf'] for...
[ "def", "is_binary", "(", "filename", ")", ":", "logger", ".", "debug", "(", "'is_binary: %(filename)r'", ",", "locals", "(", ")", ")", "# Check if the file extension is in a list of known binary types", "binary_extensions", "=", "[", "'pyc'", ",", "'iso'", ",", "'zip'...
32.5
0.001869
def fix(csvfile): '''Apply a fix (ie. remove plain names)''' header('Apply fixes from {}', csvfile.name) bads = [] reader = csv.reader(csvfile) reader.next() # Skip header for id, _, sources, dests in reader: advice = Advice.objects.get(id=id) sources = [s.strip() for s in sourc...
[ "def", "fix", "(", "csvfile", ")", ":", "header", "(", "'Apply fixes from {}'", ",", "csvfile", ".", "name", ")", "bads", "=", "[", "]", "reader", "=", "csv", ".", "reader", "(", "csvfile", ")", "reader", ".", "next", "(", ")", "# Skip header", "for", ...
40.909091
0.002172
def file_path(self, request, response=None, info=None): """ 抓取到的资源存放到七牛的时候, 应该采用什么样的key? 返回的path是一个JSON字符串, 其中有bucket和key的信息 """ return json.dumps(self._extract_key_info(request))
[ "def", "file_path", "(", "self", ",", "request", ",", "response", "=", "None", ",", "info", "=", "None", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "_extract_key_info", "(", "request", ")", ")" ]
41.4
0.009479
def _browse(cls, env, ids, from_record=None, iterated=None): """Create an instance (a recordset) corresponding to `ids` and attached to `env`. `from_record` parameter is used when the recordset is related to a parent record, and as such can take the value of a tuple (record, fie...
[ "def", "_browse", "(", "cls", ",", "env", ",", "ids", ",", "from_record", "=", "None", ",", "iterated", "=", "None", ")", ":", "records", "=", "cls", "(", ")", "records", ".", "_env_local", "=", "env", "records", ".", "_ids", "=", "_normalize_ids", "...
41.464286
0.001684
def ekinsr(handle, segno, recno): """ Add a new, empty record to a specified E-kernel segment at a specified index. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekinsr_c.html :param handle: File handle. :type handle: int :param segno: Segment number. :type segno: int :pa...
[ "def", "ekinsr", "(", "handle", ",", "segno", ",", "recno", ")", ":", "handle", "=", "ctypes", ".", "c_int", "(", "handle", ")", "segno", "=", "ctypes", ".", "c_int", "(", "segno", ")", "recno", "=", "ctypes", ".", "c_int", "(", "recno", ")", "libs...
27.722222
0.001938
def callm(method, param_dict, POST=False, socket_timeout=None, data=None): """ Call the api! Param_dict is a *regular* *python* *dictionary* so if you want to have multi-valued params put them in a list. ** note, if we require 2.6, we can get rid of this timeout munging. """ try: ...
[ "def", "callm", "(", "method", ",", "param_dict", ",", "POST", "=", "False", ",", "socket_timeout", "=", "None", ",", "data", "=", "None", ")", ":", "try", ":", "param_dict", "[", "'api_key'", "]", "=", "config", ".", "ECHO_NEST_API_KEY", "param_list", "...
36.048193
0.008458
def house_explosions(): """ Data from http://indexed.blogspot.com/2007/12/meltdown-indeed.html """ chart = PieChart2D(int(settings.width * 1.7), settings.height) chart.add_data([10, 10, 30, 200]) chart.set_pie_labels([ 'Budding Chemists', 'Propane issues', 'Meth Labs', ...
[ "def", "house_explosions", "(", ")", ":", "chart", "=", "PieChart2D", "(", "int", "(", "settings", ".", "width", "*", "1.7", ")", ",", "settings", ".", "height", ")", "chart", ".", "add_data", "(", "[", "10", ",", "10", ",", "30", ",", "200", "]", ...
30.846154
0.002421
def dump_netrc(self): """Dump the class data in the format of a .netrc file.""" rep = '' for host in self.hosts.keys(): attrs = self.hosts[host] rep = rep + 'machine ' + host + '\n\tlogin ' + str(attrs[0]) + '\n' if attrs[1]: rep = rep + 'account ' + str(attrs[1]) ...
[ "def", "dump_netrc", "(", "self", ")", ":", "rep", "=", "''", "for", "host", "in", "self", ".", "hosts", ".", "keys", "(", ")", ":", "attrs", "=", "self", ".", "hosts", "[", "host", "]", "rep", "=", "rep", "+", "'machine '", "+", "host", "+", "...
36.4
0.001786
def read_source_models(fnames, converter, monitor): """ :param fnames: list of source model files :param converter: a SourceConverter instance :param monitor: a :class:`openquake.performance.Monitor` instance :yields: SourceModel instances """ for fname in fna...
[ "def", "read_source_models", "(", "fnames", ",", "converter", ",", "monitor", ")", ":", "for", "fname", "in", "fnames", ":", "if", "fname", ".", "endswith", "(", "(", "'.xml'", ",", "'.nrml'", ")", ")", ":", "sm", "=", "to_python", "(", "fname", ",", ...
31
0.001565
def list_networks(**kwargs): ''' List all virtual networks. :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: ...
[ "def", "list_networks", "(", "*", "*", "kwargs", ")", ":", "conn", "=", "__get_conn", "(", "*", "*", "kwargs", ")", "try", ":", "return", "[", "net", ".", "name", "(", ")", "for", "net", "in", "conn", ".", "listAllNetworks", "(", ")", "]", "finally...
24.095238
0.001901
def main(log_files): """ Main executor of the trimmomatic_report template. Parameters ---------- log_files : list List of paths to the trimmomatic log files. """ log_storage = OrderedDict() for log in log_files: log_id = log.rstrip("_trimlog.txt") # Populate stor...
[ "def", "main", "(", "log_files", ")", ":", "log_storage", "=", "OrderedDict", "(", ")", "for", "log", "in", "log_files", ":", "log_id", "=", "log", ".", "rstrip", "(", "\"_trimlog.txt\"", ")", "# Populate storage of current sample", "log_storage", "[", "log_id",...
22.5
0.001938
def _get_features(self): """Decide which layers to render based on current zoom level and view type.""" if self._satellite: return [("water", [], [])] elif self._zoom <= 2: return [ ("water", [], []), ("marine_label", [], [1]), ...
[ "def", "_get_features", "(", "self", ")", ":", "if", "self", ".", "_satellite", ":", "return", "[", "(", "\"water\"", ",", "[", "]", ",", "[", "]", ")", "]", "elif", "self", ".", "_zoom", "<=", "2", ":", "return", "[", "(", "\"water\"", ",", "[",...
37.627907
0.00241
def get_arg_name(self, param): """ gets the argument name used in the command table for a parameter """ if self.current_command in self.cmdtab: for arg in self.cmdtab[self.current_command].arguments: for name in self.cmdtab[self.current_command].arguments[arg].options_list: ...
[ "def", "get_arg_name", "(", "self", ",", "param", ")", ":", "if", "self", ".", "current_command", "in", "self", ".", "cmdtab", ":", "for", "arg", "in", "self", ".", "cmdtab", "[", "self", ".", "current_command", "]", ".", "arguments", ":", "for", "name...
44.888889
0.009709
def configure(self, endpoint=None, **kwargs): """Configure a previously initialized instance of the class.""" if endpoint: kwargs['endpoint'] = endpoint keywords = self._keywords.copy() keywords.update(kwargs) if 'endpoint' in kwargs: # Then we need to cor...
[ "def", "configure", "(", "self", ",", "endpoint", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "endpoint", ":", "kwargs", "[", "'endpoint'", "]", "=", "endpoint", "keywords", "=", "self", ".", "_keywords", ".", "copy", "(", ")", "keywords", ...
45.954545
0.001938
def hcenter_blit(target, source, dest = (0, 0), area=None, special_flags=0): ''' The same as center_blit(), but only centers horizontally. ''' loc = lambda d, s: (_vec(d.get_width() / 2, 0) - _vec(s.get_width() / 2, 0)) _blitter(loc, target, source, dest, area, special_flags)
[ "def", "hcenter_blit", "(", "target", ",", "source", ",", "dest", "=", "(", "0", ",", "0", ")", ",", "area", "=", "None", ",", "special_flags", "=", "0", ")", ":", "loc", "=", "lambda", "d", ",", "s", ":", "(", "_vec", "(", "d", ".", "get_width...
43.285714
0.019417
def view_asset(self, asset): """View the given asset :param asset: the asset to view :type asset: :class:`jukeboxcore.djadapter.models.Asset` :returns: None :rtype: None :raises: None """ log.debug('Viewing asset %s', asset.name) self.cur_asset = ...
[ "def", "view_asset", "(", "self", ",", "asset", ")", ":", "log", ".", "debug", "(", "'Viewing asset %s'", ",", "asset", ".", "name", ")", "self", ".", "cur_asset", "=", "None", "self", ".", "pages_tabw", ".", "setCurrentIndex", "(", "5", ")", "name", "...
37.291667
0.001089
def pack(value, nbits=None): """Packs a given value into an array of 8-bit unsigned integers. If ``nbits`` is not present, calculates the minimal number of bits required to represent the given ``value``. The result is little endian. Args: value (int): the integer value to pack nbits (int)...
[ "def", "pack", "(", "value", ",", "nbits", "=", "None", ")", ":", "if", "nbits", "is", "None", ":", "nbits", "=", "pack_size", "(", "value", ")", "*", "BITS_PER_BYTE", "elif", "nbits", "<=", "0", ":", "raise", "ValueError", "(", "'Given number of bits mu...
33.517241
0.001
def setHorCrossPlotAutoRangeOn(self, axisNumber): """ Sets the horizontal cross-hair plot's auto-range on for the axis with number axisNumber. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.horCrossPlotRange...
[ "def", "setHorCrossPlotAutoRangeOn", "(", "self", ",", "axisNumber", ")", ":", "setXYAxesAutoRangeOn", "(", "self", ",", "self", ".", "xAxisRangeCti", ",", "self", ".", "horCrossPlotRangeCti", ",", "axisNumber", ")" ]
55.166667
0.011905
def group_batchadd(self, buyer_ids, group_ids, session): '''taobao.crm.members.group.batchadd 给一批会员添加一个分组 为一批会员添加分组,接口返回添加是否成功,如至少有一个会员的分组添加成功,接口就返回成功,否则返回失败,如果当前会员已经拥有当前分组,则直接跳过''' request = TOPRequest('taobao.crm.members.group.batchadd') request['buyer_ids'] = buyer_ids ...
[ "def", "group_batchadd", "(", "self", ",", "buyer_ids", ",", "group_ids", ",", "session", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.crm.members.group.batchadd'", ")", "request", "[", "'buyer_ids'", "]", "=", "buyer_ids", "request", "[", "'group_ids'", ...
50.444444
0.008658
def _is_custom_manager_attribute(node): """Checks if the attribute is a valid attribute for a queryset manager. """ attrname = node.attrname if not name_is_from_qs(attrname): return False for attr in node.get_children(): inferred = safe_infer(attr) funcdef = getattr(inferre...
[ "def", "_is_custom_manager_attribute", "(", "node", ")", ":", "attrname", "=", "node", ".", "attrname", "if", "not", "name_is_from_qs", "(", "attrname", ")", ":", "return", "False", "for", "attr", "in", "node", ".", "get_children", "(", ")", ":", "inferred",...
27.4
0.002353
def jquery_update_text_value(self, selector, new_value, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT): """ This method uses jQuery to update a text field. If the new_value string ends with the newline character, WebDriver will finish the call, which...
[ "def", "jquery_update_text_value", "(", "self", ",", "selector", ",", "new_value", ",", "by", "=", "By", ".", "CSS_SELECTOR", ",", "timeout", "=", "settings", ".", "LARGE_TIMEOUT", ")", ":", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "s...
53.36
0.002209
def run_supernova_keyring(ctx, action, environment, parameter): """ Sets or retrieves credentials stored in your system's keyring using the python-keyring module. Global credentials can be shared between multiple configuration sections: \b [prod] OS_PASSWORD=USE_KEYRING['sso_passwo...
[ "def", "run_supernova_keyring", "(", "ctx", ",", "action", ",", "environment", ",", "parameter", ")", ":", "if", "action", "==", "'get_credential'", ":", "result", "=", "credentials", ".", "get_user_password", "(", "env", "=", "environment", ",", "param", "=",...
29.724138
0.000374
def find_interface_by_mac(self, **kwargs): """Find the interface through which a MAC can be reached. Args: mac_address (str): A MAC address in 'xx:xx:xx:xx:xx:xx' format. Returns: list[dict]: a list of mac table data. Raises: KeyError: if `mac_addre...
[ "def", "find_interface_by_mac", "(", "self", ",", "*", "*", "kwargs", ")", ":", "mac", "=", "kwargs", ".", "pop", "(", "'mac_address'", ")", "results", "=", "[", "x", "for", "x", "in", "self", ".", "mac_table", "if", "x", "[", "'mac_address'", "]", "...
36.653846
0.002045
def regex_in(pl,regex): ''' regex = re.compile("^[a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex) regex = re.compile("^[0-9a-z]+$") pl = ['b1c3d','xab15cxx','1x','y2'] regex_in(pl,regex) ''' def cond_func(ele,regex): m...
[ "def", "regex_in", "(", "pl", ",", "regex", ")", ":", "def", "cond_func", "(", "ele", ",", "regex", ")", ":", "m", "=", "regex", ".", "search", "(", "ele", ")", "if", "(", "m", "==", "None", ")", ":", "return", "(", "False", ")", "else", ":", ...
24.789474
0.01636
def _unpack(self, ms_dict, keyjar, cls, jwt_ms=None, liss=None): """ :param ms_dict: Metadata statement as a dictionary :param keyjar: A keyjar with the necessary FO keys :param cls: What class to map the metadata into :param jwt_ms: Metadata statement as a JWS ...
[ "def", "_unpack", "(", "self", ",", "ms_dict", ",", "keyjar", ",", "cls", ",", "jwt_ms", "=", "None", ",", "liss", "=", "None", ")", ":", "if", "liss", "is", "None", ":", "liss", "=", "[", "]", "_pr", "=", "ParseInfo", "(", ")", "_pr", ".", "in...
36.903226
0.001135
def html(self) -> str: """Return html-escaped string representation of this node.""" if self.parentNode and self.parentNode._should_escape_text: return html.escape(self.data) return self.data
[ "def", "html", "(", "self", ")", "->", "str", ":", "if", "self", ".", "parentNode", "and", "self", ".", "parentNode", ".", "_should_escape_text", ":", "return", "html", ".", "escape", "(", "self", ".", "data", ")", "return", "self", ".", "data" ]
44.6
0.008811
def content(self, value): """ Setter for **self.__content** attribute. :param value: Attribute value. :type value: list """ if value is not None: assert type(value) is list, "'{0}' attribute: '{1}' type is not 'list'!".format("content", value) self._...
[ "def", "content", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "list", ",", "\"'{0}' attribute: '{1}' type is not 'list'!\"", ".", "format", "(", "\"content\"", ",", "value", ")", ...
29.636364
0.008929
def load_class(location): """ Take a string of the form 'fedmsg.consumers.ircbot:IRCBotConsumer' and return the IRCBotConsumer class. """ mod_name, cls_name = location = location.strip().split(':') tokens = mod_name.split('.') fromlist = '[]' if len(tokens) > 1: fromlist = '.'.join(...
[ "def", "load_class", "(", "location", ")", ":", "mod_name", ",", "cls_name", "=", "location", "=", "location", ".", "strip", "(", ")", ".", "split", "(", "':'", ")", "tokens", "=", "mod_name", ".", "split", "(", "'.'", ")", "fromlist", "=", "'[]'", "...
30.529412
0.001869
def suffix(self): """The final component's last suffix, if any.""" name = self.name i = name.rfind('.') if 0 < i < len(name) - 1: return name[i:] else: return ''
[ "def", "suffix", "(", "self", ")", ":", "name", "=", "self", ".", "name", "i", "=", "name", ".", "rfind", "(", "'.'", ")", "if", "0", "<", "i", "<", "len", "(", "name", ")", "-", "1", ":", "return", "name", "[", "i", ":", "]", "else", ":", ...
27.25
0.008889
def asterisk_to_min_max(field, time_filter, search_engine_endpoint, actual_params=None): """ traduce [* TO *] to something like [MIN-INDEXED-DATE TO MAX-INDEXED-DATE] :param field: map the stats to this field. :param time_filter: this is the value to be translated. think in "[* TO 2000]" :param sear...
[ "def", "asterisk_to_min_max", "(", "field", ",", "time_filter", ",", "search_engine_endpoint", ",", "actual_params", "=", "None", ")", ":", "if", "actual_params", ":", "raise", "NotImplemented", "(", "\"actual_params\"", ")", "start", ",", "end", "=", "parse_solr_...
33.052632
0.00232
def sigma(G, corpus, featureset_name, B=None, **kwargs): """ Calculate sigma (from `Chen 2009 <http://arxiv.org/pdf/0904.1439.pdf>`_) for all of the nodes in a :class:`.GraphCollection`\. You can set parameters for burstness estimation using ``kwargs``: ========= ================================...
[ "def", "sigma", "(", "G", ",", "corpus", ",", "featureset_name", ",", "B", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'date'", "not", "in", "corpus", ".", "indices", ":", "corpus", ".", "index", "(", "'date'", ")", "# Calculate burstness if...
38.53
0.001012
def formatbyindex(string, fg=None, bg=None, indices=[]): """Wrap color syntax around characters using indices and return it. fg and bg specify foreground- and background colors, respectively. """ if not string or not indices or (fg is bg is None): return string result, p = '', 0 # Th...
[ "def", "formatbyindex", "(", "string", ",", "fg", "=", "None", ",", "bg", "=", "None", ",", "indices", "=", "[", "]", ")", ":", "if", "not", "string", "or", "not", "indices", "or", "(", "fg", "is", "bg", "is", "None", ")", ":", "return", "string"...
29.423077
0.001266
def checkout(cwd, remote, target=None, user=None, username=None, password=None, *opts): ''' Download a working copy of the remote Subversion repository directory or file cwd The path to the Subversion repository ...
[ "def", "checkout", "(", "cwd", ",", "remote", ",", "target", "=", "None", ",", "user", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "*", "opts", ")", ":", "opts", "+=", "(", "remote", ",", ")", "if", "target", ":"...
22.833333
0.001
def tokenize_sents(string): """ Tokenize input text to sentences. :param string: Text to tokenize :type string: str or unicode :return: sentences :rtype: list of strings """ string = six.text_type(string) spans = [] for match in re.finditer('[^\s]+', string): spans.appe...
[ "def", "tokenize_sents", "(", "string", ")", ":", "string", "=", "six", ".", "text_type", "(", "string", ")", "spans", "=", "[", "]", "for", "match", "in", "re", ".", "finditer", "(", "'[^\\s]+'", ",", "string", ")", ":", "spans", ".", "append", "(",...
29.2
0.001894
def attributes(cls, create=False, extra=None): """Build a dict of attribute values, respecting declaration order. The process is: - Handle 'orderless' attributes, overriding defaults with provided kwargs when applicable - Handle ordered attributes, overriding them with provi...
[ "def", "attributes", "(", "cls", ",", "create", "=", "False", ",", "extra", "=", "None", ")", ":", "warnings", ".", "warn", "(", "\"Usage of Factory.attributes() is deprecated.\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ",", ")", "declarations",...
41.736842
0.002466
def parse_email(self): """Email address parsing is done in several stages. First the name of the email use is determined. Then it looks for a '@' as a delimiter between the name and the site. Lastly the email site is matched. Each part's string is stored, combined and returned. ...
[ "def", "parse_email", "(", "self", ")", ":", "email", "=", "[", "]", "# Match from current char until a non lower cased alpha", "name", "=", "self", ".", "match_string_pattern", "(", "spat", ".", "alphal", ")", "if", "not", "name", ":", "raise", "PartpyError", "...
36.5
0.001668
def available_subtypes(format=None): """Return a dictionary of available subtypes. Parameters ---------- format : str If given, only compatible subtypes are returned. Examples -------- >>> import soundfile as sf >>> sf.available_subtypes('FLAC') {'PCM_24': 'Signed 24 bit PC...
[ "def", "available_subtypes", "(", "format", "=", "None", ")", ":", "subtypes", "=", "_available_formats_helper", "(", "_snd", ".", "SFC_GET_FORMAT_SUBTYPE_COUNT", ",", "_snd", ".", "SFC_GET_FORMAT_SUBTYPE", ")", "return", "dict", "(", "(", "subtype", ",", "name", ...
31.380952
0.001473
def make_meetup_blueprint( key=None, secret=None, scope=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, storage=None, ): """ Make a blueprint for authenticating with Meetup using OAuth 2. This requires an OAuth consumer ...
[ "def", "make_meetup_blueprint", "(", "key", "=", "None", ",", "secret", "=", "None", ",", "scope", "=", "None", ",", "redirect_url", "=", "None", ",", "redirect_to", "=", "None", ",", "login_url", "=", "None", ",", "authorized_url", "=", "None", ",", "se...
40.746269
0.001788
def uses_paral_kgb(self, value=1): """True if the task is a GS Task and uses paral_kgb with the given value.""" paral_kgb = self.get_inpvar("paral_kgb", 0) # paral_kgb is used only in the GS part. return paral_kgb == value and isinstance(self, GsTask)
[ "def", "uses_paral_kgb", "(", "self", ",", "value", "=", "1", ")", ":", "paral_kgb", "=", "self", ".", "get_inpvar", "(", "\"paral_kgb\"", ",", "0", ")", "# paral_kgb is used only in the GS part.", "return", "paral_kgb", "==", "value", "and", "isinstance", "(", ...
55.8
0.010601
def iri_to_iriref(self, iri_: ShExDocParser.IriContext) -> ShExJ.IRIREF: """ iri: IRIREF | prefixedName prefixedName: PNAME_LN | PNAME_NS """ return ShExJ.IRIREF(self.iri_to_str(iri_))
[ "def", "iri_to_iriref", "(", "self", ",", "iri_", ":", "ShExDocParser", ".", "IriContext", ")", "->", "ShExJ", ".", "IRIREF", ":", "return", "ShExJ", ".", "IRIREF", "(", "self", ".", "iri_to_str", "(", "iri_", ")", ")" ]
43.6
0.018018
def from_file(cls, filename, temperature_key='DEFT', beamfill_key='BEAMFILL', **kwargs): """Creates a thermal spectral element from file. .. note:: Only FITS format is supported. Parameters ---------- filename : str Thermal spectral el...
[ "def", "from_file", "(", "cls", ",", "filename", ",", "temperature_key", "=", "'DEFT'", ",", "beamfill_key", "=", "'BEAMFILL'", ",", "*", "*", "kwargs", ")", ":", "if", "not", "(", "filename", ".", "endswith", "(", "'fits'", ")", "or", "filename", ".", ...
32
0.001624
def find_prf_cpu(idxPrc, aryFuncChnk, aryPrfTc, aryMdlParams, strVersion, lgcXval, varNumXval, queOut, lgcRstr=None, lgcPrint=True): """ Find best fitting pRF model for voxel time course, using the CPU. Parameters ---------- idxPrc : int Process ID of the process calling th...
[ "def", "find_prf_cpu", "(", "idxPrc", ",", "aryFuncChnk", ",", "aryPrfTc", ",", "aryMdlParams", ",", "strVersion", ",", "lgcXval", ",", "varNumXval", ",", "queOut", ",", "lgcRstr", "=", "None", ",", "lgcPrint", "=", "True", ")", ":", "# Number of models in the...
40.87844
0.000055
def upgrade(): """Upgrade database.""" op.create_table( 'userprofiles_userprofile', sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('username', sa.String(length=255), nullable=True), sa.Column('displayname', sa.String(length=255), nullable=True), sa.Column('...
[ "def", "upgrade", "(", ")", ":", "op", ".", "create_table", "(", "'userprofiles_userprofile'", ",", "sa", ".", "Column", "(", "'user_id'", ",", "sa", ".", "Integer", "(", ")", ",", "nullable", "=", "False", ")", ",", "sa", ".", "Column", "(", "'usernam...
43.416667
0.00188
def get_date_format_string(period): """ For a given period (e.g. 'month', 'day', or some numeric interval such as 3600 (in secs)), return the format string that can be used with strftime to format that time to specify the times across that interval, but no more detailed. For example, >>> get_date_format_string(...
[ "def", "get_date_format_string", "(", "period", ")", ":", "# handle the special case of 'month' which doesn't have", "# a static interval in seconds", "if", "isinstance", "(", "period", ",", "six", ".", "string_types", ")", "and", "period", ".", "lower", "(", ")", "=="...
31.475
0.030046
def _remote_profile_dir_default(self): """turns /home/you/.ipython/profile_foo into .ipython/profile_foo """ home = get_home_dir() if not home.endswith('/'): home = home+'/' if self.profile_dir.startswith(home): return self.profile_dir[len(home):]...
[ "def", "_remote_profile_dir_default", "(", "self", ")", ":", "home", "=", "get_home_dir", "(", ")", "if", "not", "home", ".", "endswith", "(", "'/'", ")", ":", "home", "=", "home", "+", "'/'", "if", "self", ".", "profile_dir", ".", "startswith", "(", "...
32.727273
0.008108
def aggregate_history(slugs, granularity="daily", since=None, with_data_table=False): """Template Tag to display history for multiple metrics. * ``slug_list`` -- A list of slugs to display * ``granularity`` -- the granularity: seconds, minutes, hourly, daily, weekly, monthly, yearl...
[ "def", "aggregate_history", "(", "slugs", ",", "granularity", "=", "\"daily\"", ",", "since", "=", "None", ",", "with_data_table", "=", "False", ")", ":", "r", "=", "get_r", "(", ")", "slugs", "=", "list", "(", "slugs", ")", "try", ":", "if", "since", ...
34.973684
0.001464
def generate_docs(klass): """Add documentation to generated classes""" import numina.types.datatype attrh = ('Attributes\n' '----------\n') doc = getattr(klass, '__doc__', None) if doc is None or doc == '': doc = "%s documentation." % klass.__name__ if len(klass.stored()...
[ "def", "generate_docs", "(", "klass", ")", ":", "import", "numina", ".", "types", ".", "datatype", "attrh", "=", "(", "'Attributes\\n'", "'----------\\n'", ")", "doc", "=", "getattr", "(", "klass", ",", "'__doc__'", ",", "None", ")", "if", "doc", "is", "...
27.574468
0.000745
def auto_track_url(track): """ Automatically sets the bigDataUrl for `track`. Requirements: * the track must be fully connected, such that its root is a Hub object * the root Hub object must have the Hub.url attribute set * the track must have the `source` attribute set """ ...
[ "def", "auto_track_url", "(", "track", ")", ":", "hub", "=", "track", ".", "root", "(", "cls", "=", "Hub", ")", "if", "hub", "is", "None", ":", "raise", "ValueError", "(", "\"track is not fully connected because the root is %s\"", "%", "repr", "(", "hub", ")...
31.894737
0.001603
def OnUpdate(self, event): """Updates the toolbar states""" attributes = event.attr self._update_buttoncell(attributes["button_cell"]) self.Refresh() event.Skip()
[ "def", "OnUpdate", "(", "self", ",", "event", ")", ":", "attributes", "=", "event", ".", "attr", "self", ".", "_update_buttoncell", "(", "attributes", "[", "\"button_cell\"", "]", ")", "self", ".", "Refresh", "(", ")", "event", ".", "Skip", "(", ")" ]
19.7
0.009709
def get_connected_roles(action_id): """Get roles connected to an action.""" try: from invenio.access_control_admin import compile_role_definition except ImportError: from invenio.modules.access.firerole import compile_role_definition run_sql = _get_run_sql() roles = {} res = ru...
[ "def", "get_connected_roles", "(", "action_id", ")", ":", "try", ":", "from", "invenio", ".", "access_control_admin", "import", "compile_role_definition", "except", "ImportError", ":", "from", "invenio", ".", "modules", ".", "access", ".", "firerole", "import", "c...
32.405405
0.00081
def _build_headers(self, method, auth_session): """Create headers for the request. Parameters method (str) HTTP method (e.g. 'POST'). auth_session (Session) The Session object containing OAuth 2.0 credentials. Returns headers ...
[ "def", "_build_headers", "(", "self", ",", "method", ",", "auth_session", ")", ":", "token_type", "=", "auth_session", ".", "token_type", "if", "auth_session", ".", "server_token", ":", "token", "=", "auth_session", ".", "server_token", "else", ":", "token", "...
30.702703
0.001706
def _read_packet(self): """Read a packet from the input.""" status = STATUS_WAITING mode = 0 checksum = 0 checksum_calculated = 0 length = 0 version = 0 i = 0 cnt = 0 packet = bytearray(0) while (status != STATUS_PACKET_DONE): ...
[ "def", "_read_packet", "(", "self", ")", ":", "status", "=", "STATUS_WAITING", "mode", "=", "0", "checksum", "=", "0", "checksum_calculated", "=", "0", "length", "=", "0", "version", "=", "0", "i", "=", "0", "cnt", "=", "0", "packet", "=", "bytearray",...
37.379747
0.00165
def init_app(self, app): """Initialize from flask""" uri = app.config.get("MONGO_URI", None) db_name = app.config.get("MONGO_DBNAME", 'scout') try: client = get_connection( host = app.config.get("MONGO_HOST", 'localhost'), por...
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "uri", "=", "app", ".", "config", ".", "get", "(", "\"MONGO_URI\"", ",", "None", ")", "db_name", "=", "app", ".", "config", ".", "get", "(", "\"MONGO_DBNAME\"", ",", "'scout'", ")", "try", ":", ...
33.619048
0.013774
def convert_currency(amount, from_currency, to_currency): ''' Converts currencies. Example: {% convert_currency 2 'EUR' 'SGD' as amount %} ''' try: rate = CurrencyRate.objects.get( from_currency__iso_code=from_currency, to_currency__iso_code=to_currency) exc...
[ "def", "convert_currency", "(", "amount", ",", "from_currency", ",", "to_currency", ")", ":", "try", ":", "rate", "=", "CurrencyRate", ".", "objects", ".", "get", "(", "from_currency__iso_code", "=", "from_currency", ",", "to_currency__iso_code", "=", "to_currency...
25.578947
0.001984
def remote(): """Update package info from PyPI.""" logger.info("Fetching latest data from PyPI.") results = defaultdict(list) packages = PackageVersion.objects.exclude(is_editable=True) for pv in packages: pv.update_from_pypi() results[pv.diff_status].append(pv) logger.debug(...
[ "def", "remote", "(", ")", ":", "logger", ".", "info", "(", "\"Fetching latest data from PyPI.\"", ")", "results", "=", "defaultdict", "(", "list", ")", "packages", "=", "PackageVersion", ".", "objects", ".", "exclude", "(", "is_editable", "=", "True", ")", ...
36.727273
0.002415
def _transform(self, X): """Asssume X contains only categorical features. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. """ X = self._matrix_adjust(X) X = check_array(X, accept_spar...
[ "def", "_transform", "(", "self", ",", "X", ")", ":", "X", "=", "self", ".", "_matrix_adjust", "(", "X", ")", "X", "=", "check_array", "(", "X", ",", "accept_sparse", "=", "'csc'", ",", "force_all_finite", "=", "False", ",", "dtype", "=", "int", ")",...
45.222222
0.001336
def Expand(self): """Reads the contents of the current node and the full subtree. It then makes the subtree available until the next xmlTextReaderRead() call """ ret = libxml2mod.xmlTextReaderExpand(self._o) if ret is None:raise treeError('xmlTextReaderExpand() failed') ...
[ "def", "Expand", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlTextReaderExpand", "(", "self", ".", "_o", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlTextReaderExpand() failed'", ")", "__tmp", "=", "xmlNode", "(", "_obj...
45.375
0.010811
def curriculum2schedule(curriculum, first_day, compress=False, time_table=None): """ 将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表 :param curriculum: 课表 :param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29) :param compress: 压缩连续的课时为一个 :param time_table: 每天上课的时间表, 形如 ``((start tim...
[ "def", "curriculum2schedule", "(", "curriculum", ",", "first_day", ",", "compress", "=", "False", ",", "time_table", "=", "None", ")", ":", "schedule", "=", "[", "]", "time_table", "=", "time_table", "or", "(", "(", "timedelta", "(", "hours", "=", "8", "...
42.980392
0.00223
def set_params(self, **params): """Set parameters on this object Safe setter method - attributes should not be modified directly as some changes are not valid. Valid parameters: Invalid parameters: (these would require modifying the kernel matrix) - kernel_symm -...
[ "def", "set_params", "(", "self", ",", "*", "*", "params", ")", ":", "if", "'theta'", "in", "params", "and", "params", "[", "'theta'", "]", "!=", "self", ".", "theta", ":", "raise", "ValueError", "(", "\"Cannot update theta. Please create a new graph\"", ")", ...
35.965517
0.001867
def wrap_generic_error(self, data, renderer_context): """ Convert generic error native data using the JSON API Error format See the note about the JSON API Error format on `wrap_error`. The native format for errors that are not bad requests, such as authentication issues or mis...
[ "def", "wrap_generic_error", "(", "self", ",", "data", ",", "renderer_context", ")", ":", "response", "=", "renderer_context", ".", "get", "(", "\"response\"", ",", "None", ")", "status_code", "=", "response", "and", "response", ".", "status_code", "is_error", ...
33.764706
0.001693
def _check_bullets(lines, **kwargs): """Check that the bullet point list is well formatted. Each bullet point shall have one space before and after it. The bullet character is the "*" and there is no space before it but one after it meaning the next line are starting with two blanks spaces to respect t...
[ "def", "_check_bullets", "(", "lines", ",", "*", "*", "kwargs", ")", ":", "max_length", "=", "kwargs", ".", "get", "(", "\"max_length\"", ",", "72", ")", "labels", "=", "{", "l", "for", "l", ",", "_", "in", "kwargs", ".", "get", "(", "\"commit_msg_la...
35.209677
0.000891
def boot(hostname, boot_port=consts.BOOT_PORT, scamp_binary=None, sark_struct=None, boot_delay=0.05, post_boot_delay=2.0, sv_overrides=dict(), **kwargs): """Boot a SpiNNaker machine of the given size. Parameters ---------- hostname : str Hostname or IP address of the ...
[ "def", "boot", "(", "hostname", ",", "boot_port", "=", "consts", ".", "BOOT_PORT", ",", "scamp_binary", "=", "None", ",", "sark_struct", "=", "None", ",", "boot_delay", "=", "0.05", ",", "post_boot_delay", "=", "2.0", ",", "sv_overrides", "=", "dict", "(",...
37.961165
0.000249
def create_envelope(periodic,N): ''' %This function returns an envelope for network of size N; The envelope can %either be suppressive (periodic = 0) or flat and equal to one (periodic = 1) ''' kappa = 0.3; # controls width of main body of envelope a0 = 30; # contrls steepness of envelope if perio...
[ "def", "create_envelope", "(", "periodic", ",", "N", ")", ":", "kappa", "=", "0.3", "# controls width of main body of envelope", "a0", "=", "30", "# contrls steepness of envelope", "if", "periodic", "==", "0", ":", "A", "=", "np", ".", "zeros", "(", "N", ")", ...
27.85
0.043403
def seat_slot(self): """The seat slot of the touch event. A seat slot is a non-negative seat wide unique identifier of an active touch point. Events from single touch devices will be represented as one individual touch point per device. For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOW...
[ "def", "seat_slot", "(", "self", ")", ":", "if", "self", ".", "type", "==", "EventType", ".", "TOUCH_FRAME", ":", "raise", "AttributeError", "(", "_wrong_prop", ".", "format", "(", "self", ".", "type", ")", ")", "return", "self", ".", "_libinput", ".", ...
31.708333
0.02551
def do_list(self, line): """list [path] Retrieve a list of available Science Data Objects from Member Node The response is filtered by the from-date, to-date, search, start and count session variables. See also: search """ path = self._split_args(line, 0, 1, pad=False) ...
[ "def", "do_list", "(", "self", ",", "line", ")", ":", "path", "=", "self", ".", "_split_args", "(", "line", ",", "0", ",", "1", ",", "pad", "=", "False", ")", "if", "len", "(", "path", ")", ":", "path", "=", "path", "[", "0", "]", "self", "."...
34
0.009547
def hrd(self,ifig=None,label=None,colour=None,s2ms=False, dashes=None,**kwargs): """ Plot an HR diagram Parameters ---------- ifig : integer or string Figure label, if None the current figure is used The default value is None. lims : l...
[ "def", "hrd", "(", "self", ",", "ifig", "=", "None", ",", "label", "=", "None", ",", "colour", "=", "None", ",", "s2ms", "=", "False", ",", "dashes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# fsize=18", "#", "# params = {'axes.la...
28.809524
0.015182