code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
nodes = [node for node in ast.walk(expr) if isinstance(node, ast.Name)] loaded = {node.id for node in nodes if isinstance(node.ctx, ast.Load)} stored = {node.id for node in nodes if isinstance(node.ctx, ast.Store)} return loaded - stored
def names(expr: AST) -> Set[str]
Names of globals in `expr`.
2.259473
2.148679
1.051564
return _NameReplacer(old_name, new_name).visit(deepcopy(expr))
def replace_name(expr: AST, old_name: str, new_name: str) -> AST
Replace all Name nodes named `old_name` with nodes named `new_name`.
8.659685
5.446792
1.589869
expr = Expression(_negate(expr.body)) return ast.fix_missing_locations(expr)
def Negation(expr: Expression) -> Expression
Return expression which is the negation of `expr`.
12.451494
9.334814
1.333877
expr = Expression(ast.BoolOp(ast.And(), [expr1.body, expr2.body])) return ast.fix_missing_locations(expr)
def Conjunction(expr1: Expression, expr2: Expression) -> Expression
Return expression which is the conjunction of `expr1` and `expr2`.
4.828626
3.945665
1.22378
expr = Expression(ast.BoolOp(ast.Or(), [expr1.body, expr2.body])) return ast.fix_missing_locations(expr)
def Disjunction(expr1: Expression, expr2: Expression) -> Expression
Return expression which is the disjunction of `expr1` and `expr2`.
4.733181
3.92343
1.206388
expr = Disjunction(Conjunction(expr1, Negation(expr2)), Conjunction(Negation(expr1), expr2)) return ast.fix_missing_locations(expr)
def Contradiction(expr1: Expression, expr2: Expression) -> Expression
Return expression which is the contradiction of `expr1` and `expr2`.
4.484337
3.85188
1.164195
try: prev_op, prev_op_binding = self.nested_ops[-2] except IndexError: prev_op, prev_op_binding = None, 0 try: curr_op, curr_op_binding = self.nested_ops[-1] except IndexError: curr_op, curr_op_binding = None, 0 # special c...
def diff_binding(self) -> int
Return the difference betweens the binding levels of the current and the previous operator.
2.461412
2.238711
1.099477
diff_binding = self.op_man.diff_binding() if diff_binding < 0 or diff_binding == 0 and not dfltChaining: return self.parenthesize(src) else: return src
def wrap_expr(self, src: str, dfltChaining: bool) -> str
Wrap `src` in parentheses if neccessary.
7.790868
6.012858
1.295701
# print(node.__class__.__name__) if node is None: return '' if isinstance(node, ast.Expression): return self.visit(node.body) # dispatch to specific or generic method method = 'visit_' + node.__class__.__name__ visitor = getattr(self, meth...
def visit(self, node: AST, dfltChaining: bool = True) -> str
Process `node` by dispatching to a handler.
2.70841
2.603067
1.040469
for field, value in ast.iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, AST): self.visit(item) elif isinstance(value, AST): self.visit(value)
def generic_visit(self, node: AST, dfltChaining: bool = True) -> str
Default handler, called if no explicit visitor function exists for a node.
2.112229
1.964222
1.075351
return str(node.value)
def visit_NameConstant(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s name as string.
20.810614
6.737704
3.08868
return str(node.n)
def visit_Num(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s number as string.
22.159359
6.460661
3.42989
return repr(node.s)
def visit_Str(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s string representation.
25.325464
8.912349
2.841615
format_spec = node.format_spec return f"{{{self.visit(node.value)}" \ f"{self.CONV_MAP.get(node.conversion, '')}" \ f"{':'+self._nested_str(format_spec) if format_spec else ''}}}"
def visit_FormattedValue(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s value formatted according to its format spec.
5.196936
4.812079
1.079977
elems = (self.visit(elt) for elt in node.elts) return f"({', '.join(elems)}{')' if len(node.elts) != 1 else ',)'}"
def visit_Tuple(self, node: AST, dfltChaining: bool = True) -> str
Return tuple representation of `node`s elements.
4.380913
3.283877
1.334067
return '{' + ', '.join([self.visit(elt) for elt in node.elts]) + '}'
def visit_Set(self, node: AST, dfltChaining: bool = True) -> str
Return set representation of `node`s elements.
4.455599
2.740249
1.625983
items = (': '.join((self.visit(key), self.visit(value))) for key, value in zip(node.keys, node.values)) return f"{{{', '.join(items)}}}"
def visit_Dict(self, node: AST, dfltChaining: bool = True) -> str
Return dict representation of `node`s elements.
3.443953
2.742182
1.255917
return node.id
def visit_Name(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s id.
120.620049
13.088181
9.215952
with self.op_man(node): return f"*{self.visit(node.value)}"
def visit_Starred(self, node: AST, dfltChaining: bool = True) -> str
Return representation of starred expresssion.
12.549885
8.015986
1.565607
return self.visit(node.value)
def visit_Expr(self, node: AST, dfltChaining: bool = True) -> str
Return representation of nested expression.
14.536961
4.971055
2.924321
op = node.op with self.op_man(op): return self.visit(op) + self.visit(node.operand)
def visit_UnaryOp(self, node: AST, dfltChaining: bool = True) -> str
Return representation of `node`s operator and operand.
8.398188
6.120511
1.372138
op = node.op with self.op_man(op): if isinstance(op, ast.Pow): # Pow chains right-to-left src = self.visit(op).join((self.visit(node.left, dfltChaining=False), ...
def visit_BinOp(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s operator and operands as inlined expression.
3.858078
3.609795
1.06878
return '/' if self.compact else ' / '
def visit_Div(self, node: AST, dfltChaining: bool = True) -> str
Return division sign.
52.937687
11.950102
4.429894
op = node.op with self.op_man(op): src = self.visit(op).join([self.visit(node.values[0])] + [self.visit(val, dfltChaining=False) for val in node.values[1:]]) return self.wrap_expr(src, dfltChain...
def visit_BoolOp(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s operator and operands as inlined expression.
4.932823
4.409332
1.118724
# all comparison operators have the same precedence, # we just take the first one as representative first_op = node.ops[0] with self.op_man(first_op): cmps = [' '.join((self.visit(op), self.visit(cmp, dfltChaining=False))) ...
def visit_Compare(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s operators and operands as inlined expression.
4.313624
3.992535
1.080422
arg = node.arg if arg is None: return f"**{self.visit(node.value)}" else: return f"{arg}={self.visit(node.value)}"
def visit_keyword(self, node: AST, dfltChaining: bool = True) -> str
Return representation of `node` as keyword arg.
3.366272
2.593154
1.298138
args = node.args try: kwds = node.keywords except AttributeError: kwds = [] self.compact = True args_src = (self.visit(arg) for arg in args) kwds_src = (self.visit(kwd) for kwd in kwds) param_src = ', '.join(chain(args_src, kwds_sr...
def visit_Call(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s representation as function call.
2.635554
2.421368
1.088457
args = node.args dflts = node.defaults vararg = node.vararg kwargs = node.kwonlyargs kwdflts = node.kw_defaults kwarg = node.kwarg self.compact = True n_args_without_dflt = len(args) - len(dflts) args_src = (arg.arg for arg in args[:n_args...
def visit_arguments(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s representation as argument list.
2.100736
2.040715
1.029411
with self.op_man(node): src = f"lambda {self.visit(node.args)}: {self.visit(node.body)}" return self.wrap_expr(src, dfltChaining)
def visit_Lambda(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s representation as lambda expression.
5.013011
4.107072
1.22058
with self.op_man(node): src = " if ".join((self.visit(node.body, dfltChaining=False), " else ".join((self.visit(node.test), self.visit(node.orelse))))) return self.wrap_expr(src, dfltChaining)
def visit_IfExp(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s representation as ... if ... else ... expression.
4.697386
3.974613
1.181847
return '.'.join((self.visit(node.value), node.attr))
def visit_Attribute(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s representation as attribute access.
6.876956
3.561541
1.930893
elems = [self.visit(node.lower), self.visit(node.upper)] if node.step is not None: elems.append(self.visit(node.step)) return ':'.join(elems)
def visit_Slice(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s representation as slice.
2.737349
2.265688
1.208175
return ', '.join((self.visit(dim) for dim in node.dims))
def visit_ExtSlice(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s representation as extended slice.
7.659348
5.023023
1.524848
target = node.target try: elts = target.elts # we have a tuple of names except AttributeError: names = self.visit(target) else: names = ', '.join(self.visit(elt) for elt in elts) src = f"for {names} in {self.visit(node.iter)}"...
def visit_comprehension(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s representation as comprehension.
3.394087
3.272093
1.037283
return f"[{self.visit(node.elt)} " \ f"{' '.join(self.visit(gen) for gen in node.generators)}]"
def visit_ListComp(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s representation as list comprehension.
4.730577
3.670035
1.288973
return f"{{{self.visit(node.elt)} " \ f"{' '.join(self.visit(gen) for gen in node.generators)}}}"
def visit_SetComp(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s representation as set comprehension.
5.303688
4.058452
1.306825
return f"{{{self.visit(node.key)}: {self.visit(node.value)} " \ f"{' '.join(self.visit(gen) for gen in node.generators)}}}"
def visit_DictComp(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s representation as dict comprehension.
3.822827
3.017174
1.267022
return f"({self.visit(node.elt)} " \ f"{' '.join(self.visit(gen) for gen in node.generators)})"
def visit_GeneratorExp(self, node: AST, dfltChaining: bool = True) -> str
Return `node`s representation as generator expression.
4.653404
3.743334
1.243118
parser = argparse.ArgumentParser( description='Python Disk Usage Calculator.') parser.add_argument("path", type=chkpath, nargs='?', default=".", help="A valid path.") return parser.parse_args()
def getargs()
Return a list of valid arguments.
5.592815
5.506183
1.015734
def visible_line_width(self, position = Point): extra_char_width = len([ None for c in self[:position].line_buffer if 0x2013 <= ord(c) <= 0xFFFD]) return len(self[:position].quoted_text()) + self[:position].line_buffer.count(u"\t")*7 + extra_char_width
Return the visible width of the text in line buffer up to position.
null
null
null
def copy_region_to_clipboard(self): # () u'''Copy the text in the region to the windows clipboard.''' if self.enable_win32_clipboard: mark = min(self.mark, len(self.line_buffer)) cursor = min(self.point, len(self.line_buffer)) if self.mark == -1: ...
u'''Copy the text in the region to the windows clipboard.
null
null
null
def copy_selection_to_clipboard(self): # () u'''Copy the text in the region to the windows clipboard.''' if self.enable_win32_clipboard and self.enable_selection and self.selection_mark >= 0: selection_mark = min(self.selection_mark,len(self.line_buffer)) cursor = min...
u'''Copy the text in the region to the windows clipboard.
null
null
null
import fnmatch import shutil import glob matches = [] matches.extend(glob.glob('./*.pyc')) matches.extend(glob.glob('./*.pyd')) matches.extend(glob.glob('./*.pyo')) matches.extend(glob.glob('./*.so')) dirs = [] dirs.extend(glob.glo...
def run(self)
Run CleanUp.
1.692452
1.639458
1.032325
if os.system('git add .'): sys.exit(1) if self.message is not None: os.system('git commit -a -m "' + self.message + '"') else: os.system('git commit -a')
def run(self)
Run git add and commit with message if provided.
3.036099
2.181587
1.391693
def saxon6(self, elem, **params): java = os.environ.get('java') or 'java' saxon6path = os.path.join(JARS, 'saxon.jar') # saxon 6.5.5, included with jing and trang with tempfile.TemporaryDirectory() as tempdir: if self.fn is None: xslfn = os.path.join(...
Use Saxon6 to process the element. If the XSLT has a filename (fn), use that. Otherwise, make temp.
null
null
null
jsonpointer.set_pointer(self.record, self.pointer, value)
def uri(self, value)
Set new uri value in record. It will not change the location of the underlying file!
14.028008
18.316002
0.765888
_fs, filename = opener.parse(self.uri) return _fs.open(filename, mode=mode, **kwargs)
def open(self, mode='r', **kwargs)
Open file ``uri`` under the pointer.
7.818916
6.379509
1.22563
_fs, filename = opener.parse(self.uri) _fs_dst, filename_dst = opener.parse(dst) movefile(_fs, filename, _fs_dst, filename_dst, **kwargs) self.uri = dst
def move(self, dst, **kwargs)
Move file to a new destination and update ``uri``.
4.990434
3.9391
1.266897
_fs, filename = opener.parse(self.uri) _fs_dst, filename_dst = opener.parse(dst) copyfile(_fs, filename, _fs_dst, filename_dst, **kwargs) return [{'op': 'replace', 'path': self.pointer, 'value': dst}]
def copy(self, dst, **kwargs)
Copy file to a new destination. Returns JSON Patch with proposed change pointing to new copy.
5.233764
4.839574
1.081451
if isinstance(source, six.string_types): _file = opener.open(source, 'rb') else: _file = source # signals.document_before_content_set.send(self) data = _file.read() _fs, filename = opener.parse(self.uri) _fs.setcontents(filename, data, *...
def setcontents(self, source, **kwargs)
Create a new file from a string or file-like object.
3.469137
3.292116
1.053771
if force: _fs, filename = opener.parse(self.uri) _fs.remove(filename) self.uri = None
def remove(self, force=False)
Remove file reference from record. If force is True it removes the file from filesystem
10.529545
10.973013
0.959586
def prefixed_to_namespaced(C, prefixed_name, namespaces): if ':' not in prefixed_name: return prefixed_name else: prefix, name = prefixed_name.split(':') namespace = namespaces[prefix] return "{%s}%s" % (namespace, name)
for a given prefix:name, return {namespace}name from the given namespaces dict
null
null
null
def xpath(C, node, path, namespaces=None, extensions=None, smart_strings=True, **args): return node.xpath( path, namespaces=namespaces or C.NS, extensions=extensions, smart_strings=smart_strings, **args )
shortcut to Element.xpath()
null
null
null
def find(C, node, path, namespaces=None, extensions=None, smart_strings=True, **args): xp = node.xpath( path, namespaces=namespaces or C.NS, extensions=extensions, smart_strings=smart_strings, **args ) if len(xp) > 0: ...
use Element.xpath() rather than Element.find() in order to normalize the interface
null
null
null
def tobytes( self, root=None, encoding='UTF-8', doctype=None, canonicalized=True, xml_declaration=True, pretty_print=True, with_comments=True, ): if root is None: root = self.root if canonicalized == Tr...
return the content of the XML document as a byte string suitable for writing
null
null
null
def tostring(self, root=None, doctype=None, pretty_print=True): if root is None: root = self.root return etree.tounicode( root, doctype=doctype or self.info.doctype, pretty_print=pretty_print )
return the content of the XML document as a unicode string
null
null
null
def digest(self, **args): return String(XML.canonicalized_string(self.root)).digest(**args)
calculate a digest based on the hash of the XML content
null
null
null
def element(self, tag_path, test=None, **attributes): xpath = tag_path tests = ["@%s='%s'" % (k, attributes[k]) for k in attributes] if test is not None: tests.insert(0, test) if len(tests) > 0: xpath += "[%s]" % ' and '.join(tests) e = se...
given a tag in xpath form and optional attributes, find the element in self.root or return a new one.
null
null
null
def Element(cls, s, *args): sargs = [] for arg in args: if type(arg) == etree._Element: sargs.append(etree.tounicode(arg)) else: sargs.append(arg) if type(s) == etree._Element: t = etree.tounicode(s) e...
given a string s and string *args, return an Element.
null
null
null
def jing(self, tag=None, schemas=None, schemafn=None, ext='.rnc'): from . import JARS java = os.environ.get('java') or 'java' jingfn = os.path.join(JARS, 'jing.jar') tag = tag or self.root.tag schemas = schemas or self.schemas schemafn = schemafn or Sche...
use the (included) jing library to validate the XML.
null
null
null
def namespace(self, elem=None): if elem is None: elem = self.root return XML.tag_namespace(elem.tag)
return the URL, if any, for the doc root or elem, if given.
null
null
null
def tag_namespace(cls, tag): md = re.match("^(?:\{([^\}]*)\})", tag) if md is not None: return md.group(1)
return the namespace for a given tag, or '' if no namespace given
null
null
null
def tag_name(cls, tag): while isinstance(tag, etree._Element): tag = tag.tag return tag.split('}')[-1]
return the name of the tag, with the namespace removed
null
null
null
def element_map( self, tags=None, xpath="//*", exclude_attribs=[], include_attribs=[], attrib_vals=False, hierarchy=False, minimize=False, ): if tags is None: tags = Dict() for elem in self.root.xpath(x...
return a dict of element tags, their attribute names, and optionally attribute values, in the XML document
null
null
null
def as_dict(self, elem=None, ignore_whitespace=True, namespaces=True): if elem is None: elem = self.root tag = self.tag_dict_key(elem.tag, namespaces=namespaces) d = Dict(**{tag: {}}) d[tag].update( **{ '@' + self.tag_dict_key(k, n...
Create a generalized dict output from this elem (default self.root). Rules: * Elements are objects with a single key, which is the tag. + if namespaces==True, the namespace or its prefix is included in the tag. * The value is an object: + '@name' = attribute with nam...
null
null
null
def dict_key_tag(Class, key, namespaces=None): namespaces = namespaces or Class.NS ns = Class.tag_namespace(key) tag = Class.tag_name(key) if ns is None and ':' in key: prefix, tag = key.split(':') if prefix in namespaces.keys(): n...
convert a dict key into an element or attribute name
null
null
null
def from_dict(Class, element_data, fn=None): from .builder import Builder B = Builder(default=Class.DEFAULT_NS, **Class.NS) keys = list(element_data.keys()) assert len(keys) == 1 key = keys[0] elem_tag = Class.dict_key_tag(key) elem = B(elem_tag...
reverse of XML.as_dict(): Create a new XML element from the given element_data. Rules: * element_data is a dict with one key, which is the name of the element * The element name can be in "prefix:..."" form, if the namespace prefix is in self.NS * The element name can also be...
null
null
null
def replace_with_contents(c, elem): "removes an element and leaves its contents in its place. Namespaces supported." parent = elem.getparent() index = parent.index(elem) children = elem.getchildren() previous = elem.getprevious() # text if index == 0: ...
removes an element and leaves its contents in its place. Namespaces supported.
null
null
null
def remove_range(cls, elem, end_elem, delete_end=True): while elem is not None and elem != end_elem and end_elem not in elem.xpath("descendant::*"): parent = elem.getparent() nxt = elem.getnext() parent.remove(elem) if DEBUG == True: ...
delete everything from elem to end_elem, including elem. if delete_end==True, also including end_elem; otherwise, leave it.
null
null
null
def wrap_content(cls, container, wrapper): "wrap the content of container element with wrapper element" wrapper.text = (container.text or '') + (wrapper.text or '') container.text = '' for ch in container: wrapper.append(ch) container.insert(0, wrapper) ...
wrap the content of container element with wrapper element
null
null
null
def merge_contiguous(C, node, xpath, namespaces=None): new_node = deepcopy(node) elems = XML.xpath(new_node, xpath, namespaces=namespaces) elems.reverse() for elem in elems: nxt = elem.getnext() if elem.attrib == {}: XML.replace_wi...
Within a given node, merge elements that are next to each other if they have the same tag and attributes.
null
null
null
def unnest(c, elem, ignore_whitespace=False): parent = elem.getparent() gparent = parent.getparent() index = parent.index(elem) # put everything up to elem into a new parent element right before the current parent preparent = etree.Element(parent.tag) prep...
unnest the element from its parent within doc. MUTABLE CHANGES
null
null
null
def interior_nesting(cls, elem1, xpath, namespaces=None): for elem2 in elem1.xpath(xpath, namespaces=namespaces): child_elem1 = etree.Element(elem1.tag) for k in elem1.attrib: child_elem1.set(k, elem1.get(k)) child_elem1.text, elem2.text = elem2...
for elem1 containing elements at xpath, embed elem1 inside each of those elements, and then remove the original elem1
null
null
null
def fragment_nesting(cls, elem1, tag2, namespaces=None): elems2 = elem1.xpath("child::%s" % tag2, namespaces=namespaces) while len(elems2) > 0: elem2 = elems2[0] parent2 = elem2.getparent() index2 = parent2.index(elem2) # all of elem2 has...
for elem1 containing elements with tag2, fragment elem1 into elems that are adjacent to and nested within tag2
null
null
null
if self._communityvisibilitystate == None: return None elif self._communityvisibilitystate in self.VisibilityState: return self.VisibilityState[self._communityvisibilitystate] else: #Invalid State return None
def communityvisibilitystate(self)
Return the Visibility State of the Users Profile
3.516935
3.27672
1.073309
if self._personastate == None: return None elif self._personastate in self.PersonaState: return self.PersonaState[self._personastate] else: #Invalid State return None
def personastate(self)
Return the Persona State of the Users Profile
3.458424
2.950801
1.172029
ls = [] for h in hwpack_names(): for b in board_names(h): ls += [mcu(b, h)] ls = sorted(list(set(ls))) return ls
def mcus()
MCU list.
7.721241
6.762478
1.141777
return datetime.datetime.strptime(re.match(r'.*/(.*) .*$',filepath).groups()[0],'%Y-%m-%d %H-%M')
def logpath2dt(filepath)
given a dataflashlog in the format produced by Mission Planner, return a datetime which says when the file was downloaded from the APM
3.801103
4.557811
0.833976
# Find if values are above or bellow yvalue crossing: above=series.values > cross below=scipy.logical_not(above) left_shifted_above = above[1:] left_shifted_below = below[1:] x_crossings = [] # Find indexes on left side of crossing point if direction == 'rising': idxs = (lef...
def cross(series, cross=0, direction='cross')
From http://stackoverflow.com/questions/10475488/calculating-crossing-intercept-points-of-a-series-or-dataframe Given a Series returns all the index values where the data values equal the 'cross' value. Direction can be 'rising' (for rising edge), 'falling' (for only falling edge), or 'cross' for b...
3.113245
3.078781
1.011194
finished = Deferred() response.deliverBody(TruncatingReadBodyProtocol( response.code, response.phrase, finished, max_bytes)) return finished
def read_body(response, max_bytes=None)
Return a `Deferred` yielding at most *max_bytes* bytes from the body of a Twisted Web *response*, or the whole body if *max_bytes* is `None`.
9.676897
7.881936
1.227731
if failure.check(ResponseFailed): if any(f.check(InfiniteRedirection) for f in failure.value.reasons): return u'Encountered too many redirects.' return u'Received incomplete response from server.' if failure.check(ConnectError, DNSLookupError, BlacklistedHost): ...
def describe_error(failure)
If *failure* is a common connection error, return a Unicode string describing it. Otherwise, return *failure*.
5.865286
5.643831
1.039239
hostname = urlparse(uri).hostname ip_str = yield self.resolve(hostname) # `ipaddress` takes a Unicode string and I don't really care to # handle `UnicodeDecodeError` separately. ip = ipaddress.ip_address(ip_str.decode('ascii', 'replace')) if ip.is_private or ip.i...
def request(self, method, uri, headers=None, bodyProducer=None)
Issue a request to the server indicated by *uri*.
4.922585
5.145353
0.956705
title = None if isinstance(url, unicode): url = URL.fromText(url) elif isinstance(url, str): url = URL.fromText(url.decode('ascii')) current = url response = None for _ in xrange(self.max_soft_redirects): last_response = respon...
def fetch_title(self, url, hostname_tag=False, friendly_errors=False)
Fetch the document at *url* and return a `Deferred` yielding the document title or summary as a Unicode string. *url* may be a Unicode string IRI, a byte string URI, or a Twisted `URL`. If *hostname_tag* is true, prefix the extracted title with the hostname of the initially requested U...
4.063475
3.803473
1.068359
'''returns played percentage [0,1] of item''' played = self.object_dict.get('UserData', {}).get('PlaybackPositionTicks') total = self.object_dict.get('RunTimeTicks') or 1 return (played or 0)/total
def percentage_played(self)
returns played percentage [0,1] of item
12.384029
9.205148
1.345337
'''url of the item Notes ----- if remote-adderes was given, then that is used as the base ''' path = '/web/itemdetails.html?id={}'.format(self.id) return self.connector.get_url(path, attach_api_key=False)
def url(self)
url of the item Notes ----- if remote-adderes was given, then that is used as the base
17.835264
6.18561
2.883348
'''reload object info from emby |coro| Parameters ---------- fields : str additional fields to request when updating See Also -------- refresh : same thing send : post : ''' path = 'Users/{{UserId}}/Items/{}'.format(self.id) info = await self.connector....
async def update(self, fields='')
reload object info from emby |coro| Parameters ---------- fields : str additional fields to request when updating See Also -------- refresh : same thing send : post :
16.476313
5.866618
2.808486
'''send data that was changed to emby |coro| This should be used after using any of the setter. Not necessarily immediately, but soon after. See Also -------- post: same thing update : refresh : Returns ------- aiohttp.ClientResponse or None if nothing needed ...
async def send(self)
send data that was changed to emby |coro| This should be used after using any of the setter. Not necessarily immediately, but soon after. See Also -------- post: same thing update : refresh : Returns ------- aiohttp.ClientResponse or None if nothing needed updatin...
10.106255
3.508549
2.880465
targ_dlib = libraries_dir() / lib_name log.debug('remove %s', targ_dlib) targ_dlib.rmtree()
def remove_lib(lib_name)
remove library. :param lib_name: library name (e.g. 'PS2Keyboard') :rtype: None
8.276092
8.756452
0.945142
cal = Calendar.from_ical(open(filename, 'rb').read()) holidays = [] for component in cal.walk('VEVENT'): start = component.decoded('DTSTART') try: end = component.decoded('DTEND') except KeyError: # RFC allows DTEND to be missing if isinstance(start, datetime): # For DATETIME instanc...
def _read_holidays(self, filename)
Read holidays from an iCalendar-format file.
3.243941
3.200346
1.013622
# convert to local timezone when = when.astimezone(self.tz) # is it a work day? if when.weekday() not in self.hours: # not a work day return False # work out if it is one of the ranges for start, end in self.hours[when.weekday()]: if start <= when.time() <= end: # it's in that range ...
def in_hours(self, when)
Find if the given :class:`~datetime.datetime` is in business hours for this office. :param datetime.datetime when: The time to check :returns: True if the given time is in business hours for the office, False otherwise. :rtype: bool
3.846775
3.877516
0.992072
if when == None: when = datetime.now(tz=utc) if office == None: for office in self.offices.itervalues(): if office.in_hours(when): return True return False else: # check specific office return self.offices[office].in_hours(when)
def in_hours(self, office=None, when=None)
Finds if it is business hours in the given office. :param office: Office ID to look up, or None to check if any office is in business hours. :type office: str or None :param datetime.datetime when: When to check the office is open, or None for now. :returns: True if it is business hours, False otherwise. :...
2.691544
2.582149
1.042366
loglevel = { 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, 3: logging.DEBUG, }.get(namespace.verbosity, logging.DEBUG) if namespace.verbosity > 1: logformat = '%(levelname)s csvpandas %(lineno)s %(message)s' else: logformat = 'csvpandas %(m...
def setup_logging(namespace)
setup global logging
2.731194
2.601617
1.049806
subparsers = parser.add_subparsers(dest='subparser_name') # add help sub-command parser_help = subparsers.add_parser( 'help', help='Detailed help for actions using `help <action>`') parser_help.add_argument('action', nargs=1) # add all other subcommands modules = [ name f...
def parse_subcommands(parser, subcommands, argv)
Setup all sub-commands
5.099226
5.016759
1.016438
def open_file(f): if f is sys.stdout or f is sys.stdin: return f elif f == '-': return sys.stdin if 'r' in mode else sys.stdout elif f.endswith('.bz2'): return bz2.BZ2File(f, mode) elif f.endswith('.gz'): return gzip.open(f, mode)...
def opener(mode='r')
Factory for creating file objects Keyword Arguments: - mode -- A string indicating how the file is to be opened. Accepts the same values as the builtin open() function. - bufsize -- The file's desired buffer size. Accepts the same values as the builtin open() function.
2.095617
2.224409
0.942101
resp = self.client.accounts.get(id) if no_summary: return self.display(resp) results = [] # Get a list of all volumes for this tenant id client = LunrClient(self.get_admin(), debug=self.debug) volumes = client.volumes.list(account_id=resp['id']) ...
def get(self, id, no_summary=False)
List details for a specific tenant id
5.244391
5.095862
1.029147
resp = self.client.accounts.create(id=id) self.display(resp)
def create(self, id)
Create a new tenant id
7.724401
7.208369
1.071588
resp = self.client.accounts.delete(id) self.display(resp)
def delete(self, id)
Delete an tenant id
8.999286
9.176392
0.9807
parser = argparse.ArgumentParser() group_tcp = parser.add_argument_group('TCP') group_tcp.add_argument('--tcp', dest='mode', action='store_const', const=PROP_MODE_TCP, help="Set tcp mode") group_tcp.add_argument('--host', dest='hostname', help="Specify hostname", default='') group_tcp.add_argum...
def main()
Main method for debug purposes.
2.079634
2.067846
1.005701
if (self._mode == PROP_MODE_SERIAL): self._serial = serial.Serial(self._serial_device, self._serial_speed) elif (self._mode == PROP_MODE_TCP): self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.connect((self._ip, self._port)) ...
def _open_connection(self)
Open a connection to the easyfire unit.
2.078529
1.948384
1.066797
if (self._mode == PROP_MODE_SERIAL): self._serial.close() elif (self._mode == PROP_MODE_TCP): self._socket.close() elif (self._mode == PROP_MODE_FILE): self._file.close()
def _close_connection(self)
Close the connection to the easyfire unit.
2.9177
2.583958
1.129159