text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def add_item(self,item): """Add an item to `self`. :Parameters: - `item`: the item to add. :Types: - `item`: `MucItemBase` """ if not isinstance(item,MucItemBase): raise TypeError("Bad item type for muc#user") item.as_xml(self.xmlnode)
[ "def", "add_item", "(", "self", ",", "item", ")", ":", "if", "not", "isinstance", "(", "item", ",", "MucItemBase", ")", ":", "raise", "TypeError", "(", "\"Bad item type for muc#user\"", ")", "item", ".", "as_xml", "(", "self", ".", "xmlnode", ")" ]
28.181818
0.0125
def Nu_vertical_plate_Churchill(Pr, Gr): r'''Calculates Nusselt number for natural convection around a vertical plate according to the Churchill-Chu [1]_ correlation, also presented in [2]_. Plate must be isothermal; an alternate expression exists for constant heat flux. .. math:: Nu_{L}=\l...
[ "def", "Nu_vertical_plate_Churchill", "(", "Pr", ",", "Gr", ")", ":", "Ra", "=", "Pr", "*", "Gr", "Nu", "=", "(", "0.825", "+", "(", "0.387", "*", "Ra", "**", "(", "1", "/", "6.", ")", "/", "(", "1", "+", "(", "0.492", "/", "Pr", ")", "**", ...
30.792453
0.001188
def control_group(action, action_space, control_group_act, control_group_id): """Act on a control group, selecting, setting, etc.""" del action_space select = action.action_ui.control_group select.action = control_group_act select.control_group_index = control_group_id
[ "def", "control_group", "(", "action", ",", "action_space", ",", "control_group_act", ",", "control_group_id", ")", ":", "del", "action_space", "select", "=", "action", ".", "action_ui", ".", "control_group", "select", ".", "action", "=", "control_group_act", "sel...
45.666667
0.021505
def create_process_worker(self, cmd_list, environ=None): """Create a new process worker instance.""" worker = ProcessWorker(cmd_list, environ=environ) self._create_worker(worker) return worker
[ "def", "create_process_worker", "(", "self", ",", "cmd_list", ",", "environ", "=", "None", ")", ":", "worker", "=", "ProcessWorker", "(", "cmd_list", ",", "environ", "=", "environ", ")", "self", ".", "_create_worker", "(", "worker", ")", "return", "worker" ]
44
0.008929
def parse_atom(tokens, options): """atom ::= '(' expr ')' | '[' expr ']' | 'options' | long | shorts | argument | command ; """ token = tokens.current() result = [] if token == '(': tokens.move() result = [Required(*parse_expr(tokens, options))] if tokens.move() ...
[ "def", "parse_atom", "(", "tokens", ",", "options", ")", ":", "token", "=", "tokens", ".", "current", "(", ")", "result", "=", "[", "]", "if", "token", "==", "'('", ":", "tokens", ".", "move", "(", ")", "result", "=", "[", "Required", "(", "*", "...
35.241379
0.000952
def _read_mac_addr(self): """Read MAC address.""" _byte = self._read_fileng(6) _addr = '-'.join(textwrap.wrap(_byte.hex(), 2)) return _addr
[ "def", "_read_mac_addr", "(", "self", ")", ":", "_byte", "=", "self", ".", "_read_fileng", "(", "6", ")", "_addr", "=", "'-'", ".", "join", "(", "textwrap", ".", "wrap", "(", "_byte", ".", "hex", "(", ")", ",", "2", ")", ")", "return", "_addr" ]
33.4
0.011696
def subj_pred_idx_to_uri(s: URIRef, p: URIRef, idx: Optional[int] = None) -> URIRef: """ Convert FHIR subject, predicate and entry index into a URI. The resulting element can be substituted for the name of the target BNODE :param s: Subject URI (e.g. "fhir:Patient/f201", "fhir:Patient/f201.Patient.identifi...
[ "def", "subj_pred_idx_to_uri", "(", "s", ":", "URIRef", ",", "p", ":", "URIRef", ",", "idx", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "URIRef", ":", "return", "URIRef", "(", "str", "(", "s", ")", "+", "'.'", "+", "str", "(", "p",...
71.777778
0.009174
def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`. """ self.Y = self.Pcn(self.AX + self.U)
[ "def", "ystep", "(", "self", ")", ":", "self", ".", "Y", "=", "self", ".", "Pcn", "(", "self", ".", "AX", "+", "self", ".", "U", ")" ]
25.666667
0.012579
def main(arguments=None): """ *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* """ # setup the command-line util settings su = tools( arguments=arguments, docString=__doc__, logLevel="DEBUG", option...
[ "def", "main", "(", "arguments", "=", "None", ")", ":", "# setup the command-line util settings", "su", "=", "tools", "(", "arguments", "=", "arguments", ",", "docString", "=", "__doc__", ",", "logLevel", "=", "\"DEBUG\"", ",", "options_first", "=", "False", "...
27.467456
0.001455
def inspect_node(node): """ This function accept a `elasticluster.cluster.Node` class, connects to a node and tries to discover the kind of batch system installed, and some other information. """ node_information = {} ssh = node.connect() if not ssh: log.error("Unable to connect ...
[ "def", "inspect_node", "(", "node", ")", ":", "node_information", "=", "{", "}", "ssh", "=", "node", ".", "connect", "(", ")", "if", "not", "ssh", ":", "log", ".", "error", "(", "\"Unable to connect to node %s\"", ",", "node", ".", "name", ")", "return",...
36.851852
0.001959
def set_global_defaults(**kwargs): """Set global defaults for the options passed to the icon painter.""" valid_options = [ 'active', 'selected', 'disabled', 'on', 'off', 'on_active', 'on_selected', 'on_disabled', 'off_active', 'off_selected', 'off_disabled', 'color', 'color_on',...
[ "def", "set_global_defaults", "(", "*", "*", "kwargs", ")", ":", "valid_options", "=", "[", "'active'", ",", "'selected'", ",", "'disabled'", ",", "'on'", ",", "'off'", ",", "'on_active'", ",", "'on_selected'", ",", "'on_disabled'", ",", "'off_active'", ",", ...
38.75
0.001259
def IDIV(cpu, src): """ Signed divide. Divides (signed) the value in the AL, AX, or EAX register by the source operand and stores the result in the AX, DX:AX, or EDX:EAX registers. The source operand can be a general-purpose register or a memory location. The action of t...
[ "def", "IDIV", "(", "cpu", ",", "src", ")", ":", "reg_name_h", "=", "{", "8", ":", "'AH'", ",", "16", ":", "'DX'", ",", "32", ":", "'EDX'", ",", "64", ":", "'RDX'", "}", "[", "src", ".", "size", "]", "reg_name_l", "=", "{", "8", ":", "'AL'", ...
37.225806
0.001125
def delete_by_user_name(user_name): ''' Delete user in the database by `user_name`. ''' try: del_count = TabMember.delete().where(TabMember.user_name == user_name) del_count.execute() return True except: return False
[ "def", "delete_by_user_name", "(", "user_name", ")", ":", "try", ":", "del_count", "=", "TabMember", ".", "delete", "(", ")", ".", "where", "(", "TabMember", ".", "user_name", "==", "user_name", ")", "del_count", ".", "execute", "(", ")", "return", "True",...
29.5
0.013158
def relative(self): """Identify if this URI is relative to some "current context". For example, if the protocol is missing, it's protocol-relative. If the host is missing, it's host-relative, etc. """ scheme = self.scheme if not scheme: return True return scheme.is_relative(self)
[ "def", "relative", "(", "self", ")", ":", "scheme", "=", "self", ".", "scheme", "if", "not", "scheme", ":", "return", "True", "return", "scheme", ".", "is_relative", "(", "self", ")" ]
24.666667
0.058632
def mesh(faces, coordinates, meta_data=None, properties=None): ''' mesh(faces, coordinates) yields a mesh with the given face and coordinate matrices. ''' return Mesh(faces, coordinates, meta_data=meta_data, properties=properties)
[ "def", "mesh", "(", "faces", ",", "coordinates", ",", "meta_data", "=", "None", ",", "properties", "=", "None", ")", ":", "return", "Mesh", "(", "faces", ",", "coordinates", ",", "meta_data", "=", "meta_data", ",", "properties", "=", "properties", ")" ]
48.4
0.00813
def extract_frames(self, bpf_buffer): """Extract all frames from the buffer and stored them in the received list.""" # noqa: E501 # Ensure that the BPF buffer contains at least the header len_bb = len(bpf_buffer) if len_bb < 20: # Note: 20 == sizeof(struct bfp_hdr) return ...
[ "def", "extract_frames", "(", "self", ",", "bpf_buffer", ")", ":", "# noqa: E501", "# Ensure that the BPF buffer contains at least the header", "len_bb", "=", "len", "(", "bpf_buffer", ")", "if", "len_bb", "<", "20", ":", "# Note: 20 == sizeof(struct bfp_hdr)", "return", ...
37.974359
0.001317
def conf_matrix(p,labels,names=['1','0'],threshold=.5,show=True): """ Returns error rate and true/false positives in a binary classification problem - Actual classes are displayed by column. - Predicted classes are displayed by row. :param p: array of class '1' probabilities. :param labels: arr...
[ "def", "conf_matrix", "(", "p", ",", "labels", ",", "names", "=", "[", "'1'", ",", "'0'", "]", ",", "threshold", "=", ".5", ",", "show", "=", "True", ")", ":", "assert", "p", ".", "size", "==", "labels", ".", "size", ",", "\"Arrays p and labels have ...
45.758621
0.014022
def dirs(self): """Get an iter of VenvDirs within the directory.""" contents = self.paths contents = (VenvDir(path.path) for path in contents if path.is_dir) return contents
[ "def", "dirs", "(", "self", ")", ":", "contents", "=", "self", ".", "paths", "contents", "=", "(", "VenvDir", "(", "path", ".", "path", ")", "for", "path", "in", "contents", "if", "path", ".", "is_dir", ")", "return", "contents" ]
40.2
0.009756
def uavionix_adsb_out_cfg_send(self, ICAO, callsign, emitterType, aircraftSize, gpsOffsetLat, gpsOffsetLon, stallSpeed, rfSelect, force_mavlink1=False): ''' Static data to configure the ADS-B transponder (send within 10 sec of a POR and every 10 sec thereafter) ...
[ "def", "uavionix_adsb_out_cfg_send", "(", "self", ",", "ICAO", ",", "callsign", ",", "emitterType", ",", "aircraftSize", ",", "gpsOffsetLat", ",", "gpsOffsetLon", ",", "stallSpeed", ",", "rfSelect", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self"...
89.375
0.008304
def strip_secrets(qp, matcher, kwlist): """ This function will scrub the secrets from a query param string based on the passed in matcher and kwlist. blah=1&secret=password&valid=true will result in blah=1&secret=<redacted>&valid=true You can even pass in path query combinations: /signup?blah=1&s...
[ "def", "strip_secrets", "(", "qp", ",", "matcher", ",", "kwlist", ")", ":", "path", "=", "None", "try", ":", "if", "qp", "is", "None", ":", "return", "''", "if", "type", "(", "kwlist", ")", "is", "not", "list", ":", "logger", ".", "debug", "(", "...
33.948718
0.002202
def loadFromURL(self, url): """Load an xml file from a URL and return a DOM document.""" if isfile(url) is True: file = open(url, 'r') else: file = urlopen(url) try: result = self.loadDocument(file) except Exception, ex: file....
[ "def", "loadFromURL", "(", "self", ",", "url", ")", ":", "if", "isfile", "(", "url", ")", "is", "True", ":", "file", "=", "open", "(", "url", ",", "'r'", ")", "else", ":", "file", "=", "urlopen", "(", "url", ")", "try", ":", "result", "=", "sel...
30.066667
0.008602
def build(self, paths, tags=None, wheel_version=None): """ Build a wheel from files in specified paths, and use any specified tags when determining the name of the wheel. """ if tags is None: tags = {} libkey = list(filter(lambda o: o in paths, ('purelib', 'p...
[ "def", "build", "(", "self", ",", "paths", ",", "tags", "=", "None", ",", "wheel_version", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "{", "}", "libkey", "=", "list", "(", "filter", "(", "lambda", "o", ":", "o", "in", ...
39.126214
0.000484
def remix(self, remix_dictionary=None, num_output_channels=None): '''Remix the channels of an audio file. Note: volume options are not yet implemented Parameters ---------- remix_dictionary : dict or None Dictionary mapping output channel to list of input channel(s)...
[ "def", "remix", "(", "self", ",", "remix_dictionary", "=", "None", ",", "num_output_channels", "=", "None", ")", ":", "if", "not", "(", "isinstance", "(", "remix_dictionary", ",", "dict", ")", "or", "remix_dictionary", "is", "None", ")", ":", "raise", "Val...
37.810127
0.000653
def alphafilter(request, queryset, template): """ Render the template with the filtered queryset """ qs_filter = {} for key in list(request.GET.keys()): if '__istartswith' in key: qs_filter[str(key)] = request.GET[key] break return render_to_response( te...
[ "def", "alphafilter", "(", "request", ",", "queryset", ",", "template", ")", ":", "qs_filter", "=", "{", "}", "for", "key", "in", "list", "(", "request", ".", "GET", ".", "keys", "(", ")", ")", ":", "if", "'__istartswith'", "in", "key", ":", "qs_filt...
26.941176
0.00211
def _dot_product(self, imgs_to_decode): """ Decoding using the dot product. """ return np.dot(imgs_to_decode.T, self.feature_images).T
[ "def", "_dot_product", "(", "self", ",", "imgs_to_decode", ")", ":", "return", "np", ".", "dot", "(", "imgs_to_decode", ".", "T", ",", "self", ".", "feature_images", ")", ".", "T" ]
38.75
0.012658
def p_duration_information_speed(self, p): 'duration : information AT speed' logger.debug('duration = information %s at speed %s', p[1], p[3]) p[0] = p[1].at_speed(p[3])
[ "def", "p_duration_information_speed", "(", "self", ",", "p", ")", ":", "logger", ".", "debug", "(", "'duration = information %s at speed %s'", ",", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")", "p", "[", "0", "]", "=", "p", "[", "1", "]", ".", ...
47.5
0.010363
def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, cmap:str=None, y:Any=None, **kwargs): "Show image on `ax` with `title`, using `cmap` if single-channel, overlaid with optional `y`" cmap = ifnone(cmap, defaults.cmap) ax = show_imag...
[ "def", "show", "(", "self", ",", "ax", ":", "plt", ".", "Axes", "=", "None", ",", "figsize", ":", "tuple", "=", "(", "3", ",", "3", ")", ",", "title", ":", "Optional", "[", "str", "]", "=", "None", ",", "hide_axis", ":", "bool", "=", "True", ...
68.142857
0.055901
def remove_dependency(id=None, name=None, dependency_id=None, dependency_name=None): """ Remove a BuildConfiguration from the dependency list of another BuildConfiguration """ data = remove_dependency_raw(id, name, dependency_id, dependency_name) if data: return utils.format_json_list(data)
[ "def", "remove_dependency", "(", "id", "=", "None", ",", "name", "=", "None", ",", "dependency_id", "=", "None", ",", "dependency_name", "=", "None", ")", ":", "data", "=", "remove_dependency_raw", "(", "id", ",", "name", ",", "dependency_id", ",", "depend...
44.714286
0.009404
def create_role_from_templates(role_name=None, role_path=None, project_name=None, description=None): """ Create a new role with initial files from templates. :param role_name: Name of the role :param role_path: Full path to the role :param project_name: Name of the pro...
[ "def", "create_role_from_templates", "(", "role_name", "=", "None", ",", "role_path", "=", "None", ",", "project_name", "=", "None", ",", "description", "=", "None", ")", ":", "context", "=", "locals", "(", ")", "templates_path", "=", "os", ".", "path", "....
48.609756
0.002459
def find_file(self, path, tgt_env): ''' Find the specified file in the specified environment ''' tree = self.get_tree(tgt_env) if not tree: # Branch/tag/SHA not found in repo return None, None, None blob = None mode = None depth = 0...
[ "def", "find_file", "(", "self", ",", "path", ",", "tgt_env", ")", ":", "tree", "=", "self", ".", "get_tree", "(", "tgt_env", ")", "if", "not", "tree", ":", "# Branch/tag/SHA not found in repo", "return", "None", ",", "None", ",", "None", "blob", "=", "N...
36.974359
0.002027
def state(name, path=None): ''' Returns the state of a container. path path to the container parent directory (default: /var/lib/lxc) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.state name ''' # Don't use _ensure_exists() here, it wi...
[ "def", "state", "(", "name", ",", "path", "=", "None", ")", ":", "# Don't use _ensure_exists() here, it will mess with _change_state()", "cachekey", "=", "'lxc.state.{0}{1}'", ".", "format", "(", "name", ",", "path", ")", "try", ":", "return", "__context__", "[", ...
30.325581
0.000743
def func_interpolate_na(interpolator, x, y, **kwargs): '''helper function to apply interpolation along 1 dimension''' # it would be nice if this wasn't necessary, works around: # "ValueError: assignment destination is read-only" in assignment below out = y.copy() nans = pd.isnull(y) nonans = ~n...
[ "def", "func_interpolate_na", "(", "interpolator", ",", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "# it would be nice if this wasn't necessary, works around:", "# \"ValueError: assignment destination is read-only\" in assignment below", "out", "=", "y", ".", "copy", ...
31.352941
0.001821
def logparse(*args, **kwargs): """ Parse access log on the terminal application. If list of files are given, parse each file. Otherwise, parse standard input. :param args: supporting functions after processed raw log line :type: list of callables :rtype: tuple of (statistics, key/value report) ...
[ "def", "logparse", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "clitool", ".", "cli", "import", "clistream", "from", "clitool", ".", "processor", "import", "SimpleDictReporter", "lst", "=", "[", "parse", "]", "+", "args", "reporter", "="...
34.3125
0.001773
def call_historic(self, result_callback=None, kwargs=None, proc=None): """Call the hook with given ``kwargs`` for all registered plugins and for all plugins which will be registered afterwards. If ``result_callback`` is not ``None`` it will be called for for each non-None result obtaine...
[ "def", "call_historic", "(", "self", ",", "result_callback", "=", "None", ",", "kwargs", "=", "None", ",", "proc", "=", "None", ")", ":", "if", "proc", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"Support for `proc` argument is now deprecated and...
39.807692
0.001887
def delete(self, key): """ Remove a key from the cache. """ if key in self.cache: self.cache.pop(key, None)
[ "def", "delete", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "cache", ":", "self", ".", "cache", ".", "pop", "(", "key", ",", "None", ")" ]
24.333333
0.013245
def guest_reboot(self, userid): """Reboot a guest vm.""" LOG.info("Begin to reboot vm %s", userid) self._smtclient.guest_reboot(userid) LOG.info("Complete reboot vm %s", userid)
[ "def", "guest_reboot", "(", "self", ",", "userid", ")", ":", "LOG", ".", "info", "(", "\"Begin to reboot vm %s\"", ",", "userid", ")", "self", ".", "_smtclient", ".", "guest_reboot", "(", "userid", ")", "LOG", ".", "info", "(", "\"Complete reboot vm %s\"", "...
41
0.009569
def partition(iterable, chunk_size, pad_none=False): """adapted from Toolz. Breaks an iterable into n iterables up to the certain chunk size, padding with Nones if availble. Example: >>> from searchtweets.utils import partition >>> iter_ = range(10) >>> list(partition(iter_, 3)) ...
[ "def", "partition", "(", "iterable", ",", "chunk_size", ",", "pad_none", "=", "False", ")", ":", "args", "=", "[", "iter", "(", "iterable", ")", "]", "*", "chunk_size", "if", "not", "pad_none", ":", "return", "zip", "(", "*", "args", ")", "else", ":"...
35.117647
0.001631
def interp3d_core(x,y,t,Z,xout,yout,tout,**kwargs): """ INTERP3D : Interpolate values from a 3D matrix along a 1D trajectory @param x: 1st dimension vector of size NX @param y: 2nd dimension vector of size NY @param t: 3rd dimension vector of size NT @author: Renaud DUSSURG...
[ "def", "interp3d_core", "(", "x", ",", "y", ",", "t", ",", "Z", ",", "xout", ",", "yout", ",", "tout", ",", "*", "*", "kwargs", ")", ":", "#this below can take a very LOOOOOONG time\r", "gx", "=", "np", ".", "reshape", "(", "np", ".", "repeat", "(", ...
37.304348
0.043182
def Cache(fn): """ Function cache decorator """ def fnCache(*args, **kwargs): """ Cache function """ key = (args and tuple(args) or None, kwargs and frozenset(kwargs.items()) or None) if key not in fn.__cached__: fn.__cached__[key] = cache = fn(*args, **kwargs) else: ...
[ "def", "Cache", "(", "fn", ")", ":", "def", "fnCache", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\" Cache function \"\"\"", "key", "=", "(", "args", "and", "tuple", "(", "args", ")", "or", "None", ",", "kwargs", "and", "frozenset", "(...
28.590909
0.029231
def parse_int_list(string): """ Parses a string of numbers and ranges into a list of integers. Ranges are separated by dashes and inclusive of both the start and end number. Example: parse_int_list("8 9 10,11-13") == [8,9,10,11,12,13] """ integers = [] for comma_part in string.split...
[ "def", "parse_int_list", "(", "string", ")", ":", "integers", "=", "[", "]", "for", "comma_part", "in", "string", ".", "split", "(", "\",\"", ")", ":", "for", "substring", "in", "comma_part", ".", "split", "(", "\" \"", ")", ":", "if", "len", "(", "s...
35.666667
0.0013
def hailstone(n): """Return the 'hailstone sequence' from n to 1 n: The starting point of the hailstone sequence """ sequence = [n] while n > 1: if n%2 != 0: n = 3*n + 1 else: n = int(n/2) sequence.append(n) return sequence
[ "def", "hailstone", "(", "n", ")", ":", "sequence", "=", "[", "n", "]", "while", "n", ">", "1", ":", "if", "n", "%", "2", "!=", "0", ":", "n", "=", "3", "*", "n", "+", "1", "else", ":", "n", "=", "int", "(", "n", "/", "2", ")", "sequenc...
19.384615
0.034091
def create_role_config_group(self, name, display_name, role_type): """ Create a role config group. @param name: The name of the new group. @param display_name: The display name of the new group. @param role_type: The role type of the new group. @return: New ApiRoleConfigGroup object. @since...
[ "def", "create_role_config_group", "(", "self", ",", "name", ",", "display_name", ",", "role_type", ")", ":", "return", "role_config_groups", ".", "create_role_config_group", "(", "self", ".", "_get_resource_root", "(", ")", ",", "self", ".", "name", ",", "name"...
37.769231
0.001988
def initialTrendSmoothingFactors(self, timeSeries): """ Calculate the initial Trend smoothing Factor b0. Explanation: http://en.wikipedia.org/wiki/Exponential_smoothing#Triple_exponential_smoothing :return: Returns the initial trend smoothing factor b0 """ result...
[ "def", "initialTrendSmoothingFactors", "(", "self", ",", "timeSeries", ")", ":", "result", "=", "0.0", "seasonLength", "=", "self", ".", "get_parameter", "(", "\"seasonLength\"", ")", "k", "=", "min", "(", "len", "(", "timeSeries", ")", "-", "seasonLength", ...
44.266667
0.00885
def FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'): """ Unpool the input with a fixed matrix to perform kronecker product with. Args: x (tf.Tensor): a 4D image tensor shape: int or (h, w) tuple unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape. ...
[ "def", "FixedUnPooling", "(", "x", ",", "shape", ",", "unpool_mat", "=", "None", ",", "data_format", "=", "'channels_last'", ")", ":", "data_format", "=", "get_data_format", "(", "data_format", ",", "keras_mode", "=", "False", ")", "shape", "=", "shape2d", "...
38.52
0.002025
def run(name, onlyif=None, unless=None, creates=None, cwd=None, root=None, runas=None, shell=None, env=None, prepend_path=None, stateful=False, umask=None, output_loglevel='debug', hide_output=False, timeout=...
[ "def", "run", "(", "name", ",", "onlyif", "=", "None", ",", "unless", "=", "None", ",", "creates", "=", "None", ",", "cwd", "=", "None", ",", "root", "=", "None", ",", "runas", "=", "None", ",", "shell", "=", "None", ",", "env", "=", "None", ",...
33.150171
0.001
def _getPattern(self, ipattern, done=None): """Parses sort pattern. :ipattern: A pattern to parse. :done: If :ipattern: refers to done|undone, use this to indicate proper state. :returns: A pattern suitable for Model.modify. """ if ipattern is None: ...
[ "def", "_getPattern", "(", "self", ",", "ipattern", ",", "done", "=", "None", ")", ":", "if", "ipattern", "is", "None", ":", "return", "None", "if", "ipattern", "is", "True", ":", "if", "done", "is", "not", "None", ":", "return", "(", "[", "(", "No...
32.887324
0.000832
def update_agent_db_refs(self, agent, agent_text, do_rename=True): """Update db_refs of agent using the grounding map If the grounding map is missing one of the HGNC symbol or Uniprot ID, attempts to reconstruct one from the other. Parameters ---------- agent : :py:clas...
[ "def", "update_agent_db_refs", "(", "self", ",", "agent", ",", "agent_text", ",", "do_rename", "=", "True", ")", ":", "map_db_refs", "=", "deepcopy", "(", "self", ".", "gm", ".", "get", "(", "agent_text", ")", ")", "self", ".", "standardize_agent_db_refs", ...
44.727273
0.001326
def _filter_xpath_grouping(xpath): """ This method removes the outer parentheses for xpath grouping. The xpath converter will break otherwise. Example: "(//button[@type='submit'])[1]" becomes "//button[@type='submit'][1]" """ # First remove the first open parentheses xpath = xpath[1:] ...
[ "def", "_filter_xpath_grouping", "(", "xpath", ")", ":", "# First remove the first open parentheses", "xpath", "=", "xpath", "[", "1", ":", "]", "# Next remove the last closed parentheses", "index", "=", "xpath", ".", "rfind", "(", "')'", ")", "if", "index", "==", ...
31.411765
0.001818
def iter_(obj): """A custom replacement for iter(), dispatching a few custom picklable iterators for known types. """ if six.PY2: file_types = file, # noqa if six.PY3: file_types = io.IOBase, dict_items = {}.items().__class__ dict_values = {}.values().__class__ ...
[ "def", "iter_", "(", "obj", ")", ":", "if", "six", ".", "PY2", ":", "file_types", "=", "file", ",", "# noqa", "if", "six", ".", "PY3", ":", "file_types", "=", "io", ".", "IOBase", ",", "dict_items", "=", "{", "}", ".", "items", "(", ")", ".", "...
35.925926
0.001004
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a data connector into this object. ''' self.connector_id = node.getAttributeNS(RTS_NS, 'connectorId') self.name = node.getAttributeNS(RTS_NS, 'name') self.data_type = node.getAttributeNS(RTS_NS,...
[ "def", "parse_xml_node", "(", "self", ",", "node", ")", ":", "self", ".", "connector_id", "=", "node", ".", "getAttributeNS", "(", "RTS_NS", ",", "'connectorId'", ")", "self", ".", "name", "=", "node", ".", "getAttributeNS", "(", "RTS_NS", ",", "'name'", ...
50.414634
0.001898
def all_features(): ''' Returns dictionary of all features in the module .. note:: Some of the features (hist4, corr) are relatively expensive to compute ''' features = {'mean': mean, 'median': median, 'gmean': gmean, 'hmean': hmean, 'vec_...
[ "def", "all_features", "(", ")", ":", "features", "=", "{", "'mean'", ":", "mean", ",", "'median'", ":", "median", ",", "'gmean'", ":", "gmean", ",", "'hmean'", ":", "hmean", ",", "'vec_sum'", ":", "vec_sum", ",", "'abs_sum'", ":", "abs_sum", ",", "'ab...
36.272727
0.001627
def _append_html(self, html, before_prompt=False): """ Appends HTML at the end of the console buffer. """ self._append_custom(self._insert_html, html, before_prompt)
[ "def", "_append_html", "(", "self", ",", "html", ",", "before_prompt", "=", "False", ")", ":", "self", ".", "_append_custom", "(", "self", ".", "_insert_html", ",", "html", ",", "before_prompt", ")" ]
46.5
0.010582
def format_rangefield_nodes(field_name, field, field_id, state, lineno): """Create a section node that documents a RangeField config field. Parameters ---------- field_name : `str` Name of the configuration field (the attribute name of on the config class). field : ``lsst.pex.config...
[ "def", "format_rangefield_nodes", "(", "field_name", ",", "field", ",", "field_id", ",", "state", ",", "lineno", ")", ":", "# Field type", "field_type_item", "=", "nodes", ".", "definition_list_item", "(", ")", "field_type_item", ".", "append", "(", "nodes", "."...
35.758065
0.000439
def _wrapped_call(wrap_controller, func): """ Wrap calling to a function with a generator which needs to yield exactly once. The yield point will trigger calling the wrapped function and return its ``_Result`` to the yield point. The generator then needs to finish (raise StopIteration) in order for th...
[ "def", "_wrapped_call", "(", "wrap_controller", ",", "func", ")", ":", "try", ":", "next", "(", "wrap_controller", ")", "# first yield", "except", "StopIteration", ":", "_raise_wrapfail", "(", "wrap_controller", ",", "\"did not yield\"", ")", "call_outcome", "=", ...
41.705882
0.001379
def container_delete(name, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Delete a container name : Name of the container to delete remote_addr : An URL to a remote Server, you also have to give cert and key if you provide remote_addr and its...
[ "def", "container_delete", "(", "name", ",", "remote_addr", "=", "None", ",", "cert", "=", "None", ",", "key", "=", "None", ",", "verify_cert", "=", "True", ")", ":", "container", "=", "container_get", "(", "name", ",", "remote_addr", ",", "cert", ",", ...
24.763158
0.001022
def set_timeout(self, timeout): """ Set Screen Timeout Duration """ if timeout > 0: self.timeout = timeout self.server.request("screen_set %s timeout %i" % (self.ref, (self.timeout * 8)))
[ "def", "set_timeout", "(", "self", ",", "timeout", ")", ":", "if", "timeout", ">", "0", ":", "self", ".", "timeout", "=", "timeout", "self", ".", "server", ".", "request", "(", "\"screen_set %s timeout %i\"", "%", "(", "self", ".", "ref", ",", "(", "se...
37.166667
0.013158
def is_dir(value): """ This function checks whether given path as argument exists. :param str value: Assumed directory path :rtype: str :return: If given value is valid, retuning given value. """ value = os.path.expanduser(value) value = os.path.expandvars(value) value = os.path.absp...
[ "def", "is_dir", "(", "value", ")", ":", "value", "=", "os", ".", "path", ".", "expanduser", "(", "value", ")", "value", "=", "os", ".", "path", ".", "expandvars", "(", "value", ")", "value", "=", "os", ".", "path", ".", "abspath", "(", "value", ...
33.548387
0.000935
def present( name, user=None, fingerprint=None, key=None, port=None, enc=None, config=None, hash_known_hosts=True, timeout=5, fingerprint_hash_type=None): ''' Verifies that the specified host is known by the specified user On m...
[ "def", "present", "(", "name", ",", "user", "=", "None", ",", "fingerprint", "=", "None", ",", "key", "=", "None", ",", "port", "=", "None", ",", "enc", "=", "None", ",", "config", "=", "None", ",", "hash_known_hosts", "=", "True", ",", "timeout", ...
37.666667
0.00176
def onerror(self, emitter, message, source, lineno, colno): """ WebPage Event that occurs on webpage errors """ self._log.debug("""App.onerror event occurred in webpage: \nMESSAGE:%s\nSOURCE:%s\nLINENO:%s\nCOLNO:%s\n"""%(message, source, lineno, colno))
[ "def", "onerror", "(", "self", ",", "emitter", ",", "message", ",", "source", ",", "lineno", ",", "colno", ")", ":", "self", ".", "_log", ".", "debug", "(", "\"\"\"App.onerror event occurred in webpage: \n \\nMESSAGE:%s\\nSOURCE:%s\\nLINENO:%s\\nCOLNO:%s\\n\"\"...
57.2
0.017241
def release_client(self, cb): """ Return a Connection object to the pool :param Connection cb: the client to release """ cb.stop_using() self._q.put(cb, True)
[ "def", "release_client", "(", "self", ",", "cb", ")", ":", "cb", ".", "stop_using", "(", ")", "self", ".", "_q", ".", "put", "(", "cb", ",", "True", ")" ]
28.571429
0.009709
def angularjs(parser, token): """ Conditionally switch between AngularJS and Django variable expansion for ``{{`` and ``}}`` keeping Django's expansion for ``{%`` and ``%}`` Usage:: {% angularjs 1 %} or simply {% angularjs %} {% process variables through the AngularJS template engi...
[ "def", "angularjs", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "len", "(", "bits", ")", "<", "2", ":", "bits", ".", "append", "(", "'1'", ")", "values", "=", "[", "parser", ".", "...
37.897436
0.001319
def reduce_dict(input_dict, average=True): """ Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values in the dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fi...
[ "def", "reduce_dict", "(", "input_dict", ",", "average", "=", "True", ")", ":", "world_size", "=", "get_world_size", "(", ")", "if", "world_size", "<", "2", ":", "return", "input_dict", "with", "torch", ".", "no_grad", "(", ")", ":", "names", "=", "[", ...
37.777778
0.001912
def best_sell_3(self): """三日均價由上往下 """ return self.data.continuous(self.data.moving_average(self.data.price, 3)) == -1
[ "def", "best_sell_3", "(", "self", ")", ":", "return", "self", ".", "data", ".", "continuous", "(", "self", ".", "data", ".", "moving_average", "(", "self", ".", "data", ".", "price", ",", "3", ")", ")", "==", "-", "1" ]
34.75
0.021127
def noise(params, amplitude=1, offset=0): ''' Generate a noise signal :param params: buffer parameters, controls length of signal created :param amplitude: wave amplitude (array or value) :param offset: offset of wave mean from zero (array or value) :return: array of resulting signal ''' ...
[ "def", "noise", "(", "params", ",", "amplitude", "=", "1", ",", "offset", "=", "0", ")", ":", "amplitude", "=", "create_buffer", "(", "params", ",", "amplitude", ")", "offset", "=", "create_buffer", "(", "params", ",", "offset", ")", "output", "=", "of...
40.75
0.002
def line_segment_intersection_2D(p12arg, p34arg): ''' line_segment_intersection((a, b), (c, d)) yields the intersection point between the line passing through points a and b and the line segment that passes from point c to point d. If there is no intersection point, then (numpy.nan, numpy.nan) is return...
[ "def", "line_segment_intersection_2D", "(", "p12arg", ",", "p34arg", ")", ":", "(", "p1", ",", "p2", ")", "=", "p12arg", "(", "p3", ",", "p4", ")", "=", "p34arg", "pi", "=", "np", ".", "asarray", "(", "line_intersection_2D", "(", "p12arg", ",", "p34arg...
45.870968
0.020661
def demux2(data, chunkfiles, cutters, longbar, matchdict, ipyclient): """ Submit chunks to be sorted by the barmatch() function then calls putstats(). """ ## parallel stuff, limit to 1/4 of available cores for RAM limits. start = time.time() printstr = ' sorting reads | {} | s1 |'...
[ "def", "demux2", "(", "data", ",", "chunkfiles", ",", "cutters", ",", "longbar", ",", "matchdict", ",", "ipyclient", ")", ":", "## parallel stuff, limit to 1/4 of available cores for RAM limits.", "start", "=", "time", ".", "time", "(", ")", "printstr", "=", "' so...
33.927536
0.009963
def parse_formula(fml_file): """ Parse and return MaxSAT formula. """ if re.search('\.wcnf(\.(gz|bz2|lzma|xz))?$', fml_file): fml = WCNF(from_file=fml_file) else: # expecting '*.cnf' fml = CNF(from_file=fml_file).weighted() return fml
[ "def", "parse_formula", "(", "fml_file", ")", ":", "if", "re", ".", "search", "(", "'\\.wcnf(\\.(gz|bz2|lzma|xz))?$'", ",", "fml_file", ")", ":", "fml", "=", "WCNF", "(", "from_file", "=", "fml_file", ")", "else", ":", "# expecting '*.cnf'", "fml", "=", "CNF...
24.636364
0.010676
def __expire_files(self): """Because files are always unclean""" self.__files = OrderedDict( item for item in self.__files.items() if not item[1].expired )
[ "def", "__expire_files", "(", "self", ")", ":", "self", ".", "__files", "=", "OrderedDict", "(", "item", "for", "item", "in", "self", ".", "__files", ".", "items", "(", ")", "if", "not", "item", "[", "1", "]", ".", "expired", ")" ]
31.166667
0.010417
def _load_permissions(self): """Load permissions associated to actions.""" result = _P(needs=set(), excludes=set()) if not self.allow_by_default: result.needs.update(self.explicit_needs) for explicit_need in self.explicit_needs: if explicit_need.method == 'action...
[ "def", "_load_permissions", "(", "self", ")", ":", "result", "=", "_P", "(", "needs", "=", "set", "(", ")", ",", "excludes", "=", "set", "(", ")", ")", "if", "not", "self", ".", "allow_by_default", ":", "result", ".", "needs", ".", "update", "(", "...
37.681818
0.001176
def images(self, name=None, os=None, version=None, public=None, state=None, owner=None, type=None): """ :: GET /:login/images :param name: match on the listed name :type name: :py:class:`basestring` :param os: match on the s...
[ "def", "images", "(", "self", ",", "name", "=", "None", ",", "os", "=", "None", ",", "version", "=", "None", ",", "public", "=", "None", ",", "state", "=", "None", ",", "owner", "=", "None", ",", "type", "=", "None", ")", ":", "params", "=", "{...
31.96
0.010322
def convert_exception(from_exception, to_exception, *to_args, **to_kw): """ Decorator: Catch exception ``from_exception`` and instead raise ``to_exception(*to_args, **to_kw)``. Useful when modules you're using in a method throw their own errors that you want to convert to your own exceptions that you h...
[ "def", "convert_exception", "(", "from_exception", ",", "to_exception", ",", "*", "to_args", ",", "*", "*", "to_kw", ")", ":", "def", "wrapper", "(", "fn", ")", ":", "def", "fn_new", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "try", ":", "ret...
28.813953
0.002342
def fix_multi_T1w_source_name(in_files): """ Make up a generic source name when there are multiple T1s >>> fix_multi_T1w_source_name([ ... '/path/to/sub-045_ses-test_T1w.nii.gz', ... '/path/to/sub-045_ses-retest_T1w.nii.gz']) '/path/to/sub-045_T1w.nii.gz' """ import os from...
[ "def", "fix_multi_T1w_source_name", "(", "in_files", ")", ":", "import", "os", "from", "nipype", ".", "utils", ".", "filemanip", "import", "filename_to_list", "base", ",", "in_file", "=", "os", ".", "path", ".", "split", "(", "filename_to_list", "(", "in_files...
36.266667
0.001792
def _repr_tty_(self) -> str: """Return a summary of this sample sheet in a TTY compatible codec.""" header_description = ['Sample_ID', 'Description'] header_samples = [ 'Sample_ID', 'Sample_Name', 'Library_ID', 'index', 'index2', ...
[ "def", "_repr_tty_", "(", "self", ")", "->", "str", ":", "header_description", "=", "[", "'Sample_ID'", ",", "'Description'", "]", "header_samples", "=", "[", "'Sample_ID'", ",", "'Sample_Name'", ",", "'Library_ID'", ",", "'index'", ",", "'index2'", ",", "]", ...
38.224138
0.00088
def repos(self): """View or enabled or disabled repositories """ def_cnt, cus_cnt = 0, 0 print("") self.msg.template(78) print("{0}{1}{2}{3}{4}{5}{6}".format( "| Repo id", " " * 2, "Repo URL", " " * 44, "Default", " " * 3, "...
[ "def", "repos", "(", "self", ")", ":", "def_cnt", ",", "cus_cnt", "=", "0", ",", "0", "print", "(", "\"\"", ")", "self", ".", "msg", ".", "template", "(", "78", ")", "print", "(", "\"{0}{1}{2}{3}{4}{5}{6}\"", ".", "format", "(", "\"| Repo id\"", ",", ...
42.459459
0.001245
def setbit(self, key, offset, bit): """Sets or clears the bit at offset in the string value stored at key. The bit is either set or cleared depending on value, which can be either 0 or 1. When key does not exist, a new string value is created. The string is grown to make sure it can hol...
[ "def", "setbit", "(", "self", ",", "key", ",", "offset", ",", "bit", ")", ":", "if", "0", "<", "bit", ">", "1", ":", "raise", "ValueError", "(", "'bit must be 1 or 0, not {}'", ".", "format", "(", "bit", ")", ")", "return", "self", ".", "_execute", "...
51.72973
0.001026
def complete_watch(self, text, *_): """ Autocomplete for watch """ return [t + " " for t in self.engine.cached_descriptions if t.startswith(text)]
[ "def", "complete_watch", "(", "self", ",", "text", ",", "*", "_", ")", ":", "return", "[", "t", "+", "\" \"", "for", "t", "in", "self", ".", "engine", ".", "cached_descriptions", "if", "t", ".", "startswith", "(", "text", ")", "]" ]
53.333333
0.018519
def is_prime(n, mr_rounds=25): """Test whether n is probably prime See <https://en.wikipedia.org/wiki/Primality_test#Probabilistic_tests> Arguments: n (int): the number to be tested mr_rounds (int, optional): number of Miller-Rabin iterations to run; defaults to 25 iterations, ...
[ "def", "is_prime", "(", "n", ",", "mr_rounds", "=", "25", ")", ":", "# as an optimization we quickly detect small primes using the list above", "if", "n", "<=", "first_primes", "[", "-", "1", "]", ":", "return", "n", "in", "first_primes", "# for small dividors (relati...
39.347826
0.001079
def update_pipe_channel(self, uid, channel_name, label): # pylint: disable=unused-argument ''' Update this consumer to listen on channel_name for the js widget associated with uid ''' pipe_group_name = _form_pipe_channel_name(channel_name) if self.channel_layer: curr...
[ "def", "update_pipe_channel", "(", "self", ",", "uid", ",", "channel_name", ",", "label", ")", ":", "# pylint: disable=unused-argument", "pipe_group_name", "=", "_form_pipe_channel_name", "(", "channel_name", ")", "if", "self", ".", "channel_layer", ":", "current", ...
47.571429
0.010309
def unpurge(*packages): ''' Change package selection for each package specified to 'install' CLI Example: .. code-block:: bash salt '*' lowpkg.unpurge curl ''' if not packages: return {} old = __salt__['pkg.list_pkgs'](purge_desired=True) ret = {} __salt__['cmd.run...
[ "def", "unpurge", "(", "*", "packages", ")", ":", "if", "not", "packages", ":", "return", "{", "}", "old", "=", "__salt__", "[", "'pkg.list_pkgs'", "]", "(", "purge_desired", "=", "True", ")", "ret", "=", "{", "}", "__salt__", "[", "'cmd.run'", "]", ...
27.217391
0.001543
def setPrivates(self, fieldDict) : """will set self._id, self._rev and self._key field.""" for priv in self.privates : if priv in fieldDict : setattr(self, priv, fieldDict[priv]) else : setattr(self, priv, None) if self._i...
[ "def", "setPrivates", "(", "self", ",", "fieldDict", ")", ":", "for", "priv", "in", "self", ".", "privates", ":", "if", "priv", "in", "fieldDict", ":", "setattr", "(", "self", ",", "priv", ",", "fieldDict", "[", "priv", "]", ")", "else", ":", "setatt...
35.272727
0.022613
def _write_csv(filepath, data, kwargs): """See documentation of mpu.io.write.""" kwargs_open = {'newline': ''} mode = 'w' if sys.version_info < (3, 0): kwargs_open.pop('newline', None) mode = 'wb' with open(filepath, mode, **kwargs_open) as fp: if 'delimiter' not in kwargs: ...
[ "def", "_write_csv", "(", "filepath", ",", "data", ",", "kwargs", ")", ":", "kwargs_open", "=", "{", "'newline'", ":", "''", "}", "mode", "=", "'w'", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", ":", "kwargs_open", ".", "pop", "(...
34.625
0.001757
def sorted_nicely(l): """ Sort the given iterable in the way that humans expect. http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ """ convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] r...
[ "def", "sorted_nicely", "(", "l", ")", ":", "convert", "=", "lambda", "text", ":", "int", "(", "text", ")", "if", "text", ".", "isdigit", "(", ")", "else", "text", "alphanum_key", "=", "lambda", "key", ":", "[", "convert", "(", "c", ")", "for", "c"...
43.5
0.025352
def insert_string_at_line(input_file: str, string_to_be_inserted: str, put_at_line_number: int, output_file: str, append: bool = True, newline_character: str = '\n'): r"""Write a string ...
[ "def", "insert_string_at_line", "(", "input_file", ":", "str", ",", "string_to_be_inserted", ":", "str", ",", "put_at_line_number", ":", "int", ",", "output_file", ":", "str", ",", "append", ":", "bool", "=", "True", ",", "newline_character", ":", "str", "=", ...
40.719512
0.000292
def add_actions(target, actions, insert_before=None): """Add actions to a QMenu or a QToolBar.""" previous_action = None target_actions = list(target.actions()) if target_actions: previous_action = target_actions[-1] if previous_action.isSeparator(): previous_action = ...
[ "def", "add_actions", "(", "target", ",", "actions", ",", "insert_before", "=", "None", ")", ":", "previous_action", "=", "None", "target_actions", "=", "list", "(", "target", ".", "actions", "(", ")", ")", "if", "target_actions", ":", "previous_action", "="...
41.694444
0.001302
def send(self, request, ordered=False): """ This method enqueues the given request to be sent. Its send state will be saved until a response arrives, and a ``Future`` that will be resolved when the response arrives will be returned: .. code-block:: python async def ...
[ "def", "send", "(", "self", ",", "request", ",", "ordered", "=", "False", ")", ":", "if", "not", "self", ".", "_user_connected", ":", "raise", "ConnectionError", "(", "'Cannot send requests while disconnected'", ")", "if", "not", "utils", ".", "is_list_like", ...
38.926829
0.001222
def main(args=sys.argv): """ main entry point for the manifest CLI """ if len(args) < 2: return usage("Command expected") command = args[1] rest = args[2:] if "create".startswith(command): return cli_create(rest) elif "query".startswith(command): return cli_que...
[ "def", "main", "(", "args", "=", "sys", ".", "argv", ")", ":", "if", "len", "(", "args", ")", "<", "2", ":", "return", "usage", "(", "\"Command expected\"", ")", "command", "=", "args", "[", "1", "]", "rest", "=", "args", "[", "2", ":", "]", "i...
23.421053
0.00216
def matches(self, verb, params): """ Test if the method matches the provided set of arguments :param verb: HTTP verb. Uppercase :type verb: str :param params: Existing route parameters :type params: set :returns: Whether this view matches :rtype: bool """...
[ "def", "matches", "(", "self", ",", "verb", ",", "params", ")", ":", "return", "(", "self", ".", "ifset", "is", "None", "or", "self", ".", "ifset", "<=", "params", ")", "and", "(", "self", ".", "ifnset", "is", "None", "or", "self", ".", "ifnset", ...
40.384615
0.009311
def set_dimensional_calibrations(self, dimensional_calibrations: typing.List[CalibrationModule.Calibration]) -> None: """Set the dimensional calibrations. :param dimensional_calibrations: A list of calibrations, must match the dimensions of the data. .. versionadded:: 1.0 Scriptable: ...
[ "def", "set_dimensional_calibrations", "(", "self", ",", "dimensional_calibrations", ":", "typing", ".", "List", "[", "CalibrationModule", ".", "Calibration", "]", ")", "->", "None", ":", "self", ".", "__data_item", ".", "set_dimensional_calibrations", "(", "dimensi...
40.6
0.009639
def add(self, name, proc_cls, **kwargs): """ Add a function implementation fo the library. :param name: The name of the function as a string :param proc_cls: The implementation of the function as a SimProcedure _class_, not instance :param kwargs: Any additional p...
[ "def", "add", "(", "self", ",", "name", ",", "proc_cls", ",", "*", "*", "kwargs", ")", ":", "self", ".", "procedures", "[", "name", "]", "=", "proc_cls", "(", "display_name", "=", "name", ",", "*", "*", "kwargs", ")" ]
51.333333
0.008511
def integrations(since, to, write, force): """ Generates a markdown file containing the list of integrations shipped in a given Agent release. Agent version numbers are derived inspecting tags on `integrations-core` so running this tool might provide unexpected results if the repo is not up to date ...
[ "def", "integrations", "(", "since", ",", "to", ",", "write", ",", "force", ")", ":", "agent_tags", "=", "get_agent_tags", "(", "since", ",", "to", ")", "# get the list of integrations shipped with the agent from the requirements file", "req_file_name", "=", "os", "."...
46.914286
0.002387
def pass_from_pipe(cls): """Return password from pipe if not on TTY, else False. """ is_pipe = not sys.stdin.isatty() return is_pipe and cls.strip_last_newline(sys.stdin.read())
[ "def", "pass_from_pipe", "(", "cls", ")", ":", "is_pipe", "=", "not", "sys", ".", "stdin", ".", "isatty", "(", ")", "return", "is_pipe", "and", "cls", ".", "strip_last_newline", "(", "sys", ".", "stdin", ".", "read", "(", ")", ")" ]
41
0.009569
def _arrange_fields(self, channels, sampfrom=0, expanded=False): """ Arrange/edit object fields to reflect user channel and/or signal range input. Parameters ---------- channels : list List of channel numbers specified. sampfrom : int, optional ...
[ "def", "_arrange_fields", "(", "self", ",", "channels", ",", "sampfrom", "=", "0", ",", "expanded", "=", "False", ")", ":", "# Rearrange signal specification fields", "for", "field", "in", "_header", ".", "SIGNAL_SPECS", ".", "index", ":", "item", "=", "getatt...
37.705882
0.002027
def get_motd(self, server=None): """ Gets the server's MOTD. Optional arguments: * server=None - Server to get the MOTD of. """ with self.lock: if not server: self.send('MOTD') else: self.send('MOTD %s' % server) ...
[ "def", "get_motd", "(", "self", ",", "server", "=", "None", ")", ":", "with", "self", ".", "lock", ":", "if", "not", "server", ":", "self", ".", "send", "(", "'MOTD'", ")", "else", ":", "self", ".", "send", "(", "'MOTD %s'", "%", "server", ")", "...
31.28
0.002481
def _exclude_ipv4_networks(self, networks, networks_to_exclude): """ Exclude the list of networks from another list of networks and return a flat list of new networks. :param networks: List of IPv4 networks to exclude from :param networks_to_exclude: List of IPv4 networks to exc...
[ "def", "_exclude_ipv4_networks", "(", "self", ",", "networks", ",", "networks_to_exclude", ")", ":", "for", "network_to_exclude", "in", "networks_to_exclude", ":", "def", "_exclude_ipv4_network", "(", "network", ")", ":", "\"\"\"\n Exclude a single network fr...
42.047619
0.001107
def inquire_property(name, doc=None): """Creates a property based on an inquire result This method creates a property that calls the :python:`_inquire` method, and return the value of the requested information. Args: name (str): the name of the 'inquire' result information Returns: ...
[ "def", "inquire_property", "(", "name", ",", "doc", "=", "None", ")", ":", "def", "inquire_property", "(", "self", ")", ":", "if", "not", "self", ".", "_started", ":", "msg", "=", "(", "\"Cannot read {0} from a security context whose \"", "\"establishment has not ...
29.652174
0.00142
def _process_table_cells(self, table): """ Compile all the table cells. Returns a list of rows. The rows may have different lengths because of column spans. """ rows = [] for i, tr in enumerate(table.find_all('tr')): row = [] for c in tr.conte...
[ "def", "_process_table_cells", "(", "self", ",", "table", ")", ":", "rows", "=", "[", "]", "for", "i", ",", "tr", "in", "enumerate", "(", "table", ".", "find_all", "(", "'tr'", ")", ")", ":", "row", "=", "[", "]", "for", "c", "in", "tr", ".", "...
26.967742
0.002309
def computeNodeValues(cls, graph): """ Compute the value (size) of each node by summing the associated links. """ for node in graph['nodes']: source_val = np.sum([l['value'] for l in node['sourceLinks']]) target_val = np.sum([l['value'] for l in node['targetLinks'...
[ "def", "computeNodeValues", "(", "cls", ",", "graph", ")", ":", "for", "node", "in", "graph", "[", "'nodes'", "]", ":", "source_val", "=", "np", ".", "sum", "(", "[", "l", "[", "'value'", "]", "for", "l", "in", "node", "[", "'sourceLinks'", "]", "]...
46.75
0.010499
def token_new(): """Create new token.""" form = TokenForm(request.form) form.scopes.choices = current_oauth2server.scope_choices() if form.validate_on_submit(): t = Token.create_personal( form.data['name'], current_user.get_id(), scopes=form.scopes.data ) db.session....
[ "def", "token_new", "(", ")", ":", "form", "=", "TokenForm", "(", "request", ".", "form", ")", "form", ".", "scopes", ".", "choices", "=", "current_oauth2server", ".", "scope_choices", "(", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "t"...
30.8
0.001575
def post(self, request, *args, **kwargs): """The only circumstances when we POST is to submit the main form, both updating translations (if any changed) and advancing to the next page of messages. There is no notion of validation of this content; as implemented, unknown fields a...
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# The message text inputs are captured as hashes of their initial", "# contents, preceded by \"m_\". Messages with plurals end with their", "# variation number.", "single_text_input_...
46.696774
0.002435
def list_rows(self,rowList=None,table=None,verbose=None): """ Returns the list of primary keys for each of the rows in the specified table. :param rowList (string, optional): Specifies a list of rows. The pattern CO LUMN:VALUE sets this parameter to any rows that contain the specifi...
[ "def", "list_rows", "(", "self", ",", "rowList", "=", "None", ",", "table", "=", "None", ",", "verbose", "=", "None", ")", ":", "PARAMS", "=", "set_param", "(", "[", "'rowList'", ",", "'table'", "]", ",", "[", "rowList", ",", "table", "]", ")", "re...
58.588235
0.017787