id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
145,248
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_swagger.py
txkube._swagger._ArrayTypeModel
class _ArrayTypeModel(PClass): """ An ``_ArrayTypeModel`` represents a type which is a homogeneous array. Specifically, this is used for the Swagger type *array*. :ivar tuple(type) python_types: The Python types which correspond to this the modeled Swagger type. :ivar ITypeModel element_type: The type model that applies to elements of the array. """ element_type = itypemodel_field() @property def python_types(self): # Cheat a bit and make pyrsistent synthesize a type for us... # Amusingly, it's a regular set internally so also freeze it so it's # okay to put it back in to field again. return freeze(self.pclass_field_for_type(True, NO_DEFAULT).type) def pclass_field_for_type(self, required, default): # XXX default unimplemented # XXX ignores the range's pyrsistent_invariant return pvector_field(self.element_type.python_types, optional=not required)
class _ArrayTypeModel(PClass): ''' An ``_ArrayTypeModel`` represents a type which is a homogeneous array. Specifically, this is used for the Swagger type *array*. :ivar tuple(type) python_types: The Python types which correspond to this the modeled Swagger type. :ivar ITypeModel element_type: The type model that applies to elements of the array. ''' @property def python_types(self): pass def pclass_field_for_type(self, required, default): pass
4
1
5
0
2
3
1
1.86
1
0
0
0
2
0
2
2
26
6
7
5
3
13
6
4
3
1
1
0
2
145,249
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_network.py
txkube._network._BytesProducer
class _BytesProducer(object): _data = attr.ib(validator=validators.instance_of(bytes), repr=False) @property def length(self): return len(self._data) def startProducing(self, consumer): consumer.write(self._data) return succeed(None) def stopProducing(self): pass def pauseProducing(self): pass def resumeProducing(self): pass
class _BytesProducer(object): @property def length(self): pass def startProducing(self, consumer): pass def stopProducing(self): pass def pauseProducing(self): pass def resumeProducing(self): pass
7
0
2
0
2
0
1
0
1
0
0
0
5
0
5
5
19
5
14
8
7
0
13
7
7
1
1
0
5
145,250
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_interface.py
txkube._interface.IKubernetesClient
class IKubernetesClient(Interface): """ An ``IKubernetesClient`` provider allows access to the API of a particular Kubernetes deployment. """ model = Attribute( "The Kubernetes data model for use with this client. This must " "agree with the data model used by the server with which this " "client will interact." ) def version(): """ Retrieve server version information. :return Deferred(version.Info): The version information reported by the server about itself. """ def list(kind): """ Retrieve objects of the given kind. :param type kind: A model type representing the object kind to retrieve. For example ``ConfigMap`` or ``Namespace``. :return Deferred(ObjectList): A collection of the matching objects. """ def create(obj): """ Create a new object in the given namespace. :param IObject obj: A description of the object to create. :return Deferred(IObject): A description of the created object. """ def replace(obj): """ Replace an existing object with a new one. :param IObject obj: The replacement object. An old object with the same name in the same namespace (if applicable) will be replaced with this one. :return Deferred(IObject): A description of the created object. """ def get(obj): """ Get a single object. :param IObject obj: A description of which object to get. The *kind*, *namespace*, and *name* address the specific object to retrieve. :return Deferred(IObject): A description of the retrieved object. """ def delete(obj): """ Delete a single object. :param IObject obj: A description of which object to delete. The *kind*, *namespace*, and *name* address the specific object to delete. :return Deferred(None): The Deferred fires when the object has been deleted. """
class IKubernetesClient(Interface): ''' An ``IKubernetesClient`` provider allows access to the API of a particular Kubernetes deployment. ''' def version(): ''' Retrieve server version information. :return Deferred(version.Info): The version information reported by the server about itself. ''' pass def list(kind): ''' Retrieve objects of the given kind. :param type kind: A model type representing the object kind to retrieve. For example ``ConfigMap`` or ``Namespace``. :return Deferred(ObjectList): A collection of the matching objects. ''' pass def create(obj): ''' Create a new object in the given namespace. :param IObject obj: A description of the object to create. :return Deferred(IObject): A description of the created object. ''' pass def replace(obj): ''' Replace an existing object with a new one. :param IObject obj: The replacement object. An old object with the same name in the same namespace (if applicable) will be replaced with this one. :return Deferred(IObject): A description of the created object. ''' pass def get(obj): ''' Get a single object. :param IObject obj: A description of which object to get. The *kind*, *namespace*, and *name* address the specific object to retrieve. :return Deferred(IObject): A description of the retrieved object. ''' pass def delete(obj): ''' Delete a single object. :param IObject obj: A description of which object to delete. The *kind*, *namespace*, and *name* address the specific object to delete. :return Deferred(None): The Deferred fires when the object has been deleted. ''' pass
7
7
9
2
1
6
1
3.33
1
0
0
0
6
0
6
6
74
22
12
8
5
40
8
8
1
1
1
0
6
145,251
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_interface.py
txkube._interface.IKubernetes
class IKubernetes(Interface): """ An ``IKubernetes`` provider represents a particular Kubernetes deployment. """ base_url = Attribute( "The root of the Kubernetes HTTP API for this deployment " "(``twisted.python.url.URL``)." ) credentials = Attribute( "The credentials which will grant access to use the " "deployment's API." ) def versioned_client(): """ Create a client which will interact with the Kubernetes deployment represented by this object. Customize that client for the version of Kubernetes it will interact with. :return Deferred(IKubernetesClient): The client. """ # Pending deprecation. def client(): """ Create a client which will interact with the Kubernetes deployment represented by this object. :return IKubernetesClient: The client. """
class IKubernetes(Interface): ''' An ``IKubernetes`` provider represents a particular Kubernetes deployment. ''' def versioned_client(): ''' Create a client which will interact with the Kubernetes deployment represented by this object. Customize that client for the version of Kubernetes it will interact with. :return Deferred(IKubernetesClient): The client. ''' pass def client(): ''' Create a client which will interact with the Kubernetes deployment represented by this object. :return IKubernetesClient: The client. ''' pass
3
3
9
2
1
6
1
1.45
1
0
0
0
2
0
2
2
32
5
11
5
8
16
5
5
2
1
1
0
2
145,252
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_swagger.py
txkube._swagger.UsePrefix
class UsePrefix(PClass): """ ``UsePrefix`` provides a translation which prepends a prefix. This is useful, for example, for a versioning convention where many definition names have a prefix like *v1*. :ivar unicode prefix: The prefix to prepend. """ prefix = field(mandatory=True, type=unicode) def translate(self, name): return self.prefix + name
class UsePrefix(PClass): ''' ``UsePrefix`` provides a translation which prepends a prefix. This is useful, for example, for a versioning convention where many definition names have a prefix like *v1*. :ivar unicode prefix: The prefix to prepend. ''' def translate(self, name): pass
2
1
2
0
2
0
1
1.5
1
0
0
0
1
0
1
1
12
2
4
3
2
6
4
3
2
1
1
0
1
145,253
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_exception.py
txkube._exception.KubernetesError
class KubernetesError(Exception): """ Kubernetes has returned an error for some attempted operation. :ivar int code: The HTTP response code. :ivar Status status: The *v1.Status* returned in the response. """ def __init__(self, code, status): self.code = code self.status = status def __lt__(self, other): if isinstance(other, KubernetesError): return (self.code, self.status) < (other.code, other.status) return NotImplemented def __eq__(self, other): if isinstance(other, KubernetesError): return (self.code, self.status) == (other.code, other.status) return NotImplemented def __ne__(self, other): if isinstance(other, KubernetesError): return (self.code, self.status) != (other.code, other.status) return NotImplemented @classmethod def not_found(cls, details): # Circular imports :( See below. from ._model import v1 kind = _full_kind(details) return cls( NOT_FOUND, v1.Status( status=u"Failure", message=u'{kind} "{name}" not found'.format( kind=kind, name=details[u"name"], ), reason=u"NotFound", details=details, metadata={}, code=NOT_FOUND, ), ) @classmethod def already_exists(cls, details): # Circular imports :( See below. from ._model import v1 kind = _full_kind(details) return cls( CONFLICT, v1.Status( status=u"Failure", message=u'{kind} "{name}" already exists'.format( kind=kind, name=details[u"name"], ), reason=u"AlreadyExists", details=details, metadata={}, code=CONFLICT, ), ) @classmethod def object_modified(cls, details): from ._model import v1 kind = _full_kind(details) fmt = ( u'Operation cannot be fulfilled on {kind} "{name}": ' u'the object has been modified; ' u'please apply your changes to the latest version and try again' ) return cls( CONFLICT, v1.Status( code=CONFLICT, details=details, message=fmt.format(kind=kind, name=details[u"name"]), metadata={}, reason=u'Conflict', status=u'Failure', ), ) @classmethod def from_response(cls, response): """ Create a ``KubernetesError`` for the given error response from a Kubernetes server. :param twisted.web.iweb.IResponse response: The response to inspect for the error details. :return Deferred(KubernetesError): The error with details attached. """ # txkube -> _exception -> _model -> txkube :( # # Stick the import here to break the cycle. # # This is usually what happens with the expose-it-through-__init__ # style, I guess. # # Can probably deprecate this method, anyhow, and make people use # from_model_and_response instead. from ._model import v1_5_model return cls.from_model_and_response(v1_5_model, response) @classmethod def from_model_and_response(cls, model, response): """ Create a ``KubernetesError`` for the given error response from a Kubernetes server. :param model: The Kubernetes data model to use to convert the server response into a Python object. :param twisted.web.iweb.IResponse response: The response to inspect for the error details. :return Deferred(KubernetesError): The error with details attached. """ d = readBody(response) d.addCallback( lambda body: cls( response.code, model.iobject_from_raw(loads(body)), ), ) return d def __repr__(self): return "<KubernetesError: code = {}; status = {}>".format( self.code, self.status, ) __str__ = __repr__
class KubernetesError(Exception): ''' Kubernetes has returned an error for some attempted operation. :ivar int code: The HTTP response code. :ivar Status status: The *v1.Status* returned in the response. ''' def __init__(self, code, status): pass def __lt__(self, other): pass def __eq__(self, other): pass def __ne__(self, other): pass @classmethod def not_found(cls, details): pass @classmethod def already_exists(cls, details): pass @classmethod def object_modified(cls, details): pass @classmethod def from_response(cls, response): ''' Create a ``KubernetesError`` for the given error response from a Kubernetes server. :param twisted.web.iweb.IResponse response: The response to inspect for the error details. :return Deferred(KubernetesError): The error with details attached. ''' pass @classmethod def from_model_and_response(cls, model, response): ''' Create a ``KubernetesError`` for the given error response from a Kubernetes server. :param model: The Kubernetes data model to use to convert the server response into a Python object. :param twisted.web.iweb.IResponse response: The response to inspect for the error details. :return Deferred(KubernetesError): The error with details attached. ''' pass def __repr__(self): pass
16
3
11
1
8
3
1
0.36
1
0
0
0
5
2
10
20
141
20
89
28
69
32
39
23
24
2
3
1
13
145,254
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_authentication.py
txkube._authentication.NetLocation
class NetLocation(PClass): """ ``NetLocation`` holds information which identifies a particular HTTPS server. This is useful as a key for selecting the right certificate authority and client certificate to use. :ivar unicode host: The server's hostname. :ivar port: The server's port number. """ host = field(mandatory=True, type=unicode) port = field(mandatory=True, type=(int, long))
class NetLocation(PClass): ''' ``NetLocation`` holds information which identifies a particular HTTPS server. This is useful as a key for selecting the right certificate authority and client certificate to use. :ivar unicode host: The server's hostname. :ivar port: The server's port number. ''' pass
1
1
0
0
0
0
0
2.33
1
0
0
0
0
0
0
0
11
1
3
3
2
7
3
3
2
0
1
0
0
145,255
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_authentication.py
txkube._authentication.TLSCredentials
class TLSCredentials(PClass): """ ``TLSCredentials`` holds the information necessary to use a client certificate for a TLS handshake. :ivar Chain chain: The client certificate chain to use. :ivar pem.Key key: The private key which corresponds to ``certificate``. """ chain = field(mandatory=True, invariant=instance_of(Chain)) key = field(mandatory=True, invariant=instance_of(pem.Key)) def __invariant__(self): certs = list( ssl.Certificate.loadPEM(cert.as_bytes()) for cert in self.chain.certificates ) key = ssl.KeyPair.load(self.key.as_bytes(), FILETYPE_PEM) # Invoke CertificateOptions' key/certificate match checking logic. ssl.CertificateOptions( privateKey=key.original, certificate=certs[0].original, extraCertChain=list(cert.original for cert in certs[1:]), ).getContext() return (True, "")
class TLSCredentials(PClass): ''' ``TLSCredentials`` holds the information necessary to use a client certificate for a TLS handshake. :ivar Chain chain: The client certificate chain to use. :ivar pem.Key key: The private key which corresponds to ``certificate``. ''' def __invariant__(self): pass
2
1
15
1
13
1
1
0.44
1
1
0
0
1
0
1
1
26
3
16
6
14
7
8
6
6
1
1
0
1
145,256
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_model.py
txkube._model._List
class _List(object): def __invariant__(self): return required_unique(self.items, object_sort_key) @staticmethod def __new__(cls, **kwargs): # The Kubernetes Swagger schema for Lists claims items is a *required* # *array*. However, it is frequently None/null instead. Hack around # such values, turning them into the empty sequence. # # It might be better to fix this with a schema overlay instead - eg, # with a tweak to mark them as optional instead of required. items = kwargs.get(u"items", None) if items is None: kwargs[u"items"] = () return super(_List, cls).__new__(cls, **kwargs) def item_by_name(self, name): """ Find an item in this collection by its name metadata. :param unicode name: The name of the object for which to search. :raise KeyError: If no object matching the given name is found. :return IObject: The object with the matching name. """ for obj in self.items: if obj.metadata.name == name: return obj raise KeyError(name) def add(self, obj): return self.transform([u"items"], add(obj)) def remove(self, obj): return self.transform([u"items"], remove(obj)) def replace(self, old, new): return self.transform( [u"items"], remove(old), [u"items"], add(new), )
class _List(object): def __invariant__(self): pass @staticmethod def __new__(cls, **kwargs): pass def item_by_name(self, name): ''' Find an item in this collection by its name metadata. :param unicode name: The name of the object for which to search. :raise KeyError: If no object matching the given name is found. :return IObject: The object with the matching name. ''' pass def add(self, obj): pass def remove(self, obj): pass def replace(self, old, new): pass
8
1
6
0
4
2
2
0.52
1
2
0
6
5
0
6
6
47
12
23
10
15
12
19
9
12
3
1
2
9
145,257
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_exception.py
txkube._exception.UnrecognizedKind
class UnrecognizedKind(ValueError): """ An object *kind* was encountered that we don't know about. :ivar unicode apiVersion: The API version encountered. :ivar unicode kind: The object kind encountered. :ivar object obj: The whole marshalled object. """ def __init__(self, apiVersion, kind, obj): ValueError.__init__(self, apiVersion, kind) self.apiVersion = apiVersion self.kind = kind self.obj = obj
class UnrecognizedKind(ValueError): ''' An object *kind* was encountered that we don't know about. :ivar unicode apiVersion: The API version encountered. :ivar unicode kind: The object kind encountered. :ivar object obj: The whole marshalled object. ''' def __init__(self, apiVersion, kind, obj): pass
2
1
5
0
5
0
1
1
1
0
0
0
1
3
1
12
13
1
6
5
4
6
6
5
4
1
4
0
1
145,258
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_model.py
txkube._model._KubernetesDataModel
class _KubernetesDataModel(object): """ A representation of txkube's understanding of the data model of some particular version of Kubernetes. """ spec = attr.ib() version_type = attr.ib() version = attr.ib() v1 = attr.ib() v1beta1 = attr.ib() @classmethod def from_path(cls, path, version_type_name, version_details, v1, v1beta1): return cls.from_swagger( Swagger.from_path(path), version_type_name, version_details, v1, v1beta1, ) @classmethod def from_swagger(cls, swagger, version_type_name, version_details, v1, v1beta1): spec = VersionedPClasses.transform_definitions(swagger) v1 = VersionedPClasses(spec, v1) v1beta1 = VersionedPClasses(spec, v1beta1) version_type = spec.pclass_for_definition(version_type_name) version = version_type(**version_details) model = cls( spec=spec, version_type=version_type, version=version, v1=v1, v1beta1=v1beta1, ) define_behaviors(model) return model @mutant def iobject_from_raw(self, obj): """ Load an object of unspecified type from the raw representation of it. :raise KeyError: If the kind of object is unsupported. :return IObject: The loaded object. """ versions = { version: v for v in (self.v1, self.v1beta1) for version in v.versions } versions.update({ "v1": self.v1, "v1beta1": self.v1beta1, }) kind = obj[u"kind"] apiVersion = _unmutilate(obj[u"apiVersion"]) try: v = versions[apiVersion] except KeyError: raise UnrecognizedVersion(apiVersion, obj) try: cls = getattr(v, kind) except AttributeError: raise UnrecognizedKind(apiVersion, kind, obj) others = obj.discard(u"kind").discard(u"apiVersion") return cls.create(others) def iobject_to_raw(self, obj): result = obj.serialize() result.update({ u"kind": obj.kind, u"apiVersion": _mutilate(obj.apiVersion), }) return result
class _KubernetesDataModel(object): ''' A representation of txkube's understanding of the data model of some particular version of Kubernetes. ''' @classmethod def from_path(cls, path, version_type_name, version_details, v1, v1beta1): pass @classmethod def from_swagger(cls, swagger, version_type_name, version_details, v1, v1beta1): pass @mutant def iobject_from_raw(self, obj): ''' Load an object of unspecified type from the raw representation of it. :raise KeyError: If the kind of object is unsupported. :return IObject: The loaded object. ''' pass def iobject_to_raw(self, obj): pass
8
2
15
1
13
1
2
0.15
1
6
4
0
2
0
4
4
80
10
61
23
53
9
36
20
31
3
1
1
6
145,259
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_swagger.py
txkube._swagger.VersionedPClasses
class VersionedPClasses(object): """ ``VersionedPClasses`` provides a somewhat easier to use interface to PClasses representing definitions from a Swagger definition. For example:: .. code-block: python swagger = Swagger.from_path(...) spec = VersionedPClasses.transform_definitions(swagger) v1beta1 = VersionedPClasses(spec, u"v1beta1") deployment = v1beta1.Deployment(...) Additional base classes can be inserted in the resulting class using the ``add_behavior_for_pclass`` decorator. For example:: .. code-block: python spec = ... v1beta1 = ... @v1beta1.add_behavior_for_pclass class Deployment(object): def foo(self, bar): ... deployment = v1beta1.Deployment(...) deployment.foo(bar) """ def __init__(self, spec, versions): self.spec = spec self.versions = versions @classmethod def transformable(cls, name, definition): props = definition.get(u"properties", ()) return u"kind" in props and u"apiVersion" in props @classmethod def transform_definitions(cls, spec, kind=u"kind", version=u"apiVersion"): def x_txkube_constant(value): return { u"type": u"x-txkube-constant", # TODO: Support other types? Maybe. u"format": u"string", u"default": value, } def transform_definition(name, definition): if cls.transformable(name, definition): parts = name.rsplit(u".", 2) version_value = parts[-2] kind_value = parts[-1] return definition.transform( [u"properties", kind], x_txkube_constant(kind_value), [u"properties", version], x_txkube_constant(version_value), ) return definition return spec.set( "transform_definition", transform_definition, ) def __getattr__(self, name): for version in sorted(self.versions): try: return self.spec.pclass_for_definition(self.full_name(version, name)) except NoSuchDefinition: pass raise AttributeError(name) def add_behavior_for_pclass(self, cls): """ Define an additional base class for the Python class created for a particular definition. :param type cls: The additional base class. Its name must exactly match the name of a definition with a version matching this object's version. :return: ``None`` """ kind = cls.__name__ for version in sorted(self.versions): try: self.spec.add_behavior_for_pclass(self.full_name(version, kind), cls) except NoSuchDefinition: pass else: return None raise NoSuchDefinition(kind) def full_name(self, version, name): """ Construct the full name of a definition based on this object's version and a partial definition name. :example: .. code-block: python assert v1.full_name(u"foo") == u"v1.foo" :param unicode name: The unversioned portion of the definition name. :return unicode: The full definition name. """ return u".".join((version, name))
class VersionedPClasses(object): ''' ``VersionedPClasses`` provides a somewhat easier to use interface to PClasses representing definitions from a Swagger definition. For example:: .. code-block: python swagger = Swagger.from_path(...) spec = VersionedPClasses.transform_definitions(swagger) v1beta1 = VersionedPClasses(spec, u"v1beta1") deployment = v1beta1.Deployment(...) Additional base classes can be inserted in the resulting class using the ``add_behavior_for_pclass`` decorator. For example:: .. code-block: python spec = ... v1beta1 = ... @v1beta1.add_behavior_for_pclass class Deployment(object): def foo(self, bar): ... deployment = v1beta1.Deployment(...) deployment.foo(bar) ''' def __init__(self, spec, versions): pass @classmethod def transformable(cls, name, definition): pass @classmethod def transform_definitions(cls, spec, kind=u"kind", version=u"apiVersion"): pass def x_txkube_constant(value): pass def transform_definitions(cls, spec, kind=u"kind", version=u"apiVersion"): pass def __getattr__(self, name): pass def add_behavior_for_pclass(self, cls): ''' Define an additional base class for the Python class created for a particular definition. :param type cls: The additional base class. Its name must exactly match the name of a definition with a version matching this object's version. :return: ``None`` ''' pass def full_name(self, version, name): ''' Construct the full name of a definition based on this object's version and a partial definition name. :example: .. code-block: python assert v1.full_name(u"foo") == u"v1.foo" :param unicode name: The unversioned portion of the definition name. :return unicode: The full definition name. ''' pass
11
3
11
1
8
2
2
0.8
1
2
1
0
4
2
6
6
116
28
49
20
38
39
37
18
28
3
1
2
13
145,260
LeastAuthority/txkube
LeastAuthority_txkube/src/txkube/_exception.py
txkube._exception.UnrecognizedVersion
class UnrecognizedVersion(ValueError): """ An object *apiVersion* was encountered that we don't know about. :ivar unicode apiVersion: The API version encountered. :ivar object obj: The whole marshalled object. """ def __init__(self, apiVersion, obj): ValueError.__init__(self, apiVersion) self.apiVersion = apiVersion self.obj = obj
class UnrecognizedVersion(ValueError): ''' An object *apiVersion* was encountered that we don't know about. :ivar unicode apiVersion: The API version encountered. :ivar object obj: The whole marshalled object. ''' def __init__(self, apiVersion, obj): pass
2
1
4
0
4
0
1
1
1
0
0
0
1
2
1
12
11
1
5
4
3
5
5
4
3
1
4
0
1
145,261
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipPersoWizard.py
btchip.btchipPersoWizard.ConfigDialog
class ConfigDialog(QtGui.QDialog): def __init__(self, persoData, parent=None): QDialog.__init__(self, parent) self.persoData = persoData self.ui = ui.personalization03config.Ui_Dialog() self.ui.setupUi(self) self.ui.NextButton.clicked.connect(self.processNext) self.ui.CancelButton.clicked.connect(self.processCancel) def processNext(self): if (self.ui.qwertyButton.isChecked()): self.persoData['keyboard'] = btchip.QWERTY_KEYMAP elif (self.ui.qwertzButton.isChecked()): self.persoData['keyboard'] = btchip.QWERTZ_KEYMAP elif (self.ui.azertyButton.isChecked()): self.persoData['keyboard'] = btchip.AZERTY_KEYMAP try: while not waitDongle(self, self.persoData): pass except Exception as e: self.reject() self.persoData['main'].reject() mode = btchip.OPERATION_MODE_WALLET if not self.persoData['hardened']: mode = mode | btchip.OPERATION_MODE_SERVER try: self.persoData['client'].setup(mode, btchip.FEATURE_RFC6979, self.persoData['currencyCode'], self.persoData['currencyCodeP2SH'], self.persoData['pin'], None, self.persoData['keyboard'], self.persoData['seed']) except BTChipException as e: if e.sw == 0x6985: QMessageBox.warning( self, "Error", "Dongle is already set up. Please insert a different one", "OK") return except Exception as e: QMessageBox.warning(self, "Error", "Error performing setup", "OK") return if self.persoData['seed'] is None: dialog = SeedBackupStart(self.persoData, self) self.hide() dialog.exec_() else: dialog = FinalizeDialog(self.persoData, self) self.hide() dialog.exec_() def processCancel(self): self.reject() self.persoData['main'].reject()
class ConfigDialog(QtGui.QDialog): def __init__(self, persoData, parent=None): pass def processNext(self): pass def processCancel(self): pass
4
0
15
0
15
0
4
0
1
5
4
0
3
2
3
3
49
3
46
9
42
0
41
8
37
11
1
2
13
145,262
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipPersoWizard.py
btchip.btchipPersoWizard.SeedBackupVerify
class SeedBackupVerify(QtGui.QDialog): def __init__(self, persoData, parent=None): QDialog.__init__(self, parent) self.persoData = persoData self.ui = ui.personalizationseedbackup04.Ui_Dialog() self.ui.setupUi(self) self.ui.seedOkButton.clicked.connect(self.seedOK) self.ui.seedKoButton.clicked.connect(self.seedKO) def seedOK(self): dialog = FinalizeDialog(self.persoData, self) self.hide() dialog.exec_() def seedKO(self): finished = False while not finished: try: while not waitDongle(self, self.persoData): pass except Exception as e: pass try: self.persoData['client'].verifyPin("0") except BTChipException as e: if e.sw == 0x63c0: QMessageBox.information( self, "BTChip Setup", "Dongle is reset and can be repersonalized", "OK") finished = True pass if e.sw == 0x6faa: QMessageBox.information( self, "BTChip Setup", "Please unplug the dongle and plug it again", "OK") pass except Exception as e: pass self.reject() self.persoData['main'].reject()
class SeedBackupVerify(QtGui.QDialog): def __init__(self, persoData, parent=None): pass def seedOK(self): pass def seedKO(self): pass
4
0
11
0
11
0
3
0
1
3
2
0
3
2
3
3
37
3
34
9
30
0
34
8
30
8
1
3
10
145,263
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipPersoWizard.py
btchip.btchipPersoWizard.SeedDialog
class SeedDialog(QtGui.QDialog): def __init__(self, persoData, parent=None): QDialog.__init__(self, parent) self.persoData = persoData self.ui = ui.personalization01seed.Ui_Dialog() self.ui.setupUi(self) self.ui.seed.setEnabled(False) self.ui.RestoreWalletButton.toggled.connect(self.restoreWalletToggled) self.ui.NextButton.clicked.connect(self.processNext) self.ui.CancelButton.clicked.connect(self.processCancel) if MNEMONIC: self.mnemonic = Mnemonic('english') self.ui.mnemonicNotAvailableLabel.hide() def restoreWalletToggled(self, toggled): self.ui.seed.setEnabled(toggled) def processNext(self): self.persoData['seed'] = None if self.ui.RestoreWalletButton.isChecked(): # Check if it's an hexa string seedText = str(self.ui.seed.text()) if len(seedText) == 0: QMessageBox.warning(self, "Error", "Please enter a seed", "OK") return if seedText[-1] == 'X': seedText = seedText[0:-1] try: self.persoData['seed'] = seedText.decode('hex') except Exception: pass if self.persoData['seed'] == None: if not MNEMONIC: QMessageBox.warning( self, "Error", "Mnemonic API not available. Please install https://github.com/trezor/python-mnemonic", "OK") return if not self.mnemonic.check(seedText): QMessageBox.warning( self, "Error", "Invalid mnemonic", "OK") return self.persoData['seed'] = Mnemonic.to_seed(seedText) else: if (len(self.persoData['seed']) < 32) or (len(self.persoData['seed']) > 64): QMessageBox.warning( self, "Error", "Invalid seed length", "OK") return dialog = SecurityDialog(self.persoData, self) self.hide() dialog.exec_() def processCancel(self): self.reject() self.persoData['main'].reject()
class SeedDialog(QtGui.QDialog): def __init__(self, persoData, parent=None): pass def restoreWalletToggled(self, toggled): pass def processNext(self): pass def processCancel(self): pass
5
0
12
0
11
0
3
0.02
1
3
1
0
4
3
4
4
51
4
46
10
41
1
45
10
40
9
1
3
13
145,264
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/bitcoinTransaction.py
btchip.bitcoinTransaction.bitcoinInput
class bitcoinInput: def __init__(self, bufferOffset=None): self.prevOut = "" self.script = "" self.sequence = "" if bufferOffset is not None: buf = bufferOffset['buffer'] offset = bufferOffset['offset'] self.prevOut = buf[offset:offset + 36] offset += 36 scriptSize = readVarint(buf, offset) offset += scriptSize['size'] self.script = buf[offset:offset + scriptSize['value']] offset += scriptSize['value'] self.sequence = buf[offset:offset + 4] offset += 4 bufferOffset['offset'] = offset def serialize(self): result = [] result.extend(self.prevOut) writeVarint(len(self.script), result) result.extend(self.script) result.extend(self.sequence) return result def __str__(self): buf = "Prevout : " + hexlify(self.prevOut) + "\r\n" buf += "Script : " + hexlify(self.script) + "\r\n" buf += "Sequence : " + hexlify(self.sequence) + "\r\n" return buf
class bitcoinInput: def __init__(self, bufferOffset=None): pass def serialize(self): pass def __str__(self): pass
4
0
9
0
9
0
1
0
0
0
0
0
3
3
3
3
32
3
29
12
25
0
29
12
25
2
0
1
4
145,265
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/bitcoinTransaction.py
btchip.bitcoinTransaction.bitcoinOutput
class bitcoinOutput: def __init__(self, bufferOffset=None): self.amount = "" self.script = "" if bufferOffset is not None: buf = bufferOffset['buffer'] offset = bufferOffset['offset'] self.amount = buf[offset:offset + 8] offset += 8 scriptSize = readVarint(buf, offset) offset += scriptSize['size'] self.script = buf[offset:offset + scriptSize['value']] offset += scriptSize['value'] bufferOffset['offset'] = offset def serialize(self): result = [] result.extend(self.amount) writeVarint(len(self.script), result) result.extend(self.script) return result def __str__(self): buf = "Amount : " + hexlify(self.amount) + "\r\n" buf += "Script : " + hexlify(self.script) + "\r\n" return buf
class bitcoinOutput: def __init__(self, bufferOffset=None): pass def serialize(self): pass def __str__(self): pass
4
0
8
0
8
0
1
0
0
0
0
0
3
2
3
3
27
3
24
11
20
0
24
11
20
2
0
1
4
145,266
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipPersoWizard.py
btchip.btchipPersoWizard.FinalizeDialog
class FinalizeDialog(QtGui.QDialog): def __init__(self, persoData, parent=None): QDialog.__init__(self, parent) self.persoData = persoData self.ui = ui.personalization04finalize.Ui_Dialog() self.ui.setupUi(self) self.ui.FinishButton.clicked.connect(self.finish) try: while not waitDongle(self, self.persoData): pass except Exception as e: self.reject() self.persoData['main'].reject() attempts = self.persoData['client'].getVerifyPinRemainingAttempts() self.ui.remainingAttemptsLabel.setText( "Remaining attempts " + str(attempts)) def finish(self): if (len(self.ui.pin1.text()) < 4): QMessageBox.warning( self, "Error", "PIN must be at least 4 characteres long", "OK") return if (len(self.ui.pin1.text()) > 32): QMessageBox.warning(self, "Error", "PIN is too long", "OK") return try: self.persoData['client'].verifyPin(str(self.ui.pin1.text())) except BTChipException as e: if ((e.sw == 0x63c0) or (e.sw == 0x6985)): QMessageBox.warning( self, "Error", "Invalid PIN - dongle has been reset. Please personalize again", "OK") self.reject() self.persoData['main'].reject() if ((e.sw & 0xfff0) == 0x63c0): attempts = e.sw - 0x63c0 self.ui.remainingAttemptsLabel.setText( "Remaining attempts " + str(attempts)) QMessageBox.warning( self, "Error", "Invalid PIN - please unplug the dongle and plug it again before retrying", "OK") try: while not waitDongle(self, self.persoData): pass except Exception as e: self.reject() self.persoData['main'].reject() return except Exception as e: QMessageBox.warning( self, "Error", "Unexpected error verifying PIN - aborting", "OK") self.reject() self.persoData['main'].reject() return if not self.persoData['hardened']: try: self.persoData['client'].setOperationMode( btchip.OPERATION_MODE_SERVER) except Exception: QMessageBox.warning( self, "Error", "Error switching to non hardened mode", "OK") self.reject() self.persoData['main'].reject() return QMessageBox.information( self, "BTChip Setup", "Setup completed. Please unplug the dongle and plug it again before use", "OK") self.accept() self.persoData['main'].accept()
class FinalizeDialog(QtGui.QDialog): def __init__(self, persoData, parent=None): pass def finish(self): pass
3
0
28
0
28
0
7
0
1
4
2
0
2
2
2
2
58
2
56
9
53
0
56
7
53
11
1
3
14
145,267
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/bitcoinTransaction.py
btchip.bitcoinTransaction.bitcoinTransaction
class bitcoinTransaction: def __init__(self, data=None): self.version = "" self.inputs = [] self.outputs = [] self.lockTime = "" self.witness = False self.witnessScript = "" if data is not None: offset = 0 self.version = data[offset:offset + 4] offset += 4 if (data[offset] == 0) and (data[offset + 1] != 0): offset += 2 self.witness = True inputSize = readVarint(data, offset) offset += inputSize['size'] numInputs = inputSize['value'] for i in range(numInputs): tmp = {'buffer': data, 'offset': offset} self.inputs.append(bitcoinInput(tmp)) offset = tmp['offset'] outputSize = readVarint(data, offset) offset += outputSize['size'] numOutputs = outputSize['value'] for i in range(numOutputs): tmp = {'buffer': data, 'offset': offset} self.outputs.append(bitcoinOutput(tmp)) offset = tmp['offset'] if self.witness: self.witnessScript = data[offset: len(data) - 4] self.lockTime = data[len(data) - 4:] else: self.lockTime = data[offset:offset + 4] def serialize(self, skipOutputLocktime=False, skipWitness=False): if skipWitness or (not self.witness): useWitness = False else: useWitness = True result = [] result.extend(self.version) if useWitness: result.append(0x00) result.append(0x01) writeVarint(len(self.inputs), result) for trinput in self.inputs: result.extend(trinput.serialize()) if not skipOutputLocktime: writeVarint(len(self.outputs), result) for troutput in self.outputs: result.extend(troutput.serialize()) if useWitness: result.extend(self.witnessScript) result.extend(self.lockTime) return result def serializeOutputs(self): result = [] writeVarint(len(self.outputs), result) for troutput in self.outputs: result.extend(troutput.serialize()) return result def __str__(self): buf = "Version : " + hexlify(self.version) + "\r\n" index = 1 for trinput in self.inputs: buf += "Input #" + str(index) + "\r\n" buf += str(trinput) index += 1 index = 1 for troutput in self.outputs: buf += "Output #" + str(index) + "\r\n" buf += str(troutput) index += 1 buf += "Locktime : " + hexlify(self.lockTime) + "\r\n" if self.witness: buf += "Witness script : " + hexlify(self.witnessScript) + "\r\n" return buf
class bitcoinTransaction: def __init__(self, data=None): pass def serialize(self, skipOutputLocktime=False, skipWitness=False): pass def serializeOutputs(self): pass def __str__(self): pass
5
0
19
0
19
1
5
0.03
0
4
2
0
4
6
4
4
81
4
77
28
72
2
75
28
70
7
0
2
19
145,268
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipPersoWizard.py
btchip.btchipPersoWizard.StartBTChipPersoDialog
class StartBTChipPersoDialog(QtGui.QDialog): def __init__(self): QDialog.__init__(self, None) self.ui = ui.personalization00start.Ui_Dialog() self.ui.setupUi(self) self.ui.NextButton.clicked.connect(self.processNext) self.ui.CancelButton.clicked.connect(self.processCancel) def processNext(self): persoData = {} persoData['currencyCode'] = 0x00 persoData['currencyCodeP2SH'] = 0x05 persoData['client'] = None dialog = SeedDialog(persoData, self) persoData['main'] = self dialog.exec_() pass def processCancel(self): self.reject()
class StartBTChipPersoDialog(QtGui.QDialog): def __init__(self): pass def processNext(self): pass def processCancel(self): pass
4
0
6
0
6
0
1
0
1
1
1
0
3
1
3
3
21
3
18
7
14
0
18
7
14
1
1
0
3
145,269
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipPersoWizard.py
btchip.btchipPersoWizard.SeedBackupInstructions
class SeedBackupInstructions(QtGui.QDialog): def __init__(self, persoData, parent=None): QDialog.__init__(self, parent) self.persoData = persoData self.ui = ui.personalizationseedbackup03.Ui_Dialog() self.ui.setupUi(self) self.ui.NextButton.clicked.connect(self.processNext) def processNext(self): dialog = SeedBackupVerify(self.persoData, self) self.hide() dialog.exec_()
class SeedBackupInstructions(QtGui.QDialog): def __init__(self, persoData, parent=None): pass def processNext(self): pass
3
0
5
0
5
0
1
0
1
1
1
0
2
2
2
2
13
2
11
6
8
0
11
6
8
1
1
0
2
145,270
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipComm.py
btchip.btchipComm.DongleServer
class DongleServer(Dongle): def __init__(self, server, port, debug=False): self.server = server self.port = port self.debug = debug self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.connect((self.server, self.port)) except Exception: raise BTChipException("Proxy connection failed") def exchange(self, apdu, timeout=20000): if self.debug: print("=> %s" % hexlify(apdu)) self.socket.send(struct.pack(">I", len(apdu))) self.socket.send(apdu) size = struct.unpack(">I", self.socket.recv(4))[0] response = self.socket.recv(size) sw = struct.unpack(">H", self.socket.recv(2))[0] if self.debug: print("<= %s%.2x" % (hexlify(response), sw)) if sw != 0x9000: raise BTChipException("Invalid status %04x" % sw, sw) return bytearray(response) def close(self): try: self.socket.close() except Exception: pass
class DongleServer(Dongle): def __init__(self, server, port, debug=False): pass def exchange(self, apdu, timeout=20000): pass def close(self): pass
4
0
9
0
9
0
3
0
1
3
1
0
3
4
3
6
31
3
28
11
24
0
28
11
24
4
2
1
8
145,271
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipComm.py
btchip.btchipComm.DongleSmartcard
class DongleSmartcard(Dongle): def __init__(self, device, debug=False): self.device = device self.debug = debug self.waitImpl = self self.opened = True def exchange(self, apdu, timeout=20000): if self.debug: print("=> %s" % hexlify(apdu)) response, sw1, sw2 = self.device.transmit(toBytes(hexlify(apdu))) sw = (sw1 << 8) | sw2 if self.debug: print("<= %s%.2x" % (toHexString(response).replace(" ", ""), sw)) if sw != 0x9000: raise BTChipException("Invalid status %04x" % sw, sw) return bytearray(response) def close(self): if self.opened: try: self.device.disconnect() except Exception: pass self.opened = False
class DongleSmartcard(Dongle): def __init__(self, device, debug=False): pass def exchange(self, apdu, timeout=20000): pass def close(self): pass
4
0
7
0
7
0
3
0
1
3
1
0
3
4
3
6
26
3
23
10
19
0
23
10
19
4
2
2
8
145,272
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipPersoWizard.py
btchip.btchipPersoWizard.SecurityDialog
class SecurityDialog(QtGui.QDialog): def __init__(self, persoData, parent=None): QDialog.__init__(self, parent) self.persoData = persoData self.ui = ui.personalization02security.Ui_Dialog() self.ui.setupUi(self) self.ui.NextButton.clicked.connect(self.processNext) self.ui.CancelButton.clicked.connect(self.processCancel) def processNext(self): if (self.ui.pin1.text() != self.ui.pin2.text()): self.ui.pin1.setText("") self.ui.pin2.setText("") QMessageBox.warning(self, "Error", "PINs are not matching", "OK") return if (len(self.ui.pin1.text()) < 4): QMessageBox.warning( self, "Error", "PIN must be at least 4 characteres long", "OK") return if (len(self.ui.pin1.text()) > 32): QMessageBox.warning(self, "Error", "PIN is too long", "OK") return self.persoData['pin'] = str(self.ui.pin1.text()) self.persoData['hardened'] = self.ui.HardenedButton.isChecked() dialog = ConfigDialog(self.persoData, self) self.hide() dialog.exec_() def processCancel(self): self.reject() self.persoData['main'].reject()
class SecurityDialog(QtGui.QDialog): def __init__(self, persoData, parent=None): pass def processNext(self): pass def processCancel(self): pass
4
0
9
0
9
0
2
0
1
2
1
0
3
2
3
3
32
4
28
7
24
0
28
7
24
4
1
1
6
145,273
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipException.py
btchip.btchipException.BTChipException
class BTChipException(Exception): def __init__(self, message, sw=0x6f00): self.message = message self.sw = sw def __str__(self): buf = "Exception : " + self.message return buf
class BTChipException(Exception): def __init__(self, message, sw=0x6f00): pass def __str__(self): pass
3
0
3
0
3
0
1
0
1
0
0
0
2
2
2
12
9
2
7
6
4
0
7
6
4
1
3
0
2
145,274
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchip.py
btchip.btchip.btchip
class btchip: BTCHIP_CLA = 0xe0 BTCHIP_JC_EXT_CLA = 0xf0 BTCHIP_INS_SET_ALTERNATE_COIN_VERSION = 0x14 BTCHIP_INS_SETUP = 0x20 BTCHIP_INS_VERIFY_PIN = 0x22 BTCHIP_INS_GET_OPERATION_MODE = 0x24 BTCHIP_INS_SET_OPERATION_MODE = 0x26 BTCHIP_INS_SET_KEYMAP = 0x28 BTCHIP_INS_SET_COMM_PROTOCOL = 0x2a BTCHIP_INS_GET_WALLET_PUBLIC_KEY = 0x40 BTCHIP_INS_GET_TRUSTED_INPUT = 0x42 BTCHIP_INS_HASH_INPUT_START = 0x44 BTCHIP_INS_HASH_INPUT_FINALIZE = 0x46 BTCHIP_INS_HASH_SIGN = 0x48 BTCHIP_INS_HASH_INPUT_FINALIZE_FULL = 0x4a BTCHIP_INS_GET_INTERNAL_CHAIN_INDEX = 0x4c BTCHIP_INS_SIGN_MESSAGE = 0x4e BTCHIP_INS_GET_TRANSACTION_LIMIT = 0xa0 BTCHIP_INS_SET_TRANSACTION_LIMIT = 0xa2 BTCHIP_INS_IMPORT_PRIVATE_KEY = 0xb0 BTCHIP_INS_GET_PUBLIC_KEY = 0xb2 BTCHIP_INS_DERIVE_BIP32_KEY = 0xb4 BTCHIP_INS_SIGNVERIFY_IMMEDIATE = 0xb6 BTCHIP_INS_GET_RANDOM = 0xc0 BTCHIP_INS_GET_ATTESTATION = 0xc2 BTCHIP_INS_GET_FIRMWARE_VERSION = 0xc4 BTCHIP_INS_COMPOSE_MOFN_ADDRESS = 0xc6 BTCHIP_INS_GET_POS_SEED = 0xca BTCHIP_INS_EXT_GET_HALF_PUBLIC_KEY = 0x20 BTCHIP_INS_EXT_CACHE_PUT_PUBLIC_KEY = 0x22 BTCHIP_INS_EXT_CACHE_HAS_PUBLIC_KEY = 0x24 BTCHIP_INS_EXT_CACHE_GET_FEATURES = 0x26 OPERATION_MODE_WALLET = 0x01 OPERATION_MODE_RELAXED_WALLET = 0x02 OPERATION_MODE_SERVER = 0x04 OPERATION_MODE_DEVELOPER = 0x08 FEATURE_UNCOMPRESSED_KEYS = 0x01 FEATURE_RFC6979 = 0x02 FEATURE_FREE_SIGHASHTYPE = 0x04 FEATURE_NO_2FA_P2SH = 0x08 QWERTY_KEYMAP = bytearray(unhexlify( "000000000000000000000000760f00d4ffffffc7000000782c1e3420212224342627252e362d3738271e1f202122232425263333362e37381f0405060708090a0b0c0d0e0f101112131415161718191a1b1c1d2f3130232d350405060708090a0b0c0d0e0f101112131415161718191a1b1c1d2f313035")) QWERTZ_KEYMAP = bytearray(unhexlify( "000000000000000000000000760f00d4ffffffc7000000782c1e3420212224342627252e362d3738271e1f202122232425263333362e37381f0405060708090a0b0c0d0e0f101112131415161718191a1b1d1c2f3130232d350405060708090a0b0c0d0e0f101112131415161718191a1b1d1c2f313035")) AZERTY_KEYMAP = bytearray(unhexlify( "08000000010000200100007820c8ffc3feffff07000000002c38202030341e21222d352e102e3637271e1f202122232425263736362e37101f1405060708090a0b0c0d0e0f331112130415161718191d1b1c1a2f64302f2d351405060708090a0b0c0d0e0f331112130415161718191d1b1c1a2f643035")) def __init__(self, dongle): self.dongle = dongle self.needKeyCache = False try: firmware = self.getFirmwareVersion()['version'] self.multiOutputSupported = tuple( map(int, (firmware.split(".")))) >= (1, 1, 4) if self.multiOutputSupported: self.scriptBlockLength = 50 else: self.scriptBlockLength = 255 except Exception: pass try: result = self.getJCExtendedFeatures() self.needKeyCache = (result['proprietaryApi'] == False) except Exception: pass def setAlternateCoinVersion(self, versionRegular, versionP2SH): apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_SET_ALTERNATE_COIN_VERSION, 0x00, 0x00, 0x02, versionRegular, versionP2SH] self.dongle.exchange(bytearray(apdu)) def verifyPin(self, pin): if isinstance(pin, str): pin = pin.encode('utf-8') apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_VERIFY_PIN, 0x00, 0x00, len(pin)] apdu.extend(bytearray(pin)) self.dongle.exchange(bytearray(apdu)) def getVerifyPinRemainingAttempts(self): apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_VERIFY_PIN, 0x80, 0x00, 0x01] apdu.extend(bytearray(b'0')) try: self.dongle.exchange(bytearray(apdu)) except BTChipException as e: if ((e.sw & 0xfff0) == 0x63c0): return e.sw - 0x63c0 raise e def getWalletPublicKey(self, path, showOnScreen=False, segwit=False, segwitNative=False, cashAddr=False): result = {} donglePath = parse_bip32_path(path) if self.needKeyCache: self.resolvePublicKeysInPath(path) apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_WALLET_PUBLIC_KEY, 0x01 if showOnScreen else 0x00, 0x03 if cashAddr else 0x02 if segwitNative else 0x01 if segwit else 0x00, len(donglePath)] apdu.extend(donglePath) response = self.dongle.exchange(bytearray(apdu)) offset = 0 result['publicKey'] = response[offset + 1: offset + 1 + response[offset]] offset = offset + 1 + response[offset] result['address'] = str( response[offset + 1: offset + 1 + response[offset]]) offset = offset + 1 + response[offset] result['chainCode'] = response[offset: offset + 32] return result def getTrustedInput(self, transaction, index): result = {} # Header apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x00, 0x00] params = bytearray.fromhex("%.8x" % (index)) params.extend(transaction.version) writeVarint(len(transaction.inputs), params) apdu.append(len(params)) apdu.extend(params) self.dongle.exchange(bytearray(apdu)) # Each input for trinput in transaction.inputs: apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x80, 0x00] params = bytearray(trinput.prevOut) writeVarint(len(trinput.script), params) apdu.append(len(params)) apdu.extend(params) self.dongle.exchange(bytearray(apdu)) offset = 0 while True: blockLength = 251 if ((offset + blockLength) < len(trinput.script)): dataLength = blockLength else: dataLength = len(trinput.script) - offset params = bytearray(trinput.script[offset: offset + dataLength]) if ((offset + dataLength) == len(trinput.script)): params.extend(trinput.sequence) apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x80, 0x00, len(params)] apdu.extend(params) self.dongle.exchange(bytearray(apdu)) offset += dataLength if (offset >= len(trinput.script)): break # Number of outputs apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x80, 0x00] params = [] writeVarint(len(transaction.outputs), params) apdu.append(len(params)) apdu.extend(params) self.dongle.exchange(bytearray(apdu)) # Each output indexOutput = 0 for troutput in transaction.outputs: apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x80, 0x00] params = bytearray(troutput.amount) writeVarint(len(troutput.script), params) apdu.append(len(params)) apdu.extend(params) self.dongle.exchange(bytearray(apdu)) offset = 0 while (offset < len(troutput.script)): blockLength = 255 if ((offset + blockLength) < len(troutput.script)): dataLength = blockLength else: dataLength = len(troutput.script) - offset apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x80, 0x00, dataLength] apdu.extend(troutput.script[offset: offset + dataLength]) self.dongle.exchange(bytearray(apdu)) offset += dataLength # Locktime apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_TRUSTED_INPUT, 0x80, 0x00, len(transaction.lockTime)] apdu.extend(transaction.lockTime) response = self.dongle.exchange(bytearray(apdu)) result['trustedInput'] = True result['value'] = response return result def startUntrustedTransaction(self, newTransaction, inputIndex, outputList, redeemScript, version=0x01, cashAddr=False, continueSegwit=False): # Start building a fake transaction with the passed inputs segwit = False if newTransaction: for passedOutput in outputList: if ('witness' in passedOutput) and passedOutput['witness']: segwit = True break if newTransaction: if segwit: p2 = 0x03 if cashAddr else 0x02 else: p2 = 0x00 else: p2 = 0x10 if continueSegwit else 0x80 apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_START, 0x00, p2] params = bytearray([version, 0x00, 0x00, 0x00]) writeVarint(len(outputList), params) apdu.append(len(params)) apdu.extend(params) self.dongle.exchange(bytearray(apdu)) # Loop for each input currentIndex = 0 for passedOutput in outputList: if ('sequence' in passedOutput) and passedOutput['sequence']: sequence = bytearray(unhexlify(passedOutput['sequence'])) else: # default sequence sequence = bytearray([0xFF, 0xFF, 0xFF, 0xFF]) apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_START, 0x80, 0x00] params = [] script = bytearray(redeemScript) if ('trustedInput' in passedOutput) and passedOutput['trustedInput']: params.append(0x01) elif ('witness' in passedOutput) and passedOutput['witness']: params.append(0x02) else: params.append(0x00) if ('trustedInput' in passedOutput) and passedOutput['trustedInput']: params.append(len(passedOutput['value'])) params.extend(passedOutput['value']) if currentIndex != inputIndex: script = bytearray() writeVarint(len(script), params) apdu.append(len(params)) apdu.extend(params) self.dongle.exchange(bytearray(apdu)) offset = 0 while (offset < len(script)): blockLength = 255 if ((offset + blockLength) < len(script)): dataLength = blockLength else: dataLength = len(script) - offset params = script[offset: offset + dataLength] if ((offset + dataLength) == len(script)): params.extend(sequence) apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_START, 0x80, 0x00, len(params)] apdu.extend(params) self.dongle.exchange(bytearray(apdu)) offset += blockLength if len(script) == 0: apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_START, 0x80, 0x00, len(sequence)] apdu.extend(sequence) self.dongle.exchange(bytearray(apdu)) currentIndex += 1 def finalizeInput(self, outputAddress, amount, fees, changePath, rawTx=None): alternateEncoding = False donglePath = parse_bip32_path(changePath) if self.needKeyCache: self.resolvePublicKeysInPath(changePath) result = {} outputs = None if rawTx is not None: try: fullTx = bitcoinTransaction(bytearray(rawTx)) outputs = fullTx.serializeOutputs() if len(donglePath) != 0: apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_FINALIZE_FULL, 0xFF, 0x00] params = [] params.extend(donglePath) apdu.append(len(params)) apdu.extend(params) response = self.dongle.exchange(bytearray(apdu)) offset = 0 while (offset < len(outputs)): blockLength = self.scriptBlockLength if ((offset + blockLength) < len(outputs)): dataLength = blockLength p1 = 0x00 else: dataLength = len(outputs) - offset p1 = 0x80 apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_FINALIZE_FULL, p1, 0x00, dataLength] apdu.extend(outputs[offset: offset + dataLength]) response = self.dongle.exchange(bytearray(apdu)) offset += dataLength alternateEncoding = True except Exception: pass if not alternateEncoding: apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_FINALIZE, 0x02, 0x00] params = [] params.append(len(outputAddress)) params.extend(bytearray(outputAddress)) writeHexAmountBE(btc_to_satoshi(str(amount)), params) writeHexAmountBE(btc_to_satoshi(str(fees)), params) params.extend(donglePath) apdu.append(len(params)) apdu.extend(params) response = self.dongle.exchange(bytearray(apdu)) result['confirmationNeeded'] = response[1 + response[0]] != 0x00 result['confirmationType'] = response[1 + response[0]] if result['confirmationType'] == 0x02: result['keycardData'] = response[1 + response[0] + 1:] if result['confirmationType'] == 0x03: offset = 1 + response[0] + 1 keycardDataLength = response[offset] offset = offset + 1 result['keycardData'] = response[offset: offset + keycardDataLength] offset = offset + keycardDataLength result['secureScreenData'] = response[offset:] if result['confirmationType'] == 0x04: offset = 1 + response[0] + 1 keycardDataLength = response[offset] result['keycardData'] = response[offset + 1: offset + 1 + keycardDataLength] if outputs == None: result['outputData'] = response[1: 1 + response[0]] else: result['outputData'] = outputs return result def finalizeInputFull(self, outputData): result = {} offset = 0 encryptedOutputData = b"" while (offset < len(outputData)): blockLength = self.scriptBlockLength if ((offset + blockLength) < len(outputData)): dataLength = blockLength p1 = 0x00 else: dataLength = len(outputData) - offset p1 = 0x80 apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_HASH_INPUT_FINALIZE_FULL, p1, 0x00, dataLength] apdu.extend(outputData[offset: offset + dataLength]) response = self.dongle.exchange(bytearray(apdu)) encryptedOutputData = encryptedOutputData + \ response[1: 1 + response[0]] offset += dataLength if len(response) > 1: result['confirmationNeeded'] = response[1 + response[0]] != 0x00 result['confirmationType'] = response[1 + response[0]] else: # Support for old style API before 1.0.2 result['confirmationNeeded'] = response[0] != 0x00 result['confirmationType'] = response[0] if result['confirmationType'] == 0x02: result['keycardData'] = response[1 + response[0] + 1:] # legacy if result['confirmationType'] == 0x03: offset = 1 + response[0] + 1 keycardDataLength = response[offset] offset = offset + 1 result['keycardData'] = response[offset: offset + keycardDataLength] offset = offset + keycardDataLength result['secureScreenData'] = response[offset:] result['encryptedOutputData'] = encryptedOutputData if result['confirmationType'] == 0x04: offset = 1 + response[0] + 1 keycardDataLength = response[offset] result['keycardData'] = response[offset + 1: offset + 1 + keycardDataLength] return result def untrustedHashSign(self, path, pin="", lockTime=0, sighashType=0x01): if isinstance(pin, str): pin = pin.encode('utf-8') donglePath = parse_bip32_path(path) if self.needKeyCache: self.resolvePublicKeysInPath(path) apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_HASH_SIGN, 0x00, 0x00] params = [] params.extend(donglePath) params.append(len(pin)) params.extend(bytearray(pin)) writeUint32BE(lockTime, params) params.append(sighashType) apdu.append(len(params)) apdu.extend(params) result = self.dongle.exchange(bytearray(apdu)) result[0] = 0x30 return result def signMessagePrepareV1(self, path, message): donglePath = parse_bip32_path(path) if self.needKeyCache: self.resolvePublicKeysInPath(path) result = {} apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_SIGN_MESSAGE, 0x00, 0x00] params = [] params.extend(donglePath) params.append(len(message)) params.extend(bytearray(message)) apdu.append(len(params)) apdu.extend(params) response = self.dongle.exchange(bytearray(apdu)) result['confirmationNeeded'] = response[0] != 0x00 result['confirmationType'] = response[0] if result['confirmationType'] == 0x02: result['keycardData'] = response[1:] if result['confirmationType'] == 0x03: result['secureScreenData'] = response[1:] return result def signMessagePrepareV2(self, path, message): donglePath = parse_bip32_path(path) if self.needKeyCache: self.resolvePublicKeysInPath(path) result = {} offset = 0 encryptedOutputData = b"" while (offset < len(message)): params = [] if offset == 0: params.extend(donglePath) params.append((len(message) >> 8) & 0xff) params.append(len(message) & 0xff) p2 = 0x01 else: p2 = 0x80 blockLength = 255 - len(params) if ((offset + blockLength) < len(message)): dataLength = blockLength else: dataLength = len(message) - offset params.extend(bytearray(message[offset: offset + dataLength])) apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_SIGN_MESSAGE, 0x00, p2] apdu.append(len(params)) apdu.extend(params) response = self.dongle.exchange(bytearray(apdu)) encryptedOutputData = encryptedOutputData + \ response[1: 1 + response[0]] offset += blockLength result['confirmationNeeded'] = response[1 + response[0]] != 0x00 result['confirmationType'] = response[1 + response[0]] if result['confirmationType'] == 0x03: offset = 1 + response[0] + 1 result['secureScreenData'] = response[offset:] result['encryptedOutputData'] = encryptedOutputData return result def signMessagePrepare(self, path, message): try: result = self.signMessagePrepareV2(path, message) except BTChipException as e: if (e.sw == 0x6b00): # Old firmware version, try older method result = self.signMessagePrepareV1(path, message) else: raise return result def signMessageSign(self, pin=""): if isinstance(pin, str): pin = pin.encode('utf-8') apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_SIGN_MESSAGE, 0x80, 0x00] params = [] if pin is not None: params.append(len(pin)) params.extend(bytearray(pin)) else: params.append(0x00) apdu.append(len(params)) apdu.extend(params) response = self.dongle.exchange(bytearray(apdu)) return response def setup(self, operationModeFlags, featuresFlag, keyVersion, keyVersionP2SH, userPin, wipePin, keymapEncoding, seed=None, developerKey=None): if isinstance(userPin, str): userPin = userPin.encode('utf-8') result = {} apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_SETUP, 0x00, 0x00] params = [operationModeFlags, featuresFlag, keyVersion, keyVersionP2SH] params.append(len(userPin)) params.extend(bytearray(userPin)) if wipePin is not None: if isinstance(wipePin, str): wipePin = wipePin.encode('utf-8') params.append(len(wipePin)) params.extend(bytearray(wipePin)) else: params.append(0x00) if seed is not None: if len(seed) < 32 or len(seed) > 64: raise BTChipException("Invalid seed length") params.append(len(seed)) params.extend(seed) else: params.append(0x00) if developerKey is not None: params.append(len(developerKey)) params.extend(developerKey) else: params.append(0x00) apdu.append(len(params)) apdu.extend(params) response = self.dongle.exchange(bytearray(apdu)) result['trustedInputKey'] = response[0:16] result['developerKey'] = response[16:] self.setKeymapEncoding(keymapEncoding) try: self.setTypingBehaviour(0xff, 0xff, 0xff, 0x10) except BTChipException as e: if (e.sw == 0x6700): # Old firmware version, command not supported pass else: raise return result def setKeymapEncoding(self, keymapEncoding): apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_SET_KEYMAP, 0x00, 0x00] apdu.append(len(keymapEncoding)) apdu.extend(keymapEncoding) self.dongle.exchange(bytearray(apdu)) def setTypingBehaviour(self, unitDelayStart, delayStart, unitDelayKey, delayKey): apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_SET_KEYMAP, 0x01, 0x00] params = [] writeUint32BE(unitDelayStart, params) writeUint32BE(delayStart, params) writeUint32BE(unitDelayKey, params) writeUint32BE(delayKey, params) apdu.append(len(params)) apdu.extend(params) self.dongle.exchange(bytearray(apdu)) def getOperationMode(self): apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_OPERATION_MODE, 0x00, 0x00, 0x00] response = self.dongle.exchange(bytearray(apdu)) return response[0] def setOperationMode(self, operationMode): if operationMode != btchip.OPERATION_MODE_WALLET \ and operationMode != btchip.OPERATION_MODE_RELAXED_WALLET \ and operationMode != btchip.OPERATION_MODE_SERVER \ and operationMode != btchip.OPERATION_MODE_DEVELOPER: raise BTChipException("Invalid operation mode") apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_SET_OPERATION_MODE, 0x00, 0x00, 0x01, operationMode] self.dongle.exchange(bytearray(apdu)) def enableAlternate2fa(self, persistent): if persistent: p1 = 0x02 else: p1 = 0x01 apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_SET_OPERATION_MODE, p1, 0x00, 0x01, btchip.OPERATION_MODE_WALLET] self.dongle.exchange(bytearray(apdu)) def getFirmwareVersion(self): result = {} apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_FIRMWARE_VERSION, 0x00, 0x00, 0x00] try: response = self.dongle.exchange(bytearray(apdu)) except BTChipException as e: if (e.sw == 0x6985): response = [0x00, 0x00, 0x01, 0x04, 0x03] pass else: raise result['compressedKeys'] = (response[0] == 0x01) result['version'] = "%d.%d.%d" % ( response[2], response[3], response[4]) result['specialVersion'] = response[1] return result def getRandom(self, size): if size > 255: raise BTChipException("Invalid size") apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_RANDOM, 0x00, 0x00, size] return self.dongle.exchange(bytearray(apdu)) def getPOSSeedKey(self): result = {} apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_POS_SEED, 0x01, 0x00, 0x00] return self.dongle.exchange(bytearray(apdu)) def getPOSEncryptedSeed(self): result = {} apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_POS_SEED, 0x02, 0x00, 0x00] return self.dongle.exchange(bytearray(apdu)) def importPrivateKey(self, data, isSeed=False): apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_IMPORT_PRIVATE_KEY, (0x02 if isSeed else 0x01), 0x00] apdu.append(len(data)) apdu.extend(data) return self.dongle.exchange(bytearray(apdu)) def getPublicKey(self, encodedPrivateKey): result = {} apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_GET_PUBLIC_KEY, 0x00, 0x00] apdu.append(len(encodedPrivateKey) + 1) apdu.append(len(encodedPrivateKey)) apdu.extend(encodedPrivateKey) response = self.dongle.exchange(bytearray(apdu)) offset = 1 result['publicKey'] = response[offset + 1: offset + 1 + response[offset]] offset = offset + 1 + response[offset] if response[0] == 0x02: result['chainCode'] = response[offset: offset + 32] offset = offset + 32 result['depth'] = response[offset] offset = offset + 1 result['parentFingerprint'] = response[offset: offset + 4] offset = offset + 4 result['childNumber'] = response[offset: offset + 4] return result def deriveBip32Key(self, encodedPrivateKey, path): donglePath = parse_bip32_path(path) if self.needKeyCache: self.resolvePublicKeysInPath(path) offset = 1 currentEncodedPrivateKey = encodedPrivateKey while (offset < len(donglePath)): apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_DERIVE_BIP32_KEY, 0x00, 0x00] apdu.append(len(currentEncodedPrivateKey) + 1 + 4) apdu.append(len(currentEncodedPrivateKey)) apdu.extend(currentEncodedPrivateKey) apdu.extend(donglePath[offset: offset + 4]) currentEncodedPrivateKey = self.dongle.exchange(bytearray(apdu)) offset = offset + 4 return currentEncodedPrivateKey def signImmediate(self, encodedPrivateKey, data, deterministic=True): apdu = [self.BTCHIP_CLA, self.BTCHIP_INS_SIGNVERIFY_IMMEDIATE, 0x00, (0x80 if deterministic else 0x00)] apdu.append(len(encodedPrivateKey) + len(data) + 2) apdu.append(len(encodedPrivateKey)) apdu.extend(encodedPrivateKey) apdu.append(len(data)) apdu.extend(data) return self.dongle.exchange(bytearray(apdu)) # Functions dedicated to the Java Card interface when no proprietary API is available def parse_bip32_path_internal(self, path): if len(path) == 0: return [] result = [] elements = path.split('/') for pathElement in elements: element = pathElement.split('\'') if len(element) == 1: result.append(int(element[0])) else: result.append(0x80000000 | int(element[0])) return result def serialize_bip32_path_internal(self, path): result = [] for pathElement in path: writeUint32BE(pathElement, result) return bytearray([len(path)] + result) def resolvePublicKey(self, path): expandedPath = self.serialize_bip32_path_internal(path) apdu = [self.BTCHIP_JC_EXT_CLA, self.BTCHIP_INS_EXT_CACHE_HAS_PUBLIC_KEY, 0x00, 0x00] apdu.append(len(expandedPath)) apdu.extend(expandedPath) result = self.dongle.exchange(bytearray(apdu)) if (result[0] == 0): # Not present, need to be inserted into the cache apdu = [self.BTCHIP_JC_EXT_CLA, self.BTCHIP_INS_EXT_GET_HALF_PUBLIC_KEY, 0x00, 0x00] apdu.append(len(expandedPath)) apdu.extend(expandedPath) result = self.dongle.exchange(bytearray(apdu)) hashData = result[0:32] keyX = result[32:64] signature = result[64:] keyXY = recoverKey(signature, hashData, keyX) apdu = [self.BTCHIP_JC_EXT_CLA, self.BTCHIP_INS_EXT_CACHE_PUT_PUBLIC_KEY, 0x00, 0x00] apdu.append(len(expandedPath) + 65) apdu.extend(expandedPath) apdu.extend(keyXY) self.dongle.exchange(bytearray(apdu)) def resolvePublicKeysInPath(self, path): splitPath = self.parse_bip32_path_internal(path) # Locate the first public key in path offset = 0 startOffset = 0 while (offset < len(splitPath)): if (splitPath[offset] < 0x80000000): startOffset = offset break offset = offset + 1 if startOffset != 0: searchPath = splitPath[0:startOffset - 1] offset = startOffset - 1 while (offset < len(splitPath)): searchPath = searchPath + [splitPath[offset]] self.resolvePublicKey(searchPath) offset = offset + 1 self.resolvePublicKey(splitPath) def getJCExtendedFeatures(self): result = {} apdu = [self.BTCHIP_JC_EXT_CLA, self.BTCHIP_INS_EXT_CACHE_GET_FEATURES, 0x00, 0x00, 0x00] response = self.dongle.exchange(bytearray(apdu)) result['proprietaryApi'] = ((response[0] & 0x01) != 0) return result
class btchip: def __init__(self, dongle): pass def setAlternateCoinVersion(self, versionRegular, versionP2SH): pass def verifyPin(self, pin): pass def getVerifyPinRemainingAttempts(self): pass def getWalletPublicKey(self, path, showOnScreen=False, segwit=False, segwitNative=False, cashAddr=False): pass def getTrustedInput(self, transaction, index): pass def startUntrustedTransaction(self, newTransaction, inputIndex, outputList, redeemScript, version=0x01, cashAddr=False, continueSegwit=False): pass def finalizeInput(self, outputAddress, amount, fees, changePath, rawTx=None): pass def finalizeInputFull(self, outputData): pass def untrustedHashSign(self, path, pin="", lockTime=0, sighashType=0x01): pass def signMessagePrepareV1(self, path, message): pass def signMessagePrepareV2(self, path, message): pass def signMessagePrepareV1(self, path, message): pass def signMessageSign(self, pin=""): pass def setup(self, operationModeFlags, featuresFlag, keyVersion, keyVersionP2SH, userPin, wipePin, keymapEncoding, seed=None, developerKey=None): pass def setKeymapEncoding(self, keymapEncoding): pass def setTypingBehaviour(self, unitDelayStart, delayStart, unitDelayKey, delayKey): pass def getOperationMode(self): pass def setOperationMode(self, operationMode): pass def enableAlternate2fa(self, persistent): pass def getFirmwareVersion(self): pass def getRandom(self, size): pass def getPOSSeedKey(self): pass def getPOSEncryptedSeed(self): pass def importPrivateKey(self, data, isSeed=False): pass def getPublicKey(self, encodedPrivateKey): pass def deriveBip32Key(self, encodedPrivateKey, path): pass def signImmediate(self, encodedPrivateKey, data, deterministic=True): pass def parse_bip32_path_internal(self, path): pass def serialize_bip32_path_internal(self, path): pass def resolvePublicKey(self, path): pass def resolvePublicKeysInPath(self, path): pass def getJCExtendedFeatures(self): pass
34
0
18
0
18
0
4
0.02
0
8
2
0
33
4
33
33
682
40
631
211
597
15
602
207
568
18
0
4
127
145,275
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipPersoWizard.py
btchip.btchipPersoWizard.SeedBackupStart
class SeedBackupStart(QtGui.QDialog): def __init__(self, persoData, parent=None): QDialog.__init__(self, parent) self.persoData = persoData self.ui = ui.personalizationseedbackup01.Ui_Dialog() self.ui.setupUi(self) self.ui.NextButton.clicked.connect(self.processNext) def processNext(self): dialog = SeedBackupUnplug(self.persoData, self) self.hide() dialog.exec_()
class SeedBackupStart(QtGui.QDialog): def __init__(self, persoData, parent=None): pass def processNext(self): pass
3
0
5
0
5
0
1
0
1
1
1
0
2
2
2
2
13
2
11
6
8
0
11
6
8
1
1
0
2
145,276
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipComm.py
btchip.btchipComm.HIDDongleHIDAPI
class HIDDongleHIDAPI(Dongle, DongleWait): def __init__(self, device, ledger=False, debug=False): self.device = device self.ledger = ledger self.debug = debug self.waitImpl = self self.opened = True def exchange(self, apdu, timeout=20000): if self.debug: print("=> %s" % hexlify(apdu)) if self.ledger: apdu = wrapCommandAPDU(0x0101, apdu, 64) padSize = len(apdu) % 64 tmp = apdu if padSize != 0: tmp.extend([0] * (64 - padSize)) offset = 0 while (offset != len(tmp)): data = tmp[offset:offset + 64] data = bytearray([0]) + data self.device.write(data) offset += 64 dataLength = 0 dataStart = 2 result = self.waitImpl.waitFirstResponse(timeout) if not self.ledger: if result[0] == 0x61: # 61xx : data available self.device.set_nonblocking(False) dataLength = result[1] dataLength += 2 if dataLength > 62: remaining = dataLength - 62 while (remaining != 0): if remaining > 64: blockLength = 64 else: blockLength = remaining result.extend( bytearray(self.device.read(65))[0:blockLength]) remaining -= blockLength swOffset = dataLength dataLength -= 2 self.device.set_nonblocking(True) else: swOffset = 0 else: self.device.set_nonblocking(False) while True: response = unwrapResponseAPDU(0x0101, result, 64) if response is not None: result = response dataStart = 0 swOffset = len(response) - 2 dataLength = len(response) - 2 self.device.set_nonblocking(True) break result.extend(bytearray(self.device.read(65))) sw = (result[swOffset] << 8) + result[swOffset + 1] response = result[dataStart: dataLength + dataStart] if self.debug: print("<= %s%.2x" % (hexlify(response), sw)) if sw != 0x9000: raise BTChipException("Invalid status %04x" % sw, sw) return response def waitFirstResponse(self, timeout): start = time.time() data = "" while len(data) == 0: data = self.device.read(65) if not len(data): if time.time() - start > timeout: raise BTChipException("Timeout") time.sleep(0.02) return bytearray(data) def close(self): if self.opened: try: self.device.close() except Exception: pass self.opened = False
class HIDDongleHIDAPI(Dongle, DongleWait): def __init__(self, device, ledger=False, debug=False): pass def exchange(self, apdu, timeout=20000): pass def waitFirstResponse(self, timeout): pass def close(self): pass
5
0
20
0
20
0
6
0.01
2
3
1
0
4
5
4
8
84
4
80
24
75
1
77
24
72
14
2
5
22
145,277
LedgerHQ/btchip-python
LedgerHQ_btchip-python/btchip/ui/personalization00start.py
btchip.ui.personalization00start.Ui_Dialog
class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(400, 231) self.TitleLabel = QtGui.QLabel(Dialog) self.TitleLabel.setGeometry(QtCore.QRect(120, 20, 231, 31)) font = QtGui.QFont() font.setPointSize(20) font.setBold(True) font.setItalic(True) font.setWeight(75) self.TitleLabel.setFont(font) self.TitleLabel.setObjectName(_fromUtf8("TitleLabel")) self.IntroLabel = QtGui.QLabel(Dialog) self.IntroLabel.setGeometry(QtCore.QRect(20, 60, 351, 61)) self.IntroLabel.setWordWrap(True) self.IntroLabel.setObjectName(_fromUtf8("IntroLabel")) self.NextButton = QtGui.QPushButton(Dialog) self.NextButton.setGeometry(QtCore.QRect(310, 200, 75, 25)) self.NextButton.setObjectName(_fromUtf8("NextButton")) self.arningLabel = QtGui.QLabel(Dialog) self.arningLabel.setGeometry(QtCore.QRect(20, 120, 351, 81)) self.arningLabel.setWordWrap(True) self.arningLabel.setObjectName(_fromUtf8("arningLabel")) self.CancelButton = QtGui.QPushButton(Dialog) self.CancelButton.setGeometry(QtCore.QRect(20, 200, 75, 25)) self.CancelButton.setObjectName(_fromUtf8("CancelButton")) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "BTChip setup", None, QtGui.QApplication.UnicodeUTF8)) self.TitleLabel.setText(QtGui.QApplication.translate("Dialog", "BTChip setup", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel.setText(QtGui.QApplication.translate("Dialog", "Your BTChip dongle is not set up - you\'ll be able to create a new wallet, or restore an existing one, and choose your security profile.", None, QtGui.QApplication.UnicodeUTF8)) self.NextButton.setText(QtGui.QApplication.translate("Dialog", "Next", None, QtGui.QApplication.UnicodeUTF8)) self.arningLabel.setText(QtGui.QApplication.translate("Dialog", "Sensitive information including your dongle PIN will be exchanged during this setup phase - it is recommended to execute it on a secure computer, disconnected from any network, especially if you restore a wallet backup.", None, QtGui.QApplication.UnicodeUTF8)) self.CancelButton.setText(QtGui.QApplication.translate("Dialog", "Cancel", None, QtGui.QApplication.UnicodeUTF8))
class Ui_Dialog(object): def setupUi(self, Dialog): pass def retranslateUi(self, Dialog): pass
3
0
18
1
18
0
1
0
1
0
0
0
2
5
2
2
38
2
36
9
33
0
36
9
33
1
1
0
2
145,278
LedgerHQ/btchip-python
LedgerHQ_btchip-python/btchip/ui/personalization01seed.py
btchip.ui.personalization01seed.Ui_Dialog
class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(400, 300) self.TitleLabel = QtGui.QLabel(Dialog) self.TitleLabel.setGeometry(QtCore.QRect(50, 20, 311, 31)) font = QtGui.QFont() font.setPointSize(20) font.setBold(True) font.setItalic(True) font.setWeight(75) self.TitleLabel.setFont(font) self.TitleLabel.setObjectName(_fromUtf8("TitleLabel")) self.IntroLabel = QtGui.QLabel(Dialog) self.IntroLabel.setGeometry(QtCore.QRect(20, 60, 351, 61)) self.IntroLabel.setWordWrap(True) self.IntroLabel.setObjectName(_fromUtf8("IntroLabel")) self.NewWalletButton = QtGui.QRadioButton(Dialog) self.NewWalletButton.setGeometry(QtCore.QRect(20, 130, 94, 21)) self.NewWalletButton.setChecked(True) self.NewWalletButton.setObjectName(_fromUtf8("NewWalletButton")) self.buttonGroup = QtGui.QButtonGroup(Dialog) self.buttonGroup.setObjectName(_fromUtf8("buttonGroup")) self.buttonGroup.addButton(self.NewWalletButton) self.RestoreWalletButton = QtGui.QRadioButton(Dialog) self.RestoreWalletButton.setGeometry(QtCore.QRect(20, 180, 171, 21)) self.RestoreWalletButton.setObjectName(_fromUtf8("RestoreWalletButton")) self.buttonGroup.addButton(self.RestoreWalletButton) self.seed = QtGui.QLineEdit(Dialog) self.seed.setEnabled(False) self.seed.setGeometry(QtCore.QRect(50, 210, 331, 21)) self.seed.setEchoMode(QtGui.QLineEdit.Normal) self.seed.setObjectName(_fromUtf8("seed")) self.CancelButton = QtGui.QPushButton(Dialog) self.CancelButton.setGeometry(QtCore.QRect(10, 270, 75, 25)) self.CancelButton.setObjectName(_fromUtf8("CancelButton")) self.NextButton = QtGui.QPushButton(Dialog) self.NextButton.setGeometry(QtCore.QRect(320, 270, 75, 25)) self.NextButton.setObjectName(_fromUtf8("NextButton")) self.mnemonicNotAvailableLabel = QtGui.QLabel(Dialog) self.mnemonicNotAvailableLabel.setGeometry(QtCore.QRect(130, 240, 171, 31)) font = QtGui.QFont() font.setItalic(True) self.mnemonicNotAvailableLabel.setFont(font) self.mnemonicNotAvailableLabel.setWordWrap(True) self.mnemonicNotAvailableLabel.setObjectName(_fromUtf8("mnemonicNotAvailableLabel")) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "BTChip setup - seed", None, QtGui.QApplication.UnicodeUTF8)) self.TitleLabel.setText(QtGui.QApplication.translate("Dialog", "BTChip setup - seed (1/3)", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel.setText(QtGui.QApplication.translate("Dialog", "Please select an option : either create a new wallet or restore an existing one", None, QtGui.QApplication.UnicodeUTF8)) self.NewWalletButton.setText(QtGui.QApplication.translate("Dialog", "New Wallet", None, QtGui.QApplication.UnicodeUTF8)) self.RestoreWalletButton.setText(QtGui.QApplication.translate("Dialog", "Restore wallet backup", None, QtGui.QApplication.UnicodeUTF8)) self.seed.setPlaceholderText(QtGui.QApplication.translate("Dialog", "Enter an hexadecimal seed or a BIP 39 mnemonic code", None, QtGui.QApplication.UnicodeUTF8)) self.CancelButton.setText(QtGui.QApplication.translate("Dialog", "Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.NextButton.setText(QtGui.QApplication.translate("Dialog", "Next", None, QtGui.QApplication.UnicodeUTF8)) self.mnemonicNotAvailableLabel.setText(QtGui.QApplication.translate("Dialog", "Mnemonic API is not available", None, QtGui.QApplication.UnicodeUTF8))
class Ui_Dialog(object): def setupUi(self, Dialog): pass def retranslateUi(self, Dialog): pass
3
0
29
1
29
0
1
0
1
0
0
0
2
9
2
2
60
2
58
13
55
0
58
13
55
1
1
0
2
145,279
LedgerHQ/btchip-python
LedgerHQ_btchip-python/btchip/ui/personalization02security.py
btchip.ui.personalization02security.Ui_Dialog
class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(400, 503) self.TitleLabel = QtGui.QLabel(Dialog) self.TitleLabel.setGeometry(QtCore.QRect(20, 20, 361, 31)) font = QtGui.QFont() font.setPointSize(20) font.setBold(True) font.setItalic(True) font.setWeight(75) self.TitleLabel.setFont(font) self.TitleLabel.setObjectName(_fromUtf8("TitleLabel")) self.IntroLabel = QtGui.QLabel(Dialog) self.IntroLabel.setGeometry(QtCore.QRect(10, 60, 351, 61)) self.IntroLabel.setWordWrap(True) self.IntroLabel.setObjectName(_fromUtf8("IntroLabel")) self.HardenedButton = QtGui.QRadioButton(Dialog) self.HardenedButton.setGeometry(QtCore.QRect(20, 110, 81, 21)) self.HardenedButton.setChecked(True) self.HardenedButton.setObjectName(_fromUtf8("HardenedButton")) self.buttonGroup = QtGui.QButtonGroup(Dialog) self.buttonGroup.setObjectName(_fromUtf8("buttonGroup")) self.buttonGroup.addButton(self.HardenedButton) self.HardenedButton_2 = QtGui.QRadioButton(Dialog) self.HardenedButton_2.setGeometry(QtCore.QRect(20, 210, 81, 21)) self.HardenedButton_2.setObjectName(_fromUtf8("HardenedButton_2")) self.buttonGroup.addButton(self.HardenedButton_2) self.IntroLabel_2 = QtGui.QLabel(Dialog) self.IntroLabel_2.setGeometry(QtCore.QRect(50, 140, 351, 61)) self.IntroLabel_2.setWordWrap(True) self.IntroLabel_2.setObjectName(_fromUtf8("IntroLabel_2")) self.IntroLabel_3 = QtGui.QLabel(Dialog) self.IntroLabel_3.setGeometry(QtCore.QRect(50, 230, 351, 61)) self.IntroLabel_3.setWordWrap(True) self.IntroLabel_3.setObjectName(_fromUtf8("IntroLabel_3")) self.CancelButton = QtGui.QPushButton(Dialog) self.CancelButton.setGeometry(QtCore.QRect(10, 470, 75, 25)) self.CancelButton.setObjectName(_fromUtf8("CancelButton")) self.NextButton = QtGui.QPushButton(Dialog) self.NextButton.setGeometry(QtCore.QRect(310, 470, 75, 25)) self.NextButton.setObjectName(_fromUtf8("NextButton")) self.IntroLabel_4 = QtGui.QLabel(Dialog) self.IntroLabel_4.setGeometry(QtCore.QRect(10, 300, 351, 61)) self.IntroLabel_4.setWordWrap(True) self.IntroLabel_4.setObjectName(_fromUtf8("IntroLabel_4")) self.IntroLabel_5 = QtGui.QLabel(Dialog) self.IntroLabel_5.setGeometry(QtCore.QRect(20, 380, 161, 31)) self.IntroLabel_5.setWordWrap(True) self.IntroLabel_5.setObjectName(_fromUtf8("IntroLabel_5")) self.pin1 = QtGui.QLineEdit(Dialog) self.pin1.setGeometry(QtCore.QRect(210, 380, 161, 21)) self.pin1.setEchoMode(QtGui.QLineEdit.Password) self.pin1.setObjectName(_fromUtf8("pin1")) self.pin2 = QtGui.QLineEdit(Dialog) self.pin2.setGeometry(QtCore.QRect(210, 420, 161, 21)) self.pin2.setEchoMode(QtGui.QLineEdit.Password) self.pin2.setObjectName(_fromUtf8("pin2")) self.IntroLabel_6 = QtGui.QLabel(Dialog) self.IntroLabel_6.setGeometry(QtCore.QRect(20, 420, 171, 31)) self.IntroLabel_6.setWordWrap(True) self.IntroLabel_6.setObjectName(_fromUtf8("IntroLabel_6")) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "BTChip setup - security", None, QtGui.QApplication.UnicodeUTF8)) self.TitleLabel.setText(QtGui.QApplication.translate("Dialog", "BTChip setup - security (2/3)", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel.setText(QtGui.QApplication.translate("Dialog", "Please choose a security profile", None, QtGui.QApplication.UnicodeUTF8)) self.HardenedButton.setText(QtGui.QApplication.translate("Dialog", "Hardened", None, QtGui.QApplication.UnicodeUTF8)) self.HardenedButton_2.setText(QtGui.QApplication.translate("Dialog", "PIN only", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_2.setText(QtGui.QApplication.translate("Dialog", "You need to remove the dongle and insert it again to get a second factor validation of all operations. Recommended for expert users and to be fully protected against malwares.", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_3.setText(QtGui.QApplication.translate("Dialog", "You only need to enter a PIN once when inserting the dongle. Transactions are not protected against malwares", None, QtGui.QApplication.UnicodeUTF8)) self.CancelButton.setText(QtGui.QApplication.translate("Dialog", "Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.NextButton.setText(QtGui.QApplication.translate("Dialog", "Next", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_4.setText(QtGui.QApplication.translate("Dialog", "Please choose a PIN associated to the BTChip dongle. The PIN protects the dongle in case it is stolen, and can be up to 32 characters. The dongle is wiped if a wrong PIN is entered 3 times in a row.", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_5.setText(QtGui.QApplication.translate("Dialog", "Enter the new PIN : ", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_6.setText(QtGui.QApplication.translate("Dialog", "Repeat the new PIN :", None, QtGui.QApplication.UnicodeUTF8))
class Ui_Dialog(object): def setupUi(self, Dialog): pass def retranslateUi(self, Dialog): pass
3
0
39
1
38
0
1
0
1
0
0
0
2
14
2
2
79
2
77
18
74
0
77
18
74
1
1
0
2
145,280
LedgerHQ/btchip-python
LedgerHQ_btchip-python/btchip/ui/personalization03config.py
btchip.ui.personalization03config.Ui_Dialog
class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(400, 243) self.TitleLabel = QtGui.QLabel(Dialog) self.TitleLabel.setGeometry(QtCore.QRect(30, 10, 361, 31)) font = QtGui.QFont() font.setPointSize(20) font.setBold(True) font.setItalic(True) font.setWeight(75) self.TitleLabel.setFont(font) self.TitleLabel.setObjectName(_fromUtf8("TitleLabel")) self.IntroLabel = QtGui.QLabel(Dialog) self.IntroLabel.setGeometry(QtCore.QRect(20, 50, 351, 61)) self.IntroLabel.setWordWrap(True) self.IntroLabel.setObjectName(_fromUtf8("IntroLabel")) self.qwertyButton = QtGui.QRadioButton(Dialog) self.qwertyButton.setGeometry(QtCore.QRect(50, 110, 94, 21)) self.qwertyButton.setChecked(True) self.qwertyButton.setObjectName(_fromUtf8("qwertyButton")) self.keyboardGroup = QtGui.QButtonGroup(Dialog) self.keyboardGroup.setObjectName(_fromUtf8("keyboardGroup")) self.keyboardGroup.addButton(self.qwertyButton) self.qwertzButton = QtGui.QRadioButton(Dialog) self.qwertzButton.setGeometry(QtCore.QRect(50, 140, 94, 21)) self.qwertzButton.setObjectName(_fromUtf8("qwertzButton")) self.keyboardGroup.addButton(self.qwertzButton) self.azertyButton = QtGui.QRadioButton(Dialog) self.azertyButton.setGeometry(QtCore.QRect(50, 170, 94, 21)) self.azertyButton.setObjectName(_fromUtf8("azertyButton")) self.keyboardGroup.addButton(self.azertyButton) self.CancelButton = QtGui.QPushButton(Dialog) self.CancelButton.setGeometry(QtCore.QRect(10, 210, 75, 25)) self.CancelButton.setObjectName(_fromUtf8("CancelButton")) self.NextButton = QtGui.QPushButton(Dialog) self.NextButton.setGeometry(QtCore.QRect(320, 210, 75, 25)) self.NextButton.setObjectName(_fromUtf8("NextButton")) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "BTChip setup", None, QtGui.QApplication.UnicodeUTF8)) self.TitleLabel.setText(QtGui.QApplication.translate("Dialog", "BTChip setup - config (3/3)", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel.setText(QtGui.QApplication.translate("Dialog", "Please select your keyboard type to type the second factor confirmation", None, QtGui.QApplication.UnicodeUTF8)) self.qwertyButton.setText(QtGui.QApplication.translate("Dialog", "QWERTY", None, QtGui.QApplication.UnicodeUTF8)) self.qwertzButton.setText(QtGui.QApplication.translate("Dialog", "QWERTZ", None, QtGui.QApplication.UnicodeUTF8)) self.azertyButton.setText(QtGui.QApplication.translate("Dialog", "AZERTY", None, QtGui.QApplication.UnicodeUTF8)) self.CancelButton.setText(QtGui.QApplication.translate("Dialog", "Cancel", None, QtGui.QApplication.UnicodeUTF8)) self.NextButton.setText(QtGui.QApplication.translate("Dialog", "Next", None, QtGui.QApplication.UnicodeUTF8))
class Ui_Dialog(object): def setupUi(self, Dialog): pass def retranslateUi(self, Dialog): pass
3
0
25
1
24
0
1
0
1
0
0
0
2
8
2
2
51
2
49
12
46
0
49
12
46
1
1
0
2
145,281
LedgerHQ/btchip-python
LedgerHQ_btchip-python/btchip/ui/personalization04finalize.py
btchip.ui.personalization04finalize.Ui_Dialog
class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(400, 267) self.TitleLabel = QtGui.QLabel(Dialog) self.TitleLabel.setGeometry(QtCore.QRect(20, 20, 361, 31)) font = QtGui.QFont() font.setPointSize(20) font.setBold(True) font.setItalic(True) font.setWeight(75) self.TitleLabel.setFont(font) self.TitleLabel.setObjectName(_fromUtf8("TitleLabel")) self.FinishButton = QtGui.QPushButton(Dialog) self.FinishButton.setGeometry(QtCore.QRect(320, 230, 75, 25)) self.FinishButton.setObjectName(_fromUtf8("FinishButton")) self.IntroLabel_4 = QtGui.QLabel(Dialog) self.IntroLabel_4.setGeometry(QtCore.QRect(10, 70, 351, 61)) self.IntroLabel_4.setWordWrap(True) self.IntroLabel_4.setObjectName(_fromUtf8("IntroLabel_4")) self.IntroLabel_5 = QtGui.QLabel(Dialog) self.IntroLabel_5.setGeometry(QtCore.QRect(50, 140, 121, 21)) self.IntroLabel_5.setWordWrap(True) self.IntroLabel_5.setObjectName(_fromUtf8("IntroLabel_5")) self.pin1 = QtGui.QLineEdit(Dialog) self.pin1.setGeometry(QtCore.QRect(200, 140, 181, 21)) self.pin1.setEchoMode(QtGui.QLineEdit.Password) self.pin1.setObjectName(_fromUtf8("pin1")) self.remainingAttemptsLabel = QtGui.QLabel(Dialog) self.remainingAttemptsLabel.setGeometry(QtCore.QRect(120, 170, 171, 31)) font = QtGui.QFont() font.setItalic(True) self.remainingAttemptsLabel.setFont(font) self.remainingAttemptsLabel.setWordWrap(True) self.remainingAttemptsLabel.setObjectName(_fromUtf8("remainingAttemptsLabel")) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "BTChip setup - security", None, QtGui.QApplication.UnicodeUTF8)) self.TitleLabel.setText(QtGui.QApplication.translate("Dialog", "BTChip setup - completed", None, QtGui.QApplication.UnicodeUTF8)) self.FinishButton.setText(QtGui.QApplication.translate("Dialog", "Finish", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_4.setText(QtGui.QApplication.translate("Dialog", "BTChip setup is completed. Please enter your PIN to validate it then press Finish", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_5.setText(QtGui.QApplication.translate("Dialog", "BTChip PIN :", None, QtGui.QApplication.UnicodeUTF8)) self.remainingAttemptsLabel.setText(QtGui.QApplication.translate("Dialog", "Remaining attempts", None, QtGui.QApplication.UnicodeUTF8))
class Ui_Dialog(object): def setupUi(self, Dialog): pass def retranslateUi(self, Dialog): pass
3
0
22
1
22
0
1
0
1
0
0
0
2
6
2
2
46
2
44
10
41
0
44
10
41
1
1
0
2
145,282
LedgerHQ/btchip-python
LedgerHQ_btchip-python/btchip/ui/personalizationseedbackup01.py
btchip.ui.personalizationseedbackup01.Ui_Dialog
class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(400, 300) self.TitleLabel = QtGui.QLabel(Dialog) self.TitleLabel.setGeometry(QtCore.QRect(30, 20, 351, 31)) font = QtGui.QFont() font.setPointSize(20) font.setBold(True) font.setItalic(True) font.setWeight(75) self.TitleLabel.setFont(font) self.TitleLabel.setObjectName(_fromUtf8("TitleLabel")) self.NextButton = QtGui.QPushButton(Dialog) self.NextButton.setGeometry(QtCore.QRect(320, 270, 75, 25)) self.NextButton.setObjectName(_fromUtf8("NextButton")) self.IntroLabel = QtGui.QLabel(Dialog) self.IntroLabel.setGeometry(QtCore.QRect(10, 100, 351, 31)) self.IntroLabel.setWordWrap(True) self.IntroLabel.setObjectName(_fromUtf8("IntroLabel")) self.IntroLabel_2 = QtGui.QLabel(Dialog) self.IntroLabel_2.setGeometry(QtCore.QRect(10, 140, 351, 31)) self.IntroLabel_2.setWordWrap(True) self.IntroLabel_2.setObjectName(_fromUtf8("IntroLabel_2")) self.IntroLabel_3 = QtGui.QLabel(Dialog) self.IntroLabel_3.setGeometry(QtCore.QRect(10, 180, 351, 41)) self.IntroLabel_3.setWordWrap(True) self.IntroLabel_3.setObjectName(_fromUtf8("IntroLabel_3")) self.TitleLabel_2 = QtGui.QLabel(Dialog) self.TitleLabel_2.setGeometry(QtCore.QRect(90, 60, 251, 31)) font = QtGui.QFont() font.setPointSize(20) font.setBold(True) font.setItalic(True) font.setWeight(75) self.TitleLabel_2.setFont(font) self.TitleLabel_2.setObjectName(_fromUtf8("TitleLabel_2")) self.IntroLabel_4 = QtGui.QLabel(Dialog) self.IntroLabel_4.setGeometry(QtCore.QRect(10, 220, 351, 41)) self.IntroLabel_4.setWordWrap(True) self.IntroLabel_4.setObjectName(_fromUtf8("IntroLabel_4")) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "BTChip setup", None, QtGui.QApplication.UnicodeUTF8)) self.TitleLabel.setText(QtGui.QApplication.translate("Dialog", "BTChip setup - seed backup", None, QtGui.QApplication.UnicodeUTF8)) self.NextButton.setText(QtGui.QApplication.translate("Dialog", "Next", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel.setText(QtGui.QApplication.translate("Dialog", "A new seed has been generated for your wallet.", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_2.setText(QtGui.QApplication.translate("Dialog", "You must backup this seed and keep it out of reach of hackers (typically by keeping it on paper).", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_3.setText(QtGui.QApplication.translate("Dialog", "You can use this seed to restore your dongle if you lose it or access your funds with any other compatible wallet.", None, QtGui.QApplication.UnicodeUTF8)) self.TitleLabel_2.setText(QtGui.QApplication.translate("Dialog", "READ CAREFULLY", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_4.setText(QtGui.QApplication.translate("Dialog", "Press Next to start the backuping process.", None, QtGui.QApplication.UnicodeUTF8))
class Ui_Dialog(object): def setupUi(self, Dialog): pass def retranslateUi(self, Dialog): pass
3
0
26
1
26
0
1
0
1
0
0
0
2
7
2
2
54
2
52
11
49
0
52
11
49
1
1
0
2
145,283
LedgerHQ/btchip-python
LedgerHQ_btchip-python/btchip/ui/personalizationseedbackup02.py
btchip.ui.personalizationseedbackup02.Ui_Dialog
class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(400, 300) self.TitleLabel = QtGui.QLabel(Dialog) self.TitleLabel.setGeometry(QtCore.QRect(30, 20, 351, 31)) font = QtGui.QFont() font.setPointSize(20) font.setBold(True) font.setItalic(True) font.setWeight(75) self.TitleLabel.setFont(font) self.TitleLabel.setObjectName(_fromUtf8("TitleLabel")) self.IntroLabel = QtGui.QLabel(Dialog) self.IntroLabel.setGeometry(QtCore.QRect(20, 70, 351, 31)) self.IntroLabel.setWordWrap(True) self.IntroLabel.setObjectName(_fromUtf8("IntroLabel")) self.NextButton = QtGui.QPushButton(Dialog) self.NextButton.setGeometry(QtCore.QRect(320, 270, 75, 25)) self.NextButton.setObjectName(_fromUtf8("NextButton")) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "BTChip setup", None, QtGui.QApplication.UnicodeUTF8)) self.TitleLabel.setText(QtGui.QApplication.translate("Dialog", "BTChip setup - seed backup", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel.setText(QtGui.QApplication.translate("Dialog", "Please disconnect the dongle then press Next", None, QtGui.QApplication.UnicodeUTF8)) self.NextButton.setText(QtGui.QApplication.translate("Dialog", "Next", None, QtGui.QApplication.UnicodeUTF8))
class Ui_Dialog(object): def setupUi(self, Dialog): pass def retranslateUi(self, Dialog): pass
3
0
14
1
13
0
1
0
1
0
0
0
2
3
2
2
29
2
27
7
24
0
27
7
24
1
1
0
2
145,284
LedgerHQ/btchip-python
LedgerHQ_btchip-python/btchip/ui/personalizationseedbackup03.py
btchip.ui.personalizationseedbackup03.Ui_Dialog
class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(400, 513) self.TitleLabel = QtGui.QLabel(Dialog) self.TitleLabel.setGeometry(QtCore.QRect(20, 10, 351, 31)) font = QtGui.QFont() font.setPointSize(20) font.setBold(True) font.setItalic(True) font.setWeight(75) self.TitleLabel.setFont(font) self.TitleLabel.setObjectName(_fromUtf8("TitleLabel")) self.IntroLabel = QtGui.QLabel(Dialog) self.IntroLabel.setGeometry(QtCore.QRect(20, 50, 351, 61)) self.IntroLabel.setWordWrap(True) self.IntroLabel.setObjectName(_fromUtf8("IntroLabel")) self.IntroLabel_2 = QtGui.QLabel(Dialog) self.IntroLabel_2.setGeometry(QtCore.QRect(20, 120, 351, 31)) self.IntroLabel_2.setWordWrap(True) self.IntroLabel_2.setObjectName(_fromUtf8("IntroLabel_2")) self.IntroLabel_3 = QtGui.QLabel(Dialog) self.IntroLabel_3.setGeometry(QtCore.QRect(20, 160, 351, 51)) self.IntroLabel_3.setWordWrap(True) self.IntroLabel_3.setObjectName(_fromUtf8("IntroLabel_3")) self.IntroLabel_4 = QtGui.QLabel(Dialog) self.IntroLabel_4.setGeometry(QtCore.QRect(20, 220, 351, 51)) self.IntroLabel_4.setWordWrap(True) self.IntroLabel_4.setObjectName(_fromUtf8("IntroLabel_4")) self.IntroLabel_5 = QtGui.QLabel(Dialog) self.IntroLabel_5.setGeometry(QtCore.QRect(20, 280, 351, 71)) self.IntroLabel_5.setWordWrap(True) self.IntroLabel_5.setObjectName(_fromUtf8("IntroLabel_5")) self.IntroLabel_6 = QtGui.QLabel(Dialog) self.IntroLabel_6.setGeometry(QtCore.QRect(20, 350, 351, 51)) self.IntroLabel_6.setWordWrap(True) self.IntroLabel_6.setObjectName(_fromUtf8("IntroLabel_6")) self.IntroLabel_7 = QtGui.QLabel(Dialog) self.IntroLabel_7.setGeometry(QtCore.QRect(20, 410, 351, 51)) self.IntroLabel_7.setWordWrap(True) self.IntroLabel_7.setObjectName(_fromUtf8("IntroLabel_7")) self.NextButton = QtGui.QPushButton(Dialog) self.NextButton.setGeometry(QtCore.QRect(310, 480, 75, 25)) self.NextButton.setObjectName(_fromUtf8("NextButton")) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "BTChip setup", None, QtGui.QApplication.UnicodeUTF8)) self.TitleLabel.setText(QtGui.QApplication.translate("Dialog", "BTChip setup - seed backup", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel.setText(QtGui.QApplication.translate("Dialog", "If you do not trust this computer, perform the following steps on a trusted one or a different device. Anything supporting keyboard input will work (smartphone, TV box ...)", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_2.setText(QtGui.QApplication.translate("Dialog", "Open a text editor, set the focus on the text editor, then insert the dongle", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_3.setText(QtGui.QApplication.translate("Dialog", "After a very short time, the dongle will type the seed as hexadecimal (0..9 A..F) characters, starting with \"seed\" and ending with \"X\"", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_4.setText(QtGui.QApplication.translate("Dialog", "If you perform those steps on Windows, a new device driver will be loaded the first time and the seed will not be typed. This is normal.", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_5.setText(QtGui.QApplication.translate("Dialog", "If you perform those steps on Mac, you\'ll get a popup asking you to select a keyboard type the first time and the seed will not be typed. This is normal, just close the popup.", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_6.setText(QtGui.QApplication.translate("Dialog", "If you did not see the seed for any reason, keep the focus on the text editor, unplug and plug the dongle again twice.", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel_7.setText(QtGui.QApplication.translate("Dialog", "Then press Next once you wrote the seed to a safe medium (i.e. paper) and unplugged the dongle", None, QtGui.QApplication.UnicodeUTF8)) self.NextButton.setText(QtGui.QApplication.translate("Dialog", "Next", None, QtGui.QApplication.UnicodeUTF8))
class Ui_Dialog(object): def setupUi(self, Dialog): pass def retranslateUi(self, Dialog): pass
3
0
29
1
28
0
1
0
1
0
0
0
2
9
2
2
59
2
57
13
54
0
57
13
54
1
1
0
2
145,285
LedgerHQ/btchip-python
LedgerHQ_btchip-python/btchip/ui/personalizationseedbackup04.py
btchip.ui.personalizationseedbackup04.Ui_Dialog
class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName(_fromUtf8("Dialog")) Dialog.resize(554, 190) self.TitleLabel = QtGui.QLabel(Dialog) self.TitleLabel.setGeometry(QtCore.QRect(30, 10, 351, 31)) font = QtGui.QFont() font.setPointSize(20) font.setBold(True) font.setItalic(True) font.setWeight(75) self.TitleLabel.setFont(font) self.TitleLabel.setObjectName(_fromUtf8("TitleLabel")) self.IntroLabel = QtGui.QLabel(Dialog) self.IntroLabel.setGeometry(QtCore.QRect(10, 50, 351, 51)) self.IntroLabel.setWordWrap(True) self.IntroLabel.setObjectName(_fromUtf8("IntroLabel")) self.seedOkButton = QtGui.QPushButton(Dialog) self.seedOkButton.setGeometry(QtCore.QRect(20, 140, 501, 25)) self.seedOkButton.setObjectName(_fromUtf8("seedOkButton")) self.seedKoButton = QtGui.QPushButton(Dialog) self.seedKoButton.setGeometry(QtCore.QRect(20, 110, 501, 25)) self.seedKoButton.setObjectName(_fromUtf8("seedKoButton")) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "BTChip setup", None, QtGui.QApplication.UnicodeUTF8)) self.TitleLabel.setText(QtGui.QApplication.translate("Dialog", "BTChip setup - seed backup", None, QtGui.QApplication.UnicodeUTF8)) self.IntroLabel.setText(QtGui.QApplication.translate("Dialog", "Did you see the seed correctly displayed and did you backup it properly ?", None, QtGui.QApplication.UnicodeUTF8)) self.seedOkButton.setText(QtGui.QApplication.translate("Dialog", "Yes, the seed is backed up properly and kept in a safe place, move on", None, QtGui.QApplication.UnicodeUTF8)) self.seedKoButton.setText(QtGui.QApplication.translate("Dialog", "No, I didn\'t see the seed. Wipe the dongle and start over", None, QtGui.QApplication.UnicodeUTF8))
class Ui_Dialog(object): def setupUi(self, Dialog): pass def retranslateUi(self, Dialog): pass
3
0
16
1
15
0
1
0
1
0
0
0
2
4
2
2
33
2
31
8
28
0
31
8
28
1
1
0
2
145,286
LedgerHQ/btchip-python
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LedgerHQ_btchip-python/btchip/btchipPersoWizard.py
btchip.btchipPersoWizard.SeedBackupUnplug
class SeedBackupUnplug(QtGui.QDialog): def __init__(self, persoData, parent=None): QDialog.__init__(self, parent) self.persoData = persoData self.ui = ui.personalizationseedbackup02.Ui_Dialog() self.ui.setupUi(self) self.ui.NextButton.clicked.connect(self.processNext) def processNext(self): dialog = SeedBackupInstructions(self.persoData, self) self.hide() dialog.exec_()
class SeedBackupUnplug(QtGui.QDialog): def __init__(self, persoData, parent=None): pass def processNext(self): pass
3
0
5
0
5
0
1
0
1
1
1
0
2
2
2
2
13
2
11
6
8
0
11
6
8
1
1
0
2
145,287
LedgerHQ/btchip-python
LedgerHQ_btchip-python/btchip/btchipKeyRecovery.py
btchip.btchipKeyRecovery.MyVerifyingKey
class MyVerifyingKey(ecdsa.VerifyingKey): @classmethod def from_signature(klass, sig, recid, h, curve): """ See http://www.secg.org/download/aid-780/sec1-v2.pdf, chapter 4.1.6 """ from ecdsa import util, numbertheory import msqr curveFp = curve.curve G = curve.generator order = G.order() # extract r,s from signature r, s = util.sigdecode_string(sig, order) # 1.1 x = r + (recid/2) * order # 1.3 alpha = ( x * x * x + curveFp.a() * x + curveFp.b() ) % curveFp.p() beta = msqr.modular_sqrt(alpha, curveFp.p()) y = beta if (beta - recid) % 2 == 0 else curveFp.p() - beta # 1.4 the constructor checks that nR is at infinity R = Point(curveFp, x, y, order) # 1.5 compute e from message: e = string_to_number(h) minus_e = -e % order # 1.6 compute Q = r^-1 (sR - eG) inv_r = numbertheory.inverse_mod(r,order) Q = inv_r * ( s * R + minus_e * G ) return klass.from_public_point( Q, curve )
class MyVerifyingKey(ecdsa.VerifyingKey): @classmethod def from_signature(klass, sig, recid, h, curve): ''' See http://www.secg.org/download/aid-780/sec1-v2.pdf, chapter 4.1.6 ''' pass
3
1
24
0
17
7
2
0.37
1
0
0
0
0
0
1
1
26
0
19
18
14
7
18
17
14
2
1
0
2
145,288
Leeps-Lab/otree-redwood
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Leeps-Lab_otree-redwood/otree_redwood/models.py
otree_redwood.models.Group.Meta
class Meta(BaseGroup.Meta): abstract = True
class Meta(BaseGroup.Meta): pass
1
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
145,289
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/views.py
otree_redwood.views.DebugView
class DebugView(vanilla.TemplateView): url_name = 'redwood_debug' url_pattern = r'^redwood/debug/session/(?P<session_code>[a-zA-Z0-9_-]+)/$' template_name = 'otree_redwood/Debug.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stats'] = stats.items() channel_layer = channels.asgi.get_channel_layer() if 'statistics' in channel_layer.extensions: context['global_channel_stats'] = channel_layer.global_statistics() context['connected_participants'] = Connection.objects.all() context['session_code'] = self.kwargs['session_code'] return context
class DebugView(vanilla.TemplateView): def get_context_data(self, **kwargs): pass
2
0
9
0
9
0
2
0
1
2
1
0
1
0
1
1
15
2
13
7
11
0
13
7
11
2
1
1
2
145,290
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/utils.py
otree_redwood.utils.DiscreteEventEmitter
class DiscreteEventEmitter(): def __init__(self, interval, period_length, group, callback, start_immediate=False): self.interval = float(interval) self.period_length = period_length self.group = group self.intervals = self.period_length / self.interval self.callback = callback self.current_interval = 0 if self.group not in _timers: # TODO: Should replace this with something like Huey/Celery so it'll survive a server restart. self.timer = threading.Timer(0 if start_immediate else self.interval, self._tick) _timers[self.group] = self.timer else: self.timer = None def _tick(self): start = time.time() self.callback(self.current_interval, self.intervals) self.current_interval += 1 if self.current_interval < self.intervals: self.timer = threading.Timer(self._time, self._tick) _timers[self.group] = self.timer self.timer.start() @property def _time(self): return self.interval - ((time.time() - self.start_time) % self.interval) def start(self): if self.timer: self.start_time = time.time() self.timer.start() def stop(self): del _timers[self.group]
class DiscreteEventEmitter(): def __init__(self, interval, period_length, group, callback, start_immediate=False): pass def _tick(self): pass @property def _time(self): pass def start(self): pass def stop(self): pass
7
0
6
0
6
0
2
0.03
0
2
0
0
5
8
5
5
36
5
30
16
23
1
28
15
22
3
0
1
9
145,291
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/stats.py
otree_redwood.stats.track
class track(): def __init__(self, context): self.context = context global redis if not redis: redis = mockredis.mock_redis_client() def __enter__(self): self.start = time.time() return self def __exit__(self, type, value, traceback): elapsed_time = float(time.time() - self.start) update(self.context, elapsed_time)
class track(): def __init__(self, context): pass def __enter__(self): pass def __exit__(self, type, value, traceback): pass
4
0
4
0
4
0
1
0
0
1
0
0
3
2
3
3
15
3
12
8
7
0
12
8
7
2
0
1
4
145,292
Leeps-Lab/otree-redwood
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Leeps-Lab_otree-redwood/otree_redwood/models.py
otree_redwood.models.Event.Meta
class Meta: # Default to queries returning most recent Event first. ordering = ['timestamp']
class Meta: pass
1
0
0
0
0
0
0
0.5
0
0
0
0
0
0
0
0
3
0
2
2
1
1
2
2
1
0
0
0
0
145,293
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/management/commands/asynctest.py
asynctest.Command
class Command(BaseCommand): help = ('Discover and run experiment tests in the specified ' 'modules or the current directory.') def _get_action(self, parser, signature): option_strings = list(signature) for idx, action in enumerate(parser._actions): if action.option_strings == option_strings: return parser._actions[idx] def add_arguments(self, parser): # Positional arguments parser.add_argument( 'session_config_name', nargs='?', help='If omitted, all sessions in SESSION_CONFIGS are run' ) ahelp = ( 'Number of participants. ' 'Defaults to minimum for the session config.' ) parser.add_argument( 'num_participants', type=int, nargs='?', help=ahelp) parser.add_argument( '--export', nargs='?', const=AUTO_NAME_BOTS_EXPORT_FOLDER, help=( 'Saves the data generated by the tests. ' 'Runs the "export data" command, ' 'outputting the CSV files to the specified directory, ' 'or an auto-generated one.'), ) parser.add_argument( '--save', nargs='?', const=AUTO_NAME_BOTS_EXPORT_FOLDER, help=( 'Alias for --export.'), ) v_action = self._get_action(parser, ("-v", "--verbosity")) v_action.default = '1' v_action.help = ( 'Verbosity level; 0=minimal output, 1=normal output,' '2=verbose output (DEFAULT), 3=very verbose output') def execute(self, *args, **options): if int(options['verbosity']) > 3: logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) super(Command, self).execute(*args, **options) if int(options['verbosity']) > 3: logger.removeHandler(handler) def handle(self, **options): # use in-memory. # this is the simplest way to patch tests to use in-memory, # while still using Redis in production settings.CHANNEL_LAYERS['default'] = settings.INMEMORY_CHANNEL_LAYER # so we know not to use Huey otree.common_internal.USE_REDIS = False export_path = options["export"] or options["save"] preserve_data = bool(export_path) exit_code = run_pytests( session_config_name=options["session_config_name"], num_participants=options['num_participants'], preserve_data=preserve_data, export_path=export_path, verbosity=options['verbosity'], ) if not preserve_data: logger.info('Tip: Run this command with the --export flag' ' to save the data generated by bots.') sys.exit(exit_code)
class Command(BaseCommand): def _get_action(self, parser, signature): pass def add_arguments(self, parser): pass def execute(self, *args, **options): pass def handle(self, **options): pass
5
0
18
2
15
1
2
0.08
1
6
0
0
4
0
4
4
78
11
62
15
57
5
33
15
28
3
1
2
9
145,294
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/apps.py
otree_redwood.apps.Config
class Config(AppConfig): name = 'otree_redwood' verbose_name = 'oTree Redwood Extension'
class Config(AppConfig): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
1
0
0
145,295
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/async_test_runner.py
otree_redwood.async_test_runner.SessionBotRunner
class SessionBotRunner(object): def __init__(self, bots): self.bots = OrderedDict() for bot in bots: self.bots[bot.participant.id] = bot def play(self): '''round-robin''' self.open_start_urls() loops_without_progress = 0 while True: import time start = time.time() if len(self.bots) == 0: return # bots got stuck if there's 2 wait pages in a row if loops_without_progress > 10: raise AssertionError('Bots got stuck') results = Chan(buflen=len(self.bots)) threads = [] for bot in self.bots.values(): if bot.on_wait_page(): pass else: thread = SubmitThread(bot, results) threads.append(thread) thread.start() for thread in threads: bot, status = results.get() if isinstance(status, Exception): raise status elif status == 'finished': del self.bots[bot.participant.id] else: bot.submit(status) results.close() if not threads: loops_without_progress += 1 def open_start_urls(self): for bot in self.bots.values(): bot.open_start_url()
class SessionBotRunner(object): def __init__(self, bots): pass def play(self): '''round-robin''' pass def open_start_urls(self): pass
4
1
14
1
12
1
5
0.05
1
4
1
0
3
1
3
3
46
6
38
15
33
2
35
15
30
10
1
3
14
145,296
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/async_test_runner.py
otree_redwood.async_test_runner.SubmitThread
class SubmitThread(threading.Thread): def __init__(self, bot, results): super().__init__() self.bot = bot self.results = results def run(self): try: submission = next(self.bot.submits_generator) self.results.put((self.bot, submission)) except StopIteration: self.results.put((self.bot, 'finished')) except Exception as ex: self.results.put((self.bot, ex))
class SubmitThread(threading.Thread): def __init__(self, bot, results): pass def run(self): pass
3
0
6
0
6
0
2
0
1
3
0
0
2
2
2
27
15
2
13
7
10
0
13
6
10
3
1
1
4
145,297
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/consumers.py
otree_redwood.consumers.EventConsumer
class EventConsumer(JsonWebsocketConsumer): url_pattern = ( r'^redwood' + '/app-name/(?P<app_name>[^/]+)' '/group/(?P<group>[0-9]+)' + '/participant/(?P<participant_code>[a-zA-Z0-9_-]+)' + '/$') def connect(self): self.accept() self.url_params = self.scope['url_route']['kwargs'] group = get_group(self.url_params['app_name'], self.url_params['group']) async_to_sync(self.channel_layer.group_add)( str(group.pk), self.channel_name ) participant = Participant.objects.get(code=self.url_params['participant_code']) try: last_state = group.events.filter(channel='state').latest('timestamp') self.send_json({ 'channel': 'state', 'payload': last_state.value }) except Event.DoesNotExist: pass Connection.objects.get_or_create(participant=participant) group._on_connect(participant) def disconnect(self, close_code): group = get_group(self.url_params['app_name'], self.url_params['group']) async_to_sync(self.channel_layer.group_discard)( str(group.pk), self.channel_name ) participant = Participant.objects.get(code=self.url_params['participant_code']) try: # TODO: Clean out stale connections if not terminated cleanly. Connection.objects.get(participant=participant).delete() except Connection.DoesNotExist: pass group._on_disconnect(participant) def receive_json(self, content): if content['channel'] == 'ping': with stats.track('recv_channel=ping'): if content['avg_ping_time']: stats.update('avg_ping_time', content['avg_ping_time']) self.send_json({ 'channel': 'ping', 'timestamp': content['timestamp'], }) return with stats.track('recv_channel=' + content['channel']): group = get_group(self.url_params['app_name'], self.url_params['group']) participant = Participant.objects.get(code=self.url_params['participant_code']) with stats.track('saving event object to database'): event = group.events.create( participant=participant, channel=content['channel'], value=content['payload']) with stats.track('handing event to group'): try: event_handler = getattr(group, '_on_{}_event'.format(content['channel'])) except AttributeError: pass else: event_handler(event) def redwood_send_to_group(self, event): msg = event['text'] self.send_json(msg)
class EventConsumer(JsonWebsocketConsumer): def connect(self): pass def disconnect(self, close_code): pass def receive_json(self, content): pass def redwood_send_to_group(self, event): pass
5
0
16
1
15
0
2
0.02
1
5
3
0
4
1
4
4
77
10
66
17
61
1
46
17
41
4
1
3
9
145,298
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/consumers.py
otree_redwood.consumers.EventWatcher
class EventWatcher(JsonWebsocketConsumer): url_pattern = r'^redwood/events/session/(?P<session_code>[a-zA-Z0-9_-]+)/$' def connect(self): self.session_code = self.scope['url_route']['kwargs']['session_code'] self.events_group_name = 'redwood_events-{}'.format(self.session_code) async_to_sync(self.channel_layer.group_add)( self.events_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.events_group_name, self.channel_name ) def redwood_send_to_watcher(self, event): msg = event['text'] self.send_json(msg)
class EventWatcher(JsonWebsocketConsumer): def connect(self): pass def disconnect(self, close_code): pass def redwood_send_to_watcher(self, event): pass
4
0
5
0
5
0
1
0
1
0
0
0
3
2
3
3
22
4
18
8
14
0
12
8
8
1
1
0
3
145,299
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/models.py
otree_redwood.models.Group
class Group(BaseGroup): """Group is designed to be used instead of the oTree BaseGroup to provide Redwood-specific functions for coordinating inter-page communication for players in the Group. """ class Meta(BaseGroup.Meta): abstract = True ran_ready_function = models.DateTimeField(null=True) """Set when the :meth:`when_all_players_ready` function has been run. Ensures run-only-once semantics. """ events = GenericRelation(Event, content_type_field='content_type', object_id_field='group_pk') """Allows Group to query all Event models associated with it. This effectively adds an 'events' related name to the Event.group GenericForeignKey. """ def period_length(self): """Implement this to set a timeout on the page in seconds. A period_start message will be sent on the state channel when all players in the group have connected their websockets. A period_end message will be send on the state channel period_length seconds from the period_start message. """ return None def post_round_delay(self): """Implement this to change the delay between when the period ends and the page is advanced. This delay should be provided in seconds. If :meth:`period_length` is not specified, this method does nothing. """ return 1 def get_start_time(self): """Returns a datetime.datetime object representing the time that this period started, or None if the period hasn't started yet. """ try: return self.events.get(channel='state', value='period_start').timestamp except Event.DoesNotExist: return None def get_end_time(self): """Returns a datetime.datetime object representing the time that this period ended. Returns None if :meth:`period_length` is not set, or if the period hasn't ended yet. """ try: return self.events.get(channel='state', value='period_end').timestamp except Event.DoesNotExist: return None def when_all_players_ready(self): """Implement this to perform an action for the group once all players are ready.""" pass def when_player_disconnects(self, player): """Implement this to perform an action when a player disconnects.""" pass def _on_connect(self, participant): """Called from the WebSocket consumer. Checks if all players in the group have connected; runs :meth:`when_all_players_ready` once all connections are established. """ self.refresh_from_db() if self.ran_ready_function: return for player in self.get_players(): if Connection.objects.filter(participant__code=player.participant.code).count() == 0: return self.when_all_players_ready() self.ran_ready_function = timezone.now() self.save() self.send('state', 'period_start') if self.period_length(): # TODO: Should replace this with something like Huey/Celery so it'll survive a server restart. timer = threading.Timer( self.period_length(), lambda: self.send('state', 'period_end')) timer.start() def _on_disconnect(self, participant): """Trigger the :meth:`when_player_disconnects` callback.""" player = None for p in self.get_players(): if p.participant == participant: player = p break self.when_player_disconnects(player) def send(self, channel, payload): """Send a message with the given payload on the given channel. Messages are broadcast to all players in the group. """ with track('send_channel=' + channel): with track('create event'): Event.objects.create( group=self, channel=channel, value=payload) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( str(self.pk), { 'type': 'redwood.send_to_group', 'text': { 'channel': channel, 'payload': payload, } } ) def save(self, *args, **kwargs): """ BUG: Django save-the-change, which all oTree models inherit from, doesn't recognize changes to JSONField properties. So saving the model won't trigger a database save. This is a hack, but fixes it so any JSONFields get updated every save. oTree uses a forked version of save-the-change so a good alternative might be to fix that to recognize JSONFields (diff them at save time, maybe?). """ super().save(*args, **kwargs) if self.pk is not None: update_fields = kwargs.get('update_fields') json_fields = {} for field in self._meta.get_fields(): if isinstance(field, JSONField) and (update_fields is None or field.attname in update_fields): json_fields[field.attname] = getattr(self, field.attname) self.__class__._default_manager.filter(pk=self.pk).update(**json_fields) @property def app_name(self): return self.session.config['name']
class Group(BaseGroup): '''Group is designed to be used instead of the oTree BaseGroup to provide Redwood-specific functions for coordinating inter-page communication for players in the Group. ''' class Meta(BaseGroup.Meta): def period_length(self): '''Implement this to set a timeout on the page in seconds. A period_start message will be sent on the state channel when all players in the group have connected their websockets. A period_end message will be send on the state channel period_length seconds from the period_start message. ''' pass def post_round_delay(self): '''Implement this to change the delay between when the period ends and the page is advanced. This delay should be provided in seconds. If :meth:`period_length` is not specified, this method does nothing. ''' pass def get_start_time(self): '''Returns a datetime.datetime object representing the time that this period started, or None if the period hasn't started yet. ''' pass def get_end_time(self): '''Returns a datetime.datetime object representing the time that this period ended. Returns None if :meth:`period_length` is not set, or if the period hasn't ended yet. ''' pass def when_all_players_ready(self): '''Implement this to perform an action for the group once all players are ready.''' pass def when_player_disconnects(self, player): '''Implement this to perform an action when a player disconnects.''' pass def _on_connect(self, participant): '''Called from the WebSocket consumer. Checks if all players in the group have connected; runs :meth:`when_all_players_ready` once all connections are established. ''' pass def _on_disconnect(self, participant): '''Trigger the :meth:`when_player_disconnects` callback.''' pass def send(self, channel, payload): '''Send a message with the given payload on the given channel. Messages are broadcast to all players in the group. ''' pass def save(self, *args, **kwargs): ''' BUG: Django save-the-change, which all oTree models inherit from, doesn't recognize changes to JSONField properties. So saving the model won't trigger a database save. This is a hack, but fixes it so any JSONFields get updated every save. oTree uses a forked version of save-the-change so a good alternative might be to fix that to recognize JSONFields (diff them at save time, maybe?). ''' pass @property def app_name(self): pass
14
11
10
0
6
3
2
0.57
1
6
3
1
11
0
11
11
134
15
76
25
62
43
61
24
48
5
1
3
22
145,300
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/models.py
otree_redwood.models.Connection
class Connection(models.Model): """Connections are created and deleted as Participants connect to a WebSocket.""" participant = models.ForeignKey( 'otree.Participant', related_name='+', null=True, on_delete=models.CASCADE) """Each Participant should have only one connection."""
class Connection(models.Model): '''Connections are created and deleted as Participants connect to a WebSocket.''' pass
1
1
0
0
0
0
0
0.33
1
0
0
0
0
0
0
0
9
1
6
2
5
2
2
2
1
0
1
0
0
145,301
Leeps-Lab/otree-redwood
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Leeps-Lab_otree-redwood/otree_redwood/views.py
otree_redwood.views.AppSpecificExportCSV.ExportCSV
class ExportCSV(vanilla.View): url_name = 'redwood_export_{}'.format(app_name) url_pattern = '^{}/$'.format(url_name) app_name = app_name display_name = display_name def get(request, *args, **kwargs): models_module = import_module('{}.models'.format(app_name)) groups = models_module.Group.objects.all() tables = [] for group in groups: events = Event.objects.filter( content_type=ContentType.objects.get_for_model(group), group_pk=group.pk) tables.append(get_output_table(list(events))) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{}"'.format( '{} Events (accessed {}).csv'.format( display_name, datetime.date.today().isoformat() ) ) w = csv.writer(response) w.writerow(get_output_table_header(list(groups))) for rows in tables: w.writerows(rows) return response
class ExportCSV(vanilla.View): def get(request, *args, **kwargs): pass
2
0
26
5
21
0
3
0
1
3
1
0
1
0
1
1
33
7
26
13
24
0
19
13
17
3
1
1
3
145,302
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/models.py
otree_redwood.models.DecisionGroup
class DecisionGroup(Group): """DecisionGroup receives Events on the ``decisions`` channel, then broadcasts them back to all members of the group on the ``group_decisions`` channel. """ class Meta(Group.Meta): abstract = True group_decisions = JSONField(null=True) """:attr:`group_decisions` holds a map from participant code to their current decision.""" subperiod_group_decisions = JSONField(null=True) """:attr:`subperiod_group_decisions` is a copy of the state of :attr:`group_decisions` at the end of each subperiod.""" _group_decisions_updated = models.BooleanField(default=False) """:attr:`_group_decisions_updated` is a private field used with rate limiting to determine whether group decisions need to be resent.""" def get_group_decisions_events(self): """Returns a list of all Event objects sent on the ``group_decisions`` channel so far, ordered by timestamp. If the period has ended, this gives the complete decision history of this DecisionGroup in this period. """ return list(self.events.filter(channel='group_decisions')) def num_subperiods(self): """Override to turn on sub-period behavior. None by default.""" return None def rate_limit(self): """Override to turn on rate-limiting behavior. If used, the return value of rate_limit determines the minimum time between broadcasted ::attr::`group_decisions` updates.""" return None def when_all_players_ready(self): """Initializes decisions based on ``player.initial_decision()``. If :attr:`num_subperiods` is set, starts a timed task to run the sub-periods. """ self.group_decisions = {} self.subperiod_group_decisions = {} for player in self.get_players(): self.group_decisions[player.participant.code] = player.initial_decision() self.subperiod_group_decisions[player.participant.code] = player.initial_decision() if self.num_subperiods(): emitter = DiscreteEventEmitter( self.period_length() / self.num_subperiods(), self.period_length(), self, self._subperiod_tick) emitter.start() elif self.rate_limit(): def _tick(current_interval, intervals): self.refresh_from_db() if self._group_decisions_updated: self.send('group_decisions', self.group_decisions) self._group_decisions_updated = False self.save(update_fields=['_group_decisions_updated']) update_period = self.rate_limit() emitter = DiscreteEventEmitter( update_period, self.period_length(), self, _tick) emitter.start() self.save() def _subperiod_tick(self, current_interval, intervals): """Tick each sub-period, copying group_decisions to subperiod_group_decisions.""" self.refresh_from_db() for key, value in self.group_decisions.items(): self.subperiod_group_decisions[key] = value self.send('group_decisions', self.subperiod_group_decisions) self.save(update_fields=['subperiod_group_decisions']) def _on_decisions_event(self, event=None, **kwargs): """Called when an Event is received on the decisions channel. Saves the value in group_decisions. If num_subperiods is None, immediately broadcasts the event back out on the group_decisions channel. """ if not self.ran_ready_function: logger.warning('ignoring decision from {} before when_all_players_ready: {}'.format(event.participant.code, event.value)) return with track('_on_decisions_event'): self.group_decisions[event.participant.code] = event.value self._group_decisions_updated = True self.save(update_fields=['group_decisions', '_group_decisions_updated']) if not self.num_subperiods() and not self.rate_limit(): self.send('group_decisions', self.group_decisions)
class DecisionGroup(Group): '''DecisionGroup receives Events on the ``decisions`` channel, then broadcasts them back to all members of the group on the ``group_decisions`` channel. ''' class Meta(Group.Meta): def get_group_decisions_events(self): '''Returns a list of all Event objects sent on the ``group_decisions`` channel so far, ordered by timestamp. If the period has ended, this gives the complete decision history of this DecisionGroup in this period. ''' pass def num_subperiods(self): '''Override to turn on sub-period behavior. None by default.''' pass def rate_limit(self): '''Override to turn on rate-limiting behavior. If used, the return value of rate_limit determines the minimum time between broadcasted ::attr::`group_decisions` updates.''' pass def when_all_players_ready(self): '''Initializes decisions based on ``player.initial_decision()``. If :attr:`num_subperiods` is set, starts a timed task to run the sub-periods. ''' pass def _tick(current_interval, intervals): pass def _subperiod_tick(self, current_interval, intervals): '''Tick each sub-period, copying group_decisions to subperiod_group_decisions.''' pass def _on_decisions_event(self, event=None, **kwargs): '''Called when an Event is received on the decisions channel. Saves the value in group_decisions. If num_subperiods is None, immediately broadcasts the event back out on the group_decisions channel. ''' pass
9
7
10
0
8
2
2
0.45
1
3
2
0
6
0
6
17
90
9
56
17
47
25
47
17
38
4
2
2
14
145,303
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/models.py
otree_redwood.models.Event
class Event(models.Model): """Event stores a single message going in or out across a WebSocket connection.""" class Meta: # Default to queries returning most recent Event first. ordering = ['timestamp'] timestamp = models.DateTimeField(null=False) """Time the event was received or sent by the server.""" content_type = models.ForeignKey(ContentType, related_name='content_type_events', on_delete=models.CASCADE) """Used to relate this Event to an arbitrary Group.""" group_pk = models.PositiveIntegerField() """Primary key of the Event's related Group.""" group = GenericForeignKey('content_type', 'group_pk') """The Group the event was sent to/from.""" channel = models.CharField(max_length=100, null=False) """Channels act as tags to route Events.""" participant = models.ForeignKey( 'otree.Participant', related_name='+', null=True, on_delete=models.CASCADE) """The Participant who sent the event - null for server-sent events.""" value = JSONField() """Arbitrary Event payload.""" @property def message(self): """Dictionary representation of the Event appropriate for JSON-encoding.""" return { 'timestamp': time.mktime(self.timestamp.timetuple())*1e3 + self.timestamp.microsecond/1e3, 'group': self.group_pk, 'participant': None if not self.participant else self.participant.code, 'channel': self.channel, 'value': self.value } def save(self, *args, **kwargs): """Saving an Event automatically sets the timestamp if not already set.""" if self.timestamp is None: self.timestamp = timezone.now() super().save(*args, **kwargs)
class Event(models.Model): '''Event stores a single message going in or out across a WebSocket connection.''' class Meta: @property def message(self): '''Dictionary representation of the Event appropriate for JSON-encoding.''' pass def save(self, *args, **kwargs): '''Saving an Event automatically sets the timestamp if not already set.''' pass
5
3
8
1
6
1
2
0.41
1
1
0
0
2
0
2
2
43
5
27
13
22
11
16
12
12
2
1
1
4
145,304
Leeps-Lab/otree-redwood
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Leeps-Lab_otree-redwood/otree_redwood/models.py
otree_redwood.models.DecisionGroup.Meta
class Meta(Group.Meta): abstract = True
class Meta(Group.Meta): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
2
0
0
145,305
Leeps-Lab/otree-redwood
Leeps-Lab_otree-redwood/otree_redwood/views.py
otree_redwood.views.EventsJsonAPI
class EventsJsonAPI(vanilla.ListView): url_name = 'redwood_events_json_api' url_pattern = r'^redwood/api/events/session/(?P<session_code>[a-zA-Z0-9_-]+)/$' model = Event def render_to_response(self, context): session = Session.objects.get(code=self.kwargs['session_code']) events_by_app_name_then_group = defaultdict(lambda: {}) for session_config in SESSION_CONFIGS_DICT.values(): app_name = session_config['name'] try: groups_query = getattr(session, app_name + '_group') except AttributeError: continue groups = list(groups_query.all()) if groups: for group in groups: events = Event.objects.filter(group_pk=group.pk) events_by_app_name_then_group[app_name][group.pk] = [e.message for e in events] return JsonResponse(events_by_app_name_then_group, safe=False)
class EventsJsonAPI(vanilla.ListView): def render_to_response(self, context): pass
2
0
15
0
15
0
5
0
1
3
1
0
1
0
1
1
21
2
19
13
17
0
19
13
17
5
1
3
5
145,306
LegoStormtroopr/django-spaghetti-and-meatballs
LegoStormtroopr_django-spaghetti-and-meatballs/django_spaghetti/views.py
django_spaghetti.views.Plate
class Plate(TemplateView): """ This class-based-view serves up spaghetti and meatballs. Override the following class properties when calling `as_view`: * `settings` - sets a view specific to use instead of the `SPAGHETTI_SAUCE` django settings * `override_settings` - overrides specified settings from `SPAGHETTI_SAUCE` django settings * `plate_template_name` - overrides the template name for the whole view * `meatball_template_name` - overrides the template used to render nodes For example the below URL pattern would specify a path to a view that displayed models from the `auth` app with the given templates:: url(r'^user_graph/$', Plate.as_view( settings = { 'apps': ['auth'], } meatball_template_name = "my_app/user_node.html", plate_template_name = "my_app/auth_details.html" ) """ settings = None override_settings = {} plate_template_name = 'django_spaghetti/plate.html' meatball_template_name = "django_spaghetti/meatball.html" def get(self, request): return self.plate() def get_view_settings(self): if self.settings is None: graph_settings = deepcopy(getattr(settings, 'SPAGHETTI_SAUCE', {})) graph_settings.update(self.override_settings) else: graph_settings = self.settings return graph_settings def get_apps_list(self): return self.get_view_settings().get('apps', []) def get_excluded_models(self): return [ "%s__%s" % (app, model) for app, models in self.get_view_settings().get('exclude', {}).items() for model in models ] def get_models(self): apps_list = self.get_apps_list() excludes = self.get_excluded_models() models = apps.get_models() _models = [] for model in models: if (model is None): continue app_label = model._meta.app_label model_name = model._meta.model_name if app_label not in apps_list: continue model.is_proxy = model._meta.proxy if (model.is_proxy and not self.get_view_settings().get('show_proxy', False)): continue _id = "%s__%s" % (app_label, model_name) if _id in excludes: continue _models.append(model) return _models def get_group(self, model): return model._meta.app_label def get_colours(self): return ['red', 'blue', 'green', 'yellow', 'orange'] def get_groups(self): colours = self.get_colours() groups = {} for app, colour in zip(sorted(self.get_apps_list()), colours): app_info = apps.get_app_config(app) groups.update({ app: { "color": { 'background': colour, 'border': 'gray' }, "data": { 'name': str(app_info.verbose_name) } } }) return groups def include_link_to_field(self, model, field): return True def generate_edge_style(self, model, field): edge_style = {} if str(field.name).endswith('_ptr'): # fields that end in _ptr are pointing to a parent object edge_style.update({ 'arrows': {'to': {'scaleFactor': 0.75}}, # needed to draw from-to 'font': {'align': 'middle'}, 'label': 'is a', 'dashes': True }) elif isinstance(field, related.ForeignKey): edge_style.update({ 'arrows': {'to': {'scaleFactor': 0.75}} }) elif isinstance(field, related.OneToOneField): edge_style.update({ 'font': {'align': 'middle'}, 'label': '|' }) elif isinstance(field, related.ManyToManyField): edge_style.update({ 'color': {'color': 'gray'}, 'arrows': {'to': {'scaleFactor': 1}, 'from': {'scaleFactor': 1}}, }) return edge_style def get_fields_for_model(self, model): fields = [f for f in model._meta.fields] many = [f for f in model._meta.many_to_many] return fields + many def get_link_fields_for_model(self, model): return [ f for f in self.get_fields_for_model(model) if f.remote_field is not None and self.include_link_to_field(model, f) ] def get_edge_data(self, field): return { 'from_model': str(field.model._meta.verbose_name.title()), 'to_model': str(field.remote_field.model._meta.verbose_name.title()), 'help_text': str(field.help_text), # 'many_to_many': field.many_to_many, # 'one_to_one': field.one_to_one, } def get_id_for_model(self, model): app_label = model._meta.app_label model_name = model._meta.model_name return "%s__%s" % (app_label, model_name) def get_model_display_information(self, model): return model.__doc__ def plate(self): """ Serves up a delicious plate with your models """ request = self.request graph_settings = self.get_view_settings() excludes = self.get_excluded_models() nodes = [] edges = [] for model in self.get_models(): app_label = model._meta.app_label model_name = model._meta.model_name model.doc = self.get_model_display_information(model) _id = self.get_id_for_model(model) label = self.get_node_label(model) node_fields = self.get_fields_for_model(model) if graph_settings.get('show_fields', True): label += "\n%s\n" % ("-" * len(model_name)) label += "\n".join([str(f.name) for f in node_fields]) edge_color = {'inherit': 'from'} for f in self.get_link_fields_for_model(model): m = f.remote_field.model to_id = self.get_id_for_model(f.remote_field.model) if to_id in excludes: pass elif _id == to_id and graph_settings.get('ignore_self_referential', False): pass else: if m._meta.app_label != app_label: edge_color = {'inherit': 'both'} edge = { 'from': _id, 'to': to_id, 'color': edge_color, 'title': f.verbose_name.title(), 'data': self.get_edge_data(f) } edge.update(self.generate_edge_style(model, f)) edges.append(edge) if model.is_proxy: proxy = model._meta.proxy_for_model._meta model.proxy = proxy edge = { 'to': _id, 'from': "%s__%s" % (proxy.app_label, proxy.model_name), 'color': edge_color, } edges.append(edge) nodes.append( { 'id': _id, 'label': label, 'shape': 'box', 'group': self.get_group(model), 'title': get_template(self.meatball_template_name).render( {'model': model, 'model_meta': model._meta, 'fields': node_fields} ), 'data': self.get_extra_node_data(model) } ) context = self.get_context_data() context.update({ 'meatballs': json.dumps(nodes), 'spaghetti': json.dumps(edges), 'groups': json.dumps(self.get_groups()), "pyobj": { 'meatballs': nodes, 'spaghetti': edges, 'groups': self.get_groups(), } }) return render(request, self.plate_template_name, context) def get_extra_node_data(self, model): return {} def get_node_label(self, model): """ Defines how labels are constructed from models. Default - uses verbose name, lines breaks where sensible """ if model.is_proxy: label = "(P) %s" % (model._meta.verbose_name.title()) else: label = "%s" % (model._meta.verbose_name.title()) line = "" new_label = [] for w in label.split(" "): if len(line + w) > 15: new_label.append(line) line = w else: line += " " line += w new_label.append(line) return "\n".join(new_label)
class Plate(TemplateView): ''' This class-based-view serves up spaghetti and meatballs. Override the following class properties when calling `as_view`: * `settings` - sets a view specific to use instead of the `SPAGHETTI_SAUCE` django settings * `override_settings` - overrides specified settings from `SPAGHETTI_SAUCE` django settings * `plate_template_name` - overrides the template name for the whole view * `meatball_template_name` - overrides the template used to render nodes For example the below URL pattern would specify a path to a view that displayed models from the `auth` app with the given templates:: url(r'^user_graph/$', Plate.as_view( settings = { 'apps': ['auth'], } meatball_template_name = "my_app/user_node.html", plate_template_name = "my_app/auth_details.html" ) ''' def get(self, request): pass def get_view_settings(self): pass def get_apps_list(self): pass def get_excluded_models(self): pass def get_models(self): pass def get_group(self, model): pass def get_colours(self): pass def get_groups(self): pass def include_link_to_field(self, model, field): pass def generate_edge_style(self, model, field): pass def get_fields_for_model(self, model): pass def get_link_fields_for_model(self, model): pass def get_edge_data(self, field): pass def get_id_for_model(self, model): pass def get_model_display_information(self, model): pass def plate(self): ''' Serves up a delicious plate with your models ''' pass def get_extra_node_data(self, model): pass def get_node_label(self, model): ''' Defines how labels are constructed from models. Default - uses verbose name, lines breaks where sensible ''' pass
19
3
12
1
11
1
2
0.15
1
2
0
0
18
0
18
18
268
42
198
63
179
29
125
62
106
8
1
4
39
145,307
LegoStormtroopr/django-spaghetti-and-meatballs
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LegoStormtroopr_django-spaghetti-and-meatballs/django_spaghetti/tests/models.py
django_spaghetti.tests.models.Precinct.Meta
class Meta: unique_together = ("burrough", "number")
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
145,308
LegoStormtroopr/django-spaghetti-and-meatballs
LegoStormtroopr_django-spaghetti-and-meatballs/django_spaghetti/tests/test_it.py
django_spaghetti.tests.test_it.LoadThePlate
class LoadThePlate(TestCase): def test_plate(self): response = self.client.get("/plate") self.assertEqual(response.status_code, 200) self.assertContains(response, 'Officer') self.assertContains(response, 'All arrests made by the officer') def test_plate_with_settings(self): response = self.client.get("/test/plate_settings") self.assertEqual(response.status_code, 200) self.assertNotContains(response, 'Officer') def test_plate_show_m2m_field_detail(self): response = self.client.get("/test/plate_show_m2m_field_detail") self.assertEqual(response.status_code, 200) self.assertContains(response, 'Officer') self.assertContains(response, 'All arrests made by the officer') def test_plate_with_override_settings(self): response = self.client.get("/test/plate_override") self.assertEqual(response.status_code, 200) self.assertTrue('policeofficer' in str(response.content).lower()) self.assertTrue('policestation' not in str(response.content).lower()) def test_no_override_after_override(self): response1 = self.client.get("/test/plate_override") response2 = self.client.get("/plate") self.assertEqual(response1.status_code, 200) self.assertEqual(response2.status_code, 200) self.assertContains(response1, 'policeofficer') self.assertNotContains(response1, 'policestation') def test_meatball(self): response = self.client.get("/test/plate_show_m2m_field_detail") resp_str = str(response.content) self.assertEqual(response.status_code, 200) self.assertTrue('IntegerField' in resp_str) self.assertTrue('CharField' in resp_str) self.assertTrue('ManyToManyField' in resp_str) self.assertTrue('ForeignKey' in resp_str) self.assertTrue('OneToOneField' in resp_str) self.assertTrue('DateField' in resp_str) self.assertTrue('URLField' not in resp_str)
class LoadThePlate(TestCase): def test_plate(self): pass def test_plate_with_settings(self): pass def test_plate_show_m2m_field_detail(self): pass def test_plate_with_override_settings(self): pass def test_no_override_after_override(self): pass def test_meatball(self): pass
7
0
6
0
6
0
1
0
1
1
0
0
6
0
6
6
43
5
38
15
31
0
38
15
31
1
1
0
6
145,309
LegoStormtroopr/django-spaghetti-and-meatballs
LegoStormtroopr_django-spaghetti-and-meatballs/django_spaghetti/tests/models.py
django_spaghetti.tests.models.PoliceStation
class PoliceStation(models.Model): officers = models.ForeignKey("PoliceOfficer", on_delete=models.CASCADE)
class PoliceStation(models.Model): pass
1
0
0
0
0
0
0
0
1
0
0
2
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
145,310
LegoStormtroopr/django-spaghetti-and-meatballs
LegoStormtroopr_django-spaghetti-and-meatballs/django_spaghetti/tests/models.py
django_spaghetti.tests.models.Arrest
class Arrest(models.Model): alleged_crime = models.CharField(max_length=20) perp = models.ForeignKey("Perpetrator", on_delete=models.CASCADE) arrest_date = models.DateField() processing_date = models.DateField()
class Arrest(models.Model): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
5
0
5
5
4
0
5
5
4
0
1
0
0
145,311
LegoStormtroopr/django-spaghetti-and-meatballs
LegoStormtroopr_django-spaghetti-and-meatballs/django_spaghetti/tests/models.py
django_spaghetti.tests.models.Perpetrator
class Perpetrator(models.Model): """ A person who is accused of a crime. E.g. Doug Judy, aka. "The Pontiac Bandit" """ first_name = models.CharField(max_length=200) surname = models.CharField(max_length=200) alias = models.CharField(max_length=200)
class Perpetrator(models.Model): ''' A person who is accused of a crime. E.g. Doug Judy, aka. "The Pontiac Bandit" ''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
0
8
0
4
4
3
4
4
4
3
0
1
0
0
145,312
LegoStormtroopr/django-spaghetti-and-meatballs
LegoStormtroopr_django-spaghetti-and-meatballs/django_spaghetti/tests/models.py
django_spaghetti.tests.models.PoliceOfficer
class PoliceOfficer(models.Model): """ An officer of the NYPD. E.g. "Jake Peralta" """ badge_number = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=200) surname = models.CharField(max_length=200) rank = models.CharField(max_length=200) arrests = models.ManyToManyField( "Arrest", related_name="arresting_officers", help_text='All arrests made by the officer' )
class PoliceOfficer(models.Model): ''' An officer of the NYPD. E.g. "Jake Peralta" ''' pass
1
1
0
0
0
0
0
0.4
1
0
0
0
0
0
0
0
14
0
10
6
9
4
6
6
5
0
1
0
0
145,313
LegoStormtroopr/django-spaghetti-and-meatballs
LegoStormtroopr_django-spaghetti-and-meatballs/django_spaghetti/tests/models.py
django_spaghetti.tests.models.Precinct
class Precinct(PoliceStation): """ A precinct of officers E.g. "Brookyln 99" """ number = models.IntegerField(primary_key=True) burrough = models.CharField(max_length=20) captain = models.OneToOneField(PoliceOfficer, on_delete=models.CASCADE) class Meta: unique_together = ("burrough", "number") def natural_key(self): return (self.burrough, self.number)
class Precinct(PoliceStation): ''' A precinct of officers E.g. "Brookyln 99" ''' class Meta: def natural_key(self): pass
3
1
2
0
2
0
1
0.5
1
0
0
0
1
0
1
1
14
2
8
7
5
4
8
7
5
1
2
0
1
145,314
LegoStormtroopr/django-spaghetti-and-meatballs
LegoStormtroopr_django-spaghetti-and-meatballs/django_spaghetti/tests/models.py
django_spaghetti.tests.models.Division
class Division(PoliceStation): """ A division of officers, not in the field. E.g. Major Crimes Unit """ name = models.CharField(max_length=200)
class Division(PoliceStation): ''' A division of officers, not in the field. E.g. Major Crimes Unit ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
0
6
0
2
2
1
4
2
2
1
0
2
0
0
145,315
Legobot/Legobot
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Legobot_Legobot/Legobot/Lego.py
Legobot.Lego.Lego.HandlerThread
class HandlerThread(threading.Thread): """This class provides a simple thread for running message handlers. It is used to ensure that message handlers do not block other Legos from running by simply taking too long to execute. """ def __init__(self, handler, message): threading.Thread.__init__(self) self.handler = handler self.message = message def run(self): self.handler(self.message)
class HandlerThread(threading.Thread): '''This class provides a simple thread for running message handlers. It is used to ensure that message handlers do not block other Legos from running by simply taking too long to execute. ''' def __init__(self, handler, message): pass def run(self): pass
3
1
3
0
3
0
1
0.57
1
0
0
0
2
2
2
27
14
3
7
5
4
4
7
5
4
1
1
0
2
145,316
Legobot/Legobot
Legobot_Legobot/Test/test_IRC.py
test_IRC.TestIRC
class TestIRC(unittest.TestCase): @staticmethod def test_initialization(): baseplate = Lego.start(None, threading.Lock()) baseplate_proxy = baseplate.proxy() baseplate_proxy.add_child(IRC, # nosec channels=['#foo'], nickname='test_nick', server='foo.testing', port=6667, use_ssl=False, username='test_username', password='test_password') # Cleanup children = baseplate_proxy.children.get() for child in children: child.stop() baseplate.stop()
class TestIRC(unittest.TestCase): @staticmethod def test_initialization(): pass
3
0
16
0
15
3
2
0.18
1
2
2
0
0
0
1
73
18
0
17
7
14
3
9
6
7
2
2
1
2
145,317
Legobot/Legobot
Legobot_Legobot/Test/test_Lego.py
test_Lego.TestHandlerThread
class TestHandlerThread(unittest.TestCase): @staticmethod def test_initialization(): lego = Lego(None, threading.Lock()) message = Message('Test Message', Metadata(lego)) thread = Lego.HandlerThread(lego.handle, message) assert thread.handler == lego.handle # nosec assert thread.message == message
class TestHandlerThread(unittest.TestCase): @staticmethod def test_initialization(): pass
3
0
6
0
6
2
1
0.25
1
4
4
0
0
0
1
73
8
0
8
6
5
2
7
5
5
1
2
0
1
145,318
Legobot/Legobot
Legobot_Legobot/Test/test_Message.py
test_Message.TestMetadata
class TestMetadata(unittest.TestCase): @staticmethod def test_default_init_values(): source = Lego(None, threading.Lock()) metadata = Metadata(source) assert(metadata.dest is None) # nosec @staticmethod def test_initialization(): source = Lego(None, threading.Lock()) dest = Lego(None, threading.Lock()) metadata = Metadata(source, dest) assert(metadata.source == source) # nosec assert(metadata.dest == dest)
class TestMetadata(unittest.TestCase): @staticmethod def test_default_init_values(): pass @staticmethod def test_initialization(): pass
5
0
5
0
5
2
1
0.23
1
2
2
0
0
0
2
74
14
1
13
10
8
3
11
8
8
1
2
0
2
145,319
Legobot/Legobot
Legobot_Legobot/Test/test_Message.py
test_Message.TestMessage
class TestMessage(unittest.TestCase): @staticmethod def test_initialization(): source = Lego(None, threading.Lock()) metadata = Metadata(source) message = Message('a message', metadata) assert(message.text == 'a message') # nosec assert(message.metadata == metadata) # nosec message = Message('a message', metadata, True) assert(message.text == 'a message') # nosec assert(message.metadata == metadata) # nosec assert(message.should_log) # nosec @staticmethod def test_default_init_values(): source = Lego(None, threading.Lock()) metadata = Metadata(source) message = Message('a message', metadata) assert(not message.should_log)
class TestMessage(unittest.TestCase): @staticmethod def test_initialization(): pass @staticmethod def test_default_init_values(): pass
5
0
8
0
8
3
1
0.33
1
3
3
0
0
0
2
74
19
1
18
11
13
6
16
9
13
1
2
0
2
145,320
Legobot/Legobot
Legobot_Legobot/Legobot/Chatbot.py
Legobot.Chatbot.Chatbot
class Chatbot(object): def __init__(self, config_path=None): self.schema = load_yaml_file( DIR.joinpath('chatbot_schema.yaml'), raise_ex=True) self.config = self.load_config(config_path) self.logger = build_logger( self.config.get('log_file'), self.config.get('log_level')) self.baseplate = None self.baseplate_proxy = None self.connectors = [] self.legos = [] def load_config(self, config_path): config = load_yaml_file(config_path, raise_ex=True) config = replace_vars(config) validate(config, self.schema) return config def initialize_baseplate(self): lock = threading.Lock() self.baseplate = Lego.start(None, lock) self.baseplate_proxy = self.baseplate.proxy() def add_lego(self, name, config, lego_type): if config['enabled'] is True: try: self.baseplate_proxy.add_child( locate(config['path']), **config.get('kwargs', {})) if lego_type == 'connectors': self.connectors.append(name) elif lego_type == 'legos': self.legos.append(name) except Exception as e: self.logger.error(f'Error adding {name} to {lego_type}: {e}') def run(self): if not self.baseplate: self.initialize_baseplate() if self.config['helpEnabled'] is True: self.add_lego( 'Help', {'enabled': True, 'path': HELP_PATH}, 'legos') for connector, config in self.config['connectors'].items(): self.add_lego(connector, config, 'connectors') for lego, config in self.config['legos'].items(): self.add_lego(lego, config, 'legos') def stop(self): self.baseplate.stop() self.baseplate_proxy = None self.baseplate = None
class Chatbot(object): def __init__(self, config_path=None): pass def load_config(self, config_path): pass def initialize_baseplate(self): pass def add_lego(self, name, config, lego_type): pass def run(self): pass def stop(self): pass
7
0
8
1
7
0
2
0
1
2
1
0
6
7
6
6
55
10
45
19
38
0
40
18
33
5
1
3
14
145,321
Legobot/Legobot
Legobot_Legobot/Legobot/Connectors/Discord.py
Legobot.Connectors.Discord.DiscoBot
class DiscoBot(threading.Thread, object): """Relays messages between Discord and the Legobot baseplate. Uses the REST API and Websockets. No plans to use async. Attibutes: actor_urn: URN (unique ID) of actor that initialized the bot baseplate: Parent lego/actor headers: HTTP headers use for calls to Discord REST endpoints rest_baseurl: Base URL to the REST API token: Discord bot token ws: Websocket connected to Discord """ def __init__(self, baseplate, token, actor_urn, *args, **kwargs): """Initialize DiscoBot Args: baseplate (Legobot.Lego): The parent Pykka actor. Typically passed in from Legobot.Connectors.Discord.Discord token (string): Discord bot token actor_urn (string): URN of Pykka actor launching DiscoBot *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. """ self.baseplate = baseplate self.rest_baseurl = 'https://discordapp.com/api/v6' self.token = token self.headers = {"Authorization": "Bot {}".format(token), "User-Agent": "Legobot", "Content-Type": "application/json"} self.actor_urn = actor_urn self.ws = None threading.Thread.__init__(self) def connect(self): return create_connection(self.get_ws_url()) def create_message(self, channel_id, text): """Sends a message to a Discord channel or user via REST API Args: channel_id (string): ID of destingation Discord channel text (string): Content of message """ baseurl = self.rest_baseurl + \ '/channels/{}/messages'.format(channel_id) requests.post(baseurl, headers=self.headers, data=json.dumps({'content': text})) def identify(self, token): """Identifies to the websocket endpoint Args: token (string): Discord bot token """ payload = { 'op': 2, 'd': { 'token': self.token, 'properties': { '$os': sys.platform, '$browser': 'legobot', '$device': 'legobot' }, 'compress': False, 'large_threshold': 250 } } payload['d']['synced_guilds'] = [] logger.info("Identifying with the following message: \ {}".format(payload)) self.ws.send(json.dumps(payload)) return def on_hello(self, message): """Runs on a hello event from websocket connection Args: message (dict): Full message from Discord websocket connection" """ logger.info("Got a hello") self.identify(self.token) self.heartbeat_thread = Heartbeat(self.ws, message['d']['heartbeat_interval']) self.heartbeat_thread.start() return def on_heartbeat(self, message): """Runs on a heartbeat event from websocket connection Args: message (dict): Full message from Discord websocket connection" """ logger.info("Got a heartbeat") logger.info("Heartbeat message: {}".format(message)) self.heartbeat_thread.update_sequence(message['d']) return def on_message(self, message): """Runs on a create_message event from websocket connection Args: message (dict): Full message from Discord websocket connection" """ if 'content' in message['d']: metadata = self._parse_metadata(message) message = Message(text=message['d']['content'], metadata=metadata).__dict__ logger.debug(message) self.baseplate.tell(message) def _parse_metadata(self, message): """Sets metadata in Legobot message Args: message (dict): Full message from Discord websocket connection" Returns: Legobot.Metadata """ metadata = Metadata(source=self.actor_urn).__dict__ if 'author' in message['d']: metadata['source_user'] = message['d']['author']['username'] else: metadata['source_user'] = None if 'channel_id' in message['d']: metadata['source_channel'] = message['d']['channel_id'] metadata['channel_display_name'] = message['d']['channel_id'] else: metadata['source_channel'] = None metadata['user_id'] = metadata['source_user'] metadata['display_name'] = metadata['source_user'] metadata['source_connector'] = 'discord' return metadata @staticmethod def get_ws_url(): url = requests.get( 'https://discordapp.com/api/v6/gateway').json()['url'] return url + '?v=6&encoding=json' def handle(self, message): """Dispatches messages to appropriate handler based on opcode Args: message (dict): Full message from Discord websocket connection """ opcode = message['op'] if opcode == 10: self.on_hello(message) elif opcode == 11: self.on_heartbeat(message) elif opcode == 0: self.on_message(message) else: logger.debug("Not a message we handle: OPCODE {}".format(opcode)) return def run(self): """Overrides run method of threading.Thread. Called by DiscoBot.start(), inherited from threading.Thread """ self.ws = self.connect() while True: try: data = json.loads(self.ws.recv()) self.handle(data) except json.decoder.JSONDecodeError: logger.fatal("No data on socket...")
class DiscoBot(threading.Thread, object): '''Relays messages between Discord and the Legobot baseplate. Uses the REST API and Websockets. No plans to use async. Attibutes: actor_urn: URN (unique ID) of actor that initialized the bot baseplate: Parent lego/actor headers: HTTP headers use for calls to Discord REST endpoints rest_baseurl: Base URL to the REST API token: Discord bot token ws: Websocket connected to Discord ''' def __init__(self, baseplate, token, actor_urn, *args, **kwargs): '''Initialize DiscoBot Args: baseplate (Legobot.Lego): The parent Pykka actor. Typically passed in from Legobot.Connectors.Discord.Discord token (string): Discord bot token actor_urn (string): URN of Pykka actor launching DiscoBot *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. ''' pass def connect(self): pass def create_message(self, channel_id, text): '''Sends a message to a Discord channel or user via REST API Args: channel_id (string): ID of destingation Discord channel text (string): Content of message ''' pass def identify(self, token): '''Identifies to the websocket endpoint Args: token (string): Discord bot token ''' pass def on_hello(self, message): '''Runs on a hello event from websocket connection Args: message (dict): Full message from Discord websocket connection" ''' pass def on_heartbeat(self, message): '''Runs on a heartbeat event from websocket connection Args: message (dict): Full message from Discord websocket connection" ''' pass def on_message(self, message): '''Runs on a create_message event from websocket connection Args: message (dict): Full message from Discord websocket connection" ''' pass def _parse_metadata(self, message): '''Sets metadata in Legobot message Args: message (dict): Full message from Discord websocket connection" Returns: Legobot.Metadata ''' pass @staticmethod def get_ws_url(): pass def handle(self, message): '''Dispatches messages to appropriate handler based on opcode Args: message (dict): Full message from Discord websocket connection ''' pass def run(self): '''Overrides run method of threading.Thread. Called by DiscoBot.start(), inherited from threading.Thread ''' pass
13
10
14
2
9
4
2
0.55
2
3
3
0
10
7
11
36
183
34
96
27
83
53
69
26
57
4
1
2
19
145,322
Legobot/Legobot
Legobot_Legobot/Legobot/Connectors/Discord.py
Legobot.Connectors.Discord.Discord
class Discord(Lego): """Lego that builds and connects Legobot.Connectors.Discord.DiscoBot Args: baseplate (Legobot.Lego): baseplate/parent lego (Pykka Actor) lock (threading.Lock: thread lock created in your bot script. All legos should share the same lock. *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. """ def __init__(self, baseplate, lock, *args, **kwargs): super().__init__(baseplate, lock) self.botThread = DiscoBot(baseplate, actor_urn=self.actor_urn, *args, **kwargs) def on_start(self): """Extends pykka's on_start method to launch this as an actor """ self.botThread.start() def listening_for(self, message): """Describe what this should listen for (hint: everything not from ourself) Extends Legobot.Lego.listening_for() Args: message (Legobot.Message): Message to handle Returns: bool: True if lego is interested in the message. """ return str(self.actor_urn) != str(message['metadata']['source']) def handle(self, message): """Attempts to send a message to the specified destination in Discord. Extends Legobot.Lego.handle() Args: message (Legobot.Message): message w/ metadata to send. """ logger.debug(message) if Utilities.isNotEmpty(message['metadata']['opts']): target = message['metadata']['opts']['target'] self.botThread.create_message(target, message['text']) @staticmethod def get_name(): """Called by built-in !help lego Returns name of Lego. Returns None because this is a non-interactive Lego """ return None
class Discord(Lego): '''Lego that builds and connects Legobot.Connectors.Discord.DiscoBot Args: baseplate (Legobot.Lego): baseplate/parent lego (Pykka Actor) lock (threading.Lock: thread lock created in your bot script. All legos should share the same lock. *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. ''' def __init__(self, baseplate, lock, *args, **kwargs): pass def on_start(self): '''Extends pykka's on_start method to launch this as an actor ''' pass def listening_for(self, message): '''Describe what this should listen for (hint: everything not from ourself) Extends Legobot.Lego.listening_for() Args: message (Legobot.Message): Message to handle Returns: bool: True if lego is interested in the message. ''' pass def handle(self, message): '''Attempts to send a message to the specified destination in Discord. Extends Legobot.Lego.handle() Args: message (Legobot.Message): message w/ metadata to send. ''' pass @staticmethod def get_name(): '''Called by built-in !help lego Returns name of Lego. Returns None because this is a non-interactive Lego ''' pass
7
5
9
2
3
4
1
1.59
1
4
2
0
4
1
5
20
61
17
17
9
10
27
15
8
9
2
2
1
6
145,323
Legobot/Legobot
Legobot_Legobot/Legobot/Connectors/Discord.py
Legobot.Connectors.Discord.Heartbeat
class Heartbeat(threading.Thread, object): """Manage heartbeat connection to Discord Attributes: ws: Websocket connection to Discord interval (float): time between heartbeat pings to the server """ def __init__(self, ws, interval): self.ws = ws self.interval = float(interval) / 1000.0 self.sequence = 0 logger.debug("Heartbeat handler initialized \ with interval of {}".format(self.interval)) threading.Thread.__init__(self) def send(self, ws, seq): """Sends heartbeat message to Discord Attributes: ws: Websocket connection to discord seq: Sequence number of heartbeat """ payload = {'op': 1, 'd': seq} payload = json.dumps(payload) logger.debug("Sending heartbeat with payload {}".format(payload)) ws.send(payload) return def update_sequence(self, seq): """Updates the heartbeat sequence Attributes: seq (int): Sequence number of heartbeat """ self.sequence = seq logger.debug("Heartbeat sequence updated to {}".format(self.sequence)) return def run(self): while True: self.send(self.ws, self.sequence) time.sleep(self.interval)
class Heartbeat(threading.Thread, object): '''Manage heartbeat connection to Discord Attributes: ws: Websocket connection to Discord interval (float): time between heartbeat pings to the server ''' def __init__(self, ws, interval): pass def send(self, ws, seq): '''Sends heartbeat message to Discord Attributes: ws: Websocket connection to discord seq: Sequence number of heartbeat ''' pass def update_sequence(self, seq): '''Updates the heartbeat sequence Attributes: seq (int): Sequence number of heartbeat ''' pass def run(self): pass
5
3
9
1
5
2
1
0.64
2
1
0
0
4
3
4
29
46
10
22
9
17
14
21
9
16
2
1
1
5
145,324
Legobot/Legobot
Legobot_Legobot/Legobot/Connectors/IRC.py
Legobot.Connectors.IRC.IRC
class IRC(Lego): def __init__(self, baseplate, lock, *args, **kwargs): super().__init__(baseplate, lock) self.botThread = IRCBot(baseplate=baseplate, actor_urn=self.actor_urn, *args, **kwargs) def on_start(self): self.botThread.start() def listening_for(self, message): return str(self.actor_urn) != str(message['metadata']['source']) def handle(self, message): """Attempts to send a message to the specified destination in IRC Extends Legobot.Lego.handle() Args: message (Legobot.Message): message w/ metadata to send. """ logger.debug(message) if Utilities.isNotEmpty(message['metadata']['opts']): target = message['metadata']['opts']['target'] for split_line in Utilities.tokenize(message['text']): for truncated_line in Utilities.truncate(split_line): self.botThread.connection.privmsg(target, truncated_line) # Delay to prevent floods time.sleep(0.25) @staticmethod def get_name(): return None
class IRC(Lego): def __init__(self, baseplate, lock, *args, **kwargs): pass def on_start(self): pass def listening_for(self, message): pass def handle(self, message): '''Attempts to send a message to the specified destination in IRC Extends Legobot.Lego.handle() Args: message (Legobot.Message): message w/ metadata to send. ''' pass @staticmethod def get_name(): pass
7
1
6
1
4
1
2
0.3
1
4
2
0
4
1
5
20
35
9
20
11
13
6
18
10
12
4
2
3
8
145,325
Legobot/Legobot
Legobot_Legobot/Legobot/Connectors/IRC.py
Legobot.Connectors.IRC.IRCBot
class IRCBot(threading.Thread, irc.bot.SingleServerIRCBot): """Create bot instance """ def __init__(self, baseplate, channels, nickname, server, actor_urn, port=6667, use_ssl=False, password=None, username=None, ircname=None, nickserv=False, nickserv_pass=None, rejoin_on_kick=True, auto_reconnect=True): irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname) threading.Thread.__init__(self) # the obvious self.channels is already used by irc.bot self.my_channels = channels self.nickname = nickname self.server = server self.baseplate = baseplate self.port = port self.use_ssl = use_ssl self.password = password self.username = username self.ircname = ircname self.nickserv = nickserv self.nickserv_pass = nickserv_pass self.actor_urn = actor_urn self.rejoin_on_kick = rejoin_on_kick self.auto_reconnect = auto_reconnect self.backoff = 1 def connect(self, *args, **kwargs): """Connect to a server. This overrides the function in SimpleIRCClient to provide SSL functionality. :param args: :param kwargs: :return: """ if self.use_ssl: factory = irc.connection.Factory(wrapper=ssl.wrap_socket) else: factory = irc.connection.Factory() self.connection.connect(server=self.server, port=self.port, nickname=self.nickname, connect_factory=factory, password=self.password, username=self.username, ircname=self.ircname) def set_metadata(self, e): """Sets the metadata that is common between pub and priv """ metadata = Metadata(source=self.actor_urn).__dict__ metadata['source_connector'] = 'irc' metadata['source_channel'] = e.target metadata['channel_display_name'] = e.target metadata['source_user'] = e.source metadata['source_username'] = e.source.split('!')[0] metadata['user_id'] = metadata['source_user'] metadata['display_name'] = metadata['source_username'] return metadata def on_pubmsg(self, c, e): """Runs when the bot receives a public message. """ text = e.arguments[0] metadata = self.set_metadata(e) metadata['is_private_message'] = False message = Message(text=text, metadata=metadata).__dict__ self.baseplate.tell(message) def on_privmsg(self, c, e): """Runs when the bot receives a private message (query). """ text = e.arguments[0] logger.debug('{0!s}'.format(e.source)) metadata = self.set_metadata(e) metadata['is_private_message'] = True message = Message(text=text, metadata=metadata).__dict__ self.baseplate.tell(message) def on_welcome(self, c, e): """Runs when the bot successfully connects to the IRC server """ self.backoff = 1 # Assume we had a good connection. Reset backoff. if self.nickserv: if Utilities.isNotEmpty(self.nickserv_pass): self.identify(c, e, self.nickserv_pass) time.sleep(3) # Make sure Nickserv really sees us else: logger.error('If nickserv is enabled, you must supply' ' a password') if self.nickserv is False and self.nickserv_pass is not None: logger.warn('It appears you provided a nickserv password but ' 'did not enable nickserv authentication') for channel in self.my_channels: logger.debug('Attempting to join {0!s}'.format(channel)) c.join(channel) def on_kick(self, c, e): if self.rejoin_on_kick is True: time.sleep(2) c.join(e.target) return def on_disconnect(self, c, e): if self.auto_reconnect is True: time.sleep(2 ** self.backoff) try: self._connect() except Exception: self.backoff += 1 def identify(self, c, e, password): c.privmsg('NickServ', 'IDENTIFY {0!s} {1!s}'.format(self.nickname, password)) return def run(self): """Run the bot in a thread. Implementing the IRC listener as a thread allows it to listen without blocking IRCLego's ability to listen as a pykka actor. :return: None """ self._connect() super(irc.bot.SingleServerIRCBot, self).start()
class IRCBot(threading.Thread, irc.bot.SingleServerIRCBot): '''Create bot instance ''' def __init__(self, baseplate, channels, nickname, server, actor_urn, port=6667, use_ssl=False, password=None, username=None, ircname=None, nickserv=False, nickserv_pass=None, rejoin_on_kick=True, auto_reconnect=True): pass def connect(self, *args, **kwargs): '''Connect to a server. This overrides the function in SimpleIRCClient to provide SSL functionality. :param args: :param kwargs: :return: ''' pass def set_metadata(self, e): '''Sets the metadata that is common between pub and priv ''' pass def on_pubmsg(self, c, e): '''Runs when the bot receives a public message. ''' pass def on_privmsg(self, c, e): '''Runs when the bot receives a private message (query). ''' pass def on_welcome(self, c, e): '''Runs when the bot successfully connects to the IRC server ''' pass def on_kick(self, c, e): pass def on_disconnect(self, c, e): pass def identify(self, c, e, password): pass def run(self): '''Run the bot in a thread. Implementing the IRC listener as a thread allows it to listen without blocking IRCLego's ability to listen as a pykka actor. :return: None ''' pass
11
7
14
1
10
2
2
0.25
2
5
3
0
10
15
10
35
151
22
105
49
80
26
77
35
66
5
1
2
18
145,326
Legobot/Legobot
Legobot_Legobot/Test/test_Lego.py
test_Lego.TestLego
class TestLego(unittest.TestCase): @staticmethod def test_initialization(): lock = threading.Lock() baseplate = Lego(None, lock) lego = Lego(baseplate, baseplate.lock) lego = Lego(baseplate, baseplate.lock, 'lego.log') assert(baseplate.lock == lock) # nosec assert(lego.lock == lock) # nosec assert(baseplate.baseplate is None) # nosec assert(lego.baseplate is baseplate) # nosec assert(lego.children == []) # nosec assert(lego.log_file == 'lego.log') # nosec @staticmethod def test_default_init_values(): lock = threading.Lock() baseplate = Lego(None, lock) lego = Lego(baseplate, baseplate.lock) assert lego.log_file is None # nosec def test_lock_required(self): with self.assertRaises(LegoError): lego = Lego(None, None) # noqa: F841 def test_listening_for(self): lego = Lego(None, threading.Lock()) message = self.make_message() assert not lego.listening_for(message) # nosec def test_handle(self): lego = Lego(None, threading.Lock()) assert(lego.handle(self.make_message()) is None) # nosec def make_message(self): metadata = Metadata(self, None) return Message('a message', metadata) @staticmethod def test_add_child(): baseplate = Lego(None, threading.Lock()) baseplate.add_child(Lego) child = baseplate.children[0] assert(isinstance(child, pykka.ActorRef)) # nosec child_proxy = child.proxy() child_proxy.add_child(Lego) child_children = child_proxy.children.get() assert(isinstance(child_children[0], pykka.ActorRef)) # nosec child_children[0].stop() child.stop() @staticmethod def test_cleanup(): baseplate = Lego(None, threading.Lock()) baseplate.add_child(Lego) child = baseplate.children[0] child.stop() baseplate.cleanup() assert(len(baseplate.children) == 0) # nosec @staticmethod def test_get_name(): lego = Lego(None, threading.Lock()) assert lego.get_name() == '?' # nosec @staticmethod def test_get_help(): lego = Lego(None, threading.Lock()) assert lego.get_help() == '' # nosec @staticmethod def test_receive_logs(): log_file_name = 'test_logging.log' lego = Lego(None, threading.Lock(), log_file_name) message = Message('Test Message 1', Metadata(None).__dict__, True).__dict__ lego.on_receive(message) with open(log_file_name, mode='r') as f: log = json.loads(f.read()) assert log == message # nosec os.remove(log_file_name) @staticmethod def test_on_receive_informs_children(): log_file_name = 'test_child_informed.log' baseplate = Lego(None, threading.Lock()) child = Lego.start(baseplate, threading.Lock(), log_file_name) baseplate.children.append(child) message = Message('Test Message 1', Metadata(None).__dict__, True).__dict__ baseplate.on_receive(message) child.stop() with open(log_file_name, mode='r') as f: log = json.loads(f.read()) os.remove(log_file_name) assert log == message # nosec @staticmethod def test_reply(): # Setup baseplate = Lego.start(None, threading.Lock()) baseplate_proxy = baseplate.proxy() urn = baseplate.actor_urn meta = Metadata(source=urn).__dict__ message = Message(text='0', metadata=meta, should_log=True).__dict__ log_file_name = 'test_reply.log' children = baseplate_proxy.children.get() for child in children: print(child.actor_urn) # Test baseplate_proxy.add_child(ReplyTestingPingLego, log_file_name) baseplate.tell(message) time.sleep(1) # Cleanup children = baseplate_proxy.children.get() for child in children: child.stop() baseplate.stop() with open(log_file_name, mode='r') as f: log = json.loads(f.read()) os.remove(log_file_name) assert log['text'] == '1' # nosec @staticmethod def test_on_failure(): lego = Lego(None, threading.Lock()) lego.on_failure("Exception Type", "Exception Value", "Traceback") assert True
class TestLego(unittest.TestCase): @staticmethod def test_initialization(): pass @staticmethod def test_default_init_values(): pass def test_lock_required(self): pass def test_listening_for(self): pass def test_handle(self): pass def make_message(self): pass @staticmethod def test_add_child(): pass @staticmethod def test_cleanup(): pass @staticmethod def test_get_name(): pass @staticmethod def test_get_help(): pass @staticmethod def test_receive_logs(): pass @staticmethod def test_on_receive_informs_children(): pass @staticmethod def test_reply(): pass @staticmethod def test_on_failure(): pass
25
0
8
0
7
2
1
0.19
1
5
5
0
4
0
14
86
132
16
113
66
88
22
100
53
85
3
2
1
16
145,327
Legobot/Legobot
Legobot_Legobot/Legobot/Connectors/IRC.py
Legobot.Connectors.IRC.IgnoreErrorsBuffer
class IgnoreErrorsBuffer(buffer.DecodingLineBuffer): """Handle char decode errors better """ def handle_exception(self): pass
class IgnoreErrorsBuffer(buffer.DecodingLineBuffer): '''Handle char decode errors better ''' def handle_exception(self): pass
2
1
2
0
2
0
1
0.67
1
0
0
0
1
0
1
1
6
1
3
2
1
2
3
2
1
1
1
0
1
145,328
Legobot/Legobot
Legobot_Legobot/Legobot/Connectors/Slack.py
Legobot.Connectors.Slack.RtmBot
class RtmBot(threading.Thread, object): """Creates a Slack bot using the Slackclient RTM API Attributes: baseplate: The parent pykka actor token: The Slack API token last_ping: Timestamp of last keepalive ping actor_urn: URN of the Pykka actor the RtmBot runs in supported_events: dict of Slack RTM API events we care about slack_client: initialized RTM client """ def __init__(self, baseplate, token, actor_urn, reconnect=True, *args, **kwargs): """Initializes RtmBot Args: baseplate (Legobot.Lego): The parent Pykka actor. Typically passed in fromLegobot.Connectors.Slack.Slack token (string): Slack API token actor_urn (string): URN of Pykka actor launching RtmBot *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. Returns: Returns an instance of RtmBot which connects to Slack. """ self.baseplate = baseplate self.token = token self.last_ping = 0 self.actor_urn = actor_urn self.reconnect = reconnect self.auto_reconnect = True # 'event':'method' self.supported_events = {'message': self.on_message} self.user_map = {} self.slack_client = SlackClient(self.token) self.get_channels() self.get_users() threading.Thread.__init__(self) def connect(self): self.slack_client.rtm_connect(reconnect=self.reconnect, auto_reconnect=self.auto_reconnect) def on_message(self, event): """Runs when a message event is received Args: event: RTM API event. Returns: Legobot.messge """ metadata = self._parse_metadata(event) message = Message(text=metadata['text'], metadata=metadata).__dict__ if message.get('text'): message['text'] = self.find_and_replace_userids(message['text']) message['text'] = self.find_and_replace_channel_refs( message['text'] ) return message def run(self): """Extends the run() method of threading.Thread """ self.connect() while True: for event in self.slack_client.rtm_read(): logger.debug(event) if 'type' in event and event['type'] in self.supported_events: event_type = event['type'] dispatcher = self.supported_events[event_type] message = dispatcher(event) logger.debug(message) self.baseplate.tell(message) self.keepalive() time.sleep(0.1) return def find_and_replace_userids(self, text): """Finds Slack user IDs attempts to replace them with display names. Args: text (string): The message text Returns: string: The message text with userids replaced. """ match = True pattern = re.compile('<@([A-Z0-9]{9})>') while match: match = pattern.search(text) if match: name = self.get_user_name_by_id( match.group(1), return_display_name=True, default='') text = re.sub(re.compile(match.group(0)), '@' + name, text) return text def find_and_replace_channel_refs(self, text): """Find Slack channel refs and attempts to replace them channel names. Args: text (string): The message text Returns: string: The message text with channel references replaced. """ match = True pattern = re.compile(r'<#([A-Z0-9]{9})\|([A-Za-z0-9-]+)>') while match: match = pattern.search(text) if match: text = text.replace(match.group(0), '#' + match.group(2)) return text def get_channel_name_by_id(self, id, default=None): """Given a slack channel id return the channel's name. Args: id (string): The channel id default: The default value to return if no match is found Returns: string | default: The channel name or default provided """ ch = self.channels_by_id.get(id, {}) if not ch: self.get_channels() ch = self.channels_by_id.get(id, {}) return ch.get('name', default) def get_channel_id_by_name(self, name, default=None): """Given a slack channel name return the channel's id. Args: name (string): The channel name default: The default value to return if no match is found Returns: string | default: The channel id or default provided """ ch = self.channels_by_name.get(name, {}) if not ch: self.get_channels() ch = self.channels_by_name.get(name, {}) return ch.get('id', default) def get_channels(self): """Retrieves all channels in the slack team from the API. Stores them by name and by id as class properties. """ channels = [] cursor = None params = { 'exclude_archived': False, 'limit': 50 } while True: if cursor: params['cursor'] = cursor channel_list = self.slack_client.api_call( 'conversations.list', **params) channels += channel_list.get('channels', []) cursor = channel_list.get( 'response_metadata', {}).get('next_cursor') if not cursor: break self.channels_by_id = {ch.get('id'): ch for ch in channels} self.channels_by_name = {ch.get('name'): ch for ch in channels} def get_user_id_by_name(self, name, default=None): """Given a slack user name return the user's id. Args: name (string): The user name default: The default value to return if no match is found Returns: string | default: The user id or default provided """ if name.startswith('@'): name = name[1:] u = self.users_by_name.get(name, self.users_by_display_name.get(name)) if not u: self.get_users() u = self.users_by_name.get(name, self.users_by_display_name.get( name, {})) return u.get('id', default) def get_user_name_by_id(self, id, return_display_name=None, default=None): """Given a Slack userid, return user name or display_name. Args: id (string): the user id of the user being queried return_display_name (bool): return profile display name instead of user name default: default value to return if no match is found Returns: dict: a dictionary of the api response """ u = self.users_by_id.get(id) if not u: self.get_users() u = self.users_by_id.get(id, {}) if return_display_name: return u.get('profile', {}).get('display_name', default) else: return u.get('name', default) def get_users(self): """Grabs all users in the slack team and stores them in the connector. This should should only be used for getting list of all users. Do not use it for searching users. Use get_user_info instead. """ users = [] cursor = None params = { 'include_locale': True, 'limit': 50 } while True: if cursor: params['cursor'] = cursor user_list = self.slack_client.api_call('users.list', **params) users += user_list.get('members', []) cursor = user_list.get('response_metadata', {}).get('next_cursor') if not cursor: break self.users_by_id = {u.get('id'): u for u in users} self.users_by_name = {u.get('name'): u for u in users} self.users_by_display_name = { u.get('profile', {}).get('display_name'): u for u in users} def get_dm_channel(self, userid): """Perform a lookup of users to resolve a userid to a DM channel Args: userid (string): Slack userid to lookup. Returns: string: DM channel ID of user """ dm_open = self.slack_client.api_call('im.open', user=userid) return dm_open['channel']['id'] def post_attachment(self, attachment): self.slack_client.api_call('chat.postMessage', **attachment) def get_userid_from_botid(self, botid): """Perform a lookup of bots.info to resolve a botid to a userid Args: botid (string): Slack botid to lookup. Returns: string: userid value """ botinfo = self.slack_client.api_call('bots.info', bot=botid) if botinfo['ok'] is True: return botinfo['bot'].get('user_id') else: return botid def _parse_metadata(self, message): """Parse incoming messages to build metadata dict Lots of 'if' statements. It sucks, I know. Args: message (dict): JSON dump of message sent from Slack Returns: Legobot.Metadata """ # Try to handle all the fields of events we care about. metadata = Metadata(source=self.actor_urn).__dict__ metadata['thread_ts'] = message.get('thread_ts') metadata['ts'] = message.get('ts') if 'presence' in message: metadata['presence'] = message['presence'] if 'text' in message: metadata['text'] = message['text'] elif 'previous_message' in message: # Try to handle slack links if 'text' in message['previous_message']: metadata['text'] = message['previous_message']['text'] else: metadata['text'] = None else: metadata['text'] = None if 'user' in message: metadata['source_user'] = message['user'] elif 'bot_id' in message: metadata['source_user'] = self.get_userid_from_botid( message['bot_id']) elif 'message' in message and 'user' in message['message']: metadata['source_user'] = message['message']['user'] else: metadata['source_user'] = None metadata['user_id'] = metadata['source_user'] metadata['display_name'] = self.get_user_name_by_id( metadata['source_user'], return_display_name=True, default=metadata['source_user'] ) if 'channel' in message: metadata['source_channel'] = message['channel'] # Slack starts DM channel IDs with "D" if message['channel'].startswith('D'): metadata['is_private_message'] = True else: metadata['is_private_message'] = False metadata['channel_display_name'] = self.get_channel_name_by_id( message['channel']) metadata['subtype'] = message.get('subtype') metadata['source_connector'] = 'slack' return metadata def keepalive(self): """Sends a keepalive to Slack """ # hardcode the interval to 3 seconds now = int(time.time()) if now > self.last_ping + 3: self.slack_client.server.ping() self.last_ping = now
class RtmBot(threading.Thread, object): '''Creates a Slack bot using the Slackclient RTM API Attributes: baseplate: The parent pykka actor token: The Slack API token last_ping: Timestamp of last keepalive ping actor_urn: URN of the Pykka actor the RtmBot runs in supported_events: dict of Slack RTM API events we care about slack_client: initialized RTM client ''' def __init__(self, baseplate, token, actor_urn, reconnect=True, *args, **kwargs): '''Initializes RtmBot Args: baseplate (Legobot.Lego): The parent Pykka actor. Typically passed in fromLegobot.Connectors.Slack.Slack token (string): Slack API token actor_urn (string): URN of Pykka actor launching RtmBot *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. Returns: Returns an instance of RtmBot which connects to Slack. ''' pass def connect(self): pass def on_message(self, event): '''Runs when a message event is received Args: event: RTM API event. Returns: Legobot.messge ''' pass def run(self): '''Extends the run() method of threading.Thread ''' pass def find_and_replace_userids(self, text): '''Finds Slack user IDs attempts to replace them with display names. Args: text (string): The message text Returns: string: The message text with userids replaced. ''' pass def find_and_replace_channel_refs(self, text): '''Find Slack channel refs and attempts to replace them channel names. Args: text (string): The message text Returns: string: The message text with channel references replaced. ''' pass def get_channel_name_by_id(self, id, default=None): '''Given a slack channel id return the channel's name. Args: id (string): The channel id default: The default value to return if no match is found Returns: string | default: The channel name or default provided ''' pass def get_channel_id_by_name(self, name, default=None): '''Given a slack channel name return the channel's id. Args: name (string): The channel name default: The default value to return if no match is found Returns: string | default: The channel id or default provided ''' pass def get_channels(self): '''Retrieves all channels in the slack team from the API. Stores them by name and by id as class properties. ''' pass def get_user_id_by_name(self, name, default=None): '''Given a slack user name return the user's id. Args: name (string): The user name default: The default value to return if no match is found Returns: string | default: The user id or default provided ''' pass def get_user_name_by_id(self, id, return_display_name=None, default=None): '''Given a Slack userid, return user name or display_name. Args: id (string): the user id of the user being queried return_display_name (bool): return profile display name instead of user name default: default value to return if no match is found Returns: dict: a dictionary of the api response ''' pass def get_users(self): '''Grabs all users in the slack team and stores them in the connector. This should should only be used for getting list of all users. Do not use it for searching users. Use get_user_info instead. ''' pass def get_dm_channel(self, userid): '''Perform a lookup of users to resolve a userid to a DM channel Args: userid (string): Slack userid to lookup. Returns: string: DM channel ID of user ''' pass def post_attachment(self, attachment): pass def get_userid_from_botid(self, botid): '''Perform a lookup of bots.info to resolve a botid to a userid Args: botid (string): Slack botid to lookup. Returns: string: userid value ''' pass def _parse_metadata(self, message): '''Parse incoming messages to build metadata dict Lots of 'if' statements. It sucks, I know. Args: message (dict): JSON dump of message sent from Slack Returns: Legobot.Metadata ''' pass def keepalive(self): '''Sends a keepalive to Slack ''' pass
18
16
19
3
11
6
3
0.57
2
3
2
0
17
14
17
42
357
69
185
60
166
105
154
59
136
10
1
3
48
145,329
Legobot/Legobot
Legobot_Legobot/Test/test_Lego.py
test_Lego.ReplyTestingPingLego
class ReplyTestingPingLego(Lego): def listening_for(self, message): print('\n\n{}\n\n'.format(message)) return message['text'] == '0' or message['text'] == '1' def handle(self, message): if message['text'] == '0': self.reply(message, '1') else: print(message['text'])
class ReplyTestingPingLego(Lego): def listening_for(self, message): pass def handle(self, message): pass
3
0
4
0
4
0
2
0
1
0
0
0
2
0
2
17
10
1
9
3
6
0
8
3
5
2
2
1
3
145,330
Legobot/Legobot
Legobot_Legobot/Legobot/Legos/Help.py
Legobot.Legos.Help.Help
class Help(Lego): @staticmethod def listening_for(message): if Utilities.isNotEmpty(message['text']): try: return message['text'].split()[0] == '!help' except Exception as e: logger.error( 'Help lego failed to check message text: {0!s}'.format(e)) return False def handle(self, message): try: function = message['text'].split()[1] except IndexError: function = None baseplate_proxy = self.baseplate.proxy() legos = baseplate_proxy.children.get() lego_names = [ lego.proxy().get_name().get() for lego in legos if lego.proxy().get_name().get() and lego.proxy().get_name().get() != '?' ] help_str = 'No help is available. Sorry.' if not function: help_str = 'Available functions: ' + ', '.join(lego_names) if function and function.lower() in [n.lower() for n in lego_names]: help_strs = [] for lego in legos: name = lego.proxy().get_name().get() if name and name.lower() == function.lower(): try: sub = message['text'].split()[2] try: temp = lego.proxy().get_help(sub=sub).get() except (TypeError, KeyError): temp = '{} has no information on {}'.format( function, sub) except IndexError: temp = lego.proxy().get_help().get() help_strs.append(temp) help_str = '\n'.join(help_strs) opts = self.build_reply_opts(message) self.reply(message, help_str, opts=opts) @staticmethod def get_name(): return None
class Help(Lego): @staticmethod def listening_for(message): pass def handle(self, message): pass @staticmethod def get_name(): pass
6
0
17
3
15
0
4
0
1
5
1
0
1
0
3
18
57
10
47
17
41
0
38
14
34
8
2
5
12
145,331
Legobot/Legobot
Legobot_Legobot/Legobot/LegoTests/test_TestingConnector.py
Legobot.LegoTests.test_TestingConnector.TestTestingConnector
class TestTestingConnector(unittest.TestCase): def test_init(self): testing_connector = self._make_testing_connector('blah.tmp') assert testing_connector.temp_file == 'blah.tmp' # nosec def test_default_parameters(self): testing_connector = self._make_testing_connector() assert testing_connector.temp_file == 'testing_file.tmp' # nosec def test_listening_for(self): testing_connector = self._make_testing_connector() assert testing_connector.listening_for(self._make_message()) # nosec def test_handle(self): testing_connector = self._make_testing_connector() message = self._make_message() testing_connector.handle(message) with open(testing_connector.temp_file, mode='r') as f: text = f.read() assert text == str(message) # nosec @staticmethod def _make_testing_connector(temp_file=None): lock = threading.Lock() baseplate = Lego(None, lock) if temp_file is None: testing_connector = TestingConnector(baseplate, lock) else: testing_connector = TestingConnector(baseplate, lock, temp_file) return testing_connector # nosec @staticmethod def _make_message(): source = Lego(None, threading.Lock()) metadata = Metadata(source) message = Message('blah', metadata) return message
class TestTestingConnector(unittest.TestCase): def test_init(self): pass def test_default_parameters(self): pass def test_listening_for(self): pass def test_handle(self): pass @staticmethod def _make_testing_connector(temp_file=None): pass @staticmethod def _make_message(): pass
9
0
5
0
5
1
1
0.16
1
5
4
0
4
0
6
78
37
5
32
22
23
5
29
19
22
2
2
1
7
145,332
Legobot/Legobot
Legobot_Legobot/Legobot/Connectors/Slack.py
Legobot.Connectors.Slack.Slack
class Slack(Lego): """Lego that builds and connects Legobot.Connectors.Slack.RtmBot Args: baseplate (Legobot.Lego): baseplate/parent lego (Pykka Actor) lock (threading.Lock: thread lock created in your bot script. All legos should share the same lock. *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. """ def __init__(self, baseplate, lock, *args, **kwargs): super().__init__(baseplate, lock) self.botThread = RtmBot(baseplate, actor_urn=self.actor_urn, *args, **kwargs) def on_start(self): """Extends pykka's on_start method to launch this as an actor """ self.botThread.start() def listening_for(self, message): """Describe what this should listen for (hint: everything) Extends Legobot.Lego.listening_for() Args: message (Legobot.Message): Message to handle Returns: bool: True if lego is interested in the message. """ return str(self.botThread) != str(message['metadata']['source']) def build_attachment(self, text, target, attachment, thread): """Builds a slack attachment. Args: message (Legobot.Message): message w/ metadata to send. Returns: attachment (dict): attachment data. """ attachment = { 'as_user': True, 'text': text, 'channel': target, 'attachments': [ { 'fallback': text, 'image_url': attachment } ] } if thread: attachment['thread_ts'] = thread return attachment def handle(self, message): """Attempts to send a message to the specified destination in Slack. Extends Legobot.Lego.handle() Args: message (Legobot.Message): message w/ metadata to send. """ logger.debug(message) if Utilities.isNotEmpty(message['metadata']['opts']): target = message['metadata']['opts']['target'] thread = message['metadata']['opts'].get('thread') # pattern = re.compile('@([a-zA-Z0-9._-]+)') pattern = re.compile(r'^@([a-zA-Z0-9._-]+)|\s@([a-zA-Z0-9._-]+)') matches = re.findall(pattern, message['text']) matches = set(matches) logger.debug('MATCHES!!!! {}'.format(matches)) for match in matches: if isinstance(match, tuple): if match[0] != '': match = match[0] else: match = match[1] if not match.startswith('@'): match = '@' + match message['text'] = message['text'].replace( match, '<{}>'.format(match) ) pattern = re.compile('#([A-Za-z0-9-]+)') matches = re.findall(pattern, message['text']) matches = set(matches) for match in matches: channel_id = self.botThread.get_channel_id_by_name(match) if channel_id: message['text'] = message['text'].replace( '#' + match, '<#{}|{}>'.format( channel_id, match ) ) if (message['text'].find('<<@') != -1 or message['text'].find('<<#') != -1): message['text'] = message['text'].replace('<<', '<') message['text'] = message['text'].replace('>>', '>') if target.startswith('U'): target = self.botThread.get_dm_channel(target) attachment = message['metadata']['opts'].get('attachment') if attachment: text = message['metadata']['opts'].get('fallback') attachment = self.build_attachment( text, target, attachment, thread) self.botThread.post_attachment(attachment) else: self.botThread.slack_client.rtm_send_message( target, message['text'], thread=thread) @staticmethod def get_name(): """Returns name of Lego. Called by built-in !help lego Returns none because this is a non-interactive Lego """ return None
class Slack(Lego): '''Lego that builds and connects Legobot.Connectors.Slack.RtmBot Args: baseplate (Legobot.Lego): baseplate/parent lego (Pykka Actor) lock (threading.Lock: thread lock created in your bot script. All legos should share the same lock. *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. ''' def __init__(self, baseplate, lock, *args, **kwargs): pass def on_start(self): '''Extends pykka's on_start method to launch this as an actor ''' pass def listening_for(self, message): '''Describe what this should listen for (hint: everything) Extends Legobot.Lego.listening_for() Args: message (Legobot.Message): Message to handle Returns: bool: True if lego is interested in the message. ''' pass def build_attachment(self, text, target, attachment, thread): '''Builds a slack attachment. Args: message (Legobot.Message): message w/ metadata to send. Returns: attachment (dict): attachment data. ''' pass def handle(self, message): '''Attempts to send a message to the specified destination in Slack. Extends Legobot.Lego.handle() Args: message (Legobot.Message): message w/ metadata to send. ''' pass @staticmethod def get_name(): '''Returns name of Lego. Called by built-in !help lego Returns none because this is a non-interactive Lego ''' pass
8
6
20
3
12
5
3
0.49
1
6
2
0
5
1
6
21
134
25
76
17
68
37
50
16
43
11
2
4
17
145,333
Legobot/Legobot
Legobot_Legobot/Legobot/Legos/TestingConnector.py
Legobot.Legos.TestingConnector.TestingConnector
class TestingConnector(Lego): def __init__(self, baseplate, lock, temp_file='testing_file.tmp'): super().__init__(baseplate, lock) self.temp_file = temp_file @staticmethod def listening_for(message): return True def handle(self, message): with open(self.temp_file, mode='w') as f: f.write(str(message))
class TestingConnector(Lego): def __init__(self, baseplate, lock, temp_file='testing_file.tmp'): pass @staticmethod def listening_for(message): pass def handle(self, message): pass
5
0
3
0
3
0
1
0
1
2
0
0
2
1
3
18
12
2
10
7
5
0
9
5
5
1
2
1
3
145,334
Legobot/Legobot
Legobot_Legobot/Legobot/Message.py
Legobot.Message.Message
class Message(): """Class for passing messages. Messages in pykka must be passed as dictionaries. This class provides fields corresponding to the keys in that dictionary to facilitate the construction of such messages. """ def __init__(self, text, metadata, should_log=False): self.text = text self.metadata = metadata self.should_log = should_log
class Message(): '''Class for passing messages. Messages in pykka must be passed as dictionaries. This class provides fields corresponding to the keys in that dictionary to facilitate the construction of such messages. ''' def __init__(self, text, metadata, should_log=False): pass
2
1
4
0
4
0
1
1
0
0
0
0
1
3
1
1
12
2
5
5
3
5
5
5
3
1
0
0
1
145,335
Legobot/Legobot
Legobot_Legobot/Legobot/LegoError.py
Legobot.LegoError.LegoError
class LegoError(Error): """Exceptions raised inside legos """ def __init__(self, message): self.message = message Exception.__init__(self, message)
class LegoError(Error): '''Exceptions raised inside legos ''' def __init__(self, message): pass
2
1
3
0
3
0
1
0.5
1
0
0
0
1
1
1
11
8
2
4
3
2
2
4
3
2
1
4
0
1
145,336
Legobot/Legobot
Legobot_Legobot/Legobot/Lego.py
Legobot.Lego.Lego
class Lego(ThreadingActor): class HandlerThread(threading.Thread): """This class provides a simple thread for running message handlers. It is used to ensure that message handlers do not block other Legos from running by simply taking too long to execute. """ def __init__(self, handler, message): threading.Thread.__init__(self) self.handler = handler self.message = message def run(self): self.handler(self.message) def __init__(self, baseplate, lock: threading.Lock, log_file=None, acl=None, rate_config=None): """Initializes the thread :param baseplate: the baseplate Lego, which should be \ the same instance of Lego for all Legos :param lock: a threading lock, which should be the same \ instance of threading.Lock for all Legos :param log_file str: a file path for writing logs to file :param acl dict: a dict representing an access control list. \ ex: {'whitelist': [list of source_users]} :param rate_config dict: a dict representing the rate limite config. \ ex: {'rate_key': jmespath expr to get rate \ key value from message object, \ 'rate_interval': the rate limit \ interval in seconds} """ super().__init__() if not lock: raise LegoError("Lock expected but not provided!") self.baseplate = baseplate self.children = [] self.lock = lock self.log_file = log_file self.acl = acl if acl else {} # set rate limit items self.set_rate_limit(rate_config) def set_rate_limit(self, rate_config): """Set rate limit config for this Lego. :param rate_config dict: dict representing the rate limit config """ rate_config = rate_config if isinstance(rate_config, dict) else {} self.rate_key = rate_config.get('rate_key') self.rate_interval = rate_config.get('rate_interval') self.rate_log = {} def on_receive(self, message): """Handle being informed of a message. This function is called whenever a Lego receives a message, as specified in the pykka documentation. Legos should not override this function. :param message: :return: """ if self.log_file is not None and message['should_log']: message_copy = Message(message['text'], Metadata(None).__dict__, message['should_log']).__dict__ with open(self.log_file, mode='w') as f: f.write(json.dumps(message_copy)) logger.info(message['metadata']['source']) if (self.acl_check(message) and self.rate_check(message) and self.listening_for(message)): self_thread = self.HandlerThread(self.handle, message) self_thread.start() self.cleanup() for child in self.children: child.tell(message) def cleanup(self): """Clean up finished children. :return: None """ self.lock.acquire() logger.debug('Acquired lock in cleanup for ' + str(self)) self.children = [child for child in self.children if child.is_alive()] self.lock.release() def rate_check(self, message): """Return whether the message passes the rate limit check for this Lego :param message: a Message object :return: Boolean """ if not self.rate_key or not self.rate_interval: return True now = int(round(time.time())) key = jmespath.search(self.rate_key, message) last_invoke = self.rate_log.get(key, 0) if now - last_invoke >= self.rate_interval: self.rate_log[key] = now return True else: return False def acl_check(self, message): """Return whether the message passes the ACL check for this Lego. :param message: a Message object :return: Boolean """ user = message.get('metadata', {}).get('source_user') acl_conditions = [ user, isinstance(user, str), self.acl, isinstance(self.acl, dict) ] if all(acl_conditions): whitelist = self.acl.get('whitelist', []) if whitelist and user in whitelist: return True elif whitelist and user not in whitelist: return False blacklist = self.acl.get('blacklist', []) if blacklist and user in blacklist: return False if blacklist and user not in blacklist: return True return True def listening_for(self, message): """Return whether this Lego is listening for the provided Message. All Legos should override this function. :param message: a Message object :return: a boolean """ return False def handle(self, message): """Handle the provided Message. All Legos should override this function. :param message: a Message object :return: None """ return def add_child(self, child_type, *args, **kwargs): """Initialize and keep track of a child. :param child_type: a class inheriting from Lego to initialize \ an instance of :param args: arguments for initializing the child :param kwargs: keyword arguments for initializing the child :return: """ try: baseplate = kwargs['baseplate'] except Exception: if self.baseplate is None: baseplate = self.actor_ref else: baseplate = self.baseplate try: lock = kwargs['lock'] except Exception: lock = self.lock child = child_type.start(baseplate, lock, *args, **kwargs) self.children.append(child) def reply(self, message, text, opts=None): """Reply to the sender of the message with a containing the text :param message: the message to reply to :param text: the text to reply with :param opts: A dictionary of additional values to add to metadata :return: None """ metadata = Metadata(source=self.actor_urn, dest=message['metadata']['source']).__dict__ metadata['opts'] = opts message = Message(text=text, metadata=metadata, should_log=message['should_log']).__dict__ dest_actor = ActorRegistry.get_by_urn(message['metadata']['dest']) if dest_actor is not None: dest_actor.tell(message) else: raise("Tried to send message to nonexistent actor") def reply_attachment(self, message, text, attachment, opts=None): """Convenience method for formatting reply as attachment (if available) Passes attachment on to the reply method. Individual connectors can deal with the attachment or simply pass it on as a regular message :param message: the message to reply to :param text: the text to reply with :param attachment: the attachment link :param opts: A dictionary of additional values to add to metadata :return: None """ if not opts: opts = {} opts['attachment'] = attachment opts['fallback'] = text text += '\n {}'.format(attachment) self.reply(message, text, opts) def build_reply_opts(self, message): """Convenience method for constructing default options for a reply :param message: the message to reply to :return: opts """ try: source = message['metadata']['source_channel'] thread = message['metadata'].get('thread_ts') opts = {'target': source, 'thread': thread} except LookupError: source = None opts = None logger.error("Could not identify source from message:{}\n" .format(str(message))) return opts def get_name(self): """Return the name the Lego recognizes from the help function. :return: a string """ return '?' def get_help(self): """Return a helpstring for the function. :return: a string """ return '' def on_failure(self, exception_type, exception_value, traceback): ref = ActorRegistry.get_by_urn(self.actor_urn) logger.exception('Lego crashed: ' + str(ref)) logger.exception(exception_type) logger.exception(exception_value)
class Lego(ThreadingActor): class HandlerThread(threading.Thread): '''This class provides a simple thread for running message handlers. It is used to ensure that message handlers do not block other Legos from running by simply taking too long to execute. ''' def __init__(self, handler, message): pass def run(self): pass def __init__(self, handler, message): '''Initializes the thread :param baseplate: the baseplate Lego, which should be the same instance of Lego for all Legos :param lock: a threading lock, which should be the same instance of threading.Lock for all Legos :param log_file str: a file path for writing logs to file :param acl dict: a dict representing an access control list. ex: {'whitelist': [list of source_users]} :param rate_config dict: a dict representing the rate limite config. ex: {'rate_key': jmespath expr to get rate key value from message object, 'rate_interval': the rate limit interval in seconds} ''' pass def set_rate_limit(self, rate_config): '''Set rate limit config for this Lego. :param rate_config dict: dict representing the rate limit config ''' pass def on_receive(self, message): '''Handle being informed of a message. This function is called whenever a Lego receives a message, as specified in the pykka documentation. Legos should not override this function. :param message: :return: ''' pass def cleanup(self): '''Clean up finished children. :return: None ''' pass def rate_check(self, message): '''Return whether the message passes the rate limit check for this Lego :param message: a Message object :return: Boolean ''' pass def acl_check(self, message): '''Return whether the message passes the ACL check for this Lego. :param message: a Message object :return: Boolean ''' pass def listening_for(self, message): '''Return whether this Lego is listening for the provided Message. All Legos should override this function. :param message: a Message object :return: a boolean ''' pass def handle(self, message): '''Handle the provided Message. All Legos should override this function. :param message: a Message object :return: None ''' pass def add_child(self, child_type, *args, **kwargs): '''Initialize and keep track of a child. :param child_type: a class inheriting from Lego to initialize an instance of :param args: arguments for initializing the child :param kwargs: keyword arguments for initializing the child :return: ''' pass def reply(self, message, text, opts=None): '''Reply to the sender of the message with a containing the text :param message: the message to reply to :param text: the text to reply with :param opts: A dictionary of additional values to add to metadata :return: None ''' pass def reply_attachment(self, message, text, attachment, opts=None): '''Convenience method for formatting reply as attachment (if available) Passes attachment on to the reply method. Individual connectors can deal with the attachment or simply pass it on as a regular message :param message: the message to reply to :param text: the text to reply with :param attachment: the attachment link :param opts: A dictionary of additional values to add to metadata :return: None ''' pass def build_reply_opts(self, message): '''Convenience method for constructing default options for a reply :param message: the message to reply to :return: opts ''' pass def get_name(self): '''Return the name the Lego recognizes from the help function. :return: a string ''' pass def get_help(self): '''Return a helpstring for the function. :return: a string ''' pass def on_failure(self, exception_type, exception_value, traceback): pass
19
15
14
1
8
5
2
0.62
1
10
4
6
15
9
15
15
257
43
132
50
112
82
115
48
96
6
1
2
36
145,337
Legobot/Legobot
Legobot_Legobot/Legobot/Message.py
Legobot.Message.Metadata
class Metadata(): """Class for passing Message metadata. Message Metadata is passed as a dictionary. This class provides fields corresponding to the keys in that dictionary to facilitate the construction of such dictionaries. """ def __init__(self, source, dest=None, opts=None): self.source = source self.dest = dest self.opts = opts
class Metadata(): '''Class for passing Message metadata. Message Metadata is passed as a dictionary. This class provides fields corresponding to the keys in that dictionary to facilitate the construction of such dictionaries. ''' def __init__(self, source, dest=None, opts=None): pass
2
1
4
0
4
0
1
1
0
0
0
0
1
3
1
1
12
2
5
5
3
5
5
5
3
1
0
0
1
145,338
Legobot/Legobot
Legobot_Legobot/Legobot/Utilities.py
Legobot.Utilities.Utilities
class Utilities(): """Miscellaneous utilities for Legobot services """ @staticmethod def tokenize(text): """Returns text split along newlines. Args: text (str): The text to be tokenized Returns: list: Text split along newlines """ return text.split('\n') @staticmethod def truncate(text, length=255): """Splits the message into a list of strings of of length `length` Args: text (str): The text to be divided length (int, optional): The length of the chunks of text. \ Defaults to 255. Returns: list: Text divided into chunks of length `length` """ lines = [] i = 0 while i < len(text) - 1: try: lines.append(text[i:i+length]) i += length except IndexError: lines.append(text[i:]) return lines @staticmethod def isNotEmpty(text): """Check if the given text is empty. Args: text (str): The text to assess Returns: bool: False if empty otherwise, True """ return True if text else False
class Utilities(): '''Miscellaneous utilities for Legobot services ''' @staticmethod def tokenize(text): '''Returns text split along newlines. Args: text (str): The text to be tokenized Returns: list: Text split along newlines ''' pass @staticmethod def truncate(text, length=255): '''Splits the message into a list of strings of of length `length` Args: text (str): The text to be divided length (int, optional): The length of the chunks of text. Defaults to 255. Returns: list: Text divided into chunks of length `length` ''' pass @staticmethod def isNotEmpty(text): '''Check if the given text is empty. Args: text (str): The text to assess Returns: bool: False if empty otherwise, True ''' pass
7
4
14
3
5
7
2
1.22
0
1
0
0
0
0
3
3
52
12
18
9
11
22
15
6
11
3
0
2
6
145,339
Legobot/legos.devopsy
Legobot_legos.devopsy/legos/devopsy.py
legos.devopsy.Devopsy
class Devopsy(Lego): def listening_for(self, message): return message['text'].split()[0] == '!devopsy' def handle(self, message): logger.info(message) try: target = message['metadata']['source_channel'] self.opts = {'target': target} self.message = message except IndexError: logger.error('Could not identify message source in message: {0!s}' .format(str(message))) args = self.devopsy(message['text'].split()) self.reply(message, args, self.opts) def devopsy(self, *args): """Return a gif based on search of several *reactions Ported to Legobot from: "https://github.com/ricardokirkner/err-devops-reactions" ... and extended. Return a random gif if no query is specified or query not found Example: !devopsy somefoofulquery !devopsy """ args = ' '.join(self.message['text'].split()[1:]) if args: base_main = { 'dev': 'https://devopsreactions.tumblr.com/', 'sec': 'https://securityreactions.tumblr.com/' } main_items = list(base_main.items()) key, val = random.choice(main_items) # nosec else: base_alt = { 'qa': 'https://qareacts.tumblr.com/', 'dba': 'http://dbareactions.com/' } alt_items = list(base_alt.items()) key, val = random.choice(alt_items) # nosec if args and set(('dev', 'sec')) <= set(base_main): q = urlencode({'q': args}) path = ''.join(['?', q]) else: path = 'random' url = urljoin(val, path) r = requests.get(url) logger.debug('url sent: {}'.format(r.url)) if r.ok: dom = PyQuery(r.content) results = dom('div[class=post_title] a') logger.debug('results found: {}'.format(len(results))) else: results = [] if results: item = random.choice(results) # nosec img = item.get('href') response = img else: path = 'random' noway = urljoin(url, path) response = 'Foo for you: {}'.format(noway) return response def get_name(self): return 'devopsy' def get_help(self): help_text = "Enter a query or we'll pick a random one " \ "Usage: !devopsy foofulquery" return help_text
class Devopsy(Lego): def listening_for(self, message): pass def handle(self, message): pass def devopsy(self, *args): '''Return a gif based on search of several *reactions Ported to Legobot from: "https://github.com/ricardokirkner/err-devops-reactions" ... and extended. Return a random gif if no query is specified or query not found Example: !devopsy somefoofulquery !devopsy ''' pass def get_name(self): pass def get_help(self): pass
6
1
15
1
12
2
2
0.2
1
4
0
0
5
2
5
5
79
11
59
26
53
12
47
26
41
5
1
1
10
145,340
LemmoTresto/Webcord
LemmoTresto_Webcord/webcord/errors.py
webcord.errors.ClientException
class ClientException(DiscordException): """Exception that's thrown when an operation in the :class:`Client` fails. These are usually for exceptions that happened due to user input. """ pass
class ClientException(DiscordException): '''Exception that's thrown when an operation in the :class:`Client` fails. These are usually for exceptions that happened due to user input. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
1
0
0
0
10
6
1
2
1
1
3
2
1
1
0
4
0
0
145,341
LemmoTresto/Webcord
LemmoTresto_Webcord/webcord/errors.py
webcord.errors.GatewayNotFound
class GatewayNotFound(DiscordException): """An exception that is usually thrown when the gateway hub for the :class:`Client` websocket is not found.""" def __init__(self): message = 'The gateway to connect to discord was not found.' super(GatewayNotFound, self).__init__(message)
class GatewayNotFound(DiscordException): '''An exception that is usually thrown when the gateway hub for the :class:`Client` websocket is not found.''' def __init__(self): pass
2
1
3
0
3
0
1
0.5
1
1
0
0
1
0
1
11
6
0
4
3
2
2
4
3
2
1
4
0
1
145,342
LemmoTresto/Webcord
LemmoTresto_Webcord/webcord/embed.py
webcord.embed.EmbedProxy
class EmbedProxy: def __init__(self, layer): self.__dict__.update(layer) def __repr__(self): return 'EmbedProxy(%s)' % ', '.join(('%s=%r' % (k, v) for k, v in self.__dict__.items() if not k.startswith('_'))) def __getattr__(self, attr): return EmptyEmbed
class EmbedProxy: def __init__(self, layer): pass def __repr__(self): pass def __getattr__(self, attr): pass
4
0
2
0
2
0
1
0
0
0
0
0
3
0
3
3
9
2
7
4
3
0
7
4
3
1
0
0
3
145,343
LemmoTresto/Webcord
LemmoTresto_Webcord/webcord/embed.py
webcord.embed.Embed
class Embed: """Represents a Discord embed. The following attributes can be set during creation of the object: Certain properties return an ``EmbedProxy``. Which is a type that acts similar to a regular `dict` except access the attributes via dotted access, e.g. ``embed.author.icon_url``. If the attribute is invalid or empty, then a special sentinel value is returned, :attr:`Embed.Empty`. For ease of use, all parameters that expect a ``str`` are implicitly casted to ``str`` for you. Attributes ----------- title: str The title of the embed. type: str The type of embed. Usually "rich". description: str The description of the embed. url: str The URL of the embed. timestamp: `datetime.datetime` The timestamp of the embed content. colour: :class:`Colour` or int The colour code of the embed. Aliased to ``color`` as well. Empty A special sentinel value used by ``EmbedProxy`` and this class to denote that the value or attribute is empty. """ __slots__ = ('title', 'url', 'type', '_timestamp', '_colour', '_footer', '_image', '_thumbnail', '_video', '_provider', '_author', '_fields', 'description') Empty = EmptyEmbed def __init__(self, **kwargs): # swap the colour/color aliases try: colour = kwargs['colour'] except KeyError: colour = kwargs.get('color', EmptyEmbed) self.colour = colour self.title = kwargs.get('title', EmptyEmbed) self.type = kwargs.get('type', 'rich') self.url = kwargs.get('url', EmptyEmbed) self.description = kwargs.get('description', EmptyEmbed) try: timestamp = kwargs['timestamp'] except KeyError: pass else: self.timestamp = timestamp @classmethod def from_data(cls, data): # we are bypassing __init__ here since it doesn't apply here self = cls.__new__(cls) # fill in the basic fields self.title = data.get('title', EmptyEmbed) self.type = data.get('type', EmptyEmbed) self.description = data.get('description', EmptyEmbed) self.url = data.get('url', EmptyEmbed) # try to fill in the more rich fields try: self._colour = Colour(value=data['color']) except KeyError: pass try: self._timestamp = utils.parse_time(data['timestamp']) except KeyError: pass for attr in ('thumbnail', 'video', 'provider', 'author', 'fields'): try: value = data[attr] except KeyError: continue else: setattr(self, '_' + attr, value) return self @property def colour(self): return getattr(self, '_colour', EmptyEmbed) @colour.setter def colour(self, value): if isinstance(value, (Colour, _EmptyEmbed)): self._colour = value elif isinstance(value, int): self._colour = Colour(value=value) else: raise TypeError('Expected discord.Colour, int, or Embed.Empty but received %s instead.' % value.__class__.__name__) color = colour @property def timestamp(self): return getattr(self, '_timestamp', EmptyEmbed) @timestamp.setter def timestamp(self, value): if isinstance(value, (datetime.datetime, _EmptyEmbed)): self._timestamp = value else: raise TypeError("Expected datetime.datetime or Embed.Empty received %s instead" % value.__class__.__name__) @property def footer(self): """Returns a ``EmbedProxy`` denoting the footer contents. See :meth:`set_footer` for possible values you can access. If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_footer', {})) def set_footer(self, *, text=EmptyEmbed, icon_url=EmptyEmbed): """Sets the footer for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- text: str The footer text. icon_url: str The URL of the footer icon. Only HTTP(S) is supported. """ self._footer = {} if text is not EmptyEmbed: self._footer['text'] = str(text) if icon_url is not EmptyEmbed: self._footer['icon_url'] = str(icon_url) return self @property def image(self): """Returns a ``EmbedProxy`` denoting the image contents. Possible attributes you can access are: - ``url`` - ``proxy_url`` - ``width`` - ``height`` If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_image', {})) def set_image(self, *, url): """Sets the image for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- url: str The source URL for the image. Only HTTP(S) is supported. """ self._image = { 'url': str(url) } return self @property def thumbnail(self): """Returns a ``EmbedProxy`` denoting the thumbnail contents. Possible attributes you can access are: - ``url`` - ``proxy_url`` - ``width`` - ``height`` If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_thumbnail', {})) def set_thumbnail(self, *, url): """Sets the thumbnail for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- url: str The source URL for the thumbnail. Only HTTP(S) is supported. """ self._thumbnail = { 'url': str(url) } return self @property def video(self): """Returns a ``EmbedProxy`` denoting the video contents. Possible attributes include: - ``url`` for the video URL. - ``height`` for the video height. - ``width`` for the video width. If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_video', {})) @property def provider(self): """Returns a ``EmbedProxy`` denoting the provider contents. The only attributes that might be accessed are ``name`` and ``url``. If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_provider', {})) @property def author(self): """Returns a ``EmbedProxy`` denoting the author contents. See :meth:`set_author` for possible values you can access. If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_author', {})) def set_author(self, *, name, url=EmptyEmbed, icon_url=EmptyEmbed): """Sets the author for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: str The name of the author. url: str The URL for the author. icon_url: str The URL of the author icon. Only HTTP(S) is supported. """ self._author = { 'name': str(name) } if url is not EmptyEmbed: self._author['url'] = str(url) if icon_url is not EmptyEmbed: self._author['icon_url'] = str(icon_url) return self @property def fields(self): """Returns a list of ``EmbedProxy`` denoting the field contents. See :meth:`add_field` for possible values you can access. If the attribute has no value then :attr:`Empty` is returned. """ return [EmbedProxy(d) for d in getattr(self, '_fields', [])] def add_field(self, *, name, value, inline=True): """Adds a field to the embed object. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: str The name of the field. value: str The value of the field. inline: bool Whether the field should be displayed inline. """ field = { 'inline': inline, 'name': str(name), 'value': str(value) } try: self._fields.append(field) except AttributeError: self._fields = [field] return self def clear_fields(self): """Removes all fields from this embed.""" try: self._fields.clear() except AttributeError: self._fields = [] def remove_field(self, index): """Removes a field at a specified index. If the index is invalid or out of bounds then the error is silently swallowed. .. note:: When deleting a field by index, the index of the other fields shift to fill the gap just like a regular list. Parameters ----------- index: int The index of the field to remove. """ try: del self._fields[index] except (AttributeError, IndexError): pass def set_field_at(self, index, *, name, value, inline=True): """Modifies a field to the embed object. The index must point to a valid pre-existing field. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- index: int The index of the field to modify. name: str The name of the field. value: str The value of the field. inline: bool Whether the field should be displayed inline. Raises ------- IndexError An invalid index was provided. """ try: field = self._fields[index] except (TypeError, IndexError, AttributeError): raise IndexError('field index out of range') field['name'] = str(name) field['value'] = str(value) field['inline'] = inline return self def to_dict(self): """Converts this embed object into a dict.""" # add in the raw data into the dict result = { key[1:]: getattr(self, key) for key in self.__slots__ if key[0] == '_' and hasattr(self, key) } # deal with basic convenience wrappers try: colour = result.pop('colour') except KeyError: pass else: if colour: result['color'] = colour.value try: timestamp = result.pop('timestamp') except KeyError: pass else: if timestamp: result['timestamp'] = timestamp.isoformat() # add in the non raw attribute ones if self.type: result['type'] = self.type if self.description: result['description'] = self.description if self.url: result['url'] = self.url if self.title: result['title'] = self.title return result
class Embed: '''Represents a Discord embed. The following attributes can be set during creation of the object: Certain properties return an ``EmbedProxy``. Which is a type that acts similar to a regular `dict` except access the attributes via dotted access, e.g. ``embed.author.icon_url``. If the attribute is invalid or empty, then a special sentinel value is returned, :attr:`Embed.Empty`. For ease of use, all parameters that expect a ``str`` are implicitly casted to ``str`` for you. Attributes ----------- title: str The title of the embed. type: str The type of embed. Usually "rich". description: str The description of the embed. url: str The URL of the embed. timestamp: `datetime.datetime` The timestamp of the embed content. colour: :class:`Colour` or int The colour code of the embed. Aliased to ``color`` as well. Empty A special sentinel value used by ``EmbedProxy`` and this class to denote that the value or attribute is empty. ''' def __init__(self, **kwargs): pass @classmethod def from_data(cls, data): pass @property def colour(self): pass @colour.setter def colour(self): pass @property def timestamp(self): pass @timestamp.setter def timestamp(self): pass @property def footer(self): '''Returns a ``EmbedProxy`` denoting the footer contents. See :meth:`set_footer` for possible values you can access. If the attribute has no value then :attr:`Empty` is returned. ''' pass def set_footer(self, *, text=EmptyEmbed, icon_url=EmptyEmbed): '''Sets the footer for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- text: str The footer text. icon_url: str The URL of the footer icon. Only HTTP(S) is supported. ''' pass @property def image(self): '''Returns a ``EmbedProxy`` denoting the image contents. Possible attributes you can access are: - ``url`` - ``proxy_url`` - ``width`` - ``height`` If the attribute has no value then :attr:`Empty` is returned. ''' pass def set_image(self, *, url): '''Sets the image for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- url: str The source URL for the image. Only HTTP(S) is supported. ''' pass @property def thumbnail(self): '''Returns a ``EmbedProxy`` denoting the thumbnail contents. Possible attributes you can access are: - ``url`` - ``proxy_url`` - ``width`` - ``height`` If the attribute has no value then :attr:`Empty` is returned. ''' pass def set_thumbnail(self, *, url): '''Sets the thumbnail for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- url: str The source URL for the thumbnail. Only HTTP(S) is supported. ''' pass @property def video(self): '''Returns a ``EmbedProxy`` denoting the video contents. Possible attributes include: - ``url`` for the video URL. - ``height`` for the video height. - ``width`` for the video width. If the attribute has no value then :attr:`Empty` is returned. ''' pass @property def provider(self): '''Returns a ``EmbedProxy`` denoting the provider contents. The only attributes that might be accessed are ``name`` and ``url``. If the attribute has no value then :attr:`Empty` is returned. ''' pass @property def author(self): '''Returns a ``EmbedProxy`` denoting the author contents. See :meth:`set_author` for possible values you can access. If the attribute has no value then :attr:`Empty` is returned. ''' pass def set_author(self, *, name, url=EmptyEmbed, icon_url=EmptyEmbed): '''Sets the author for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: str The name of the author. url: str The URL for the author. icon_url: str The URL of the author icon. Only HTTP(S) is supported. ''' pass @property def fields(self): '''Returns a list of ``EmbedProxy`` denoting the field contents. See :meth:`add_field` for possible values you can access. If the attribute has no value then :attr:`Empty` is returned. ''' pass def add_field(self, *, name, value, inline=True): '''Adds a field to the embed object. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: str The name of the field. value: str The value of the field. inline: bool Whether the field should be displayed inline. ''' pass def clear_fields(self): '''Removes all fields from this embed.''' pass def remove_field(self, index): '''Removes a field at a specified index. If the index is invalid or out of bounds then the error is silently swallowed. .. note:: When deleting a field by index, the index of the other fields shift to fill the gap just like a regular list. Parameters ----------- index: int The index of the field to remove. ''' pass def set_field_at(self, index, *, name, value, inline=True): '''Modifies a field to the embed object. The index must point to a valid pre-existing field. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- index: int The index of the field to modify. name: str The name of the field. value: str The value of the field. inline: bool Whether the field should be displayed inline. Raises ------- IndexError An invalid index was provided. ''' pass def to_dict(self): '''Converts this embed object into a dict.''' pass
35
17
16
3
7
6
2
0.91
0
10
3
0
21
11
22
22
425
98
171
59
136
156
140
47
117
9
0
2
47
145,344
LemmoTresto/Webcord
LemmoTresto_Webcord/webcord/errors.py
webcord.errors.HTTPException
class HTTPException(DiscordException): """Exception that's thrown when an HTTP request operation fails. .. attribute:: response The response of the failed HTTP request. This is an instance of `aiohttp.ClientResponse`__. __ http://aiohttp.readthedocs.org/en/stable/client_reference.html#aiohttp.ClientResponse .. attribute:: text The text of the error. Could be an empty string. """ def __init__(self, response, message): self.response = response if type(message) is dict: self.text = message.get('message', '') self.code = message.get('code', 0) else: self.text = message fmt = '{0.reason} (status code: {0.status})' if len(self.text): fmt = fmt + ': {1}' super().__init__(fmt.format(self.response, self.text))
class HTTPException(DiscordException): '''Exception that's thrown when an HTTP request operation fails. .. attribute:: response The response of the failed HTTP request. This is an instance of `aiohttp.ClientResponse`__. __ http://aiohttp.readthedocs.org/en/stable/client_reference.html#aiohttp.ClientResponse .. attribute:: text The text of the error. Could be an empty string. ''' def __init__(self, response, message): pass
2
1
13
2
11
0
3
0.67
1
3
0
2
1
3
1
11
28
8
12
6
10
8
11
6
9
3
4
1
3
145,345
LemmoTresto/Webcord
LemmoTresto_Webcord/webcord/errors.py
webcord.errors.Forbidden
class Forbidden(HTTPException): """Exception that's thrown for when status code 403 occurs. Subclass of :exc:`HTTPException` """ pass
class Forbidden(HTTPException): '''Exception that's thrown for when status code 403 occurs. Subclass of :exc:`HTTPException` ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
11
6
1
2
1
1
3
2
1
1
0
5
0
0
145,346
LemmoTresto/Webcord
LemmoTresto_Webcord/webcord/embed.py
webcord.embed._EmptyEmbed
class _EmptyEmbed: def __bool__(self): return False def __repr__(self): return 'Embed.Empty'
class _EmptyEmbed: def __bool__(self): pass def __repr__(self): pass
3
0
2
0
2
0
1
0
0
0
0
0
2
0
2
2
6
1
5
3
2
0
5
3
2
1
0
0
2
145,347
LemmoTresto/Webcord
LemmoTresto_Webcord/webcord/colour.py
webcord.colour.Colour
class Colour: """Represents a Discord role colour. This class is similar to an (red, green, blue) tuple. There is an alias for this called Color. Supported operations: +-----------+----------------------------------------+ | Operation | Description | +===========+========================================+ | x == y | Checks if two colours are equal. | +-----------+----------------------------------------+ | x != y | Checks if two colours are not equal. | +-----------+----------------------------------------+ | hash(x) | Return the colour's hash. | +-----------+----------------------------------------+ | str(x) | Returns the hex format for the colour. | +-----------+----------------------------------------+ Attributes ------------ value : int The raw integer colour value. """ __slots__ = [ 'value' ] def __init__(self, value): self.value = value def _get_byte(self, byte): return (self.value >> (8 * byte)) & 0xff def __eq__(self, other): return isinstance(other, Colour) and self.value == other.value def __ne__(self, other): return not self.__eq__(other) def __str__(self): return '#{:0>6x}'.format(self.value) def __hash__(self): return hash(self.value) @property def r(self): """Returns the red component of the colour.""" return self._get_byte(2) @property def g(self): """Returns the green component of the colour.""" return self._get_byte(1) @property def b(self): """Returns the blue component of the colour.""" return self._get_byte(0) def to_tuple(self): """Returns an (r, g, b) tuple representing the colour.""" return (self.r, self.g, self.b) @classmethod def default(cls): """A factory method that returns a :class:`Colour` with a value of 0.""" return cls(0) @classmethod def teal(cls): """A factory method that returns a :class:`Colour` with a value of ``0x1abc9c``.""" return cls(0x1abc9c) @classmethod def dark_teal(cls): """A factory method that returns a :class:`Colour` with a value of ``0x11806a``.""" return cls(0x11806a) @classmethod def green(cls): """A factory method that returns a :class:`Colour` with a value of ``0x2ecc71``.""" return cls(0x2ecc71) @classmethod def dark_green(cls): """A factory method that returns a :class:`Colour` with a value of ``0x1f8b4c``.""" return cls(0x1f8b4c) @classmethod def blue(cls): """A factory method that returns a :class:`Colour` with a value of ``0x3498db``.""" return cls(0x3498db) @classmethod def dark_blue(cls): """A factory method that returns a :class:`Colour` with a value of ``0x206694``.""" return cls(0x206694) @classmethod def purple(cls): """A factory method that returns a :class:`Colour` with a value of ``0x9b59b6``.""" return cls(0x9b59b6) @classmethod def dark_purple(cls): """A factory method that returns a :class:`Colour` with a value of ``0x71368a``.""" return cls(0x71368a) @classmethod def magenta(cls): """A factory method that returns a :class:`Colour` with a value of ``0xe91e63``.""" return cls(0xe91e63) @classmethod def dark_magenta(cls): """A factory method that returns a :class:`Colour` with a value of ``0xad1457``.""" return cls(0xad1457) @classmethod def gold(cls): """A factory method that returns a :class:`Colour` with a value of ``0xf1c40f``.""" return cls(0xf1c40f) @classmethod def dark_gold(cls): """A factory method that returns a :class:`Colour` with a value of ``0xc27c0e``.""" return cls(0xc27c0e) @classmethod def orange(cls): """A factory method that returns a :class:`Colour` with a value of ``0xe67e22``.""" return cls(0xe67e22) @classmethod def dark_orange(cls): """A factory method that returns a :class:`Colour` with a value of ``0xa84300``.""" return cls(0xa84300) @classmethod def red(cls): """A factory method that returns a :class:`Colour` with a value of ``0xe74c3c``.""" return cls(0xe74c3c) @classmethod def dark_red(cls): """A factory method that returns a :class:`Colour` with a value of ``0x992d22``.""" return cls(0x992d22) @classmethod def lighter_grey(cls): """A factory method that returns a :class:`Colour` with a value of ``0x95a5a6``.""" return cls(0x95a5a6) @classmethod def dark_grey(cls): """A factory method that returns a :class:`Colour` with a value of ``0x607d8b``.""" return cls(0x607d8b) @classmethod def light_grey(cls): """A factory method that returns a :class:`Colour` with a value of ``0x979c9f``.""" return cls(0x979c9f) @classmethod def darker_grey(cls): """A factory method that returns a :class:`Colour` with a value of ``0x546e7a``.""" return cls(0x546e7a)
class Colour: '''Represents a Discord role colour. This class is similar to an (red, green, blue) tuple. There is an alias for this called Color. Supported operations: +-----------+----------------------------------------+ | Operation | Description | +===========+========================================+ | x == y | Checks if two colours are equal. | +-----------+----------------------------------------+ | x != y | Checks if two colours are not equal. | +-----------+----------------------------------------+ | hash(x) | Return the colour's hash. | +-----------+----------------------------------------+ | str(x) | Returns the hex format for the colour. | +-----------+----------------------------------------+ Attributes ------------ value : int The raw integer colour value. ''' def __init__(self, value): pass def _get_byte(self, byte): pass def __eq__(self, other): pass def __ne__(self, other): pass def __str__(self): pass def __hash__(self): pass @property def r(self): '''Returns the red component of the colour.''' pass @property def g(self): '''Returns the green component of the colour.''' pass @property def b(self): '''Returns the blue component of the colour.''' pass def to_tuple(self): '''Returns an (r, g, b) tuple representing the colour.''' pass @classmethod def default(cls): '''A factory method that returns a :class:`Colour` with a value of 0.''' pass @classmethod def teal(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x1abc9c``.''' pass @classmethod def dark_teal(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x11806a``.''' pass @classmethod def green(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x2ecc71``.''' pass @classmethod def dark_green(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x1f8b4c``.''' pass @classmethod def blue(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x3498db``.''' pass @classmethod def dark_blue(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x206694``.''' pass @classmethod def purple(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x9b59b6``.''' pass @classmethod def dark_purple(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x71368a``.''' pass @classmethod def magenta(cls): '''A factory method that returns a :class:`Colour` with a value of ``0xe91e63``.''' pass @classmethod def dark_magenta(cls): '''A factory method that returns a :class:`Colour` with a value of ``0xad1457``.''' pass @classmethod def gold(cls): '''A factory method that returns a :class:`Colour` with a value of ``0xf1c40f``.''' pass @classmethod def dark_gold(cls): '''A factory method that returns a :class:`Colour` with a value of ``0xc27c0e``.''' pass @classmethod def orange(cls): '''A factory method that returns a :class:`Colour` with a value of ``0xe67e22``.''' pass @classmethod def dark_orange(cls): '''A factory method that returns a :class:`Colour` with a value of ``0xa84300``.''' pass @classmethod def red(cls): '''A factory method that returns a :class:`Colour` with a value of ``0xe74c3c``.''' pass @classmethod def dark_red(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x992d22``.''' pass @classmethod def lighter_grey(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x95a5a6``.''' pass @classmethod def dark_grey(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x607d8b``.''' pass @classmethod def light_grey(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x979c9f``.''' pass @classmethod def darker_grey(cls): '''A factory method that returns a :class:`Colour` with a value of ``0x546e7a``.''' pass
56
26
3
0
2
1
1
0.52
0
0
0
0
10
1
31
31
169
36
88
58
32
46
64
34
32
1
0
0
31