code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
obj = {}
cls.add_if_not_none(obj, cls._FIELD_LATITUDE, geolocation.latitude)
cls.add_if_not_none(obj, cls._FIELD_LONGITUDE, geolocation.longitude)
cls.add_if_not_none(obj, cls._FIELD_ALTITUDE, geolocation.altitude)
cls.add_if_not_none(obj, cls._FIELD_RADIUS, geolocation.radius)
return obj | def serialize(cls, geolocation) | :type geolocation: object_.Geolocation
:rtype: dict | 1.859212 | 1.898491 | 0.97931 |
if value is not None:
dict_[key] = str(value) | def add_if_not_none(cls, dict_, key, value) | :type dict_: dict[str, str]
:type key: str
:type value: float
:rtype: None | 5.845136 | 3.423464 | 1.707375 |
label_monetary_account = converter.deserialize(
object_.LabelMonetaryAccount,
obj
)
return target_class.create_from_label_monetary_account(
label_monetary_account
) | def deserialize(cls, target_class, obj) | :type target_class: object_.MonetaryAccountReference|type
:type obj: dict
:rtype: object_.MonetaryAccountReference | 8.406882 | 6.071608 | 1.384622 |
share_detail = target_class.__new__(target_class)
share_detail.__dict__ = {
cls._ATTRIBUTE_PAYMENT: converter.deserialize(
object_.ShareDetailPayment,
cls._get_field_or_none(cls._FIELD_DRAFT_PAYMENT, obj)
),
cls._ATTRIBUTE_READ_ONLY: converter.deserialize(
object_.ShareDetailReadOnly,
cls._get_field_or_none(cls._FIELD_READ_ONLY, obj)
),
cls._ATTRIBUTE_DRAFT_PAYMENT: converter.deserialize(
object_.ShareDetailDraftPayment,
cls._get_field_or_none(cls._FIELD_DRAFT_PAYMENT, obj)
),
}
return share_detail | def deserialize(cls, target_class, obj) | :type target_class: object_.ShareDetail|type
:type obj: dict
:rtype: object_.ShareDetail | 3.048108 | 2.784739 | 1.094576 |
return {
cls._FIELD_PAYMENT: converter.serialize(
share_detail._payment_field_for_request),
cls._FIELD_READ_ONLY: converter.serialize(
share_detail._read_only_field_for_request),
cls._FIELD_DRAFT_PAYMENT: converter.serialize(
share_detail._draft_payment
),
} | def serialize(cls, share_detail) | :type share_detail: object_.ShareDetail
:rtype: dict | 4.656015 | 5.037582 | 0.924256 |
pagination = client.Pagination()
pagination.__dict__.update(
cls.parse_pagination_dict(pagination_response)
)
return pagination | def deserialize(cls, target_class, pagination_response) | :type target_class: client.Pagination|type
:type pagination_response: dict
:rtype: client.Pagination | 7.403392 | 6.101883 | 1.213296 |
pagination_dict = {}
cls.update_dict_id_field_from_response_field(
pagination_dict,
cls._FIELD_OLDER_ID,
response_obj,
cls._FIELD_OLDER_URL,
client.Pagination.PARAM_OLDER_ID
)
cls.update_dict_id_field_from_response_field(
pagination_dict,
cls._FIELD_NEWER_ID,
response_obj,
cls._FIELD_NEWER_URL,
client.Pagination.PARAM_NEWER_ID
)
cls.update_dict_id_field_from_response_field(
pagination_dict,
cls._FIELD_FUTURE_ID,
response_obj,
cls._FIELD_FUTURE_URL,
client.Pagination.PARAM_NEWER_ID
)
return pagination_dict | def parse_pagination_dict(cls, response_obj) | :type response_obj: dict
:rtype: dict | 2.232042 | 2.229979 | 1.000925 |
url = response_obj[response_field]
if url is not None:
url_parsed = urlparse.urlparse(url)
parameters = urlparse.parse_qs(url_parsed.query)
dict_[dict_id_field] = int(
parameters[response_param][cls._INDEX_FIRST]
)
if cls._FIELD_COUNT in parameters and cls._FIELD_COUNT not in dict_:
dict_[cls._FIELD_COUNT] = int(
parameters[client.Pagination.PARAM_COUNT][cls._INDEX_FIRST]
) | def update_dict_id_field_from_response_field(cls, dict_, dict_id_field,
response_obj, response_field,
response_param) | :type dict_: dict
:type dict_id_field: str
:type response_obj: dict
:type response_field: str
:type response_param: str | 3.237003 | 3.233055 | 1.001221 |
self._initialize_installation()
self._register_device(device_description, permitted_ips)
self._initialize_session() | def _initialize(self, device_description, permitted_ips) | :type device_description: str
:type permitted_ips: list[str]
:rtype: None | 6.359007 | 6.311564 | 1.007517 |
private_key_client = security.generate_rsa_private_key()
installation = core.Installation.create(
self,
security.public_key_to_string(private_key_client.publickey())
).value
token = installation.token.token
public_key_server_string = \
installation.server_public_key.server_public_key
public_key_server = RSA.import_key(public_key_server_string)
self._installation_context = InstallationContext(
token,
private_key_client,
public_key_server
) | def _initialize_installation(self) | :rtype: None | 4.489009 | 4.243366 | 1.057889 |
from bunq.sdk.model.device_server_internal import DeviceServerInternal
DeviceServerInternal.create(
device_description,
self.api_key,
permitted_ips,
api_context=self
) | def _register_device(self, device_description,
permitted_ips) | :type device_description: str
:type permitted_ips: list[]
:rtype: None | 7.586243 | 7.719211 | 0.982774 |
session_server = core.SessionServer.create(self).value
token = session_server.token.token
expiry_time = self._get_expiry_timestamp(session_server)
user_id = session_server.get_referenced_user().id_
self._session_context = SessionContext(token, expiry_time, user_id) | def _initialize_session(self) | :rtype: None | 7.075973 | 6.555167 | 1.07945 |
timeout_seconds = cls._get_session_timeout_seconds(session_server)
time_now = datetime.datetime.now()
return time_now + datetime.timedelta(seconds=timeout_seconds) | def _get_expiry_timestamp(cls, session_server) | :type session_server: core.SessionServer
:rtype: datetime.datetime | 3.173339 | 2.828446 | 1.121937 |
if session_server.user_company is not None:
return session_server.user_company.session_timeout
elif session_server.user_person is not None:
return session_server.user_person.session_timeout
elif session_server.user_api_key is not None:
return session_server \
.user_api_key \
.requested_by_user \
.get_referenced_object() \
.session_timeout
else:
raise BunqException() | def _get_session_timeout_seconds(cls, session_server) | :type session_server: core.SessionServer
:rtype: int | 3.679429 | 3.484228 | 1.056024 |
if self.session_context is None:
return False
time_now = datetime.datetime.now()
time_to_expiry = self.session_context.expiry_time - time_now
time_to_expiry_minimum = datetime.timedelta(
seconds=self._TIME_TO_SESSION_EXPIRY_MINIMUM_SECONDS
)
return time_to_expiry > time_to_expiry_minimum | def is_session_active(self) | :rtype: bool | 3.250199 | 2.946623 | 1.103025 |
if self._session_context is not None:
return self.session_context.token
elif self._installation_context is not None:
return self.installation_context.token
else:
return None | def token(self) | :rtype: str | 4.117177 | 3.431427 | 1.199844 |
if path is None:
path = self._PATH_API_CONTEXT_DEFAULT
with open(path, self._FILE_MODE_WRITE) as file_:
file_.write(self.to_json()) | def save(self, path=None) | :type path: str
:rtype: None | 6.018171 | 5.734375 | 1.04949 |
if path is None:
path = cls._PATH_API_CONTEXT_DEFAULT
with open(path, cls._FILE_MODE_READ) as file_:
return cls.from_json(file_.read()) | def restore(cls, path=None) | :type path: str
:rtype: ApiContext | 5.561227 | 4.09183 | 1.359105 |
cls._api_context = api_context
cls._user_context = UserContext(api_context.session_context.user_id)
cls._user_context.init_main_monetary_account() | def load_api_context(cls, api_context) | :type api_context: ApiContext | 6.350336 | 5.712643 | 1.111628 |
import datetime
import inspect
from bunq.sdk import client
from bunq.sdk import context
from bunq.sdk.model import core
from bunq.sdk.json import adapters
from bunq.sdk.json import converter
from bunq.sdk.model.generated import object_
from bunq.sdk.model.generated import endpoint
converter.register_adapter(core.Installation, adapters.InstallationAdapter)
converter.register_adapter(
core.SessionServer,
adapters.SessionServerAdapter
)
converter.register_adapter(
context.InstallationContext,
adapters.InstallationContextAdapter
)
converter.register_adapter(
context.ApiEnvironmentType,
adapters.ApiEnvironmentTypeAdapter
)
converter.register_adapter(float, adapters.FloatAdapter)
converter.register_adapter(object_.Geolocation, adapters.GeolocationAdapter)
converter.register_adapter(
object_.MonetaryAccountReference,
adapters.MonetaryAccountReferenceAdapter
)
converter.register_adapter(object_.ShareDetail, adapters.ShareDetailAdapter)
converter.register_adapter(datetime.datetime, adapters.DateTimeAdapter)
converter.register_adapter(client.Pagination, adapters.PaginationAdapter)
def register_anchor_adapter(class_to_regsiter):
if issubclass(class_to_regsiter, core.AnchoredObjectInterface):
converter.register_adapter(
class_to_regsiter,
adapters.AnchoredObjectModelAdapter
)
def get_class(class_string_to_get):
if hasattr(object_, class_string_to_get):
return getattr(object_, class_string_to_get)
if hasattr(endpoint, class_string_to_get):
return getattr(endpoint, class_string_to_get)
for class_string in list(dir(object_) + dir(endpoint)):
class_ = get_class(class_string)
if not inspect.isclass(class_):
continue
register_anchor_adapter(class_) | def initialize_converter() | :rtype: None | 2.360734 | 2.338269 | 1.009607 |
head_bytes = _generate_request_head_bytes(method, endpoint, headers)
bytes_to_sign = head_bytes + body_bytes
signer = PKCS1_v1_5.new(private_key)
digest = SHA256.new()
digest.update(bytes_to_sign)
sign = signer.sign(digest)
return b64encode(sign) | def sign_request(private_key, method, endpoint, body_bytes, headers) | :type private_key: RSA.RsaKey
:type method: str
:type endpoint: str
:type body_bytes: bytes
:type headers: dict[str, str]
:rtype: str | 2.392539 | 2.398876 | 0.997358 |
head_string = _FORMAT_METHOD_AND_ENDPOINT.format(method, endpoint)
header_tuples = sorted((k, headers[k]) for k in headers)
for name, value in header_tuples:
if _should_sign_request_header(name):
head_string += _FORMAT_HEADER_STRING.format(name, value)
return (head_string + _DELIMITER_NEWLINE).encode() | def _generate_request_head_bytes(method, endpoint, headers) | :type method: str
:type endpoint: str
:type headers: dict[str, str]
:rtype: bytes | 3.753132 | 3.516824 | 1.067193 |
if header_name in {_HEADER_USER_AGENT, _HEADER_CACHE_CONTROL}:
return True
if re.match(_PATTERN_HEADER_PREFIX_BUNQ, header_name):
return True
return False | def _should_sign_request_header(header_name) | :type header_name: str
:rtype: bool | 6.817773 | 5.647274 | 1.207268 |
key = Random.get_random_bytes(_AES_KEY_SIZE)
iv = Random.get_random_bytes(_BLOCK_SIZE)
_add_header_client_encryption_key(api_context, key, custom_headers)
_add_header_client_encryption_iv(iv, custom_headers)
request_bytes = _encrypt_request_bytes(request_bytes, key, iv)
_add_header_client_encryption_hmac(request_bytes, key, iv, custom_headers)
return request_bytes | def encrypt(api_context, request_bytes, custom_headers) | :type api_context: bunq.sdk.context.ApiContext
:type request_bytes: bytes
:type custom_headers: dict[str, str]
:rtype: bytes | 2.918036 | 3.085069 | 0.945857 |
public_key_server = api_context.installation_context.public_key_server
key_cipher = PKCS1_v1_5_Cipher.new(public_key_server)
key_encrypted = key_cipher.encrypt(key)
key_encrypted_base64 = base64.b64encode(key_encrypted).decode()
custom_headers[_HEADER_CLIENT_ENCRYPTION_KEY] = key_encrypted_base64 | def _add_header_client_encryption_key(api_context, key, custom_headers) | :type api_context: bunq.sdk.context.ApiContext
:type key: bytes
:type custom_headers: dict[str, str]
:rtype: None | 2.969169 | 2.862663 | 1.037205 |
cipher = Cipher.AES.new(key, Cipher.AES.MODE_CBC, iv)
request_bytes_padded = _pad_bytes(request_bytes)
return cipher.encrypt(request_bytes_padded) | def _encrypt_request_bytes(request_bytes, key, iv) | :type request_bytes: bytes
:type key: bytes
:type iv: bytes
:rtype: bytes | 3.214006 | 3.131128 | 1.026469 |
padding_length = (_BLOCK_SIZE - len(request_bytes) % _BLOCK_SIZE)
padding_character = bytes(bytearray([padding_length]))
return request_bytes + padding_character * padding_length | def _pad_bytes(request_bytes) | :type request_bytes: bytes
:rtype: bytes | 3.196691 | 3.394854 | 0.941628 |
hashed = hmac.new(key, iv + request_bytes, sha1)
hashed_base64 = base64.b64encode(hashed.digest()).decode()
custom_headers[_HEADER_CLIENT_ENCRYPTION_HMAC] = hashed_base64 | def _add_header_client_encryption_hmac(request_bytes, key, iv, custom_headers) | :type request_bytes: bytes
:type key: bytes
:type iv: bytes
:type custom_headers: dict[str, str]
:rtype: None | 2.831303 | 2.998839 | 0.944133 |
head_bytes = _generate_response_head_bytes(status_code, headers)
bytes_signed = head_bytes + body_bytes
signer = PKCS1_v1_5.pkcs1_15.new(public_key_server)
digest = SHA256.new()
digest.update(bytes_signed)
signer.verify(digest, base64.b64decode(headers[_HEADER_SERVER_SIGNATURE])) | def validate_response(public_key_server, status_code, body_bytes, headers) | :type public_key_server: RSA.RsaKey
:type status_code: int
:type body_bytes: bytes
:type headers: dict[str, str]
:rtype: None | 3.464255 | 3.302855 | 1.048867 |
head_string = str(status_code) + _DELIMITER_NEWLINE
header_tuples = sorted((k, headers[k]) for k in headers)
for name, value in header_tuples:
name = _get_header_correctly_cased(name)
if _should_sign_response_header(name):
head_string += _FORMAT_HEADER_STRING.format(name, value)
return (head_string + _DELIMITER_NEWLINE).encode() | def _generate_response_head_bytes(status_code, headers) | :type status_code: int
:type headers: dict[str, str]
:rtype: bytes | 4.021459 | 3.905701 | 1.029638 |
header_name = header_name.capitalize()
matches = re.findall(_REGEX_FOR_LOWERCASE_HEADERS, header_name)
for match in matches:
header_name = (re.sub(match, match.upper(), header_name))
return header_name | def _get_header_correctly_cased(header_name) | :type header_name: str
:rtype: str | 3.567371 | 3.352292 | 1.064159 |
if header_name == _HEADER_SERVER_SIGNATURE:
return False
if re.match(_PATTERN_HEADER_PREFIX_BUNQ, header_name):
return True
return False | def _should_sign_response_header(header_name) | :type header_name: str
:rtype: bool | 8.082378 | 6.548315 | 1.234268 |
sandbox_user = __generate_new_sandbox_user()
return ApiContext(
ApiEnvironmentType.SANDBOX,
sandbox_user.api_key,
socket.gethostname()
) | def automatic_sandbox_install() | :rtype: ApiContext | 10.136911 | 6.32549 | 1.60255 |
url = ApiEnvironmentType.SANDBOX.uri_base + __ENDPOINT_SANDBOX_USER
headers = {
ApiClient.HEADER_REQUEST_ID: __UNIQUE_REQUEST_ID,
ApiClient.HEADER_CACHE_CONTROL: ApiClient._CACHE_CONTROL_NONE,
ApiClient.HEADER_GEOLOCATION: ApiClient._GEOLOCATION_ZERO,
ApiClient.HEADER_LANGUAGE: ApiClient._LANGUAGE_EN_US,
ApiClient.HEADER_REGION: ApiClient._REGION_NL_NL,
}
response = requests.request(ApiClient._METHOD_POST, url, headers=headers)
if response.status_code is ApiClient._STATUS_CODE_OK:
response_json = json.loads(response.text)
return endpoint.SandboxUser.from_json(
json.dumps(response_json[__FIELD_RESPONSE][__INDEX_FIRST][
__FIELD_API_KEY]))
raise BunqException(_ERROR_COULD_NOT_CREATE_NEW_SANDBOX_USER) | def __generate_new_sandbox_user() | :rtype: endpoint.SandboxUser | 4.322207 | 3.795435 | 1.138791 |
json = response_raw.body_bytes.decode()
obj = converter.json_to_class(dict, json)
value = converter.deserialize(cls, obj[cls._FIELD_RESPONSE])
return client.BunqResponse(value, response_raw.headers) | def _from_json_array_nested(cls, response_raw) | :type response_raw: client.BunqResponseRaw
:rtype: bunq.sdk.client.BunqResponse[cls] | 10.022992 | 7.79495 | 1.285831 |
json = response_raw.body_bytes.decode()
obj = converter.json_to_class(dict, json)
value = converter.deserialize(
cls,
cls._unwrap_response_single(obj, wrapper)
)
return client.BunqResponse(value, response_raw.headers) | def _from_json(cls, response_raw, wrapper=None) | :type response_raw: client.BunqResponseRaw
:type wrapper: str|None
:rtype: client.BunqResponse[cls] | 8.296427 | 7.228936 | 1.147669 |
if wrapper is not None:
return obj[cls._FIELD_RESPONSE][cls._INDEX_FIRST][wrapper]
return obj[cls._FIELD_RESPONSE][cls._INDEX_FIRST] | def _unwrap_response_single(cls, obj, wrapper=None) | :type obj: dict
:type wrapper: str|None
:rtype: dict | 4.863892 | 4.475292 | 1.086832 |
json = response_raw.body_bytes.decode()
obj = converter.json_to_class(dict, json)
id_ = converter.deserialize(
Id,
cls._unwrap_response_single(obj, cls._FIELD_ID)
)
return client.BunqResponse(id_.id_, response_raw.headers) | def _process_for_id(cls, response_raw) | :type response_raw: client.BunqResponseRaw
:rtype: client.BunqResponse[int] | 10.231139 | 8.837927 | 1.15764 |
json = response_raw.body_bytes.decode()
obj = converter.json_to_class(dict, json)
uuid = converter.deserialize(
Uuid,
cls._unwrap_response_single(obj, cls._FIELD_UUID)
)
return client.BunqResponse(uuid.uuid, response_raw.headers) | def _process_for_uuid(cls, response_raw) | :type response_raw: client.BunqResponseRaw
:rtype: client.BunqResponse[str] | 9.739377 | 8.359808 | 1.165024 |
json = response_raw.body_bytes.decode()
obj = converter.json_to_class(dict, json)
array = obj[cls._FIELD_RESPONSE]
array_deserialized = []
for item in array:
item_unwrapped = item if wrapper is None else item[wrapper]
item_deserialized = converter.deserialize(cls, item_unwrapped)
array_deserialized.append(item_deserialized)
pagination = converter.deserialize(client.Pagination,
obj[cls._FIELD_PAGINATION])
return client.BunqResponse(array_deserialized, response_raw.headers,
pagination) | def _from_json_list(cls, response_raw, wrapper=None) | :type response_raw: client.BunqResponseRaw
:type wrapper: str|None
:rtype: client.BunqResponse[list[cls]] | 4.394794 | 3.803921 | 1.155332 |
if monetary_account_id is None:
return context.BunqContext.user_context().primary_monetary_account.id_
return monetary_account_id | def _determine_monetary_account_id(cls, monetary_account_id=None) | :type monetary_account_id: int
:rtype: int | 5.991033 | 6.204513 | 0.965593 |
api_client = client.ApiClient(api_context)
body_bytes = cls.generate_request_body_bytes(
public_key_string
)
response_raw = api_client.post(cls._ENDPOINT_URL_POST, body_bytes, {})
return cls._from_json_array_nested(response_raw) | def create(cls, api_context, public_key_string) | :type api_context: bunq.sdk.context.ApiContext
:type public_key_string: str
:rtype: client.BunqResponse[Installation] | 5.47397 | 5.261506 | 1.040381 |
if self._user_person is not None:
return self._user_person
if self._user_company is not None:
return self._user_company
if self._user_api_key is not None:
return self._user_api_key
raise BunqException(self._ERROR_ALL_FIELD_IS_NULL) | def get_referenced_user(self) | :rtype: BunqModel | 3.574015 | 2.836959 | 1.259805 |
if not package:
package = '%s.resources.images' % calling_package()
name = resource_filename(package, name)
if not name.startswith('/'):
return 'file://%s' % abspath(name)
return 'file://%s' % name | def icon_resource(name, package=None) | Returns the absolute URI path to an image. If a package is not explicitly specified then the calling package name is
used.
:param name: path relative to package path of the image resource.
:param package: package name in dotted format.
:return: the file URI path to the image resource (i.e. file:///foo/bar/image.png). | 4.137726 | 4.083937 | 1.013171 |
if not package:
package = calling_package()
package_dir = '.'.join([package, directory])
images = []
for i in resource_listdir(package, directory):
if i.startswith('__') or i.endswith('.egg-info'):
continue
fname = resource_filename(package_dir, i)
if resource_isdir(package_dir, i):
images.extend(image_resources(package_dir, i))
elif what(fname):
images.append(fname)
return images | def image_resources(package=None, directory='resources') | Returns all images under the directory relative to a package path. If no directory or package is specified then the
resources module of the calling package will be used. Images are recursively discovered.
:param package: package name in dotted format.
:param directory: path relative to package path of the resources directory.
:return: a list of images under the specified resources path. | 3.033103 | 2.922444 | 1.037865 |
transform = None
try:
transform = load_object(transform_py_name)()
if os.name == 'posix' and transform.superuser and os.geteuid():
rc = sudo(sys.argv)
if rc == 1:
message_writer(MaltegoTransformResponseMessage() + UIMessage('User cancelled transform.'))
elif rc == 2:
message_writer(MaltegoTransformResponseMessage() + UIMessage('Too many incorrect password attempts.'))
elif rc:
message_writer(MaltegoTransformResponseMessage() + UIMessage('Unknown error occurred.'))
sys.exit(rc)
on_terminate(transform.on_terminate)
request = MaltegoTransformRequestMessage(
parameters={'canari.local.arguments': Field(name='canari.local.arguments', value=params)}
)
request._entities = [to_entity(transform.input_type, value, fields)]
request.limits = Limits(soft=10000)
msg = transform.do_transform(
request,
MaltegoTransformResponseMessage(),
config
)
if isinstance(msg, MaltegoTransformResponseMessage):
message_writer(msg)
elif isinstance(msg, string_types):
raise MaltegoException(msg)
else:
raise MaltegoException('Could not resolve message type returned by transform.')
except MaltegoException as me:
croak(me, message_writer)
except KeyboardInterrupt:
# Ensure that the keyboard interrupt handler does not execute twice if a transform is sudo'd
if transform and (transform.superuser and not os.geteuid()) or (not transform.superuser and os.geteuid()):
transform.on_terminate()
except Exception:
croak(traceback.format_exc(), message_writer) | def local_transform_runner(transform_py_name, value, fields, params, config, message_writer=message) | Internal API: The local transform runner is responsible for executing the local transform.
Parameters:
transform - The name or module of the transform to execute (i.e sploitego.transforms.whatismyip).
value - The input entity value.
fields - A dict of the field names and their respective values.
params - The extra parameters passed into the transform via the command line.
config - The Canari configuration object.
message_writer - The message writing function used to write the MaltegoTransformResponseMessage to stdout. This is
can either be the console_message or message functions. Alternatively, the message_writer function
can be any callable object that accepts the MaltegoTransformResponseMessage as the first parameter
and writes the output to a destination of your choosing.
This helper function is only used by the run-transform, debug-transform, and dispatcher commands. | 4.530871 | 4.264593 | 1.062439 |
tab += 1
if isinstance(msg, Model):
msg = fromstring(msg.render(encoding='utf-8'))
print('%s`- %s: %s %s' % (
' ' * tab,
click.style(msg.tag, bold=True),
click.style(msg.text, fg='red') if msg.text is not None else '',
click.style(repr(msg.attrib), fg='green', bold=True) if msg.attrib.keys() else ''
))
for c in msg.getchildren():
print(' %s`- %s: %s %s' % (
' ' * tab,
click.style(c.tag, bold=True),
click.style(c.text, fg='red') if c.text is not None else '',
click.style(repr(c.attrib), fg='green', bold=True) if c.attrib.keys() else ''
))
for sc in c.getchildren():
tab += 1
console_writer(sc, tab)
tab -= 1 | def console_writer(msg, tab=-1) | Internal API: Returns a prettified tree-based output of an XML message for debugging purposes. This helper function
is used by the debug-transform command. | 2.328649 | 2.250115 | 1.034902 |
return boolbox(msg, title, choices, image=image) | def ynbox(msg="Shall I continue?"
, title=" "
, choices=("Yes", "No")
, image=None
) | Display a msgbox with choices of Yes and No.
The default is "Yes".
The returned value is calculated this way::
if the first choice ("Yes") is chosen, or if the dialog is cancelled:
return 1
else:
return 0
If invoked without a msg argument, displays a generic request for a confirmation
that the user wishes to continue. So it can be used this way::
if ynbox(): pass # continue
else: sys.exit(0) # exit the program
@arg msg: the msg to be displayed.
@arg title: the window title
@arg choices: a list or tuple of the choices to be displayed | 5.305628 | 27.891972 | 0.190221 |
return boolbox(msg, title, choices, image=image) | def ccbox(msg="Shall I continue?"
, title=" "
, choices=("Continue", "Cancel")
, image=None
) | Display a msgbox with choices of Continue and Cancel.
The default is "Continue".
The returned value is calculated this way::
if the first choice ("Continue") is chosen, or if the dialog is cancelled:
return 1
else:
return 0
If invoked without a msg argument, displays a generic request for a confirmation
that the user wishes to continue. So it can be used this way::
if ccbox():
pass # continue
else:
sys.exit(0) # exit the program
@arg msg: the msg to be displayed.
@arg title: the window title
@arg choices: a list or tuple of the choices to be displayed | 5.088627 | 27.262482 | 0.186653 |
reply = buttonbox(msg=msg, choices=choices, title=title, image=image)
if reply == choices[0]: return 1
else: return 0 | def boolbox(msg="Shall I continue?"
, title=" "
, choices=("Yes","No")
, image=None
) | Display a boolean msgbox.
The default is the first choice.
The returned value is calculated this way::
if the first choice is chosen, or if the dialog is cancelled:
returns 1
else:
returns 0 | 2.648368 | 3.873197 | 0.683768 |
reply = buttonbox(msg=msg, choices=choices, title=title, image=image)
index = -1
for choice in choices:
index = index + 1
if reply == choice: return index
raise AssertionError(
"There is a program logic error in the EasyGui code for indexbox.") | def indexbox(msg="Shall I continue?"
, title=" "
, choices=("Yes","No")
, image=None
) | Display a buttonbox with the specified choices.
Return the index of the choice selected. | 5.509401 | 5.871893 | 0.938267 |
if type(ok_button) != type("OK"):
raise AssertionError("The 'ok_button' argument to msgbox must be a string.")
return buttonbox(msg=msg, title=title, choices=[ok_button], image=image,root=root) | def msgbox(msg="(Your message goes here)", title=" ", ok_button="OK",image=None,root=None) | Display a messagebox | 3.633652 | 3.710203 | 0.979367 |
if sys.platform == 'darwin':
_bring_to_front()
global boxRoot, __replyButtonText, __widgetTexts, buttonsFrame
# Initialize __replyButtonText to the first choice.
# This is what will be used if the window is closed by the close button.
__replyButtonText = choices[0]
if root:
root.withdraw()
boxRoot = Toplevel(master=root)
boxRoot.withdraw()
else:
boxRoot = Tk()
boxRoot.withdraw()
boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose )
boxRoot.title(title)
boxRoot.iconname('Dialog')
boxRoot.geometry(rootWindowPosition)
boxRoot.minsize(400, 100)
# ------------- define the messageFrame ---------------------------------
messageFrame = Frame(master=boxRoot)
messageFrame.pack(side=TOP, fill=BOTH)
# ------------- define the imageFrame ---------------------------------
tk_Image = None
if image:
imageFilename = os.path.normpath(image)
junk,ext = os.path.splitext(imageFilename)
if os.path.exists(imageFilename):
if ext.lower() in [".gif", ".pgm", ".ppm"]:
tk_Image = PhotoImage(master=boxRoot, file=imageFilename)
else:
if PILisLoaded:
try:
pil_Image = PILImage.open(imageFilename)
tk_Image = PILImageTk.PhotoImage(pil_Image, master=boxRoot)
except:
msg += ImageErrorMsg % (imageFilename,
"\nThe Python Imaging Library (PIL) could not convert this file to a displayable image."
"\n\nPIL reports:\n" + exception_format())
else: # PIL is not loaded
msg += ImageErrorMsg % (imageFilename,
"\nI could not import the Python Imaging Library (PIL) to display the image.\n\n"
"You may need to install PIL\n"
"(http://www.pythonware.com/products/pil/)\n"
"to display " + ext + " image files.")
else:
msg += ImageErrorMsg % (imageFilename, "\nImage file not found.")
if tk_Image:
imageFrame = Frame(master=boxRoot)
imageFrame.pack(side=TOP, fill=BOTH)
label = Label(imageFrame,image=tk_Image)
label.image = tk_Image # keep a reference!
label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m')
# ------------- define the buttonsFrame ---------------------------------
buttonsFrame = Frame(master=boxRoot)
buttonsFrame.pack(side=TOP, fill=BOTH)
# -------------------- place the widgets in the frames -----------------------
messageWidget = Message(messageFrame, text=msg, width=400)
messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE))
messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m')
__put_buttons_in_buttonframe(choices)
# -------------- the action begins -----------
# put the focus on the first button
__firstWidget.focus_force()
boxRoot.deiconify()
boxRoot.mainloop()
boxRoot.destroy()
if root: root.deiconify()
return __replyButtonText | def buttonbox(msg="",title=" "
,choices=("Button1", "Button2", "Button3")
, image=None
, root=None
) | Display a msg, a title, and a set of buttons.
The buttons are defined by the members of the choices list.
Return the text of the button that the user selected.
@arg msg: the msg to be displayed.
@arg title: the window title
@arg choices: a list or tuple of the choices to be displayed | 3.144359 | 3.247599 | 0.968211 |
if sys.platform == 'darwin':
_bring_to_front()
if "argLowerBound" in invalidKeywordArguments:
raise AssertionError(
"\nintegerbox no longer supports the 'argLowerBound' argument.\n"
+ "Use 'lowerbound' instead.\n\n")
if "argUpperBound" in invalidKeywordArguments:
raise AssertionError(
"\nintegerbox no longer supports the 'argUpperBound' argument.\n"
+ "Use 'upperbound' instead.\n\n")
if default != "":
if type(default) != type(1):
raise AssertionError(
"integerbox received a non-integer value for "
+ "default of " + dq(str(default)) , "Error")
if type(lowerbound) != type(1):
raise AssertionError(
"integerbox received a non-integer value for "
+ "lowerbound of " + dq(str(lowerbound)) , "Error")
if type(upperbound) != type(1):
raise AssertionError(
"integerbox received a non-integer value for "
+ "upperbound of " + dq(str(upperbound)) , "Error")
if msg == "":
msg = ("Enter an integer between " + str(lowerbound)
+ " and "
+ str(upperbound)
)
while 1:
reply = enterbox(msg, title, str(default), image=image, root=root)
if reply is None:
return None
try:
reply = int(reply)
except:
msgbox ("The value that you entered:\n\t%s\nis not an integer." % dq(str(reply))
, "Error")
continue
if reply < lowerbound:
msgbox ("The value that you entered is less than the lower bound of "
+ str(lowerbound) + ".", "Error")
continue
if reply > upperbound:
msgbox ("The value that you entered is greater than the upper bound of "
+ str(upperbound) + ".", "Error")
continue
# reply has passed all validation checks.
# It is an integer between the specified bounds.
return reply | def integerbox(msg=""
, title=" "
, default=""
, lowerbound=0
, upperbound=99
, image = None
, root = None
, **invalidKeywordArguments
) | Show a box in which a user can enter an integer.
In addition to arguments for msg and title, this function accepts
integer arguments for "default", "lowerbound", and "upperbound".
The default argument may be None.
When the user enters some text, the text is checked to verify that it
can be converted to an integer between the lowerbound and upperbound.
If it can be, the integer (not the text) is returned.
If it cannot, then an error msg is displayed, and the integerbox is
redisplayed.
If the user cancels the operation, None is returned.
NOTE that the "argLowerBound" and "argUpperBound" arguments are no longer
supported. They have been replaced by "upperbound" and "lowerbound". | 2.3258 | 2.273727 | 1.022902 |
r
return __multfillablebox(msg,title,fields,values,"*") | def multpasswordbox(msg="Fill in values for the fields."
, title=" "
, fields=tuple()
,values=tuple()
) | r"""
Same interface as multenterbox. But in multpassword box,
the last of the fields is assumed to be a password, and
is masked with asterisks.
Example
=======
Here is some example code, that shows how values returned from
multpasswordbox can be checked for validity before they are accepted::
msg = "Enter logon information"
title = "Demo of multpasswordbox"
fieldNames = ["Server ID", "User ID", "Password"]
fieldValues = [] # we start with blanks for the values
fieldValues = multpasswordbox(msg,title, fieldNames)
# make sure that none of the fields was left blank
while 1:
if fieldValues == None: break
errmsg = ""
for i in range(len(fieldNames)):
if fieldValues[i].strip() == "":
errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i])
if errmsg == "": break # no problems found
fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues)
writeln("Reply was: %s" % str(fieldValues)) | 20.91123 | 53.264751 | 0.39259 |
result = __fillablebox(msg, title, default=default, mask=None,image=image,root=root)
if result and strip:
result = result.strip()
return result | def enterbox(msg="Enter something."
, title=" "
, default=""
, strip=True
, image=None
, root=None
) | Show a box in which a user can enter some text.
You may optionally specify some default text, which will appear in the
enterbox when it is displayed.
Returns the text that the user entered, or None if he cancels the operation.
By default, enterbox strips its result (i.e. removes leading and trailing
whitespace). (If you want it not to strip, use keyword argument: strip=False.)
This makes it easier to test the results of the call::
reply = enterbox(....)
if reply:
...
else:
... | 5.489161 | 9.383274 | 0.584994 |
return __fillablebox(msg, title, default, mask="*",image=image,root=root) | def passwordbox(msg="Enter your password."
, title=" "
, default=""
, image=None
, root=None
) | Show a box in which a user can enter a password.
The text is masked with asterisks, so the password is not displayed.
Returns the text that the user entered, or None if he cancels the operation. | 11.256577 | 12.103391 | 0.930035 |
if len(choices) == 0: choices = ["Program logic error - no choices were specified."]
global __choiceboxMultipleSelect
__choiceboxMultipleSelect = 1
return __choicebox(msg, title, choices) | def multchoicebox(msg="Pick as many items as you like."
, title=" "
, choices=()
, **kwargs
) | Present the user with a list of choices.
allow him to select multiple items and return them in a list.
if the user doesn't choose anything from the list, return the empty list.
return None if he cancelled selection.
@arg msg: the msg to be displayed.
@arg title: the window title
@arg choices: a list or tuple of the choices to be displayed | 9.459044 | 13.191953 | 0.717031 |
if len(choices) == 0: choices = ["Program logic error - no choices were specified."]
global __choiceboxMultipleSelect
__choiceboxMultipleSelect = 0
return __choicebox(msg,title,choices) | def choicebox(msg="Pick something."
, title=" "
, choices=()
) | Present the user with a list of choices.
return the choice that he selects.
return None if he cancels the selection selection.
@arg msg: the msg to be displayed.
@arg title: the window title
@arg choices: a list or tuple of the choices to be displayed | 7.911793 | 13.162625 | 0.60108 |
if sys.platform == 'darwin':
_bring_to_front()
title=getFileDialogTitle(msg,title)
localRoot = Tk()
localRoot.withdraw()
if not default: default = None
f = tk_FileDialog.askdirectory(
parent=localRoot
, title=title
, initialdir=default
, initialfile=None
)
localRoot.destroy()
if not f: return None
return os.path.normpath(f) | def diropenbox(msg=None
, title=None
, default=None
) | A dialog to get a directory name.
Note that the msg argument, if specified, is ignored.
Returns the name of a directory, or None if user chose to cancel.
If the "default" argument specifies a directory name, and that
directory exists, then the dialog box will start with that directory. | 3.952541 | 4.692076 | 0.842386 |
if sys.platform == 'darwin':
_bring_to_front()
localRoot = Tk()
localRoot.withdraw()
initialbase, initialfile, initialdir, filetypes = fileboxSetup(default,filetypes)
#------------------------------------------------------------
# if initialfile contains no wildcards; we don't want an
# initial file. It won't be used anyway.
# Also: if initialbase is simply "*", we don't want an
# initialfile; it is not doing any useful work.
#------------------------------------------------------------
if (initialfile.find("*") < 0) and (initialfile.find("?") < 0):
initialfile = None
elif initialbase == "*":
initialfile = None
f = tk_FileDialog.askopenfilename(parent=localRoot
, title=getFileDialogTitle(msg,title)
, initialdir=initialdir
, initialfile=initialfile
, filetypes=filetypes
)
localRoot.destroy()
if not f: return None
return os.path.normpath(f) | def fileopenbox(msg=None
, title=None
, default="*"
, filetypes=None
) | A dialog to get a file name.
About the "default" argument
============================
The "default" argument specifies a filepath that (normally)
contains one or more wildcards.
fileopenbox will display only files that match the default filepath.
If omitted, defaults to "*" (all files in the current directory).
WINDOWS EXAMPLE::
...default="c:/myjunk/*.py"
will open in directory c:\myjunk\ and show all Python files.
WINDOWS EXAMPLE::
...default="c:/myjunk/test*.py"
will open in directory c:\myjunk\ and show all Python files
whose names begin with "test".
Note that on Windows, fileopenbox automatically changes the path
separator to the Windows path separator (backslash).
About the "filetypes" argument
==============================
If specified, it should contain a list of items,
where each item is either::
- a string containing a filemask # e.g. "*.txt"
- a list of strings, where all of the strings except the last one
are filemasks (each beginning with "*.",
such as "*.txt" for text files, "*.py" for Python files, etc.).
and the last string contains a filetype description
EXAMPLE::
filetypes = ["*.css", ["*.htm", "*.html", "HTML files"] ]
NOTE THAT
=========
If the filetypes list does not contain ("All files","*"),
it will be added.
If the filetypes list does not contain a filemask that includes
the extension of the "default" argument, it will be added.
For example, if default="*abc.py"
and no filetypes argument was specified, then
"*.py" will automatically be added to the filetypes argument.
@rtype: string or None
@return: the name of a file, or None if user chose to cancel
@arg msg: the msg to be displayed.
@arg title: the window title
@arg default: filepath with wildcards
@arg filetypes: filemasks that a user can choose, e.g. "*.txt" | 4.720273 | 5.166422 | 0.913644 |
global boxRoot, __widgetTexts, __replyButtonText
__replyButtonText = __widgetTexts[event.widget]
boxRoot.quit() | def __buttonEvent(event) | Handle an event that is generated by a person clicking a button. | 23.664099 | 23.763927 | 0.995799 |
v = MaltegoMessage(message=msg).render(encoding='utf-8')
return Response(v, status=200, mimetype='text/xml') | def message(msg) | Write a MaltegoMessage to stdout and exit successfully | 12.172861 | 7.943179 | 1.532492 |
def exit_function(*args):
func()
exit(0)
signal.signal(signal.SIGTERM, exit_function) | def on_terminate(func) | Register a signal handler to execute when Maltego forcibly terminates the transform. | 3.605646 | 3.597311 | 1.002317 |
if sys.platform == 'win32':
decoding = sys.stdout.encoding if sys.version_info[0] > 2 else 'cp1252'
click.echo(MaltegoMessage(message=m).render(fragment=True, encoding='utf-8').decode(decoding), file=fd)
else:
click.echo(MaltegoMessage(message=m).render(encoding='utf-8', fragment=True), file=fd)
exit(0) | def message(m, fd=sys.stdout) | Write a MaltegoMessage to stdout and exit successfully | 3.454584 | 3.103293 | 1.113199 |
if isinstance(error, MaltegoException):
message_writer(MaltegoTransformExceptionMessage(exceptions=[error]))
else:
message_writer(MaltegoTransformExceptionMessage(exceptions=[MaltegoException(error)])) | def croak(error, message_writer=message) | Throw an exception in the Maltego GUI containing error_msg. | 4.54015 | 3.04332 | 1.491841 |
e = entity_type(value)
for k, v in fields.items():
e.fields[k] = Field(k, v)
return e | def to_entity(entity_type, value, fields) | Internal API: Returns an instance of an entity of type entity_type with the specified value and fields (stored in
dict). This is only used by the local transform runner as a helper function. | 3.550197 | 3.508225 | 1.011964 |
if sys.version_info[0] > 3:
spec = inspect.getfullargspec(transform)
else:
spec = inspect.getargspec(transform)
if spec.varargs:
return 3
n = len(spec.args)
if 2 <= n <= 3:
return n
raise Exception('Could not determine transform version.') | def get_transform_version(transform) | Internal API: Returns the version of the transform function based on the transform function's signature. Currently,
only two versions are supported (2 and 3). This is what version 2 transform functions look like:
def transform(request, response):
...
Version 3 transforms have the additional config variable like so:
def transform(request, response, config):
...
Or can have a varargs parameter as a third argument:
def transform(request, response, *args):
...
In both cases, version 3 transforms will be passed a local copy of the canari configuration object as the third
argument. However, in the latter example, the configuration object will be stored in a tuple (i.e. (config,)). | 3.256932 | 2.748345 | 1.185052 |
for i in args:
click.echo('D:%s' % str(i), err=True) | def debug(*args) | Send debug messages to the Maltego console. | 7.345047 | 7.064711 | 1.039681 |
from canari.commands.create_aws_lambda import create_aws_lambda
create_aws_lambda(ctx.project, bucket, region_name, aws_access_key_id, aws_secret_access_key) | def create_aws_lambda(ctx, bucket, region_name, aws_access_key_id, aws_secret_access_key) | Creates an AWS Chalice project for deployment to AWS Lambda. | 3.241109 | 2.982564 | 1.086686 |
from canari.commands.create_package import create_package
create_package(package, author, email, description, create_example) | def create_package(package, author, email, description, create_example) | Creates a Canari transform package skeleton. | 4.761158 | 2.979909 | 1.597753 |
from canari.commands.create_profile import create_profile
create_profile(ctx.config_dir, ctx.project, package) | def create_profile(ctx, package) | Creates an importable Maltego profile (*.mtz) file. | 9.39035 | 9.652221 | 0.972869 |
from canari.commands.create_transform import create_transform
create_transform(ctx.project, transform) | def create_transform(ctx, transform) | Creates a new transform in the specified directory and auto-updates dependencies. | 13.146358 | 9.961802 | 1.319677 |
from canari.commands.debug_transform import debug_transform
debug_transform(transform, value, fields, params, ctx.project, ctx.config) | def debug_transform(ctx, transform, params, value, fields) | Runs Canari local transforms in a terminal-friendly fashion. | 9.695469 | 7.637939 | 1.269383 |
from canari.commands.dockerize_package import dockerize_package
dockerize_package(ctx.project, os, host) | def dockerize_package(ctx, os, host) | Creates a Docker build file pre-configured with Plume. | 9.181887 | 8.798799 | 1.043539 |
from canari.commands.generate_entities import generate_entities
generate_entities(
ctx.project, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity) | def generate_entities(ctx, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity) | Converts Maltego entity definition files to Canari python classes.
Excludes Maltego built-in entities by default. | 4.088519 | 3.706028 | 1.103208 |
from canari.commands.generate_entities_doc import generate_entities_doc
generate_entities_doc(ctx.project, out_path, package) | def generate_entities_doc(ctx, out_path, package) | Create entities documentation from Canari python classes file. | 5.290452 | 3.426171 | 1.54413 |
from canari.commands.load_plume_package import load_plume_package
load_plume_package(package, plume_dir, accept_defaults) | def load_plume_package(package, plume_dir, accept_defaults) | Loads a canari package into Plume. | 3.978723 | 2.507107 | 1.586977 |
from canari.commands.remote_transform import remote_transform
remote_transform(host, transform, input, entity_field, transform_parameter, raw_output, ssl,
base_path, soft_limit, hard_limit, verbose) | def remote_transform(host, transform, input, entity_field, transform_parameter, raw_output, ssl,
base_path, soft_limit, hard_limit, verbose) | Runs Canari local transforms in a terminal-friendly fashion. | 2.600729 | 2.255694 | 1.152962 |
ctx.mode = CanariMode.LocalShellDebug
from canari.commands.shell import shell
shell(package, working_dir, sudo) | def shell(ctx, package, working_dir, sudo) | Runs a Canari interactive python shell | 18.245296 | 11.354026 | 1.606945 |
from canari.commands.unload_plume_package import unload_plume_package
unload_plume_package(package, plume_dir) | def unload_plume_package(package, plume_dir) | Unloads a canari package from Plume. | 4.204894 | 2.816002 | 1.493214 |
global canari_mode
old_mode = canari_mode
canari_mode = mode
return old_mode | def set_canari_mode(mode=CanariMode.Unknown) | Sets the global operating mode for Canari. This is used to alter the behaviour of dangerous classes like the
CanariConfigParser.
:param mode: the numeric Canari operating mode (CanariMode.Local, CanariMode.Remote, etc.).
:return: previous operating mode. | 3.362943 | 4.158606 | 0.808671 |
kwargs = {} if kwargs is None else kwargs
n = len(x)
f0 = f(*(x,) + args, **kwargs)
dim = np.atleast_1d(f0).shape # it could be a scalar
grad = np.zeros((n,) + dim, float)
ei = np.zeros(np.shape(x), float)
if not centered:
epsilon = _get_epsilon(x, 2, epsilon, n)
for k in range(n):
ei[k] = epsilon[k]
grad[k, :] = (f(*(x + ei,) + args, **kwargs) - f0) / epsilon[k]
ei[k] = 0.0
else:
epsilon = _get_epsilon(x, 3, epsilon, n) / 2.
for k in range(n):
ei[k] = epsilon[k]
grad[k, :] = (f(*(x + ei,) + args, **kwargs) -
f(*(x - ei,) + args, **kwargs)) / (2 * epsilon[k])
ei[k] = 0.0
grad = grad.squeeze()
axes = [0, 1, 2][:grad.ndim]
axes[:2] = axes[1::-1]
return np.transpose(grad, axes=axes).squeeze() | def approx_fprime(x, f, epsilon=None, args=(), kwargs=None, centered=True) | Gradient of function, or Jacobian if function fun returns 1d array
Parameters
----------
x : array
parameters at which the derivative is evaluated
fun : function
`fun(*((x,)+args), **kwargs)` returning either one value or 1d array
epsilon : float, optional
Stepsize, if None, optimal stepsize is used. This is _EPS**(1/2)*x for
`centered` == False and _EPS**(1/3)*x for `centered` == True.
args : tuple
Tuple of additional arguments for function `fun`.
kwargs : dict
Dictionary of additional keyword arguments for function `fun`.
centered : bool
Whether central difference should be returned. If not, does forward
differencing.
Returns
-------
grad : array
gradient or Jacobian
Notes
-----
If fun returns a 1d array, it returns a Jacobian. If a 2d array is returned
by fun (e.g., with a value for each observation), it returns a 3d array
with the Jacobian of each observation with shape xk x nobs x xk. I.e.,
the Jacobian of the first observation would be [:, 0, :] | 2.680572 | 2.572993 | 1.041811 |
@wraps(fun)
def measure_time(*args, **kwargs):
t1 = timer()
result = fun(*args, **kwargs)
t2 = timer()
print("@timefun:" + fun.__name__ + " took " + str(t2 - t1) + " seconds")
return result
return measure_time | def timefun(fun) | Timing decorator
Timers require you to do some digging. Start wrapping a few of the higher level
functions and confirm where the bottleneck is, then drill down into that function,
repeating as you go. When you find the disproportionately slow bit of code, fix it,
and work your way back out confirming that it is fixed.
Handy tip: Don't forget the handy timeit module! It tends to be more useful for
benchmarking small pieces of code than for doing the actual investigation.
Timer Pros:
Easy to understand and implement. Also very simple to compare before and after fixes.
Works across many languages.
Timer Cons:
Sometimes a little too simplistic for extremely complex codebases, you might spend
more time placing and replacing boilerplate code than you will fixing the problem! | 2.155505 | 2.879753 | 0.748504 |
def profiled_func(*args, **kwargs):
profile = cProfile.Profile()
try:
profile.enable()
result = func(*args, **kwargs)
profile.disable()
return result
finally:
profile.print_stats()
return profiled_func | def do_cprofile(func) | Decorator to profile a function
It gives good numbers on various function calls but it omits a vital piece
of information: what is it about a function that makes it so slow?
However, it is a great start to basic profiling. Sometimes it can even
point you to the solution with very little fuss. I often use it as a
gut check to start the debugging process before I dig deeper into the
specific functions that are either slow are called way too often.
Pros:
No external dependencies and quite fast. Useful for quick high-level
checks.
Cons:
Rather limited information that usually requires deeper debugging; reports
are a bit unintuitive, especially for complex codebases.
See also
--------
do_profile, test_do_profile | 1.646042 | 2.48379 | 0.662714 |
dtype = np.result_type(float, np.ravel(sequence)[0])
seq = np.asarray(sequence, dtype=dtype)
if np.iscomplexobj(seq):
return (convolve1d(seq.real, rule, **kwds) + 1j * convolve1d(seq.imag, rule, **kwds))
return convolve1d(seq, rule, **kwds) | def convolve(sequence, rule, **kwds) | Wrapper around scipy.ndimage.convolve1d that allows complex input. | 2.428655 | 2.158247 | 1.125291 |
def linfun(i):
return np.linspace(0, np.pi / 2., 2**i + 1)
dea = EpsAlg(limexp=15)
print('NO. PANELS TRAP. APPROX APPROX W/EA abserr')
txt = '{0:5d} {1:20.8f} {2:20.8f} {3:20.8f}'
for k in np.arange(10):
x = linfun(k)
val = np.trapz(np.sin(x), x)
vale = dea(val)
err = np.abs(1.0 - vale)
print(txt.format(len(x) - 1, val, vale, err)) | def epsalg_demo() | >>> epsalg_demo()
NO. PANELS TRAP. APPROX APPROX W/EA abserr
1 0.78539816 0.78539816 0.21460184
2 0.94805945 0.94805945 0.05194055
4 0.98711580 0.99945672 0.00054328
8 0.99678517 0.99996674 0.00003326
16 0.99919668 0.99999988 0.00000012
32 0.99979919 1.00000000 0.00000000
64 0.99994980 1.00000000 0.00000000
128 0.99998745 1.00000000 0.00000000
256 0.99999686 1.00000000 0.00000000
512 0.99999922 1.00000000 0.00000000 | 5.72242 | 3.544278 | 1.614552 |
def linfun(i):
return np.linspace(0, np.pi / 2., 2**i + 1)
dea = Dea(limexp=6)
print('NO. PANELS TRAP. APPROX APPROX W/EA abserr')
txt = '{0:5d} {1:20.8f} {2:20.8f} {3:20.8f}'
for k in np.arange(12):
x = linfun(k)
val = np.trapz(np.sin(x), x)
vale, err = dea(val)
print(txt.format(len(x) - 1, val, vale, err)) | def dea_demo() | >>> dea_demo()
NO. PANELS TRAP. APPROX APPROX W/EA abserr
1 0.78539816 0.78539816 0.78539816
2 0.94805945 0.94805945 0.97596771
4 0.98711580 0.99945672 0.21405856
8 0.99678517 0.99996674 0.00306012
16 0.99919668 0.99999988 0.00115259
32 0.99979919 1.00000000 0.00057665
64 0.99994980 1.00000000 0.00003338
128 0.99998745 1.00000000 0.00000012
256 0.99999686 1.00000000 0.00000000
512 0.99999922 1.00000000 0.00000000
1024 0.99999980 1.00000000 0.00000000
2048 0.99999995 1.00000000 0.00000000 | 6.286397 | 3.571503 | 1.760155 |
e0, e1, e2 = np.atleast_1d(v0, v1, v2)
with warnings.catch_warnings():
warnings.simplefilter("ignore") # ignore division by zero and overflow
delta2, delta1 = e2 - e1, e1 - e0
err2, err1 = np.abs(delta2), np.abs(delta1)
tol2, tol1 = max_abs(e2, e1) * _EPS, max_abs(e1, e0) * _EPS
delta1[err1 < _TINY] = _TINY
delta2[err2 < _TINY] = _TINY # avoid division by zero and overflow
ss = 1.0 / delta2 - 1.0 / delta1 + _TINY
smalle2 = abs(ss * e1) <= 1.0e-3
converged = (err1 <= tol1) & (err2 <= tol2) | smalle2
result = np.where(converged, e2 * 1.0, e1 + 1.0 / ss)
abserr = err1 + err2 + np.where(converged, tol2 * 10, np.abs(result - e2))
if symmetric and len(result) > 1:
return result[:-1], abserr[1:]
return result, abserr | def dea3(v0, v1, v2, symmetric=False) | Extrapolate a slowly convergent sequence
Parameters
----------
v0, v1, v2 : array-like
3 values of a convergent sequence to extrapolate
Returns
-------
result : array-like
extrapolated value
abserr : array-like
absolute error estimate
Notes
-----
DEA3 attempts to extrapolate nonlinearly to a better estimate
of the sequence's limiting value, thus improving the rate of
convergence. The routine is based on the epsilon algorithm of
P. Wynn, see [1]_.
Examples
--------
# integrate sin(x) from 0 to pi/2
>>> import numpy as np
>>> import numdifftools as nd
>>> Ei= np.zeros(3)
>>> linfun = lambda i : np.linspace(0, np.pi/2., 2**(i+5)+1)
>>> for k in np.arange(3):
... x = linfun(k)
... Ei[k] = np.trapz(np.sin(x),x)
>>> [En, err] = nd.dea3(Ei[0], Ei[1], Ei[2])
>>> truErr = np.abs(En-1.)
>>> np.all(truErr < err)
True
>>> np.allclose(En, 1)
True
>>> np.all(np.abs(Ei-1)<1e-3)
True
See also
--------
dea
References
----------
.. [1] C. Brezinski and M. Redivo Zaglia (1991)
"Extrapolation Methods. Theory and Practice", North-Holland.
.. [2] C. Brezinski (1977)
"Acceleration de la convergence en analyse numerique",
"Lecture Notes in Math.", vol. 584,
Springer-Verlag, New York, 1977.
.. [3] E. J. Weniger (1989)
"Nonlinear sequence transformations for the acceleration of
convergence and the summation of divergent series"
Computer Physics Reports Vol. 10, 189 - 371
http://arxiv.org/abs/math/0306302v1 | 3.441959 | 3.467069 | 0.992758 |
_assert(0 <= parity <= 6,
'Parity must be 0, 1, 2, 3, 4, 5 or 6! ({0:d})'.format(parity))
step = [1, 2, 2, 4, 4, 4, 4][parity]
inv_sr = 1.0 / step_ratio
offset = [1, 1, 2, 2, 4, 1, 3][parity]
c0 = [1.0, 1.0, 1.0, 2.0, 24.0, 1.0, 6.0][parity]
c = c0 / \
special.factorial(np.arange(offset, step * nterms + offset, step))
[i, j] = np.ogrid[0:nterms, 0:nterms]
return np.atleast_2d(c[j] * inv_sr ** (i * (step * j + offset))) | def _fd_matrix(step_ratio, parity, nterms) | Return matrix for finite difference and complex step derivation.
Parameters
----------
step_ratio : real scalar
ratio between steps in unequally spaced difference rule.
parity : scalar, integer
0 (one sided, all terms included but zeroth order)
1 (only odd terms included)
2 (only even terms included)
3 (only every 4'th order terms included starting from order 2)
4 (only every 4'th order terms included starting from order 4)
5 (only every 4'th order terms included starting from order 1)
6 (only every 4'th order terms included starting from order 3)
nterms : scalar, integer
number of terms | 3.203941 | 3.362466 | 0.952855 |
f_del, h, original_shape = self._vstack(sequence, steps)
fd_rule = self._get_finite_difference_rule(step_ratio)
ne = h.shape[0]
nr = fd_rule.size - 1
_assert(nr < ne, 'num_steps ({0:d}) must be larger than '
'({1:d}) n + order - 1 = {2:d} + {3:d} -1'
' ({4:s})'.format(ne, nr+1, self.n, self.order, self.method))
f_diff = convolve(f_del, fd_rule[::-1], axis=0, origin=nr // 2)
der_init = f_diff / (h ** self.n)
ne = max(ne - nr, 1)
return der_init[:ne], h[:ne], original_shape | def _apply_fd_rule(self, step_ratio, sequence, steps) | Return derivative estimates of fun at x0 for a sequence of stepsizes h
Member variables used
---------------------
n | 5.820941 | 6.01152 | 0.968298 |
n = len(x)
ee = np.diag(h)
hess = 2. * np.outer(h, h)
for i in range(n):
for j in range(i, n):
hess[i, j] = (f(x + 1j * ee[i] + ee[j])
- f(x + 1j * ee[i] - ee[j])).imag / hess[j, i]
hess[j, i] = hess[i, j]
return hess | def _complex_even(f, fx, x, h) | Calculate Hessian with complex-step derivative approximation
The stepsize is the same for the complex and the finite difference part | 2.905005 | 2.723455 | 1.066662 |
n = len(x)
ee = np.diag(h)
hess = np.outer(h, h)
cmplx_wrap = Bicomplex.__array_wrap__
for i in range(n):
for j in range(i, n):
zph = Bicomplex(x + 1j * ee[i, :], ee[j, :])
hess[i, j] = cmplx_wrap(f(zph)).imag12 / hess[j, i]
hess[j, i] = hess[i, j]
return hess | def _multicomplex2(f, fx, x, h) | Calculate Hessian with Bicomplex-step derivative approximation | 4.229984 | 3.76339 | 1.123982 |
n = len(x)
ee = np.diag(h)
dtype = np.result_type(fx)
hess = np.empty((n, n), dtype=dtype)
np.outer(h, h, out=hess)
for i in range(n):
hess[i, i] = (f(x + 2 * ee[i, :]) - 2 * fx + f(x - 2 * ee[i, :])) / (4. * hess[i, i])
for j in range(i + 1, n):
hess[i, j] = (f(x + ee[i, :] + ee[j, :])
- f(x + ee[i, :] - ee[j, :])
- f(x - ee[i, :] + ee[j, :])
+ f(x - ee[i, :] - ee[j, :])) / (4. * hess[j, i])
hess[j, i] = hess[i, j]
return hess | def _central_even(f, fx, x, h) | Eq 9. | 2.003179 | 1.971873 | 1.015877 |
n = len(x)
ee = np.diag(h)
dtype = np.result_type(fx)
g = np.empty(n, dtype=dtype)
gg = np.empty(n, dtype=dtype)
for i in range(n):
g[i] = f(x + ee[i])
gg[i] = f(x - ee[i])
hess = np.empty((n, n), dtype=dtype)
np.outer(h, h, out=hess)
for i in range(n):
for j in range(i, n):
hess[i, j] = (f(x + ee[i, :] + ee[j, :])
+ f(x - ee[i, :] - ee[j, :])
- g[i] - g[j] + fx
- gg[i] - gg[j] + fx) / (2 * hess[j, i])
hess[j, i] = hess[i, j]
return hess | def _central2(f, fx, x, h) | Eq. 8 | 2.274419 | 2.235142 | 1.017573 |
x0 = np.asarray(x0)
vec = np.asarray(vec)
if x0.size != vec.size:
raise ValueError('vec and x0 must be the same shapes')
vec = np.reshape(vec/np.linalg.norm(vec.ravel()), x0.shape)
return Derivative(lambda t: f(x0+t*vec), **options)(0) | def directionaldiff(f, x0, vec, **options) | Return directional derivative of a function of n variables
Parameters
----------
fun: callable
analytical function to differentiate.
x0: array
vector location at which to differentiate fun. If x0 is an nxm array,
then fun is assumed to be a function of n*m variables.
vec: array
vector defining the line along which to take the derivative. It should
be the same size as x0, but need not be a vector of unit length.
**options:
optional arguments to pass on to Derivative.
Returns
-------
dder: scalar
estimate of the first derivative of fun in the specified direction.
Examples
--------
At the global minimizer (1,1) of the Rosenbrock function,
compute the directional derivative in the direction [1 2]
>>> import numpy as np
>>> import numdifftools as nd
>>> vec = np.r_[1, 2]
>>> rosen = lambda x: (1-x[0])**2 + 105*(x[1]-x[0]**2)**2
>>> dd, info = nd.directionaldiff(rosen, [1, 1], vec, full_output=True)
>>> np.allclose(dd, 0)
True
>>> np.abs(info.error_estimate)<1e-14
True
See also
--------
Derivative,
Gradient | 3.178294 | 3.938895 | 0.8069 |
if typecode is None:
typecode = bool
out = np.ones(shape, dtype=typecode) * value
if not isinstance(out, np.ndarray):
out = np.asarray(out)
return out | def valarray(shape, value=np.NaN, typecode=None) | Return an array of all value. | 2.865672 | 2.767511 | 1.035469 |
if x is None:
return 1.0
return np.log1p(np.abs(x)).clip(min=1.0) | def nominal_step(x=None) | Return nominal step | 4.6502 | 4.285447 | 1.085115 |
step_ratio = self.step_ratio
method = self.method
if method in ('multicomplex', ) or self.n == 0:
return np.ones((1,))
order, method_order = self.n - 1, self._method_order
parity = self._parity(method, order, method_order)
step = self._richardson_step()
num_terms, ix = (order + method_order) // step, order // step
fd_rules = FD_RULES.get((step_ratio, parity, num_terms))
if fd_rules is None:
fd_mat = self._fd_matrix(step_ratio, parity, num_terms)
fd_rules = linalg.pinv(fd_mat)
FD_RULES[(step_ratio, parity, num_terms)] = fd_rules
if self._flip_fd_rule:
return -fd_rules[ix]
return fd_rules[ix] | def rule(self) | Return finite differencing rule.
The rule is for a nominal unit step size, and must be scaled later
to reflect the local step size.
Member methods used
-------------------
_fd_matrix
Member variables used
---------------------
n
order
method | 4.58046 | 4.259216 | 1.075423 |
fd_rule = self.rule
ne = h.shape[0]
nr = fd_rule.size - 1
_assert(nr < ne, 'num_steps ({0:d}) must be larger than '
'({1:d}) n + order - 1 = {2:d} + {3:d} -1'
' ({4:s})'.format(ne, nr+1, self.n, self.order, self.method))
f_diff = convolve(f_del, fd_rule[::-1], axis=0, origin=nr // 2)
der_init = f_diff / (h ** self.n)
ne = max(ne - nr, 1)
return der_init[:ne], h[:ne] | def apply(self, f_del, h) | Apply finite difference rule along the first axis. | 6.883742 | 6.192999 | 1.111536 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.