text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def create_developer_certificate(self, authorization, body, **kwargs): # noqa: E501 """Create a new developer certificate to connect to the bootstrap server. # noqa: E501 This REST API is intended to be used by customers to get a developer certificate (a certificate that can be flashed into multiple ...
[ "def", "create_developer_certificate", "(", "self", ",", "authorization", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", ...
86.636364
0.001038
def deploy(self): ''' Creates a link at the original path of this target ''' if not os.path.exists(self.path): makedirs(self.path) link(self.vault_path, self.real_path)
[ "def", "deploy", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "path", ")", ":", "makedirs", "(", "self", ".", "path", ")", "link", "(", "self", ".", "vault_path", ",", "self", ".", "real_path", ")" ]
27.25
0.008889
def delete_jail(name): ''' Deletes poudriere jail with `name` CLI Example: .. code-block:: bash salt '*' poudriere.delete_jail 90amd64 ''' if is_jail(name): cmd = 'poudriere jail -d -j {0}'.format(name) __salt__['cmd.run'](cmd) # Make sure jail is gone ...
[ "def", "delete_jail", "(", "name", ")", ":", "if", "is_jail", "(", "name", ")", ":", "cmd", "=", "'poudriere jail -d -j {0}'", ".", "format", "(", "name", ")", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", "# Make sure jail is gone", "if", "is_jail", ...
28.939394
0.001013
def open_tablebase(directory: PathLike, *, load_wdl: bool = True, load_dtz: bool = True, max_fds: Optional[int] = 128, VariantBoard: Type[chess.Board] = chess.Board) -> Tablebase: """ Opens a collection of tables for probing. See :class:`~chess.syzygy.Tablebase`. .. note:: Generally probing re...
[ "def", "open_tablebase", "(", "directory", ":", "PathLike", ",", "*", ",", "load_wdl", ":", "bool", "=", "True", ",", "load_dtz", ":", "bool", "=", "True", ",", "max_fds", ":", "Optional", "[", "int", "]", "=", "128", ",", "VariantBoard", ":", "Type", ...
49.882353
0.002315
def imageOperation(image1, operation, image2=None): """ Perform operations with ``vtkImageData`` objects. `image2` can be a constant value. Possible operations are: ``+``, ``-``, ``/``, ``1/x``, ``sin``, ``cos``, ``exp``, ``log``, ``abs``, ``**2``, ``sqrt``, ``min``, ``max``, ``atan``, ``atan2``, ...
[ "def", "imageOperation", "(", "image1", ",", "operation", ",", "image2", "=", "None", ")", ":", "op", "=", "operation", ".", "lower", "(", ")", "if", "op", "in", "[", "\"median\"", "]", ":", "mf", "=", "vtk", ".", "vtkImageMedian3D", "(", ")", "mf", ...
28.587719
0.001186
def decompose_graph(g, heuristic='tour', max_odds=20, verbose=0): '''Decompose a graph into a set of non-overlapping trails.''' # Get the connected subgraphs subgraphs = [nx.subgraph(g, x).copy() for x in nx.connected_components(g)] chains = [] num_subgraphs = len(subgraphs) step = 0 while ...
[ "def", "decompose_graph", "(", "g", ",", "heuristic", "=", "'tour'", ",", "max_odds", "=", "20", ",", "verbose", "=", "0", ")", ":", "# Get the connected subgraphs", "subgraphs", "=", "[", "nx", ".", "subgraph", "(", "g", ",", "x", ")", ".", "copy", "(...
38.932432
0.00237
def from_directory(input_dir, optional_files=None): """ Read in a set of VASP input from a directory. Note that only the standard INCAR, POSCAR, POTCAR and KPOINTS files are read unless optional_filenames is specified. Args: input_dir (str): Directory to read VASP in...
[ "def", "from_directory", "(", "input_dir", ",", "optional_files", "=", "None", ")", ":", "sub_d", "=", "{", "}", "for", "fname", ",", "ftype", "in", "[", "(", "\"INCAR\"", ",", "Incar", ")", ",", "(", "\"KPOINTS\"", ",", "Kpoints", ")", ",", "(", "\"...
46.695652
0.001825
def can_use_widgets(): """ Expanded from from http://stackoverflow.com/a/34092072/1958900 """ if 'IPython' not in sys.modules: # IPython hasn't been imported, definitely not return False from IPython import get_ipython # check for `kernel` attribute on the IPython instance if ge...
[ "def", "can_use_widgets", "(", ")", ":", "if", "'IPython'", "not", "in", "sys", ".", "modules", ":", "# IPython hasn't been imported, definitely not", "return", "False", "from", "IPython", "import", "get_ipython", "# check for `kernel` attribute on the IPython instance", "i...
26.210526
0.001938
def do_EOF(self, args): """Exit on system end of file character""" if _debug: ConsoleCmd._debug("do_EOF %r", args) return self.do_exit(args)
[ "def", "do_EOF", "(", "self", ",", "args", ")", ":", "if", "_debug", ":", "ConsoleCmd", ".", "_debug", "(", "\"do_EOF %r\"", ",", "args", ")", "return", "self", ".", "do_exit", "(", "args", ")" ]
40.25
0.018293
def get_bounding_box(self, crs): """Gets bounding box as GeoVector in a specified CRS.""" return self.from_bounds(*self.get_bounds(crs), crs=crs)
[ "def", "get_bounding_box", "(", "self", ",", "crs", ")", ":", "return", "self", ".", "from_bounds", "(", "*", "self", ".", "get_bounds", "(", "crs", ")", ",", "crs", "=", "crs", ")" ]
53
0.012422
def all(cls, name, hash_key, range_key=None, throughput=None): """ Create an index that projects all attributes """ return cls(cls.ALL, name, hash_key, range_key, throughput=throughput)
[ "def", "all", "(", "cls", ",", "name", ",", "hash_key", ",", "range_key", "=", "None", ",", "throughput", "=", "None", ")", ":", "return", "cls", "(", "cls", ".", "ALL", ",", "name", ",", "hash_key", ",", "range_key", ",", "throughput", "=", "through...
66.333333
0.00995
def action_filter(method_name, *args, **kwargs): """ Creates an effect that will call the action's method with the current value and specified arguments and keywords. @param method_name: the name of method belonging to the action. @type method_name: str """ def action_filter(value, context,...
[ "def", "action_filter", "(", "method_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "action_filter", "(", "value", ",", "context", ",", "*", "*", "_params", ")", ":", "method", "=", "getattr", "(", "context", "[", "\"action\"", "]",...
35
0.002141
def toProtocolElement(self): """ Returns the GA4GH protocol representation of this Reference. """ reference = protocol.Reference() reference.id = self.getId() reference.is_derived = self.getIsDerived() reference.length = self.getLength() reference.md5check...
[ "def", "toProtocolElement", "(", "self", ")", ":", "reference", "=", "protocol", ".", "Reference", "(", ")", "reference", ".", "id", "=", "self", ".", "getId", "(", ")", "reference", ".", "is_derived", "=", "self", ".", "getIsDerived", "(", ")", "referen...
43.5
0.00225
def parse_single(str_): """ Very simple parser to parse expressions represent some single values. :param str_: a string to parse :return: Int | Bool | String >>> parse_single(None) '' >>> parse_single("0") 0 >>> parse_single("123") 123 >>> parse_single("True") True ...
[ "def", "parse_single", "(", "str_", ")", ":", "if", "str_", "is", "None", ":", "return", "''", "str_", "=", "str_", ".", "strip", "(", ")", "if", "not", "str_", ":", "return", "''", "if", "BOOL_PATTERN", ".", "match", "(", "str_", ")", "is", "not",...
20.613636
0.001053
def set_id(self,pid): """ Set the property identifier @type pid: string @param pid: property identifier """ if self.type == 'KAF': return self.node.set('pid',pid) elif self.type == 'NAF': return self.node.set('id',pid)
[ "def", "set_id", "(", "self", ",", "pid", ")", ":", "if", "self", ".", "type", "==", "'KAF'", ":", "return", "self", ".", "node", ".", "set", "(", "'pid'", ",", "pid", ")", "elif", "self", ".", "type", "==", "'NAF'", ":", "return", "self", ".", ...
29
0.020067
def temporary_object_path(self, name): """ Returns the path to a temporary object, before we know its hash. """ return os.path.join(self._path, self.TMP_OBJ_DIR, name)
[ "def", "temporary_object_path", "(", "self", ",", "name", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "self", ".", "TMP_OBJ_DIR", ",", "name", ")" ]
39
0.01005
async def stoplisten(self, connmark = -1): ''' Can call without delegate ''' if connmark is None: connmark = self.connmark self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.STOPLISTEN, True, connmark))
[ "async", "def", "stoplisten", "(", "self", ",", "connmark", "=", "-", "1", ")", ":", "if", "connmark", "is", "None", ":", "connmark", "=", "self", ".", "connmark", "self", ".", "scheduler", ".", "emergesend", "(", "ConnectionControlEvent", "(", "self", "...
39.285714
0.017794
def render(self, name, value, attrs=None, **kwargs): """Widget render method.""" min_score = zxcvbn_min_score() message_title = _('Warning') message_body = _( 'This password would take ' '<em class="password_strength_time"></em> to crack.') strength_marku...
[ "def", "render", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "min_score", "=", "zxcvbn_min_score", "(", ")", "message_title", "=", "_", "(", "'Warning'", ")", "message_body", "=", "_", "(", "'...
35.818182
0.001235
def populate(cls, graph): """ populate an rdflib graph with these curies """ [graph.bind(k, v) for k, v in cls._dict.items()]
[ "def", "populate", "(", "cls", ",", "graph", ")", ":", "[", "graph", ".", "bind", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "cls", ".", "_dict", ".", "items", "(", ")", "]" ]
46.333333
0.014184
async def xgroup_del_consumer(self, name: str, group: str, consumer: str) -> int: """ [NOTICE] Not officially released yet XGROUP is used in order to create, destroy and manage consumer groups. :param name: name of the stream :param group: name of the consumer group :para...
[ "async", "def", "xgroup_del_consumer", "(", "self", ",", "name", ":", "str", ",", "group", ":", "str", ",", "consumer", ":", "str", ")", "->", "int", ":", "return", "await", "self", ".", "execute_command", "(", "'XGROUP DELCONSUMER'", ",", "name", ",", "...
49.222222
0.008869
def build_listen(self, listen_node): """parse `listen` sections, and return a config.Listen Args: listen_node (TreeNode): Description Returns: config.Listen: an object """ proxy_name = listen_node.listen_header.proxy_name.text service_address_nod...
[ "def", "build_listen", "(", "self", ",", "listen_node", ")", ":", "proxy_name", "=", "listen_node", ".", "listen_header", ".", "proxy_name", ".", "text", "service_address_node", "=", "listen_node", ".", "listen_header", ".", "service_address", "# parse the config bloc...
36
0.001591
def plot_average(sdat, lovs): """Plot time averaged profiles. Args: sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance. lovs (nested list of str): nested list of profile names such as the one produced by :func:`stagpy.misc.list_of_vars`. Other Parameters: ...
[ "def", "plot_average", "(", "sdat", ",", "lovs", ")", ":", "steps_iter", "=", "iter", "(", "sdat", ".", "walk", ".", "filter", "(", "rprof", "=", "True", ")", ")", "try", ":", "step", "=", "next", "(", "steps_iter", ")", "except", "StopIteration", ":...
29.75
0.000678
def freq_from_iterators(cls, iterators): """ Returns the frequency corresponding to the given iterators """ return { set(it): f for f, it in cls.FREQUENCIES.items()}[set(iterators)]
[ "def", "freq_from_iterators", "(", "cls", ",", "iterators", ")", ":", "return", "{", "set", "(", "it", ")", ":", "f", "for", "f", ",", "it", "in", "cls", ".", "FREQUENCIES", ".", "items", "(", ")", "}", "[", "set", "(", "iterators", ")", "]" ]
36.666667
0.008889
def simulate_static(self, steps, time, solution = solve_type.FAST, collect_dynamic = False): """! @brief Performs static simulation of oscillatory network. @param[in] steps (uint): Number steps of simulations during simulation. @param[in] time (double): Time of simulation. ...
[ "def", "simulate_static", "(", "self", ",", "steps", ",", "time", ",", "solution", "=", "solve_type", ".", "FAST", ",", "collect_dynamic", "=", "False", ")", ":", "if", "(", "self", ".", "_ccore_network_pointer", "is", "not", "None", ")", ":", "ccore_insta...
43.217391
0.020167
def resistor_max_actuation_readings(control_board, frequencies, oscope_reading_func): ''' For each resistor in the high-voltage feedback resistor bank, read the board measured voltage and the oscilloscope measured voltage for an actuation voltage that nearly saturates...
[ "def", "resistor_max_actuation_readings", "(", "control_board", ",", "frequencies", ",", "oscope_reading_func", ")", ":", "# Set board amplifier gain to 1.", "# __NB__ This is likely _far_ lower than the actual gain _(which may be a", "# factor of several hundred)_..", "control_board", "...
46.846154
0.000643
def write(self, values, data=None): """ Write reaction info to db file Parameters ---------- values: dict The values dict can include: {'chemical_composition': str (chemical composition on empty slab) , 'surface_composition': str (reduced chemical compos...
[ "def", "write", "(", "self", ",", "values", ",", "data", "=", "None", ")", ":", "con", "=", "self", ".", "connection", "or", "self", ".", "_connect", "(", ")", "self", ".", "_initialize", "(", "con", ")", "cur", "=", "con", ".", "cursor", "(", ")...
35.741573
0.000612
def from_note(cls, note): """ Construct a :class:`Tone` from a musical note which must consist of a capital letter A through G, followed by an optional semi-tone modifier ("b" for flat, "#" for sharp, or their Unicode equivalents), followed by an octave number (0 through 9). ...
[ "def", "from_note", "(", "cls", ",", "note", ")", ":", "if", "isinstance", "(", "note", ",", "bytes", ")", ":", "note", "=", "note", ".", "decode", "(", "'ascii'", ")", "if", "isinstance", "(", "note", ",", "str", ")", ":", "match", "=", "Tone", ...
45.173913
0.001885
def daily_hours(self,local=False): """ This returns a number from 0 to 24 that describes the number of hours passed in a day. This is very useful for hr.attendances """ data = self.get(local) daily_hours = (data.hour + data.minute / 60.0 + ...
[ "def", "daily_hours", "(", "self", ",", "local", "=", "False", ")", ":", "data", "=", "self", ".", "get", "(", "local", ")", "daily_hours", "=", "(", "data", ".", "hour", "+", "data", ".", "minute", "/", "60.0", "+", "data", ".", "second", "/", "...
42.111111
0.010336
def get_tornado_apps(context, debug=False): """ Create Tornado's application for all interfaces which are defined in the configuration. *context* is instance of the :class:`shelter.core.context.Context`. If *debug* is :const:`True`, server will be run in **DEBUG** mode. Return :class:`list` of the ...
[ "def", "get_tornado_apps", "(", "context", ",", "debug", "=", "False", ")", ":", "if", "context", ".", "config", ".", "app_settings_handler", ":", "app_settings_handler", "=", "import_object", "(", "context", ".", "config", ".", "app_settings_handler", ")", "set...
34.777778
0.001036
def _cover2exprs(inputs, noutputs, cover): """Convert a cover to a tuple of Expression instances.""" fs = list() for i in range(noutputs): terms = list() for invec, outvec in cover: if outvec[i]: term = list() for j, v in enumerate(inputs): ...
[ "def", "_cover2exprs", "(", "inputs", ",", "noutputs", ",", "cover", ")", ":", "fs", "=", "list", "(", ")", "for", "i", "in", "range", "(", "noutputs", ")", ":", "terms", "=", "list", "(", ")", "for", "invec", ",", "outvec", "in", "cover", ":", "...
33.235294
0.001721
def createMultipleL4L2ColumnsWithTopology(network, networkConfig): """ Create a network consisting of multiple columns. Each column contains one L4 and one L2, is identical in structure to the network created by createL4L2Column. In addition the L2 columns are connected to each other through their lateral in...
[ "def", "createMultipleL4L2ColumnsWithTopology", "(", "network", ",", "networkConfig", ")", ":", "numCorticalColumns", "=", "networkConfig", "[", "\"numCorticalColumns\"", "]", "output_lateral_connections", "=", "[", "[", "]", "for", "i", "in", "xrange", "(", "numCorti...
39.921569
0.008387
def check_agency( feed: "Feed", *, as_df: bool = False, include_warnings: bool = False ) -> List: """ Check that ``feed.agency`` follows the GTFS. Return a list of problems of the form described in :func:`check_table`; the list will be empty if no problems are found. """ table = "agency"...
[ "def", "check_agency", "(", "feed", ":", "\"Feed\"", ",", "*", ",", "as_df", ":", "bool", "=", "False", ",", "include_warnings", ":", "bool", "=", "False", ")", "->", "List", ":", "table", "=", "\"agency\"", "problems", "=", "[", "]", "# Preliminary chec...
28.213115
0.000561
def _kurtosis(self, x, z, d=0): """ returns the kurtosis parameter for direction d, d=0 is rho, d=1 is z """ val = self._poly(z, self._kurtosis_coeffs(d)) return (np.tanh(val)+1)/12.*(3 - 6*x**2 + x**4)
[ "def", "_kurtosis", "(", "self", ",", "x", ",", "z", ",", "d", "=", "0", ")", ":", "val", "=", "self", ".", "_poly", "(", "z", ",", "self", ".", "_kurtosis_coeffs", "(", "d", ")", ")", "return", "(", "np", ".", "tanh", "(", "val", ")", "+", ...
55.75
0.013274
def xml_to_dict(xml_bytes: bytes, tags: list=[], array_tags: list=[], int_tags: list=[], strip_namespaces: bool=True, parse_attributes: bool=True, value_key: str='@', attribute_prefix: str='@', document_tag: bool=False) -> dict: """ Parses XML string to dict. In c...
[ "def", "xml_to_dict", "(", "xml_bytes", ":", "bytes", ",", "tags", ":", "list", "=", "[", "]", ",", "array_tags", ":", "list", "=", "[", "]", ",", "int_tags", ":", "list", "=", "[", "]", ",", "strip_namespaces", ":", "bool", "=", "True", ",", "pars...
44.016129
0.010036
def IncrementErrorCount(self, category): """Bumps the module's error statistic.""" self.error_count += 1 if self.counting in ('toplevel', 'detailed'): if self.counting != 'detailed': category = category.split('/')[0] if category not in self.errors_by_category: self.errors_by_cate...
[ "def", "IncrementErrorCount", "(", "self", ",", "category", ")", ":", "self", ".", "error_count", "+=", "1", "if", "self", ".", "counting", "in", "(", "'toplevel'", ",", "'detailed'", ")", ":", "if", "self", ".", "counting", "!=", "'detailed'", ":", "cat...
41.666667
0.010444
def wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd, ab, xdirect, msrc, mrec, use_ne_eval): r"""Calculate wavenumber domain solution. Return the wavenumber domain solutions ``PJ0``, ``PJ1``, and ``PJ0b``, which have to be transformed with a Hankel transform to the f...
[ "def", "wavenumber", "(", "zsrc", ",", "zrec", ",", "lsrc", ",", "lrec", ",", "depth", ",", "etaH", ",", "etaV", ",", "zetaH", ",", "zetaV", ",", "lambd", ",", "ab", ",", "xdirect", ",", "msrc", ",", "mrec", ",", "use_ne_eval", ")", ":", "# ** CALC...
37.626506
0.000312
def make_lastbeat(peer_uid, app_id): """ Prepares the last beat UDP packet (when the peer is going away) Format : Little endian * Kind of beat (1 byte) * Peer UID length (2 bytes) * Peer UID (variable, UTF-8) * Application ID length (2 bytes) * Application ID (variable, UTF-8) :par...
[ "def", "make_lastbeat", "(", "peer_uid", ",", "app_id", ")", ":", "packet", "=", "struct", ".", "pack", "(", "\"<BB\"", ",", "PACKET_FORMAT_VERSION", ",", "PACKET_TYPE_LASTBEAT", ")", "for", "string", "in", "(", "peer_uid", ",", "app_id", ")", ":", "string_b...
30.772727
0.001433
def rowmap(table, rowmapper, header, failonerror=False): """ Transform rows via an arbitrary function. E.g.:: >>> import petl as etl >>> table1 = [['id', 'sex', 'age', 'height', 'weight'], ... [1, 'male', 16, 1.45, 62.0], ... [2, 'female', 19, 1.34, 55.4], ...
[ "def", "rowmap", "(", "table", ",", "rowmapper", ",", "header", ",", "failonerror", "=", "False", ")", ":", "return", "RowMapView", "(", "table", ",", "rowmapper", ",", "header", ",", "failonerror", "=", "failonerror", ")" ]
47.833333
0.000488
def clean_aliases(ctx, force_yes): """ Removes aliases from your config file that point to inactive projects. """ inactive_aliases = [] for (alias, mapping) in six.iteritems(aliases_database): # Ignore local aliases if mapping.mapping is None: continue project =...
[ "def", "clean_aliases", "(", "ctx", ",", "force_yes", ")", ":", "inactive_aliases", "=", "[", "]", "for", "(", "alias", ",", "mapping", ")", "in", "six", ".", "iteritems", "(", "aliases_database", ")", ":", "# Ignore local aliases", "if", "mapping", ".", "...
35.121212
0.00084
def _record_buffer(records, buffer_size=DEFAULT_BUFFER_SIZE): """ Buffer for transform functions which require multiple passes through data. Value returned by context manager is a function which returns an iterator through records. """ with tempfile.SpooledTemporaryFile(buffer_size, mode='wb+')...
[ "def", "_record_buffer", "(", "records", ",", "buffer_size", "=", "DEFAULT_BUFFER_SIZE", ")", ":", "with", "tempfile", ".", "SpooledTemporaryFile", "(", "buffer_size", ",", "mode", "=", "'wb+'", ")", "as", "tf", ":", "pickler", "=", "pickle", ".", "Pickler", ...
30.772727
0.001433
def to_html(self, codebase): """ Convert this to HTML. """ html = '' def build_line(key, include_pred, format_fn): val = getattr(self, key) if include_pred(val): return '<dt>%s</dt><dd>%s</dd>\n' % (printable(key), format_fn(val)) ...
[ "def", "to_html", "(", "self", ",", "codebase", ")", ":", "html", "=", "''", "def", "build_line", "(", "key", ",", "include_pred", ",", "format_fn", ")", ":", "val", "=", "getattr", "(", "self", ",", "key", ")", "if", "include_pred", "(", "val", ")",...
41.4
0.008499
def get_graph(self, directed=True): """Returns a NetworkX multi-graph instance built from the result set :param directed: boolean, optional (default=`True`). Whether to create a direted or an undirected graph. """ if nx is None: raise ImportError("Try installing ...
[ "def", "get_graph", "(", "self", ",", "directed", "=", "True", ")", ":", "if", "nx", "is", "None", ":", "raise", "ImportError", "(", "\"Try installing NetworkX first.\"", ")", "if", "directed", ":", "graph", "=", "nx", ".", "MultiDiGraph", "(", ")", "else"...
40.730769
0.001845
def call(self, *values, **named_values): """ Call an expression to evaluate it at the given point. Future improvements: I would like if func and signature could be buffered after the first call so they don't have to be recalculated for every call. However, nothing can be stored on self as sympy use...
[ "def", "call", "(", "self", ",", "*", "values", ",", "*", "*", "named_values", ")", ":", "independent_vars", ",", "params", "=", "seperate_symbols", "(", "self", ")", "# Convert to a pythonic function", "func", "=", "sympy_to_py", "(", "self", ",", "independen...
52.022222
0.008805
def match(cls, pattern, inverse=False): """Factory method to create a StringFilter which filters with the given pattern.""" string_pattern = pattern invert_search = inverse class DefinedStringFilter(cls): pattern = string_pattern inverse = invert_search r...
[ "def", "match", "(", "cls", ",", "pattern", ",", "inverse", "=", "False", ")", ":", "string_pattern", "=", "pattern", "invert_search", "=", "inverse", "class", "DefinedStringFilter", "(", "cls", ")", ":", "pattern", "=", "string_pattern", "inverse", "=", "in...
37.444444
0.008696
def del_edge(self, edge): """ Remove an edge from the graph. @type edge: tuple @param edge: Edge. """ u, v = edge self.node_neighbors[u].remove(v) self.del_edge_labeling((u, v)) if (u != v): self.node_neighbors[v].remove(u) ...
[ "def", "del_edge", "(", "self", ",", "edge", ")", ":", "u", ",", "v", "=", "edge", "self", ".", "node_neighbors", "[", "u", "]", ".", "remove", "(", "v", ")", "self", ".", "del_edge_labeling", "(", "(", "u", ",", "v", ")", ")", "if", "(", "u", ...
26.307692
0.008475
def project(dest, app_bundle, force, dev, admin, api, celery, graphene, mail, oauth, security, session, sqlalchemy, webpack): """ Create a new Flask Unchained project. """ if os.path.exists(dest) and os.listdir(dest) and not force: if not click.confirm(f'WARNING: Project ...
[ "def", "project", "(", "dest", ",", "app_bundle", ",", "force", ",", "dev", ",", "admin", ",", "api", ",", "celery", ",", "graphene", ",", "mail", ",", "oauth", ",", "security", ",", "session", ",", "sqlalchemy", ",", "webpack", ")", ":", "if", "os",...
39.860465
0.001708
def sortByName(self): """Qt Override.""" self.shortcuts = sorted(self.shortcuts, key=lambda x: x.context+'/'+x.name) self.reset()
[ "def", "sortByName", "(", "self", ")", ":", "self", ".", "shortcuts", "=", "sorted", "(", "self", ".", "shortcuts", ",", "key", "=", "lambda", "x", ":", "x", ".", "context", "+", "'/'", "+", "x", ".", "name", ")", "self", ".", "reset", "(", ")" ]
37
0.010582
def set_objective(model, value, additive=False): """Set the model objective. Parameters ---------- model : cobra model The model to set the objective for value : model.problem.Objective, e.g. optlang.glpk_interface.Objective, sympy.Basic or dict If the model objective is...
[ "def", "set_objective", "(", "model", ",", "value", ",", "additive", "=", "False", ")", ":", "interface", "=", "model", ".", "problem", "reverse_value", "=", "model", ".", "solver", ".", "objective", ".", "expression", "reverse_value", "=", "interface", ".",...
38.746269
0.000376
def rgb_to_yuv(r, g=None, b=None): """Convert the color from RGB coordinates to YUV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, u, v) tuple in the range: y[0...1], ...
[ "def", "rgb_to_yuv", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "y", "=", "(", "r", "*", "0.29900", ")", "...
23.107143
0.014837
def translate_js_with_compilation_plan(js, HEADER=DEFAULT_HEADER): """js has to be a javascript source code. returns equivalent python code. compile plans only work with the following restrictions: - only enabled for oneliner expressions - when there are comments in the js code string s...
[ "def", "translate_js_with_compilation_plan", "(", "js", ",", "HEADER", "=", "DEFAULT_HEADER", ")", ":", "match_increaser_str", ",", "match_increaser_num", ",", "compilation_plan", "=", "get_compilation_plan", "(", "js", ")", "cp_hash", "=", "hashlib", ".", "md5", "(...
35.955556
0.002407
def maximize_dockwidget(self, restore=False): """Shortcut: Ctrl+Alt+Shift+M First call: maximize current dockwidget Second call (or restore=True): restore original window layout""" if self.state_before_maximizing is None: if restore: return ...
[ "def", "maximize_dockwidget", "(", "self", ",", "restore", "=", "False", ")", ":", "if", "self", ".", "state_before_maximizing", "is", "None", ":", "if", "restore", ":", "return", "# Select plugin to maximize\r", "self", ".", "state_before_maximizing", "=", "self"...
50.96
0.001155
def identify_core(core): """Identify the polynomial argument.""" for datatype, identifier in { int: _identify_scaler, numpy.int8: _identify_scaler, numpy.int16: _identify_scaler, numpy.int32: _identify_scaler, numpy.int64: _identify_scaler, ...
[ "def", "identify_core", "(", "core", ")", ":", "for", "datatype", ",", "identifier", "in", "{", "int", ":", "_identify_scaler", ",", "numpy", ".", "int8", ":", "_identify_scaler", ",", "numpy", ".", "int16", ":", "_identify_scaler", ",", "numpy", ".", "int...
36.608696
0.001157
def schedule(self, callback, timeout=100): '''Schedule a function to be called repeated time. This method can be used to perform animations. **Example** This is a typical way to perform an animation, just:: from chemlab.graphics.qt import QtViewer ...
[ "def", "schedule", "(", "self", ",", "callback", ",", "timeout", "=", "100", ")", ":", "timer", "=", "QTimer", "(", "self", ")", "timer", ".", "timeout", ".", "connect", "(", "callback", ")", "timer", ".", "start", "(", "timeout", ")", "return", "tim...
30.395349
0.008895
def assure_container(fnc): """ Assures that whether a Container or a name of a container is passed, a Container object is available. """ @wraps(fnc) def _wrapped(self, container, *args, **kwargs): if not isinstance(container, Container): # Must be the name contain...
[ "def", "assure_container", "(", "fnc", ")", ":", "@", "wraps", "(", "fnc", ")", "def", "_wrapped", "(", "self", ",", "container", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "container", ",", "Container", ")",...
33.833333
0.002398
def signup_verify(request, uidb36=None, token=None): """ View for the link in the verification email sent to a new user when they create an account and ``ACCOUNTS_VERIFICATION_REQUIRED`` is set to ``True``. Activates the user and logs them in, redirecting to the URL they tried to access when signing...
[ "def", "signup_verify", "(", "request", ",", "uidb36", "=", "None", ",", "token", "=", "None", ")", ":", "user", "=", "authenticate", "(", "uidb36", "=", "uidb36", ",", "token", "=", "token", ",", "is_active", "=", "False", ")", "if", "user", "is", "...
40.764706
0.00141
def _bdtr(k, n, p): """The binomial cumulative distribution function. Args: k: floating point `Tensor`. n: floating point `Tensor`. p: floating point `Tensor`. Returns: `sum_{j=0}^k p^j (1 - p)^(n - j)`. """ # Trick for getting safe backprop/gradients into n, k when # betainc(a = 0, ..) ...
[ "def", "_bdtr", "(", "k", ",", "n", ",", "p", ")", ":", "# Trick for getting safe backprop/gradients into n, k when", "# betainc(a = 0, ..) = nan", "# Write:", "# where(unsafe, safe_output, betainc(where(unsafe, safe_input, input)))", "ones", "=", "tf", ".", "ones_like", "(...
28.9
0.018425
def verify(self, h, sig, sig_fmt=SER_BINARY): """ Verifies that `sig' is a signature for a message with SHA-512 hash `h'. """ s = deserialize_number(sig, sig_fmt) return self.p._ECDSA_verify(h, s)
[ "def", "verify", "(", "self", ",", "h", ",", "sig", ",", "sig_fmt", "=", "SER_BINARY", ")", ":", "s", "=", "deserialize_number", "(", "sig", ",", "sig_fmt", ")", "return", "self", ".", "p", ".", "_ECDSA_verify", "(", "h", ",", "s", ")" ]
45.6
0.008621
def Vc(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[SURF]): r'''This function handles the retrieval of a chemical's critical volume. Lookup is based on CASRNs. Will automatically select a data source to use if no Method is provided; returns None if the data is not available. Prefered ...
[ "def", "Vc", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ",", "IgnoreMethods", "=", "[", "SURF", "]", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "_crit_IUPAC", "...
49.130178
0.001062
def emit(msg_dict): ''' Extracts the details from the syslog message and returns an object having the following structure: .. code-block:: python { u'users': { u'user': { u'luke': { u'action': { ...
[ "def", "emit", "(", "msg_dict", ")", ":", "log", ".", "debug", "(", "'Evaluating the message dict:'", ")", "log", ".", "debug", "(", "msg_dict", ")", "ret", "=", "{", "}", "extracted", "=", "napalm_logs", ".", "utils", ".", "extract", "(", "_RGX", ",", ...
32.181818
0.001828
def generate_build_file(startpath, outfilename=DEFAULT_BUILDFILE): """ Generate a build file (yaml) based on the contents of a directory tree. """ buildfilepath = os.path.join(startpath, outfilename) if os.path.exists(buildfilepath): raise BuildException("Build file %s already exists." %...
[ "def", "generate_build_file", "(", "startpath", ",", "outfilename", "=", "DEFAULT_BUILDFILE", ")", ":", "buildfilepath", "=", "os", ".", "path", ".", "join", "(", "startpath", ",", "outfilename", ")", "if", "os", ".", "path", ".", "exists", "(", "buildfilepa...
36.785714
0.001894
def text_badness(text): u''' Look for red flags that text is encoded incorrectly: Obvious problems: - The replacement character \ufffd, indicating a decoding error - Unassigned or private-use Unicode characters Very weird things: - Adjacent letters from two different scripts - Letters ...
[ "def", "text_badness", "(", "text", ")", ":", "assert", "isinstance", "(", "text", ",", "str", ")", "errors", "=", "0", "very_weird_things", "=", "0", "weird_things", "=", "0", "prev_letter_script", "=", "None", "unicodedata_name", "=", "unicodedata", ".", "...
37.4375
0.000407
def _make_file_handle(self, row_idx): """Build and return a `FileHandle` object from an `astropy.table.row.Row` """ row = self._table[row_idx] return FileHandle.create_from_row(row)
[ "def", "_make_file_handle", "(", "self", ",", "row_idx", ")", ":", "row", "=", "self", ".", "_table", "[", "row_idx", "]", "return", "FileHandle", ".", "create_from_row", "(", "row", ")" ]
50.5
0.014634
def _populate_blotto_payoff_arrays(payoff_arrays, actions, values): """ Populate the ndarrays in `payoff_arrays` with the payoff values of the Blotto game with h hills and t troops. Parameters ---------- payoff_arrays : tuple(ndarray(float, ndim=2)) Tuple of 2 ndarrays of shape (n, n), ...
[ "def", "_populate_blotto_payoff_arrays", "(", "payoff_arrays", ",", "actions", ",", "values", ")", ":", "n", ",", "h", "=", "actions", ".", "shape", "payoffs", "=", "np", ".", "empty", "(", "2", ")", "for", "i", "in", "range", "(", "n", ")", ":", "fo...
37.322581
0.000842
def json(self, data): """Set the POST/PUT body content in JSON format for this request.""" if data is not None: self._body = json.dumps(data) self.add_header('Content-Type', 'application/json')
[ "def", "json", "(", "self", ",", "data", ")", ":", "if", "data", "is", "not", "None", ":", "self", ".", "_body", "=", "json", ".", "dumps", "(", "data", ")", "self", ".", "add_header", "(", "'Content-Type'", ",", "'application/json'", ")" ]
45.8
0.008584
def list_refs(profile, ref_type=None): """List all refs. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. ref_type ...
[ "def", "list_refs", "(", "profile", ",", "ref_type", "=", "None", ")", ":", "resource", "=", "\"/refs\"", "if", "ref_type", ":", "resource", "+=", "\"/\"", "+", "ref_type", "data", "=", "api", ".", "get_request", "(", "profile", ",", "resource", ")", "re...
29
0.001335
def timeseries(self): """ Load time series It returns the actual time series used in power flow analysis. If :attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise, :meth:`timeseries()` looks for time series of the according sector in :class:`~.grid.network.Ti...
[ "def", "timeseries", "(", "self", ")", ":", "if", "self", ".", "_timeseries", "is", "None", ":", "if", "isinstance", "(", "self", ".", "grid", ",", "MVGrid", ")", ":", "voltage_level", "=", "'mv'", "elif", "isinstance", "(", "self", ".", "grid", ",", ...
34.964912
0.000976
def copy(self): """ Convenience method to get a copy of the structure, with options to add site properties. Returns: A copy of the Structure, with optionally new site_properties and optionally sanitized. """ return GrainBoundary(self.lattice, self...
[ "def", "copy", "(", "self", ")", ":", "return", "GrainBoundary", "(", "self", ".", "lattice", ",", "self", ".", "species_and_occu", ",", "self", ".", "frac_coords", ",", "self", ".", "rotation_axis", ",", "self", ".", "rotation_angle", ",", "self", ".", ...
46.538462
0.009724
def get(self, id: int) -> AssetClass: """ Loads Asset Class """ self.open_session() item = self.session.query(AssetClass).filter( AssetClass.id == id).first() return item
[ "def", "get", "(", "self", ",", "id", ":", "int", ")", "->", "AssetClass", ":", "self", ".", "open_session", "(", ")", "item", "=", "self", ".", "session", ".", "query", "(", "AssetClass", ")", ".", "filter", "(", "AssetClass", ".", "id", "==", "id...
34.833333
0.009346
def tables(self): """ A list containing the tables in this container, in document order. Read-only. """ from .table import Table return [Table(tbl, self) for tbl in self._element.tbl_lst]
[ "def", "tables", "(", "self", ")", ":", "from", ".", "table", "import", "Table", "return", "[", "Table", "(", "tbl", ",", "self", ")", "for", "tbl", "in", "self", ".", "_element", ".", "tbl_lst", "]" ]
32.714286
0.008511
def ssh_directory_for_unit(application_name, user=None): """Return the directory used to store ssh assets for the application. :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str :...
[ "def", "ssh_directory_for_unit", "(", "application_name", ",", "user", "=", "None", ")", ":", "if", "user", ":", "application_name", "=", "\"{}_{}\"", ".", "format", "(", "application_name", ",", "user", ")", "_dir", "=", "os", ".", "path", ".", "join", "(...
36.047619
0.001287
def joined_units(self): """ A list view of all the units joined on this relation. This is actually a :class:`~charms.reactive.endpoints.CombinedUnitsView`, so the units will be in order by unit name, and you can access a merged view of all of the units' data with ``self....
[ "def", "joined_units", "(", "self", ")", ":", "if", "self", ".", "_units", "is", "None", ":", "self", ".", "_units", "=", "CombinedUnitsView", "(", "[", "RelatedUnit", "(", "self", ",", "unit_name", ")", "for", "unit_name", "in", "sorted", "(", "hookenv"...
45.709677
0.002073
def ConsoleLogHandler(loggerRef='', handler=None, level=logging.DEBUG, color=None): """Add a handler to stderr with our custom formatter to a logger.""" if isinstance(loggerRef, logging.Logger): pass elif isinstance(loggerRef, str): # check for root if not loggerRef: log...
[ "def", "ConsoleLogHandler", "(", "loggerRef", "=", "''", ",", "handler", "=", "None", ",", "level", "=", "logging", ".", "DEBUG", ",", "color", "=", "None", ")", ":", "if", "isinstance", "(", "loggerRef", ",", "logging", ".", "Logger", ")", ":", "pass"...
31.435897
0.001582
def _get_run_info_dict(self, run_id): """Get the RunInfo for a run, as a dict.""" run_info_path = os.path.join(self._settings.info_dir, run_id, 'info') if os.path.exists(run_info_path): # We copy the RunInfo as a dict, so we can add stuff to it to pass to the template. return RunInfo(run_info_pa...
[ "def", "_get_run_info_dict", "(", "self", ",", "run_id", ")", ":", "run_info_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_settings", ".", "info_dir", ",", "run_id", ",", "'info'", ")", "if", "os", ".", "path", ".", "exists", "(", "...
44.75
0.013699
def mod_replace(match, sphinx_modules): """Convert Sphinx ``:mod:`` to plain reST link. Args: match (_sre.SRE_Match): A match (from ``re``) to be used in substitution. sphinx_modules (list): List to be track the modules that have been encountered. Returns: s...
[ "def", "mod_replace", "(", "match", ",", "sphinx_modules", ")", ":", "sphinx_modules", ".", "append", "(", "match", ".", "group", "(", "\"module\"", ")", ")", "return", "\"`{}`_\"", ".", "format", "(", "match", ".", "group", "(", "\"value\"", ")", ")" ]
32.142857
0.00216
def bytes_to_int(bytes_, width = None): """ .. _bytes_to_int: Converts the ``bytes`` object ``bytes_`` to an ``int``. If ``width`` is none, ``width = len(byte_) * 8`` is choosen. See also: int_to_bytes_ *Example* >>> from py_register_machine2.engine_tools.conversions import * >>> i = 4012 >>> int_to_bytes(...
[ "def", "bytes_to_int", "(", "bytes_", ",", "width", "=", "None", ")", ":", "if", "(", "width", "==", "None", ")", ":", "width", "=", "len", "(", "bytes_", ")", "else", ":", "width", "=", "width", "//", "8", "if", "(", "width", ">", "len", "(", ...
22.285714
0.041475
def gatherInput(**Config): r"""Helps to interactively get user input. """ _type = Config.get('type') while True: try: got = raw_input('%s: ' % getLabel(Config)) except EOFError: got = None if not got and 'default' in Config: return Config['default'] try: return _type(...
[ "def", "gatherInput", "(", "*", "*", "Config", ")", ":", "_type", "=", "Config", ".", "get", "(", "'type'", ")", "while", "True", ":", "try", ":", "got", "=", "raw_input", "(", "'%s: '", "%", "getLabel", "(", "Config", ")", ")", "except", "EOFError",...
19.565217
0.021186
def basic_auth(credentials): """Create an HTTP basic authentication callable Parameters ---------- credentials: ~typing.Tuple[str, str] The (username, password)-tuple Returns ------- ~typing.Callable[[Request], Request] A callable which adds basic authentication to a :class...
[ "def", "basic_auth", "(", "credentials", ")", ":", "encoded", "=", "b64encode", "(", "':'", ".", "join", "(", "credentials", ")", ".", "encode", "(", "'ascii'", ")", ")", ".", "decode", "(", ")", "return", "header_adder", "(", "{", "'Authorization'", ":"...
30.666667
0.00211
def register_views(self, app): """ Register Flasgger views """ # Wrap the views in an arbitrary number of decorators. def wrap_view(view): if self.decorators: for decorator in self.decorators: view = decorator(view) ret...
[ "def", "register_views", "(", "self", ",", "app", ")", ":", "# Wrap the views in an arbitrary number of decorators.", "def", "wrap_view", "(", "view", ")", ":", "if", "self", ".", "decorators", ":", "for", "decorator", "in", "self", ".", "decorators", ":", "view...
34.819672
0.000916
def dict_remove_value(d, v): """ Recursively remove keys with a certain value from a dict :param d: the dictionary :param v: value which should be removed :return: formatted dictionary """ dd = dict() for key, value in d.items(): if not value == v: if isinstance(value...
[ "def", "dict_remove_value", "(", "d", ",", "v", ")", ":", "dd", "=", "dict", "(", ")", "for", "key", ",", "value", "in", "d", ".", "items", "(", ")", ":", "if", "not", "value", "==", "v", ":", "if", "isinstance", "(", "value", ",", "dict", ")",...
31.705882
0.001802
def is_str(tg_type, inc_array=False): """Tells if the given tango type is string :param tg_type: tango type :type tg_type: :class:`tango.CmdArgType` :param inc_array: (optional, default is False) determines if include array in the list of checked types :type inc_array: :py:obj...
[ "def", "is_str", "(", "tg_type", ",", "inc_array", "=", "False", ")", ":", "global", "_scalar_str_types", ",", "_array_str_types", "if", "tg_type", "in", "_scalar_str_types", ":", "return", "True", "if", "not", "inc_array", ":", "return", "False", "return", "t...
33.5
0.001613
def cc(project, detect_project=False): """ Return a clang that hides CFLAGS and LDFLAGS. This will generate a wrapper script in the current directory and return a complete plumbum command to it. Args: cflags: The CFLAGS we want to hide. ldflags: The LDFLAGS we want to hide. ...
[ "def", "cc", "(", "project", ",", "detect_project", "=", "False", ")", ":", "from", "benchbuild", ".", "utils", "import", "cmd", "cc_name", "=", "str", "(", "CFG", "[", "\"compiler\"", "]", "[", "\"c\"", "]", ")", "wrap_cc", "(", "cc_name", ",", "compi...
35.956522
0.002356
def _decode_thrift_span(self, thrift_span): """Decodes a thrift span. :param thrift_span: thrift span :type thrift_span: thrift Span object :returns: span builder representing this span :rtype: Span """ parent_id = None local_endpoint = None annot...
[ "def", "_decode_thrift_span", "(", "self", ",", "thrift_span", ")", ":", "parent_id", "=", "None", "local_endpoint", "=", "None", "annotations", "=", "{", "}", "tags", "=", "{", "}", "kind", "=", "Kind", ".", "LOCAL", "remote_endpoint", "=", "None", "times...
33.411765
0.00114
def execute_sql_statement(sql_statement, query, user_name, session, cursor): """Executes a single SQL statement""" database = query.database db_engine_spec = database.db_engine_spec parsed_query = ParsedQuery(sql_statement) sql = parsed_query.stripped() SQL_MAX_ROWS = app.config.get('SQL_MAX_ROW...
[ "def", "execute_sql_statement", "(", "sql_statement", ",", "query", ",", "user_name", ",", "session", ",", "cursor", ")", ":", "database", "=", "query", ".", "database", "db_engine_spec", "=", "database", ".", "db_engine_spec", "parsed_query", "=", "ParsedQuery", ...
43.287879
0.001027
def format_obj_name(obj, delim="<>"): """ Formats the object name in a pretty way @obj: any python object @delim: the characters to wrap a parent object name in -> #str formatted name .. from vital.debug import format_obj_name format_obj_name(vital.debug.Ti...
[ "def", "format_obj_name", "(", "obj", ",", "delim", "=", "\"<>\"", ")", ":", "pname", "=", "\"\"", "parent_name", "=", "get_parent_name", "(", "obj", ")", "if", "parent_name", ":", "pname", "=", "\"{}{}{}\"", ".", "format", "(", "delim", "[", "0", "]", ...
29.04
0.001333
def device_selected(self, index): """Handler for selecting a device from the list in the UI""" device = self.devicelist_model.itemFromIndex(index) print(device.device.addr) self.btnConnect.setEnabled(True)
[ "def", "device_selected", "(", "self", ",", "index", ")", ":", "device", "=", "self", ".", "devicelist_model", ".", "itemFromIndex", "(", "index", ")", "print", "(", "device", ".", "device", ".", "addr", ")", "self", ".", "btnConnect", ".", "setEnabled", ...
46.6
0.008439
def serialize_all(obj): """Return all non-None ``hyperparameter`` values on ``obj`` as a ``dict[str,str].``""" if '_hyperparameters' not in dir(obj): return {} return {k: str(v) for k, v in obj._hyperparameters.items() if v is not None}
[ "def", "serialize_all", "(", "obj", ")", ":", "if", "'_hyperparameters'", "not", "in", "dir", "(", "obj", ")", ":", "return", "{", "}", "return", "{", "k", ":", "str", "(", "v", ")", "for", "k", ",", "v", "in", "obj", ".", "_hyperparameters", ".", ...
53.6
0.014706
def readpartial(self, start, end): 'Get a part of the file, from start byte to end byte (integers)' #return self.jfs.raw('%s?mode=bin' % self.path, return self.jfs.raw(url=self.path, params={'mode':'bin'}, # note that we deduct 1 from end because ...
[ "def", "readpartial", "(", "self", ",", "start", ",", "end", ")", ":", "#return self.jfs.raw('%s?mode=bin' % self.path,", "return", "self", ".", "jfs", ".", "raw", "(", "url", "=", "self", ".", "path", ",", "params", "=", "{", "'mode'", ":", "'bin'", "}", ...
66
0.013084
def unique(iterables): """Create an iterable from the iterables that contains each element once. :return: an iterable over the iterables. Each element of the result appeared only once in the result. They are ordered by the first occurrence in the iterables. """ included_elements = set() ...
[ "def", "unique", "(", "iterables", ")", ":", "included_elements", "=", "set", "(", ")", "def", "included", "(", "element", ")", ":", "result", "=", "element", "in", "included_elements", "included_elements", ".", "add", "(", "element", ")", "return", "result"...
36.333333
0.001789
def on_disconnect(self=None) -> callable: """Use this decorator to automatically register a function for handling disconnections. This does the same thing as :meth:`add_handler` using the :class:`DisconnectHandler`. """ def decorator(func: callable) -> Handler: handler = pyr...
[ "def", "on_disconnect", "(", "self", "=", "None", ")", "->", "callable", ":", "def", "decorator", "(", "func", ":", "callable", ")", "->", "Handler", ":", "handler", "=", "pyrogram", ".", "DisconnectHandler", "(", "func", ")", "if", "self", "is", "not", ...
33.285714
0.008351
def _removePunctuation(text_string): """ Removes punctuation symbols from a string. :param text_string: A string. :type text_string: str. :returns: The input ``text_string`` with punctuation symbols removed. :rtype: str. >>> from rnlp.textprocessing import __removePunctuation >>> exam...
[ "def", "_removePunctuation", "(", "text_string", ")", ":", "try", ":", "return", "text_string", ".", "translate", "(", "None", ",", "_punctuation", ")", "except", "TypeError", ":", "return", "text_string", ".", "translate", "(", "str", ".", "maketrans", "(", ...
28.842105
0.001767
def del_metadata_keys(self, bucket, label, keys): '''Delete the metadata corresponding to the specified keys. ''' if self.mode !="r": try: payload = self._get_bucket_md(bucket) except OFSFileNotFound: # No MD found... raise ...
[ "def", "del_metadata_keys", "(", "self", ",", "bucket", ",", "label", ",", "keys", ")", ":", "if", "self", ".", "mode", "!=", "\"r\"", ":", "try", ":", "payload", "=", "self", ".", "_get_bucket_md", "(", "bucket", ")", "except", "OFSFileNotFound", ":", ...
46.823529
0.008621
def from_payload(self, payload): """Init frame from binary data.""" self.node_id = payload[0] self.name = bytes_to_string(payload[1:65])
[ "def", "from_payload", "(", "self", ",", "payload", ")", ":", "self", ".", "node_id", "=", "payload", "[", "0", "]", "self", ".", "name", "=", "bytes_to_string", "(", "payload", "[", "1", ":", "65", "]", ")" ]
39.25
0.0125
def printColConfidence(self, aState, maxCols = 20): """ Print up to maxCols number from a flat floating point array. :param aState: TODO: document :param maxCols: TODO: document """ def formatFPRow(var): s = '' for c in range(min(maxCols, self.numberOfCols)): if c > 0 and c ...
[ "def", "printColConfidence", "(", "self", ",", "aState", ",", "maxCols", "=", "20", ")", ":", "def", "formatFPRow", "(", "var", ")", ":", "s", "=", "''", "for", "c", "in", "range", "(", "min", "(", "maxCols", ",", "self", ".", "numberOfCols", ")", ...
25.117647
0.018059
def setSampleTypes(self, value, **kw): """ For the moment, we're manually trimming the sampletype<>samplepoint relation to be equal on both sides, here. It's done strangely, because it may be required to behave strangely. """ bsc = getToolByName(self, 'bika_setup_catalog'...
[ "def", "setSampleTypes", "(", "self", ",", "value", ",", "*", "*", "kw", ")", ":", "bsc", "=", "getToolByName", "(", "self", ",", "'bika_setup_catalog'", ")", "# convert value to objects", "if", "value", "and", "type", "(", "value", ")", "==", "str", ":", ...
43.666667
0.002037
def show(self, title=None, window_size=None, interactive=True, auto_close=True, interactive_update=False, full_screen=False, screenshot=False, return_img=False, use_panel=None): """ Creates plotting window Parameters ---------- title : string, optional ...
[ "def", "show", "(", "self", ",", "title", "=", "None", ",", "window_size", "=", "None", ",", "interactive", "=", "True", ",", "auto_close", "=", "True", ",", "interactive_update", "=", "False", ",", "full_screen", "=", "False", ",", "screenshot", "=", "F...
36.56
0.00213
def print_info(self, buf=sys.stdout, verbose=False): """Prints a message summarising the contents of the suite.""" _pr = Printer(buf) if not self.contexts: _pr("Suite is empty.") return context_names = sorted(self.contexts.iterkeys()) _pr("Suite contains...
[ "def", "print_info", "(", "self", ",", "buf", "=", "sys", ".", "stdout", ",", "verbose", "=", "False", ")", ":", "_pr", "=", "Printer", "(", "buf", ")", "if", "not", "self", ".", "contexts", ":", "_pr", "(", "\"Suite is empty.\"", ")", "return", "con...
35.894737
0.001428
def data_collector(iterable, def_buf_size=5242880): """ Buffers n bytes of data. :param iterable: Could be a list, generator or string :type iterable: List, generator, String :returns: A generator object """ buf = b'' for data in iterable: buf += data ...
[ "def", "data_collector", "(", "iterable", ",", "def_buf_size", "=", "5242880", ")", ":", "buf", "=", "b''", "for", "data", "in", "iterable", ":", "buf", "+=", "data", "if", "len", "(", "buf", ")", ">=", "def_buf_size", ":", "output", "=", "buf", "[", ...
23.6
0.002037
def _load_config(path: str) -> dict: """ Given a file path, parse it based on its extension (YAML or JSON) and return the values as a Python dictionary. JSON is the default if an extension can't be determined. """ __, ext = os.path.splitext(path) if ext in ['.yaml', '.yml']: import r...
[ "def", "_load_config", "(", "path", ":", "str", ")", "->", "dict", ":", "__", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "if", "ext", "in", "[", "'.yaml'", ",", "'.yml'", "]", ":", "import", "ruamel", ".", "yaml", "loa...
30.866667
0.002096
def format_content_type_object(repo, content_type, uuid): """ Return a content object from a repository for a given content_type and uuid :param Repo repo: The git repository. :param str content_type: The content type to list :returns: dict """ try: storage_manag...
[ "def", "format_content_type_object", "(", "repo", ",", "content_type", ",", "uuid", ")", ":", "try", ":", "storage_manager", "=", "StorageManager", "(", "repo", ")", "model_class", "=", "load_model_class", "(", "repo", ",", "content_type", ")", "return", "dict",...
30.882353
0.001848
def namedbuffer(buffer_name, fields_spec): # noqa (ignore ciclomatic complexity) """ Class factory, returns a class to wrap a buffer instance and expose the data as fields. The field spec specifies how many bytes should be used for a field and what is the encoding / decoding function. """ # py...
[ "def", "namedbuffer", "(", "buffer_name", ",", "fields_spec", ")", ":", "# noqa (ignore ciclomatic complexity)", "# pylint: disable=protected-access,unused-argument", "if", "not", "len", "(", "buffer_name", ")", ":", "raise", "ValueError", "(", "'buffer_name is empty'", ")"...
30.280303
0.000727