id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
226,400 | ForensicArtifacts/artifacts | artifacts/reader.py | ArtifactsReader.ReadFile | def ReadFile(self, filename):
"""Reads artifact definitions from a file.
Args:
filename (str): name of the file to read from.
Yields:
ArtifactDefinition: an artifact definition.
"""
with io.open(filename, 'r', encoding='utf-8') as file_object:
for artifact_definition in self.ReadFileObject(file_object):
yield artifact_definition | python | def ReadFile(self, filename):
with io.open(filename, 'r', encoding='utf-8') as file_object:
for artifact_definition in self.ReadFileObject(file_object):
yield artifact_definition | [
"def",
"ReadFile",
"(",
"self",
",",
"filename",
")",
":",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"file_object",
":",
"for",
"artifact_definition",
"in",
"self",
".",
"ReadFileObject",
"(",
"fi... | Reads artifact definitions from a file.
Args:
filename (str): name of the file to read from.
Yields:
ArtifactDefinition: an artifact definition. | [
"Reads",
"artifact",
"definitions",
"from",
"a",
"file",
"."
] | 044a63bfb4448af33d085c69066c80f9505ae7ca | https://github.com/ForensicArtifacts/artifacts/blob/044a63bfb4448af33d085c69066c80f9505ae7ca/artifacts/reader.py#L286-L297 |
226,401 | ForensicArtifacts/artifacts | artifacts/writer.py | ArtifactWriter.WriteArtifactsFile | def WriteArtifactsFile(self, artifacts, filename):
"""Writes artifact definitions to a file.
Args:
artifacts (list[ArtifactDefinition]): artifact definitions to be written.
filename (str): name of the file to write artifacts to.
"""
with open(filename, 'w') as file_object:
file_object.write(self.FormatArtifacts(artifacts)) | python | def WriteArtifactsFile(self, artifacts, filename):
with open(filename, 'w') as file_object:
file_object.write(self.FormatArtifacts(artifacts)) | [
"def",
"WriteArtifactsFile",
"(",
"self",
",",
"artifacts",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"file_object",
":",
"file_object",
".",
"write",
"(",
"self",
".",
"FormatArtifacts",
"(",
"artifacts",
")",
")"
... | Writes artifact definitions to a file.
Args:
artifacts (list[ArtifactDefinition]): artifact definitions to be written.
filename (str): name of the file to write artifacts to. | [
"Writes",
"artifact",
"definitions",
"to",
"a",
"file",
"."
] | 044a63bfb4448af33d085c69066c80f9505ae7ca | https://github.com/ForensicArtifacts/artifacts/blob/044a63bfb4448af33d085c69066c80f9505ae7ca/artifacts/writer.py#L58-L66 |
226,402 | ForensicArtifacts/artifacts | artifacts/artifact.py | ArtifactDefinition.AppendSource | def AppendSource(self, type_indicator, attributes):
"""Appends a source.
If you want to implement your own source type you should create a subclass
in source_type.py and change the AppendSource method to handle the new
subclass. This function raises FormatError if an unsupported source type
indicator is encountered.
Args:
type_indicator (str): source type indicator.
attributes (dict[str, object]): source attributes.
Returns:
SourceType: a source type.
Raises:
FormatError: if the type indicator is not set or unsupported,
or if required attributes are missing.
"""
if not type_indicator:
raise errors.FormatError('Missing type indicator.')
try:
source_object = registry.ArtifactDefinitionsRegistry.CreateSourceType(
type_indicator, attributes)
except (AttributeError, TypeError) as exception:
raise errors.FormatError((
'Unable to create source type: {0:s} for artifact definition: {1:s} '
'with error: {2!s}').format(type_indicator, self.name, exception))
self.sources.append(source_object)
return source_object | python | def AppendSource(self, type_indicator, attributes):
if not type_indicator:
raise errors.FormatError('Missing type indicator.')
try:
source_object = registry.ArtifactDefinitionsRegistry.CreateSourceType(
type_indicator, attributes)
except (AttributeError, TypeError) as exception:
raise errors.FormatError((
'Unable to create source type: {0:s} for artifact definition: {1:s} '
'with error: {2!s}').format(type_indicator, self.name, exception))
self.sources.append(source_object)
return source_object | [
"def",
"AppendSource",
"(",
"self",
",",
"type_indicator",
",",
"attributes",
")",
":",
"if",
"not",
"type_indicator",
":",
"raise",
"errors",
".",
"FormatError",
"(",
"'Missing type indicator.'",
")",
"try",
":",
"source_object",
"=",
"registry",
".",
"Artifact... | Appends a source.
If you want to implement your own source type you should create a subclass
in source_type.py and change the AppendSource method to handle the new
subclass. This function raises FormatError if an unsupported source type
indicator is encountered.
Args:
type_indicator (str): source type indicator.
attributes (dict[str, object]): source attributes.
Returns:
SourceType: a source type.
Raises:
FormatError: if the type indicator is not set or unsupported,
or if required attributes are missing. | [
"Appends",
"a",
"source",
"."
] | 044a63bfb4448af33d085c69066c80f9505ae7ca | https://github.com/ForensicArtifacts/artifacts/blob/044a63bfb4448af33d085c69066c80f9505ae7ca/artifacts/artifact.py#L42-L73 |
226,403 | ForensicArtifacts/artifacts | artifacts/artifact.py | ArtifactDefinition.AsDict | def AsDict(self):
"""Represents an artifact as a dictionary.
Returns:
dict[str, object]: artifact attributes.
"""
sources = []
for source in self.sources:
source_definition = {
'type': source.type_indicator,
'attributes': source.AsDict()
}
if source.supported_os:
source_definition['supported_os'] = source.supported_os
if source.conditions:
source_definition['conditions'] = source.conditions
sources.append(source_definition)
artifact_definition = {
'name': self.name,
'doc': self.description,
'sources': sources,
}
if self.labels:
artifact_definition['labels'] = self.labels
if self.supported_os:
artifact_definition['supported_os'] = self.supported_os
if self.provides:
artifact_definition['provides'] = self.provides
if self.conditions:
artifact_definition['conditions'] = self.conditions
if self.urls:
artifact_definition['urls'] = self.urls
return artifact_definition | python | def AsDict(self):
sources = []
for source in self.sources:
source_definition = {
'type': source.type_indicator,
'attributes': source.AsDict()
}
if source.supported_os:
source_definition['supported_os'] = source.supported_os
if source.conditions:
source_definition['conditions'] = source.conditions
sources.append(source_definition)
artifact_definition = {
'name': self.name,
'doc': self.description,
'sources': sources,
}
if self.labels:
artifact_definition['labels'] = self.labels
if self.supported_os:
artifact_definition['supported_os'] = self.supported_os
if self.provides:
artifact_definition['provides'] = self.provides
if self.conditions:
artifact_definition['conditions'] = self.conditions
if self.urls:
artifact_definition['urls'] = self.urls
return artifact_definition | [
"def",
"AsDict",
"(",
"self",
")",
":",
"sources",
"=",
"[",
"]",
"for",
"source",
"in",
"self",
".",
"sources",
":",
"source_definition",
"=",
"{",
"'type'",
":",
"source",
".",
"type_indicator",
",",
"'attributes'",
":",
"source",
".",
"AsDict",
"(",
... | Represents an artifact as a dictionary.
Returns:
dict[str, object]: artifact attributes. | [
"Represents",
"an",
"artifact",
"as",
"a",
"dictionary",
"."
] | 044a63bfb4448af33d085c69066c80f9505ae7ca | https://github.com/ForensicArtifacts/artifacts/blob/044a63bfb4448af33d085c69066c80f9505ae7ca/artifacts/artifact.py#L75-L108 |
226,404 | capless/warrant | warrant/__init__.py | Cognito.renew_access_token | def renew_access_token(self):
"""
Sets a new access token on the User using the refresh token.
"""
auth_params = {'REFRESH_TOKEN': self.refresh_token}
self._add_secret_hash(auth_params, 'SECRET_HASH')
refresh_response = self.client.initiate_auth(
ClientId=self.client_id,
AuthFlow='REFRESH_TOKEN',
AuthParameters=auth_params,
)
self._set_attributes(
refresh_response,
{
'access_token': refresh_response['AuthenticationResult']['AccessToken'],
'id_token': refresh_response['AuthenticationResult']['IdToken'],
'token_type': refresh_response['AuthenticationResult']['TokenType']
}
) | python | def renew_access_token(self):
auth_params = {'REFRESH_TOKEN': self.refresh_token}
self._add_secret_hash(auth_params, 'SECRET_HASH')
refresh_response = self.client.initiate_auth(
ClientId=self.client_id,
AuthFlow='REFRESH_TOKEN',
AuthParameters=auth_params,
)
self._set_attributes(
refresh_response,
{
'access_token': refresh_response['AuthenticationResult']['AccessToken'],
'id_token': refresh_response['AuthenticationResult']['IdToken'],
'token_type': refresh_response['AuthenticationResult']['TokenType']
}
) | [
"def",
"renew_access_token",
"(",
"self",
")",
":",
"auth_params",
"=",
"{",
"'REFRESH_TOKEN'",
":",
"self",
".",
"refresh_token",
"}",
"self",
".",
"_add_secret_hash",
"(",
"auth_params",
",",
"'SECRET_HASH'",
")",
"refresh_response",
"=",
"self",
".",
"client"... | Sets a new access token on the User using the refresh token. | [
"Sets",
"a",
"new",
"access",
"token",
"on",
"the",
"User",
"using",
"the",
"refresh",
"token",
"."
] | ff2e4793d8479e770f2461ef7cbc0c15ee784395 | https://github.com/capless/warrant/blob/ff2e4793d8479e770f2461ef7cbc0c15ee784395/warrant/__init__.py#L546-L565 |
226,405 | capless/warrant | warrant/__init__.py | Cognito.initiate_forgot_password | def initiate_forgot_password(self):
"""
Sends a verification code to the user to use to change their password.
"""
params = {
'ClientId': self.client_id,
'Username': self.username
}
self._add_secret_hash(params, 'SecretHash')
self.client.forgot_password(**params) | python | def initiate_forgot_password(self):
params = {
'ClientId': self.client_id,
'Username': self.username
}
self._add_secret_hash(params, 'SecretHash')
self.client.forgot_password(**params) | [
"def",
"initiate_forgot_password",
"(",
"self",
")",
":",
"params",
"=",
"{",
"'ClientId'",
":",
"self",
".",
"client_id",
",",
"'Username'",
":",
"self",
".",
"username",
"}",
"self",
".",
"_add_secret_hash",
"(",
"params",
",",
"'SecretHash'",
")",
"self",... | Sends a verification code to the user to use to change their password. | [
"Sends",
"a",
"verification",
"code",
"to",
"the",
"user",
"to",
"use",
"to",
"change",
"their",
"password",
"."
] | ff2e4793d8479e770f2461ef7cbc0c15ee784395 | https://github.com/capless/warrant/blob/ff2e4793d8479e770f2461ef7cbc0c15ee784395/warrant/__init__.py#L567-L576 |
226,406 | capless/warrant | warrant/__init__.py | Cognito.change_password | def change_password(self, previous_password, proposed_password):
"""
Change the User password
"""
self.check_token()
response = self.client.change_password(
PreviousPassword=previous_password,
ProposedPassword=proposed_password,
AccessToken=self.access_token
)
self._set_attributes(response, {'password': proposed_password}) | python | def change_password(self, previous_password, proposed_password):
self.check_token()
response = self.client.change_password(
PreviousPassword=previous_password,
ProposedPassword=proposed_password,
AccessToken=self.access_token
)
self._set_attributes(response, {'password': proposed_password}) | [
"def",
"change_password",
"(",
"self",
",",
"previous_password",
",",
"proposed_password",
")",
":",
"self",
".",
"check_token",
"(",
")",
"response",
"=",
"self",
".",
"client",
".",
"change_password",
"(",
"PreviousPassword",
"=",
"previous_password",
",",
"Pr... | Change the User password | [
"Change",
"the",
"User",
"password"
] | ff2e4793d8479e770f2461ef7cbc0c15ee784395 | https://github.com/capless/warrant/blob/ff2e4793d8479e770f2461ef7cbc0c15ee784395/warrant/__init__.py#L609-L619 |
226,407 | capless/warrant | warrant/__init__.py | Cognito._add_secret_hash | def _add_secret_hash(self, parameters, key):
"""
Helper function that computes SecretHash and adds it
to a parameters dictionary at a specified key
"""
if self.client_secret is not None:
secret_hash = AWSSRP.get_secret_hash(self.username, self.client_id,
self.client_secret)
parameters[key] = secret_hash | python | def _add_secret_hash(self, parameters, key):
if self.client_secret is not None:
secret_hash = AWSSRP.get_secret_hash(self.username, self.client_id,
self.client_secret)
parameters[key] = secret_hash | [
"def",
"_add_secret_hash",
"(",
"self",
",",
"parameters",
",",
"key",
")",
":",
"if",
"self",
".",
"client_secret",
"is",
"not",
"None",
":",
"secret_hash",
"=",
"AWSSRP",
".",
"get_secret_hash",
"(",
"self",
".",
"username",
",",
"self",
".",
"client_id"... | Helper function that computes SecretHash and adds it
to a parameters dictionary at a specified key | [
"Helper",
"function",
"that",
"computes",
"SecretHash",
"and",
"adds",
"it",
"to",
"a",
"parameters",
"dictionary",
"at",
"a",
"specified",
"key"
] | ff2e4793d8479e770f2461ef7cbc0c15ee784395 | https://github.com/capless/warrant/blob/ff2e4793d8479e770f2461ef7cbc0c15ee784395/warrant/__init__.py#L621-L629 |
226,408 | capless/warrant | warrant/aws_srp.py | hash_sha256 | def hash_sha256(buf):
"""AuthenticationHelper.hash"""
a = hashlib.sha256(buf).hexdigest()
return (64 - len(a)) * '0' + a | python | def hash_sha256(buf):
a = hashlib.sha256(buf).hexdigest()
return (64 - len(a)) * '0' + a | [
"def",
"hash_sha256",
"(",
"buf",
")",
":",
"a",
"=",
"hashlib",
".",
"sha256",
"(",
"buf",
")",
".",
"hexdigest",
"(",
")",
"return",
"(",
"64",
"-",
"len",
"(",
"a",
")",
")",
"*",
"'0'",
"+",
"a"
] | AuthenticationHelper.hash | [
"AuthenticationHelper",
".",
"hash"
] | ff2e4793d8479e770f2461ef7cbc0c15ee784395 | https://github.com/capless/warrant/blob/ff2e4793d8479e770f2461ef7cbc0c15ee784395/warrant/aws_srp.py#L28-L31 |
226,409 | ranaroussi/pywallet | pywallet/utils/bip32.py | Wallet.create_new_address_for_user | def create_new_address_for_user(self, user_id):
"""Create a new bitcoin address to accept payments for a User.
This is a convenience wrapper around `get_child` that helps you do
the right thing. This method always creates a public, non-prime
address that can be generated from a BIP32 public key on an
insecure server."""
max_id = 0x80000000
if user_id < 0 or user_id > max_id:
raise ValueError(
"Invalid UserID. Must be between 0 and %s" % max_id)
return self.get_child(user_id, is_prime=False, as_private=False) | python | def create_new_address_for_user(self, user_id):
max_id = 0x80000000
if user_id < 0 or user_id > max_id:
raise ValueError(
"Invalid UserID. Must be between 0 and %s" % max_id)
return self.get_child(user_id, is_prime=False, as_private=False) | [
"def",
"create_new_address_for_user",
"(",
"self",
",",
"user_id",
")",
":",
"max_id",
"=",
"0x80000000",
"if",
"user_id",
"<",
"0",
"or",
"user_id",
">",
"max_id",
":",
"raise",
"ValueError",
"(",
"\"Invalid UserID. Must be between 0 and %s\"",
"%",
"max_id",
")"... | Create a new bitcoin address to accept payments for a User.
This is a convenience wrapper around `get_child` that helps you do
the right thing. This method always creates a public, non-prime
address that can be generated from a BIP32 public key on an
insecure server. | [
"Create",
"a",
"new",
"bitcoin",
"address",
"to",
"accept",
"payments",
"for",
"a",
"User",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L177-L188 |
226,410 | ranaroussi/pywallet | pywallet/utils/bip32.py | Wallet.get_child_for_path | def get_child_for_path(self, path):
"""Get a child for a given path.
Rather than repeated calls to get_child, children can be found
by a derivation path. Paths look like:
m/0/1'/10
Which is the same as
self.get_child(0).get_child(-1).get_child(10)
Or, in other words, the 10th publicly derived child of the 1st
privately derived child of the 0th publicly derived child of master.
You can use either ' or p to denote a prime (that is, privately
derived) child.
A child that has had its private key stripped can be requested by
either passing a capital M or appending '.pub' to the end of the path.
These three paths all give the same child that has had its private
key scrubbed:
M/0/1
m/0/1.pub
M/0/1.pub
"""
path = ensure_str(path)
if not path:
raise InvalidPathError("%s is not a valid path" % path)
# Figure out public/private derivation
as_private = True
if path.startswith("M"):
as_private = False
if path.endswith(".pub"):
as_private = False
path = path[:-4]
parts = path.split("/")
if len(parts) == 0:
raise InvalidPathError()
child = self
for part in parts:
if part.lower() == "m":
continue
is_prime = None # Let primeness be figured out by the child number
if part[-1] in "'p":
is_prime = True
part = part.replace("'", "").replace("p", "")
try:
child_number = long_or_int(part)
except ValueError:
raise InvalidPathError("%s is not a valid path" % path)
child = child.get_child(child_number, is_prime)
if not as_private:
return child.public_copy()
return child | python | def get_child_for_path(self, path):
path = ensure_str(path)
if not path:
raise InvalidPathError("%s is not a valid path" % path)
# Figure out public/private derivation
as_private = True
if path.startswith("M"):
as_private = False
if path.endswith(".pub"):
as_private = False
path = path[:-4]
parts = path.split("/")
if len(parts) == 0:
raise InvalidPathError()
child = self
for part in parts:
if part.lower() == "m":
continue
is_prime = None # Let primeness be figured out by the child number
if part[-1] in "'p":
is_prime = True
part = part.replace("'", "").replace("p", "")
try:
child_number = long_or_int(part)
except ValueError:
raise InvalidPathError("%s is not a valid path" % path)
child = child.get_child(child_number, is_prime)
if not as_private:
return child.public_copy()
return child | [
"def",
"get_child_for_path",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"ensure_str",
"(",
"path",
")",
"if",
"not",
"path",
":",
"raise",
"InvalidPathError",
"(",
"\"%s is not a valid path\"",
"%",
"path",
")",
"# Figure out public/private derivation",
"as_... | Get a child for a given path.
Rather than repeated calls to get_child, children can be found
by a derivation path. Paths look like:
m/0/1'/10
Which is the same as
self.get_child(0).get_child(-1).get_child(10)
Or, in other words, the 10th publicly derived child of the 1st
privately derived child of the 0th publicly derived child of master.
You can use either ' or p to denote a prime (that is, privately
derived) child.
A child that has had its private key stripped can be requested by
either passing a capital M or appending '.pub' to the end of the path.
These three paths all give the same child that has had its private
key scrubbed:
M/0/1
m/0/1.pub
M/0/1.pub | [
"Get",
"a",
"child",
"for",
"a",
"given",
"path",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L190-L249 |
226,411 | ranaroussi/pywallet | pywallet/utils/bip32.py | Wallet.public_copy | def public_copy(self):
"""Clone this wallet and strip it of its private information."""
return self.__class__(
chain_code=self.chain_code,
depth=self.depth,
parent_fingerprint=self.parent_fingerprint,
child_number=self.child_number,
public_pair=self.public_key.to_public_pair(),
network=self.network) | python | def public_copy(self):
return self.__class__(
chain_code=self.chain_code,
depth=self.depth,
parent_fingerprint=self.parent_fingerprint,
child_number=self.child_number,
public_pair=self.public_key.to_public_pair(),
network=self.network) | [
"def",
"public_copy",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"chain_code",
"=",
"self",
".",
"chain_code",
",",
"depth",
"=",
"self",
".",
"depth",
",",
"parent_fingerprint",
"=",
"self",
".",
"parent_fingerprint",
",",
"child_number... | Clone this wallet and strip it of its private information. | [
"Clone",
"this",
"wallet",
"and",
"strip",
"it",
"of",
"its",
"private",
"information",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L370-L378 |
226,412 | ranaroussi/pywallet | pywallet/utils/bip32.py | Wallet.serialize | def serialize(self, private=True):
"""Serialize this key.
:param private: Whether or not the serialized key should contain
private information. Set to False for a public-only representation
that cannot spend funds but can create children. You want
private=False if you are, for example, running an e-commerce
website and want to accept bitcoin payments. See the README
for more information.
:type private: bool, defaults to True
See the spec in `deserialize` for more details.
"""
if private and not self.private_key:
raise ValueError("Cannot serialize a public key as private")
if private:
network_version = long_to_hex(
self.network.EXT_SECRET_KEY, 8)
else:
network_version = long_to_hex(
self.network.EXT_PUBLIC_KEY, 8)
depth = long_to_hex(self.depth, 2)
parent_fingerprint = self.parent_fingerprint[2:] # strip leading 0x
child_number = long_to_hex(self.child_number, 8)
chain_code = self.chain_code
ret = (network_version + depth + parent_fingerprint + child_number +
chain_code)
# Private and public serializations are slightly different
if private:
ret += b'00' + self.private_key.get_key()
else:
ret += self.get_public_key_hex(compressed=True)
return ensure_bytes(ret.lower()) | python | def serialize(self, private=True):
if private and not self.private_key:
raise ValueError("Cannot serialize a public key as private")
if private:
network_version = long_to_hex(
self.network.EXT_SECRET_KEY, 8)
else:
network_version = long_to_hex(
self.network.EXT_PUBLIC_KEY, 8)
depth = long_to_hex(self.depth, 2)
parent_fingerprint = self.parent_fingerprint[2:] # strip leading 0x
child_number = long_to_hex(self.child_number, 8)
chain_code = self.chain_code
ret = (network_version + depth + parent_fingerprint + child_number +
chain_code)
# Private and public serializations are slightly different
if private:
ret += b'00' + self.private_key.get_key()
else:
ret += self.get_public_key_hex(compressed=True)
return ensure_bytes(ret.lower()) | [
"def",
"serialize",
"(",
"self",
",",
"private",
"=",
"True",
")",
":",
"if",
"private",
"and",
"not",
"self",
".",
"private_key",
":",
"raise",
"ValueError",
"(",
"\"Cannot serialize a public key as private\"",
")",
"if",
"private",
":",
"network_version",
"=",... | Serialize this key.
:param private: Whether or not the serialized key should contain
private information. Set to False for a public-only representation
that cannot spend funds but can create children. You want
private=False if you are, for example, running an e-commerce
website and want to accept bitcoin payments. See the README
for more information.
:type private: bool, defaults to True
See the spec in `deserialize` for more details. | [
"Serialize",
"this",
"key",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L444-L477 |
226,413 | ranaroussi/pywallet | pywallet/utils/bip32.py | Wallet.serialize_b58 | def serialize_b58(self, private=True):
"""Encode the serialized node in base58."""
return ensure_str(
base58.b58encode_check(unhexlify(self.serialize(private)))) | python | def serialize_b58(self, private=True):
return ensure_str(
base58.b58encode_check(unhexlify(self.serialize(private)))) | [
"def",
"serialize_b58",
"(",
"self",
",",
"private",
"=",
"True",
")",
":",
"return",
"ensure_str",
"(",
"base58",
".",
"b58encode_check",
"(",
"unhexlify",
"(",
"self",
".",
"serialize",
"(",
"private",
")",
")",
")",
")"
] | Encode the serialized node in base58. | [
"Encode",
"the",
"serialized",
"node",
"in",
"base58",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L479-L482 |
226,414 | ranaroussi/pywallet | pywallet/utils/bip32.py | Wallet.to_address | def to_address(self):
"""Create a public address from this Wallet.
Public addresses can accept payments.
https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses
"""
key = unhexlify(self.get_public_key_hex())
# First get the hash160 of the key
hash160_bytes = hash160(key)
# Prepend the network address byte
network_hash160_bytes = \
chr_py2(self.network.PUBKEY_ADDRESS) + hash160_bytes
# Return a base58 encoded address with a checksum
return ensure_str(base58.b58encode_check(network_hash160_bytes)) | python | def to_address(self):
key = unhexlify(self.get_public_key_hex())
# First get the hash160 of the key
hash160_bytes = hash160(key)
# Prepend the network address byte
network_hash160_bytes = \
chr_py2(self.network.PUBKEY_ADDRESS) + hash160_bytes
# Return a base58 encoded address with a checksum
return ensure_str(base58.b58encode_check(network_hash160_bytes)) | [
"def",
"to_address",
"(",
"self",
")",
":",
"key",
"=",
"unhexlify",
"(",
"self",
".",
"get_public_key_hex",
"(",
")",
")",
"# First get the hash160 of the key",
"hash160_bytes",
"=",
"hash160",
"(",
"key",
")",
"# Prepend the network address byte",
"network_hash160_b... | Create a public address from this Wallet.
Public addresses can accept payments.
https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses | [
"Create",
"a",
"public",
"address",
"from",
"this",
"Wallet",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L484-L498 |
226,415 | ranaroussi/pywallet | pywallet/utils/bip32.py | Wallet.deserialize | def deserialize(cls, key, network="bitcoin_testnet"):
"""Load the ExtendedBip32Key from a hex key.
The key consists of
* 4 byte version bytes (network key)
* 1 byte depth:
- 0x00 for master nodes,
- 0x01 for level-1 descendants, ....
* 4 byte fingerprint of the parent's key (0x00000000 if master key)
* 4 byte child number. This is the number i in x_i = x_{par}/i,
with x_i the key being serialized. This is encoded in MSB order.
(0x00000000 if master key)
* 32 bytes: the chain code
* 33 bytes: the public key or private key data
(0x02 + X or 0x03 + X for public keys, 0x00 + k for private keys)
(Note that this also supports 0x04 + X + Y uncompressed points,
but this is totally non-standard and this library won't even
generate such data.)
"""
network = Wallet.get_network(network)
if len(key) in [78, (78 + 32)]:
# we have a byte array, so pass
pass
else:
key = ensure_bytes(key)
if len(key) in [78 * 2, (78 + 32) * 2]:
# we have a hexlified non-base58 key, continue!
key = unhexlify(key)
elif len(key) == 111:
# We have a base58 encoded string
key = base58.b58decode_check(key)
# Now that we double checkd the values, convert back to bytes because
# they're easier to slice
version, depth, parent_fingerprint, child, chain_code, key_data = (
key[:4], key[4], key[5:9], key[9:13], key[13:45], key[45:])
version_long = long_or_int(hexlify(version), 16)
exponent = None
pubkey = None
point_type = key_data[0]
if not isinstance(point_type, six.integer_types):
point_type = ord(point_type)
if point_type == 0:
# Private key
if version_long != network.EXT_SECRET_KEY:
raise incompatible_network_exception_factory(
network.NAME, network.EXT_SECRET_KEY,
version)
exponent = key_data[1:]
elif point_type in [2, 3, 4]:
# Compressed public coordinates
if version_long != network.EXT_PUBLIC_KEY:
raise incompatible_network_exception_factory(
network.NAME, network.EXT_PUBLIC_KEY,
version)
pubkey = PublicKey.from_hex_key(key_data, network=network)
# Even though this was generated from a compressed pubkey, we
# want to store it as an uncompressed pubkey
pubkey.compressed = False
else:
raise ValueError("Invalid key_data prefix, got %s" % point_type)
def l(byte_seq):
if byte_seq is None:
return byte_seq
elif isinstance(byte_seq, six.integer_types):
return byte_seq
return long_or_int(hexlify(byte_seq), 16)
return cls(depth=l(depth),
parent_fingerprint=l(parent_fingerprint),
child_number=l(child),
chain_code=l(chain_code),
private_exponent=l(exponent),
public_key=pubkey,
network=network) | python | def deserialize(cls, key, network="bitcoin_testnet"):
network = Wallet.get_network(network)
if len(key) in [78, (78 + 32)]:
# we have a byte array, so pass
pass
else:
key = ensure_bytes(key)
if len(key) in [78 * 2, (78 + 32) * 2]:
# we have a hexlified non-base58 key, continue!
key = unhexlify(key)
elif len(key) == 111:
# We have a base58 encoded string
key = base58.b58decode_check(key)
# Now that we double checkd the values, convert back to bytes because
# they're easier to slice
version, depth, parent_fingerprint, child, chain_code, key_data = (
key[:4], key[4], key[5:9], key[9:13], key[13:45], key[45:])
version_long = long_or_int(hexlify(version), 16)
exponent = None
pubkey = None
point_type = key_data[0]
if not isinstance(point_type, six.integer_types):
point_type = ord(point_type)
if point_type == 0:
# Private key
if version_long != network.EXT_SECRET_KEY:
raise incompatible_network_exception_factory(
network.NAME, network.EXT_SECRET_KEY,
version)
exponent = key_data[1:]
elif point_type in [2, 3, 4]:
# Compressed public coordinates
if version_long != network.EXT_PUBLIC_KEY:
raise incompatible_network_exception_factory(
network.NAME, network.EXT_PUBLIC_KEY,
version)
pubkey = PublicKey.from_hex_key(key_data, network=network)
# Even though this was generated from a compressed pubkey, we
# want to store it as an uncompressed pubkey
pubkey.compressed = False
else:
raise ValueError("Invalid key_data prefix, got %s" % point_type)
def l(byte_seq):
if byte_seq is None:
return byte_seq
elif isinstance(byte_seq, six.integer_types):
return byte_seq
return long_or_int(hexlify(byte_seq), 16)
return cls(depth=l(depth),
parent_fingerprint=l(parent_fingerprint),
child_number=l(child),
chain_code=l(chain_code),
private_exponent=l(exponent),
public_key=pubkey,
network=network) | [
"def",
"deserialize",
"(",
"cls",
",",
"key",
",",
"network",
"=",
"\"bitcoin_testnet\"",
")",
":",
"network",
"=",
"Wallet",
".",
"get_network",
"(",
"network",
")",
"if",
"len",
"(",
"key",
")",
"in",
"[",
"78",
",",
"(",
"78",
"+",
"32",
")",
"]... | Load the ExtendedBip32Key from a hex key.
The key consists of
* 4 byte version bytes (network key)
* 1 byte depth:
- 0x00 for master nodes,
- 0x01 for level-1 descendants, ....
* 4 byte fingerprint of the parent's key (0x00000000 if master key)
* 4 byte child number. This is the number i in x_i = x_{par}/i,
with x_i the key being serialized. This is encoded in MSB order.
(0x00000000 if master key)
* 32 bytes: the chain code
* 33 bytes: the public key or private key data
(0x02 + X or 0x03 + X for public keys, 0x00 + k for private keys)
(Note that this also supports 0x04 + X + Y uncompressed points,
but this is totally non-standard and this library won't even
generate such data.) | [
"Load",
"the",
"ExtendedBip32Key",
"from",
"a",
"hex",
"key",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L501-L578 |
226,416 | ranaroussi/pywallet | pywallet/utils/bip32.py | Wallet.from_master_secret | def from_master_secret(cls, seed, network="bitcoin_testnet"):
"""Generate a new PrivateKey from a secret key.
:param seed: The key to use to generate this wallet. It may be a long
string. Do not use a phrase from a book or song, as that will
be guessed and is not secure. My advice is to not supply this
argument and let me generate a new random key for you.
See https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format # nopep8
"""
network = Wallet.get_network(network)
seed = ensure_bytes(seed)
# Given a seed S of at least 128 bits, but 256 is advised
# Calculate I = HMAC-SHA512(key="Bitcoin seed", msg=S)
I = hmac.new(b"Bitcoin seed", msg=seed, digestmod=sha512).digest()
# Split I into two 32-byte sequences, IL and IR.
I_L, I_R = I[:32], I[32:]
# Use IL as master secret key, and IR as master chain code.
return cls(private_exponent=long_or_int(hexlify(I_L), 16),
chain_code=long_or_int(hexlify(I_R), 16),
network=network) | python | def from_master_secret(cls, seed, network="bitcoin_testnet"):
network = Wallet.get_network(network)
seed = ensure_bytes(seed)
# Given a seed S of at least 128 bits, but 256 is advised
# Calculate I = HMAC-SHA512(key="Bitcoin seed", msg=S)
I = hmac.new(b"Bitcoin seed", msg=seed, digestmod=sha512).digest()
# Split I into two 32-byte sequences, IL and IR.
I_L, I_R = I[:32], I[32:]
# Use IL as master secret key, and IR as master chain code.
return cls(private_exponent=long_or_int(hexlify(I_L), 16),
chain_code=long_or_int(hexlify(I_R), 16),
network=network) | [
"def",
"from_master_secret",
"(",
"cls",
",",
"seed",
",",
"network",
"=",
"\"bitcoin_testnet\"",
")",
":",
"network",
"=",
"Wallet",
".",
"get_network",
"(",
"network",
")",
"seed",
"=",
"ensure_bytes",
"(",
"seed",
")",
"# Given a seed S of at least 128 bits, bu... | Generate a new PrivateKey from a secret key.
:param seed: The key to use to generate this wallet. It may be a long
string. Do not use a phrase from a book or song, as that will
be guessed and is not secure. My advice is to not supply this
argument and let me generate a new random key for you.
See https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format # nopep8 | [
"Generate",
"a",
"new",
"PrivateKey",
"from",
"a",
"secret",
"key",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L581-L601 |
226,417 | ranaroussi/pywallet | pywallet/utils/bip32.py | Wallet.from_master_secret_slow | def from_master_secret_slow(cls, password, network=BitcoinMainNet):
"""
Generate a new key from a password using 50,000 rounds of HMAC-SHA256.
This should generate the same result as bip32.org.
WARNING: The security of this method has not been evaluated.
"""
# Make sure the password string is bytes
key = ensure_bytes(password)
data = unhexlify(b"0" * 64) # 256-bit 0
for i in range(50000):
data = hmac.new(key, msg=data, digestmod=sha256).digest()
return cls.from_master_secret(data, network) | python | def from_master_secret_slow(cls, password, network=BitcoinMainNet):
# Make sure the password string is bytes
key = ensure_bytes(password)
data = unhexlify(b"0" * 64) # 256-bit 0
for i in range(50000):
data = hmac.new(key, msg=data, digestmod=sha256).digest()
return cls.from_master_secret(data, network) | [
"def",
"from_master_secret_slow",
"(",
"cls",
",",
"password",
",",
"network",
"=",
"BitcoinMainNet",
")",
":",
"# Make sure the password string is bytes",
"key",
"=",
"ensure_bytes",
"(",
"password",
")",
"data",
"=",
"unhexlify",
"(",
"b\"0\"",
"*",
"64",
")",
... | Generate a new key from a password using 50,000 rounds of HMAC-SHA256.
This should generate the same result as bip32.org.
WARNING: The security of this method has not been evaluated. | [
"Generate",
"a",
"new",
"key",
"from",
"a",
"password",
"using",
"50",
"000",
"rounds",
"of",
"HMAC",
"-",
"SHA256",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L604-L617 |
226,418 | ranaroussi/pywallet | pywallet/utils/bip32.py | Wallet.new_random_wallet | def new_random_wallet(cls, user_entropy=None, network=BitcoinMainNet):
"""
Generate a new wallet using a randomly generated 512 bit seed.
Args:
user_entropy: Optional user-supplied entropy which is combined
combined with the random seed, to help counteract compromised
PRNGs.
You are encouraged to add an optional `user_entropy` string to protect
against a compromised CSPRNG. This will be combined with the output
from the CSPRNG. Note that if you do supply this value it only adds
additional entropy and will not be sufficient to recover the random
wallet. If you're even saving `user_entropy` at all, you're doing it
wrong.
"""
seed = str(urandom(64)) # 512/8
# weak extra protection inspired by pybitcointools implementation:
seed += str(int(time.time()*10**6))
if user_entropy:
user_entropy = str(user_entropy) # allow for int/long
seed += user_entropy
return cls.from_master_secret(seed, network=network) | python | def new_random_wallet(cls, user_entropy=None, network=BitcoinMainNet):
seed = str(urandom(64)) # 512/8
# weak extra protection inspired by pybitcointools implementation:
seed += str(int(time.time()*10**6))
if user_entropy:
user_entropy = str(user_entropy) # allow for int/long
seed += user_entropy
return cls.from_master_secret(seed, network=network) | [
"def",
"new_random_wallet",
"(",
"cls",
",",
"user_entropy",
"=",
"None",
",",
"network",
"=",
"BitcoinMainNet",
")",
":",
"seed",
"=",
"str",
"(",
"urandom",
"(",
"64",
")",
")",
"# 512/8",
"# weak extra protection inspired by pybitcointools implementation:",
"seed... | Generate a new wallet using a randomly generated 512 bit seed.
Args:
user_entropy: Optional user-supplied entropy which is combined
combined with the random seed, to help counteract compromised
PRNGs.
You are encouraged to add an optional `user_entropy` string to protect
against a compromised CSPRNG. This will be combined with the output
from the CSPRNG. Note that if you do supply this value it only adds
additional entropy and will not be sufficient to recover the random
wallet. If you're even saving `user_entropy` at all, you're doing it
wrong. | [
"Generate",
"a",
"new",
"wallet",
"using",
"a",
"randomly",
"generated",
"512",
"bit",
"seed",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L677-L699 |
226,419 | ranaroussi/pywallet | pywallet/utils/ethereum.py | get_bytes | def get_bytes(s):
"""Returns the byte representation of a hex- or byte-string."""
if isinstance(s, bytes):
b = s
elif isinstance(s, str):
b = bytes.fromhex(s)
else:
raise TypeError("s must be either 'bytes' or 'str'!")
return b | python | def get_bytes(s):
if isinstance(s, bytes):
b = s
elif isinstance(s, str):
b = bytes.fromhex(s)
else:
raise TypeError("s must be either 'bytes' or 'str'!")
return b | [
"def",
"get_bytes",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"b",
"=",
"s",
"elif",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"b",
"=",
"bytes",
".",
"fromhex",
"(",
"s",
")",
"else",
":",
"raise",
"TypeErro... | Returns the byte representation of a hex- or byte-string. | [
"Returns",
"the",
"byte",
"representation",
"of",
"a",
"hex",
"-",
"or",
"byte",
"-",
"string",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L37-L46 |
226,420 | ranaroussi/pywallet | pywallet/utils/ethereum.py | PrivateKey.from_b58check | def from_b58check(private_key):
""" Decodes a Base58Check encoded private-key.
Args:
private_key (str): A Base58Check encoded private key.
Returns:
PrivateKey: A PrivateKey object
"""
b58dec = base58.b58decode_check(private_key)
version = b58dec[0]
assert version in [PrivateKey.TESTNET_VERSION,
PrivateKey.MAINNET_VERSION]
return PrivateKey(int.from_bytes(b58dec[1:], 'big')) | python | def from_b58check(private_key):
b58dec = base58.b58decode_check(private_key)
version = b58dec[0]
assert version in [PrivateKey.TESTNET_VERSION,
PrivateKey.MAINNET_VERSION]
return PrivateKey(int.from_bytes(b58dec[1:], 'big')) | [
"def",
"from_b58check",
"(",
"private_key",
")",
":",
"b58dec",
"=",
"base58",
".",
"b58decode_check",
"(",
"private_key",
")",
"version",
"=",
"b58dec",
"[",
"0",
"]",
"assert",
"version",
"in",
"[",
"PrivateKey",
".",
"TESTNET_VERSION",
",",
"PrivateKey",
... | Decodes a Base58Check encoded private-key.
Args:
private_key (str): A Base58Check encoded private key.
Returns:
PrivateKey: A PrivateKey object | [
"Decodes",
"a",
"Base58Check",
"encoded",
"private",
"-",
"key",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L350-L364 |
226,421 | ranaroussi/pywallet | pywallet/utils/ethereum.py | PrivateKey.to_b58check | def to_b58check(self, testnet=False):
""" Generates a Base58Check encoding of this private key.
Returns:
str: A Base58Check encoded string representing the key.
"""
version = self.TESTNET_VERSION if testnet else self.MAINNET_VERSION
return base58.b58encode_check(bytes([version]) + bytes(self)) | python | def to_b58check(self, testnet=False):
version = self.TESTNET_VERSION if testnet else self.MAINNET_VERSION
return base58.b58encode_check(bytes([version]) + bytes(self)) | [
"def",
"to_b58check",
"(",
"self",
",",
"testnet",
"=",
"False",
")",
":",
"version",
"=",
"self",
".",
"TESTNET_VERSION",
"if",
"testnet",
"else",
"self",
".",
"MAINNET_VERSION",
"return",
"base58",
".",
"b58encode_check",
"(",
"bytes",
"(",
"[",
"version",... | Generates a Base58Check encoding of this private key.
Returns:
str: A Base58Check encoded string representing the key. | [
"Generates",
"a",
"Base58Check",
"encoding",
"of",
"this",
"private",
"key",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L495-L502 |
226,422 | ranaroussi/pywallet | pywallet/utils/ethereum.py | PublicKey.from_int | def from_int(i):
""" Generates a public key object from an integer.
Note:
This assumes that the upper 32 bytes of the integer
are the x component of the public key point and the
lower 32 bytes are the y component.
Args:
i (Bignum): A 512-bit integer representing the public
key point on the secp256k1 curve.
Returns:
PublicKey: A PublicKey object.
"""
point = ECPointAffine.from_int(bitcoin_curve, i)
return PublicKey.from_point(point) | python | def from_int(i):
point = ECPointAffine.from_int(bitcoin_curve, i)
return PublicKey.from_point(point) | [
"def",
"from_int",
"(",
"i",
")",
":",
"point",
"=",
"ECPointAffine",
".",
"from_int",
"(",
"bitcoin_curve",
",",
"i",
")",
"return",
"PublicKey",
".",
"from_point",
"(",
"point",
")"
] | Generates a public key object from an integer.
Note:
This assumes that the upper 32 bytes of the integer
are the x component of the public key point and the
lower 32 bytes are the y component.
Args:
i (Bignum): A 512-bit integer representing the public
key point on the secp256k1 curve.
Returns:
PublicKey: A PublicKey object. | [
"Generates",
"a",
"public",
"key",
"object",
"from",
"an",
"integer",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L543-L559 |
226,423 | ranaroussi/pywallet | pywallet/utils/ethereum.py | PublicKey.from_signature | def from_signature(message, signature):
""" Attempts to create PublicKey object by deriving it
from the message and signature.
Args:
message (bytes): The message to be verified.
signature (Signature): The signature for message.
The recovery_id must not be None!
Returns:
PublicKey:
A PublicKey object derived from the
signature, it it exists. None otherwise.
"""
if signature.recovery_id is None:
raise ValueError("The signature must have a recovery_id.")
msg = get_bytes(message)
pub_keys = bitcoin_curve.recover_public_key(msg,
signature,
signature.recovery_id)
for k, recid in pub_keys:
if signature.recovery_id is not None and recid == signature.recovery_id:
return PublicKey(k.x, k.y)
return None | python | def from_signature(message, signature):
if signature.recovery_id is None:
raise ValueError("The signature must have a recovery_id.")
msg = get_bytes(message)
pub_keys = bitcoin_curve.recover_public_key(msg,
signature,
signature.recovery_id)
for k, recid in pub_keys:
if signature.recovery_id is not None and recid == signature.recovery_id:
return PublicKey(k.x, k.y)
return None | [
"def",
"from_signature",
"(",
"message",
",",
"signature",
")",
":",
"if",
"signature",
".",
"recovery_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"The signature must have a recovery_id.\"",
")",
"msg",
"=",
"get_bytes",
"(",
"message",
")",
"pub_keys",
... | Attempts to create PublicKey object by deriving it
from the message and signature.
Args:
message (bytes): The message to be verified.
signature (Signature): The signature for message.
The recovery_id must not be None!
Returns:
PublicKey:
A PublicKey object derived from the
signature, it it exists. None otherwise. | [
"Attempts",
"to",
"create",
"PublicKey",
"object",
"by",
"deriving",
"it",
"from",
"the",
"message",
"and",
"signature",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L638-L664 |
226,424 | ranaroussi/pywallet | pywallet/utils/ethereum.py | Signature.from_der | def from_der(der):
""" Decodes a Signature that was DER-encoded.
Args:
der (bytes or str): The DER encoding to be decoded.
Returns:
Signature: The deserialized signature.
"""
d = get_bytes(der)
# d must conform to (from btcd):
# [0 ] 0x30 - ASN.1 identifier for sequence
# [1 ] <1-byte> - total remaining length
# [2 ] 0x02 - ASN.1 identifier to specify an integer follows
# [3 ] <1-byte> - length of R
# [4.] <bytes> - R
# [..] 0x02 - ASN.1 identifier to specify an integer follows
# [..] <1-byte> - length of S
# [..] <bytes> - S
# 6 bytes + R (min. 1 byte) + S (min. 1 byte)
if len(d) < 8:
raise ValueError("DER signature string is too short.")
# 6 bytes + R (max. 33 bytes) + S (max. 33 bytes)
if len(d) > 72:
raise ValueError("DER signature string is too long.")
if d[0] != 0x30:
raise ValueError("DER signature does not start with 0x30.")
if d[1] != len(d[2:]):
raise ValueError("DER signature length incorrect.")
total_length = d[1]
if d[2] != 0x02:
raise ValueError("DER signature no 1st int marker.")
if d[3] <= 0 or d[3] > (total_length - 7):
raise ValueError("DER signature incorrect R length.")
# Grab R, check for errors
rlen = d[3]
s_magic_index = 4 + rlen
rb = d[4:s_magic_index]
if rb[0] & 0x80 != 0:
raise ValueError("DER signature R is negative.")
if len(rb) > 1 and rb[0] == 0 and rb[1] & 0x80 != 0x80:
raise ValueError("DER signature R is excessively padded.")
r = int.from_bytes(rb, 'big')
# Grab S, check for errors
if d[s_magic_index] != 0x02:
raise ValueError("DER signature no 2nd int marker.")
slen_index = s_magic_index + 1
slen = d[slen_index]
if slen <= 0 or slen > len(d) - (slen_index + 1):
raise ValueError("DER signature incorrect S length.")
sb = d[slen_index + 1:]
if sb[0] & 0x80 != 0:
raise ValueError("DER signature S is negative.")
if len(sb) > 1 and sb[0] == 0 and sb[1] & 0x80 != 0x80:
raise ValueError("DER signature S is excessively padded.")
s = int.from_bytes(sb, 'big')
if r < 1 or r >= bitcoin_curve.n:
raise ValueError("DER signature R is not between 1 and N - 1.")
if s < 1 or s >= bitcoin_curve.n:
raise ValueError("DER signature S is not between 1 and N - 1.")
return Signature(r, s) | python | def from_der(der):
d = get_bytes(der)
# d must conform to (from btcd):
# [0 ] 0x30 - ASN.1 identifier for sequence
# [1 ] <1-byte> - total remaining length
# [2 ] 0x02 - ASN.1 identifier to specify an integer follows
# [3 ] <1-byte> - length of R
# [4.] <bytes> - R
# [..] 0x02 - ASN.1 identifier to specify an integer follows
# [..] <1-byte> - length of S
# [..] <bytes> - S
# 6 bytes + R (min. 1 byte) + S (min. 1 byte)
if len(d) < 8:
raise ValueError("DER signature string is too short.")
# 6 bytes + R (max. 33 bytes) + S (max. 33 bytes)
if len(d) > 72:
raise ValueError("DER signature string is too long.")
if d[0] != 0x30:
raise ValueError("DER signature does not start with 0x30.")
if d[1] != len(d[2:]):
raise ValueError("DER signature length incorrect.")
total_length = d[1]
if d[2] != 0x02:
raise ValueError("DER signature no 1st int marker.")
if d[3] <= 0 or d[3] > (total_length - 7):
raise ValueError("DER signature incorrect R length.")
# Grab R, check for errors
rlen = d[3]
s_magic_index = 4 + rlen
rb = d[4:s_magic_index]
if rb[0] & 0x80 != 0:
raise ValueError("DER signature R is negative.")
if len(rb) > 1 and rb[0] == 0 and rb[1] & 0x80 != 0x80:
raise ValueError("DER signature R is excessively padded.")
r = int.from_bytes(rb, 'big')
# Grab S, check for errors
if d[s_magic_index] != 0x02:
raise ValueError("DER signature no 2nd int marker.")
slen_index = s_magic_index + 1
slen = d[slen_index]
if slen <= 0 or slen > len(d) - (slen_index + 1):
raise ValueError("DER signature incorrect S length.")
sb = d[slen_index + 1:]
if sb[0] & 0x80 != 0:
raise ValueError("DER signature S is negative.")
if len(sb) > 1 and sb[0] == 0 and sb[1] & 0x80 != 0x80:
raise ValueError("DER signature S is excessively padded.")
s = int.from_bytes(sb, 'big')
if r < 1 or r >= bitcoin_curve.n:
raise ValueError("DER signature R is not between 1 and N - 1.")
if s < 1 or s >= bitcoin_curve.n:
raise ValueError("DER signature S is not between 1 and N - 1.")
return Signature(r, s) | [
"def",
"from_der",
"(",
"der",
")",
":",
"d",
"=",
"get_bytes",
"(",
"der",
")",
"# d must conform to (from btcd):",
"# [0 ] 0x30 - ASN.1 identifier for sequence",
"# [1 ] <1-byte> - total remaining length",
"# [2 ] 0x02 - ASN.1 identifier to specify an integer follows",
"... | Decodes a Signature that was DER-encoded.
Args:
der (bytes or str): The DER encoding to be decoded.
Returns:
Signature: The deserialized signature. | [
"Decodes",
"a",
"Signature",
"that",
"was",
"DER",
"-",
"encoded",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L810-L882 |
226,425 | ranaroussi/pywallet | pywallet/utils/ethereum.py | Signature.from_bytes | def from_bytes(b):
""" Extracts the r and s components from a byte string.
Args:
b (bytes): A 64-byte long string. The first 32 bytes are
extracted as the r component and the second 32 bytes
are extracted as the s component.
Returns:
Signature: A Signature object.
Raises:
ValueError: If signature is incorrect length
"""
if len(b) != 64:
raise ValueError("from_bytes: Signature length != 64.")
r = int.from_bytes(b[0:32], 'big')
s = int.from_bytes(b[32:64], 'big')
return Signature(r, s) | python | def from_bytes(b):
if len(b) != 64:
raise ValueError("from_bytes: Signature length != 64.")
r = int.from_bytes(b[0:32], 'big')
s = int.from_bytes(b[32:64], 'big')
return Signature(r, s) | [
"def",
"from_bytes",
"(",
"b",
")",
":",
"if",
"len",
"(",
"b",
")",
"!=",
"64",
":",
"raise",
"ValueError",
"(",
"\"from_bytes: Signature length != 64.\"",
")",
"r",
"=",
"int",
".",
"from_bytes",
"(",
"b",
"[",
"0",
":",
"32",
"]",
",",
"'big'",
")... | Extracts the r and s components from a byte string.
Args:
b (bytes): A 64-byte long string. The first 32 bytes are
extracted as the r component and the second 32 bytes
are extracted as the s component.
Returns:
Signature: A Signature object.
Raises:
ValueError: If signature is incorrect length | [
"Extracts",
"the",
"r",
"and",
"s",
"components",
"from",
"a",
"byte",
"string",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L897-L915 |
226,426 | ranaroussi/pywallet | pywallet/utils/ethereum.py | Signature.to_der | def to_der(self):
""" Encodes this signature using DER
Returns:
bytes: The DER encoding of (self.r, self.s).
"""
# Output should be:
# 0x30 <length> 0x02 <length r> r 0x02 <length s> s
r, s = self._canonicalize()
total_length = 6 + len(r) + len(s)
der = bytes([0x30, total_length - 2, 0x02, len(r)]) + r + bytes([0x02, len(s)]) + s
return der | python | def to_der(self):
# Output should be:
# 0x30 <length> 0x02 <length r> r 0x02 <length s> s
r, s = self._canonicalize()
total_length = 6 + len(r) + len(s)
der = bytes([0x30, total_length - 2, 0x02, len(r)]) + r + bytes([0x02, len(s)]) + s
return der | [
"def",
"to_der",
"(",
"self",
")",
":",
"# Output should be:",
"# 0x30 <length> 0x02 <length r> r 0x02 <length s> s",
"r",
",",
"s",
"=",
"self",
".",
"_canonicalize",
"(",
")",
"total_length",
"=",
"6",
"+",
"len",
"(",
"r",
")",
"+",
"len",
"(",
"s",
")",
... | Encodes this signature using DER
Returns:
bytes: The DER encoding of (self.r, self.s). | [
"Encodes",
"this",
"signature",
"using",
"DER"
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L969-L981 |
226,427 | ranaroussi/pywallet | pywallet/utils/ethereum.py | HDKey.from_bytes | def from_bytes(b):
""" Generates either a HDPrivateKey or HDPublicKey from the underlying
bytes.
The serialization must conform to the description in:
https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#serialization-format
Args:
b (bytes): A byte stream conforming to the above.
Returns:
HDPrivateKey or HDPublicKey:
Either an HD private or
public key object, depending on what was serialized.
"""
if len(b) < 78:
raise ValueError("b must be at least 78 bytes long.")
version = int.from_bytes(b[:4], 'big')
depth = b[4]
parent_fingerprint = b[5:9]
index = int.from_bytes(b[9:13], 'big')
chain_code = b[13:45]
key_bytes = b[45:78]
rv = None
if version == HDPrivateKey.MAINNET_VERSION or version == HDPrivateKey.TESTNET_VERSION:
if key_bytes[0] != 0:
raise ValueError("First byte of private key must be 0x00!")
private_key = int.from_bytes(key_bytes[1:], 'big')
rv = HDPrivateKey(key=private_key,
chain_code=chain_code,
index=index,
depth=depth,
parent_fingerprint=parent_fingerprint)
elif version == HDPublicKey.MAINNET_VERSION or version == HDPublicKey.TESTNET_VERSION:
if key_bytes[0] != 0x02 and key_bytes[0] != 0x03:
raise ValueError("First byte of public key must be 0x02 or 0x03!")
public_key = PublicKey.from_bytes(key_bytes)
rv = HDPublicKey(x=public_key.point.x,
y=public_key.point.y,
chain_code=chain_code,
index=index,
depth=depth,
parent_fingerprint=parent_fingerprint)
else:
raise ValueError("incorrect encoding.")
return rv | python | def from_bytes(b):
if len(b) < 78:
raise ValueError("b must be at least 78 bytes long.")
version = int.from_bytes(b[:4], 'big')
depth = b[4]
parent_fingerprint = b[5:9]
index = int.from_bytes(b[9:13], 'big')
chain_code = b[13:45]
key_bytes = b[45:78]
rv = None
if version == HDPrivateKey.MAINNET_VERSION or version == HDPrivateKey.TESTNET_VERSION:
if key_bytes[0] != 0:
raise ValueError("First byte of private key must be 0x00!")
private_key = int.from_bytes(key_bytes[1:], 'big')
rv = HDPrivateKey(key=private_key,
chain_code=chain_code,
index=index,
depth=depth,
parent_fingerprint=parent_fingerprint)
elif version == HDPublicKey.MAINNET_VERSION or version == HDPublicKey.TESTNET_VERSION:
if key_bytes[0] != 0x02 and key_bytes[0] != 0x03:
raise ValueError("First byte of public key must be 0x02 or 0x03!")
public_key = PublicKey.from_bytes(key_bytes)
rv = HDPublicKey(x=public_key.point.x,
y=public_key.point.y,
chain_code=chain_code,
index=index,
depth=depth,
parent_fingerprint=parent_fingerprint)
else:
raise ValueError("incorrect encoding.")
return rv | [
"def",
"from_bytes",
"(",
"b",
")",
":",
"if",
"len",
"(",
"b",
")",
"<",
"78",
":",
"raise",
"ValueError",
"(",
"\"b must be at least 78 bytes long.\"",
")",
"version",
"=",
"int",
".",
"from_bytes",
"(",
"b",
"[",
":",
"4",
"]",
",",
"'big'",
")",
... | Generates either a HDPrivateKey or HDPublicKey from the underlying
bytes.
The serialization must conform to the description in:
https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#serialization-format
Args:
b (bytes): A byte stream conforming to the above.
Returns:
HDPrivateKey or HDPublicKey:
Either an HD private or
public key object, depending on what was serialized. | [
"Generates",
"either",
"a",
"HDPrivateKey",
"or",
"HDPublicKey",
"from",
"the",
"underlying",
"bytes",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L1039-L1089 |
226,428 | ranaroussi/pywallet | pywallet/utils/ethereum.py | HDKey.to_b58check | def to_b58check(self, testnet=False):
""" Generates a Base58Check encoding of this key.
Args:
testnet (bool): True if the key is to be used with
testnet, False otherwise.
Returns:
str: A Base58Check encoded string representing the key.
"""
b = self.testnet_bytes if testnet else bytes(self)
return base58.b58encode_check(b) | python | def to_b58check(self, testnet=False):
b = self.testnet_bytes if testnet else bytes(self)
return base58.b58encode_check(b) | [
"def",
"to_b58check",
"(",
"self",
",",
"testnet",
"=",
"False",
")",
":",
"b",
"=",
"self",
".",
"testnet_bytes",
"if",
"testnet",
"else",
"bytes",
"(",
"self",
")",
"return",
"base58",
".",
"b58encode_check",
"(",
"b",
")"
] | Generates a Base58Check encoding of this key.
Args:
testnet (bool): True if the key is to be used with
testnet, False otherwise.
Returns:
str: A Base58Check encoded string representing the key. | [
"Generates",
"a",
"Base58Check",
"encoding",
"of",
"this",
"key",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L1220-L1230 |
226,429 | ranaroussi/pywallet | pywallet/utils/ethereum.py | HDPrivateKey.master_key_from_entropy | def master_key_from_entropy(passphrase='', strength=128):
""" Generates a master key from system entropy.
Args:
strength (int): Amount of entropy desired. This should be
a multiple of 32 between 128 and 256.
passphrase (str): An optional passphrase for the generated
mnemonic string.
Returns:
HDPrivateKey, str:
a tuple consisting of the master
private key and a mnemonic string from which the seed
can be recovered.
"""
if strength % 32 != 0:
raise ValueError("strength must be a multiple of 32")
if strength < 128 or strength > 256:
raise ValueError("strength should be >= 128 and <= 256")
entropy = rand_bytes(strength // 8)
m = Mnemonic(language='english')
n = m.to_mnemonic(entropy)
return HDPrivateKey.master_key_from_seed(
Mnemonic.to_seed(n, passphrase)), n | python | def master_key_from_entropy(passphrase='', strength=128):
if strength % 32 != 0:
raise ValueError("strength must be a multiple of 32")
if strength < 128 or strength > 256:
raise ValueError("strength should be >= 128 and <= 256")
entropy = rand_bytes(strength // 8)
m = Mnemonic(language='english')
n = m.to_mnemonic(entropy)
return HDPrivateKey.master_key_from_seed(
Mnemonic.to_seed(n, passphrase)), n | [
"def",
"master_key_from_entropy",
"(",
"passphrase",
"=",
"''",
",",
"strength",
"=",
"128",
")",
":",
"if",
"strength",
"%",
"32",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"strength must be a multiple of 32\"",
")",
"if",
"strength",
"<",
"128",
"or",
... | Generates a master key from system entropy.
Args:
strength (int): Amount of entropy desired. This should be
a multiple of 32 between 128 and 256.
passphrase (str): An optional passphrase for the generated
mnemonic string.
Returns:
HDPrivateKey, str:
a tuple consisting of the master
private key and a mnemonic string from which the seed
can be recovered. | [
"Generates",
"a",
"master",
"key",
"from",
"system",
"entropy",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L1301-L1324 |
226,430 | ranaroussi/pywallet | pywallet/utils/ethereum.py | HDPrivateKey.master_key_from_seed | def master_key_from_seed(seed):
""" Generates a master key from a provided seed.
Args:
seed (bytes or str): a string of bytes or a hex string
Returns:
HDPrivateKey: the master private key.
"""
S = get_bytes(seed)
I = hmac.new(b"Bitcoin seed", S, hashlib.sha512).digest()
Il, Ir = I[:32], I[32:]
parse_Il = int.from_bytes(Il, 'big')
if parse_Il == 0 or parse_Il >= bitcoin_curve.n:
raise ValueError("Bad seed, resulting in invalid key!")
return HDPrivateKey(key=parse_Il, chain_code=Ir, index=0, depth=0) | python | def master_key_from_seed(seed):
S = get_bytes(seed)
I = hmac.new(b"Bitcoin seed", S, hashlib.sha512).digest()
Il, Ir = I[:32], I[32:]
parse_Il = int.from_bytes(Il, 'big')
if parse_Il == 0 or parse_Il >= bitcoin_curve.n:
raise ValueError("Bad seed, resulting in invalid key!")
return HDPrivateKey(key=parse_Il, chain_code=Ir, index=0, depth=0) | [
"def",
"master_key_from_seed",
"(",
"seed",
")",
":",
"S",
"=",
"get_bytes",
"(",
"seed",
")",
"I",
"=",
"hmac",
".",
"new",
"(",
"b\"Bitcoin seed\"",
",",
"S",
",",
"hashlib",
".",
"sha512",
")",
".",
"digest",
"(",
")",
"Il",
",",
"Ir",
"=",
"I",... | Generates a master key from a provided seed.
Args:
seed (bytes or str): a string of bytes or a hex string
Returns:
HDPrivateKey: the master private key. | [
"Generates",
"a",
"master",
"key",
"from",
"a",
"provided",
"seed",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L1327-L1343 |
226,431 | ranaroussi/pywallet | pywallet/utils/ethereum.py | HDPrivateKey.from_parent | def from_parent(parent_key, i):
""" Derives a child private key from a parent
private key. It is not possible to derive a child
private key from a public parent key.
Args:
parent_private_key (HDPrivateKey):
"""
if not isinstance(parent_key, HDPrivateKey):
raise TypeError("parent_key must be an HDPrivateKey object.")
hmac_key = parent_key.chain_code
if i & 0x80000000:
hmac_data = b'\x00' + bytes(parent_key._key) + i.to_bytes(length=4, byteorder='big')
else:
hmac_data = parent_key.public_key.compressed_bytes + i.to_bytes(length=4, byteorder='big')
I = hmac.new(hmac_key, hmac_data, hashlib.sha512).digest()
Il, Ir = I[:32], I[32:]
parse_Il = int.from_bytes(Il, 'big')
if parse_Il >= bitcoin_curve.n:
return None
child_key = (parse_Il + parent_key._key.key) % bitcoin_curve.n
if child_key == 0:
# Incredibly unlucky choice
return None
child_depth = parent_key.depth + 1
return HDPrivateKey(key=child_key,
chain_code=Ir,
index=i,
depth=child_depth,
parent_fingerprint=parent_key.fingerprint) | python | def from_parent(parent_key, i):
if not isinstance(parent_key, HDPrivateKey):
raise TypeError("parent_key must be an HDPrivateKey object.")
hmac_key = parent_key.chain_code
if i & 0x80000000:
hmac_data = b'\x00' + bytes(parent_key._key) + i.to_bytes(length=4, byteorder='big')
else:
hmac_data = parent_key.public_key.compressed_bytes + i.to_bytes(length=4, byteorder='big')
I = hmac.new(hmac_key, hmac_data, hashlib.sha512).digest()
Il, Ir = I[:32], I[32:]
parse_Il = int.from_bytes(Il, 'big')
if parse_Il >= bitcoin_curve.n:
return None
child_key = (parse_Il + parent_key._key.key) % bitcoin_curve.n
if child_key == 0:
# Incredibly unlucky choice
return None
child_depth = parent_key.depth + 1
return HDPrivateKey(key=child_key,
chain_code=Ir,
index=i,
depth=child_depth,
parent_fingerprint=parent_key.fingerprint) | [
"def",
"from_parent",
"(",
"parent_key",
",",
"i",
")",
":",
"if",
"not",
"isinstance",
"(",
"parent_key",
",",
"HDPrivateKey",
")",
":",
"raise",
"TypeError",
"(",
"\"parent_key must be an HDPrivateKey object.\"",
")",
"hmac_key",
"=",
"parent_key",
".",
"chain_c... | Derives a child private key from a parent
private key. It is not possible to derive a child
private key from a public parent key.
Args:
parent_private_key (HDPrivateKey): | [
"Derives",
"a",
"child",
"private",
"key",
"from",
"a",
"parent",
"private",
"key",
".",
"It",
"is",
"not",
"possible",
"to",
"derive",
"a",
"child",
"private",
"key",
"from",
"a",
"public",
"parent",
"key",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/ethereum.py#L1346-L1381 |
226,432 | ranaroussi/pywallet | pywallet/utils/utils.py | is_hex_string | def is_hex_string(string):
"""Check if the string is only composed of hex characters."""
pattern = re.compile(r'[A-Fa-f0-9]+')
if isinstance(string, six.binary_type):
string = str(string)
return pattern.match(string) is not None | python | def is_hex_string(string):
pattern = re.compile(r'[A-Fa-f0-9]+')
if isinstance(string, six.binary_type):
string = str(string)
return pattern.match(string) is not None | [
"def",
"is_hex_string",
"(",
"string",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'[A-Fa-f0-9]+'",
")",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"binary_type",
")",
":",
"string",
"=",
"str",
"(",
"string",
")",
"return",
"pattern"... | Check if the string is only composed of hex characters. | [
"Check",
"if",
"the",
"string",
"is",
"only",
"composed",
"of",
"hex",
"characters",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/utils.py#L39-L44 |
226,433 | ranaroussi/pywallet | pywallet/utils/utils.py | long_to_hex | def long_to_hex(l, size):
"""Encode a long value as a hex string, 0-padding to size.
Note that size is the size of the resulting hex string. So, for a 32Byte
long size should be 64 (two hex characters per byte"."""
f_str = "{0:0%sx}" % size
return ensure_bytes(f_str.format(l).lower()) | python | def long_to_hex(l, size):
f_str = "{0:0%sx}" % size
return ensure_bytes(f_str.format(l).lower()) | [
"def",
"long_to_hex",
"(",
"l",
",",
"size",
")",
":",
"f_str",
"=",
"\"{0:0%sx}\"",
"%",
"size",
"return",
"ensure_bytes",
"(",
"f_str",
".",
"format",
"(",
"l",
")",
".",
"lower",
"(",
")",
")"
] | Encode a long value as a hex string, 0-padding to size.
Note that size is the size of the resulting hex string. So, for a 32Byte
long size should be 64 (two hex characters per byte". | [
"Encode",
"a",
"long",
"value",
"as",
"a",
"hex",
"string",
"0",
"-",
"padding",
"to",
"size",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/utils.py#L47-L53 |
226,434 | ranaroussi/pywallet | pywallet/utils/keys.py | PrivateKey.get_public_key | def get_public_key(self):
"""Get the PublicKey for this PrivateKey."""
return PublicKey.from_verifying_key(
self._private_key.get_verifying_key(),
network=self.network, compressed=self.compressed) | python | def get_public_key(self):
return PublicKey.from_verifying_key(
self._private_key.get_verifying_key(),
network=self.network, compressed=self.compressed) | [
"def",
"get_public_key",
"(",
"self",
")",
":",
"return",
"PublicKey",
".",
"from_verifying_key",
"(",
"self",
".",
"_private_key",
".",
"get_verifying_key",
"(",
")",
",",
"network",
"=",
"self",
".",
"network",
",",
"compressed",
"=",
"self",
".",
"compres... | Get the PublicKey for this PrivateKey. | [
"Get",
"the",
"PublicKey",
"for",
"this",
"PrivateKey",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/keys.py#L63-L67 |
226,435 | ranaroussi/pywallet | pywallet/utils/keys.py | PrivateKey.get_extended_key | def get_extended_key(self):
"""Get the extended key.
Extended keys contain the network bytes and the public or private
key.
"""
network_hex_chars = hexlify(
chr_py2(self.network.SECRET_KEY))
return ensure_bytes(network_hex_chars + self.get_key()) | python | def get_extended_key(self):
network_hex_chars = hexlify(
chr_py2(self.network.SECRET_KEY))
return ensure_bytes(network_hex_chars + self.get_key()) | [
"def",
"get_extended_key",
"(",
"self",
")",
":",
"network_hex_chars",
"=",
"hexlify",
"(",
"chr_py2",
"(",
"self",
".",
"network",
".",
"SECRET_KEY",
")",
")",
"return",
"ensure_bytes",
"(",
"network_hex_chars",
"+",
"self",
".",
"get_key",
"(",
")",
")"
] | Get the extended key.
Extended keys contain the network bytes and the public or private
key. | [
"Get",
"the",
"extended",
"key",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/keys.py#L69-L77 |
226,436 | ranaroussi/pywallet | pywallet/utils/keys.py | PrivateKey.from_wif | def from_wif(cls, wif, network=BitcoinMainNet):
"""Import a key in WIF format.
WIF is Wallet Import Format. It is a base58 encoded checksummed key.
See https://en.bitcoin.it/wiki/Wallet_import_format for a full
description.
This supports compressed WIFs - see this for an explanation:
http://bitcoin.stackexchange.com/questions/7299/when-importing-private-keys-will-compressed-or-uncompressed-format-be-used # nopep8
(specifically http://bitcoin.stackexchange.com/a/7958)
"""
# Decode the base58 string and ensure the checksum is valid
wif = ensure_str(wif)
try:
extended_key_bytes = base58.b58decode_check(wif)
except ValueError as e:
# Invalid checksum!
raise ChecksumException(e)
# Verify we're on the right network
network_bytes = extended_key_bytes[0]
# py3k interprets network_byte as an int already
if not isinstance(network_bytes, six.integer_types):
network_bytes = ord(network_bytes)
if (network_bytes != network.SECRET_KEY):
raise incompatible_network_exception_factory(
network_name=network.NAME,
expected_prefix=network.SECRET_KEY,
given_prefix=network_bytes)
# Drop the network bytes
extended_key_bytes = extended_key_bytes[1:]
# Check for comprssed public key
# This only affects the way in which addresses are generated.
compressed = False
if len(extended_key_bytes) == 33:
# We are supposed to use compressed form!
extended_key_bytes = extended_key_bytes[:-1]
compressed = True
# And we should finally have a valid key
return cls(long_or_int(hexlify(extended_key_bytes), 16), network,
compressed=compressed) | python | def from_wif(cls, wif, network=BitcoinMainNet):
# Decode the base58 string and ensure the checksum is valid
wif = ensure_str(wif)
try:
extended_key_bytes = base58.b58decode_check(wif)
except ValueError as e:
# Invalid checksum!
raise ChecksumException(e)
# Verify we're on the right network
network_bytes = extended_key_bytes[0]
# py3k interprets network_byte as an int already
if not isinstance(network_bytes, six.integer_types):
network_bytes = ord(network_bytes)
if (network_bytes != network.SECRET_KEY):
raise incompatible_network_exception_factory(
network_name=network.NAME,
expected_prefix=network.SECRET_KEY,
given_prefix=network_bytes)
# Drop the network bytes
extended_key_bytes = extended_key_bytes[1:]
# Check for comprssed public key
# This only affects the way in which addresses are generated.
compressed = False
if len(extended_key_bytes) == 33:
# We are supposed to use compressed form!
extended_key_bytes = extended_key_bytes[:-1]
compressed = True
# And we should finally have a valid key
return cls(long_or_int(hexlify(extended_key_bytes), 16), network,
compressed=compressed) | [
"def",
"from_wif",
"(",
"cls",
",",
"wif",
",",
"network",
"=",
"BitcoinMainNet",
")",
":",
"# Decode the base58 string and ensure the checksum is valid",
"wif",
"=",
"ensure_str",
"(",
"wif",
")",
"try",
":",
"extended_key_bytes",
"=",
"base58",
".",
"b58decode_che... | Import a key in WIF format.
WIF is Wallet Import Format. It is a base58 encoded checksummed key.
See https://en.bitcoin.it/wiki/Wallet_import_format for a full
description.
This supports compressed WIFs - see this for an explanation:
http://bitcoin.stackexchange.com/questions/7299/when-importing-private-keys-will-compressed-or-uncompressed-format-be-used # nopep8
(specifically http://bitcoin.stackexchange.com/a/7958) | [
"Import",
"a",
"key",
"in",
"WIF",
"format",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/keys.py#L104-L147 |
226,437 | ranaroussi/pywallet | pywallet/utils/keys.py | PrivateKey.from_master_password | def from_master_password(cls, password, network=BitcoinMainNet):
"""Generate a new key from a master password.
This password is hashed via a single round of sha256 and is highly
breakable, but it's the standard brainwallet approach.
See `PrivateKey.from_master_password_slow` for a slightly more
secure generation method (which will still be subject to a rainbow
table attack :\)
"""
password = ensure_bytes(password)
key = sha256(password).hexdigest()
return cls.from_hex_key(key, network) | python | def from_master_password(cls, password, network=BitcoinMainNet):
password = ensure_bytes(password)
key = sha256(password).hexdigest()
return cls.from_hex_key(key, network) | [
"def",
"from_master_password",
"(",
"cls",
",",
"password",
",",
"network",
"=",
"BitcoinMainNet",
")",
":",
"password",
"=",
"ensure_bytes",
"(",
"password",
")",
"key",
"=",
"sha256",
"(",
"password",
")",
".",
"hexdigest",
"(",
")",
"return",
"cls",
"."... | Generate a new key from a master password.
This password is hashed via a single round of sha256 and is highly
breakable, but it's the standard brainwallet approach.
See `PrivateKey.from_master_password_slow` for a slightly more
secure generation method (which will still be subject to a rainbow
table attack :\) | [
"Generate",
"a",
"new",
"key",
"from",
"a",
"master",
"password",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/keys.py#L160-L172 |
226,438 | ranaroussi/pywallet | pywallet/utils/keys.py | PublicKey.get_key | def get_key(self, compressed=None):
"""Get the hex-encoded key.
:param compressed: False if you want a standard 65 Byte key (the most
standard option). True if you want the compressed 33 Byte form.
Defaults to None, which in turn uses the self.compressed attribute.
:type compressed: bool
PublicKeys consist of an ID byte, the x, and the y coordinates
on the elliptic curve.
In the case of uncompressed keys, the ID byte is 04.
Compressed keys use the SEC1 format:
If Y is odd: id_byte = 03
else: id_byte = 02
Note that I pieced this algorithm together from the pycoin source.
This is documented in http://www.secg.org/collateral/sec1_final.pdf
but, honestly, it's pretty confusing.
I guess this is a pretty big warning that I'm not *positive* this
will do the right thing in all cases. The tests pass, and this does
exactly what pycoin does, but I'm not positive pycoin works either!
"""
if compressed is None:
compressed = self.compressed
if compressed:
parity = 2 + (self.y & 1) # 0x02 even, 0x03 odd
return ensure_bytes(
long_to_hex(parity, 2) +
long_to_hex(self.x, 64))
else:
return ensure_bytes(
b'04' +
long_to_hex(self.x, 64) +
long_to_hex(self.y, 64)) | python | def get_key(self, compressed=None):
if compressed is None:
compressed = self.compressed
if compressed:
parity = 2 + (self.y & 1) # 0x02 even, 0x03 odd
return ensure_bytes(
long_to_hex(parity, 2) +
long_to_hex(self.x, 64))
else:
return ensure_bytes(
b'04' +
long_to_hex(self.x, 64) +
long_to_hex(self.y, 64)) | [
"def",
"get_key",
"(",
"self",
",",
"compressed",
"=",
"None",
")",
":",
"if",
"compressed",
"is",
"None",
":",
"compressed",
"=",
"self",
".",
"compressed",
"if",
"compressed",
":",
"parity",
"=",
"2",
"+",
"(",
"self",
".",
"y",
"&",
"1",
")",
"#... | Get the hex-encoded key.
:param compressed: False if you want a standard 65 Byte key (the most
standard option). True if you want the compressed 33 Byte form.
Defaults to None, which in turn uses the self.compressed attribute.
:type compressed: bool
PublicKeys consist of an ID byte, the x, and the y coordinates
on the elliptic curve.
In the case of uncompressed keys, the ID byte is 04.
Compressed keys use the SEC1 format:
If Y is odd: id_byte = 03
else: id_byte = 02
Note that I pieced this algorithm together from the pycoin source.
This is documented in http://www.secg.org/collateral/sec1_final.pdf
but, honestly, it's pretty confusing.
I guess this is a pretty big warning that I'm not *positive* this
will do the right thing in all cases. The tests pass, and this does
exactly what pycoin does, but I'm not positive pycoin works either! | [
"Get",
"the",
"hex",
"-",
"encoded",
"key",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/keys.py#L210-L246 |
226,439 | ranaroussi/pywallet | pywallet/utils/keys.py | PublicKey.from_hex_key | def from_hex_key(cls, key, network=BitcoinMainNet):
"""Load the PublicKey from a compressed or uncompressed hex key.
This format is defined in PublicKey.get_key()
"""
if len(key) == 130 or len(key) == 66:
# It might be a hexlified byte array
try:
key = unhexlify(key)
except TypeError:
pass
key = ensure_bytes(key)
compressed = False
id_byte = key[0]
if not isinstance(id_byte, six.integer_types):
id_byte = ord(id_byte)
if id_byte == 4:
# Uncompressed public point
# 1B ID + 32B x coord + 32B y coord = 65 B
if len(key) != 65:
raise KeyParseError("Invalid key length")
public_pair = PublicPair(
long_or_int(hexlify(key[1:33]), 16),
long_or_int(hexlify(key[33:]), 16))
elif id_byte in [2, 3]:
# Compressed public point!
compressed = True
if len(key) != 33:
raise KeyParseError("Invalid key length")
y_odd = bool(id_byte & 0x01) # 0 even, 1 odd
x = long_or_int(hexlify(key[1:]), 16)
# The following x-to-pair algorithm was lifted from pycoin
# I still need to sit down an understand it. It is also described
# in http://www.secg.org/collateral/sec1_final.pdf
curve = SECP256k1.curve
p = curve.p()
# For SECP256k1, curve.a() is 0 and curve.b() is 7, so this is
# effectively (x ** 3 + 7) % p, but the full equation is kept
# for just-in-case-the-curve-is-broken future-proofing
alpha = (pow(x, 3, p) + curve.a() * x + curve.b()) % p
beta = square_root_mod_prime(alpha, p)
y_even = not y_odd
if y_even == bool(beta & 1):
public_pair = PublicPair(x, p - beta)
else:
public_pair = PublicPair(x, beta)
else:
raise KeyParseError("The given key is not in a known format.")
return cls.from_public_pair(public_pair, network=network,
compressed=compressed) | python | def from_hex_key(cls, key, network=BitcoinMainNet):
if len(key) == 130 or len(key) == 66:
# It might be a hexlified byte array
try:
key = unhexlify(key)
except TypeError:
pass
key = ensure_bytes(key)
compressed = False
id_byte = key[0]
if not isinstance(id_byte, six.integer_types):
id_byte = ord(id_byte)
if id_byte == 4:
# Uncompressed public point
# 1B ID + 32B x coord + 32B y coord = 65 B
if len(key) != 65:
raise KeyParseError("Invalid key length")
public_pair = PublicPair(
long_or_int(hexlify(key[1:33]), 16),
long_or_int(hexlify(key[33:]), 16))
elif id_byte in [2, 3]:
# Compressed public point!
compressed = True
if len(key) != 33:
raise KeyParseError("Invalid key length")
y_odd = bool(id_byte & 0x01) # 0 even, 1 odd
x = long_or_int(hexlify(key[1:]), 16)
# The following x-to-pair algorithm was lifted from pycoin
# I still need to sit down an understand it. It is also described
# in http://www.secg.org/collateral/sec1_final.pdf
curve = SECP256k1.curve
p = curve.p()
# For SECP256k1, curve.a() is 0 and curve.b() is 7, so this is
# effectively (x ** 3 + 7) % p, but the full equation is kept
# for just-in-case-the-curve-is-broken future-proofing
alpha = (pow(x, 3, p) + curve.a() * x + curve.b()) % p
beta = square_root_mod_prime(alpha, p)
y_even = not y_odd
if y_even == bool(beta & 1):
public_pair = PublicPair(x, p - beta)
else:
public_pair = PublicPair(x, beta)
else:
raise KeyParseError("The given key is not in a known format.")
return cls.from_public_pair(public_pair, network=network,
compressed=compressed) | [
"def",
"from_hex_key",
"(",
"cls",
",",
"key",
",",
"network",
"=",
"BitcoinMainNet",
")",
":",
"if",
"len",
"(",
"key",
")",
"==",
"130",
"or",
"len",
"(",
"key",
")",
"==",
"66",
":",
"# It might be a hexlified byte array",
"try",
":",
"key",
"=",
"u... | Load the PublicKey from a compressed or uncompressed hex key.
This format is defined in PublicKey.get_key() | [
"Load",
"the",
"PublicKey",
"from",
"a",
"compressed",
"or",
"uncompressed",
"hex",
"key",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/keys.py#L249-L299 |
226,440 | ranaroussi/pywallet | pywallet/utils/keys.py | PublicKey.create_point | def create_point(self, x, y):
"""Create an ECDSA point on the SECP256k1 curve with the given coords.
:param x: The x coordinate on the curve
:type x: long
:param y: The y coodinate on the curve
:type y: long
"""
if (not isinstance(x, six.integer_types) or
not isinstance(y, six.integer_types)):
raise ValueError("The coordinates must be longs.")
return _ECDSA_Point(SECP256k1.curve, x, y) | python | def create_point(self, x, y):
if (not isinstance(x, six.integer_types) or
not isinstance(y, six.integer_types)):
raise ValueError("The coordinates must be longs.")
return _ECDSA_Point(SECP256k1.curve, x, y) | [
"def",
"create_point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"x",
",",
"six",
".",
"integer_types",
")",
"or",
"not",
"isinstance",
"(",
"y",
",",
"six",
".",
"integer_types",
")",
")",
":",
"raise",
"Value... | Create an ECDSA point on the SECP256k1 curve with the given coords.
:param x: The x coordinate on the curve
:type x: long
:param y: The y coodinate on the curve
:type y: long | [
"Create",
"an",
"ECDSA",
"point",
"on",
"the",
"SECP256k1",
"curve",
"with",
"the",
"given",
"coords",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/keys.py#L302-L313 |
226,441 | ranaroussi/pywallet | pywallet/utils/keys.py | PublicKey.from_point | def from_point(cls, point, network=BitcoinMainNet, **kwargs):
"""Create a PublicKey from a point on the SECP256k1 curve.
:param point: A point on the SECP256k1 curve.
:type point: SECP256k1.point
"""
verifying_key = VerifyingKey.from_public_point(point, curve=SECP256k1)
return cls.from_verifying_key(verifying_key, network=network, **kwargs) | python | def from_point(cls, point, network=BitcoinMainNet, **kwargs):
verifying_key = VerifyingKey.from_public_point(point, curve=SECP256k1)
return cls.from_verifying_key(verifying_key, network=network, **kwargs) | [
"def",
"from_point",
"(",
"cls",
",",
"point",
",",
"network",
"=",
"BitcoinMainNet",
",",
"*",
"*",
"kwargs",
")",
":",
"verifying_key",
"=",
"VerifyingKey",
".",
"from_public_point",
"(",
"point",
",",
"curve",
"=",
"SECP256k1",
")",
"return",
"cls",
"."... | Create a PublicKey from a point on the SECP256k1 curve.
:param point: A point on the SECP256k1 curve.
:type point: SECP256k1.point | [
"Create",
"a",
"PublicKey",
"from",
"a",
"point",
"on",
"the",
"SECP256k1",
"curve",
"."
] | 206ff224389c490d8798f660c9e79fe97ebb64cf | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/keys.py#L319-L326 |
226,442 | blockchain/api-v1-client-python | blockchain/statistics.py | get_chart | def get_chart(chart_type, time_span=None, rolling_average=None, api_code=None):
"""Get chart data of a specific chart type.
:param str chart_type: type of chart
:param str time_span: duration of the chart.
Default is 1 year for most charts, 1 week for mempool charts (optional)
(Example: 5weeks)
:param str rolling_average: duration over which the data should be averaged (optional)
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Chart` class
"""
resource = 'charts/' + chart_type + '?format=json'
if time_span is not None:
resource += '×pan=' + time_span
if rolling_average is not None:
resource += '&rollingAverage=' + rolling_average
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return Chart(json_response) | python | def get_chart(chart_type, time_span=None, rolling_average=None, api_code=None):
resource = 'charts/' + chart_type + '?format=json'
if time_span is not None:
resource += '×pan=' + time_span
if rolling_average is not None:
resource += '&rollingAverage=' + rolling_average
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return Chart(json_response) | [
"def",
"get_chart",
"(",
"chart_type",
",",
"time_span",
"=",
"None",
",",
"rolling_average",
"=",
"None",
",",
"api_code",
"=",
"None",
")",
":",
"resource",
"=",
"'charts/'",
"+",
"chart_type",
"+",
"'?format=json'",
"if",
"time_span",
"is",
"not",
"None",... | Get chart data of a specific chart type.
:param str chart_type: type of chart
:param str time_span: duration of the chart.
Default is 1 year for most charts, 1 week for mempool charts (optional)
(Example: 5weeks)
:param str rolling_average: duration over which the data should be averaged (optional)
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Chart` class | [
"Get",
"chart",
"data",
"of",
"a",
"specific",
"chart",
"type",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/statistics.py#L25-L46 |
226,443 | blockchain/api-v1-client-python | blockchain/statistics.py | get_pools | def get_pools(time_span=None, api_code=None):
"""Get number of blocks mined by each pool.
:param str time_span: duration of the chart.
Default is 4days (optional)
:param str api_code: Blockchain.info API code (optional)
:return: an instance of dict:{str,int}
"""
resource = 'pools'
if time_span is not None:
resource += '?timespan=' + time_span
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource, base_url='https://api.blockchain.info/')
json_response = json.loads(response)
return {k: v for (k, v) in json_response.items()} | python | def get_pools(time_span=None, api_code=None):
resource = 'pools'
if time_span is not None:
resource += '?timespan=' + time_span
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource, base_url='https://api.blockchain.info/')
json_response = json.loads(response)
return {k: v for (k, v) in json_response.items()} | [
"def",
"get_pools",
"(",
"time_span",
"=",
"None",
",",
"api_code",
"=",
"None",
")",
":",
"resource",
"=",
"'pools'",
"if",
"time_span",
"is",
"not",
"None",
":",
"resource",
"+=",
"'?timespan='",
"+",
"time_span",
"if",
"api_code",
"is",
"not",
"None",
... | Get number of blocks mined by each pool.
:param str time_span: duration of the chart.
Default is 4days (optional)
:param str api_code: Blockchain.info API code (optional)
:return: an instance of dict:{str,int} | [
"Get",
"number",
"of",
"blocks",
"mined",
"by",
"each",
"pool",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/statistics.py#L49-L65 |
226,444 | blockchain/api-v1-client-python | blockchain/wallet.py | Wallet.send | def send(self, to, amount, from_address=None, fee=None):
"""Send bitcoin from your wallet to a single address.
:param str to: recipient bitcoin address
:param int amount: amount to send (in satoshi)
:param str from_address: specific address to send from (optional)
:param int fee: transaction fee in satoshi. Must be greater than the default
fee (optional).
:return: an instance of :class:`PaymentResponse` class
"""
recipient = {to: amount}
return self.send_many(recipient, from_address, fee) | python | def send(self, to, amount, from_address=None, fee=None):
recipient = {to: amount}
return self.send_many(recipient, from_address, fee) | [
"def",
"send",
"(",
"self",
",",
"to",
",",
"amount",
",",
"from_address",
"=",
"None",
",",
"fee",
"=",
"None",
")",
":",
"recipient",
"=",
"{",
"to",
":",
"amount",
"}",
"return",
"self",
".",
"send_many",
"(",
"recipient",
",",
"from_address",
","... | Send bitcoin from your wallet to a single address.
:param str to: recipient bitcoin address
:param int amount: amount to send (in satoshi)
:param str from_address: specific address to send from (optional)
:param int fee: transaction fee in satoshi. Must be greater than the default
fee (optional).
:return: an instance of :class:`PaymentResponse` class | [
"Send",
"bitcoin",
"from",
"your",
"wallet",
"to",
"a",
"single",
"address",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/wallet.py#L34-L46 |
226,445 | blockchain/api-v1-client-python | blockchain/wallet.py | Wallet.send_many | def send_many(self, recipients, from_address=None, fee=None):
"""Send bitcoin from your wallet to multiple addresses.
:param dictionary recipients: dictionary with the structure of 'address':amount
:param str from_address: specific address to send from (optional)
:param int fee: transaction fee in satoshi. Must be greater than the default
fee (optional).
:return: an instance of :class:`PaymentResponse` class
"""
params = self.build_basic_request(read_only=False)
if len(recipients) == 1:
to_address, amount = recipients.popitem()
params['to'] = to_address
params['amount'] = amount
method = 'payment'
else:
params['recipients'] = json.dumps(recipients)
method = 'sendmany'
if from_address is not None:
params['from'] = from_address
if fee is not None:
params['fee'] = fee
response = util.call_api("merchant/{0}/{1}".format(self.identifier, method), params,
base_url=self.service_url)
json_response = json.loads(response)
self.parse_error(json_response)
payment_response = PaymentResponse(json_response['message'],
json_response['tx_hash'],
json_response.get('notice'))
return payment_response | python | def send_many(self, recipients, from_address=None, fee=None):
params = self.build_basic_request(read_only=False)
if len(recipients) == 1:
to_address, amount = recipients.popitem()
params['to'] = to_address
params['amount'] = amount
method = 'payment'
else:
params['recipients'] = json.dumps(recipients)
method = 'sendmany'
if from_address is not None:
params['from'] = from_address
if fee is not None:
params['fee'] = fee
response = util.call_api("merchant/{0}/{1}".format(self.identifier, method), params,
base_url=self.service_url)
json_response = json.loads(response)
self.parse_error(json_response)
payment_response = PaymentResponse(json_response['message'],
json_response['tx_hash'],
json_response.get('notice'))
return payment_response | [
"def",
"send_many",
"(",
"self",
",",
"recipients",
",",
"from_address",
"=",
"None",
",",
"fee",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"build_basic_request",
"(",
"read_only",
"=",
"False",
")",
"if",
"len",
"(",
"recipients",
")",
"==",
... | Send bitcoin from your wallet to multiple addresses.
:param dictionary recipients: dictionary with the structure of 'address':amount
:param str from_address: specific address to send from (optional)
:param int fee: transaction fee in satoshi. Must be greater than the default
fee (optional).
:return: an instance of :class:`PaymentResponse` class | [
"Send",
"bitcoin",
"from",
"your",
"wallet",
"to",
"multiple",
"addresses",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/wallet.py#L48-L82 |
226,446 | blockchain/api-v1-client-python | blockchain/wallet.py | Wallet.list_addresses | def list_addresses(self):
"""List all active addresses in the wallet.
:return: an array of :class:`Address` objects
"""
params = self.build_basic_request()
response = util.call_api("merchant/{0}/list".format(self.identifier), params, base_url=self.service_url)
json_response = json.loads(response)
self.parse_error(json_response)
addresses = []
for a in json_response['addresses']:
address = Address(a['balance'], a['address'], a.get('label'), a['total_received'])
addresses.append(address)
return addresses | python | def list_addresses(self):
params = self.build_basic_request()
response = util.call_api("merchant/{0}/list".format(self.identifier), params, base_url=self.service_url)
json_response = json.loads(response)
self.parse_error(json_response)
addresses = []
for a in json_response['addresses']:
address = Address(a['balance'], a['address'], a.get('label'), a['total_received'])
addresses.append(address)
return addresses | [
"def",
"list_addresses",
"(",
"self",
")",
":",
"params",
"=",
"self",
".",
"build_basic_request",
"(",
")",
"response",
"=",
"util",
".",
"call_api",
"(",
"\"merchant/{0}/list\"",
".",
"format",
"(",
"self",
".",
"identifier",
")",
",",
"params",
",",
"ba... | List all active addresses in the wallet.
:return: an array of :class:`Address` objects | [
"List",
"all",
"active",
"addresses",
"in",
"the",
"wallet",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/wallet.py#L97-L114 |
226,447 | blockchain/api-v1-client-python | blockchain/createwallet.py | create_wallet | def create_wallet(password, api_code, service_url, priv=None, label=None, email=None):
"""Create a new Blockchain.info wallet. It can be created containing a
pre-generated private key or will otherwise generate a new private key.
:param str password: password for the new wallet. At least 10 characters.
:param str api_code: API code with create wallets permission
:param str service_url: URL to an instance of service-my-wallet-v3 (with trailing slash)
:param str priv: private key to add to the wallet (optional)
:param str label: label for the first address in the wallet (optional)
:param str email: email to associate with the new wallet (optional)
:return: an instance of :class:`WalletResponse` class
"""
params = {'password': password, 'api_code': api_code}
if priv is not None:
params['priv'] = priv
if label is not None:
params['label'] = label
if email is not None:
params['email'] = email
response = util.call_api("api/v2/create", params, base_url=service_url)
json_response = json.loads(response)
return CreateWalletResponse(json_response['guid'],
json_response['address'],
json_response['label']) | python | def create_wallet(password, api_code, service_url, priv=None, label=None, email=None):
params = {'password': password, 'api_code': api_code}
if priv is not None:
params['priv'] = priv
if label is not None:
params['label'] = label
if email is not None:
params['email'] = email
response = util.call_api("api/v2/create", params, base_url=service_url)
json_response = json.loads(response)
return CreateWalletResponse(json_response['guid'],
json_response['address'],
json_response['label']) | [
"def",
"create_wallet",
"(",
"password",
",",
"api_code",
",",
"service_url",
",",
"priv",
"=",
"None",
",",
"label",
"=",
"None",
",",
"email",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'password'",
":",
"password",
",",
"'api_code'",
":",
"api_code",... | Create a new Blockchain.info wallet. It can be created containing a
pre-generated private key or will otherwise generate a new private key.
:param str password: password for the new wallet. At least 10 characters.
:param str api_code: API code with create wallets permission
:param str service_url: URL to an instance of service-my-wallet-v3 (with trailing slash)
:param str priv: private key to add to the wallet (optional)
:param str label: label for the first address in the wallet (optional)
:param str email: email to associate with the new wallet (optional)
:return: an instance of :class:`WalletResponse` class | [
"Create",
"a",
"new",
"Blockchain",
".",
"info",
"wallet",
".",
"It",
"can",
"be",
"created",
"containing",
"a",
"pre",
"-",
"generated",
"private",
"key",
"or",
"will",
"otherwise",
"generate",
"a",
"new",
"private",
"key",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/createwallet.py#L10-L35 |
226,448 | blockchain/api-v1-client-python | blockchain/blockexplorer.py | get_block | def get_block(block_id, api_code=None):
"""Get a single block based on a block hash.
:param str block_id: block hash to look up
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Block` class
"""
resource = 'rawblock/' + block_id
if api_code is not None:
resource += '?api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return Block(json_response) | python | def get_block(block_id, api_code=None):
resource = 'rawblock/' + block_id
if api_code is not None:
resource += '?api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return Block(json_response) | [
"def",
"get_block",
"(",
"block_id",
",",
"api_code",
"=",
"None",
")",
":",
"resource",
"=",
"'rawblock/'",
"+",
"block_id",
"if",
"api_code",
"is",
"not",
"None",
":",
"resource",
"+=",
"'?api_code='",
"+",
"api_code",
"response",
"=",
"util",
".",
"call... | Get a single block based on a block hash.
:param str block_id: block hash to look up
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Block` class | [
"Get",
"a",
"single",
"block",
"based",
"on",
"a",
"block",
"hash",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/blockexplorer.py#L11-L24 |
226,449 | blockchain/api-v1-client-python | blockchain/blockexplorer.py | get_tx | def get_tx(tx_id, api_code=None):
"""Get a single transaction based on a transaction hash.
:param str tx_id: transaction hash to look up
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Transaction` class
"""
resource = 'rawtx/' + tx_id
if api_code is not None:
resource += '?api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return Transaction(json_response) | python | def get_tx(tx_id, api_code=None):
resource = 'rawtx/' + tx_id
if api_code is not None:
resource += '?api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return Transaction(json_response) | [
"def",
"get_tx",
"(",
"tx_id",
",",
"api_code",
"=",
"None",
")",
":",
"resource",
"=",
"'rawtx/'",
"+",
"tx_id",
"if",
"api_code",
"is",
"not",
"None",
":",
"resource",
"+=",
"'?api_code='",
"+",
"api_code",
"response",
"=",
"util",
".",
"call_api",
"("... | Get a single transaction based on a transaction hash.
:param str tx_id: transaction hash to look up
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Transaction` class | [
"Get",
"a",
"single",
"transaction",
"based",
"on",
"a",
"transaction",
"hash",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/blockexplorer.py#L27-L40 |
226,450 | blockchain/api-v1-client-python | blockchain/blockexplorer.py | get_block_height | def get_block_height(height, api_code=None):
"""Get an array of blocks at the specified height.
:param int height: block height to look up
:param str api_code: Blockchain.info API code (optional)
:return: an array of :class:`Block` objects
"""
resource = 'block-height/{0}?format=json'.format(height)
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return [Block(b) for b in json_response['blocks']] | python | def get_block_height(height, api_code=None):
resource = 'block-height/{0}?format=json'.format(height)
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return [Block(b) for b in json_response['blocks']] | [
"def",
"get_block_height",
"(",
"height",
",",
"api_code",
"=",
"None",
")",
":",
"resource",
"=",
"'block-height/{0}?format=json'",
".",
"format",
"(",
"height",
")",
"if",
"api_code",
"is",
"not",
"None",
":",
"resource",
"+=",
"'&api_code='",
"+",
"api_code... | Get an array of blocks at the specified height.
:param int height: block height to look up
:param str api_code: Blockchain.info API code (optional)
:return: an array of :class:`Block` objects | [
"Get",
"an",
"array",
"of",
"blocks",
"at",
"the",
"specified",
"height",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/blockexplorer.py#L43-L56 |
226,451 | blockchain/api-v1-client-python | blockchain/blockexplorer.py | get_address | def get_address(address, filter=None, limit=None, offset=None, api_code=None):
"""Get data for a single address including an address balance and list of relevant transactions.
:param str address: address(base58 or hash160) to look up
:param FilterType filter: the filter for transactions selection (optional)
:param int limit: limit number of transactions to display (optional)
:param int offset: number of transactions to skip when display (optional)
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Address` class
"""
resource = 'address/{0}?format=json'.format(address)
if filter is not None:
if isinstance(filter, FilterType):
resource += '&filter=' + str(filter.value)
else:
raise ValueError('Filter must be of FilterType enum')
if limit is not None:
resource += '&limit=' + str(limit)
if offset is not None:
resource += '&offset=' + str(offset)
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return Address(json_response) | python | def get_address(address, filter=None, limit=None, offset=None, api_code=None):
resource = 'address/{0}?format=json'.format(address)
if filter is not None:
if isinstance(filter, FilterType):
resource += '&filter=' + str(filter.value)
else:
raise ValueError('Filter must be of FilterType enum')
if limit is not None:
resource += '&limit=' + str(limit)
if offset is not None:
resource += '&offset=' + str(offset)
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return Address(json_response) | [
"def",
"get_address",
"(",
"address",
",",
"filter",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"api_code",
"=",
"None",
")",
":",
"resource",
"=",
"'address/{0}?format=json'",
".",
"format",
"(",
"address",
")",
"if",
"filt... | Get data for a single address including an address balance and list of relevant transactions.
:param str address: address(base58 or hash160) to look up
:param FilterType filter: the filter for transactions selection (optional)
:param int limit: limit number of transactions to display (optional)
:param int offset: number of transactions to skip when display (optional)
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Address` class | [
"Get",
"data",
"for",
"a",
"single",
"address",
"including",
"an",
"address",
"balance",
"and",
"list",
"of",
"relevant",
"transactions",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/blockexplorer.py#L59-L84 |
226,452 | blockchain/api-v1-client-python | blockchain/blockexplorer.py | get_xpub | def get_xpub(xpub, filter=None, limit=None, offset=None, api_code=None):
"""Get data for a single xpub including balance and list of relevant transactions.
:param str xpub: address(xpub) to look up
:param FilterType filter: the filter for transactions selection (optional)
:param int limit: limit number of transactions to fetch (optional)
:param int offset: number of transactions to skip when fetch (optional)
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Xpub` class
"""
resource = 'multiaddr?active=' + xpub
if filter is not None:
if isinstance(filter, FilterType):
resource += '&filter=' + str(filter.value)
else:
raise ValueError('Filter must be of FilterType enum')
if limit is not None:
resource += '&limit=' + str(limit)
if offset is not None:
resource += '&offset=' + str(offset)
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return Xpub(json_response) | python | def get_xpub(xpub, filter=None, limit=None, offset=None, api_code=None):
resource = 'multiaddr?active=' + xpub
if filter is not None:
if isinstance(filter, FilterType):
resource += '&filter=' + str(filter.value)
else:
raise ValueError('Filter must be of FilterType enum')
if limit is not None:
resource += '&limit=' + str(limit)
if offset is not None:
resource += '&offset=' + str(offset)
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return Xpub(json_response) | [
"def",
"get_xpub",
"(",
"xpub",
",",
"filter",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"api_code",
"=",
"None",
")",
":",
"resource",
"=",
"'multiaddr?active='",
"+",
"xpub",
"if",
"filter",
"is",
"not",
"None",
":",
... | Get data for a single xpub including balance and list of relevant transactions.
:param str xpub: address(xpub) to look up
:param FilterType filter: the filter for transactions selection (optional)
:param int limit: limit number of transactions to fetch (optional)
:param int offset: number of transactions to skip when fetch (optional)
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`Xpub` class | [
"Get",
"data",
"for",
"a",
"single",
"xpub",
"including",
"balance",
"and",
"list",
"of",
"relevant",
"transactions",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/blockexplorer.py#L87-L112 |
226,453 | blockchain/api-v1-client-python | blockchain/blockexplorer.py | get_multi_address | def get_multi_address(addresses, filter=None, limit=None, offset=None, api_code=None):
"""Get aggregate summary for multiple addresses including overall balance, per address balance
and list of relevant transactions.
:param tuple addresses: addresses(xpub or base58) to look up
:param FilterType filter: the filter for transactions selection (optional)
:param int limit: limit number of transactions to fetch (optional)
:param int offset: number of transactions to skip when fetch (optional)
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`MultiAddress` class
"""
if isinstance(addresses, basestring):
resource = 'multiaddr?active=' + addresses
else:
resource = 'multiaddr?active=' + '|'.join(addresses)
if filter is not None:
if isinstance(filter, FilterType):
resource += '&filter=' + str(filter.value)
else:
raise ValueError('Filter must be of FilterType enum')
if limit is not None:
resource += '&limit=' + str(limit)
if offset is not None:
resource += '&offset=' + str(offset)
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return MultiAddress(json_response) | python | def get_multi_address(addresses, filter=None, limit=None, offset=None, api_code=None):
if isinstance(addresses, basestring):
resource = 'multiaddr?active=' + addresses
else:
resource = 'multiaddr?active=' + '|'.join(addresses)
if filter is not None:
if isinstance(filter, FilterType):
resource += '&filter=' + str(filter.value)
else:
raise ValueError('Filter must be of FilterType enum')
if limit is not None:
resource += '&limit=' + str(limit)
if offset is not None:
resource += '&offset=' + str(offset)
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return MultiAddress(json_response) | [
"def",
"get_multi_address",
"(",
"addresses",
",",
"filter",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"api_code",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"addresses",
",",
"basestring",
")",
":",
"resource",
"=",
... | Get aggregate summary for multiple addresses including overall balance, per address balance
and list of relevant transactions.
:param tuple addresses: addresses(xpub or base58) to look up
:param FilterType filter: the filter for transactions selection (optional)
:param int limit: limit number of transactions to fetch (optional)
:param int offset: number of transactions to skip when fetch (optional)
:param str api_code: Blockchain.info API code (optional)
:return: an instance of :class:`MultiAddress` class | [
"Get",
"aggregate",
"summary",
"for",
"multiple",
"addresses",
"including",
"overall",
"balance",
"per",
"address",
"balance",
"and",
"list",
"of",
"relevant",
"transactions",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/blockexplorer.py#L115-L144 |
226,454 | blockchain/api-v1-client-python | blockchain/blockexplorer.py | get_balance | def get_balance(addresses, filter=None, api_code=None):
"""Get balances for each address provided.
:param tuple addresses: addresses(xpub or base58) to look up
:param FilterType filter: the filter for transactions selection (optional)
:param str api_code: Blockchain.info API code (optional)
:return: a dictionary of str, :class:`Balance`
"""
if isinstance(addresses, basestring):
resource = 'balance?active=' + addresses
else:
resource = 'balance?active=' + '|'.join(addresses)
if filter is not None:
if isinstance(filter, FilterType):
resource += '&filter=' + str(filter.value)
else:
raise ValueError('Filter must be of FilterType enum')
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return {k: Balance(v) for (k, v) in json_response.items()} | python | def get_balance(addresses, filter=None, api_code=None):
if isinstance(addresses, basestring):
resource = 'balance?active=' + addresses
else:
resource = 'balance?active=' + '|'.join(addresses)
if filter is not None:
if isinstance(filter, FilterType):
resource += '&filter=' + str(filter.value)
else:
raise ValueError('Filter must be of FilterType enum')
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return {k: Balance(v) for (k, v) in json_response.items()} | [
"def",
"get_balance",
"(",
"addresses",
",",
"filter",
"=",
"None",
",",
"api_code",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"addresses",
",",
"basestring",
")",
":",
"resource",
"=",
"'balance?active='",
"+",
"addresses",
"else",
":",
"resource",
... | Get balances for each address provided.
:param tuple addresses: addresses(xpub or base58) to look up
:param FilterType filter: the filter for transactions selection (optional)
:param str api_code: Blockchain.info API code (optional)
:return: a dictionary of str, :class:`Balance` | [
"Get",
"balances",
"for",
"each",
"address",
"provided",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/blockexplorer.py#L147-L170 |
226,455 | blockchain/api-v1-client-python | blockchain/blockexplorer.py | get_unspent_outputs | def get_unspent_outputs(addresses, confirmations=None, limit=None, api_code=None):
"""Get unspent outputs for a single address.
:param tuple addresses: addresses(xpub or base58) to look up
:param int confirmations: minimum confirmations to include (optional)
:param int limit: limit number of unspent outputs to fetch (optional)
:param str api_code: Blockchain.info API code (optional)
:return: an array of :class:`UnspentOutput` objects
"""
if isinstance(addresses, basestring):
resource = 'unspent?active=' + addresses
else:
resource = 'unspent?active=' + '|'.join(addresses)
if confirmations is not None:
resource += '&confirmations=' + str(confirmations)
if limit is not None:
resource += '&limit=' + str(limit)
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return [UnspentOutput(o) for o in json_response['unspent_outputs']] | python | def get_unspent_outputs(addresses, confirmations=None, limit=None, api_code=None):
if isinstance(addresses, basestring):
resource = 'unspent?active=' + addresses
else:
resource = 'unspent?active=' + '|'.join(addresses)
if confirmations is not None:
resource += '&confirmations=' + str(confirmations)
if limit is not None:
resource += '&limit=' + str(limit)
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return [UnspentOutput(o) for o in json_response['unspent_outputs']] | [
"def",
"get_unspent_outputs",
"(",
"addresses",
",",
"confirmations",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"api_code",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"addresses",
",",
"basestring",
")",
":",
"resource",
"=",
"'unspent?active='",
"+"... | Get unspent outputs for a single address.
:param tuple addresses: addresses(xpub or base58) to look up
:param int confirmations: minimum confirmations to include (optional)
:param int limit: limit number of unspent outputs to fetch (optional)
:param str api_code: Blockchain.info API code (optional)
:return: an array of :class:`UnspentOutput` objects | [
"Get",
"unspent",
"outputs",
"for",
"a",
"single",
"address",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/blockexplorer.py#L173-L195 |
226,456 | blockchain/api-v1-client-python | blockchain/blockexplorer.py | get_unconfirmed_tx | def get_unconfirmed_tx(api_code=None):
"""Get a list of currently unconfirmed transactions.
:param str api_code: Blockchain.info API code (optional)
:return: an array of :class:`Transaction` objects
"""
resource = 'unconfirmed-transactions?format=json'
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return [Transaction(t) for t in json_response['txs']] | python | def get_unconfirmed_tx(api_code=None):
resource = 'unconfirmed-transactions?format=json'
if api_code is not None:
resource += '&api_code=' + api_code
response = util.call_api(resource)
json_response = json.loads(response)
return [Transaction(t) for t in json_response['txs']] | [
"def",
"get_unconfirmed_tx",
"(",
"api_code",
"=",
"None",
")",
":",
"resource",
"=",
"'unconfirmed-transactions?format=json'",
"if",
"api_code",
"is",
"not",
"None",
":",
"resource",
"+=",
"'&api_code='",
"+",
"api_code",
"response",
"=",
"util",
".",
"call_api",... | Get a list of currently unconfirmed transactions.
:param str api_code: Blockchain.info API code (optional)
:return: an array of :class:`Transaction` objects | [
"Get",
"a",
"list",
"of",
"currently",
"unconfirmed",
"transactions",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/blockexplorer.py#L213-L225 |
226,457 | blockchain/api-v1-client-python | blockchain/blockexplorer.py | get_blocks | def get_blocks(time=None, pool_name=None, api_code=None):
"""Get a list of blocks for a specific day or mining pool.
Both parameters are optional but at least one is required.
:param int time: time in milliseconds
:param str pool_name: name of the mining pool
:param str api_code: Blockchain.info API code (optional)
:return: an array of :class:`SimpleBlock` objects
"""
resource = 'blocks/{0}?format=json'
if api_code is not None:
resource += '&api_code=' + api_code
if time is not None:
resource = resource.format(time)
elif pool_name is not None:
resource = resource.format(pool_name)
else:
resource = resource.format('')
response = util.call_api(resource)
json_response = json.loads(response)
return [SimpleBlock(b) for b in json_response['blocks']] | python | def get_blocks(time=None, pool_name=None, api_code=None):
resource = 'blocks/{0}?format=json'
if api_code is not None:
resource += '&api_code=' + api_code
if time is not None:
resource = resource.format(time)
elif pool_name is not None:
resource = resource.format(pool_name)
else:
resource = resource.format('')
response = util.call_api(resource)
json_response = json.loads(response)
return [SimpleBlock(b) for b in json_response['blocks']] | [
"def",
"get_blocks",
"(",
"time",
"=",
"None",
",",
"pool_name",
"=",
"None",
",",
"api_code",
"=",
"None",
")",
":",
"resource",
"=",
"'blocks/{0}?format=json'",
"if",
"api_code",
"is",
"not",
"None",
":",
"resource",
"+=",
"'&api_code='",
"+",
"api_code",
... | Get a list of blocks for a specific day or mining pool.
Both parameters are optional but at least one is required.
:param int time: time in milliseconds
:param str pool_name: name of the mining pool
:param str api_code: Blockchain.info API code (optional)
:return: an array of :class:`SimpleBlock` objects | [
"Get",
"a",
"list",
"of",
"blocks",
"for",
"a",
"specific",
"day",
"or",
"mining",
"pool",
".",
"Both",
"parameters",
"are",
"optional",
"but",
"at",
"least",
"one",
"is",
"required",
"."
] | 52ea562f824f04303e75239364e06722bec8620f | https://github.com/blockchain/api-v1-client-python/blob/52ea562f824f04303e75239364e06722bec8620f/blockchain/blockexplorer.py#L228-L250 |
226,458 | dtmilano/AndroidViewClient | src/com/dtmilano/android/culebron.py | Culebron.populateViewTree | def populateViewTree(self, view):
'''
Populates the View tree.
'''
vuid = view.getUniqueId()
text = view.__smallStr__()
if view.getParent() is None:
self.viewTree.insert('', Tkinter.END, vuid, text=text)
else:
self.viewTree.insert(view.getParent().getUniqueId(), Tkinter.END, vuid, text=text, tags=('ttk'))
self.viewTree.set(vuid, 'T', '*' if view.isTarget() else ' ')
self.viewTree.tag_bind('ttk', '<1>', self.viewTreeItemClicked) | python | def populateViewTree(self, view):
'''
Populates the View tree.
'''
vuid = view.getUniqueId()
text = view.__smallStr__()
if view.getParent() is None:
self.viewTree.insert('', Tkinter.END, vuid, text=text)
else:
self.viewTree.insert(view.getParent().getUniqueId(), Tkinter.END, vuid, text=text, tags=('ttk'))
self.viewTree.set(vuid, 'T', '*' if view.isTarget() else ' ')
self.viewTree.tag_bind('ttk', '<1>', self.viewTreeItemClicked) | [
"def",
"populateViewTree",
"(",
"self",
",",
"view",
")",
":",
"vuid",
"=",
"view",
".",
"getUniqueId",
"(",
")",
"text",
"=",
"view",
".",
"__smallStr__",
"(",
")",
"if",
"view",
".",
"getParent",
"(",
")",
"is",
"None",
":",
"self",
".",
"viewTree"... | Populates the View tree. | [
"Populates",
"the",
"View",
"tree",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/culebron.py#L548-L560 |
226,459 | dtmilano/AndroidViewClient | src/com/dtmilano/android/culebron.py | Culebron.command | def command(self, keycode):
'''
Presses a key.
Generates the actual key press on the device and prints the line in the script.
'''
self.device.press(keycode)
self.printOperation(None, Operation.PRESS, keycode) | python | def command(self, keycode):
'''
Presses a key.
Generates the actual key press on the device and prints the line in the script.
'''
self.device.press(keycode)
self.printOperation(None, Operation.PRESS, keycode) | [
"def",
"command",
"(",
"self",
",",
"keycode",
")",
":",
"self",
".",
"device",
".",
"press",
"(",
"keycode",
")",
"self",
".",
"printOperation",
"(",
"None",
",",
"Operation",
".",
"PRESS",
",",
"keycode",
")"
] | Presses a key.
Generates the actual key press on the device and prints the line in the script. | [
"Presses",
"a",
"key",
".",
"Generates",
"the",
"actual",
"key",
"press",
"on",
"the",
"device",
"and",
"prints",
"the",
"line",
"in",
"the",
"script",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/culebron.py#L911-L918 |
226,460 | dtmilano/AndroidViewClient | src/com/dtmilano/android/culebron.py | Culebron.cancelOperation | def cancelOperation(self):
'''
Cancels the ongoing operation if any.
'''
if self.isLongTouchingPoint:
self.toggleLongTouchPoint()
elif self.isTouchingPoint:
self.toggleTouchPoint()
elif self.isGeneratingTestCondition:
self.toggleGenerateTestCondition() | python | def cancelOperation(self):
'''
Cancels the ongoing operation if any.
'''
if self.isLongTouchingPoint:
self.toggleLongTouchPoint()
elif self.isTouchingPoint:
self.toggleTouchPoint()
elif self.isGeneratingTestCondition:
self.toggleGenerateTestCondition() | [
"def",
"cancelOperation",
"(",
"self",
")",
":",
"if",
"self",
".",
"isLongTouchingPoint",
":",
"self",
".",
"toggleLongTouchPoint",
"(",
")",
"elif",
"self",
".",
"isTouchingPoint",
":",
"self",
".",
"toggleTouchPoint",
"(",
")",
"elif",
"self",
".",
"isGen... | Cancels the ongoing operation if any. | [
"Cancels",
"the",
"ongoing",
"operation",
"if",
"any",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/culebron.py#L1035-L1044 |
226,461 | dtmilano/AndroidViewClient | src/com/dtmilano/android/culebron.py | Culebron.saveSnapshot | def saveSnapshot(self):
'''
Saves the current shanpshot to the specified file.
Current snapshot is the image being displayed on the main window.
'''
filename = self.snapshotDir + os.sep + '${serialno}-${focusedwindowname}-${timestamp}' + '.' + self.snapshotFormat.lower()
# We have the snapshot already taken, no need to retake
d = FileDialog(self, self.device.substituteDeviceTemplate(filename))
saveAsFilename = d.askSaveAsFilename()
if saveAsFilename:
_format = os.path.splitext(saveAsFilename)[1][1:].upper()
self.printOperation(None, Operation.SNAPSHOT, filename, _format, self.deviceArt, self.dropShadow,
self.screenGlare)
# FIXME: we should add deviceArt, dropShadow and screenGlare to the saved image
# self.unscaledScreenshot.save(saveAsFilename, _format, self.deviceArt, self.dropShadow, self.screenGlare)
self.unscaledScreenshot.save(saveAsFilename, _format) | python | def saveSnapshot(self):
'''
Saves the current shanpshot to the specified file.
Current snapshot is the image being displayed on the main window.
'''
filename = self.snapshotDir + os.sep + '${serialno}-${focusedwindowname}-${timestamp}' + '.' + self.snapshotFormat.lower()
# We have the snapshot already taken, no need to retake
d = FileDialog(self, self.device.substituteDeviceTemplate(filename))
saveAsFilename = d.askSaveAsFilename()
if saveAsFilename:
_format = os.path.splitext(saveAsFilename)[1][1:].upper()
self.printOperation(None, Operation.SNAPSHOT, filename, _format, self.deviceArt, self.dropShadow,
self.screenGlare)
# FIXME: we should add deviceArt, dropShadow and screenGlare to the saved image
# self.unscaledScreenshot.save(saveAsFilename, _format, self.deviceArt, self.dropShadow, self.screenGlare)
self.unscaledScreenshot.save(saveAsFilename, _format) | [
"def",
"saveSnapshot",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"snapshotDir",
"+",
"os",
".",
"sep",
"+",
"'${serialno}-${focusedwindowname}-${timestamp}'",
"+",
"'.'",
"+",
"self",
".",
"snapshotFormat",
".",
"lower",
"(",
")",
"# We have the snaps... | Saves the current shanpshot to the specified file.
Current snapshot is the image being displayed on the main window. | [
"Saves",
"the",
"current",
"shanpshot",
"to",
"the",
"specified",
"file",
".",
"Current",
"snapshot",
"is",
"the",
"image",
"being",
"displayed",
"on",
"the",
"main",
"window",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/culebron.py#L1065-L1081 |
226,462 | dtmilano/AndroidViewClient | src/com/dtmilano/android/culebron.py | Culebron.saveViewSnapshot | def saveViewSnapshot(self, view):
'''
Saves the View snapshot.
'''
if not view:
raise ValueError("view must be provided to take snapshot")
filename = self.snapshotDir + os.sep + '${serialno}-' + view.variableNameFromId() + '-${timestamp}' + '.' + self.snapshotFormat.lower()
d = FileDialog(self, self.device.substituteDeviceTemplate(filename))
saveAsFilename = d.askSaveAsFilename()
if saveAsFilename:
_format = os.path.splitext(saveAsFilename)[1][1:].upper()
self.printOperation(view, Operation.VIEW_SNAPSHOT, filename, _format)
view.writeImageToFile(saveAsFilename, _format) | python | def saveViewSnapshot(self, view):
'''
Saves the View snapshot.
'''
if not view:
raise ValueError("view must be provided to take snapshot")
filename = self.snapshotDir + os.sep + '${serialno}-' + view.variableNameFromId() + '-${timestamp}' + '.' + self.snapshotFormat.lower()
d = FileDialog(self, self.device.substituteDeviceTemplate(filename))
saveAsFilename = d.askSaveAsFilename()
if saveAsFilename:
_format = os.path.splitext(saveAsFilename)[1][1:].upper()
self.printOperation(view, Operation.VIEW_SNAPSHOT, filename, _format)
view.writeImageToFile(saveAsFilename, _format) | [
"def",
"saveViewSnapshot",
"(",
"self",
",",
"view",
")",
":",
"if",
"not",
"view",
":",
"raise",
"ValueError",
"(",
"\"view must be provided to take snapshot\"",
")",
"filename",
"=",
"self",
".",
"snapshotDir",
"+",
"os",
".",
"sep",
"+",
"'${serialno}-'",
"... | Saves the View snapshot. | [
"Saves",
"the",
"View",
"snapshot",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/culebron.py#L1083-L1096 |
226,463 | dtmilano/AndroidViewClient | src/com/dtmilano/android/culebron.py | Culebron.toggleLongTouchPoint | def toggleLongTouchPoint(self):
'''
Toggles the long touch point operation.
'''
if not self.isLongTouchingPoint:
msg = 'Long touching point'
self.toast(msg, background=Color.GREEN)
self.statusBar.set(msg)
self.isLongTouchingPoint = True
# FIXME: There should be 2 methods DIP & PX
self.coordinatesUnit = Unit.PX
else:
self.toast(None)
self.statusBar.clear()
self.isLongTouchingPoint = False | python | def toggleLongTouchPoint(self):
'''
Toggles the long touch point operation.
'''
if not self.isLongTouchingPoint:
msg = 'Long touching point'
self.toast(msg, background=Color.GREEN)
self.statusBar.set(msg)
self.isLongTouchingPoint = True
# FIXME: There should be 2 methods DIP & PX
self.coordinatesUnit = Unit.PX
else:
self.toast(None)
self.statusBar.clear()
self.isLongTouchingPoint = False | [
"def",
"toggleLongTouchPoint",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"isLongTouchingPoint",
":",
"msg",
"=",
"'Long touching point'",
"self",
".",
"toast",
"(",
"msg",
",",
"background",
"=",
"Color",
".",
"GREEN",
")",
"self",
".",
"statusBar",
... | Toggles the long touch point operation. | [
"Toggles",
"the",
"long",
"touch",
"point",
"operation",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/culebron.py#L1110-L1124 |
226,464 | dtmilano/AndroidViewClient | src/com/dtmilano/android/adb/adbclient.py | WifiManager.getWifiState | def getWifiState(self):
'''
Gets the Wi-Fi enabled state.
@return: One of WIFI_STATE_DISABLED, WIFI_STATE_DISABLING, WIFI_STATE_ENABLED, WIFI_STATE_ENABLING, WIFI_STATE_UNKNOWN
'''
result = self.device.shell('dumpsys wifi')
if result:
state = result.splitlines()[0]
if self.WIFI_IS_ENABLED_RE.match(state):
return self.WIFI_STATE_ENABLED
elif self.WIFI_IS_DISABLED_RE.match(state):
return self.WIFI_STATE_DISABLED
print >> sys.stderr, "UNKNOWN WIFI STATE:", state
return self.WIFI_STATE_UNKNOWN | python | def getWifiState(self):
'''
Gets the Wi-Fi enabled state.
@return: One of WIFI_STATE_DISABLED, WIFI_STATE_DISABLING, WIFI_STATE_ENABLED, WIFI_STATE_ENABLING, WIFI_STATE_UNKNOWN
'''
result = self.device.shell('dumpsys wifi')
if result:
state = result.splitlines()[0]
if self.WIFI_IS_ENABLED_RE.match(state):
return self.WIFI_STATE_ENABLED
elif self.WIFI_IS_DISABLED_RE.match(state):
return self.WIFI_STATE_DISABLED
print >> sys.stderr, "UNKNOWN WIFI STATE:", state
return self.WIFI_STATE_UNKNOWN | [
"def",
"getWifiState",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"device",
".",
"shell",
"(",
"'dumpsys wifi'",
")",
"if",
"result",
":",
"state",
"=",
"result",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
"if",
"self",
".",
"WIFI_IS_ENABLED_R... | Gets the Wi-Fi enabled state.
@return: One of WIFI_STATE_DISABLED, WIFI_STATE_DISABLING, WIFI_STATE_ENABLED, WIFI_STATE_ENABLING, WIFI_STATE_UNKNOWN | [
"Gets",
"the",
"Wi",
"-",
"Fi",
"enabled",
"state",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/adb/adbclient.py#L134-L149 |
226,465 | dtmilano/AndroidViewClient | src/com/dtmilano/android/adb/adbclient.py | AdbClient.setTimer | def setTimer(self, timeout, description=None):
"""
Sets a timer.
:param description:
:param timeout: timeout in seconds
:return: the timerId
"""
self.timerId += 1
timer = Timer(timeout, self.__timeoutHandler, (self.timerId, description))
timer.start()
self.timers[self.timerId] = timer
return self.timerId | python | def setTimer(self, timeout, description=None):
self.timerId += 1
timer = Timer(timeout, self.__timeoutHandler, (self.timerId, description))
timer.start()
self.timers[self.timerId] = timer
return self.timerId | [
"def",
"setTimer",
"(",
"self",
",",
"timeout",
",",
"description",
"=",
"None",
")",
":",
"self",
".",
"timerId",
"+=",
"1",
"timer",
"=",
"Timer",
"(",
"timeout",
",",
"self",
".",
"__timeoutHandler",
",",
"(",
"self",
".",
"timerId",
",",
"descripti... | Sets a timer.
:param description:
:param timeout: timeout in seconds
:return: the timerId | [
"Sets",
"a",
"timer",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/adb/adbclient.py#L210-L222 |
226,466 | dtmilano/AndroidViewClient | src/com/dtmilano/android/adb/adbclient.py | AdbClient.getProperty | def getProperty(self, key, strip=True):
''' Gets the property value for key '''
self.__checkTransport()
import collections
MAP_PROPS = collections.OrderedDict([
(re.compile('display.width'), self.__getDisplayWidth),
(re.compile('display.height'), self.__getDisplayHeight),
(re.compile('display.density'), self.__getDisplayDensity),
(re.compile('display.orientation'), self.__getDisplayOrientation),
(re.compile('.*'), self.__getProp),
])
'''Maps properties key values (as regexps) to instance methods to obtain its values.'''
for kre in MAP_PROPS.keys():
if kre.match(key):
return MAP_PROPS[kre](key=key, strip=strip)
raise ValueError("key='%s' does not match any map entry") | python | def getProperty(self, key, strip=True):
''' Gets the property value for key '''
self.__checkTransport()
import collections
MAP_PROPS = collections.OrderedDict([
(re.compile('display.width'), self.__getDisplayWidth),
(re.compile('display.height'), self.__getDisplayHeight),
(re.compile('display.density'), self.__getDisplayDensity),
(re.compile('display.orientation'), self.__getDisplayOrientation),
(re.compile('.*'), self.__getProp),
])
'''Maps properties key values (as regexps) to instance methods to obtain its values.'''
for kre in MAP_PROPS.keys():
if kre.match(key):
return MAP_PROPS[kre](key=key, strip=strip)
raise ValueError("key='%s' does not match any map entry") | [
"def",
"getProperty",
"(",
"self",
",",
"key",
",",
"strip",
"=",
"True",
")",
":",
"self",
".",
"__checkTransport",
"(",
")",
"import",
"collections",
"MAP_PROPS",
"=",
"collections",
".",
"OrderedDict",
"(",
"[",
"(",
"re",
".",
"compile",
"(",
"'displ... | Gets the property value for key | [
"Gets",
"the",
"property",
"value",
"for",
"key"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/adb/adbclient.py#L680-L697 |
226,467 | dtmilano/AndroidViewClient | src/com/dtmilano/android/adb/adbclient.py | AdbClient.isLocked | def isLocked(self):
'''
Checks if the device screen is locked.
@return True if the device screen is locked
'''
self.__checkTransport()
lockScreenRE = re.compile('mShowingLockscreen=(true|false)')
dwp = self.shell('dumpsys window policy')
m = lockScreenRE.search(dwp)
if m:
return m.group(1) == 'true'
dreamingLockscreenRE = re.compile('mDreamingLockscreen=(true|false)')
m = dreamingLockscreenRE.search(dwp)
if m:
return m.group(1) == 'true'
raise RuntimeError("Couldn't determine screen lock state") | python | def isLocked(self):
'''
Checks if the device screen is locked.
@return True if the device screen is locked
'''
self.__checkTransport()
lockScreenRE = re.compile('mShowingLockscreen=(true|false)')
dwp = self.shell('dumpsys window policy')
m = lockScreenRE.search(dwp)
if m:
return m.group(1) == 'true'
dreamingLockscreenRE = re.compile('mDreamingLockscreen=(true|false)')
m = dreamingLockscreenRE.search(dwp)
if m:
return m.group(1) == 'true'
raise RuntimeError("Couldn't determine screen lock state") | [
"def",
"isLocked",
"(",
"self",
")",
":",
"self",
".",
"__checkTransport",
"(",
")",
"lockScreenRE",
"=",
"re",
".",
"compile",
"(",
"'mShowingLockscreen=(true|false)'",
")",
"dwp",
"=",
"self",
".",
"shell",
"(",
"'dumpsys window policy'",
")",
"m",
"=",
"l... | Checks if the device screen is locked.
@return True if the device screen is locked | [
"Checks",
"if",
"the",
"device",
"screen",
"is",
"locked",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/adb/adbclient.py#L994-L1011 |
226,468 | dtmilano/AndroidViewClient | src/com/dtmilano/android/adb/adbclient.py | AdbClient.isScreenOn | def isScreenOn(self):
"""
Checks if the screen is ON.
@return: True if the device screen is ON
"""
self.__checkTransport()
screenOnRE = re.compile('mScreenOnFully=(true|false)')
m = screenOnRE.search(self.shell('dumpsys window policy'))
if m:
return m.group(1) == 'true'
raise RuntimeError("Couldn't determine screen ON state") | python | def isScreenOn(self):
self.__checkTransport()
screenOnRE = re.compile('mScreenOnFully=(true|false)')
m = screenOnRE.search(self.shell('dumpsys window policy'))
if m:
return m.group(1) == 'true'
raise RuntimeError("Couldn't determine screen ON state") | [
"def",
"isScreenOn",
"(",
"self",
")",
":",
"self",
".",
"__checkTransport",
"(",
")",
"screenOnRE",
"=",
"re",
".",
"compile",
"(",
"'mScreenOnFully=(true|false)'",
")",
"m",
"=",
"screenOnRE",
".",
"search",
"(",
"self",
".",
"shell",
"(",
"'dumpsys window... | Checks if the screen is ON.
@return: True if the device screen is ON | [
"Checks",
"if",
"the",
"screen",
"is",
"ON",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/adb/adbclient.py#L1013-L1025 |
226,469 | dtmilano/AndroidViewClient | src/com/dtmilano/android/adb/adbclient.py | AdbClient.percentSame | def percentSame(image1, image2):
'''
Returns the percent of pixels that are equal
@author: catshoes
'''
# If the images differ in size, return 0% same.
size_x1, size_y1 = image1.size
size_x2, size_y2 = image2.size
if (size_x1 != size_x2 or
size_y1 != size_y2):
return 0
# Images are the same size
# Return the percent of pixels that are equal.
numPixelsSame = 0
numPixelsTotal = size_x1 * size_y1
image1Pixels = image1.load()
image2Pixels = image2.load()
# Loop over all pixels, comparing pixel in image1 to image2
for x in range(size_x1):
for y in range(size_y1):
if image1Pixels[x, y] == image2Pixels[x, y]:
numPixelsSame += 1
return numPixelsSame / float(numPixelsTotal) | python | def percentSame(image1, image2):
'''
Returns the percent of pixels that are equal
@author: catshoes
'''
# If the images differ in size, return 0% same.
size_x1, size_y1 = image1.size
size_x2, size_y2 = image2.size
if (size_x1 != size_x2 or
size_y1 != size_y2):
return 0
# Images are the same size
# Return the percent of pixels that are equal.
numPixelsSame = 0
numPixelsTotal = size_x1 * size_y1
image1Pixels = image1.load()
image2Pixels = image2.load()
# Loop over all pixels, comparing pixel in image1 to image2
for x in range(size_x1):
for y in range(size_y1):
if image1Pixels[x, y] == image2Pixels[x, y]:
numPixelsSame += 1
return numPixelsSame / float(numPixelsTotal) | [
"def",
"percentSame",
"(",
"image1",
",",
"image2",
")",
":",
"# If the images differ in size, return 0% same.",
"size_x1",
",",
"size_y1",
"=",
"image1",
".",
"size",
"size_x2",
",",
"size_y2",
"=",
"image2",
".",
"size",
"if",
"(",
"size_x1",
"!=",
"size_x2",
... | Returns the percent of pixels that are equal
@author: catshoes | [
"Returns",
"the",
"percent",
"of",
"pixels",
"that",
"are",
"equal"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/adb/adbclient.py#L1037-L1064 |
226,470 | dtmilano/AndroidViewClient | src/com/dtmilano/android/adb/adbclient.py | AdbClient.imageInScreen | def imageInScreen(screen, image):
"""
Checks if image is on the screen
@param screen: the screen image
@param image: the partial image to look for
@return: True or False
@author: Perry Tsai <ripple0129@gmail.com>
"""
# To make sure image smaller than screen.
size_x1, size_y1 = screen.size
size_x2, size_y2 = image.size
if size_x1 <= size_x2 or size_y1 <= size_y2:
return 0
# Load pixels.
screenPixels = screen.load()
imagePixels = image.load()
# Loop over all pixels, if pixel image[0,0] same as pixel screen[x,y] do crop and compare
for x in range(size_x1 - size_x2):
for y in range(size_y1 - size_y2):
if imagePixels[0, 0] == screenPixels[x, y]:
croppedScreen = screen.crop((x, y, x + size_x2, y + size_y2))
size_x3, size_y3 = croppedScreen.size
croppedPixels = croppedScreen.load()
for x in range(size_x3):
for y in range(size_y3):
if imagePixels[x, y] == croppedPixels[x, y]:
return True | python | def imageInScreen(screen, image):
# To make sure image smaller than screen.
size_x1, size_y1 = screen.size
size_x2, size_y2 = image.size
if size_x1 <= size_x2 or size_y1 <= size_y2:
return 0
# Load pixels.
screenPixels = screen.load()
imagePixels = image.load()
# Loop over all pixels, if pixel image[0,0] same as pixel screen[x,y] do crop and compare
for x in range(size_x1 - size_x2):
for y in range(size_y1 - size_y2):
if imagePixels[0, 0] == screenPixels[x, y]:
croppedScreen = screen.crop((x, y, x + size_x2, y + size_y2))
size_x3, size_y3 = croppedScreen.size
croppedPixels = croppedScreen.load()
for x in range(size_x3):
for y in range(size_y3):
if imagePixels[x, y] == croppedPixels[x, y]:
return True | [
"def",
"imageInScreen",
"(",
"screen",
",",
"image",
")",
":",
"# To make sure image smaller than screen.",
"size_x1",
",",
"size_y1",
"=",
"screen",
".",
"size",
"size_x2",
",",
"size_y2",
"=",
"image",
".",
"size",
"if",
"size_x1",
"<=",
"size_x2",
"or",
"si... | Checks if image is on the screen
@param screen: the screen image
@param image: the partial image to look for
@return: True or False
@author: Perry Tsai <ripple0129@gmail.com> | [
"Checks",
"if",
"image",
"is",
"on",
"the",
"screen"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/adb/adbclient.py#L1077-L1108 |
226,471 | dtmilano/AndroidViewClient | src/com/dtmilano/android/adb/adbclient.py | AdbClient.isKeyboardShown | def isKeyboardShown(self):
'''
Whether the keyboard is displayed.
'''
self.__checkTransport()
dim = self.shell('dumpsys input_method')
if dim:
# FIXME: API >= 15 ?
return "mInputShown=true" in dim
return False | python | def isKeyboardShown(self):
'''
Whether the keyboard is displayed.
'''
self.__checkTransport()
dim = self.shell('dumpsys input_method')
if dim:
# FIXME: API >= 15 ?
return "mInputShown=true" in dim
return False | [
"def",
"isKeyboardShown",
"(",
"self",
")",
":",
"self",
".",
"__checkTransport",
"(",
")",
"dim",
"=",
"self",
".",
"shell",
"(",
"'dumpsys input_method'",
")",
"if",
"dim",
":",
"# FIXME: API >= 15 ?",
"return",
"\"mInputShown=true\"",
"in",
"dim",
"return",
... | Whether the keyboard is displayed. | [
"Whether",
"the",
"keyboard",
"is",
"displayed",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/adb/adbclient.py#L1122-L1132 |
226,472 | dtmilano/AndroidViewClient | src/com/dtmilano/android/controlpanel.py | ControlPanel.tabLayout | def tabLayout(self):
''' For all tabs, specify the number of buttons in a row '''
self.childWindow.column += 1
if self.childWindow.column > Layout.BUTTONS_NUMBER:
self.childWindow.column = 0
self.childWindow.row += 1 | python | def tabLayout(self):
''' For all tabs, specify the number of buttons in a row '''
self.childWindow.column += 1
if self.childWindow.column > Layout.BUTTONS_NUMBER:
self.childWindow.column = 0
self.childWindow.row += 1 | [
"def",
"tabLayout",
"(",
"self",
")",
":",
"self",
".",
"childWindow",
".",
"column",
"+=",
"1",
"if",
"self",
".",
"childWindow",
".",
"column",
">",
"Layout",
".",
"BUTTONS_NUMBER",
":",
"self",
".",
"childWindow",
".",
"column",
"=",
"0",
"self",
".... | For all tabs, specify the number of buttons in a row | [
"For",
"all",
"tabs",
"specify",
"the",
"number",
"of",
"buttons",
"in",
"a",
"row"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/controlpanel.py#L152-L157 |
226,473 | dtmilano/AndroidViewClient | src/com/dtmilano/android/common.py | debugArgsToDict | def debugArgsToDict(a):
"""
Converts a string representation of debug arguments to a dictionary.
The string can be of the form
IDENTIFIER1=val1,IDENTIFIER2=val2
:param a: the argument string
:return: the dictionary
"""
s = a.replace('+', ' ')
s = s.replace('=', ':')
s = re.sub(r'([A-Z][A-Z_]+)', r"'\1'", s)
return ast.literal_eval('{ ' + s + ' }') | python | def debugArgsToDict(a):
s = a.replace('+', ' ')
s = s.replace('=', ':')
s = re.sub(r'([A-Z][A-Z_]+)', r"'\1'", s)
return ast.literal_eval('{ ' + s + ' }') | [
"def",
"debugArgsToDict",
"(",
"a",
")",
":",
"s",
"=",
"a",
".",
"replace",
"(",
"'+'",
",",
"' '",
")",
"s",
"=",
"s",
".",
"replace",
"(",
"'='",
",",
"':'",
")",
"s",
"=",
"re",
".",
"sub",
"(",
"r'([A-Z][A-Z_]+)'",
",",
"r\"'\\1'\"",
",",
... | Converts a string representation of debug arguments to a dictionary.
The string can be of the form
IDENTIFIER1=val1,IDENTIFIER2=val2
:param a: the argument string
:return: the dictionary | [
"Converts",
"a",
"string",
"representation",
"of",
"debug",
"arguments",
"to",
"a",
"dictionary",
".",
"The",
"string",
"can",
"be",
"of",
"the",
"form"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/common.py#L190-L205 |
226,474 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | View.getHeight | def getHeight(self):
'''
Gets the height.
'''
if self.useUiAutomator:
return self.map['bounds'][1][1] - self.map['bounds'][0][1]
else:
try:
return int(self.map[self.heightProperty])
except:
return 0 | python | def getHeight(self):
'''
Gets the height.
'''
if self.useUiAutomator:
return self.map['bounds'][1][1] - self.map['bounds'][0][1]
else:
try:
return int(self.map[self.heightProperty])
except:
return 0 | [
"def",
"getHeight",
"(",
"self",
")",
":",
"if",
"self",
".",
"useUiAutomator",
":",
"return",
"self",
".",
"map",
"[",
"'bounds'",
"]",
"[",
"1",
"]",
"[",
"1",
"]",
"-",
"self",
".",
"map",
"[",
"'bounds'",
"]",
"[",
"0",
"]",
"[",
"1",
"]",
... | Gets the height. | [
"Gets",
"the",
"height",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L536-L547 |
226,475 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | View.getWidth | def getWidth(self):
'''
Gets the width.
'''
if self.useUiAutomator:
return self.map['bounds'][1][0] - self.map['bounds'][0][0]
else:
try:
return int(self.map[self.widthProperty])
except:
return 0 | python | def getWidth(self):
'''
Gets the width.
'''
if self.useUiAutomator:
return self.map['bounds'][1][0] - self.map['bounds'][0][0]
else:
try:
return int(self.map[self.widthProperty])
except:
return 0 | [
"def",
"getWidth",
"(",
"self",
")",
":",
"if",
"self",
".",
"useUiAutomator",
":",
"return",
"self",
".",
"map",
"[",
"'bounds'",
"]",
"[",
"1",
"]",
"[",
"0",
"]",
"-",
"self",
".",
"map",
"[",
"'bounds'",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
... | Gets the width. | [
"Gets",
"the",
"width",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L549-L560 |
226,476 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | View.getVisibility | def getVisibility(self):
'''
Gets the View visibility
'''
try:
if self.map[GET_VISIBILITY_PROPERTY] == 'VISIBLE':
return VISIBLE
elif self.map[GET_VISIBILITY_PROPERTY] == 'INVISIBLE':
return INVISIBLE
elif self.map[GET_VISIBILITY_PROPERTY] == 'GONE':
return GONE
else:
return -2
except:
return -1 | python | def getVisibility(self):
'''
Gets the View visibility
'''
try:
if self.map[GET_VISIBILITY_PROPERTY] == 'VISIBLE':
return VISIBLE
elif self.map[GET_VISIBILITY_PROPERTY] == 'INVISIBLE':
return INVISIBLE
elif self.map[GET_VISIBILITY_PROPERTY] == 'GONE':
return GONE
else:
return -2
except:
return -1 | [
"def",
"getVisibility",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"map",
"[",
"GET_VISIBILITY_PROPERTY",
"]",
"==",
"'VISIBLE'",
":",
"return",
"VISIBLE",
"elif",
"self",
".",
"map",
"[",
"GET_VISIBILITY_PROPERTY",
"]",
"==",
"'INVISIBLE'",
":",
... | Gets the View visibility | [
"Gets",
"the",
"View",
"visibility"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L574-L589 |
226,477 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | View.__getX | def __getX(self):
'''
Gets the View X coordinate
'''
if DEBUG_COORDS:
print >>sys.stderr, "getX(%s %s ## %s)" % (self.getClass(), self.getId(), self.getUniqueId())
x = 0
if self.useUiAutomator:
x = self.map['bounds'][0][0]
else:
try:
if GET_VISIBILITY_PROPERTY in self.map and self.map[GET_VISIBILITY_PROPERTY] == 'VISIBLE':
_x = int(self.map[self.leftProperty])
if DEBUG_COORDS: print >>sys.stderr, " getX: VISIBLE adding %d" % _x
x += _x
except:
warnings.warn("View %s has no '%s' property" % (self.getId(), self.leftProperty))
if DEBUG_COORDS: print >>sys.stderr, " getX: returning %d" % (x)
return x | python | def __getX(self):
'''
Gets the View X coordinate
'''
if DEBUG_COORDS:
print >>sys.stderr, "getX(%s %s ## %s)" % (self.getClass(), self.getId(), self.getUniqueId())
x = 0
if self.useUiAutomator:
x = self.map['bounds'][0][0]
else:
try:
if GET_VISIBILITY_PROPERTY in self.map and self.map[GET_VISIBILITY_PROPERTY] == 'VISIBLE':
_x = int(self.map[self.leftProperty])
if DEBUG_COORDS: print >>sys.stderr, " getX: VISIBLE adding %d" % _x
x += _x
except:
warnings.warn("View %s has no '%s' property" % (self.getId(), self.leftProperty))
if DEBUG_COORDS: print >>sys.stderr, " getX: returning %d" % (x)
return x | [
"def",
"__getX",
"(",
"self",
")",
":",
"if",
"DEBUG_COORDS",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"getX(%s %s ## %s)\"",
"%",
"(",
"self",
".",
"getClass",
"(",
")",
",",
"self",
".",
"getId",
"(",
")",
",",
"self",
".",
"getUniqueId",
"... | Gets the View X coordinate | [
"Gets",
"the",
"View",
"X",
"coordinate"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L598-L619 |
226,478 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | View.__getY | def __getY(self):
'''
Gets the View Y coordinate
'''
if DEBUG_COORDS:
print >>sys.stderr, "getY(%s %s ## %s)" % (self.getClass(), self.getId(), self.getUniqueId())
y = 0
if self.useUiAutomator:
y = self.map['bounds'][0][1]
else:
try:
if GET_VISIBILITY_PROPERTY in self.map and self.map[GET_VISIBILITY_PROPERTY] == 'VISIBLE':
_y = int(self.map[self.topProperty])
if DEBUG_COORDS: print >>sys.stderr, " getY: VISIBLE adding %d" % _y
y += _y
except:
warnings.warn("View %s has no '%s' property" % (self.getId(), self.topProperty))
if DEBUG_COORDS: print >>sys.stderr, " getY: returning %d" % (y)
return y | python | def __getY(self):
'''
Gets the View Y coordinate
'''
if DEBUG_COORDS:
print >>sys.stderr, "getY(%s %s ## %s)" % (self.getClass(), self.getId(), self.getUniqueId())
y = 0
if self.useUiAutomator:
y = self.map['bounds'][0][1]
else:
try:
if GET_VISIBILITY_PROPERTY in self.map and self.map[GET_VISIBILITY_PROPERTY] == 'VISIBLE':
_y = int(self.map[self.topProperty])
if DEBUG_COORDS: print >>sys.stderr, " getY: VISIBLE adding %d" % _y
y += _y
except:
warnings.warn("View %s has no '%s' property" % (self.getId(), self.topProperty))
if DEBUG_COORDS: print >>sys.stderr, " getY: returning %d" % (y)
return y | [
"def",
"__getY",
"(",
"self",
")",
":",
"if",
"DEBUG_COORDS",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"getY(%s %s ## %s)\"",
"%",
"(",
"self",
".",
"getClass",
"(",
")",
",",
"self",
".",
"getId",
"(",
")",
",",
"self",
".",
"getUniqueId",
"... | Gets the View Y coordinate | [
"Gets",
"the",
"View",
"Y",
"coordinate"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L628-L649 |
226,479 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | View.getCoords | def getCoords(self):
'''
Gets the coords of the View
@return: A tuple containing the View's coordinates ((L, T), (R, B))
'''
if DEBUG_COORDS:
print >>sys.stderr, "getCoords(%s %s ## %s)" % (self.getClass(), self.getId(), self.getUniqueId())
(x, y) = self.getXY();
w = self.getWidth()
h = self.getHeight()
return ((x, y), (x+w, y+h)) | python | def getCoords(self):
'''
Gets the coords of the View
@return: A tuple containing the View's coordinates ((L, T), (R, B))
'''
if DEBUG_COORDS:
print >>sys.stderr, "getCoords(%s %s ## %s)" % (self.getClass(), self.getId(), self.getUniqueId())
(x, y) = self.getXY();
w = self.getWidth()
h = self.getHeight()
return ((x, y), (x+w, y+h)) | [
"def",
"getCoords",
"(",
"self",
")",
":",
"if",
"DEBUG_COORDS",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"getCoords(%s %s ## %s)\"",
"%",
"(",
"self",
".",
"getClass",
"(",
")",
",",
"self",
".",
"getId",
"(",
")",
",",
"self",
".",
"getUnique... | Gets the coords of the View
@return: A tuple containing the View's coordinates ((L, T), (R, B)) | [
"Gets",
"the",
"coords",
"of",
"the",
"View"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L738-L751 |
226,480 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | View.getCenter | def getCenter(self):
'''
Gets the center coords of the View
@author: U{Dean Morin <https://github.com/deanmorin>}
'''
(left, top), (right, bottom) = self.getCoords()
x = left + (right - left) / 2
y = top + (bottom - top) / 2
return (x, y) | python | def getCenter(self):
'''
Gets the center coords of the View
@author: U{Dean Morin <https://github.com/deanmorin>}
'''
(left, top), (right, bottom) = self.getCoords()
x = left + (right - left) / 2
y = top + (bottom - top) / 2
return (x, y) | [
"def",
"getCenter",
"(",
"self",
")",
":",
"(",
"left",
",",
"top",
")",
",",
"(",
"right",
",",
"bottom",
")",
"=",
"self",
".",
"getCoords",
"(",
")",
"x",
"=",
"left",
"+",
"(",
"right",
"-",
"left",
")",
"/",
"2",
"y",
"=",
"top",
"+",
... | Gets the center coords of the View
@author: U{Dean Morin <https://github.com/deanmorin>} | [
"Gets",
"the",
"center",
"coords",
"of",
"the",
"View"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L775-L785 |
226,481 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | View.isFocused | def isFocused(self):
'''
Gets the focused value
@return: the focused value. If the property cannot be found returns C{False}
'''
try:
return True if self.map[self.isFocusedProperty].lower() == 'true' else False
except Exception:
return False | python | def isFocused(self):
'''
Gets the focused value
@return: the focused value. If the property cannot be found returns C{False}
'''
try:
return True if self.map[self.isFocusedProperty].lower() == 'true' else False
except Exception:
return False | [
"def",
"isFocused",
"(",
"self",
")",
":",
"try",
":",
"return",
"True",
"if",
"self",
".",
"map",
"[",
"self",
".",
"isFocusedProperty",
"]",
".",
"lower",
"(",
")",
"==",
"'true'",
"else",
"False",
"except",
"Exception",
":",
"return",
"False"
] | Gets the focused value
@return: the focused value. If the property cannot be found returns C{False} | [
"Gets",
"the",
"focused",
"value"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L1028-L1038 |
226,482 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | EditText.setText | def setText(self, text):
"""
This function makes sure that any previously entered text is deleted before
setting the value of the field.
"""
if self.text() == text:
return
self.touch()
maxSize = len(self.text()) + 1
self.device.press('KEYCODE_DEL', adbclient.DOWN_AND_UP, repeat=maxSize)
self.device.press('KEYCODE_FORWARD_DEL', adbclient.DOWN_AND_UP, repeat=maxSize)
self.type(text, alreadyTouched=True) | python | def setText(self, text):
if self.text() == text:
return
self.touch()
maxSize = len(self.text()) + 1
self.device.press('KEYCODE_DEL', adbclient.DOWN_AND_UP, repeat=maxSize)
self.device.press('KEYCODE_FORWARD_DEL', adbclient.DOWN_AND_UP, repeat=maxSize)
self.type(text, alreadyTouched=True) | [
"def",
"setText",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"text",
"(",
")",
"==",
"text",
":",
"return",
"self",
".",
"touch",
"(",
")",
"maxSize",
"=",
"len",
"(",
"self",
".",
"text",
"(",
")",
")",
"+",
"1",
"self",
".",
"de... | This function makes sure that any previously entered text is deleted before
setting the value of the field. | [
"This",
"function",
"makes",
"sure",
"that",
"any",
"previously",
"entered",
"text",
"is",
"deleted",
"before",
"setting",
"the",
"value",
"of",
"the",
"field",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L1194-L1205 |
226,483 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | UiDevice.openNotification | def openNotification(self):
'''
Opens the notification shade.
'''
# the tablet has a different Notification/Quick Settings bar depending on x
w13 = self.device.display['width'] / 3
s = (w13, 0)
e = (w13, self.device.display['height']/2)
self.device.drag(s, e, 500, 20, -1)
self.vc.sleep(1)
self.vc.dump(-1) | python | def openNotification(self):
'''
Opens the notification shade.
'''
# the tablet has a different Notification/Quick Settings bar depending on x
w13 = self.device.display['width'] / 3
s = (w13, 0)
e = (w13, self.device.display['height']/2)
self.device.drag(s, e, 500, 20, -1)
self.vc.sleep(1)
self.vc.dump(-1) | [
"def",
"openNotification",
"(",
"self",
")",
":",
"# the tablet has a different Notification/Quick Settings bar depending on x",
"w13",
"=",
"self",
".",
"device",
".",
"display",
"[",
"'width'",
"]",
"/",
"3",
"s",
"=",
"(",
"w13",
",",
"0",
")",
"e",
"=",
"(... | Opens the notification shade. | [
"Opens",
"the",
"notification",
"shade",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L1222-L1233 |
226,484 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | UiDevice.openQuickSettings | def openQuickSettings(self):
'''
Opens the Quick Settings shade.
'''
# the tablet has a different Notification/Quick Settings bar depending on x
w23 = 2 * self.device.display['width'] / 3
s = (w23, 0)
e = (w23, self.device.display['height']/2)
self.device.drag(s, e, 500, 20, -1)
self.vc.sleep(1)
if self.vc.getSdkVersion() >= 20:
self.device.drag(s, e, 500, 20, -1)
self.vc.sleep(1)
self.vc.dump(-1) | python | def openQuickSettings(self):
'''
Opens the Quick Settings shade.
'''
# the tablet has a different Notification/Quick Settings bar depending on x
w23 = 2 * self.device.display['width'] / 3
s = (w23, 0)
e = (w23, self.device.display['height']/2)
self.device.drag(s, e, 500, 20, -1)
self.vc.sleep(1)
if self.vc.getSdkVersion() >= 20:
self.device.drag(s, e, 500, 20, -1)
self.vc.sleep(1)
self.vc.dump(-1) | [
"def",
"openQuickSettings",
"(",
"self",
")",
":",
"# the tablet has a different Notification/Quick Settings bar depending on x",
"w23",
"=",
"2",
"*",
"self",
".",
"device",
".",
"display",
"[",
"'width'",
"]",
"/",
"3",
"s",
"=",
"(",
"w23",
",",
"0",
")",
"... | Opens the Quick Settings shade. | [
"Opens",
"the",
"Quick",
"Settings",
"shade",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L1235-L1249 |
226,485 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | UiAutomator2AndroidViewClient.StartElement | def StartElement(self, name, attributes):
'''
Expat start element event handler
'''
if name == 'hierarchy':
pass
elif name == 'node':
# Instantiate an Element object
attributes['uniqueId'] = 'id/no_id/%d' % self.idCount
bounds = re.split('[\][,]', attributes['bounds'])
attributes['bounds'] = ((int(bounds[1]), int(bounds[2])), (int(bounds[4]), int(bounds[5])))
if DEBUG_BOUNDS:
print >> sys.stderr, "bounds=", attributes['bounds']
self.idCount += 1
child = View.factory(attributes, self.device, version=self.version, uiAutomatorHelper=self.uiAutomatorHelper)
self.views.append(child)
# Push element onto the stack and make it a child of parent
if not self.nodeStack:
self.root = child
else:
self.parent = self.nodeStack[-1]
self.parent.add(child)
self.nodeStack.append(child) | python | def StartElement(self, name, attributes):
'''
Expat start element event handler
'''
if name == 'hierarchy':
pass
elif name == 'node':
# Instantiate an Element object
attributes['uniqueId'] = 'id/no_id/%d' % self.idCount
bounds = re.split('[\][,]', attributes['bounds'])
attributes['bounds'] = ((int(bounds[1]), int(bounds[2])), (int(bounds[4]), int(bounds[5])))
if DEBUG_BOUNDS:
print >> sys.stderr, "bounds=", attributes['bounds']
self.idCount += 1
child = View.factory(attributes, self.device, version=self.version, uiAutomatorHelper=self.uiAutomatorHelper)
self.views.append(child)
# Push element onto the stack and make it a child of parent
if not self.nodeStack:
self.root = child
else:
self.parent = self.nodeStack[-1]
self.parent.add(child)
self.nodeStack.append(child) | [
"def",
"StartElement",
"(",
"self",
",",
"name",
",",
"attributes",
")",
":",
"if",
"name",
"==",
"'hierarchy'",
":",
"pass",
"elif",
"name",
"==",
"'node'",
":",
"# Instantiate an Element object",
"attributes",
"[",
"'uniqueId'",
"]",
"=",
"'id/no_id/%d'",
"%... | Expat start element event handler | [
"Expat",
"start",
"element",
"event",
"handler"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L2250-L2272 |
226,486 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | Excerpt2Code.CharacterData | def CharacterData(self, data):
'''
Expat character data event handler
'''
if data.strip():
data = data.encode()
if not self.data:
self.data = data
else:
self.data += data | python | def CharacterData(self, data):
'''
Expat character data event handler
'''
if data.strip():
data = data.encode()
if not self.data:
self.data = data
else:
self.data += data | [
"def",
"CharacterData",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"strip",
"(",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
")",
"if",
"not",
"self",
".",
"data",
":",
"self",
".",
"data",
"=",
"data",
"else",
":",
"self",
"... | Expat character data event handler | [
"Expat",
"character",
"data",
"event",
"handler"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L2333-L2343 |
226,487 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.__updateNavButtons | def __updateNavButtons(self):
"""
Updates the navigation buttons that might be on the device screen.
"""
navButtons = None
for v in self.views:
if v.getId() == 'com.android.systemui:id/nav_buttons':
navButtons = v
break
if navButtons:
self.navBack = self.findViewById('com.android.systemui:id/back', navButtons)
self.navHome = self.findViewById('com.android.systemui:id/home', navButtons)
self.navRecentApps = self.findViewById('com.android.systemui:id/recent_apps', navButtons)
else:
if self.uiAutomatorHelper:
print >> sys.stderr, "WARNING: nav buttons not found. Perhaps the device has hardware buttons."
self.navBack = None
self.navHome = None
self.navRecentApps = None | python | def __updateNavButtons(self):
navButtons = None
for v in self.views:
if v.getId() == 'com.android.systemui:id/nav_buttons':
navButtons = v
break
if navButtons:
self.navBack = self.findViewById('com.android.systemui:id/back', navButtons)
self.navHome = self.findViewById('com.android.systemui:id/home', navButtons)
self.navRecentApps = self.findViewById('com.android.systemui:id/recent_apps', navButtons)
else:
if self.uiAutomatorHelper:
print >> sys.stderr, "WARNING: nav buttons not found. Perhaps the device has hardware buttons."
self.navBack = None
self.navHome = None
self.navRecentApps = None | [
"def",
"__updateNavButtons",
"(",
"self",
")",
":",
"navButtons",
"=",
"None",
"for",
"v",
"in",
"self",
".",
"views",
":",
"if",
"v",
".",
"getId",
"(",
")",
"==",
"'com.android.systemui:id/nav_buttons'",
":",
"navButtons",
"=",
"v",
"break",
"if",
"navBu... | Updates the navigation buttons that might be on the device screen. | [
"Updates",
"the",
"navigation",
"buttons",
"that",
"might",
"be",
"on",
"the",
"device",
"screen",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L3136-L3155 |
226,488 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.list | def list(self, sleep=1):
'''
List the windows.
Sleep is useful to wait some time before obtaining the new content when something in the
window has changed.
This also sets L{self.windows} as the list of windows.
@type sleep: int
@param sleep: sleep in seconds before proceeding to dump the content
@return: the list of windows
'''
if sleep > 0:
time.sleep(sleep)
if self.useUiAutomator:
raise Exception("Not implemented yet: listing windows with UiAutomator")
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((VIEW_SERVER_HOST, self.localPort))
except socket.error, ex:
raise RuntimeError("ERROR: Connecting to %s:%d: %s" % (VIEW_SERVER_HOST, self.localPort, ex))
s.send('list\r\n')
received = ""
doneRE = re.compile("DONE")
while True:
received += s.recv(1024)
if doneRE.search(received[-7:]):
break
s.close()
if DEBUG:
self.received = received
if DEBUG_RECEIVED:
print >>sys.stderr, "received %d chars" % len(received)
print >>sys.stderr
print >>sys.stderr, received
print >>sys.stderr
self.windows = {}
for line in received.split('\n'):
if not line:
break
if doneRE.search(line):
break
values = line.split()
if len(values) > 1:
package = values[1]
else:
package = "UNKNOWN"
if len(values) > 0:
wid = values[0]
else:
wid = '00000000'
self.windows[int('0x' + wid, 16)] = package
return self.windows | python | def list(self, sleep=1):
'''
List the windows.
Sleep is useful to wait some time before obtaining the new content when something in the
window has changed.
This also sets L{self.windows} as the list of windows.
@type sleep: int
@param sleep: sleep in seconds before proceeding to dump the content
@return: the list of windows
'''
if sleep > 0:
time.sleep(sleep)
if self.useUiAutomator:
raise Exception("Not implemented yet: listing windows with UiAutomator")
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((VIEW_SERVER_HOST, self.localPort))
except socket.error, ex:
raise RuntimeError("ERROR: Connecting to %s:%d: %s" % (VIEW_SERVER_HOST, self.localPort, ex))
s.send('list\r\n')
received = ""
doneRE = re.compile("DONE")
while True:
received += s.recv(1024)
if doneRE.search(received[-7:]):
break
s.close()
if DEBUG:
self.received = received
if DEBUG_RECEIVED:
print >>sys.stderr, "received %d chars" % len(received)
print >>sys.stderr
print >>sys.stderr, received
print >>sys.stderr
self.windows = {}
for line in received.split('\n'):
if not line:
break
if doneRE.search(line):
break
values = line.split()
if len(values) > 1:
package = values[1]
else:
package = "UNKNOWN"
if len(values) > 0:
wid = values[0]
else:
wid = '00000000'
self.windows[int('0x' + wid, 16)] = package
return self.windows | [
"def",
"list",
"(",
"self",
",",
"sleep",
"=",
"1",
")",
":",
"if",
"sleep",
">",
"0",
":",
"time",
".",
"sleep",
"(",
"sleep",
")",
"if",
"self",
".",
"useUiAutomator",
":",
"raise",
"Exception",
"(",
"\"Not implemented yet: listing windows with UiAutomator... | List the windows.
Sleep is useful to wait some time before obtaining the new content when something in the
window has changed.
This also sets L{self.windows} as the list of windows.
@type sleep: int
@param sleep: sleep in seconds before proceeding to dump the content
@return: the list of windows | [
"List",
"the",
"windows",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L3415-L3472 |
226,489 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.findViewById | def findViewById(self, viewId, root="ROOT", viewFilter=None):
'''
Finds the View with the specified viewId.
@type viewId: str
@param viewId: the ID of the view to find
@type root: str
@type root: View
@param root: the root node of the tree where the View will be searched
@type: viewFilter: function
@param viewFilter: a function that will be invoked providing the candidate View as a parameter
and depending on the return value (C{True} or C{False}) the View will be
selected and returned as the result of C{findViewById()} or ignored.
This can be C{None} and no extra filtering is applied.
@return: the C{View} found or C{None}
'''
if not root:
return None
if type(root) == types.StringType and root == "ROOT":
return self.findViewById(viewId, self.root, viewFilter)
if root.getId() == viewId:
if viewFilter:
if viewFilter(root):
return root
else:
return root
if re.match('^id/no_id', viewId) or re.match('^id/.+/.+', viewId):
if root.getUniqueId() == viewId:
if viewFilter:
if viewFilter(root):
return root;
else:
return root
for ch in root.children:
foundView = self.findViewById(viewId, ch, viewFilter)
if foundView:
if viewFilter:
if viewFilter(foundView):
return foundView
else:
return foundView | python | def findViewById(self, viewId, root="ROOT", viewFilter=None):
'''
Finds the View with the specified viewId.
@type viewId: str
@param viewId: the ID of the view to find
@type root: str
@type root: View
@param root: the root node of the tree where the View will be searched
@type: viewFilter: function
@param viewFilter: a function that will be invoked providing the candidate View as a parameter
and depending on the return value (C{True} or C{False}) the View will be
selected and returned as the result of C{findViewById()} or ignored.
This can be C{None} and no extra filtering is applied.
@return: the C{View} found or C{None}
'''
if not root:
return None
if type(root) == types.StringType and root == "ROOT":
return self.findViewById(viewId, self.root, viewFilter)
if root.getId() == viewId:
if viewFilter:
if viewFilter(root):
return root
else:
return root
if re.match('^id/no_id', viewId) or re.match('^id/.+/.+', viewId):
if root.getUniqueId() == viewId:
if viewFilter:
if viewFilter(root):
return root;
else:
return root
for ch in root.children:
foundView = self.findViewById(viewId, ch, viewFilter)
if foundView:
if viewFilter:
if viewFilter(foundView):
return foundView
else:
return foundView | [
"def",
"findViewById",
"(",
"self",
",",
"viewId",
",",
"root",
"=",
"\"ROOT\"",
",",
"viewFilter",
"=",
"None",
")",
":",
"if",
"not",
"root",
":",
"return",
"None",
"if",
"type",
"(",
"root",
")",
"==",
"types",
".",
"StringType",
"and",
"root",
"=... | Finds the View with the specified viewId.
@type viewId: str
@param viewId: the ID of the view to find
@type root: str
@type root: View
@param root: the root node of the tree where the View will be searched
@type: viewFilter: function
@param viewFilter: a function that will be invoked providing the candidate View as a parameter
and depending on the return value (C{True} or C{False}) the View will be
selected and returned as the result of C{findViewById()} or ignored.
This can be C{None} and no extra filtering is applied.
@return: the C{View} found or C{None} | [
"Finds",
"the",
"View",
"with",
"the",
"specified",
"viewId",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L3475-L3522 |
226,490 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.findViewByTagOrRaise | def findViewByTagOrRaise(self, tag, root="ROOT"):
'''
Finds the View with the specified tag or raise a ViewNotFoundException
'''
view = self.findViewWithAttribute('getTag()', tag, root)
if view:
return view
else:
raise ViewNotFoundException("tag", tag, root) | python | def findViewByTagOrRaise(self, tag, root="ROOT"):
'''
Finds the View with the specified tag or raise a ViewNotFoundException
'''
view = self.findViewWithAttribute('getTag()', tag, root)
if view:
return view
else:
raise ViewNotFoundException("tag", tag, root) | [
"def",
"findViewByTagOrRaise",
"(",
"self",
",",
"tag",
",",
"root",
"=",
"\"ROOT\"",
")",
":",
"view",
"=",
"self",
".",
"findViewWithAttribute",
"(",
"'getTag()'",
",",
"tag",
",",
"root",
")",
"if",
"view",
":",
"return",
"view",
"else",
":",
"raise",... | Finds the View with the specified tag or raise a ViewNotFoundException | [
"Finds",
"the",
"View",
"with",
"the",
"specified",
"tag",
"or",
"raise",
"a",
"ViewNotFoundException"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L3555-L3564 |
226,491 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.findViewWithAttribute | def findViewWithAttribute(self, attr, val, root="ROOT"):
'''
Finds the View with the specified attribute and value
'''
if DEBUG:
try:
print >> sys.stderr, u'findViewWithAttribute({0}, {1}, {2})'.format(attr, unicode(val, encoding='utf-8', errors='replace'), root)
except:
pass
print >> sys.stderr, " findViewWithAttribute: type(val)=", type(val)
return self.__findViewWithAttributeInTree(attr, val, root) | python | def findViewWithAttribute(self, attr, val, root="ROOT"):
'''
Finds the View with the specified attribute and value
'''
if DEBUG:
try:
print >> sys.stderr, u'findViewWithAttribute({0}, {1}, {2})'.format(attr, unicode(val, encoding='utf-8', errors='replace'), root)
except:
pass
print >> sys.stderr, " findViewWithAttribute: type(val)=", type(val)
return self.__findViewWithAttributeInTree(attr, val, root) | [
"def",
"findViewWithAttribute",
"(",
"self",
",",
"attr",
",",
"val",
",",
"root",
"=",
"\"ROOT\"",
")",
":",
"if",
"DEBUG",
":",
"try",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"u'findViewWithAttribute({0}, {1}, {2})'",
".",
"format",
"(",
"attr",
"... | Finds the View with the specified attribute and value | [
"Finds",
"the",
"View",
"with",
"the",
"specified",
"attribute",
"and",
"value"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L3681-L3693 |
226,492 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.findViewsWithAttribute | def findViewsWithAttribute(self, attr, val, root="ROOT"):
'''
Finds the Views with the specified attribute and value.
This allows you to see all items that match your criteria in the view hierarchy
Usage:
buttons = v.findViewsWithAttribute("class", "android.widget.Button")
'''
return self.__findViewsWithAttributeInTree(attr, val, root) | python | def findViewsWithAttribute(self, attr, val, root="ROOT"):
'''
Finds the Views with the specified attribute and value.
This allows you to see all items that match your criteria in the view hierarchy
Usage:
buttons = v.findViewsWithAttribute("class", "android.widget.Button")
'''
return self.__findViewsWithAttributeInTree(attr, val, root) | [
"def",
"findViewsWithAttribute",
"(",
"self",
",",
"attr",
",",
"val",
",",
"root",
"=",
"\"ROOT\"",
")",
":",
"return",
"self",
".",
"__findViewsWithAttributeInTree",
"(",
"attr",
",",
"val",
",",
"root",
")"
] | Finds the Views with the specified attribute and value.
This allows you to see all items that match your criteria in the view hierarchy
Usage:
buttons = v.findViewsWithAttribute("class", "android.widget.Button") | [
"Finds",
"the",
"Views",
"with",
"the",
"specified",
"attribute",
"and",
"value",
".",
"This",
"allows",
"you",
"to",
"see",
"all",
"items",
"that",
"match",
"your",
"criteria",
"in",
"the",
"view",
"hierarchy"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L3695-L3705 |
226,493 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.findViewWithAttributeThatMatches | def findViewWithAttributeThatMatches(self, attr, regex, root="ROOT"):
'''
Finds the list of Views with the specified attribute matching
regex
'''
return self.__findViewWithAttributeInTreeThatMatches(attr, regex, root) | python | def findViewWithAttributeThatMatches(self, attr, regex, root="ROOT"):
'''
Finds the list of Views with the specified attribute matching
regex
'''
return self.__findViewWithAttributeInTreeThatMatches(attr, regex, root) | [
"def",
"findViewWithAttributeThatMatches",
"(",
"self",
",",
"attr",
",",
"regex",
",",
"root",
"=",
"\"ROOT\"",
")",
":",
"return",
"self",
".",
"__findViewWithAttributeInTreeThatMatches",
"(",
"attr",
",",
"regex",
",",
"root",
")"
] | Finds the list of Views with the specified attribute matching
regex | [
"Finds",
"the",
"list",
"of",
"Views",
"with",
"the",
"specified",
"attribute",
"matching",
"regex"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L3721-L3727 |
226,494 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.click | def click(self, x=-1, y=-1, selector=None):
"""
An alias for touch.
:param x:
:param y:
:param selector:
:return:
"""
self.touch(x=x, y=y, selector=selector) | python | def click(self, x=-1, y=-1, selector=None):
self.touch(x=x, y=y, selector=selector) | [
"def",
"click",
"(",
"self",
",",
"x",
"=",
"-",
"1",
",",
"y",
"=",
"-",
"1",
",",
"selector",
"=",
"None",
")",
":",
"self",
".",
"touch",
"(",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"selector",
"=",
"selector",
")"
] | An alias for touch.
:param x:
:param y:
:param selector:
:return: | [
"An",
"alias",
"for",
"touch",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L3800-L3810 |
226,495 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.pressKeyCode | def pressKeyCode(self, keycode, metaState=0):
'''By default no meta state'''
if self.uiAutomatorHelper:
if DEBUG_UI_AUTOMATOR_HELPER:
print >> sys.stderr, "pressKeyCode(%d, %d)" % (keycode, metaState)
self.uiAutomatorHelper.pressKeyCode(keycode, metaState)
else:
warnings.warn("pressKeyCode only implemented using UiAutomatorHelper. Use AdbClient.type() instead") | python | def pressKeyCode(self, keycode, metaState=0):
'''By default no meta state'''
if self.uiAutomatorHelper:
if DEBUG_UI_AUTOMATOR_HELPER:
print >> sys.stderr, "pressKeyCode(%d, %d)" % (keycode, metaState)
self.uiAutomatorHelper.pressKeyCode(keycode, metaState)
else:
warnings.warn("pressKeyCode only implemented using UiAutomatorHelper. Use AdbClient.type() instead") | [
"def",
"pressKeyCode",
"(",
"self",
",",
"keycode",
",",
"metaState",
"=",
"0",
")",
":",
"if",
"self",
".",
"uiAutomatorHelper",
":",
"if",
"DEBUG_UI_AUTOMATOR_HELPER",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"pressKeyCode(%d, %d)\"",
"%",
"(",
"ke... | By default no meta state | [
"By",
"default",
"no",
"meta",
"state"
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L3872-L3879 |
226,496 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.__pickleable | def __pickleable(tree):
'''
Makes the tree pickleable.
'''
def removeDeviceReference(view):
'''
Removes the reference to a L{MonkeyDevice}.
'''
view.device = None
###########################################################################################
# FIXME: Unfortunately deepcopy does not work with MonkeyDevice objects, which is
# sadly the reason why we cannot pickle the tree and we need to remove the MonkeyDevice
# references.
# We wanted to copy the tree to preserve the original and make piclkleable the copy.
#treeCopy = copy.deepcopy(tree)
treeCopy = tree
# IMPORTANT:
# This assumes that the first element in the list is the tree root
ViewClient.__traverse(treeCopy[0], transform=removeDeviceReference)
###########################################################################################
return treeCopy | python | def __pickleable(tree):
'''
Makes the tree pickleable.
'''
def removeDeviceReference(view):
'''
Removes the reference to a L{MonkeyDevice}.
'''
view.device = None
###########################################################################################
# FIXME: Unfortunately deepcopy does not work with MonkeyDevice objects, which is
# sadly the reason why we cannot pickle the tree and we need to remove the MonkeyDevice
# references.
# We wanted to copy the tree to preserve the original and make piclkleable the copy.
#treeCopy = copy.deepcopy(tree)
treeCopy = tree
# IMPORTANT:
# This assumes that the first element in the list is the tree root
ViewClient.__traverse(treeCopy[0], transform=removeDeviceReference)
###########################################################################################
return treeCopy | [
"def",
"__pickleable",
"(",
"tree",
")",
":",
"def",
"removeDeviceReference",
"(",
"view",
")",
":",
"'''\n Removes the reference to a L{MonkeyDevice}.\n '''",
"view",
".",
"device",
"=",
"None",
"#############################################################... | Makes the tree pickleable. | [
"Makes",
"the",
"tree",
"pickleable",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L4144-L4167 |
226,497 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.distanceTo | def distanceTo(self, tree):
'''
Calculates the distance between the current state and the tree passed as argument.
@type tree: list of Views
@param tree: Tree of Views
@return: the distance
'''
return ViewClient.distance(ViewClient.__pickleable(self.views), tree) | python | def distanceTo(self, tree):
'''
Calculates the distance between the current state and the tree passed as argument.
@type tree: list of Views
@param tree: Tree of Views
@return: the distance
'''
return ViewClient.distance(ViewClient.__pickleable(self.views), tree) | [
"def",
"distanceTo",
"(",
"self",
",",
"tree",
")",
":",
"return",
"ViewClient",
".",
"distance",
"(",
"ViewClient",
".",
"__pickleable",
"(",
"self",
".",
"views",
")",
",",
"tree",
")"
] | Calculates the distance between the current state and the tree passed as argument.
@type tree: list of Views
@param tree: Tree of Views
@return: the distance | [
"Calculates",
"the",
"distance",
"between",
"the",
"current",
"state",
"and",
"the",
"tree",
"passed",
"as",
"argument",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L4169-L4177 |
226,498 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.distance | def distance(tree1, tree2):
'''
Calculates the distance between the two trees.
@type tree1: list of Views
@param tree1: Tree of Views
@type tree2: list of Views
@param tree2: Tree of Views
@return: the distance
'''
################################################################
#FIXME: this should copy the entire tree and then transform it #
################################################################
pickleableTree1 = ViewClient.__pickleable(tree1)
pickleableTree2 = ViewClient.__pickleable(tree2)
s1 = pickle.dumps(pickleableTree1)
s2 = pickle.dumps(pickleableTree2)
if DEBUG_DISTANCE:
print >>sys.stderr, "distance: calculating distance between", s1[:20], "and", s2[:20]
l1 = len(s1)
l2 = len(s2)
t = float(max(l1, l2))
if l1 == l2:
if DEBUG_DISTANCE:
print >>sys.stderr, "distance: trees have same length, using Hamming distance"
return ViewClient.__hammingDistance(s1, s2)/t
else:
if DEBUG_DISTANCE:
print >>sys.stderr, "distance: trees have different length, using Levenshtein distance"
return ViewClient.__levenshteinDistance(s1, s2)/t | python | def distance(tree1, tree2):
'''
Calculates the distance between the two trees.
@type tree1: list of Views
@param tree1: Tree of Views
@type tree2: list of Views
@param tree2: Tree of Views
@return: the distance
'''
################################################################
#FIXME: this should copy the entire tree and then transform it #
################################################################
pickleableTree1 = ViewClient.__pickleable(tree1)
pickleableTree2 = ViewClient.__pickleable(tree2)
s1 = pickle.dumps(pickleableTree1)
s2 = pickle.dumps(pickleableTree2)
if DEBUG_DISTANCE:
print >>sys.stderr, "distance: calculating distance between", s1[:20], "and", s2[:20]
l1 = len(s1)
l2 = len(s2)
t = float(max(l1, l2))
if l1 == l2:
if DEBUG_DISTANCE:
print >>sys.stderr, "distance: trees have same length, using Hamming distance"
return ViewClient.__hammingDistance(s1, s2)/t
else:
if DEBUG_DISTANCE:
print >>sys.stderr, "distance: trees have different length, using Levenshtein distance"
return ViewClient.__levenshteinDistance(s1, s2)/t | [
"def",
"distance",
"(",
"tree1",
",",
"tree2",
")",
":",
"################################################################",
"#FIXME: this should copy the entire tree and then transform it #",
"################################################################",
"pickleableTree1",
"=",
"View... | Calculates the distance between the two trees.
@type tree1: list of Views
@param tree1: Tree of Views
@type tree2: list of Views
@param tree2: Tree of Views
@return: the distance | [
"Calculates",
"the",
"distance",
"between",
"the",
"two",
"trees",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L4180-L4212 |
226,499 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.__hammingDistance | def __hammingDistance(s1, s2):
'''
Finds the Hamming distance between two strings.
@param s1: string
@param s2: string
@return: the distance
@raise ValueError: if the lenght of the strings differ
'''
l1 = len(s1)
l2 = len(s2)
if l1 != l2:
raise ValueError("Hamming distance requires strings of same size.")
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) | python | def __hammingDistance(s1, s2):
'''
Finds the Hamming distance between two strings.
@param s1: string
@param s2: string
@return: the distance
@raise ValueError: if the lenght of the strings differ
'''
l1 = len(s1)
l2 = len(s2)
if l1 != l2:
raise ValueError("Hamming distance requires strings of same size.")
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) | [
"def",
"__hammingDistance",
"(",
"s1",
",",
"s2",
")",
":",
"l1",
"=",
"len",
"(",
"s1",
")",
"l2",
"=",
"len",
"(",
"s2",
")",
"if",
"l1",
"!=",
"l2",
":",
"raise",
"ValueError",
"(",
"\"Hamming distance requires strings of same size.\"",
")",
"return",
... | Finds the Hamming distance between two strings.
@param s1: string
@param s2: string
@return: the distance
@raise ValueError: if the lenght of the strings differ | [
"Finds",
"the",
"Hamming",
"distance",
"between",
"two",
"strings",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L4216-L4232 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.