_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q226500
has_type
train
def has_type(type, names): """Return type with name if `type` has name as one of its base types, and name is in the `names` list. otherwise, return None.""" if type.arg in names: return type for t in type.search('type'): # check all union's member types r = has_type(t, names) if...
python
{ "resource": "" }
q226501
search_typedef
train
def search_typedef(stmt, name): """Search for a typedef in scope First search the hierarchy, then the module and its submodules.""" mod = stmt.i_orig_module while stmt is not None: if name in stmt.i_typedefs: t = stmt.i_typedefs[name] if (mod is not None and ...
python
{ "resource": "" }
q226502
search_grouping
train
def search_grouping(stmt, name): """Search for a grouping in scope First search the hierarchy, then the module and its submodules.""" mod = stmt.i_orig_module while stmt is not None: if name in stmt.i_groupings: g = stmt.i_groupings[name] if (mod is not None and ...
python
{ "resource": "" }
q226503
is_submodule_included
train
def is_submodule_included(src, tgt): """Check that the tgt's submodule is included by src, if they belong to the same module.""" if tgt is None or not hasattr(tgt, 'i_orig_module'): return True if (tgt.i_orig_module.keyword == 'submodule' and src.i_orig_module != tgt.i_orig_module and ...
python
{ "resource": "" }
q226504
mk_path_str
train
def mk_path_str(stmt, with_prefixes=False, prefix_onchange=False, prefix_to_module=False, resolve_top_prefix_to_module=False): """Returns the XPath path of the node. with_prefixes indicates whether or not to prefix every node. prefix_onchange ...
python
{ "resource": "" }
q226505
get_xpath
train
def get_xpath(stmt, qualified=False, prefix_to_module=False): """Gets the XPath of the statement. Unless qualified=True, does not include prefixes unless the prefix changes mid-XPath. qualified will add a prefix to each node. prefix_to_module will resolve prefixes to module names instead. F...
python
{ "resource": "" }
q226506
get_qualified_type
train
def get_qualified_type(stmt): """Gets the qualified, top-level type of the node. This enters the typedef if defined instead of using the prefix to ensure absolute distinction. """ type_obj = stmt.search_one('type') fq_type_name = None if type_obj: if getattr(type_obj, 'i_typedef', No...
python
{ "resource": "" }
q226507
get_primitive_type
train
def get_primitive_type(stmt): """Recurses through the typedefs and returns the most primitive YANG type defined. """ type_obj = stmt.search_one('type') type_name = getattr(type_obj, 'arg', None) typedef_obj = getattr(type_obj, 'i_typedef', None) if typedef_obj: type_name = get_primit...
python
{ "resource": "" }
q226508
Statement.search
train
def search(self, keyword, children=None, arg=None): """Return list of receiver's substmts with `keyword`. """ if children is None: children = self.substmts return [ ch for ch in children if (ch.keyword == keyword and (arg is None or ch.ar...
python
{ "resource": "" }
q226509
Statement.search_one
train
def search_one(self, keyword, arg=None, children=None): """Return receiver's substmt with `keyword` and optionally `arg`. """ if children is None: children = self.substmts for ch in children: if ch.keyword == keyword and (arg is None or ch.arg == arg): ...
python
{ "resource": "" }
q226510
Statement.main_module
train
def main_module(self): """Return the main module to which the receiver belongs.""" if self.i_module.keyword == "submodule": return self.i_module.i_ctx.get_module( self.i_module.i_including_modulename) return self.i_module
python
{ "resource": "" }
q226511
add_prefix
train
def add_prefix(prefix, s): "Add `prefix` to all unprefixed names in `s`" # tokenize the XPath expression toks = xpath_lexer.scan(s) # add default prefix to unprefixed names toks2 = [_add_prefix(prefix, tok) for tok in toks] # build a string of the patched expression ls = [x.value for x in to...
python
{ "resource": "" }
q226512
chk_date_arg
train
def chk_date_arg(s): """Checks if the string `s` is a valid date string. Return True of False.""" if re_date.search(s) is None: return False comp = s.split('-') try: dt = datetime.date(int(comp[0]), int(comp[1]), int(comp[2])) return True except Exception as e: r...
python
{ "resource": "" }
q226513
chk_enum_arg
train
def chk_enum_arg(s): """Checks if the string `s` is a valid enum string. Return True or False.""" if len(s) == 0 or s[0].isspace() or s[-1].isspace(): return False else: return True
python
{ "resource": "" }
q226514
chk_fraction_digits_arg
train
def chk_fraction_digits_arg(s): """Checks if the string `s` is a valid fraction-digits argument. Return True or False.""" try: v = int(s) if v >= 1 and v <= 18: return True else: return False except ValueError: return False
python
{ "resource": "" }
q226515
Patch.combine
train
def combine(self, patch): """Add `patch.plist` to `self.plist`.""" exclusive = set(["config", "default", "mandatory", "presence", "min-elements", "max-elements"]) kws = set([s.keyword for s in self.plist]) & exclusive add = [n for n in patch.plist if n.keyword not in...
python
{ "resource": "" }
q226516
HybridDSDLSchema.serialize
train
def serialize(self): """Return the string representation of the receiver.""" res = '<?xml version="1.0" encoding="UTF-8"?>' for ns in self.namespaces: self.top_grammar.attr["xmlns:" + self.namespaces[ns]] = ns res += self.top_grammar.start_tag() for ch in self.top_gra...
python
{ "resource": "" }
q226517
HybridDSDLSchema.setup_top
train
def setup_top(self): """Create top-level elements of the hybrid schema.""" self.top_grammar = SchemaNode("grammar") self.top_grammar.attr = { "xmlns": "http://relaxng.org/ns/structure/1.0", "datatypeLibrary": "http://www.w3.org/2001/XMLSchema-datatypes"} self.tree...
python
{ "resource": "" }
q226518
HybridDSDLSchema.create_roots
train
def create_roots(self, yam): """Create the top-level structure for module `yam`.""" self.local_grammar = SchemaNode("grammar") self.local_grammar.attr = { "ns": yam.search_one("namespace").arg, "nma:module": self.module.arg} src_text = "YANG module '%s'" % yam.arg...
python
{ "resource": "" }
q226519
HybridDSDLSchema.yang_to_xpath
train
def yang_to_xpath(self, xpe): """Transform YANG's `xpath` to a form suitable for Schematron. 1. Prefixes are added to unprefixed local names. Inside global groupings, the prefix is represented as the variable '$pref' which is substituted via Schematron abstract patterns...
python
{ "resource": "" }
q226520
HybridDSDLSchema.register_identity
train
def register_identity(self, id_stmt): """Register `id_stmt` with its base identity, if any. """ bst = id_stmt.search_one("base") if bst: bder = self.identity_deps.setdefault(bst.i_identity, []) bder.append(id_stmt)
python
{ "resource": "" }
q226521
HybridDSDLSchema.add_derived_identity
train
def add_derived_identity(self, id_stmt): """Add pattern def for `id_stmt` and all derived identities. The corresponding "ref" pattern is returned. """ p = self.add_namespace(id_stmt.main_module()) if id_stmt not in self.identities: # add named pattern def self.iden...
python
{ "resource": "" }
q226522
HybridDSDLSchema.preload_defs
train
def preload_defs(self): """Preload all top-level definitions.""" for d in (self.module.search("grouping") + self.module.search("typedef")): uname, dic = self.unique_def_name(d) self.install_def(uname, d, dic)
python
{ "resource": "" }
q226523
HybridDSDLSchema.add_prefix
train
def add_prefix(self, name, stmt): """Return `name` prepended with correct prefix. If the name is already prefixed, the prefix may be translated to the value obtained from `self.module_prefixes`. Unmodified `name` is returned if we are inside a global grouping. """ if se...
python
{ "resource": "" }
q226524
HybridDSDLSchema.dc_element
train
def dc_element(self, parent, name, text): """Add DC element `name` containing `text` to `parent`.""" if self.dc_uri in self.namespaces: dcel = SchemaNode(self.namespaces[self.dc_uri] + ":" + name, text=text) parent.children.insert(0,dcel)
python
{ "resource": "" }
q226525
HybridDSDLSchema.get_default
train
def get_default(self, stmt, refd): """Return default value for `stmt` node. `refd` is a dictionary of applicable refinements that is constructed in the `process_patches` method. """ if refd["default"]: return refd["default"] defst = stmt.search_one("defau...
python
{ "resource": "" }
q226526
HybridDSDLSchema.add_patch
train
def add_patch(self, pset, augref): """Add patch corresponding to `augref` to `pset`. `augref` must be either 'augment' or 'refine' statement. """ try: path = [ self.add_prefix(c, augref) for c in augref.arg.split("/") if c ] except KeyError: ...
python
{ "resource": "" }
q226527
HybridDSDLSchema.apply_augments
train
def apply_augments(self, auglist, p_elem, pset): """Handle substatements of augments from `auglist`. The augments are applied in the context of `p_elem`. `pset` is a patch set containing patches that may be applicable to descendants. """ for a in auglist: pa...
python
{ "resource": "" }
q226528
HybridDSDLSchema.current_revision
train
def current_revision(self, r_stmts): """Pick the most recent revision date. `r_stmts` is a list of 'revision' statements. """ cur = max([[int(p) for p in r.arg.split("-")] for r in r_stmts]) return "%4d-%02d-%02d" % tuple(cur)
python
{ "resource": "" }
q226529
HybridDSDLSchema.install_def
train
def install_def(self, name, dstmt, def_map, interleave=False): """Install definition `name` into the appropriate dictionary. `dstmt` is the definition statement ('typedef' or 'grouping') that is to be mapped to a RELAX NG named pattern '<define name="`name`">'. `def_map` must be either ...
python
{ "resource": "" }
q226530
HybridDSDLSchema.rng_annotation
train
def rng_annotation(self, stmt, p_elem): """Append YIN representation of extension statement `stmt`.""" ext = stmt.i_extension prf, extkw = stmt.raw_keyword (modname,rev)=stmt.i_module.i_prefixes[prf] prefix = self.add_namespace( statements.modulename_to_module(self.mo...
python
{ "resource": "" }
q226531
HybridDSDLSchema.propagate_occur
train
def propagate_occur(self, node, value): """Propagate occurence `value` to `node` and its ancestors. Occurence values are defined and explained in the SchemaNode class. """ while node.occur < value: node.occur = value if node.name == "define": ...
python
{ "resource": "" }
q226532
HybridDSDLSchema.process_patches
train
def process_patches(self, pset, stmt, elem, altname=None): """Process patches for data node `name` from `pset`. `stmt` provides the context in YANG and `elem` is the parent element in the output schema. Refinements adding documentation and changing the config status are immediately appl...
python
{ "resource": "" }
q226533
HybridDSDLSchema.lookup_expand
train
def lookup_expand(self, stmt, names): """Find schema nodes under `stmt`, also in used groupings. `names` is a list with qualified names of the schema nodes to look up. All 'uses'/'grouping' pairs between `stmt` and found schema nodes are marked for expansion. """ if not ...
python
{ "resource": "" }
q226534
HybridDSDLSchema.type_with_ranges
train
def type_with_ranges(self, tchain, p_elem, rangekw, gen_data): """Handle types with 'range' or 'length' restrictions. `tchain` is the chain of type definitions from which the ranges may need to be extracted. `rangekw` is the statement keyword determining the range type (either 'range' o...
python
{ "resource": "" }
q226535
HybridDSDLSchema.get_ranges
train
def get_ranges(self, tchain, kw): """Return list of ranges defined in `tchain`. `kw` is the statement keyword determining the type of the range, i.e. 'range' or 'length'. `tchain` is the chain of type definitions from which the resulting range is obtained. The returned value is...
python
{ "resource": "" }
q226536
HybridDSDLSchema.handle_stmt
train
def handle_stmt(self, stmt, p_elem, pset={}): """ Run handler method for statement `stmt`. `p_elem` is the parent node in the output schema. `pset` is the current "patch set" - a dictionary with keys being QNames of schema nodes at the current level of hierarchy for which ...
python
{ "resource": "" }
q226537
HybridDSDLSchema.handle_substmts
train
def handle_substmts(self, stmt, p_elem, pset={}): """Handle all substatements of `stmt`.""" for sub in stmt.substmts: self.handle_stmt(sub, p_elem, pset)
python
{ "resource": "" }
q226538
HybridDSDLSchema.nma_attribute
train
def nma_attribute(self, stmt, p_elem, pset=None): """Map `stmt` to a NETMOD-specific attribute. The name of the attribute is the same as the 'keyword' of `stmt`. """ att = "nma:" + stmt.keyword if att not in p_elem.attr: p_elem.attr[att] = stmt.arg
python
{ "resource": "" }
q226539
HybridDSDLSchema.type_stmt
train
def type_stmt(self, stmt, p_elem, pset): """Handle ``type`` statement. Built-in types are handled by one of the specific type callback methods defined below. """ typedef = stmt.i_typedef if typedef and not stmt.i_is_derived: # just ref uname, dic = self.uniqu...
python
{ "resource": "" }
q226540
HybridDSDLSchema.choice_type
train
def choice_type(self, tchain, p_elem): """Handle ``enumeration`` and ``union`` types.""" elem = SchemaNode.choice(p_elem, occur=2) self.handle_substmts(tchain[0], elem)
python
{ "resource": "" }
q226541
HybridDSDLSchema.mapped_type
train
def mapped_type(self, tchain, p_elem): """Handle types that are simply mapped to RELAX NG.""" SchemaNode("data", p_elem).set_attr("type", self.datatype_map[tchain[0].arg])
python
{ "resource": "" }
q226542
HybridDSDLSchema.numeric_type
train
def numeric_type(self, tchain, p_elem): """Handle numeric types.""" typ = tchain[0].arg def gen_data(): elem = SchemaNode("data").set_attr("type", self.datatype_map[typ]) if typ == "decimal64": fd = tchain[0].search_one("fraction-digits").arg ...
python
{ "resource": "" }
q226543
add_stmt
train
def add_stmt(stmt, arg_rules): """Use by plugins to add grammar for an extension statement.""" (arg, rules) = arg_rules stmt_map[stmt] = (arg, rules)
python
{ "resource": "" }
q226544
add_to_stmts_rules
train
def add_to_stmts_rules(stmts, rules): """Use by plugins to add extra rules to the existing rules for a statement.""" def is_rule_less_than(ra, rb): rka = ra[0] rkb = rb[0] if not util.is_prefixed(rkb): # old rule is non-prefixed; append new rule after return F...
python
{ "resource": "" }
q226545
chk_module_statements
train
def chk_module_statements(ctx, module_stmt, canonical=False): """Validate the statement hierarchy according to the grammar. Return True if module is valid, False otherwise. """ return chk_statement(ctx, module_stmt, top_stmts, canonical)
python
{ "resource": "" }
q226546
chk_statement
train
def chk_statement(ctx, stmt, grammar, canonical=False): """Validate `stmt` according to `grammar`. Marks each statement in the hierearchy with stmt.is_grammatically_valid, which is a boolean. Return True if stmt is valid, False otherwise. """ n = len(ctx.errors) if canonical == True: ...
python
{ "resource": "" }
q226547
sort_canonical
train
def sort_canonical(keyword, stmts): """Sort all `stmts` in the canonical order defined by `keyword`. Return the sorted list. The `stmt` list is not modified. If `keyword` does not have a canonical order, the list is returned as is. """ try: (_arg_type, subspec) = stmt_map[keyword] ...
python
{ "resource": "" }
q226548
scan
train
def scan(s): """Return a list of tokens, or throw SyntaxError on failure. """ line = 1 linepos = 1 pos = 0 toks = [] while pos < len(s): matched = False for (tokname, r) in patterns: m = r.match(s, pos) if m is not None: # found a match...
python
{ "resource": "" }
q226549
HelloParser.yang_modules
train
def yang_modules(self): """ Return a list of advertised YANG module names with revisions. Avoid repeated modules. """ res = {} for c in self.capabilities: m = c.parameters.get("module") if m is None or m in res: continue res[m] = c.par...
python
{ "resource": "" }
q226550
HelloParser.get_features
train
def get_features(self, yam): """Return list of features declared for module `yam`.""" mcap = [ c for c in self.capabilities if c.parameters.get("module", None) == yam ][0] if not mcap.parameters.get("features"): return [] return mcap.parameters["features"].split(",")
python
{ "resource": "" }
q226551
HelloParser.registered_capabilities
train
def registered_capabilities(self): """Return dictionary of non-YANG capabilities. Only capabilities from the `CAPABILITIES` dictionary are taken into account. """ return dict ([ (CAPABILITIES[c.id],c) for c in self.capabilities if c.id in CAPABILITIES ])
python
{ "resource": "" }
q226552
listsdelete
train
def listsdelete(x, xs): """Return a new list with x removed from xs""" i = xs.index(x) return xs[:i] + xs[(i+1):]
python
{ "resource": "" }
q226553
unique_prefixes
train
def unique_prefixes(context): """Return a dictionary with unique prefixes for modules in `context`. Keys are 'module' statements and values are prefixes, disambiguated where necessary. """ res = {} for m in context.modules.values(): if m.keyword == "submodule": continue prf = ne...
python
{ "resource": "" }
q226554
PyangDist.preprocess_files
train
def preprocess_files(self, prefix): """Change the installation prefix where necessary. """ if prefix is None: return files = ("bin/yang2dsdl", "man/man1/yang2dsdl.1", "pyang/plugins/jsonxsl.py") regex = re.compile("^(.*)/usr/local(.*)$") ...
python
{ "resource": "" }
q226555
Context.add_module
train
def add_module(self, ref, text, format=None, expect_modulename=None, expect_revision=None, expect_failure_error=True): """Parse a module text and add the module data to the context `ref` is a string which is used to identify the source of the text for...
python
{ "resource": "" }
q226556
Context.del_module
train
def del_module(self, module): """Remove a module from the context""" rev = util.get_latest_revision(module) del self.modules[(module.arg, rev)]
python
{ "resource": "" }
q226557
Context.get_module
train
def get_module(self, modulename, revision=None): """Return the module if it exists in the context""" if revision is None and modulename in self.revs: (revision, _handle) = self._get_latest_rev(self.revs[modulename]) if revision is not None: if (modulename,revision) in sel...
python
{ "resource": "" }
q226558
init
train
def init(plugindirs=[]): """Initialize the plugin framework""" # initialize the builtin plugins from .translators import yang,yin,dsdl yang.pyang_plugin_init() yin.pyang_plugin_init() dsdl.pyang_plugin_init() # initialize installed plugins for ep in pkg_resources.iter_entry_points(grou...
python
{ "resource": "" }
q226559
YinParser.split_qname
train
def split_qname(qname): """Split `qname` into namespace URI and local name Return namespace and local name as a tuple. This is a static method.""" res = qname.split(YinParser.ns_sep) if len(res) == 1: # no namespace return None, res[0] else: ...
python
{ "resource": "" }
q226560
YinParser.check_attr
train
def check_attr(self, pos, attrs): """Check for unknown attributes.""" for at in attrs: (ns, local_name) = self.split_qname(at) if ns is None: error.err_add(self.ctx.errors, pos, 'UNEXPECTED_ATTRIBUTE', local_name) elif ns...
python
{ "resource": "" }
q226561
YinParser.search_definition
train
def search_definition(self, module, keyword, arg): """Search for a defintion with `keyword` `name` Search the module and its submodules.""" r = module.search_one(keyword, arg) if r is not None: return r for i in module.search('include'): modulename = i.arg...
python
{ "resource": "" }
q226562
emit_path_arg
train
def emit_path_arg(keywordstr, arg, fd, indent, max_line_len, line_len, eol): """Heuristically pretty print a path argument""" quote = '"' arg = escape_str(arg) if not(need_new_line(max_line_len, line_len, arg)): fd.write(" " + quote + arg + quote) return False ## FIXME: we should...
python
{ "resource": "" }
q226563
emit_arg
train
def emit_arg(keywordstr, stmt, fd, indent, indentstep, max_line_len, line_len): """Heuristically pretty print the argument string with double quotes""" arg = escape_str(stmt.arg) lines = arg.splitlines(True) if len(lines) <= 1: if len(arg) > 0 and arg[-1] == '\n': arg = arg[:-1] + r'...
python
{ "resource": "" }
q226564
SampleXMLSkeletonPlugin.process_children
train
def process_children(self, node, elem, module, path, omit=[]): """Proceed with all children of `node`.""" for ch in node.i_children: if ch not in omit and (ch.i_config or self.doctype == "data"): self.node_handler.get(ch.keyword, self.ignore)( ch, elem, mo...
python
{ "resource": "" }
q226565
SampleXMLSkeletonPlugin.container
train
def container(self, node, elem, module, path): """Create a sample container element and proceed with its children.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: pres = node.search_one("presence") ...
python
{ "resource": "" }
q226566
SampleXMLSkeletonPlugin.leaf
train
def leaf(self, node, elem, module, path): """Create a sample leaf element.""" if node.i_default is None: nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: nel.append(etree.Comment( ...
python
{ "resource": "" }
q226567
SampleXMLSkeletonPlugin.anyxml
train
def anyxml(self, node, elem, module, path): """Create a sample anyxml element.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: nel.append(etree.Comment(" anyxml "))
python
{ "resource": "" }
q226568
SampleXMLSkeletonPlugin.list
train
def list(self, node, elem, module, path): """Create sample entries of a list.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return for kn in node.i_key: self.node_handler.get(kn.keyword, self.ignore)( kn, nel, ...
python
{ "resource": "" }
q226569
SampleXMLSkeletonPlugin.leaf_list
train
def leaf_list(self, node, elem, module, path): """Create sample entries of a leaf-list.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return minel = node.search_one("min-elements") self.add_copies(node, elem, nel, minel) s...
python
{ "resource": "" }
q226570
SampleXMLSkeletonPlugin.sample_element
train
def sample_element(self, node, parent, module, path): """Create element under `parent`. Declare new namespace if necessary. """ if path is None: return parent, module, None elif path == []: # GO ON pass else: if node.arg ==...
python
{ "resource": "" }
q226571
SampleXMLSkeletonPlugin.add_copies
train
def add_copies(self, node, parent, elem, minel): """Add appropriate number of `elem` copies to `parent`.""" rep = 0 if minel is None else int(minel.arg) - 1 for i in range(rep): parent.append(copy.deepcopy(elem))
python
{ "resource": "" }
q226572
SampleXMLSkeletonPlugin.list_comment
train
def list_comment(self, node, elem, minel): """Add list annotation to `elem`.""" lo = "0" if minel is None else minel.arg maxel = node.search_one("max-elements") hi = "" if maxel is None else maxel.arg elem.insert(0, etree.Comment( " # entries: %s..%s " % (lo, hi))) ...
python
{ "resource": "" }
q226573
slugify
train
def slugify(value, separator='-', max_length=0, word_boundary=False, entities=True, decimal=True, hexadecimal=True): '''Normalizes string, removes non-alpha characters, and converts spaces to ``separator`` character ''' value = normalize('NFKD', to_string(value, 'utf-8', 'ignore')) if un...
python
{ "resource": "" }
q226574
smart_truncate
train
def smart_truncate(value, max_length=0, word_boundaries=False, separator=' '): """ Truncate a string """ value = value.strip(separator) if not max_length: return value if len(value) < max_length: return value if not word_boundaries: return value[:max_length].strip(separat...
python
{ "resource": "" }
q226575
RedisParser.get
train
def get(self): '''Called by the protocol consumer''' if self._current: return self._resume(self._current, False) else: return self._get(None)
python
{ "resource": "" }
q226576
RedisParser.pack_pipeline
train
def pack_pipeline(self, commands): '''Packs pipeline commands into bytes.''' return b''.join( starmap(lambda *args: b''.join(self._pack_command(args)), (a for a, _ in commands)))
python
{ "resource": "" }
q226577
PyPi.pypi_release
train
def pypi_release(self): """Get the latest pypi release """ meta = self.distribution.metadata pypi = ServerProxy(self.pypi_index_url) releases = pypi.package_releases(meta.name) if releases: return next(iter(sorted(releases, reverse=True)))
python
{ "resource": "" }
q226578
is_mainthread
train
def is_mainthread(thread=None): '''Check if thread is the main thread. If ``thread`` is not supplied check the current thread ''' thread = thread if thread is not None else current_thread() return isinstance(thread, threading._MainThread)
python
{ "resource": "" }
q226579
process_data
train
def process_data(name=None): '''Fetch the current process local data dictionary. If ``name`` is not ``None`` it returns the value at``name``, otherwise it return the process data dictionary ''' ct = current_process() if not hasattr(ct, '_pulsar_local'): ct._pulsar_local = {} loc = c...
python
{ "resource": "" }
q226580
thread_data
train
def thread_data(name, value=NOTHING, ct=None): '''Set or retrieve an attribute ``name`` from thread ``ct``. If ``ct`` is not given used the current thread. If ``value`` is None, it will get the value otherwise it will set the value. ''' ct = ct or current_thread() if is_mainthread(ct): ...
python
{ "resource": "" }
q226581
parse_address
train
def parse_address(netloc, default_port=8000): '''Parse an internet address ``netloc`` and return a tuple with ``host`` and ``port``.''' if isinstance(netloc, tuple): if len(netloc) != 2: raise ValueError('Invalid address %s' % str(netloc)) return netloc # netloc = native_str(...
python
{ "resource": "" }
q226582
is_socket_closed
train
def is_socket_closed(sock): # pragma nocover """Check if socket ``sock`` is closed.""" if not sock: return True try: if not poll: # pragma nocover if not select: return False try: return bool(select([sock], [], [], 0.0)[0]) ...
python
{ "resource": "" }
q226583
close_socket
train
def close_socket(sock): '''Shutdown and close the socket.''' if sock: try: sock.shutdown(socket.SHUT_RDWR) except Exception: pass try: sock.close() except Exception: pass
python
{ "resource": "" }
q226584
PulsarServerCommands.rpc_server_info
train
async def rpc_server_info(self, request): '''Return a dictionary of information regarding the server and workers. It invokes the :meth:`extra_server_info` for adding custom information. ''' info = await send('arbiter', 'info') info = self.extra_server_info(request, info)...
python
{ "resource": "" }
q226585
Event.bind
train
def bind(self, callback): """Bind a ``callback`` to this event. """ handlers = self._handlers if self._self is None: raise RuntimeError('%s already fired, cannot add callbacks' % self) if handlers is None: handlers = [] self._handlers = handler...
python
{ "resource": "" }
q226586
Event.unbind
train
def unbind(self, callback): """Remove a callback from the list """ handlers = self._handlers if handlers: filtered_callbacks = [f for f in handlers if f != callback] removed_count = len(handlers) - len(filtered_callbacks) if removed_count: ...
python
{ "resource": "" }
q226587
Event.fire
train
def fire(self, exc=None, data=None): """Fire the event :param exc: fire the event with an exception :param data: fire an event with data """ o = self._self if o is not None: handlers = self._handlers if self._onetime: self._handle...
python
{ "resource": "" }
q226588
EventHandler.fire_event
train
def fire_event(self, name, exc=None, data=None): """Fire event at ``name`` if it is registered """ if self._events and name in self._events: self._events[name].fire(exc=exc, data=data)
python
{ "resource": "" }
q226589
EventHandler.bind_events
train
def bind_events(self, events): '''Register all known events found in ``events`` key-valued parameters. ''' evs = self._events if evs and events: for event in evs.values(): if event.name in events: event.bind(events[event.name])
python
{ "resource": "" }
q226590
_get_args_for_reloading
train
def _get_args_for_reloading(): """Returns the executable. This contains a workaround for windows if the executable is incorrectly reported to not have the .exe extension which can cause bugs on reloading. """ rv = [sys.executable] py_script = sys.argv[0] if os.name == 'nt' and not os.path.ex...
python
{ "resource": "" }
q226591
Reloader.restart_with_reloader
train
def restart_with_reloader(self): """Spawn a new Python interpreter with the same arguments as this one """ while True: LOGGER.info('Restarting with %s reloader' % self.name) args = _get_args_for_reloading() new_environ = os.environ.copy() new_envir...
python
{ "resource": "" }
q226592
Thread.kill
train
def kill(self, sig): '''Invoke the stop on the event loop method.''' if self.is_alive() and self._loop: self._loop.call_soon_threadsafe(self._loop.stop)
python
{ "resource": "" }
q226593
HTTPDigestAuth.encode
train
def encode(self, method, uri): '''Called by the client to encode Authentication header.''' if not self.username or not self.password: return o = self.options qop = o.get('qop') realm = o.get('realm') nonce = o.get('nonce') entdig = None p_parse...
python
{ "resource": "" }
q226594
handle_wsgi_error
train
def handle_wsgi_error(environ, exc): '''The default error handler while serving a WSGI request. :param environ: The WSGI environment. :param exc: the exception :return: a :class:`.WsgiResponse` ''' if isinstance(exc, tuple): exc_info = exc exc = exc[1] else: exc_info...
python
{ "resource": "" }
q226595
render_error
train
def render_error(request, exc): '''Default renderer for errors.''' cfg = request.get('pulsar.cfg') debug = cfg.debug if cfg else False response = request.response if not response.content_type: content_type = request.get('default.content_type') response.content_type = request.content_...
python
{ "resource": "" }
q226596
render_error_debug
train
def render_error_debug(request, exception, is_html): '''Render the ``exception`` traceback ''' error = Html('div', cn='well well-lg') if is_html else [] for trace in format_traceback(exception): counter = 0 for line in trace.split('\n'): if line.startswith(' '): ...
python
{ "resource": "" }
q226597
arbiter
train
def arbiter(**params): '''Obtain the ``arbiter``. It returns the arbiter instance only if we are on the arbiter context domain, otherwise it returns nothing. ''' arbiter = get_actor() if arbiter is None: # Create the arbiter return set_actor(_spawn_actor('arbiter', None, **param...
python
{ "resource": "" }
q226598
MonitorMixin.manage_actor
train
def manage_actor(self, monitor, actor, stop=False): '''If an actor failed to notify itself to the arbiter for more than the timeout, stop the actor. :param actor: the :class:`Actor` to manage. :param stop: if ``True``, stop the actor. :return: if the actor is alive 0 if it is no...
python
{ "resource": "" }
q226599
MonitorMixin.spawn_actors
train
def spawn_actors(self, monitor): '''Spawn new actors if needed. ''' to_spawn = monitor.cfg.workers - len(self.managed_actors) if monitor.cfg.workers and to_spawn > 0: for _ in range(to_spawn): monitor.spawn()
python
{ "resource": "" }