code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
pattern_index = len(self.patterns) renamed_constraints = [c.with_renamed_vars(renaming) for c in pattern.local_constraints] constraint_indices = [self._add_constraint(c, pattern_index) for c in renamed_constraints] self.patterns.append((pattern, label, constraint_indices)) ...
def _internal_add(self, pattern: Pattern, label, renaming) -> int
Add a new pattern to the matcher. Equivalent patterns are not added again. However, patterns that are structurally equivalent, but have different constraints or different variable names are distinguished by the matcher. Args: pattern: The pattern to add. Returns: ...
4.367484
4.622143
0.944905
return _MatchIter(self, subject)
def match(self, subject: Expression) -> Iterator[Tuple[Expression, Substitution]]
Match the subject against all the matcher's patterns. Args: subject: The subject to match. Yields: For every match, a tuple of the matching pattern and the match substitution.
19.858047
47.219948
0.420544
if position is None: position = [0] if variables is None: variables = {} if getattr(expression, 'variable_name', False): if expression.variable_name not in variables: variables[expression.variable_name] = cls._get_name_for_position(pos...
def _collect_variable_renaming( cls, expression: Expression, position: List[int]=None, variables: Dict[str, str]=None ) -> Dict[str, str]
Return renaming for the variables in the expression. The variable names are generated according to the position of the variable in the expression. The goal is to rename variables in structurally identical patterns so that the automaton contains less redundant states.
2.3886
2.523107
0.94669
self.matcher.add(rule.pattern, rule.replacement)
def add(self, rule: 'functions.ReplacementRule') -> None
Add a new rule to the replacer. Args: rule: The rule to add.
8.503203
9.632515
0.88276
replaced = True replace_count = 0 while replaced and replace_count < max_count: replaced = False for subexpr, pos in preorder_iter_with_position(expression): try: replacement, subst = next(iter(self.matcher.match(subexpr))) ...
def replace(self, expression: Expression, max_count: int=math.inf) -> Union[Expression, Sequence[Expression]]
Replace all occurrences of the patterns according to the replacement rules. Args: expression: The expression to which the replacement rules are applied. max_count: If given, at most *max_count* applications of the rules are performed. Otherwise, the rules...
3.877773
4.400493
0.881213
return self._replace_post_order(expression)[0]
def replace_post_order(self, expression: Expression) -> Union[Expression, Sequence[Expression]]
Replace all occurrences of the patterns according to the replacement rules. Replaces innermost expressions first. Args: expression: The expression to which the replacement rules are applied. max_count: If given, at most *max_count* applications o...
7.070641
14.109263
0.501135
raise ImportError('The graphviz package is required to draw the graph.') graph = Graph() nodes_left = {} # type: Dict[TLeft, str] nodes_right = {} # type: Dict[TRight, str] node_id = 0 for (left, right), value in self.bipartite._edges.items(): if left no...
def bipartite_as_graph(self) -> Graph: # pragma: no cover if Graph is None
Returns a :class:`graphviz.Graph` representation of this bipartite graph.
2.534039
2.423751
1.045503
raise ImportError('The graphviz package is required to draw the graph.') bipartite = self._build_bipartite(subjects, patterns) graph = Graph() nodes_left = {} # type: Dict[TLeft, str] nodes_right = {} # type: Dict[TRight, str] node_id = 0 for (left, right), ...
def concrete_bipartite_as_graph(self, subjects, patterns) -> Graph: # pragma: no cover if Graph is None
Returns a :class:`graphviz.Graph` representation of this bipartite graph.
2.528686
2.478656
1.020184
if self.variable_name is not None: variables.add(self.variable_name)
def collect_variables(self, variables: MultisetOfVariables) -> None
Recursively adds all variables occuring in the expression to the given multiset. This is used internally by `variables`. Needs to be overwritten by inheriting container expression classes. This method can be used when gathering the `variables` of multiple expressions, because only one multiset ...
5.262314
4.911959
1.071327
if cls.associative: new_operands = [] # type: List[Expression] for operand in operands: if isinstance(operand, cls): new_operands.extend(operand.operands) # type: ignore else: new_operands.append(operand)...
def _simplify(cls, operands: List[Expression]) -> bool
Flatten/sort the operands of associative/commutative operations. Returns: True iff *one_identity* is True and the operation contains a single argument that is not a sequence wildcard.
3.010969
2.556257
1.177882
class_name = class_name or name if not class_name.isidentifier() or keyword.iskeyword(class_name): raise ValueError("Invalid identifier for new operator class.") return type( class_name, (Operation, ), { 'name': name, 'arity': ari...
def new( name: str, arity: Arity, class_name: str=None, *, associative: bool=False, commutative: bool=False, one_identity: bool=False, infix: bool=False ) -> Type['Operation']
Utility method to create a new operation type. Example: >>> Times = Operation.new('*', Arity.polyadic, 'Times', associative=True, commutative=True, one_identity=True) >>> Times Times['*', Arity(min_count=2, fixed_size=False), associative, commutative, one_identity] >>> str(Time...
2.127065
2.266347
0.938544
return Wildcard(min_count=1, fixed_size=True, variable_name=name, optional=default)
def optional(name, default) -> 'Wildcard'
Create a `Wildcard` that matches a single argument with a default value. If the wildcard does not match, the substitution will contain the default value instead. Args: name: The name for the wildcard. default: The default value of the wil...
10.152008
16.608183
0.611265
if isinstance(name, type) and issubclass(name, Symbol) and symbol_type is Symbol: return SymbolWildcard(name) return SymbolWildcard(symbol_type, variable_name=name)
def symbol(name: str=None, symbol_type: Type[Symbol]=Symbol) -> 'SymbolWildcard'
Create a `SymbolWildcard` that matches a single `Symbol` argument. Args: name: Optional variable name for the wildcard. symbol_type: An optional subclass of `Symbol` to further limit which kind of symbols are matched by the wildcard. ...
3.523236
4.19731
0.839403
if method in self.ALLOWED_REQUESTS: # add request token header headers = headers or {} # test if Oauth token if self.token_type == 'legacy': headers.update( {'Token': self.api_key, 'User-Agent': 'o...
def request(self, method, url_parts, headers=None, data=None)
Method for making requests to the Optimizely API
2.990305
2.829445
1.056852
if resp.status_code in [200, 201, 202]: return resp.json() elif resp.status_code == 204: return None elif resp.status_code == 400: raise error.BadRequestError(resp.text) elif resp.status_code == 401: raise error.UnauthorizedError(r...
def parse_response(resp)
Method to parse response from the Optimizely API and return results as JSON. Errors are thrown for various errors that the API can throw.
1.423211
1.358567
1.047583
if o is None: return "NA" if isinstance(o, basestring): return o if hasattr(o, "r"): # bridge to @property r on GGStatement(s) return o.r elif isinstance(o, bool): return "TRUE" if o else "FALSE" elif isinstance(o, (list, tuple)): inner = ",".join...
def _to_r(o, as_data=False, level=0)
Helper function to convert python data structures to R equivalents TODO: a single model for transforming to r to handle * function args * lists as function args
2.757813
2.712363
1.016757
if not db: if sql: print "ERR: -db option must be set if using -sql" return "" cmd = return GGData(cmd % { 'db_name': db, 'query': sql })
def data_sql(db, sql)
Load file using RPostgreSQL Place to edit if want to add more database backend support
15.413861
16.001972
0.963248
if isinstance(o, basestring): fname = o else: if not is_pandas_df(o): # convert incoming data layout to pandas' DataFrame o = pandas.DataFrame(o) fname = tempfile.NamedTemporaryFile().name o.to_csv(fname, sep=',', encoding='utf-8', index=False) kw...
def data_py(o, *args, **kwargs)
converts python object into R Dataframe definition converts following data structures: row oriented list of dictionaries: [ { 'x': 0, 'y': 1, ...}, ... ] col oriented dictionary of lists { 'x': [0,1,2...], 'y': [...], ... } @param o python object to convert @param args ...
6.427516
6.275914
1.024156
# constants kwdefaults = { 'width': 10, 'height': 8, 'scale': 1 } keys_to_rm = ["prefix", "quiet", "postfix", 'libs'] varname = 'p' # process arguments prefix = kwargs.get('prefix', '') postfix = kwargs.get('postfix', '') libs = kwargs.get('libs', []) ...
def ggsave(name, plot, data=None, *args, **kwargs)
Save a GGStatements object to destination name @param name output file name. if None, don't run R command @param kwargs keyword args to pass to ggsave. The following are special keywords for the python save method data: a python data object (list, dict, DataFrame) used to populate ...
4.286082
3.704115
1.157114
try: import IPython.display tmp_image_filename = tempfile.NamedTemporaryFile(suffix='.jpg').name # Quiet by default kwargs['quiet'] = kwargs.get('quiet', True) if width is None: raise ValueError("Width cannot be None") height = height or width ...
def gg_ipython(plot, data, width=IPYTHON_IMAGE_SIZE, height=None, *args, **kwargs)
Render pygg in an IPython notebook Allows one to say things like: import pygg p = pygg.ggplot('diamonds', pygg.aes(x='carat', y='price', color='clarity')) p += pygg.geom_point(alpha=0.5, size = 2) p += pygg.scale_x_log10(limits=[1, 2]) pygg.gg_ipython(p, data=None, quiet=True) directly in...
4.281508
4.716404
0.907791
# both width and height are given aspect_ratio = height / (1.0 * width) return R_IMAGE_SIZE, round(aspect_ratio * R_IMAGE_SIZE, 2)
def size_r_img_inches(width, height)
Compute the width and height for an R image for display in IPython Neight width nor height can be null but should be integer pixel values > 0. Returns a tuple of (width, height) that should be used by ggsave in R to produce an appropriately sized jpeg/png/pdf image with the right aspect ratio. The re...
5.500604
7.507321
0.732699
FNULL = open(os.devnull, 'w') if quiet else None try: input_proc = subprocess.Popen(["echo", prog], stdout=subprocess.PIPE) status = subprocess.call("R --no-save --quiet", stdin=input_proc.stdout, stdout=FNULL, ...
def execute_r(prog, quiet)
Run the R code prog an R subprocess @raises ValueError if the subprocess exits with non-zero status
4.284472
4.384245
0.977243
exec "xfunc = scale_x_%s" % xsuffix exec "yfunc = scale_y_%s" % ysuffix return ( xfunc(name=esc(xtitle), **xkwargs) + yfunc(name=esc(ytitle), **ykwargs) )
def axis_labels(xtitle, ytitle, xsuffix="continuous", ysuffix="continuous", xkwargs={}, ykwargs={})
Helper function to create reasonable axis labels @param xtitle String for the title of the X axis. Automatically escaped @param ytitle String for the title of the Y axis. Automatically escaped @param xsuffix Suffix string appended to "scales_x_" to define the type of x axis Default: "continuou...
4.922152
4.48299
1.097962
ggplot = make_ggplot2_binding("ggplot") def _ggplot(data, *args, **kwargs): data_var = data if not isinstance(data, basestring): data_var = "data" else: data = None stmt = ggplot(data_var, *args, **kwargs) stmt.data = data return stmt return _ggplot
def make_master_binding()
wrap around ggplot() call to handle passed in data objects
4.594017
3.675439
1.249923
r_args = [_to_r(self.args), _to_r(self.kwargs)] # remove empty strings from the call args r_args = ",".join([x for x in r_args if x != ""]) return "{}({})".format(self.name, r_args)
def r(self)
Convert this GGStatement into its R equivalent expression
4.805607
4.462049
1.076996
if not c: print "no command. exiting" return kwargs = { 'width': w, 'height': h, 'scale': scale, 'prefix': '\n'.join(filter(bool, [prefix])) } if csv: kwargs['data'] = csv else: kwargs['data'] = data_sql(db, sql) c = "plot = %s" % c if o: exec c plot.save(o...
def main(c, prefix, csv, db, sql, o, w, h, scale)
ggplot2 syntax in Python. Run pygg command from command line python pygg -c "ggplot('diamonds', aes('carat', 'price')) + geom_point()" Import into your python program to use ggplot \b from pygg import * p = ggplot('diamonds', aes('carat', y='price')) + geom_point() p = p + facet_wrap(None, "...
4.933767
4.493797
1.097906
logger = logging.getLogger('geobuf') stdin = click.get_text_stream('stdin') sink = click.get_binary_stream('stdout') try: data = json.load(stdin) pbf = geobuf.encode( data, precision if precision >= 0 else 6, 3 if with_z else 2) sink.write...
def encode(precision, with_z)
Given GeoJSON on stdin, writes a geobuf file to stdout.
3.623493
3.184321
1.137917
logger = logging.getLogger('geobuf') stdin = click.get_binary_stream('stdin') sink = click.get_text_stream('stdout') try: pbf = stdin.read() data = geobuf.decode(pbf) json.dump(data, sink) sys.exit(0) except Exception: logger.exception("Failed. Exception ...
def decode()
Given a Geobuf byte string on stdin, write a GeoJSON feature collection to stdout.
3.892072
3.353318
1.160663
if code < 0: raise ValueError('Only positive ints are allowed!') if bits_per_char == 6: return _encode_int64(code) if bits_per_char == 4: return _encode_int16(code) if bits_per_char == 2: return _encode_int4(code) raise ValueError('`bits_per_char` must be in {6...
def encode_int(code, bits_per_char=6)
Encode int into a string preserving order It is using 2, 4 or 6 bits per coding character (default 6). Parameters: code: int Positive integer. bits_per_char: int The number of bits per coding character. Returns: str: the encoded integer
2.394459
2.501994
0.957021
if bits_per_char == 6: return _decode_int64(tag) if bits_per_char == 4: return _decode_int16(tag) if bits_per_char == 2: return _decode_int4(tag) raise ValueError('`bits_per_char` must be in {6, 4, 2}')
def decode_int(tag, bits_per_char=6)
Decode string into int assuming encoding with `encode_int()` It is using 2, 4 or 6 bits per coding character (default 6). Parameters: tag: str Encoded integer. bits_per_char: int The number of bits per coding character. Returns: int: the decoded string
2.183373
2.372079
0.920447
assert _LNG_INTERVAL[0] <= lng <= _LNG_INTERVAL[1] assert _LAT_INTERVAL[0] <= lat <= _LAT_INTERVAL[1] assert precision > 0 assert bits_per_char in (2, 4, 6) bits = precision * bits_per_char level = bits >> 1 dim = 1 << level x, y = _coord2int(lng, lat, dim) if CYTHON_AVAILABL...
def encode(lng, lat, precision=10, bits_per_char=6)
Encode a lng/lat position as a geohash using a hilbert curve This function encodes a lng/lat coordinate to a geohash of length `precision` on a corresponding a hilbert curve. Each character encodes `bits_per_char` bits per character (allowed are 2, 4 and 6 bits [default 6]). Hence, the geohash encodes ...
3.499418
3.449428
1.014492
assert bits_per_char in (2, 4, 6) if len(code) == 0: return 0., 0. lng, lat, _lng_err, _lat_err = decode_exactly(code, bits_per_char) return lng, lat
def decode(code, bits_per_char=6)
Decode a geohash on a hilbert curve as a lng/lat position Decodes the geohash `code` as a lng/lat position. It assumes, that the length of `code` corresponds to the precision! And that each character in `code` encodes `bits_per_char` bits. Do not mix geohashes with different `bits_per_char`! Param...
4.105783
3.852938
1.065624
assert bits_per_char in (2, 4, 6) if len(code) == 0: return 0., 0., _LNG_INTERVAL[1], _LAT_INTERVAL[1] bits = len(code) * bits_per_char level = bits >> 1 dim = 1 << level code_int = decode_int(code, bits_per_char) if CYTHON_AVAILABLE and bits <= MAX_BITS: x, y = hash2...
def decode_exactly(code, bits_per_char=6)
Decode a geohash on a hilbert curve as a lng/lat position with error-margins Decodes the geohash `code` as a lng/lat position with error-margins. It assumes, that the length of `code` corresponds to the precision! And that each character in `code` encodes `bits_per_char` bits. Do not mix geohashes with dif...
4.285247
3.799656
1.127799
assert dim >= 1 lat_y = (lat + _LAT_INTERVAL[1]) / 180.0 * dim # [0 ... dim) lng_x = (lng + _LNG_INTERVAL[1]) / 360.0 * dim # [0 ... dim) return min(dim - 1, int(floor(lng_x))), min(dim - 1, int(floor(lat_y)))
def _coord2int(lng, lat, dim)
Convert lon, lat values into a dim x dim-grid coordinate system. Parameters: lng: float Longitude value of coordinate (-180.0, 180.0); corresponds to X axis lat: float Latitude value of coordinate (-90.0, 90.0); corresponds to Y axis dim: int Number of coding points each x, y val...
3.269127
3.558967
0.918561
assert dim >= 1 assert x < dim assert y < dim lng = x / dim * 360 - 180 lat = y / dim * 180 - 90 return lng, lat
def _int2coord(x, y, dim)
Convert x, y values in dim x dim-grid coordinate system into lng, lat values. Parameters: x: int x value of point [0, dim); corresponds to longitude y: int y value of point [0, dim); corresponds to latitude dim: int Number of coding points each x, y value can take. ...
2.882394
3.132689
0.920102
d = 0 lvl = dim >> 1 while (lvl > 0): rx = int((x & lvl) > 0) ry = int((y & lvl) > 0) d += lvl * lvl * ((3 * rx) ^ ry) x, y = _rotate(lvl, x, y, rx, ry) lvl >>= 1 return d
def _xy2hash(x, y, dim)
Convert (x, y) to hashcode. Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: x: int x value of point [0, dim) in dim x dim coord system y: int y value of point [0, dim) ...
3.823873
4.099648
0.932732
assert(hashcode <= dim * dim - 1) x = y = 0 lvl = 1 while (lvl < dim): rx = 1 & (hashcode >> 1) ry = 1 & (hashcode ^ rx) x, y = _rotate(lvl, x, y, rx, ry) x += lvl * rx y += lvl * ry hashcode >>= 2 lvl <<= 1 return x, y
def _hash2xy(hashcode, dim)
Convert hashcode to (x, y). Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: hashcode: int Hashcode to decode [0, dim**2) dim: int Number of coding points each x, y value can t...
3.768064
4.155138
0.906845
if ry == 0: if rx == 1: x = n - 1 - x y = n - 1 - y return y, x return x, y
def _rotate(n, x, y, rx, ry)
Rotate and flip a quadrant appropriately Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
3.624755
3.768152
0.961945
lng, lat, lng_err, lat_err = decode_exactly(code, bits_per_char) precision = len(code) north = lat + 2 * lat_err south = lat - 2 * lat_err east = lng + 2 * lng_err if east > 180: east -= 360 west = lng - 2 * lng_err if west < -180: west += 360 neighbours_dic...
def neighbours(code, bits_per_char=6)
Get the neighbouring geohashes for `code`. Look for the north, north-east, east, south-east, south, south-west, west, north-west neighbours. If you are at the east/west edge of the grid (lng ∈ (-180, 180)), then it wraps around the globe and gets the corresponding neighbor. Parameters: cod...
1.935778
1.900714
1.018448
lng, lat, lng_err, lat_err = decode_exactly(code, bits_per_char) return { 'type': 'Feature', 'properties': { 'code': code, 'lng': lng, 'lat': lat, 'lng_err': lng_err, 'lat_err': lat_err, 'bits_per_char': bits_per_char,...
def rectangle(code, bits_per_char=6)
Builds a (geojson) rectangle from `code` The center of the rectangle decodes as the lng/lat for code and the rectangle corresponds to the error-margin, i.e. every lng/lat point within this rectangle will be encoded as `code`, given `precision == len(code)`. Parameters: code: str The ...
1.662763
1.681132
0.989074
bits = precision * bits_per_char coords = [] for i in range(1 << bits): code = encode_int(i, bits_per_char).rjust(precision, '0') coords += [decode(code, bits_per_char)] return { 'type': 'Feature', 'properties': {}, 'geometry': { 'type': 'LineSt...
def hilbert_curve(precision, bits_per_char=6)
Build the (geojson) `LineString` of the used hilbert-curve Builds the `LineString` of the used hilbert-curve given the `precision` and the `bits_per_char`. The number of bits to encode the geohash is equal to `precision * bits_per_char`, and for each level, you need 2 bits, hence the number of bits has...
2.925172
2.763437
1.058527
if expected: if not received or expected != received: return False else: if received: return False return True
def isSignatureValid(expected, received)
Verifies that the received signature matches the expected value
3.237297
3.41748
0.947276
if self._disconnectCBs is None: self._disconnectCBs = [] self._disconnectCBs.append(callback)
def notifyOnDisconnect(self, callback)
Registers a callback that will be called when the DBus connection underlying the remote object is lost @type callback: Callable object accepting a L{RemoteDBusObject} and L{twisted.python.failure.Failure} @param callback: Function that will be called when the connection ...
3.000609
3.8063
0.788327
if self._disconnectCBs: for cb in self._disconnectCBs: cb(self, reason)
def connectionLost(self, reason)
Called by the L{DBusObjectHandler} when the connection is lost
4.724708
4.704735
1.004245
iface = None signal = None for i in self.interfaces: if interface and not i.name == interface: continue if signalName in i.signals: signal = i.signals[signalName] iface = i break def callb...
def notifyOnSignal(self, signalName, callback, interface=None)
Informs the DBus daemon of the process's interest in the specified signal and registers the callback function to be called when the signal arrives. Multiple callbacks may be registered. @type signalName: C{string} @param signalName: Name of the signal to register the callback for ...
4.085322
3.994345
1.022776
if self._signalRules and rule_id in self._signalRules: self.objHandler.conn.delMatch(rule_id) self._signalRules.remove(rule_id)
def cancelSignalNotification(self, rule_id)
Cancels a callback previously registered with notifyOnSignal
6.079714
6.4765
0.938735
expectReply = kwargs.get('expectReply', True) autoStart = kwargs.get('autoStart', True) timeout = kwargs.get('timeout', None) interface = kwargs.get('interface', None) m = None for i in self.interfaces: if interface and not interface == i.name: ...
def callRemote(self, methodName, *args, **kwargs)
Calls the remote method and returns a Deferred instance to the result. DBus does not support passing keyword arguments over the wire. The keyword arguments accepted by this method alter the behavior of the remote call as described in the kwargs prameter description. @type methodName: C{...
3.164716
2.805319
1.128113
for wref in self._weakProxies.valuerefs(): p = wref() if p is not None: p.connectionLost(reason)
def connectionLost(self, reason)
Called by the DBus Connection object when the connection is lost. @type reason: L{twistd.python.failure.Failure} @param reason: The value passed to the associated connection's connectionLost method.
6.439766
8.240371
0.78149
o = IDBusObject(dbusObject) self.exports[o.getObjectPath()] = o o.setObjectHandler(self) i = {} for iface in o.getInterfaces(): i[iface.name] = o.getAllProperties(iface.name) msig = message.SignalMessage( o.getObjectPath(), '...
def exportObject(self, dbusObject)
Makes the specified object available over DBus @type dbusObject: an object implementing the L{IDBusObject} interface @param dbusObject: The object to export over DBus
5.169391
5.985879
0.863598
d = {} for p in sorted(self.exports.keys()): if not p.startswith(objectPath) or p == objectPath: continue o = self.exports[p] i = {} d[p] = i for iface in o.getInterfaces(): i[iface.name] = o.getAllProp...
def getManagedObjects(self, objectPath)
Returns a Python dictionary containing the reply content for org.freedesktop.DBus.ObjectManager.GetManagedObjects
4.123681
4.018778
1.026103
r = message.ErrorMessage( errName, msg.serial, body=[errMsg], signature='s', destination=msg.sender, ) self.conn.sendMessage(r)
def _send_err(self, msg, errName, errMsg)
Helper method for sending error messages
13.531116
13.633842
0.992465
if ( msg.interface == 'org.freedesktop.DBus.Peer' and msg.member == 'Ping' ): r = message.MethodReturnMessage( msg.serial, destination=msg.sender, ) self.conn.sendMessage(r) return ...
def handleMethodCallMessage(self, msg)
Handles DBus MethodCall messages on behalf of the DBus Connection and dispatches them to the appropriate exported object
2.561842
2.528139
1.013331
weak_id = (busName, objectPath, interfaces) need_introspection = False required_interfaces = set() if interfaces is not None: ifl = [] if not isinstance(interfaces, list): interfaces = [interfaces] for i in interfaces: ...
def getRemoteObject(self, busName, objectPath, interfaces=None, replaceKnownInterfaces=False)
Creates a L{RemoteDBusObject} instance to represent the specified DBus object. If explicit interfaces are not supplied, DBus object introspection will be used to obtain them automatically. @type busName: C{string} @param busName: Name of the bus exporting the desired object ...
2.993676
2.894326
1.034326
if m.nargs == -1: m.nargs = len([a for a in marshal.genCompleteTypes(m.sigIn)]) m.nret = len([a for a in marshal.genCompleteTypes(m.sigOut)]) self.methods[m.name] = m self._xml = None
def addMethod(self, m)
Adds a L{Method} to the interface
5.586029
5.556911
1.00524
if s.nargs == -1: s.nargs = len([a for a in marshal.genCompleteTypes(s.sig)]) self.signals[s.name] = s self._xml = None
def addSignal(self, s)
Adds a L{Signal} to the interface
10.597902
9.910213
1.069392
from txdbus import endpoints f = DBusClientFactory() d = f.getConnection() eplist = endpoints.getDBusEndpoints(reactor, busAddress) eplist.reverse() def try_next_ep(err): if eplist: eplist.pop().connect(f).addErrback(try_next_ep) else: d.errback(...
def connect(reactor, busAddress='session')
Connects to the specified bus and returns a L{twisted.internet.defer.Deferred} to the fully-connected L{DBusClientConnection}. @param reactor: L{twisted.internet.interfaces.IReactor} implementor @param busAddress: 'session', 'system', or a valid bus address as defined by the DBus specification...
3.698869
4.179464
0.88501
self.router = router.MessageRouter() self.match_rules = {} self.objHandler = objects.DBusObjectHandler(self) # serial_number => (deferred, delayed_timeout_cb | None): self._pendingCalls = {} self._dcCallbacks = [] d = self.callRemote( '/Hello...
def connectionAuthenticated(self)
Called by L{protocol.BasicDBusProtocol} when the DBus authentication has completed successfully.
10.227566
9.323886
1.096921
self.busName = busName # print 'Connection Bus Name = ', self.busName self.factory._ok(self)
def _cbGotHello(self, busName)
Called in reply to the initial Hello remote method invocation
12.440737
10.573779
1.176565
if self.busName is None: return for cb in self._dcCallbacks: cb(self, reason) for d, timeout in self._pendingCalls.values(): if timeout: timeout.cancel() d.errback(reason) self._pendingCalls = {} self.obj...
def connectionLost(self, reason)
Called when the transport loses connection to the bus
6.032983
5.422223
1.11264
return self.objHandler.getRemoteObject( busName, objectPath, interfaces, replaceKnownInterfaces, )
def getRemoteObject(self, busName, objectPath, interfaces=None, replaceKnownInterfaces=False)
Creates a L{objects.RemoteDBusObject} instance to represent the specified DBus object. If explicit interfaces are not supplied, DBus object introspection will be used to obtain them automatically. @param interfaces: May be None, a single value, or a list of string in...
3.688478
6.994511
0.527339
rule = self.match_rules[rule_id] d = self.callRemote( '/org/freedesktop/DBus', 'RemoveMatch', interface='org.freedesktop.DBus', destination='org.freedesktop.DBus', body=[rule], signature='s', ) def ok(_): ...
def delMatch(self, rule_id)
Removes a message matching rule previously registered with addMatch
4.069607
3.848716
1.057393
l = [] def add(k, v): if v is not None: l.append("%s='%s'" % (k, v)) add('type', mtype) add('sender', sender) add('interface', interface) add('member', member) add('path', path) add('path_namespace', path_namespace) ...
def addMatch(self, callback, mtype=None, sender=None, interface=None, member=None, path=None, path_namespace=None, destination=None, arg=None, arg_path=None, arg0namespace=None)
Creates a message matching rule, associates it with the specified callback function, and sends the match rule to the DBus daemon. The arguments to this function are exactly follow the DBus specification. Refer to the \"Message Bus Message Routing\" section of the DBus specification for ...
2.269259
2.243646
1.011416
d = self.callRemote( '/org/freedesktop/DBus', 'GetNameOwner', interface='org.freedesktop.DBus', signature='s', body=[busName], destination='org.freedesktop.DBus', ) return d
def getNameOwner(self, busName)
Calls org.freedesktop.DBus.GetNameOwner @rtype: L{twisted.internet.defer.Deferred} @returns: a Deferred to the unique connection name owning the bus name
3.357629
3.05527
1.098963
flags = 0 if allowReplacement: flags |= 0x1 if replaceExisting: flags |= 0x2 if doNotQueue: flags |= 0x4 d = self.callRemote( '/org/freedesktop/DBus', 'RequestName', interface='org.freedesktop.DBus'...
def requestBusName(self, newName, allowReplacement=False, replaceExisting=False, doNotQueue=True, errbackUnlessAcquired=True)
Calls org.freedesktop.DBus.RequestName to request that the specified bus name be associated with the connection. @type newName: C{string} @param newName: Bus name to acquire @type allowReplacement: C{bool} @param allowReplacement: If True (defaults to False) and another ...
2.995919
3.12939
0.957349
d = self.callRemote( objectPath, 'Introspect', interface='org.freedesktop.DBus.Introspectable', destination=busName, ) def ok(xml_str): return introspection.getInterfacesFromXML( xml_str, replac...
def introspectRemoteObject(self, busName, objectPath, replaceKnownInterfaces=False)
Calls org.freedesktop.DBus.Introspectable.Introspect @type busName: C{string} @param busName: Name of the bus containing the object @type objectPath: C{string} @param objectPath: Object Path to introspect @type replaceKnownInterfaces: C{bool} @param replaceKnownInterfa...
3.5072
3.943937
0.889264
if msg is None: return None if returnSignature != _NO_CHECK_RETURN: if not returnSignature: if msg.signature: raise error.RemoteError( 'Unexpected return value signature') else: if n...
def _cbCvtReply(self, msg, returnSignature)
Converts a remote method call reply message into an appropriate callback value.
3.497738
3.464814
1.009502
try: mcall = message.MethodCallMessage( objectPath, methodName, interface=interface, destination=destination, signature=signature, body=body, expectReply=expectReply, ...
def callRemote(self, objectPath, methodName, interface=None, destination=None, signature=None, body=None, expectReply=True, autoStart=True, timeout=None, returnSignatur...
Calls a method on a remote DBus object and returns a deferred to the result. @type objectPath: C{string} @param objectPath: Path of the remote object @type methodName: C{string} @param methodName: Name of the method to call @type interface: None or C{string} @p...
3.9412
4.46191
0.883299
del self._pendingCalls[serial] d.errback(error.TimeOut('Method call timed out'))
def _onMethodTimeout(self, serial, d)
Called when a remote method invocation timeout occurs
7.951497
9.625575
0.82608
assert isinstance(mcall, message.MethodCallMessage) if mcall.expectReply: d = defer.Deferred() if timeout: timeout = reactor.callLater( timeout, self._onMethodTimeout, mcall.serial, d) self._pendingCalls[mcall.serial] = ...
def callRemoteMessage(self, mcall, timeout=None)
Uses the specified L{message.MethodCallMessage} to call a remote method @rtype: L{twisted.internet.defer.Deferred} @returns: a Deferred to the result of the remote method call
3.164552
3.098666
1.021263
d, timeout = self._pendingCalls.get(mret.reply_serial, (None, None)) if timeout: timeout.cancel() if d: del self._pendingCalls[mret.reply_serial] d.callback(mret)
def methodReturnReceived(self, mret)
Called when a method return message is received
3.690971
3.747239
0.984984
d, timeout = self._pendingCalls.get(merr.reply_serial, (None, None)) if timeout: timeout.cancel() if d: del self._pendingCalls[merr.reply_serial] e = error.RemoteError(merr.error_name) e.message = '' e.values = [] i...
def errorReceived(self, merr)
Called when an error message is received
3.427822
3.388597
1.011576
env = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None) if env is None: raise Exception('DBus Session environment variable not set') return getDBusEndpoints(reactor, env, client)
def getDBusEnvEndpoints(reactor, client=True)
Creates endpoints from the DBUS_SESSION_BUS_ADDRESS environment variable @rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint} @returns: A list of endpoint instances
3.366037
4.25529
0.791024
if busAddress == 'session': addrString = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None) if addrString is None: raise Exception('DBus Session environment variable not set') elif busAddress == 'system': addrString = os.environ.get( 'DBUS_SYSTEM_BUS_ADDRESS'...
def getDBusEndpoints(reactor, busAddress, client=True)
Creates DBus endpoints. @param busAddress: 'session', 'system', or a valid bus address as defined by the DBus specification. If 'session' (the default) or 'system' is supplied, the contents of the DBUS_SESSION_BUS_ADDRESS or DBUS_SYSTEM_BUS_ADDRESS environment variables will be used for the...
2.88111
2.752254
1.046818
if not p.startswith('/'): raise MarshallingError('Object paths must begin with a "/"') if len(p) > 1 and p[-1] == '/': raise MarshallingError('Object paths may not end with "/"') if '//' in p: raise MarshallingError('"//" is not allowed in object paths"') if invalid_obj_path...
def validateObjectPath(p)
Ensures that the provided object path conforms to the DBus standard. Throws a L{error.MarshallingError} if non-conformant @type p: C{string} @param p: A DBus object path
2.970907
2.986751
0.994695
try: if '.' not in n: raise Exception('At least two components required') if '..' in n: raise Exception('".." not allowed in interface names') if len(n) > 255: raise Exception('Name exceeds maximum length of 255') if n[0] == '.': r...
def validateInterfaceName(n)
Verifies that the supplied name is a valid DBus Interface name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus interface name
3.300321
3.437419
0.960116
try: if '.' not in n: raise Exception('At least two components required') if '..' in n: raise Exception('".." not allowed in bus names') if len(n) > 255: raise Exception('Name exceeds maximum length of 255') if n[0] == '.': raise E...
def validateBusName(n)
Verifies that the supplied name is a valid DBus Bus name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus bus name
3.679434
3.844042
0.957178
try: if len(n) < 1: raise Exception('Name must be at least one byte in length') if len(n) > 255: raise Exception('Name exceeds maximum length of 255') if n[0].isdigit(): raise Exception('Names may not begin with a digit') if mbr_re.search(n): ...
def validateMemberName(n)
Verifies that the supplied name is a valid DBus member name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus member name
3.243041
3.200418
1.013318
f = os.fdopen(fd, 'rb') result = len(f.read()) f.close() return result
def dbus_lenFD(self, fd)
Returns the byte count after reading till EOF.
3.171623
2.75246
1.152286
f = os.fdopen(fd, 'rb') result = f.read(byte_count) f.close() return bytearray(result)
def dbus_readBytesFD(self, fd, byte_count)
Reads byte_count bytes from fd and returns them.
2.570668
2.654489
0.968423
result = bytearray() for fd in (fd1, fd2): f = os.fdopen(fd, 'rb') result.extend(f.read(byte_count)) f.close() return result
def dbus_readBytesTwoFDs(self, fd1, fd2, byte_count)
Reads byte_count from fd1 and fd2. Returns concatenation.
2.566458
2.448684
1.048096
l = [_dtd_decl] l.append('<node name="%s">' % (objectPath,)) obj = exportedObjects.get(objectPath, None) if obj is not None: for i in obj.getInterfaces(): l.append(i.introspectionXml) l.append(_intro) # make sure objectPath ends with '/' to only get partial matches...
def generateIntrospectionXML(objectPath, exportedObjects)
Generates the introspection XML for an object path or partial object path that matches exported objects. This allows for browsing the exported objects with tools such as d-feet. @rtype: C{string}
3.792286
4.103068
0.924256
handler = IntrospectionHandler(replaceKnownInterfaces) xmlStr = xmlStr.strip() if xmlStr.startswith('<!DOCTYPE'): xmlStr = xmlStr[xmlStr.find('>') + 1:] # xml.sax.parseString( xmlStr, handler ) p = xml.sax.make_parser() p.setFeature(xml.sax.handler.feature_validation, False) p...
def getInterfacesFromXML(xmlStr, replaceKnownInterfaces=False)
Parses the supplied Introspection XML string and returns a list of L{interface.DBusInerface} instances representing the XML interface definitions. @type replaceKnownInterfaces: C{bool} @param replaceKnownInterfaces: If true, pre-existing interface definitions will be ...
2.427253
2.928272
0.828903
proto.uniqueName = ':1.%d' % (self.next_id,) self.next_id += 1 self.clients[proto.uniqueName] = proto
def clientConnected(self, proto)
Called when a client connects to the bus. This method assigns the new connection a unique bus name.
5.790372
5.07621
1.140688
for rule_id in proto.matchRules: self.router.delMatch(rule_id) for busName in proto.busNames.keys(): self.dbus_ReleaseName(busName, proto.uniqueName) if proto.uniqueName: del self.clients[proto.uniqueName]
def clientDisconnected(self, proto)
Called when a client disconnects from the bus
7.715181
7.307436
1.055799
if msg._messageType in (1, 2): assert msg.destination, 'Failed to specify a message destination' if msg.destination is not None: if msg.destination[0] == ':': p = self.clients.get(msg.destination, None) else: p = self.busNames...
def sendMessage(self, msg)
Sends the supplied message to the correct destination. The @type msg: L{message.DBusMessage} @param msg: The 'destination' field of the message must be set for method calls and returns
4.874202
4.657041
1.046631
if not isinstance(body, (list, tuple)): body = [body] s = message.SignalMessage(path, member, interface, p.uniqueName, signature, body) p.sendMessage(s)
def sendSignal(self, p, member, signature=None, body=None, path='/org/freedesktop/DBus', interface='org.freedesktop.DBus')
Sends a signal to a specific connection @type p: L{BusProtocol} @param p: L{BusProtocol} instance to send a signal to @type member: C{string} @param member: Name of the signal to send @type path: C{string} @param path: Path of the object emitting the signal. Defaults t...
5.13587
6.394049
0.803227
if not isinstance(body, (list, tuple)): body = [body] s = message.SignalMessage(path, member, interface, None, signature, body) self.router.routeMessage(s)
def broadcastSignal(self, member, signature=None, body=None, path='/org/freedesktop/DBus', interface='org.freedesktop.DBus')
Sends a signal to all connections with registered interest @type member: C{string} @param member: Name of the signal to send @type path: C{string} @param path: Path of the object emitting the signal. Defaults to 'org/freedesktop/DBus' @type interface: C{st...
5.038203
7.030919
0.716578
lendian = rawMessage[0] == b'l'[0] nheader, hval = marshal.unmarshal( _headerFormat, rawMessage, 0, lendian, oobFDs, ) messageType = hval[1] if messageType not in _mtype: raise error.MarshallingError( 'Unknown Message Type: ' + str...
def parseMessage(rawMessage, oobFDs)
Parses the raw binary message and returns a L{DBusMessage} subclass. Unmarshalling DBUS 'h' (UNIX_FD) gets the FDs from the oobFDs list. @type rawMessage: C{str} @param rawMessage: Raw binary message to parse @rtype: L{DBusMessage} subclass @returns: The L{DBusMessage} subclass corresponding to th...
3.853988
3.821121
1.008601
flags = 0 if not self.expectReply: flags |= 0x1 if not self.autoStart: flags |= 0x2 # may be overriden below, depending on oobFDs _headerAttrs = self._headerAttrs # marshal body before headers to know if the 'unix_fd' header is needed ...
def _marshal(self, newSerial=True, oobFDs=None)
Encodes the message into binary format. The resulting binary message is stored in C{self.rawMessage}
4.05986
4.096998
0.990935
if not isinstance(plaintext, int): raise ValueError('Plaintext must be an integer value') if not self.in_range.contains(plaintext): raise OutOfRangeError('Plaintext is not within the input range') return self.encrypt_recursive(plaintext, self.in_range, self.out_r...
def encrypt(self, plaintext)
Encrypt the given plaintext value
4.177011
4.065641
1.027393
if not isinstance(ciphertext, int): raise ValueError('Ciphertext must be an integer value') if not self.out_range.contains(ciphertext): raise OutOfRangeError('Ciphertext is not within the output range') return self.decrypt_recursive(ciphertext, self.in_range, sel...
def decrypt(self, ciphertext)
Decrypt the given ciphertext value
3.919999
3.835514
1.022027
# FIXME data = str(data).encode() # Derive a key from data hmac_obj = hmac.HMAC(self.key, digestmod=hashlib.sha256) hmac_obj.update(data) assert hmac_obj.digest_size == 32 digest = hmac_obj.digest() # Use AES in the CTR mode to generate a pseud...
def tape_gen(self, data)
Return a bit string, generated from the given data string
3.43373
3.241916
1.059167
random_seq = os.urandom(block_size) random_key = base64.b64encode(random_seq) return random_key
def generate_key(block_size=32)
Generate random key for ope cipher. Parameters ---------- block_size : int, optional Length of random bytes. Returns ------- random_key : str A random key for encryption. Notes: ------ Implementation follows https://githu...
2.859392
2.883
0.991811
assert 0 <= byte <= 0xff bits = [int(x) for x in list(bin(byte + 0x100)[3:])] return bits
def byte_to_bitstring(byte)
Convert one byte to a list of bits
4.173567
3.960295
1.053853
assert isinstance(data, bytes), "Data must be an instance of bytes" byte_list = data_to_byte_list(data) bit_list = [bit for data_byte in byte_list for bit in byte_to_bitstring(data_byte)] return bit_list
def str_to_bitstring(data)
Convert a string to a list of bits
2.827143
2.80016
1.009636
in_size = in_range.size() out_size = out_range.size() assert in_size > 0 and out_size > 0 assert in_size <= out_size assert out_range.contains(nsample) # 1-based index of nsample in out_range nsample_index = nsample - out_range.start + 1 if in_size == out_size: # Input and ...
def sample_hgd(in_range, out_range, nsample, seed_coins)
Get a sample from the hypergeometric distribution, using the provided bit list as a source of randomness
2.930509
2.792283
1.049503
if isinstance(seed_coins, list): seed_coins.append(None) seed_coins = iter(seed_coins) cur_range = in_range.copy() assert cur_range.size() != 0 while cur_range.size() > 1: mid = (cur_range.start + cur_range.end) // 2 bit = next(seed_coins) if bit == 0: ...
def sample_uniform(in_range, seed_coins)
Uniformly select a number from the range using the bit list as a source of randomness
2.629185
2.551751
1.030345
# The Twisted API is weird: # 1) web.client.downloadPage() doesn't give us the HTTP headers # 2) there is no method that simply accepts a URL and gives you back # a HTTPDownloader object #TODO: convert getPage() usage to something similar, too downloader = factory(*args, **kwargs) ...
def __downloadPage(factory, *args, **kwargs)
Start a HTTP download, returning a HTTPDownloader object
5.010079
4.694602
1.0672
boundary = mimetools.choose_boundary() crlf = '\r\n' l = [] for k, v in fields: l.append('--' + boundary) l.append('Content-Disposition: form-data; name="%s"' % k) l.append('') l.append(v) for (k, f, v) in files: ...
def __encodeMultipart(self, fields, files)
fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance
1.474669
1.409221
1.046443
def handle_headers(r): self.gotHeaders(c.response_headers) return r return c.deferred.addBoth(handle_headers)
def __clientDefer(self, c)
Return a deferred for a HTTP client, after handling incoming headers
9.316733
7.164239
1.30045