text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _interpret_angle(name, angle_object, angle_float, unit='degrees'): """Return an angle in radians from one of two arguments. It is common for Skyfield routines to accept both an argument like `alt` that takes an Angle object as well as an `alt_degrees` that can be given a bare float or a sexagesimal...
[ "def", "_interpret_angle", "(", "name", ",", "angle_object", ",", "angle_float", ",", "unit", "=", "'degrees'", ")", ":", "if", "angle_object", "is", "not", "None", ":", "if", "isinstance", "(", "angle_object", ",", "Angle", ")", ":", "return", "angle_object...
48.647059
20.705882
def on_connect(client): """ Sample on_connect function. Handles new connections. """ print "++ Opened connection to %s" % client.addrport() broadcast('%s joins the conversation.\n' % client.addrport() ) CLIENT_LIST.append(client) client.send("Welcome to the Chat Server, %s.\n" % client.a...
[ "def", "on_connect", "(", "client", ")", ":", "print", "\"++ Opened connection to %s\"", "%", "client", ".", "addrport", "(", ")", "broadcast", "(", "'%s joins the conversation.\\n'", "%", "client", ".", "addrport", "(", ")", ")", "CLIENT_LIST", ".", "append", "...
35.888889
13.888889
def in_dir(directory, create=True): """Context manager to execute a code block in a directory. * The directory is created if it does not exist (unless create=False is set) * At the end or after an exception code always returns to the directory that was the current directory before entering ...
[ "def", "in_dir", "(", "directory", ",", "create", "=", "True", ")", ":", "startdir", "=", "os", ".", "getcwd", "(", ")", "try", ":", "try", ":", "os", ".", "chdir", "(", "directory", ")", "logger", ".", "debug", "(", "\"Working in {directory!r}...\"", ...
36.88
19.88
def chart(colors, data, args, labels): """Handle the normalization of data and the printing of the graph.""" len_categories = len(data[0]) if len_categories > 1: # Stacked graph if args['stacked']: normal_dat = normalize(data, args['width']) stacked_graph(labels, data...
[ "def", "chart", "(", "colors", ",", "data", ",", "args", ",", "labels", ")", ":", "len_categories", "=", "len", "(", "data", "[", "0", "]", ")", "if", "len_categories", ">", "1", ":", "# Stacked graph", "if", "args", "[", "'stacked'", "]", ":", "norm...
34.147541
17.606557
def parallel(func, inputs, n_jobs, expand_args=False): """ Convenience wrapper around joblib's parallelization. """ if expand_args: return Parallel(n_jobs=n_jobs)(delayed(func)(*args) for args in inputs) else: return Parallel(n_jobs=n_jobs)(delayed(func)(arg) for arg in inputs)
[ "def", "parallel", "(", "func", ",", "inputs", ",", "n_jobs", ",", "expand_args", "=", "False", ")", ":", "if", "expand_args", ":", "return", "Parallel", "(", "n_jobs", "=", "n_jobs", ")", "(", "delayed", "(", "func", ")", "(", "*", "args", ")", "for...
38.375
19.625
def get_realnames(packages): """ Return list of unique case-correct package names. Packages are listed in a case-insensitive sorted order. """ return sorted({get_distribution(p).project_name for p in packages}, key=lambda n: n.lower())
[ "def", "get_realnames", "(", "packages", ")", ":", "return", "sorted", "(", "{", "get_distribution", "(", "p", ")", ".", "project_name", "for", "p", "in", "packages", "}", ",", "key", "=", "lambda", "n", ":", "n", ".", "lower", "(", ")", ")" ]
33.375
14.625
def draw(self, y_pred, residuals, train=False, **kwargs): """ Draw the residuals against the predicted value for the specified split. It is best to draw the training split first, then the test split so that the test split (usually smaller) is above the training split; particularl...
[ "def", "draw", "(", "self", ",", "y_pred", ",", "residuals", ",", "train", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "train", ":", "color", "=", "self", ".", "colors", "[", "'train_point'", "]", "label", "=", "\"Train $R^2 = {:0.3f}$\"", "...
36.036364
21.236364
def append(self, text, afterline=None): """Append text to the current buffer. Args: text (str or Sequence[str]): One or many lines of text to append. afterline (Optional[int]): Line number to append after. If 0, text is prepended before the first ...
[ "def", "append", "(", "self", ",", "text", ",", "afterline", "=", "None", ")", ":", "if", "afterline", ":", "self", ".", "_vim", ".", "current", ".", "buffer", ".", "append", "(", "text", ",", "afterline", ")", "else", ":", "self", ".", "_vim", "."...
39
18.692308
def is_opening_code_fence(line: str, parser: str = 'github'): r"""Determine if the given line is possibly the opening of a fenced code block. :parameter line: a single markdown line to evaluate. :parameter parser: decides rules on how to generate the anchor text. Defaults to ``github``. :type ...
[ "def", "is_opening_code_fence", "(", "line", ":", "str", ",", "parser", ":", "str", "=", "'github'", ")", ":", "if", "(", "parser", "==", "'github'", "or", "parser", "==", "'cmark'", "or", "parser", "==", "'gitlab'", "or", "parser", "==", "'commonmarker'",...
38.795455
18.659091
def update(self, **kwargs): """Customize the lazy field""" assert not self.called self.kw.update(kwargs) return self
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "assert", "not", "self", ".", "called", "self", ".", "kw", ".", "update", "(", "kwargs", ")", "return", "self" ]
28.8
10.8
def is_ec2_instance(): """Try fetching instance metadata at 'curl http://169.254.169.254/latest/meta-data/' to see if host is on an ec2 instance""" # Note: this code assumes that docker containers running on ec2 instances # inherit instances metadata, which they do as of 2016-08-25 global IS_EC2_I...
[ "def", "is_ec2_instance", "(", ")", ":", "# Note: this code assumes that docker containers running on ec2 instances", "# inherit instances metadata, which they do as of 2016-08-25", "global", "IS_EC2_INSTANCE", "if", "IS_EC2_INSTANCE", "!=", "-", "1", ":", "# Returned the cached value"...
29.28
19.16
def serialize_attrib(self, op): """ Serializer for :meth:`SpiffWorkflow.operators.Attrib`. Example:: <attribute>foobar</attribute> """ elem = etree.Element('attribute') elem.text = op.name return elem
[ "def", "serialize_attrib", "(", "self", ",", "op", ")", ":", "elem", "=", "etree", ".", "Element", "(", "'attribute'", ")", "elem", ".", "text", "=", "op", ".", "name", "return", "elem" ]
23.636364
15.454545
def get_bytes(self): """set_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:bytes = Set_client_DH_params_answer""" ret = struct.pack("<I16s16s", set_client_DH_params.constructor, self.nonce, self.server_nonce) bytes_io = BytesIO() bytes_io.write(ret) s...
[ "def", "get_bytes", "(", "self", ")", ":", "ret", "=", "struct", ".", "pack", "(", "\"<I16s16s\"", ",", "set_client_DH_params", ".", "constructor", ",", "self", ".", "nonce", ",", "self", ".", "server_nonce", ")", "bytes_io", "=", "BytesIO", "(", ")", "b...
39.3
24.8
def get_affinity(pid): """ Returns the affinity mask of the process whose ID is pid. @param pid: process PID (0 == current process) @type pid: C{int} @return: set of CPU ids @rtype: C{set} """ cpuset = cpu_set_t() result = set() libnuma.sched_getaffinity(pid, sizeof(cpu_set_t)...
[ "def", "get_affinity", "(", "pid", ")", ":", "cpuset", "=", "cpu_set_t", "(", ")", "result", "=", "set", "(", ")", "libnuma", ".", "sched_getaffinity", "(", "pid", ",", "sizeof", "(", "cpu_set_t", ")", ",", "byref", "(", "cpuset", ")", ")", "for", "i...
22.1
20.8
def _read_by_weight(self, F, att_weights, value): """Read from the value matrix given the attention weights. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, Shape (b...
[ "def", "_read_by_weight", "(", "self", ",", "F", ",", "att_weights", ",", "value", ")", ":", "output", "=", "F", ".", "batch_dot", "(", "att_weights", ",", "value", ")", "return", "output" ]
35.818182
16.772727
def auth(view, **kwargs): """ This plugin allow user to login to application kwargs: - signin_view - signout_view - template_dir - menu: - name - group_name - ... @plugin(user.login, model=model.User) class MyAccount(Juice...
[ "def", "auth", "(", "view", ",", "*", "*", "kwargs", ")", ":", "endpoint_namespace", "=", "view", ".", "__name__", "+", "\":%s\"", "view_name", "=", "view", ".", "__name__", "UserModel", "=", "kwargs", ".", "pop", "(", "\"model\"", ")", "User", "=", "U...
41.650092
20.298343
def put(self, file_path, upload_path = ''): """PUT Args: file_path: Full path for a file you want to upload upload_path: Ndrive path where you want to upload file ex) /Picture/ Returns: True: Upload success False: Upload failed ...
[ "def", "put", "(", "self", ",", "file_path", ",", "upload_path", "=", "''", ")", ":", "f", "=", "open", "(", "file_path", ",", "\"r\"", ")", "c", "=", "f", ".", "read", "(", ")", "file_name", "=", "os", ".", "path", ".", "basename", "(", "file_pa...
29.83871
18.83871
def zip_file(self, app_path, app_name, tmp_path): """Zip the App with tcex extension. Args: app_path (str): The path of the current project. app_name (str): The name of the App. tmp_path (str): The temp output path for the zip. """ # zip build directo...
[ "def", "zip_file", "(", "self", ",", "app_path", ",", "app_name", ",", "tmp_path", ")", ":", "# zip build directory", "zip_file", "=", "os", ".", "path", ".", "join", "(", "app_path", ",", "self", ".", "args", ".", "outdir", ",", "app_name", ")", "zip_fi...
44.764706
16.764706
def _create_connection(self): """Create a connection. :return: """ attempts = 0 while True: attempts += 1 if self._stopped.is_set(): break try: self._connection = Connection(self.hostname, ...
[ "def", "_create_connection", "(", "self", ")", ":", "attempts", "=", "0", "while", "True", ":", "attempts", "+=", "1", "if", "self", ".", "_stopped", ".", "is_set", "(", ")", ":", "break", "try", ":", "self", ".", "_connection", "=", "Connection", "(",...
34.136364
16.045455
def get_current_temperature(self, refresh=False): """Get current temperature""" if refresh: self.refresh() try: return float(self.get_value('temperature')) except (TypeError, ValueError): return None
[ "def", "get_current_temperature", "(", "self", ",", "refresh", "=", "False", ")", ":", "if", "refresh", ":", "self", ".", "refresh", "(", ")", "try", ":", "return", "float", "(", "self", ".", "get_value", "(", "'temperature'", ")", ")", "except", "(", ...
32.5
13.125
def init_widget(self): """ Initialize the underlying widget. This reads all items declared in the enamldef block for this node and sets only the values that have been specified. All other values will be left as default. Doing it this way makes atom to only create the ...
[ "def", "init_widget", "(", "self", ")", ":", "super", "(", "AndroidView", ",", "self", ")", ".", "init_widget", "(", ")", "# Initialize the widget by updating only the members that", "# have read expressions declared. This saves a lot of time and", "# simplifies widget initializa...
43.272727
22.545455
def international_str(self, name, sdmxobj): ''' return DictLike of xml:lang attributes. If node has no attributes, assume that language is 'en'. ''' # Get language tokens like 'en', 'fr'... elem_attrib = self._paths['int_str_names'](sdmxobj._elem, name=name) ...
[ "def", "international_str", "(", "self", ",", "name", ",", "sdmxobj", ")", ":", "# Get language tokens like 'en', 'fr'...\r", "elem_attrib", "=", "self", ".", "_paths", "[", "'int_str_names'", "]", "(", "sdmxobj", ".", "_elem", ",", "name", "=", "name", ")", "...
46.666667
19.5
def has_current_path(self, path, **kwargs): """ Checks if the page has the given path. Args: path (str | RegexObject): The string or regex that the current "path" should match. **kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`. Returns: ...
[ "def", "has_current_path", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "self", ".", "assert_current_path", "(", "path", ",", "*", "*", "kwargs", ")", "except", "ExpectationNotMet", ":", "return", "False" ]
30
21.75
def formatreturn(arg, input_is_array=False): """If the given argument is a numpy array with shape (1,), just returns that value.""" if not input_is_array and arg.size == 1: arg = arg.item() return arg
[ "def", "formatreturn", "(", "arg", ",", "input_is_array", "=", "False", ")", ":", "if", "not", "input_is_array", "and", "arg", ".", "size", "==", "1", ":", "arg", "=", "arg", ".", "item", "(", ")", "return", "arg" ]
36.5
8.333333
def get_form_kwargs(self): """ Returns the keyword arguments to provide tp the associated form. """ kwargs = super(ModelFormMixin, self).get_form_kwargs() kwargs['poll'] = self.object return kwargs
[ "def", "get_form_kwargs", "(", "self", ")", ":", "kwargs", "=", "super", "(", "ModelFormMixin", ",", "self", ")", ".", "get_form_kwargs", "(", ")", "kwargs", "[", "'poll'", "]", "=", "self", ".", "object", "return", "kwargs" ]
45
11.8
def get_admin_urls_for_registration(self): """ Utilised by Wagtail's 'register_admin_urls' hook to register urls for our the views that class offers. """ urls = super(OrderModelAdmin, self).get_admin_urls_for_registration() urls = urls + ( url(self.url_helper....
[ "def", "get_admin_urls_for_registration", "(", "self", ")", ":", "urls", "=", "super", "(", "OrderModelAdmin", ",", "self", ")", ".", "get_admin_urls_for_registration", "(", ")", "urls", "=", "urls", "+", "(", "url", "(", "self", ".", "url_helper", ".", "get...
39.583333
17.083333
def p_statement_randomize_expr(p): """ statement : RANDOMIZE expr """ p[0] = make_sentence('RANDOMIZE', make_typecast(TYPE.ulong, p[2], p.lineno(1)))
[ "def", "p_statement_randomize_expr", "(", "p", ")", ":", "p", "[", "0", "]", "=", "make_sentence", "(", "'RANDOMIZE'", ",", "make_typecast", "(", "TYPE", ".", "ulong", ",", "p", "[", "2", "]", ",", "p", ".", "lineno", "(", "1", ")", ")", ")" ]
39.5
12.25
def attention_lm_translation(): """Version to use for seq2seq.""" hparams = attention_lm_base() hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.learning_rate = 0.4 hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.max_length = 512 hparams.label_sm...
[ "def", "attention_lm_translation", "(", ")", ":", "hparams", "=", "attention_lm_base", "(", ")", "hparams", ".", "layer_preprocess_sequence", "=", "\"n\"", "hparams", ".", "layer_postprocess_sequence", "=", "\"da\"", "hparams", ".", "learning_rate", "=", "0.4", "hpa...
35.818182
10.090909
def compare(molecules, ensemble_lookup, options): """ compare stuff :param molecules: :param ensemble_lookup: :param options: :return: """ print(" Analyzing differences ... ") print('') sort_order = classification.get_sort_order(molecules) ensemble1 = sorted(ensemble_lookup...
[ "def", "compare", "(", "molecules", ",", "ensemble_lookup", ",", "options", ")", ":", "print", "(", "\" Analyzing differences ... \"", ")", "print", "(", "''", ")", "sort_order", "=", "classification", ".", "get_sort_order", "(", "molecules", ")", "ensemble1", "...
33.134328
21.880597
def radio_calibration_send(self, aileron, elevator, rudder, gyro, pitch, throttle, force_mavlink1=False): ''' Complete set of calibration parameters for the radio aileron : Aileron setpoints: left, center, right (uint16_t) elevator ...
[ "def", "radio_calibration_send", "(", "self", ",", "aileron", ",", "elevator", ",", "rudder", ",", "gyro", ",", "pitch", ",", "throttle", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "radio_calibration_encod...
72.230769
51
def error(self, s, pos): """Show text and a caret under that. For example: x = 2y + z ^ """ print("Lexical error:") print("%s" % s[:pos+10]) # + 10 for trailing context print("%s^" % (" "*(pos-1))) for t in self.rv: print(t) raise SystemExit
[ "def", "error", "(", "self", ",", "s", ",", "pos", ")", ":", "print", "(", "\"Lexical error:\"", ")", "print", "(", "\"%s\"", "%", "s", "[", ":", "pos", "+", "10", "]", ")", "# + 10 for trailing context", "print", "(", "\"%s^\"", "%", "(", "\" \"", "...
28.6
13.6
def _op_factory(func, kwargs, opname, bands, rgb_op=False): """create an operation function closure don't call directly, use parse_operations returns a function which itself takes and returns ndarrays """ def f(arr): # Avoid mutation by copying newarr = arr.copy() if rgb_op:...
[ "def", "_op_factory", "(", "func", ",", "kwargs", ",", "opname", ",", "bands", ",", "rgb_op", "=", "False", ")", ":", "def", "f", "(", "arr", ")", ":", "# Avoid mutation by copying", "newarr", "=", "arr", ".", "copy", "(", ")", "if", "rgb_op", ":", "...
32.428571
17.095238
def disable_device(self): """ disable (lock) device, to ensure no user activity in device while some process run :return: bool """ cmd_response = self.__send_command(const.CMD_DISABLEDEVICE) if cmd_response.get('status'): self.is_enabled = False r...
[ "def", "disable_device", "(", "self", ")", ":", "cmd_response", "=", "self", ".", "__send_command", "(", "const", ".", "CMD_DISABLEDEVICE", ")", "if", "cmd_response", ".", "get", "(", "'status'", ")", ":", "self", ".", "is_enabled", "=", "False", "return", ...
32.583333
18.25
def parse_files(self, req, name, field): """Pull a file from the request.""" return core.get_value(req.FILES, name, field)
[ "def", "parse_files", "(", "self", ",", "req", ",", "name", ",", "field", ")", ":", "return", "core", ".", "get_value", "(", "req", ".", "FILES", ",", "name", ",", "field", ")" ]
45.333333
4.333333
def get_manager(self, osid=None, impl_class_name=None, version=None): """Finds, loads and instantiates providers of OSID managers. Providers must conform to an OsidManager interface. The interfaces are defined in the OSID enumeration. For all OSID requests, an instance of ``OsidManager`...
[ "def", "get_manager", "(", "self", ",", "osid", "=", "None", ",", "impl_class_name", "=", "None", ",", "version", "=", "None", ")", ":", "# This implementation assumes that all osid impls reside as seperate", "# packages in the dlkit library, so that for instance the proxy mana...
52.895833
25.125
def end_grouping(self): """ Raises IndexError when no group is open. """ close = self._open.pop() if not close: return if self._open: self._open[-1].extend(close) elif self._undoing: self._redo.append(close) else: ...
[ "def", "end_grouping", "(", "self", ")", ":", "close", "=", "self", ".", "_open", ".", "pop", "(", ")", "if", "not", "close", ":", "return", "if", "self", ".", "_open", ":", "self", ".", "_open", "[", "-", "1", "]", ".", "extend", "(", "close", ...
25.642857
11.357143
def open(name=None, fileobj=None, closefd=True): """ Use all decompressor possible to make the stream """ return Guesser().open(name=name, fileobj=fileobj, closefd=closefd)
[ "def", "open", "(", "name", "=", "None", ",", "fileobj", "=", "None", ",", "closefd", "=", "True", ")", ":", "return", "Guesser", "(", ")", ".", "open", "(", "name", "=", "name", ",", "fileobj", "=", "fileobj", ",", "closefd", "=", "closefd", ")" ]
36.8
10
def _regressor_names(con_name, hrf_model, fir_delays=None): """ Returns a list of regressor names, computed from con-name and hrf type Parameters ---------- con_name: string identifier of the condition hrf_model: string or None, hrf model chosen fir_delays: 1D array_like, optio...
[ "def", "_regressor_names", "(", "con_name", ",", "hrf_model", ",", "fir_delays", "=", "None", ")", ":", "if", "hrf_model", "in", "[", "'glover'", ",", "'spm'", ",", "None", "]", ":", "return", "[", "con_name", "]", "elif", "hrf_model", "in", "[", "\"glov...
32.25
19.142857
def paths(self, destination_account, destination_amount, source_account, destination_asset_code, destination_asset_issuer=None): """Load a list of assets available to the source account id and find any payment paths from those source assets to the desired destination asset. ...
[ "def", "paths", "(", "self", ",", "destination_account", ",", "destination_amount", ",", "source_account", ",", "destination_asset_code", ",", "destination_asset_issuer", "=", "None", ")", ":", "destination_asset", "=", "Asset", "(", "destination_asset_code", ",", "de...
52.435897
30.512821
def dsphdr(x, y, z): """ This routine computes the Jacobian of the transformation from rectangular to spherical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dsphdr_c.html :param x: X-coordinate of point. :type x: float :param y: Y-coordinate of point. :type y: ...
[ "def", "dsphdr", "(", "x", ",", "y", ",", "z", ")", ":", "x", "=", "ctypes", ".", "c_double", "(", "x", ")", "y", "=", "ctypes", ".", "c_double", "(", "y", ")", "z", "=", "ctypes", ".", "c_double", "(", "z", ")", "jacobi", "=", "stypes", ".",...
28.347826
14.173913
def nested(*contexts): """ Reimplementation of nested in python 3. """ with ExitStack() as stack: results = [ stack.enter_context(context) for context in contexts ] yield results
[ "def", "nested", "(", "*", "contexts", ")", ":", "with", "ExitStack", "(", ")", "as", "stack", ":", "results", "=", "[", "stack", ".", "enter_context", "(", "context", ")", "for", "context", "in", "contexts", "]", "yield", "results" ]
23.3
10.7
def auto_register_inlines(admin_site, metadata_class): """ This is a questionable function that automatically adds our metadata inline to all relevant models in the site. """ inline_class = get_inline(metadata_class) for model, admin_class_instance in admin_site._registry.items(): _mon...
[ "def", "auto_register_inlines", "(", "admin_site", ",", "metadata_class", ")", ":", "inline_class", "=", "get_inline", "(", "metadata_class", ")", "for", "model", ",", "admin_class_instance", "in", "admin_site", ".", "_registry", ".", "items", "(", ")", ":", "_m...
54.615385
27.615385
async def create( cls, node: Union[Node, str], name: str, backing_device: Union[BlockDevice, Partition], cache_set: Union[BcacheCacheSet, int], cache_mode: CacheMode, *, uuid: str = None): """ Create a Bcache on a Node. :pa...
[ "async", "def", "create", "(", "cls", ",", "node", ":", "Union", "[", "Node", ",", "str", "]", ",", "name", ":", "str", ",", "backing_device", ":", "Union", "[", "BlockDevice", ",", "Partition", "]", ",", "cache_set", ":", "Union", "[", "BcacheCacheSet...
37.153846
15.461538
def normalize_file(file, separators=None): """ Normalizes the file path to use the POSIX path separator (i.e., ``'/'``). *file* (:class:`str`) is the file path. *separators* (:class:`~collections.abc.Collection` of :class:`str`; or :data:`None`) optionally contains the path separators to normalize. This does no...
[ "def", "normalize_file", "(", "file", ",", "separators", "=", "None", ")", ":", "# Normalize path separators.", "if", "separators", "is", "None", ":", "separators", "=", "NORMALIZE_PATH_SEPS", "norm_file", "=", "file", "for", "sep", "in", "separators", ":", "nor...
32.925926
19.592593
def touch_object(self, objects: Set[Object]) -> Set[Object]: """ Returns all objects that touch the given set of objects. """ objects_per_box = self._separate_objects_by_boxes(objects) return_set = set() for box, box_objects in objects_per_box.items(): candida...
[ "def", "touch_object", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ")", "->", "Set", "[", "Object", "]", ":", "objects_per_box", "=", "self", ".", "_separate_objects_by_boxes", "(", "objects", ")", "return_set", "=", "set", "(", ")", "fo...
45.846154
14.923077
async def running(self): """Start websocket connection.""" url = 'http://{}:{}'.format(self.host, self.port) try: async with self.session.ws_connect(url) as ws: self.state = STATE_RUNNING async for msg in ws: if self.state == STATE_...
[ "async", "def", "running", "(", "self", ")", ":", "url", "=", "'http://{}:{}'", ".", "format", "(", "self", ".", "host", ",", "self", ".", "port", ")", "try", ":", "async", "with", "self", ".", "session", ".", "ws_connect", "(", "url", ")", "as", "...
42.185185
13.407407
def wet_bulb_from_db_rh(db_temp, rh, b_press=101325): """Wet Bulb Temperature (C) at db_temp (C), Relative Humidity rh (%), and Pressure b_press (Pa). Note: [1] J. Sullivan and L. D. Sanders. "Method for obtaining wet-bulb temperatures by modifying the psychrometric formula." Center for Exp...
[ "def", "wet_bulb_from_db_rh", "(", "db_temp", ",", "rh", ",", "b_press", "=", "101325", ")", ":", "es", "=", "6.112", "*", "math", ".", "e", "**", "(", "(", "17.67", "*", "db_temp", ")", "/", "(", "db_temp", "+", "243.5", ")", ")", "e", "=", "(",...
35.461538
17.666667
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_audio( # receiver, self.media, disable_notification...
[ "def", "send", "(", "self", ",", "sender", ":", "PytgbotApiBot", ")", ":", "return", "sender", ".", "send_audio", "(", "# receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id", "audio", "=", "self", ".", "audio", ",", "chat_id...
52.076923
36.846154
def play(): """Open the matched movie with a media player.""" with sqlite3.connect(ARGS.database) as connection: connection.text_factory = str cursor = connection.cursor() if ARGS.pattern: if not ARGS.strict: ARGS.pattern = '%{0}%'.format(ARGS.pattern) ...
[ "def", "play", "(", ")", ":", "with", "sqlite3", ".", "connect", "(", "ARGS", ".", "database", ")", "as", "connection", ":", "connection", ".", "text_factory", "=", "str", "cursor", "=", "connection", ".", "cursor", "(", ")", "if", "ARGS", ".", "patter...
44.722222
14.555556
def get_groups_by_path(self, path, parent=None): """ Retrieve all groups matching the given path and optionally filtered by the given parent node. The path is converted into the absolute path of the OS before comparison. :param path: The name of the group that has to be returned ...
[ "def", "get_groups_by_path", "(", "self", ",", "path", ",", "parent", "=", "None", ")", ":", "groups", "=", "self", ".", "objects", ".", "get_objects_in_section", "(", "u'PBXGroup'", ")", "groups", "=", "[", "group", "for", "group", "in", "groups", "if", ...
49.2
29.2
def initdoc(request, namespace, docid, mode, template, context=None, configuration=None): """Initialise a document (not invoked directly)""" perspective = request.GET.get('perspective','document') if context is None: context = {} if 'configuration' in request.session: configuration = request.ses...
[ "def", "initdoc", "(", "request", ",", "namespace", ",", "docid", ",", "mode", ",", "template", ",", "context", "=", "None", ",", "configuration", "=", "None", ")", ":", "perspective", "=", "request", ".", "GET", ".", "get", "(", "'perspective'", ",", ...
56.327273
31.890909
def channels_voice_agent_user_display_create(self, agent_id, user_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/voice-api/partner_edition#open-a-users-profile-in-an-agents-browser" api_path = "/api/v2/channels/voice/agents/{agent_id}/users/{user_id}/display.json" api_path = a...
[ "def", "channels_voice_agent_user_display_create", "(", "self", ",", "agent_id", ",", "user_id", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/channels/voice/agents/{agent_id}/users/{user_id}/display.json\"", "api_path", "=", "api_path", ".",...
87.4
47.4
def run_gap_k_selection(data, k_min=1, k_max=50, B=5, skip=5, **kwargs): """ Runs gap score for all k from k_min to k_max. """ if k_min == k_max: return k_min gap_vals = [] sk_vals = [] k_range = list(range(k_min, k_max, skip)) min_k = 0 min_i = 0 for i, k in enum...
[ "def", "run_gap_k_selection", "(", "data", ",", "k_min", "=", "1", ",", "k_max", "=", "50", ",", "B", "=", "5", ",", "skip", "=", "5", ",", "*", "*", "kwargs", ")", ":", "if", "k_min", "==", "k_max", ":", "return", "k_min", "gap_vals", "=", "[", ...
29.95122
13.121951
def _set_properties(self, api_response): """Update properties from resource in body of ``api_response`` :type api_response: dict :param api_response: response returned from an API call """ self._properties.clear() cleaned = api_response.copy() self.dns_name = cle...
[ "def", "_set_properties", "(", "self", ",", "api_response", ")", ":", "self", ".", "_properties", ".", "clear", "(", ")", "cleaned", "=", "api_response", ".", "copy", "(", ")", "self", ".", "dns_name", "=", "cleaned", ".", "pop", "(", "\"dnsName\"", ",",...
41.416667
11.666667
def address(self, is_compressed=None): """ Return the public address representation of this key, if available. """ return self._network.address.for_p2pkh(self.hash160(is_compressed=is_compressed))
[ "def", "address", "(", "self", ",", "is_compressed", "=", "None", ")", ":", "return", "self", ".", "_network", ".", "address", ".", "for_p2pkh", "(", "self", ".", "hash160", "(", "is_compressed", "=", "is_compressed", ")", ")" ]
44.8
17.2
def schema_complete(): """Schema for data in CollectorUpdate.""" return Schema({ 'stage': And(str, len), 'timestamp': int, 'status': And(str, lambda s: s in ['started', 'succeeded', 'failed']), # optional matrix Optional('matrix', default='defa...
[ "def", "schema_complete", "(", ")", ":", "return", "Schema", "(", "{", "'stage'", ":", "And", "(", "str", ",", "len", ")", ",", "'timestamp'", ":", "int", ",", "'status'", ":", "And", "(", "str", ",", "lambda", "s", ":", "s", "in", "[", "'started'"...
38.384615
16.923077
def do_action(self, target, dry_run=False): """ :param target: Full path and filename :param dry_run: True - don't actually perform action. False: perform action. No effect for this rule. :return: filename: Full path and filename after action completes """ if dry_run is F...
[ "def", "do_action", "(", "self", ",", "target", ",", "dry_run", "=", "False", ")", ":", "if", "dry_run", "is", "False", ":", "try", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "target", ")", "size", "=", "os", ".", "path", ".", ...
41.333333
19.6
def update(self): """ Update this object with the latest changes from Bugzilla >>> bug.status 'NEW' #Changes happen on Bugzilla >>> bug.update() >>> bug.status 'FIXED' """ if 'id' in self._bug: resul...
[ "def", "update", "(", "self", ")", ":", "if", "'id'", "in", "self", ".", "_bug", ":", "result", "=", "self", ".", "_bugsy", ".", "request", "(", "'bug/%s'", "%", "self", ".", "_bug", "[", "'id'", "]", ")", "self", ".", "_bug", "=", "dict", "(", ...
31.125
18
def _paramf16(ins): """ Pushes 32bit fixed point param into the stack """ output = _f16_oper(ins.quad[1]) output.append('push de') output.append('push hl') return output
[ "def", "_paramf16", "(", "ins", ")", ":", "output", "=", "_f16_oper", "(", "ins", ".", "quad", "[", "1", "]", ")", "output", ".", "append", "(", "'push de'", ")", "output", ".", "append", "(", "'push hl'", ")", "return", "output" ]
26.714286
10.428571
def _get_default_radius(site): """ An internal method to get a "default" covalent/element radius Args: site: (Site) Returns: Covalent radius of element on site, or Atomic radius if unavailable """ try: return CovalentRadius.radius[sit...
[ "def", "_get_default_radius", "(", "site", ")", ":", "try", ":", "return", "CovalentRadius", ".", "radius", "[", "site", ".", "specie", ".", "symbol", "]", "except", ":", "return", "site", ".", "specie", ".", "atomic_radius" ]
27.428571
21.571429
def ReadCronJobs(self, cronjob_ids=None): """Reads a cronjob from the database.""" if cronjob_ids is None: res = [job.Copy() for job in itervalues(self.cronjobs)] else: res = [] for job_id in cronjob_ids: try: res.append(self.cronjobs[job_id].Copy()) except KeyEr...
[ "def", "ReadCronJobs", "(", "self", ",", "cronjob_ids", "=", "None", ")", ":", "if", "cronjob_ids", "is", "None", ":", "res", "=", "[", "job", ".", "Copy", "(", ")", "for", "job", "in", "itervalues", "(", "self", ".", "cronjobs", ")", "]", "else", ...
30.631579
19.263158
def filter(args): """ %prog filter gffile > filtered.gff Filter the gff file based on criteria below: (1) feature attribute values: [Identity, Coverage]. You can get this type of gff by using gmap $ gmap -f 2 .... (2) Total bp length of child features """ p = OptionParser(filter.__...
[ "def", "filter", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "filter", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--type\"", ",", "default", "=", "\"mRNA\"", ",", "help", "=", "\"The feature to scan for the attributes [default: %default]\"", ...
38.367089
18.341772
def setonce(decorator): """A descriptor modifier which allows __set__ to be called at most once.""" def decorate(fn, *args, **kwargs): parent = decorator(fn, *args, **kwargs) #doc = _add_msg(getattr(parent, '__doc__', None), '*@setonce*') doc = getattr(parent, '__doc__', None) as...
[ "def", "setonce", "(", "decorator", ")", ":", "def", "decorate", "(", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "parent", "=", "decorator", "(", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", "#doc = _add_msg(getattr(parent, '__...
50.111111
14.666667
def state_estimation_ensemble(data, k, n_runs=10, M_list=[], **se_params): """ Runs an ensemble method on the list of M results... Args: data: genes x cells array k: number of classes n_runs (optional): number of random initializations of state estimation M_list (optional): ...
[ "def", "state_estimation_ensemble", "(", "data", ",", "k", ",", "n_runs", "=", "10", ",", "M_list", "=", "[", "]", ",", "*", "*", "se_params", ")", ":", "if", "len", "(", "M_list", ")", "==", "0", ":", "M_list", "=", "[", "]", "for", "i", "in", ...
32.115385
20.730769
def isRegionValid(self): """ Returns false if the whole region is not even partially inside any screen, otherwise true """ screens = PlatformManager.getScreenDetails() for screen in screens: s_x, s_y, s_w, s_h = screen["rect"] if self.x+self.w >= s_x and s_x+s_w >= self.x...
[ "def", "isRegionValid", "(", "self", ")", ":", "screens", "=", "PlatformManager", ".", "getScreenDetails", "(", ")", "for", "screen", "in", "screens", ":", "s_x", ",", "s_y", ",", "s_w", ",", "s_h", "=", "screen", "[", "\"rect\"", "]", "if", "self", "....
49
16.888889
def check(self, cfg, state, peek_blocks): """ Check if the specified address will be executed :param cfg: :param state: :param int peek_blocks: :return: :rtype: bool """ # Get the current CFGNode from the CFG node = self._get_cfg_node(cfg...
[ "def", "check", "(", "self", ",", "cfg", ",", "state", ",", "peek_blocks", ")", ":", "# Get the current CFGNode from the CFG", "node", "=", "self", ".", "_get_cfg_node", "(", "cfg", ",", "state", ")", "if", "node", "is", "None", ":", "# Umm it doesn't exist on...
34.111111
22.777778
async def deregister(self, service): """Deregisters a local service Parameters: service (ObjectID): Service ID Returns: bool: ``True`` on success The deregister endpoint is used to remove a service from the local agent. The agent will take care of deregi...
[ "async", "def", "deregister", "(", "self", ",", "service", ")", ":", "service_id", "=", "extract_attr", "(", "service", ",", "keys", "=", "[", "\"ServiceID\"", ",", "\"ID\"", "]", ")", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "\"...
39.0625
18
def get_attribute(self, code, default=None): """Get attribute for user""" try: return self.get(code=code).value except models.ObjectDoesNotExist: return default
[ "def", "get_attribute", "(", "self", ",", "code", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", ".", "get", "(", "code", "=", "code", ")", ".", "value", "except", "models", ".", "ObjectDoesNotExist", ":", "return", "default" ]
33.833333
8.5
def get_tagstring_representation(self, tag, onebelow_normal=None, onebelow_focus=None): """ looks up user's preferred way to represent a given tagstring. :param tag: tagstring :type tag: str :param onebelow_normal: attribute that shines throu...
[ "def", "get_tagstring_representation", "(", "self", ",", "tag", ",", "onebelow_normal", "=", "None", ",", "onebelow_focus", "=", "None", ")", ":", "colourmode", "=", "int", "(", "self", ".", "_config", ".", "get", "(", "'colourmode'", ")", ")", "theme", "=...
43.174603
20.888889
def _plain_or_callable(obj): """Returns the value of the called object of obj is a callable, otherwise the plain object. Returns None if obj is None. >>> obj = None >>> _plain_or_callable(obj) >>> stmt = 'select * from sys.nodes' >>> _plain_or_callable(stmt) 'select * from sys.nodes' ...
[ "def", "_plain_or_callable", "(", "obj", ")", ":", "if", "callable", "(", "obj", ")", ":", "return", "obj", "(", ")", "elif", "isinstance", "(", "obj", ",", "types", ".", "GeneratorType", ")", ":", "return", "next", "(", "obj", ")", "else", ":", "ret...
25.65625
17.15625
def _unlock(self, name, client_id, request_id): """Handles unlocking""" if name in self._locks: other_client_id, other_request_id, lock_time = self._locks[name] if other_client_id != client_id: response = (self.RELEASE_ERROR + self.DELIMITER + ...
[ "def", "_unlock", "(", "self", ",", "name", ",", "client_id", ",", "request_id", ")", ":", "if", "name", "in", "self", ".", "_locks", ":", "other_client_id", ",", "other_request_id", ",", "lock_time", "=", "self", ".", "_locks", "[", "name", "]", "if", ...
54.9
21.933333
def todate(self): """ Calculates the corresponding day in the gregorian calendar. this is the main use case of this library. :return: Corresponding date in gregorian calendar. :rtype: :py:class:`datetime.date` """ arr = get_gregorian_date_from_julian_day(self.tojulianday...
[ "def", "todate", "(", "self", ")", ":", "arr", "=", "get_gregorian_date_from_julian_day", "(", "self", ".", "tojulianday", "(", ")", ")", "return", "datetime", ".", "date", "(", "int", "(", "arr", "[", "0", "]", ")", ",", "int", "(", "arr", "[", "1",...
42.555556
23
def get(): """Check the health of this service""" uptime = time.time() - START_TIME response = dict(uptime=f'{uptime:.2f}s', links=dict(root='{}'.format(get_root_url()))) # TODO(BM) check if we can connect to the config database ... # try: # DB.get_sub_array_ids() # ...
[ "def", "get", "(", ")", ":", "uptime", "=", "time", ".", "time", "(", ")", "-", "START_TIME", "response", "=", "dict", "(", "uptime", "=", "f'{uptime:.2f}s'", ",", "links", "=", "dict", "(", "root", "=", "'{}'", ".", "format", "(", "get_root_url", "(...
35.076923
13.692308
def to_comment(comment): """ Convert a string to a ``.properties`` file comment. All non-Latin-1 characters in the string are escaped using ``\\uXXXX`` escapes (after converting non-BMP characters to surrogate pairs), a ``#`` is prepended to the string, any CR LF or CR line breaks in the string are...
[ "def", "to_comment", "(", "comment", ")", ":", "return", "'#'", "+", "re", ".", "sub", "(", "r'[^\\x00-\\xFF]'", ",", "_esc", ",", "re", ".", "sub", "(", "r'\\n(?![#!])'", ",", "'\\n#'", ",", "re", ".", "sub", "(", "r'\\r\\n?'", ",", "'\\n'", ",", "c...
44.157895
20.578947
def _find_ip4_addresses(): """Find all the IP4 addresses currently bound to interfaces """ global _ip4_addresses proto = socket.AF_INET if _ip4_addresses is None: _ip4_addresses = [] # # Determine the interface for the default gateway # (if any) and, later, prioritis...
[ "def", "_find_ip4_addresses", "(", ")", ":", "global", "_ip4_addresses", "proto", "=", "socket", ".", "AF_INET", "if", "_ip4_addresses", "is", "None", ":", "_ip4_addresses", "=", "[", "]", "#", "# Determine the interface for the default gateway", "# (if any) and, later,...
34.892857
18.964286
def append_flag_values(self, flag_values): """Appends flags registered in another FlagValues instance. Args: flag_values: FlagValues, the FlagValues instance from which to copy flags. """ for flag_name, flag in six.iteritems(flag_values._flags()): # pylint: disable=protected-access # Each ...
[ "def", "append_flag_values", "(", "self", ",", "flag_values", ")", ":", "for", "flag_name", ",", "flag", "in", "six", ".", "iteritems", "(", "flag_values", ".", "_flags", "(", ")", ")", ":", "# pylint: disable=protected-access", "# Each flags with short_name appears...
46.833333
21.5
def from_private_key(account_name, private_key=None, private_key_path=None, storage=None, storage_path=None, api_version="v3", readonly=False, http_client=None, ga_hook=None): """Create a client for a service account. Create a client with an account name and a private ...
[ "def", "from_private_key", "(", "account_name", ",", "private_key", "=", "None", ",", "private_key_path", "=", "None", ",", "storage", "=", "None", ",", "storage_path", "=", "None", ",", "api_version", "=", "\"v3\"", ",", "readonly", "=", "False", ",", "http...
45
23.333333
def _readClusterSettings(self): """ Read the current instance's meta-data to get the cluster settings. """ # get the leader metadata mdUrl = "http://169.254.169.254/metadata/instance?api-version=2017-08-01" header = {'Metadata': 'True'} request = urllib.request.Re...
[ "def", "_readClusterSettings", "(", "self", ")", ":", "# get the leader metadata", "mdUrl", "=", "\"http://169.254.169.254/metadata/instance?api-version=2017-08-01\"", "header", "=", "{", "'Metadata'", ":", "'True'", "}", "request", "=", "urllib", ".", "request", ".", "...
47.461538
18.923077
def parse_genotypes(self, lb, ub): """Extracts a fraction of the file (current chunk of loci) loading the genotypes into memoery. :param lb: Lower bound of the current chunk :param ub: Upper bound of the current chunk :return: Dosage dosages for current chunk """ ...
[ "def", "parse_genotypes", "(", "self", ",", "lb", ",", "ub", ")", ":", "file", "=", "self", ".", "openfile", "(", "self", ".", "current_file", ")", "words", "=", "file", ".", "readline", "(", ")", ".", "strip", "(", ")", ".", "split", "(", ")", "...
32.615385
15.884615
def before_app_request(self, f): """Like :meth:`Flask.before_request`. Such a function is executed before each request, even if outside of a blueprint. """ self.record_once(lambda s: s.app.before_request_funcs .setdefault(None, []).append(f)) return f
[ "def", "before_app_request", "(", "self", ",", "f", ")", ":", "self", ".", "record_once", "(", "lambda", "s", ":", "s", ".", "app", ".", "before_request_funcs", ".", "setdefault", "(", "None", ",", "[", "]", ")", ".", "append", "(", "f", ")", ")", ...
42.571429
11
def i8(self, name, value=None, align=None): """Add an 1 byte integer field to template. This is an convenience method that simply calls `Int` keyword with predefined length.""" self.int(1, name, value, align)
[ "def", "i8", "(", "self", ",", "name", ",", "value", "=", "None", ",", "align", "=", "None", ")", ":", "self", ".", "int", "(", "1", ",", "name", ",", "value", ",", "align", ")" ]
45.8
8.8
def _ss_reg(self): """Sum of squares of the regression.""" return np.sum( np.square(self._predicted - np.expand_dims(self._ybar, axis=1)), axis=1, )
[ "def", "_ss_reg", "(", "self", ")", ":", "return", "np", ".", "sum", "(", "np", ".", "square", "(", "self", ".", "_predicted", "-", "np", ".", "expand_dims", "(", "self", ".", "_ybar", ",", "axis", "=", "1", ")", ")", ",", "axis", "=", "1", ","...
32.666667
21
def get_host_health_temperature_sensors(self, data=None): """Get the health Temp Sensor report. :param: the data to retrieve from the server, defaults to None. :returns: the dictionary containing the temperature sensors information. :raises: IloConnectionError if failed conn...
[ "def", "get_host_health_temperature_sensors", "(", "self", ",", "data", "=", "None", ")", ":", "data", "=", "self", ".", "get_host_health_data", "(", "data", ")", "d", "=", "data", "[", "'GET_EMBEDDED_HEALTH_DATA'", "]", "[", "'TEMPERATURE'", "]", "[", "'TEMP'...
41
17.857143
def conform_query(cls, query): """Converts the query string from a target uri, uses cls.allowed_kwargs, and cls.filter_kwargs to drive logic. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls...
[ "def", "conform_query", "(", "cls", ",", "query", ")", ":", "query", "=", "parse_qs", "(", "query", ",", "keep_blank_values", "=", "True", ")", "# Remove any unexpected keywords from the query string.", "if", "cls", ".", "filter_kwargs", ":", "query", "=", "{", ...
37.814815
21.703704
def tag_begin(self, tag_name, attributes=None): """Marks the beginning of the ``tag_name`` structure. Call :meth:`tag_end` with the same ``tag_name`` to mark the end of the structure. The attributes string is of the form "key1=value2 key2=value2 ...". Values may be boolean (tru...
[ "def", "tag_begin", "(", "self", ",", "tag_name", ",", "attributes", "=", "None", ")", ":", "if", "attributes", "is", "None", ":", "attributes", "=", "''", "cairo", ".", "cairo_tag_begin", "(", "self", ".", "_pointer", ",", "_encode_string", "(", "tag_name...
33.325581
25.55814
def prob_classify(self, text): """Return the label probability distribution for classifying a string of text. Example: :: >>> classifier = MaxEntClassifier(train_data) >>> prob_dist = classifier.prob_classify("I feel happy this morning.") >>> prob_di...
[ "def", "prob_classify", "(", "self", ",", "text", ")", ":", "feats", "=", "self", ".", "extract_features", "(", "text", ")", "return", "self", ".", "classifier", ".", "prob_classify", "(", "feats", ")" ]
29.157895
20.315789
def call(self, method, *args): """ Calls the service method defined with the arguments provided """ try: response = getattr(self.client.service, method)(*args) except (URLError, SSLError) as e: log.exception('Failed to connect to responsys service') raise Conn...
[ "def", "call", "(", "self", ",", "method", ",", "*", "args", ")", ":", "try", ":", "response", "=", "getattr", "(", "self", ".", "client", ".", "service", ",", "method", ")", "(", "*", "args", ")", "except", "(", "URLError", ",", "SSLError", ")", ...
42.5
13.681818
def callback_request(self, msg, reply_cb=None, inform_cb=None, user_data=None, timeout=None, use_mid=None): """Send a request messsage. Parameters ---------- msg : Message object The request message to send. reply_cb : function Th...
[ "def", "callback_request", "(", "self", ",", "msg", ",", "reply_cb", "=", "None", ",", "inform_cb", "=", "None", ",", "user_data", "=", "None", ",", "timeout", "=", "None", ",", "use_mid", "=", "None", ")", ":", "if", "timeout", "is", "None", ":", "t...
36.377778
17.8
def measurements(self): """Return modeled measurements 1. dimension: frequency 2. dimension: config-number 3. dimension: 2: magnitude and phase (resistivity) """ m_all = np.array([self.tds[key].measurements() for key in sorted(self.tds.keys())]...
[ "def", "measurements", "(", "self", ")", ":", "m_all", "=", "np", ".", "array", "(", "[", "self", ".", "tds", "[", "key", "]", ".", "measurements", "(", ")", "for", "key", "in", "sorted", "(", "self", ".", "tds", ".", "keys", "(", ")", ")", "]"...
30.181818
16.818182
def insert_child ( self, object, index, child ): """ Inserts a child into the object's children. """ if isinstance( child, Subgraph ): object.subgraphs.insert( index, child ) elif isinstance( child, Cluster ): object.clusters.insert( index, child ) elif ...
[ "def", "insert_child", "(", "self", ",", "object", ",", "index", ",", "child", ")", ":", "if", "isinstance", "(", "child", ",", "Subgraph", ")", ":", "object", ".", "subgraphs", ".", "insert", "(", "index", ",", "child", ")", "elif", "isinstance", "(",...
29.352941
15.235294
def set_permissions(self, object, replace=False): """ Sets the S3 ACL grants for the given object to the appropriate value based on the type of Distribution. If the Distribution is serving private content the ACL will be set to include the Origin Access Identity associated with ...
[ "def", "set_permissions", "(", "self", ",", "object", ",", "replace", "=", "False", ")", ":", "if", "isinstance", "(", "self", ".", "config", ".", "origin", ",", "S3Origin", ")", ":", "if", "self", ".", "config", ".", "origin", ".", "origin_access_identi...
47.258065
20.483871
def _readASCII(self, filename): """ASCII files have no headers. Following synphot, this routine will assume the first column is wavelength in Angstroms, and the second column is flux in Flam. """ self.waveunits = units.Units('angstrom') self.fluxunits = units.Units('flam...
[ "def", "_readASCII", "(", "self", ",", "filename", ")", ":", "self", ".", "waveunits", "=", "units", ".", "Units", "(", "'angstrom'", ")", "self", ".", "fluxunits", "=", "units", ".", "Units", "(", "'flam'", ")", "wlist", ",", "flist", "=", "self", "...
44
13.454545
def render_request(self, sort=True): """Render the dict's Cookie objects into a string formatted for HTTP request headers (simple 'Cookie: ' style). """ if not sort: return ("; ".join( cookie.render_request() for cookie in self.values())) return ("; "....
[ "def", "render_request", "(", "self", ",", "sort", "=", "True", ")", ":", "if", "not", "sort", ":", "return", "(", "\"; \"", ".", "join", "(", "cookie", ".", "render_request", "(", ")", "for", "cookie", "in", "self", ".", "values", "(", ")", ")", "...
43.444444
11.777778
def follow(self, gpid, callback=None, callback_parsed=None): """Create a subscription (i.e. follow) a Feed/Point with a global point id (gpid) and a feed data callback Returns a new [RemoteFeed](RemotePoint.m.html#IoticAgent.IOT.RemotePoint.RemoteFeed) object or the existing one if the subscrip...
[ "def", "follow", "(", "self", ",", "gpid", ",", "callback", "=", "None", ",", "callback_parsed", "=", "None", ")", ":", "if", "callback_parsed", ":", "callback", "=", "self", ".", "_client", ".", "_get_parsed_feed_callback", "(", "callback_parsed", ",", "cal...
59.333333
39.916667
def iteration(self, node_status=True): """ Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status) """ # One iteration changes the opinion of several voters using the following procedure: # - select randomly one voter (sp...
[ "def", "iteration", "(", "self", ",", "node_status", "=", "True", ")", ":", "# One iteration changes the opinion of several voters using the following procedure:", "# - select randomly one voter (speaker 1)", "# - select randomly one of its neighbours (speaker 2)", "# - if the two voters a...
45.897059
27.073529
def _get_postqueue_stats(self, postfix_config_dir, tags): # get some intersting configuratin values from postconf pc_output, _, _ = get_subprocess_output(['postconf', 'mail_version'], self.log, False) postfix_version = pc_output.strip('\n').split('=')[1].strip() pc_output, _, _ = get_su...
[ "def", "_get_postqueue_stats", "(", "self", ",", "postfix_config_dir", ",", "tags", ")", ":", "# get some intersting configuratin values from postconf", "pc_output", ",", "_", ",", "_", "=", "get_subprocess_output", "(", "[", "'postconf'", ",", "'mail_version'", "]", ...
41.333333
30.148148
def matchBytes(self, bytes): """Look for a sequence of bytes at the start of a string. If the bytes are found return True and advance the position to the byte after the match. Otherwise return False and leave the position alone""" p = self.position data = self[p:p + len(bytes)] ...
[ "def", "matchBytes", "(", "self", ",", "bytes", ")", ":", "p", "=", "self", ".", "position", "data", "=", "self", "[", "p", ":", "p", "+", "len", "(", "bytes", ")", "]", "rv", "=", "data", ".", "startswith", "(", "bytes", ")", "if", "rv", ":", ...
41.8
12.1
def from_bytes(cls, data): """ I am so sorry. """ len_username = int.from_bytes(data[0:2], byteorder="big") offset_username = 2 + len_username username = data[2:offset_username].decode("UTF-8") offset_password = 2 + offset_username len_password = int.from_...
[ "def", "from_bytes", "(", "cls", ",", "data", ")", ":", "len_username", "=", "int", ".", "from_bytes", "(", "data", "[", "0", ":", "2", "]", ",", "byteorder", "=", "\"big\"", ")", "offset_username", "=", "2", "+", "len_username", "username", "=", "data...
36
13.5
def get_default_config(self): """ Returns the default collector settings """ default_config = super(WebsiteMonitorCollector, self).get_default_config() default_config['URL'] = '' default_config['path'] = 'websitemonitor' return defau...
[ "def", "get_default_config", "(", "self", ")", ":", "default_config", "=", "super", "(", "WebsiteMonitorCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "default_config", "[", "'URL'", "]", "=", "''", "default_config", "[", "'path'", "]", "="...
35.666667
8.333333
def create_discount_coupon(cls, discount_coupon, **kwargs): """Create DiscountCoupon Create a new DiscountCoupon This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_discount_coupon(discount...
[ "def", "create_discount_coupon", "(", "cls", ",", "discount_coupon", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_create_discount...
43.904762
21.761905