body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
8cae533b82f13d7e895c8501db4304b258faf06f2c8438c095c4bee6a8ab3ae7
def draw_grid(): '\n Draws a grid with 2 rows and 2 columns.\n ' def separator(): print('+', (4 * '-'), '+', (4 * '-'), '+', sep='') for r in range(2): separator() for _ in range(4): print('|', (4 * ' '), '|', (4 * ' '), '|', sep='') separator()
Draws a grid with 2 rows and 2 columns.
POP1/worksheets/one/ex23/code.py
draw_grid
silvafj/BBK-MSCCS-2017-18
1
python
def draw_grid(): '\n \n ' def separator(): print('+', (4 * '-'), '+', (4 * '-'), '+', sep=) for r in range(2): separator() for _ in range(4): print('|', (4 * ' '), '|', (4 * ' '), '|', sep=) separator()
def draw_grid(): '\n \n ' def separator(): print('+', (4 * '-'), '+', (4 * '-'), '+', sep=) for r in range(2): separator() for _ in range(4): print('|', (4 * ' '), '|', (4 * ' '), '|', sep=) separator()<|docstring|>Draws a grid with 2 rows and 2 columns.<|endoftext|>
f156305c4341c76ad3acbd58ac878e6880537ba98f38f113315f51eed33aa1d4
@staticmethod def from_proto(extension: CsrExtension) -> extensions.ExtensionType: '\n Return an extension instance based on enum extension type.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a CSR Extension.\n :rtype: :class:`cryptography.x509.extensions.ExtensionType`\n ' this_extension = extension.extension_type if (this_extension == extension.ExtensionType.OCSPNoCheck): return extensions.OCSPNoCheck() if (this_extension == extension.ExtensionType.PrecertPoison): return extensions.PrecertPoison() raise TypeError(f'No known extension: {this_extension}')
Return an extension instance based on enum extension type. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a CSR Extension. :rtype: :class:`cryptography.x509.extensions.ExtensionType`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@staticmethod def from_proto(extension: CsrExtension) -> extensions.ExtensionType: '\n Return an extension instance based on enum extension type.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a CSR Extension.\n :rtype: :class:`cryptography.x509.extensions.ExtensionType`\n ' this_extension = extension.extension_type if (this_extension == extension.ExtensionType.OCSPNoCheck): return extensions.OCSPNoCheck() if (this_extension == extension.ExtensionType.PrecertPoison): return extensions.PrecertPoison() raise TypeError(f'No known extension: {this_extension}')
@staticmethod def from_proto(extension: CsrExtension) -> extensions.ExtensionType: '\n Return an extension instance based on enum extension type.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a CSR Extension.\n :rtype: :class:`cryptography.x509.extensions.ExtensionType`\n ' this_extension = extension.extension_type if (this_extension == extension.ExtensionType.OCSPNoCheck): return extensions.OCSPNoCheck() if (this_extension == extension.ExtensionType.PrecertPoison): return extensions.PrecertPoison() raise TypeError(f'No known extension: {this_extension}')<|docstring|>Return an extension instance based on enum extension type. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a CSR Extension. :rtype: :class:`cryptography.x509.extensions.ExtensionType`<|endoftext|>
88b4a8983dd189481043841e0ba0d5dc5ebcbb13d6c9b9a9418553a348866c0f
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a SubjectKeyIdentifier extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a SubjectKeyIdentifier Extension.\n :rtype: :class:`cryptography.x509.extensions.SubjectKeyIdentifier`\n ' this_extension = extension.subject_key_identifier return cls(digest=b64decode(this_extension.b64_digest.encode()))
Create a SubjectKeyIdentifier extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a SubjectKeyIdentifier Extension. :rtype: :class:`cryptography.x509.extensions.SubjectKeyIdentifier`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a SubjectKeyIdentifier extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a SubjectKeyIdentifier Extension.\n :rtype: :class:`cryptography.x509.extensions.SubjectKeyIdentifier`\n ' this_extension = extension.subject_key_identifier return cls(digest=b64decode(this_extension.b64_digest.encode()))
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a SubjectKeyIdentifier extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a SubjectKeyIdentifier Extension.\n :rtype: :class:`cryptography.x509.extensions.SubjectKeyIdentifier`\n ' this_extension = extension.subject_key_identifier return cls(digest=b64decode(this_extension.b64_digest.encode()))<|docstring|>Create a SubjectKeyIdentifier extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a SubjectKeyIdentifier Extension. :rtype: :class:`cryptography.x509.extensions.SubjectKeyIdentifier`<|endoftext|>
74639914af5abf77d71ff075f1bebace78b6857450c3cd53fa1a3d61e8e7ae6e
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a BasicConstraints extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a BasicConstraints Extension.\n :rtype: :class:`cryptography.x509.extensions.BasicConstraints`\n ' this_extension = extension.basic_constraints path_length = this_extension.path_length if (not path_length): path_length = None return cls(ca=this_extension.ca, path_length=path_length)
Create a BasicConstraints extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a BasicConstraints Extension. :rtype: :class:`cryptography.x509.extensions.BasicConstraints`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a BasicConstraints extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a BasicConstraints Extension.\n :rtype: :class:`cryptography.x509.extensions.BasicConstraints`\n ' this_extension = extension.basic_constraints path_length = this_extension.path_length if (not path_length): path_length = None return cls(ca=this_extension.ca, path_length=path_length)
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a BasicConstraints extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a BasicConstraints Extension.\n :rtype: :class:`cryptography.x509.extensions.BasicConstraints`\n ' this_extension = extension.basic_constraints path_length = this_extension.path_length if (not path_length): path_length = None return cls(ca=this_extension.ca, path_length=path_length)<|docstring|>Create a BasicConstraints extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a BasicConstraints Extension. :rtype: :class:`cryptography.x509.extensions.BasicConstraints`<|endoftext|>
8db7080109c7035dabfbf4f171471c7754318f576f2e8176beeb75068705830b
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a PolicyConstraints Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a PolicyConstraints Extension.\n :rtype: :class:`cryptography.x509.extensions.PolicyConstraints`\n ' this_extension = extension.policy_constraints require_explicit_policy = this_extension.require_explicit_policy inhibit_policy_mapping = this_extension.inhibit_policy_mapping if (not require_explicit_policy): require_explicit_policy = None if (not inhibit_policy_mapping): inhibit_policy_mapping = None return cls(require_explicit_policy=require_explicit_policy, inhibit_policy_mapping=inhibit_policy_mapping)
Create a PolicyConstraints Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a PolicyConstraints Extension. :rtype: :class:`cryptography.x509.extensions.PolicyConstraints`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a PolicyConstraints Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a PolicyConstraints Extension.\n :rtype: :class:`cryptography.x509.extensions.PolicyConstraints`\n ' this_extension = extension.policy_constraints require_explicit_policy = this_extension.require_explicit_policy inhibit_policy_mapping = this_extension.inhibit_policy_mapping if (not require_explicit_policy): require_explicit_policy = None if (not inhibit_policy_mapping): inhibit_policy_mapping = None return cls(require_explicit_policy=require_explicit_policy, inhibit_policy_mapping=inhibit_policy_mapping)
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a PolicyConstraints Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a PolicyConstraints Extension.\n :rtype: :class:`cryptography.x509.extensions.PolicyConstraints`\n ' this_extension = extension.policy_constraints require_explicit_policy = this_extension.require_explicit_policy inhibit_policy_mapping = this_extension.inhibit_policy_mapping if (not require_explicit_policy): require_explicit_policy = None if (not inhibit_policy_mapping): inhibit_policy_mapping = None return cls(require_explicit_policy=require_explicit_policy, inhibit_policy_mapping=inhibit_policy_mapping)<|docstring|>Create a PolicyConstraints Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a PolicyConstraints Extension. :rtype: :class:`cryptography.x509.extensions.PolicyConstraints`<|endoftext|>
f38c5e04351acba49689c0daaea90b757781fcc98468eaf517aa55c97f6469d3
@classmethod def from_proto(cls, notice: CsrExtension.NoticeReference): '\n Create a NoticeReference from a protobuf.\n\n :param CsrExtension.NoticeReference notice: A protobuf representation of a NoticeReference.\n :return: A `cryptography` representation of a NoticeReference.\n :rtype: :class:`cryptography.x509.extensions.NoticeReference`\n ' organization = notice.organization if (not organization): organization = None return cls(organization=organization, notice_numbers=notice.notice_numbers)
Create a NoticeReference from a protobuf. :param CsrExtension.NoticeReference notice: A protobuf representation of a NoticeReference. :return: A `cryptography` representation of a NoticeReference. :rtype: :class:`cryptography.x509.extensions.NoticeReference`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, notice: CsrExtension.NoticeReference): '\n Create a NoticeReference from a protobuf.\n\n :param CsrExtension.NoticeReference notice: A protobuf representation of a NoticeReference.\n :return: A `cryptography` representation of a NoticeReference.\n :rtype: :class:`cryptography.x509.extensions.NoticeReference`\n ' organization = notice.organization if (not organization): organization = None return cls(organization=organization, notice_numbers=notice.notice_numbers)
@classmethod def from_proto(cls, notice: CsrExtension.NoticeReference): '\n Create a NoticeReference from a protobuf.\n\n :param CsrExtension.NoticeReference notice: A protobuf representation of a NoticeReference.\n :return: A `cryptography` representation of a NoticeReference.\n :rtype: :class:`cryptography.x509.extensions.NoticeReference`\n ' organization = notice.organization if (not organization): organization = None return cls(organization=organization, notice_numbers=notice.notice_numbers)<|docstring|>Create a NoticeReference from a protobuf. :param CsrExtension.NoticeReference notice: A protobuf representation of a NoticeReference. :return: A `cryptography` representation of a NoticeReference. :rtype: :class:`cryptography.x509.extensions.NoticeReference`<|endoftext|>
1cd24bb4d4e3dbbe90075ffc98d278170b144910ba83a551b90f935870ab7db0
@classmethod def from_proto(cls, notices: Iterable[CsrExtension.UserNotice]) -> Iterable[extensions.UserNotice]: '\n Create a list of UserNotice form a protobuf.\n\n :param Iterable[CsrExtension.UserNotice] notices: A protobuf representation of UserNotices.\n :return: A `cryptography` representation of UserNotices.\n :rtype: Iterable[:class:`cryptography.x509.extensions.UserNotice`]\n ' information_list = [] for notice in notices: notice_reference = NoticeReference.from_proto(notice.notice_reference) explicit_text = notice.explicit_text if (not notice_reference): notice_reference = None if (not explicit_text): explicit_text = None information_list.append(cls(notice_reference=notice_reference, explicit_text=explicit_text)) return information_list
Create a list of UserNotice form a protobuf. :param Iterable[CsrExtension.UserNotice] notices: A protobuf representation of UserNotices. :return: A `cryptography` representation of UserNotices. :rtype: Iterable[:class:`cryptography.x509.extensions.UserNotice`]
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, notices: Iterable[CsrExtension.UserNotice]) -> Iterable[extensions.UserNotice]: '\n Create a list of UserNotice form a protobuf.\n\n :param Iterable[CsrExtension.UserNotice] notices: A protobuf representation of UserNotices.\n :return: A `cryptography` representation of UserNotices.\n :rtype: Iterable[:class:`cryptography.x509.extensions.UserNotice`]\n ' information_list = [] for notice in notices: notice_reference = NoticeReference.from_proto(notice.notice_reference) explicit_text = notice.explicit_text if (not notice_reference): notice_reference = None if (not explicit_text): explicit_text = None information_list.append(cls(notice_reference=notice_reference, explicit_text=explicit_text)) return information_list
@classmethod def from_proto(cls, notices: Iterable[CsrExtension.UserNotice]) -> Iterable[extensions.UserNotice]: '\n Create a list of UserNotice form a protobuf.\n\n :param Iterable[CsrExtension.UserNotice] notices: A protobuf representation of UserNotices.\n :return: A `cryptography` representation of UserNotices.\n :rtype: Iterable[:class:`cryptography.x509.extensions.UserNotice`]\n ' information_list = [] for notice in notices: notice_reference = NoticeReference.from_proto(notice.notice_reference) explicit_text = notice.explicit_text if (not notice_reference): notice_reference = None if (not explicit_text): explicit_text = None information_list.append(cls(notice_reference=notice_reference, explicit_text=explicit_text)) return information_list<|docstring|>Create a list of UserNotice form a protobuf. :param Iterable[CsrExtension.UserNotice] notices: A protobuf representation of UserNotices. :return: A `cryptography` representation of UserNotices. :rtype: Iterable[:class:`cryptography.x509.extensions.UserNotice`]<|endoftext|>
0765e6faa3fee2e2ea02cdbe035173e5ff7d009f0166151c8bd233bcadd54545
@classmethod def from_proto(cls, policies: Iterable[CsrExtension.PolicyInformation]): '\n Create a list of PolicyInformation from a protobuf.\n\n :param Iterable[CsrExtension.PolicyInformation] policies: A protobuf of PolicyInformations\n :return: A `cryptography` representation of PolicyInformations.\n :rtype: Iterable[:class:`cryptography.x509.extensions.PolicyInformation`]\n ' information_list = [] for policy in policies: policy_qualifiers = [] for string in policy.string_qualifiers: policy_qualifiers.append(string) for user_notice in UserNotice.from_proto(policy.user_qualifiers): policy_qualifiers.append(user_notice) information_list.append(cls(policy_identifier=ObjectIdentifier.from_string(policy.policy_identifier), policy_qualifiers=policy_qualifiers)) return information_list
Create a list of PolicyInformation from a protobuf. :param Iterable[CsrExtension.PolicyInformation] policies: A protobuf of PolicyInformations :return: A `cryptography` representation of PolicyInformations. :rtype: Iterable[:class:`cryptography.x509.extensions.PolicyInformation`]
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, policies: Iterable[CsrExtension.PolicyInformation]): '\n Create a list of PolicyInformation from a protobuf.\n\n :param Iterable[CsrExtension.PolicyInformation] policies: A protobuf of PolicyInformations\n :return: A `cryptography` representation of PolicyInformations.\n :rtype: Iterable[:class:`cryptography.x509.extensions.PolicyInformation`]\n ' information_list = [] for policy in policies: policy_qualifiers = [] for string in policy.string_qualifiers: policy_qualifiers.append(string) for user_notice in UserNotice.from_proto(policy.user_qualifiers): policy_qualifiers.append(user_notice) information_list.append(cls(policy_identifier=ObjectIdentifier.from_string(policy.policy_identifier), policy_qualifiers=policy_qualifiers)) return information_list
@classmethod def from_proto(cls, policies: Iterable[CsrExtension.PolicyInformation]): '\n Create a list of PolicyInformation from a protobuf.\n\n :param Iterable[CsrExtension.PolicyInformation] policies: A protobuf of PolicyInformations\n :return: A `cryptography` representation of PolicyInformations.\n :rtype: Iterable[:class:`cryptography.x509.extensions.PolicyInformation`]\n ' information_list = [] for policy in policies: policy_qualifiers = [] for string in policy.string_qualifiers: policy_qualifiers.append(string) for user_notice in UserNotice.from_proto(policy.user_qualifiers): policy_qualifiers.append(user_notice) information_list.append(cls(policy_identifier=ObjectIdentifier.from_string(policy.policy_identifier), policy_qualifiers=policy_qualifiers)) return information_list<|docstring|>Create a list of PolicyInformation from a protobuf. :param Iterable[CsrExtension.PolicyInformation] policies: A protobuf of PolicyInformations :return: A `cryptography` representation of PolicyInformations. :rtype: Iterable[:class:`cryptography.x509.extensions.PolicyInformation`]<|endoftext|>
66c2e95cc5cb55d183d1acfc82af83c0c1af7a441469cc6e8afb051ac1222efb
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a CertificatePolicies Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a CertificatePolicies Extension.\n :rtype: :class:`cryptography.x509.extensions.CertificatePolicies`\n ' this_extension = extension.certificate_policies return cls(policies=PolicyInformation.from_proto(this_extension.policies))
Create a CertificatePolicies Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a CertificatePolicies Extension. :rtype: :class:`cryptography.x509.extensions.CertificatePolicies`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a CertificatePolicies Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a CertificatePolicies Extension.\n :rtype: :class:`cryptography.x509.extensions.CertificatePolicies`\n ' this_extension = extension.certificate_policies return cls(policies=PolicyInformation.from_proto(this_extension.policies))
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a CertificatePolicies Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a CertificatePolicies Extension.\n :rtype: :class:`cryptography.x509.extensions.CertificatePolicies`\n ' this_extension = extension.certificate_policies return cls(policies=PolicyInformation.from_proto(this_extension.policies))<|docstring|>Create a CertificatePolicies Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a CertificatePolicies Extension. :rtype: :class:`cryptography.x509.extensions.CertificatePolicies`<|endoftext|>
11afc71950d038e7cc9bd15fb65a387a25553cfcfa139f6f2697c669beb163c2
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a ExtendedKeyUsage Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a ExtendedKeyUsage Extension.\n :rtype: :class:`cryptography.x509.extensions.ExtendedKeyUsage`\n ' this_extension = extension.extended_key_usage return cls(usages=(ObjectIdentifier.from_string(oid) for oid in this_extension.usages))
Create a ExtendedKeyUsage Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a ExtendedKeyUsage Extension. :rtype: :class:`cryptography.x509.extensions.ExtendedKeyUsage`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a ExtendedKeyUsage Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a ExtendedKeyUsage Extension.\n :rtype: :class:`cryptography.x509.extensions.ExtendedKeyUsage`\n ' this_extension = extension.extended_key_usage return cls(usages=(ObjectIdentifier.from_string(oid) for oid in this_extension.usages))
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a ExtendedKeyUsage Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a ExtendedKeyUsage Extension.\n :rtype: :class:`cryptography.x509.extensions.ExtendedKeyUsage`\n ' this_extension = extension.extended_key_usage return cls(usages=(ObjectIdentifier.from_string(oid) for oid in this_extension.usages))<|docstring|>Create a ExtendedKeyUsage Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a ExtendedKeyUsage Extension. :rtype: :class:`cryptography.x509.extensions.ExtendedKeyUsage`<|endoftext|>
1c4a26aab97a42e31a65c2379fb09495b7c5992b93f3e5b8c30a62d81ea64d79
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a TLSFeature Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a TLSFeature Extension.\n :rtype: :class:`cryptography.x509.extensions.TLSFeature`\n ' this_extension = extension.tls_feature return cls(features=(extensions.TLSFeatureType(feature) for feature in this_extension.features))
Create a TLSFeature Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a TLSFeature Extension. :rtype: :class:`cryptography.x509.extensions.TLSFeature`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a TLSFeature Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a TLSFeature Extension.\n :rtype: :class:`cryptography.x509.extensions.TLSFeature`\n ' this_extension = extension.tls_feature return cls(features=(extensions.TLSFeatureType(feature) for feature in this_extension.features))
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a TLSFeature Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a TLSFeature Extension.\n :rtype: :class:`cryptography.x509.extensions.TLSFeature`\n ' this_extension = extension.tls_feature return cls(features=(extensions.TLSFeatureType(feature) for feature in this_extension.features))<|docstring|>Create a TLSFeature Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a TLSFeature Extension. :rtype: :class:`cryptography.x509.extensions.TLSFeature`<|endoftext|>
c2953287e8d2906302dc900c3fa91b0d7cd1e3ef7873945023e891a739c1b67f
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a InhibitAnyPolicy Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a InhibitAnyPolicy Extension.\n :rtype: :class:`cryptography.x509.extensions.InhibitAnyPolicy`\n ' this_extension = extension.inhibit_any_policy return cls(skip_certs=this_extension.skip_certs)
Create a InhibitAnyPolicy Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a InhibitAnyPolicy Extension. :rtype: :class:`cryptography.x509.extensions.InhibitAnyPolicy`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a InhibitAnyPolicy Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a InhibitAnyPolicy Extension.\n :rtype: :class:`cryptography.x509.extensions.InhibitAnyPolicy`\n ' this_extension = extension.inhibit_any_policy return cls(skip_certs=this_extension.skip_certs)
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a InhibitAnyPolicy Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a InhibitAnyPolicy Extension.\n :rtype: :class:`cryptography.x509.extensions.InhibitAnyPolicy`\n ' this_extension = extension.inhibit_any_policy return cls(skip_certs=this_extension.skip_certs)<|docstring|>Create a InhibitAnyPolicy Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a InhibitAnyPolicy Extension. :rtype: :class:`cryptography.x509.extensions.InhibitAnyPolicy`<|endoftext|>
197371e4d3acc1ce8d3ed0d5e8b35a14a2f555ada53fd2e06dc57786b8d59853
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a KeyUsage Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a KeyUsage Extension.\n :rtype: :class:`cryptography.x509.extensions.KeyUsage`\n ' this_extension = extension.key_usage return cls(digital_signature=this_extension.digital_signature, content_commitment=this_extension.content_commitment, key_encipherment=this_extension.key_encipherment, data_encipherment=this_extension.data_encipherment, key_agreement=this_extension.key_agreement, key_cert_sign=this_extension.key_cert_sign, crl_sign=this_extension.crl_sign, encipher_only=this_extension.encipher_only, decipher_only=this_extension.decipher_only)
Create a KeyUsage Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a KeyUsage Extension. :rtype: :class:`cryptography.x509.extensions.KeyUsage`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a KeyUsage Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a KeyUsage Extension.\n :rtype: :class:`cryptography.x509.extensions.KeyUsage`\n ' this_extension = extension.key_usage return cls(digital_signature=this_extension.digital_signature, content_commitment=this_extension.content_commitment, key_encipherment=this_extension.key_encipherment, data_encipherment=this_extension.data_encipherment, key_agreement=this_extension.key_agreement, key_cert_sign=this_extension.key_cert_sign, crl_sign=this_extension.crl_sign, encipher_only=this_extension.encipher_only, decipher_only=this_extension.decipher_only)
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a KeyUsage Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a KeyUsage Extension.\n :rtype: :class:`cryptography.x509.extensions.KeyUsage`\n ' this_extension = extension.key_usage return cls(digital_signature=this_extension.digital_signature, content_commitment=this_extension.content_commitment, key_encipherment=this_extension.key_encipherment, data_encipherment=this_extension.data_encipherment, key_agreement=this_extension.key_agreement, key_cert_sign=this_extension.key_cert_sign, crl_sign=this_extension.crl_sign, encipher_only=this_extension.encipher_only, decipher_only=this_extension.decipher_only)<|docstring|>Create a KeyUsage Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a KeyUsage Extension. :rtype: :class:`cryptography.x509.extensions.KeyUsage`<|endoftext|>
fd2faaacf05526e59289ca983b4e76ab06c6e8f6787de2f5b4cf0da0f82fbc2d
@staticmethod def from_proto(reason: ProtoFlag) -> ExtFlag: '\n Convert a protobuf version ReasonFlag into the `cryptography` version.\n\n :param ProtoFlag reason: A protobuf representation of a ReasonFlag.\n :return: A `cryptography` representation of a ReasonFlag.\n :rtype: :class:`cryptography.x509.extensions.ReasonFlags`\n ' return ReasonFlags.flags[reason]
Convert a protobuf version ReasonFlag into the `cryptography` version. :param ProtoFlag reason: A protobuf representation of a ReasonFlag. :return: A `cryptography` representation of a ReasonFlag. :rtype: :class:`cryptography.x509.extensions.ReasonFlags`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@staticmethod def from_proto(reason: ProtoFlag) -> ExtFlag: '\n Convert a protobuf version ReasonFlag into the `cryptography` version.\n\n :param ProtoFlag reason: A protobuf representation of a ReasonFlag.\n :return: A `cryptography` representation of a ReasonFlag.\n :rtype: :class:`cryptography.x509.extensions.ReasonFlags`\n ' return ReasonFlags.flags[reason]
@staticmethod def from_proto(reason: ProtoFlag) -> ExtFlag: '\n Convert a protobuf version ReasonFlag into the `cryptography` version.\n\n :param ProtoFlag reason: A protobuf representation of a ReasonFlag.\n :return: A `cryptography` representation of a ReasonFlag.\n :rtype: :class:`cryptography.x509.extensions.ReasonFlags`\n ' return ReasonFlags.flags[reason]<|docstring|>Convert a protobuf version ReasonFlag into the `cryptography` version. :param ProtoFlag reason: A protobuf representation of a ReasonFlag. :return: A `cryptography` representation of a ReasonFlag. :rtype: :class:`cryptography.x509.extensions.ReasonFlags`<|endoftext|>
a1a4e1a00465e3627ef862c56906fd8710c2b97a0a5f3aa9c60a6c2f7975234f
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a RFC822Name from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a RFC822Name.\n :return: A `cryptography` representation of a RFC822Name.\n :rtype: :class:`cryptography.x509.general_name.RFC822Name`\n ' this_name = name.rfc_822_name return cls(value=this_name.value)
Create a RFC822Name from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a RFC822Name. :return: A `cryptography` representation of a RFC822Name. :rtype: :class:`cryptography.x509.general_name.RFC822Name`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a RFC822Name from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a RFC822Name.\n :return: A `cryptography` representation of a RFC822Name.\n :rtype: :class:`cryptography.x509.general_name.RFC822Name`\n ' this_name = name.rfc_822_name return cls(value=this_name.value)
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a RFC822Name from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a RFC822Name.\n :return: A `cryptography` representation of a RFC822Name.\n :rtype: :class:`cryptography.x509.general_name.RFC822Name`\n ' this_name = name.rfc_822_name return cls(value=this_name.value)<|docstring|>Create a RFC822Name from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a RFC822Name. :return: A `cryptography` representation of a RFC822Name. :rtype: :class:`cryptography.x509.general_name.RFC822Name`<|endoftext|>
5ed77f66858d23ffe0df4fd2870f4fc31746f386d2aa90c1ece5d71a494f47af
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a DNSName from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a DNSName.\n :return: A `cryptography` representation of a DNSName.\n :rtype: :class:`cryptography.x509.general_name.DNSName`\n ' this_name = name.dns_name return cls(value=this_name.value)
Create a DNSName from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a DNSName. :return: A `cryptography` representation of a DNSName. :rtype: :class:`cryptography.x509.general_name.DNSName`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a DNSName from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a DNSName.\n :return: A `cryptography` representation of a DNSName.\n :rtype: :class:`cryptography.x509.general_name.DNSName`\n ' this_name = name.dns_name return cls(value=this_name.value)
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a DNSName from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a DNSName.\n :return: A `cryptography` representation of a DNSName.\n :rtype: :class:`cryptography.x509.general_name.DNSName`\n ' this_name = name.dns_name return cls(value=this_name.value)<|docstring|>Create a DNSName from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a DNSName. :return: A `cryptography` representation of a DNSName. :rtype: :class:`cryptography.x509.general_name.DNSName`<|endoftext|>
9f3a0d347911b9d5f532c5bdc40f883ba8f2ecdc68dbc386b1cfb2138b0249cc
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a UniformResourceIdentifier from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf of a UniformResourceIdentifier.\n :return: A `cryptography` representation of a UniformResourceIdentifier.\n :rtype: :class:`cryptography.x509.general_name.UniformResourceIdentifier`\n ' this_name = name.uniform_resource_identifier return cls(value=this_name.value)
Create a UniformResourceIdentifier from a protobuf. :param CsrExtension.GeneralName name: A protobuf of a UniformResourceIdentifier. :return: A `cryptography` representation of a UniformResourceIdentifier. :rtype: :class:`cryptography.x509.general_name.UniformResourceIdentifier`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a UniformResourceIdentifier from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf of a UniformResourceIdentifier.\n :return: A `cryptography` representation of a UniformResourceIdentifier.\n :rtype: :class:`cryptography.x509.general_name.UniformResourceIdentifier`\n ' this_name = name.uniform_resource_identifier return cls(value=this_name.value)
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a UniformResourceIdentifier from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf of a UniformResourceIdentifier.\n :return: A `cryptography` representation of a UniformResourceIdentifier.\n :rtype: :class:`cryptography.x509.general_name.UniformResourceIdentifier`\n ' this_name = name.uniform_resource_identifier return cls(value=this_name.value)<|docstring|>Create a UniformResourceIdentifier from a protobuf. :param CsrExtension.GeneralName name: A protobuf of a UniformResourceIdentifier. :return: A `cryptography` representation of a UniformResourceIdentifier. :rtype: :class:`cryptography.x509.general_name.UniformResourceIdentifier`<|endoftext|>
2f4b80dcf5070e5a7761ab9e8ff5f1153e459029f9f5381d0968651f9f8a1b6a
@classmethod def from_proto(cls, attribute: CsrExtension.NameAttribute): '\n Create a NameAttribute from a config file.\n\n :param CsrExtension.NameAttribute attribute: A protobuf representation of a NameAttribute.\n :return: A `cryptography` representation of a NameAttribute.\n :rtype: :class:`cryptography.x509.name.NameAttribute`\n ' return cls(oid=ObjectIdentifier.from_string(attribute.oid), value=attribute.value)
Create a NameAttribute from a config file. :param CsrExtension.NameAttribute attribute: A protobuf representation of a NameAttribute. :return: A `cryptography` representation of a NameAttribute. :rtype: :class:`cryptography.x509.name.NameAttribute`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, attribute: CsrExtension.NameAttribute): '\n Create a NameAttribute from a config file.\n\n :param CsrExtension.NameAttribute attribute: A protobuf representation of a NameAttribute.\n :return: A `cryptography` representation of a NameAttribute.\n :rtype: :class:`cryptography.x509.name.NameAttribute`\n ' return cls(oid=ObjectIdentifier.from_string(attribute.oid), value=attribute.value)
@classmethod def from_proto(cls, attribute: CsrExtension.NameAttribute): '\n Create a NameAttribute from a config file.\n\n :param CsrExtension.NameAttribute attribute: A protobuf representation of a NameAttribute.\n :return: A `cryptography` representation of a NameAttribute.\n :rtype: :class:`cryptography.x509.name.NameAttribute`\n ' return cls(oid=ObjectIdentifier.from_string(attribute.oid), value=attribute.value)<|docstring|>Create a NameAttribute from a config file. :param CsrExtension.NameAttribute attribute: A protobuf representation of a NameAttribute. :return: A `cryptography` representation of a NameAttribute. :rtype: :class:`cryptography.x509.name.NameAttribute`<|endoftext|>
e9b4963b9ef5fb476495bb9b430329a7226c9b070eb3c602fb20df724d516f87
@classmethod def from_proto(cls, name: CsrExtension.Name): '\n Create a Name from a config file.\n\n :param CsrExtension.Name name: A protobuf representation of a Name.\n :return: A `cryptography` representation of a Name.\n :rtype: :class:`cryptography.x509.name.Name`\n ' return cls(attributes=(NameAttribute.from_proto(attribute) for attribute in name.attributes))
Create a Name from a config file. :param CsrExtension.Name name: A protobuf representation of a Name. :return: A `cryptography` representation of a Name. :rtype: :class:`cryptography.x509.name.Name`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, name: CsrExtension.Name): '\n Create a Name from a config file.\n\n :param CsrExtension.Name name: A protobuf representation of a Name.\n :return: A `cryptography` representation of a Name.\n :rtype: :class:`cryptography.x509.name.Name`\n ' return cls(attributes=(NameAttribute.from_proto(attribute) for attribute in name.attributes))
@classmethod def from_proto(cls, name: CsrExtension.Name): '\n Create a Name from a config file.\n\n :param CsrExtension.Name name: A protobuf representation of a Name.\n :return: A `cryptography` representation of a Name.\n :rtype: :class:`cryptography.x509.name.Name`\n ' return cls(attributes=(NameAttribute.from_proto(attribute) for attribute in name.attributes))<|docstring|>Create a Name from a config file. :param CsrExtension.Name name: A protobuf representation of a Name. :return: A `cryptography` representation of a Name. :rtype: :class:`cryptography.x509.name.Name`<|endoftext|>
04568f72a4718b943e207436d15c2866c2f8166f0ff3d922537f994b63e5b9e9
@classmethod def from_proto(cls, name: CsrExtension.Name): '\n Create a RelativeDistinguishedName from a config file.\n\n :param CsrExtension.Name name: A protobuf representation of a RelativeDistinguishedName.\n :return: A `cryptography` representation of a RelativeDistinguishedName.\n :rtype: :class:`cryptography.x509.name.RelativeDistinguishedName`\n ' return cls(attributes=(NameAttribute.from_proto(attribute) for attribute in name.attributes))
Create a RelativeDistinguishedName from a config file. :param CsrExtension.Name name: A protobuf representation of a RelativeDistinguishedName. :return: A `cryptography` representation of a RelativeDistinguishedName. :rtype: :class:`cryptography.x509.name.RelativeDistinguishedName`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, name: CsrExtension.Name): '\n Create a RelativeDistinguishedName from a config file.\n\n :param CsrExtension.Name name: A protobuf representation of a RelativeDistinguishedName.\n :return: A `cryptography` representation of a RelativeDistinguishedName.\n :rtype: :class:`cryptography.x509.name.RelativeDistinguishedName`\n ' return cls(attributes=(NameAttribute.from_proto(attribute) for attribute in name.attributes))
@classmethod def from_proto(cls, name: CsrExtension.Name): '\n Create a RelativeDistinguishedName from a config file.\n\n :param CsrExtension.Name name: A protobuf representation of a RelativeDistinguishedName.\n :return: A `cryptography` representation of a RelativeDistinguishedName.\n :rtype: :class:`cryptography.x509.name.RelativeDistinguishedName`\n ' return cls(attributes=(NameAttribute.from_proto(attribute) for attribute in name.attributes))<|docstring|>Create a RelativeDistinguishedName from a config file. :param CsrExtension.Name name: A protobuf representation of a RelativeDistinguishedName. :return: A `cryptography` representation of a RelativeDistinguishedName. :rtype: :class:`cryptography.x509.name.RelativeDistinguishedName`<|endoftext|>
67c2ceb04775d2c351066daa424adc141e8e5cbd290e3b5b1713aedba10b3403
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a DirectoryName from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a DirectoryName.\n :return: A `cryptography` representation of a DirectoryName.\n :rtype: :class:`cryptography.x509.general_name.DirectoryName`\n ' this_name = name.directory_name return cls(value=Name.from_proto(this_name.value))
Create a DirectoryName from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a DirectoryName. :return: A `cryptography` representation of a DirectoryName. :rtype: :class:`cryptography.x509.general_name.DirectoryName`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a DirectoryName from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a DirectoryName.\n :return: A `cryptography` representation of a DirectoryName.\n :rtype: :class:`cryptography.x509.general_name.DirectoryName`\n ' this_name = name.directory_name return cls(value=Name.from_proto(this_name.value))
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a DirectoryName from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a DirectoryName.\n :return: A `cryptography` representation of a DirectoryName.\n :rtype: :class:`cryptography.x509.general_name.DirectoryName`\n ' this_name = name.directory_name return cls(value=Name.from_proto(this_name.value))<|docstring|>Create a DirectoryName from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a DirectoryName. :return: A `cryptography` representation of a DirectoryName. :rtype: :class:`cryptography.x509.general_name.DirectoryName`<|endoftext|>
9164594002a22876d99188f90bef50539f9ccfa7ad60f212e7e46185e1e3f3cb
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a RegisteredID from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a RegisteredID.\n :return: A `cryptography` representation of a RegisteredID.\n :rtype: :class:`cryptography.x509.general_name.RegisteredID`\n ' this_name = name.registered_id return cls(value=ObjectIdentifier.from_string(this_name.oid))
Create a RegisteredID from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a RegisteredID. :return: A `cryptography` representation of a RegisteredID. :rtype: :class:`cryptography.x509.general_name.RegisteredID`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a RegisteredID from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a RegisteredID.\n :return: A `cryptography` representation of a RegisteredID.\n :rtype: :class:`cryptography.x509.general_name.RegisteredID`\n ' this_name = name.registered_id return cls(value=ObjectIdentifier.from_string(this_name.oid))
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a RegisteredID from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a RegisteredID.\n :return: A `cryptography` representation of a RegisteredID.\n :rtype: :class:`cryptography.x509.general_name.RegisteredID`\n ' this_name = name.registered_id return cls(value=ObjectIdentifier.from_string(this_name.oid))<|docstring|>Create a RegisteredID from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a RegisteredID. :return: A `cryptography` representation of a RegisteredID. :rtype: :class:`cryptography.x509.general_name.RegisteredID`<|endoftext|>
e7c89d179f65f6e44373202305953edbaeb851f55067304d47a519c72c21e334
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a IPAddress from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a IPAddress.\n :return: A `cryptography` representation of a IPAddress.\n :rtype: :class:`cryptography.x509.general_name.IPAddress`\n ' this_name = name.ip_address return cls(value=ip_address(this_name.value))
Create a IPAddress from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a IPAddress. :return: A `cryptography` representation of a IPAddress. :rtype: :class:`cryptography.x509.general_name.IPAddress`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a IPAddress from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a IPAddress.\n :return: A `cryptography` representation of a IPAddress.\n :rtype: :class:`cryptography.x509.general_name.IPAddress`\n ' this_name = name.ip_address return cls(value=ip_address(this_name.value))
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a IPAddress from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a IPAddress.\n :return: A `cryptography` representation of a IPAddress.\n :rtype: :class:`cryptography.x509.general_name.IPAddress`\n ' this_name = name.ip_address return cls(value=ip_address(this_name.value))<|docstring|>Create a IPAddress from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a IPAddress. :return: A `cryptography` representation of a IPAddress. :rtype: :class:`cryptography.x509.general_name.IPAddress`<|endoftext|>
e88ee4e85261b2aadba65bdcd41a7231979029b29bc34dbb15b32b3e1a4cdd4d
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a OtherName from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a OtherName.\n :return: A `cryptography` representation of a OtherName.\n :rtype: :class:`cryptography.x509.general_name.OtherName`\n ' this_name = name.other_name return cls(type_id=ObjectIdentifier.from_string(this_name.oid), value=b64decode(this_name.b64_value.encode()))
Create a OtherName from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a OtherName. :return: A `cryptography` representation of a OtherName. :rtype: :class:`cryptography.x509.general_name.OtherName`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a OtherName from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a OtherName.\n :return: A `cryptography` representation of a OtherName.\n :rtype: :class:`cryptography.x509.general_name.OtherName`\n ' this_name = name.other_name return cls(type_id=ObjectIdentifier.from_string(this_name.oid), value=b64decode(this_name.b64_value.encode()))
@classmethod def from_proto(cls, name: CsrExtension.GeneralName): '\n Create a OtherName from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a OtherName.\n :return: A `cryptography` representation of a OtherName.\n :rtype: :class:`cryptography.x509.general_name.OtherName`\n ' this_name = name.other_name return cls(type_id=ObjectIdentifier.from_string(this_name.oid), value=b64decode(this_name.b64_value.encode()))<|docstring|>Create a OtherName from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a OtherName. :return: A `cryptography` representation of a OtherName. :rtype: :class:`cryptography.x509.general_name.OtherName`<|endoftext|>
16bb460c73720015cb9f64bff8661cf151110cba41e50651e46b7e0b7ec044d3
@staticmethod def from_proto(name: CsrExtension.GeneralName) -> general_name.GeneralName: '\n Create a GeneralName instance from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a GeneralName.\n :return: A `cryptography` representation of a GeneralName.\n :rtype: :class:`cryptography.x509.general_name.GeneralName`\n ' return GeneralName.name_types.get(name.WhichOneof('name')).from_proto(name)
Create a GeneralName instance from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a GeneralName. :return: A `cryptography` representation of a GeneralName. :rtype: :class:`cryptography.x509.general_name.GeneralName`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@staticmethod def from_proto(name: CsrExtension.GeneralName) -> general_name.GeneralName: '\n Create a GeneralName instance from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a GeneralName.\n :return: A `cryptography` representation of a GeneralName.\n :rtype: :class:`cryptography.x509.general_name.GeneralName`\n ' return GeneralName.name_types.get(name.WhichOneof('name')).from_proto(name)
@staticmethod def from_proto(name: CsrExtension.GeneralName) -> general_name.GeneralName: '\n Create a GeneralName instance from a protobuf.\n\n :param CsrExtension.GeneralName name: A protobuf representation of a GeneralName.\n :return: A `cryptography` representation of a GeneralName.\n :rtype: :class:`cryptography.x509.general_name.GeneralName`\n ' return GeneralName.name_types.get(name.WhichOneof('name')).from_proto(name)<|docstring|>Create a GeneralName instance from a protobuf. :param CsrExtension.GeneralName name: A protobuf representation of a GeneralName. :return: A `cryptography` representation of a GeneralName. :rtype: :class:`cryptography.x509.general_name.GeneralName`<|endoftext|>
90de1bf661b9ff6375149b5b35313ea3499d10e254b29683879c12b04495fffe
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a AuthorityKeyIdentifier Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a AuthorityKeyIdentifier Extension.\n :rtype: :class:`cryptography.x509.extensions.AuthorityKeyIdentifier`\n ' this_extension = extension.authority_key_identifier key_identifier = this_extension.key_identifier authority_cert_serial_number = this_extension.authority_cert_serial_number if (not key_identifier): key_identifier = None if (not authority_cert_serial_number): authority_cert_serial_number = None return cls(key_identifier=key_identifier, authority_cert_issuer=(GeneralName.from_proto(name) for name in this_extension.authority_cert_issuer), authority_cert_serial_number=authority_cert_serial_number)
Create a AuthorityKeyIdentifier Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a AuthorityKeyIdentifier Extension. :rtype: :class:`cryptography.x509.extensions.AuthorityKeyIdentifier`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a AuthorityKeyIdentifier Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a AuthorityKeyIdentifier Extension.\n :rtype: :class:`cryptography.x509.extensions.AuthorityKeyIdentifier`\n ' this_extension = extension.authority_key_identifier key_identifier = this_extension.key_identifier authority_cert_serial_number = this_extension.authority_cert_serial_number if (not key_identifier): key_identifier = None if (not authority_cert_serial_number): authority_cert_serial_number = None return cls(key_identifier=key_identifier, authority_cert_issuer=(GeneralName.from_proto(name) for name in this_extension.authority_cert_issuer), authority_cert_serial_number=authority_cert_serial_number)
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a AuthorityKeyIdentifier Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a AuthorityKeyIdentifier Extension.\n :rtype: :class:`cryptography.x509.extensions.AuthorityKeyIdentifier`\n ' this_extension = extension.authority_key_identifier key_identifier = this_extension.key_identifier authority_cert_serial_number = this_extension.authority_cert_serial_number if (not key_identifier): key_identifier = None if (not authority_cert_serial_number): authority_cert_serial_number = None return cls(key_identifier=key_identifier, authority_cert_issuer=(GeneralName.from_proto(name) for name in this_extension.authority_cert_issuer), authority_cert_serial_number=authority_cert_serial_number)<|docstring|>Create a AuthorityKeyIdentifier Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a AuthorityKeyIdentifier Extension. :rtype: :class:`cryptography.x509.extensions.AuthorityKeyIdentifier`<|endoftext|>
4e603954e42758ac556c22892b794776718f5cc887371b75549ef19a78f988ec
@classmethod def from_proto(cls, description: CsrExtension.AccessDescription): '\n Create a AccessDescription from a protobuf.\n\n :param CsrExtension.AccessDescription description: A protobuf of a AccessDescription.\n :return: A `cryptography` representation of a AccessDescription.\n :rtype: :class:`cryptography.x509.extensions.AccessDescription`\n ' return cls(access_method=ObjectIdentifier.from_string(description.access_method), access_location=GeneralName.from_proto(description.access_location))
Create a AccessDescription from a protobuf. :param CsrExtension.AccessDescription description: A protobuf of a AccessDescription. :return: A `cryptography` representation of a AccessDescription. :rtype: :class:`cryptography.x509.extensions.AccessDescription`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, description: CsrExtension.AccessDescription): '\n Create a AccessDescription from a protobuf.\n\n :param CsrExtension.AccessDescription description: A protobuf of a AccessDescription.\n :return: A `cryptography` representation of a AccessDescription.\n :rtype: :class:`cryptography.x509.extensions.AccessDescription`\n ' return cls(access_method=ObjectIdentifier.from_string(description.access_method), access_location=GeneralName.from_proto(description.access_location))
@classmethod def from_proto(cls, description: CsrExtension.AccessDescription): '\n Create a AccessDescription from a protobuf.\n\n :param CsrExtension.AccessDescription description: A protobuf of a AccessDescription.\n :return: A `cryptography` representation of a AccessDescription.\n :rtype: :class:`cryptography.x509.extensions.AccessDescription`\n ' return cls(access_method=ObjectIdentifier.from_string(description.access_method), access_location=GeneralName.from_proto(description.access_location))<|docstring|>Create a AccessDescription from a protobuf. :param CsrExtension.AccessDescription description: A protobuf of a AccessDescription. :return: A `cryptography` representation of a AccessDescription. :rtype: :class:`cryptography.x509.extensions.AccessDescription`<|endoftext|>
b207ffe8a0a676054aa7b3c945fc31614c5e811f56f8d130d6b0c44d617c97d9
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a AuthorityInformationAccess Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a AuthorityInformationAccess Extension.\n :rtype: :class:`cryptography.x509.extensions.AuthorityInformationAccess`\n ' this_extension = extension.authority_information_access return cls(descriptions=(AccessDescription.from_proto(description) for description in this_extension.descriptions))
Create a AuthorityInformationAccess Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a AuthorityInformationAccess Extension. :rtype: :class:`cryptography.x509.extensions.AuthorityInformationAccess`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a AuthorityInformationAccess Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a AuthorityInformationAccess Extension.\n :rtype: :class:`cryptography.x509.extensions.AuthorityInformationAccess`\n ' this_extension = extension.authority_information_access return cls(descriptions=(AccessDescription.from_proto(description) for description in this_extension.descriptions))
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a AuthorityInformationAccess Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a AuthorityInformationAccess Extension.\n :rtype: :class:`cryptography.x509.extensions.AuthorityInformationAccess`\n ' this_extension = extension.authority_information_access return cls(descriptions=(AccessDescription.from_proto(description) for description in this_extension.descriptions))<|docstring|>Create a AuthorityInformationAccess Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a AuthorityInformationAccess Extension. :rtype: :class:`cryptography.x509.extensions.AuthorityInformationAccess`<|endoftext|>
85e92c5d3c71fcfd27f4ecb9f31e67bd245658ebe9ab476e52f040a60637cfae
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a SubjectInformationAccess Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a SubjectInformationAccess Extension.\n :rtype: :class:`cryptography.x509.extensions.SubjectInformationAccess`\n ' this_extension = extension.subject_information_access return cls(descriptions=(AccessDescription.from_proto(description) for description in this_extension.descriptions))
Create a SubjectInformationAccess Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a SubjectInformationAccess Extension. :rtype: :class:`cryptography.x509.extensions.SubjectInformationAccess`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a SubjectInformationAccess Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a SubjectInformationAccess Extension.\n :rtype: :class:`cryptography.x509.extensions.SubjectInformationAccess`\n ' this_extension = extension.subject_information_access return cls(descriptions=(AccessDescription.from_proto(description) for description in this_extension.descriptions))
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a SubjectInformationAccess Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a SubjectInformationAccess Extension.\n :rtype: :class:`cryptography.x509.extensions.SubjectInformationAccess`\n ' this_extension = extension.subject_information_access return cls(descriptions=(AccessDescription.from_proto(description) for description in this_extension.descriptions))<|docstring|>Create a SubjectInformationAccess Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a SubjectInformationAccess Extension. :rtype: :class:`cryptography.x509.extensions.SubjectInformationAccess`<|endoftext|>
e4c85165883455a420aceb75d447b3b2fc7590e7b1763b58df12008e6205e827
@classmethod def from_proto(cls, dist: CsrExtension.DistributionPoint): '\n Create a DistributionPoint from a protobuf.\n\n :param CsrExtension.DistributionPoint dist: A protobuf of a DistributionPoint.\n :return: A `cryptography` representation of a DistributionPoint.\n :rtype: :class:`cryptography.x509.extensions.DistributionPoint`\n ' full_name = [GeneralName.from_proto(name) for name in dist.full_name] relative_name = RelativeDistinguishedName.from_proto(dist.relative_name) reasons = frozenset((ReasonFlags.from_proto(reason) for reason in dist.reasons)) crl_issuer = [GeneralName.from_proto(name) for name in dist.crl_issuer] if (not full_name): full_name = None if (not relative_name): relative_name = None if (not reasons): reasons = None if (not crl_issuer): crl_issuer = None return cls(full_name=full_name, relative_name=relative_name, reasons=reasons, crl_issuer=crl_issuer)
Create a DistributionPoint from a protobuf. :param CsrExtension.DistributionPoint dist: A protobuf of a DistributionPoint. :return: A `cryptography` representation of a DistributionPoint. :rtype: :class:`cryptography.x509.extensions.DistributionPoint`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, dist: CsrExtension.DistributionPoint): '\n Create a DistributionPoint from a protobuf.\n\n :param CsrExtension.DistributionPoint dist: A protobuf of a DistributionPoint.\n :return: A `cryptography` representation of a DistributionPoint.\n :rtype: :class:`cryptography.x509.extensions.DistributionPoint`\n ' full_name = [GeneralName.from_proto(name) for name in dist.full_name] relative_name = RelativeDistinguishedName.from_proto(dist.relative_name) reasons = frozenset((ReasonFlags.from_proto(reason) for reason in dist.reasons)) crl_issuer = [GeneralName.from_proto(name) for name in dist.crl_issuer] if (not full_name): full_name = None if (not relative_name): relative_name = None if (not reasons): reasons = None if (not crl_issuer): crl_issuer = None return cls(full_name=full_name, relative_name=relative_name, reasons=reasons, crl_issuer=crl_issuer)
@classmethod def from_proto(cls, dist: CsrExtension.DistributionPoint): '\n Create a DistributionPoint from a protobuf.\n\n :param CsrExtension.DistributionPoint dist: A protobuf of a DistributionPoint.\n :return: A `cryptography` representation of a DistributionPoint.\n :rtype: :class:`cryptography.x509.extensions.DistributionPoint`\n ' full_name = [GeneralName.from_proto(name) for name in dist.full_name] relative_name = RelativeDistinguishedName.from_proto(dist.relative_name) reasons = frozenset((ReasonFlags.from_proto(reason) for reason in dist.reasons)) crl_issuer = [GeneralName.from_proto(name) for name in dist.crl_issuer] if (not full_name): full_name = None if (not relative_name): relative_name = None if (not reasons): reasons = None if (not crl_issuer): crl_issuer = None return cls(full_name=full_name, relative_name=relative_name, reasons=reasons, crl_issuer=crl_issuer)<|docstring|>Create a DistributionPoint from a protobuf. :param CsrExtension.DistributionPoint dist: A protobuf of a DistributionPoint. :return: A `cryptography` representation of a DistributionPoint. :rtype: :class:`cryptography.x509.extensions.DistributionPoint`<|endoftext|>
5b616134ebbd56afe2328ede9e078a4db9855325d83664c351cedd0392cdb5a0
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a CRLDistributionPoints Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a CRLDistributionPoints Extension.\n :rtype: :class:`cryptography.x509.extensions.CRLDistributionPoints`\n ' this_extension = extension.crl_distribution_points return cls(distribution_points=(DistributionPoint.from_proto(dist) for dist in this_extension.distribution_points))
Create a CRLDistributionPoints Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a CRLDistributionPoints Extension. :rtype: :class:`cryptography.x509.extensions.CRLDistributionPoints`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a CRLDistributionPoints Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a CRLDistributionPoints Extension.\n :rtype: :class:`cryptography.x509.extensions.CRLDistributionPoints`\n ' this_extension = extension.crl_distribution_points return cls(distribution_points=(DistributionPoint.from_proto(dist) for dist in this_extension.distribution_points))
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a CRLDistributionPoints Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a CRLDistributionPoints Extension.\n :rtype: :class:`cryptography.x509.extensions.CRLDistributionPoints`\n ' this_extension = extension.crl_distribution_points return cls(distribution_points=(DistributionPoint.from_proto(dist) for dist in this_extension.distribution_points))<|docstring|>Create a CRLDistributionPoints Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a CRLDistributionPoints Extension. :rtype: :class:`cryptography.x509.extensions.CRLDistributionPoints`<|endoftext|>
6dbd5dc9ab4120987a8f0b2ccf0b5ee34061518da5c699b7ad6007466e5304ef
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a FreshestCRL Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a FreshestCRL Extension.\n :rtype: :class:`cryptography.x509.extensions.FreshestCRL`\n ' this_extension = extension.freshest_crl return cls(distribution_points=(DistributionPoint.from_proto(dist) for dist in this_extension.distribution_points))
Create a FreshestCRL Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a FreshestCRL Extension. :rtype: :class:`cryptography.x509.extensions.FreshestCRL`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a FreshestCRL Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a FreshestCRL Extension.\n :rtype: :class:`cryptography.x509.extensions.FreshestCRL`\n ' this_extension = extension.freshest_crl return cls(distribution_points=(DistributionPoint.from_proto(dist) for dist in this_extension.distribution_points))
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a FreshestCRL Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a FreshestCRL Extension.\n :rtype: :class:`cryptography.x509.extensions.FreshestCRL`\n ' this_extension = extension.freshest_crl return cls(distribution_points=(DistributionPoint.from_proto(dist) for dist in this_extension.distribution_points))<|docstring|>Create a FreshestCRL Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a FreshestCRL Extension. :rtype: :class:`cryptography.x509.extensions.FreshestCRL`<|endoftext|>
9a3648c9529e44d4f6690073c6fd31461b631c5b273b5132943daab64bc86ffe
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a NameConstraints Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a NameConstraints Extension.\n :rtype: :class:`cryptography.x509.extensions.NameConstraints`\n ' this_extension = extension.name_constraints return cls(permitted_subtrees=(GeneralName.from_proto(name) for name in this_extension.permitted_subtrees), excluded_subtrees=(GeneralName.from_proto(name) for name in this_extension.excluded_subtrees))
Create a NameConstraints Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a NameConstraints Extension. :rtype: :class:`cryptography.x509.extensions.NameConstraints`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a NameConstraints Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a NameConstraints Extension.\n :rtype: :class:`cryptography.x509.extensions.NameConstraints`\n ' this_extension = extension.name_constraints return cls(permitted_subtrees=(GeneralName.from_proto(name) for name in this_extension.permitted_subtrees), excluded_subtrees=(GeneralName.from_proto(name) for name in this_extension.excluded_subtrees))
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a NameConstraints Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a NameConstraints Extension.\n :rtype: :class:`cryptography.x509.extensions.NameConstraints`\n ' this_extension = extension.name_constraints return cls(permitted_subtrees=(GeneralName.from_proto(name) for name in this_extension.permitted_subtrees), excluded_subtrees=(GeneralName.from_proto(name) for name in this_extension.excluded_subtrees))<|docstring|>Create a NameConstraints Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a NameConstraints Extension. :rtype: :class:`cryptography.x509.extensions.NameConstraints`<|endoftext|>
779da7bb979f05a5372e7bd42a671eb57badd2308d589ab3a648c815f21eb6e8
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a SubjectAlternativeName Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a SubjectAlternativeName Extension.\n :rtype: :class:`cryptography.x509.extensions.SubjectAlternativeName`\n ' this_extension = extension.subject_alternative_name return cls(general_names=(GeneralName.from_proto(name) for name in this_extension.general_names))
Create a SubjectAlternativeName Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a SubjectAlternativeName Extension. :rtype: :class:`cryptography.x509.extensions.SubjectAlternativeName`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a SubjectAlternativeName Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a SubjectAlternativeName Extension.\n :rtype: :class:`cryptography.x509.extensions.SubjectAlternativeName`\n ' this_extension = extension.subject_alternative_name return cls(general_names=(GeneralName.from_proto(name) for name in this_extension.general_names))
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a SubjectAlternativeName Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a SubjectAlternativeName Extension.\n :rtype: :class:`cryptography.x509.extensions.SubjectAlternativeName`\n ' this_extension = extension.subject_alternative_name return cls(general_names=(GeneralName.from_proto(name) for name in this_extension.general_names))<|docstring|>Create a SubjectAlternativeName Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a SubjectAlternativeName Extension. :rtype: :class:`cryptography.x509.extensions.SubjectAlternativeName`<|endoftext|>
b5af1117cf372d4f985288a1267302177e1b83fe2c37669f0643e78b04fffc42
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a IssuerAlternativeName Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a IssuerAlternativeName Extension.\n :rtype: :class:`cryptography.x509.extensions.IssuerAlternativeName`\n ' this_extension = extension.issuer_alternative_name return cls(general_names=(GeneralName.from_proto(name) for name in this_extension.general_names))
Create a IssuerAlternativeName Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a IssuerAlternativeName Extension. :rtype: :class:`cryptography.x509.extensions.IssuerAlternativeName`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a IssuerAlternativeName Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a IssuerAlternativeName Extension.\n :rtype: :class:`cryptography.x509.extensions.IssuerAlternativeName`\n ' this_extension = extension.issuer_alternative_name return cls(general_names=(GeneralName.from_proto(name) for name in this_extension.general_names))
@classmethod def from_proto(cls, extension: CsrExtension): '\n Create a IssuerAlternativeName Extension from a protobuf.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a IssuerAlternativeName Extension.\n :rtype: :class:`cryptography.x509.extensions.IssuerAlternativeName`\n ' this_extension = extension.issuer_alternative_name return cls(general_names=(GeneralName.from_proto(name) for name in this_extension.general_names))<|docstring|>Create a IssuerAlternativeName Extension from a protobuf. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a IssuerAlternativeName Extension. :rtype: :class:`cryptography.x509.extensions.IssuerAlternativeName`<|endoftext|>
6a01e7f99f5f74ad39648b26ad2315b4c23b088adab4c42b8c40a56e367b74a7
@staticmethod def _get_extension_type(extension: CsrExtension) -> extensions.ExtensionType: 'Get the custom extension wrapper for an extension protobuf.' return Extension.extension_list.get(extension.WhichOneof('extension'))
Get the custom extension wrapper for an extension protobuf.
autocsr/extensions.py
_get_extension_type
maxwolfe/autocsr
0
python
@staticmethod def _get_extension_type(extension: CsrExtension) -> extensions.ExtensionType: return Extension.extension_list.get(extension.WhichOneof('extension'))
@staticmethod def _get_extension_type(extension: CsrExtension) -> extensions.ExtensionType: return Extension.extension_list.get(extension.WhichOneof('extension'))<|docstring|>Get the custom extension wrapper for an extension protobuf.<|endoftext|>
24f890182391c99b337dc214efe8303b6c7b2bc6f2cb20a66cfcce6342177040
@staticmethod def from_proto(extension: CsrExtension) -> extensions.ExtensionType: '\n Create a `cryptography` Extension from a protobuf representation.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a CSR Extension.\n :rtype: :class:`cryptography.x509.extensions.ExtensionType`\n ' extension_type = Extension._get_extension_type(extension) return extension_type.from_proto(extension)
Create a `cryptography` Extension from a protobuf representation. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a CSR Extension. :rtype: :class:`cryptography.x509.extensions.ExtensionType`
autocsr/extensions.py
from_proto
maxwolfe/autocsr
0
python
@staticmethod def from_proto(extension: CsrExtension) -> extensions.ExtensionType: '\n Create a `cryptography` Extension from a protobuf representation.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a CSR Extension.\n :rtype: :class:`cryptography.x509.extensions.ExtensionType`\n ' extension_type = Extension._get_extension_type(extension) return extension_type.from_proto(extension)
@staticmethod def from_proto(extension: CsrExtension) -> extensions.ExtensionType: '\n Create a `cryptography` Extension from a protobuf representation.\n\n :param CsrExtension extension: A protobuf representation of a CSR Extension.\n :return: A `cryptography` representation of a CSR Extension.\n :rtype: :class:`cryptography.x509.extensions.ExtensionType`\n ' extension_type = Extension._get_extension_type(extension) return extension_type.from_proto(extension)<|docstring|>Create a `cryptography` Extension from a protobuf representation. :param CsrExtension extension: A protobuf representation of a CSR Extension. :return: A `cryptography` representation of a CSR Extension. :rtype: :class:`cryptography.x509.extensions.ExtensionType`<|endoftext|>
5d8c85b6b1170c914c9ce1d44bb1b5660ecc0befb6eabc72d90054026176637f
def top_hit(search_string): "\n Use browser to search for a term and return top hit\n return empty string if browser doesn't suggest a spelling\n " html = browser_driver.st_html(search_string) parsed = parsed_text(html) return parsed
Use browser to search for a term and return top hit return empty string if browser doesn't suggest a spelling
websearcher/top_hit.py
top_hit
beepscore/websearcher
0
python
def top_hit(search_string): "\n Use browser to search for a term and return top hit\n return empty string if browser doesn't suggest a spelling\n " html = browser_driver.st_html(search_string) parsed = parsed_text(html) return parsed
def top_hit(search_string): "\n Use browser to search for a term and return top hit\n return empty string if browser doesn't suggest a spelling\n " html = browser_driver.st_html(search_string) parsed = parsed_text(html) return parsed<|docstring|>Use browser to search for a term and return top hit return empty string if browser doesn't suggest a spelling<|endoftext|>
d8f87f344ddce60ba2d93ca58f89b32e5a8407595be26a8a9e44a81993bc150f
def parsed_text(html): "\n return html text, stripped of tags and ellipses '...'\n " soup = BeautifulSoup(html, 'html.parser') text = soup.get_text() text_no_ellipsis = text.replace('...', '') return text_no_ellipsis
return html text, stripped of tags and ellipses '...'
websearcher/top_hit.py
parsed_text
beepscore/websearcher
0
python
def parsed_text(html): "\n \n " soup = BeautifulSoup(html, 'html.parser') text = soup.get_text() text_no_ellipsis = text.replace('...', ) return text_no_ellipsis
def parsed_text(html): "\n \n " soup = BeautifulSoup(html, 'html.parser') text = soup.get_text() text_no_ellipsis = text.replace('...', ) return text_no_ellipsis<|docstring|>return html text, stripped of tags and ellipses '...'<|endoftext|>
dfba4feba9595c891336ff22eba205438e3679bd6163f0b25d09e28f0f9d677c
def get_topic_name(topic_name='root', type='publish', is_shadow=False): '\n 返回一个topic自定义的topic类\n :param topic_name:\n :param type\n :param is_shadow\n :return:\n ' registered_topic = ['', 'mic_text_from_server', 'conversation_log'] if (type not in ['subscribe', 'publish']): raise Exception('Unsupported topic type.') if (topic_name not in registered_topic): _logger.error('not registered topic') raise Exception(('Topic:"%s"未注册' % topic_name)) else: if is_shadow: if (type == 'publish'): return ((('/shadow/update/' + device.product_key) + '/') + device.device_name) elif (type == 'subscribe'): return ((('/shadow/get/' + device.product_key) + '/') + device.device_name) if ((topic_name == '') or (topic_name is None) or (topic_name == 'root')): return ((('/' + device.product_key) + '/') + device.device_name) elif (type == 'publish'): return ((((('/' + device.product_key) + '/') + device.device_name) + '/update_') + topic_name) elif (type == 'subscribe'): return ((((('/' + device.product_key) + '/') + device.device_name) + '/get_') + topic_name)
返回一个topic自定义的topic类 :param topic_name: :param type :param is_shadow :return:
src/components/aliyun_iotx/topic.py
get_topic_name
culiutudousi/kim-voice-assistant
75
python
def get_topic_name(topic_name='root', type='publish', is_shadow=False): '\n 返回一个topic自定义的topic类\n :param topic_name:\n :param type\n :param is_shadow\n :return:\n ' registered_topic = [, 'mic_text_from_server', 'conversation_log'] if (type not in ['subscribe', 'publish']): raise Exception('Unsupported topic type.') if (topic_name not in registered_topic): _logger.error('not registered topic') raise Exception(('Topic:"%s"未注册' % topic_name)) else: if is_shadow: if (type == 'publish'): return ((('/shadow/update/' + device.product_key) + '/') + device.device_name) elif (type == 'subscribe'): return ((('/shadow/get/' + device.product_key) + '/') + device.device_name) if ((topic_name == ) or (topic_name is None) or (topic_name == 'root')): return ((('/' + device.product_key) + '/') + device.device_name) elif (type == 'publish'): return ((((('/' + device.product_key) + '/') + device.device_name) + '/update_') + topic_name) elif (type == 'subscribe'): return ((((('/' + device.product_key) + '/') + device.device_name) + '/get_') + topic_name)
def get_topic_name(topic_name='root', type='publish', is_shadow=False): '\n 返回一个topic自定义的topic类\n :param topic_name:\n :param type\n :param is_shadow\n :return:\n ' registered_topic = [, 'mic_text_from_server', 'conversation_log'] if (type not in ['subscribe', 'publish']): raise Exception('Unsupported topic type.') if (topic_name not in registered_topic): _logger.error('not registered topic') raise Exception(('Topic:"%s"未注册' % topic_name)) else: if is_shadow: if (type == 'publish'): return ((('/shadow/update/' + device.product_key) + '/') + device.device_name) elif (type == 'subscribe'): return ((('/shadow/get/' + device.product_key) + '/') + device.device_name) if ((topic_name == ) or (topic_name is None) or (topic_name == 'root')): return ((('/' + device.product_key) + '/') + device.device_name) elif (type == 'publish'): return ((((('/' + device.product_key) + '/') + device.device_name) + '/update_') + topic_name) elif (type == 'subscribe'): return ((((('/' + device.product_key) + '/') + device.device_name) + '/get_') + topic_name)<|docstring|>返回一个topic自定义的topic类 :param topic_name: :param type :param is_shadow :return:<|endoftext|>
44dde16893effe703a8e92bdf033e63cda3394de76367fca34fe3dbdf0930dd5
@httpretty.activate def test_tracking_context(self): '\n Ensure the tracking context is set up in the api client correctly and\n automatically.\n ' with freeze_time('2015-7-2'): httpretty.register_uri(httpretty.POST, '{}/baskets/1/'.format(settings.ECOMMERCE_API_URL.strip('/')), status=200, body='{}', adding_headers={'Content-Type': JSON}) mock_tracker = mock.Mock() mock_tracker.resolve_context = mock.Mock(return_value={'ip': '127.0.0.1'}) with mock.patch('openedx.core.djangoapps.commerce.utils.tracker.get_tracker', return_value=mock_tracker): ecommerce_api_client(self.user).baskets(1).post() actual_header = httpretty.last_request().headers['Authorization'] claims = {'tracking_context': {'lms_user_id': self.user.id, 'lms_ip': '127.0.0.1'}} expected_jwt = create_jwt_for_user(self.user, additional_claims=claims, scopes=self.SCOPES) expected_header = f'JWT {expected_jwt}' assert (actual_header == expected_header)
Ensure the tracking context is set up in the api client correctly and automatically.
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/commerce/tests/__init__.py
test_tracking_context
osoco/better-ways-of-thinking-about-software
3
python
@httpretty.activate def test_tracking_context(self): '\n Ensure the tracking context is set up in the api client correctly and\n automatically.\n ' with freeze_time('2015-7-2'): httpretty.register_uri(httpretty.POST, '{}/baskets/1/'.format(settings.ECOMMERCE_API_URL.strip('/')), status=200, body='{}', adding_headers={'Content-Type': JSON}) mock_tracker = mock.Mock() mock_tracker.resolve_context = mock.Mock(return_value={'ip': '127.0.0.1'}) with mock.patch('openedx.core.djangoapps.commerce.utils.tracker.get_tracker', return_value=mock_tracker): ecommerce_api_client(self.user).baskets(1).post() actual_header = httpretty.last_request().headers['Authorization'] claims = {'tracking_context': {'lms_user_id': self.user.id, 'lms_ip': '127.0.0.1'}} expected_jwt = create_jwt_for_user(self.user, additional_claims=claims, scopes=self.SCOPES) expected_header = f'JWT {expected_jwt}' assert (actual_header == expected_header)
@httpretty.activate def test_tracking_context(self): '\n Ensure the tracking context is set up in the api client correctly and\n automatically.\n ' with freeze_time('2015-7-2'): httpretty.register_uri(httpretty.POST, '{}/baskets/1/'.format(settings.ECOMMERCE_API_URL.strip('/')), status=200, body='{}', adding_headers={'Content-Type': JSON}) mock_tracker = mock.Mock() mock_tracker.resolve_context = mock.Mock(return_value={'ip': '127.0.0.1'}) with mock.patch('openedx.core.djangoapps.commerce.utils.tracker.get_tracker', return_value=mock_tracker): ecommerce_api_client(self.user).baskets(1).post() actual_header = httpretty.last_request().headers['Authorization'] claims = {'tracking_context': {'lms_user_id': self.user.id, 'lms_ip': '127.0.0.1'}} expected_jwt = create_jwt_for_user(self.user, additional_claims=claims, scopes=self.SCOPES) expected_header = f'JWT {expected_jwt}' assert (actual_header == expected_header)<|docstring|>Ensure the tracking context is set up in the api client correctly and automatically.<|endoftext|>
a01e4b44eef1b0f570f77f69b0b2ed3f8141b45213869b6b6ce80e8106f9915a
@httpretty.activate def test_client_unicode(self): '\n The client should handle json responses properly when they contain\n unicode character data.\n\n Regression test for ECOM-1606.\n ' expected_content = '{"result": "Préparatoire"}' httpretty.register_uri(httpretty.GET, '{}/baskets/1/order/'.format(settings.ECOMMERCE_API_URL.strip('/')), status=200, body=expected_content, adding_headers={'Content-Type': JSON}) actual_object = ecommerce_api_client(self.user).baskets(1).order.get() assert (actual_object == {'result': 'Préparatoire'})
The client should handle json responses properly when they contain unicode character data. Regression test for ECOM-1606.
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/commerce/tests/__init__.py
test_client_unicode
osoco/better-ways-of-thinking-about-software
3
python
@httpretty.activate def test_client_unicode(self): '\n The client should handle json responses properly when they contain\n unicode character data.\n\n Regression test for ECOM-1606.\n ' expected_content = '{"result": "Préparatoire"}' httpretty.register_uri(httpretty.GET, '{}/baskets/1/order/'.format(settings.ECOMMERCE_API_URL.strip('/')), status=200, body=expected_content, adding_headers={'Content-Type': JSON}) actual_object = ecommerce_api_client(self.user).baskets(1).order.get() assert (actual_object == {'result': 'Préparatoire'})
@httpretty.activate def test_client_unicode(self): '\n The client should handle json responses properly when they contain\n unicode character data.\n\n Regression test for ECOM-1606.\n ' expected_content = '{"result": "Préparatoire"}' httpretty.register_uri(httpretty.GET, '{}/baskets/1/order/'.format(settings.ECOMMERCE_API_URL.strip('/')), status=200, body=expected_content, adding_headers={'Content-Type': JSON}) actual_object = ecommerce_api_client(self.user).baskets(1).order.get() assert (actual_object == {'result': 'Préparatoire'})<|docstring|>The client should handle json responses properly when they contain unicode character data. Regression test for ECOM-1606.<|endoftext|>
0b2912f9725feddb012e73deccba9e6ec1d3392c458235d62635c36acfce0a63
def MnistInput(mnist_data_file, batch_size, randomize): 'Create operations to read the MNIST input file.\n\n Args:\n mnist_data_file: Path of a file containing the MNIST images to process.\n batch_size: size of the mini batches to generate.\n randomize: If true, randomize the dataset.\n\n Returns:\n images: A tensor with the formatted image data. shape [batch_size, 28*28]\n labels: A tensor with the labels for each image. shape [batch_size]\n ' file_queue = tf.train.string_input_producer([mnist_data_file]) reader = tf.TFRecordReader() (_, value) = reader.read(file_queue) example = tf.parse_single_example(value, features={'image/encoded': tf.FixedLenFeature(shape=(), dtype=tf.string), 'image/class/label': tf.FixedLenFeature([1], tf.int64)}) image = tf.cast(tf.image.decode_png(example['image/encoded'], channels=1), tf.float32) image = tf.reshape(image, [(IMAGE_SIZE * IMAGE_SIZE)]) image /= 255 label = tf.cast(example['image/class/label'], dtype=tf.int32) label = tf.reshape(label, []) if randomize: (images, labels) = tf.train.shuffle_batch([image, label], batch_size=batch_size, capacity=(batch_size * 100), min_after_dequeue=(batch_size * 10)) else: (images, labels) = tf.train.batch([image, label], batch_size=batch_size) return (images, labels)
Create operations to read the MNIST input file. Args: mnist_data_file: Path of a file containing the MNIST images to process. batch_size: size of the mini batches to generate. randomize: If true, randomize the dataset. Returns: images: A tensor with the formatted image data. shape [batch_size, 28*28] labels: A tensor with the labels for each image. shape [batch_size]
tensorflow_dl_models/research/differential_privacy/dp_sgd/dp_mnist/dp_mnist.py
MnistInput
AadityaGupta/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
3,326
python
def MnistInput(mnist_data_file, batch_size, randomize): 'Create operations to read the MNIST input file.\n\n Args:\n mnist_data_file: Path of a file containing the MNIST images to process.\n batch_size: size of the mini batches to generate.\n randomize: If true, randomize the dataset.\n\n Returns:\n images: A tensor with the formatted image data. shape [batch_size, 28*28]\n labels: A tensor with the labels for each image. shape [batch_size]\n ' file_queue = tf.train.string_input_producer([mnist_data_file]) reader = tf.TFRecordReader() (_, value) = reader.read(file_queue) example = tf.parse_single_example(value, features={'image/encoded': tf.FixedLenFeature(shape=(), dtype=tf.string), 'image/class/label': tf.FixedLenFeature([1], tf.int64)}) image = tf.cast(tf.image.decode_png(example['image/encoded'], channels=1), tf.float32) image = tf.reshape(image, [(IMAGE_SIZE * IMAGE_SIZE)]) image /= 255 label = tf.cast(example['image/class/label'], dtype=tf.int32) label = tf.reshape(label, []) if randomize: (images, labels) = tf.train.shuffle_batch([image, label], batch_size=batch_size, capacity=(batch_size * 100), min_after_dequeue=(batch_size * 10)) else: (images, labels) = tf.train.batch([image, label], batch_size=batch_size) return (images, labels)
def MnistInput(mnist_data_file, batch_size, randomize): 'Create operations to read the MNIST input file.\n\n Args:\n mnist_data_file: Path of a file containing the MNIST images to process.\n batch_size: size of the mini batches to generate.\n randomize: If true, randomize the dataset.\n\n Returns:\n images: A tensor with the formatted image data. shape [batch_size, 28*28]\n labels: A tensor with the labels for each image. shape [batch_size]\n ' file_queue = tf.train.string_input_producer([mnist_data_file]) reader = tf.TFRecordReader() (_, value) = reader.read(file_queue) example = tf.parse_single_example(value, features={'image/encoded': tf.FixedLenFeature(shape=(), dtype=tf.string), 'image/class/label': tf.FixedLenFeature([1], tf.int64)}) image = tf.cast(tf.image.decode_png(example['image/encoded'], channels=1), tf.float32) image = tf.reshape(image, [(IMAGE_SIZE * IMAGE_SIZE)]) image /= 255 label = tf.cast(example['image/class/label'], dtype=tf.int32) label = tf.reshape(label, []) if randomize: (images, labels) = tf.train.shuffle_batch([image, label], batch_size=batch_size, capacity=(batch_size * 100), min_after_dequeue=(batch_size * 10)) else: (images, labels) = tf.train.batch([image, label], batch_size=batch_size) return (images, labels)<|docstring|>Create operations to read the MNIST input file. Args: mnist_data_file: Path of a file containing the MNIST images to process. batch_size: size of the mini batches to generate. randomize: If true, randomize the dataset. Returns: images: A tensor with the formatted image data. shape [batch_size, 28*28] labels: A tensor with the labels for each image. shape [batch_size]<|endoftext|>
3cef9941c677dc3a245628af8eb9fe1ef0425d0f396dce4452da1a1fa64c4eb8
def Eval(mnist_data_file, network_parameters, num_testing_images, randomize, load_path, save_mistakes=False): 'Evaluate MNIST for a number of steps.\n\n Args:\n mnist_data_file: Path of a file containing the MNIST images to process.\n network_parameters: parameters for defining and training the network.\n num_testing_images: the number of images we will evaluate on.\n randomize: if false, randomize; otherwise, read the testing images\n sequentially.\n load_path: path where to load trained parameters from.\n save_mistakes: save the mistakes if True.\n\n Returns:\n The evaluation accuracy as a float.\n ' batch_size = 100 with tf.Graph().as_default(), tf.Session() as sess: (images, labels) = MnistInput(mnist_data_file, batch_size, randomize) (logits, _, _) = utils.BuildNetwork(images, network_parameters) softmax = tf.nn.softmax(logits) ckpt_state = tf.train.get_checkpoint_state(load_path) if (not (ckpt_state and ckpt_state.model_checkpoint_path)): raise ValueError(('No model checkpoint to eval at %s\n' % load_path)) saver = tf.train.Saver() saver.restore(sess, ckpt_state.model_checkpoint_path) coord = tf.train.Coordinator() _ = tf.train.start_queue_runners(sess=sess, coord=coord) total_examples = 0 correct_predictions = 0 image_index = 0 mistakes = [] for _ in xrange((((num_testing_images + batch_size) - 1) // batch_size)): (predictions, label_values) = sess.run([softmax, labels]) for (prediction, label_value) in zip(predictions, label_values): total_examples += 1 if (np.argmax(prediction) == label_value): correct_predictions += 1 elif save_mistakes: mistakes.append({'index': image_index, 'label': label_value, 'pred': np.argmax(prediction)}) image_index += 1 return ((correct_predictions / total_examples), (mistakes if save_mistakes else None))
Evaluate MNIST for a number of steps. Args: mnist_data_file: Path of a file containing the MNIST images to process. network_parameters: parameters for defining and training the network. num_testing_images: the number of images we will evaluate on. randomize: if false, randomize; otherwise, read the testing images sequentially. load_path: path where to load trained parameters from. save_mistakes: save the mistakes if True. Returns: The evaluation accuracy as a float.
tensorflow_dl_models/research/differential_privacy/dp_sgd/dp_mnist/dp_mnist.py
Eval
AadityaGupta/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
3,326
python
def Eval(mnist_data_file, network_parameters, num_testing_images, randomize, load_path, save_mistakes=False): 'Evaluate MNIST for a number of steps.\n\n Args:\n mnist_data_file: Path of a file containing the MNIST images to process.\n network_parameters: parameters for defining and training the network.\n num_testing_images: the number of images we will evaluate on.\n randomize: if false, randomize; otherwise, read the testing images\n sequentially.\n load_path: path where to load trained parameters from.\n save_mistakes: save the mistakes if True.\n\n Returns:\n The evaluation accuracy as a float.\n ' batch_size = 100 with tf.Graph().as_default(), tf.Session() as sess: (images, labels) = MnistInput(mnist_data_file, batch_size, randomize) (logits, _, _) = utils.BuildNetwork(images, network_parameters) softmax = tf.nn.softmax(logits) ckpt_state = tf.train.get_checkpoint_state(load_path) if (not (ckpt_state and ckpt_state.model_checkpoint_path)): raise ValueError(('No model checkpoint to eval at %s\n' % load_path)) saver = tf.train.Saver() saver.restore(sess, ckpt_state.model_checkpoint_path) coord = tf.train.Coordinator() _ = tf.train.start_queue_runners(sess=sess, coord=coord) total_examples = 0 correct_predictions = 0 image_index = 0 mistakes = [] for _ in xrange((((num_testing_images + batch_size) - 1) // batch_size)): (predictions, label_values) = sess.run([softmax, labels]) for (prediction, label_value) in zip(predictions, label_values): total_examples += 1 if (np.argmax(prediction) == label_value): correct_predictions += 1 elif save_mistakes: mistakes.append({'index': image_index, 'label': label_value, 'pred': np.argmax(prediction)}) image_index += 1 return ((correct_predictions / total_examples), (mistakes if save_mistakes else None))
def Eval(mnist_data_file, network_parameters, num_testing_images, randomize, load_path, save_mistakes=False): 'Evaluate MNIST for a number of steps.\n\n Args:\n mnist_data_file: Path of a file containing the MNIST images to process.\n network_parameters: parameters for defining and training the network.\n num_testing_images: the number of images we will evaluate on.\n randomize: if false, randomize; otherwise, read the testing images\n sequentially.\n load_path: path where to load trained parameters from.\n save_mistakes: save the mistakes if True.\n\n Returns:\n The evaluation accuracy as a float.\n ' batch_size = 100 with tf.Graph().as_default(), tf.Session() as sess: (images, labels) = MnistInput(mnist_data_file, batch_size, randomize) (logits, _, _) = utils.BuildNetwork(images, network_parameters) softmax = tf.nn.softmax(logits) ckpt_state = tf.train.get_checkpoint_state(load_path) if (not (ckpt_state and ckpt_state.model_checkpoint_path)): raise ValueError(('No model checkpoint to eval at %s\n' % load_path)) saver = tf.train.Saver() saver.restore(sess, ckpt_state.model_checkpoint_path) coord = tf.train.Coordinator() _ = tf.train.start_queue_runners(sess=sess, coord=coord) total_examples = 0 correct_predictions = 0 image_index = 0 mistakes = [] for _ in xrange((((num_testing_images + batch_size) - 1) // batch_size)): (predictions, label_values) = sess.run([softmax, labels]) for (prediction, label_value) in zip(predictions, label_values): total_examples += 1 if (np.argmax(prediction) == label_value): correct_predictions += 1 elif save_mistakes: mistakes.append({'index': image_index, 'label': label_value, 'pred': np.argmax(prediction)}) image_index += 1 return ((correct_predictions / total_examples), (mistakes if save_mistakes else None))<|docstring|>Evaluate MNIST for a number of steps. Args: mnist_data_file: Path of a file containing the MNIST images to process. network_parameters: parameters for defining and training the network. num_testing_images: the number of images we will evaluate on. randomize: if false, randomize; otherwise, read the testing images sequentially. load_path: path where to load trained parameters from. save_mistakes: save the mistakes if True. Returns: The evaluation accuracy as a float.<|endoftext|>
89aaa7a9b3ab6e2beb613167ea10cafa6ff3a7d981b3c5db157d22b6db35bd62
def Train(mnist_train_file, mnist_test_file, network_parameters, num_steps, save_path, eval_steps=0): 'Train MNIST for a number of steps.\n\n Args:\n mnist_train_file: path of MNIST train data file.\n mnist_test_file: path of MNIST test data file.\n network_parameters: parameters for defining and training the network.\n num_steps: number of steps to run. Here steps = lots\n save_path: path where to save trained parameters.\n eval_steps: evaluate the model every eval_steps.\n\n Returns:\n the result after the final training step.\n\n Raises:\n ValueError: if the accountant_type is not supported.\n ' batch_size = FLAGS.batch_size params = {'accountant_type': FLAGS.accountant_type, 'task_id': 0, 'batch_size': FLAGS.batch_size, 'projection_dimensions': FLAGS.projection_dimensions, 'default_gradient_l2norm_bound': network_parameters.default_gradient_l2norm_bound, 'num_hidden_layers': FLAGS.num_hidden_layers, 'hidden_layer_num_units': FLAGS.hidden_layer_num_units, 'num_examples': NUM_TRAINING_IMAGES, 'learning_rate': FLAGS.lr, 'end_learning_rate': FLAGS.end_lr, 'learning_rate_saturate_epochs': FLAGS.lr_saturate_epochs} if (FLAGS.accountant_type == 'Amortized'): params.update({'flag_eps': FLAGS.eps, 'flag_delta': FLAGS.delta, 'flag_pca_eps': FLAGS.pca_eps, 'flag_pca_delta': FLAGS.pca_delta}) elif (FLAGS.accountant_type == 'Moments'): params.update({'sigma': FLAGS.sigma, 'pca_sigma': FLAGS.pca_sigma}) with tf.Graph().as_default(), tf.Session() as sess, tf.device('/cpu:0'): (images, labels) = MnistInput(mnist_train_file, batch_size, FLAGS.randomize) (logits, projection, training_params) = utils.BuildNetwork(images, network_parameters) cost = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf.one_hot(labels, 10)) cost = (tf.reduce_sum(cost, [0]) / batch_size) if (FLAGS.accountant_type == 'Amortized'): priv_accountant = accountant.AmortizedAccountant(NUM_TRAINING_IMAGES) sigma = None pca_sigma = None with_privacy = (FLAGS.eps > 0) elif (FLAGS.accountant_type == 'Moments'): priv_accountant = accountant.GaussianMomentsAccountant(NUM_TRAINING_IMAGES) sigma = FLAGS.sigma pca_sigma = FLAGS.pca_sigma with_privacy = (FLAGS.sigma > 0) else: raise ValueError(('Undefined accountant type, needs to be Amortized or Moments, but got %s' % FLAGS.accountant)) gaussian_sanitizer = sanitizer.AmortizedGaussianSanitizer(priv_accountant, [(network_parameters.default_gradient_l2norm_bound / batch_size), True]) for var in training_params: if ('gradient_l2norm_bound' in training_params[var]): l2bound = (training_params[var]['gradient_l2norm_bound'] / batch_size) gaussian_sanitizer.set_option(var, sanitizer.ClipOption(l2bound, True)) lr = tf.placeholder(tf.float32) eps = tf.placeholder(tf.float32) delta = tf.placeholder(tf.float32) init_ops = [] if (network_parameters.projection_type == 'PCA'): with tf.variable_scope('pca'): (all_data, _) = MnistInput(mnist_train_file, NUM_TRAINING_IMAGES, False) pca_projection = dp_pca.ComputeDPPrincipalProjection(all_data, network_parameters.projection_dimensions, gaussian_sanitizer, [FLAGS.pca_eps, FLAGS.pca_delta], pca_sigma) assign_pca_proj = tf.assign(projection, pca_projection) init_ops.append(assign_pca_proj) global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step') if with_privacy: gd_op = dp_optimizer.DPGradientDescentOptimizer(lr, [eps, delta], gaussian_sanitizer, sigma=sigma, batches_per_lot=FLAGS.batches_per_lot).minimize(cost, global_step=global_step) else: gd_op = tf.train.GradientDescentOptimizer(lr).minimize(cost) saver = tf.train.Saver() coord = tf.train.Coordinator() _ = tf.train.start_queue_runners(sess=sess, coord=coord) for v in tf.trainable_variables(): sess.run(tf.variables_initializer([v])) sess.run(tf.global_variables_initializer()) sess.run(init_ops) results = [] start_time = time.time() prev_time = start_time filename = 'results-0.json' log_path = os.path.join(save_path, filename) target_eps = [float(s) for s in FLAGS.target_eps.split(',')] if (FLAGS.accountant_type == 'Amortized'): target_eps = [max(target_eps)] max_target_eps = max(target_eps) lot_size = (FLAGS.batches_per_lot * FLAGS.batch_size) lots_per_epoch = (NUM_TRAINING_IMAGES / lot_size) for step in xrange(num_steps): epoch = (step / lots_per_epoch) curr_lr = utils.VaryRate(FLAGS.lr, FLAGS.end_lr, FLAGS.lr_saturate_epochs, epoch) curr_eps = utils.VaryRate(FLAGS.eps, FLAGS.end_eps, FLAGS.eps_saturate_epochs, epoch) for _ in xrange(FLAGS.batches_per_lot): _ = sess.run([gd_op], feed_dict={lr: curr_lr, eps: curr_eps, delta: FLAGS.delta}) sys.stderr.write(('step: %d\n' % step)) should_terminate = False terminate_spent_eps_delta = None if (with_privacy and FLAGS.terminate_based_on_privacy): terminate_spent_eps_delta = priv_accountant.get_privacy_spent(sess, target_eps=[max_target_eps])[0] if ((terminate_spent_eps_delta.spent_delta > FLAGS.target_delta) or (terminate_spent_eps_delta.spent_eps > max_target_eps)): should_terminate = True if (((eval_steps > 0) and (((step + 1) % eval_steps) == 0)) or should_terminate): if with_privacy: spent_eps_deltas = priv_accountant.get_privacy_spent(sess, target_eps=target_eps) else: spent_eps_deltas = [accountant.EpsDelta(0, 0)] for (spent_eps, spent_delta) in spent_eps_deltas: sys.stderr.write(('spent privacy: eps %.4f delta %.5g\n' % (spent_eps, spent_delta))) saver.save(sess, save_path=(save_path + '/ckpt')) (train_accuracy, _) = Eval(mnist_train_file, network_parameters, num_testing_images=NUM_TESTING_IMAGES, randomize=True, load_path=save_path) sys.stderr.write(('train_accuracy: %.2f\n' % train_accuracy)) (test_accuracy, mistakes) = Eval(mnist_test_file, network_parameters, num_testing_images=NUM_TESTING_IMAGES, randomize=False, load_path=save_path, save_mistakes=FLAGS.save_mistakes) sys.stderr.write(('eval_accuracy: %.2f\n' % test_accuracy)) curr_time = time.time() elapsed_time = (curr_time - prev_time) prev_time = curr_time results.append({'step': (step + 1), 'elapsed_secs': elapsed_time, 'spent_eps_deltas': spent_eps_deltas, 'train_accuracy': train_accuracy, 'test_accuracy': test_accuracy, 'mistakes': mistakes}) loginfo = {'elapsed_secs': (curr_time - start_time), 'spent_eps_deltas': spent_eps_deltas, 'train_accuracy': train_accuracy, 'test_accuracy': test_accuracy, 'num_training_steps': (step + 1), 'mistakes': mistakes, 'result_series': results} loginfo.update(params) if log_path: with tf.gfile.Open(log_path, 'w') as f: json.dump(loginfo, f, indent=2) f.write('\n') f.close() if should_terminate: break
Train MNIST for a number of steps. Args: mnist_train_file: path of MNIST train data file. mnist_test_file: path of MNIST test data file. network_parameters: parameters for defining and training the network. num_steps: number of steps to run. Here steps = lots save_path: path where to save trained parameters. eval_steps: evaluate the model every eval_steps. Returns: the result after the final training step. Raises: ValueError: if the accountant_type is not supported.
tensorflow_dl_models/research/differential_privacy/dp_sgd/dp_mnist/dp_mnist.py
Train
AadityaGupta/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
3,326
python
def Train(mnist_train_file, mnist_test_file, network_parameters, num_steps, save_path, eval_steps=0): 'Train MNIST for a number of steps.\n\n Args:\n mnist_train_file: path of MNIST train data file.\n mnist_test_file: path of MNIST test data file.\n network_parameters: parameters for defining and training the network.\n num_steps: number of steps to run. Here steps = lots\n save_path: path where to save trained parameters.\n eval_steps: evaluate the model every eval_steps.\n\n Returns:\n the result after the final training step.\n\n Raises:\n ValueError: if the accountant_type is not supported.\n ' batch_size = FLAGS.batch_size params = {'accountant_type': FLAGS.accountant_type, 'task_id': 0, 'batch_size': FLAGS.batch_size, 'projection_dimensions': FLAGS.projection_dimensions, 'default_gradient_l2norm_bound': network_parameters.default_gradient_l2norm_bound, 'num_hidden_layers': FLAGS.num_hidden_layers, 'hidden_layer_num_units': FLAGS.hidden_layer_num_units, 'num_examples': NUM_TRAINING_IMAGES, 'learning_rate': FLAGS.lr, 'end_learning_rate': FLAGS.end_lr, 'learning_rate_saturate_epochs': FLAGS.lr_saturate_epochs} if (FLAGS.accountant_type == 'Amortized'): params.update({'flag_eps': FLAGS.eps, 'flag_delta': FLAGS.delta, 'flag_pca_eps': FLAGS.pca_eps, 'flag_pca_delta': FLAGS.pca_delta}) elif (FLAGS.accountant_type == 'Moments'): params.update({'sigma': FLAGS.sigma, 'pca_sigma': FLAGS.pca_sigma}) with tf.Graph().as_default(), tf.Session() as sess, tf.device('/cpu:0'): (images, labels) = MnistInput(mnist_train_file, batch_size, FLAGS.randomize) (logits, projection, training_params) = utils.BuildNetwork(images, network_parameters) cost = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf.one_hot(labels, 10)) cost = (tf.reduce_sum(cost, [0]) / batch_size) if (FLAGS.accountant_type == 'Amortized'): priv_accountant = accountant.AmortizedAccountant(NUM_TRAINING_IMAGES) sigma = None pca_sigma = None with_privacy = (FLAGS.eps > 0) elif (FLAGS.accountant_type == 'Moments'): priv_accountant = accountant.GaussianMomentsAccountant(NUM_TRAINING_IMAGES) sigma = FLAGS.sigma pca_sigma = FLAGS.pca_sigma with_privacy = (FLAGS.sigma > 0) else: raise ValueError(('Undefined accountant type, needs to be Amortized or Moments, but got %s' % FLAGS.accountant)) gaussian_sanitizer = sanitizer.AmortizedGaussianSanitizer(priv_accountant, [(network_parameters.default_gradient_l2norm_bound / batch_size), True]) for var in training_params: if ('gradient_l2norm_bound' in training_params[var]): l2bound = (training_params[var]['gradient_l2norm_bound'] / batch_size) gaussian_sanitizer.set_option(var, sanitizer.ClipOption(l2bound, True)) lr = tf.placeholder(tf.float32) eps = tf.placeholder(tf.float32) delta = tf.placeholder(tf.float32) init_ops = [] if (network_parameters.projection_type == 'PCA'): with tf.variable_scope('pca'): (all_data, _) = MnistInput(mnist_train_file, NUM_TRAINING_IMAGES, False) pca_projection = dp_pca.ComputeDPPrincipalProjection(all_data, network_parameters.projection_dimensions, gaussian_sanitizer, [FLAGS.pca_eps, FLAGS.pca_delta], pca_sigma) assign_pca_proj = tf.assign(projection, pca_projection) init_ops.append(assign_pca_proj) global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step') if with_privacy: gd_op = dp_optimizer.DPGradientDescentOptimizer(lr, [eps, delta], gaussian_sanitizer, sigma=sigma, batches_per_lot=FLAGS.batches_per_lot).minimize(cost, global_step=global_step) else: gd_op = tf.train.GradientDescentOptimizer(lr).minimize(cost) saver = tf.train.Saver() coord = tf.train.Coordinator() _ = tf.train.start_queue_runners(sess=sess, coord=coord) for v in tf.trainable_variables(): sess.run(tf.variables_initializer([v])) sess.run(tf.global_variables_initializer()) sess.run(init_ops) results = [] start_time = time.time() prev_time = start_time filename = 'results-0.json' log_path = os.path.join(save_path, filename) target_eps = [float(s) for s in FLAGS.target_eps.split(',')] if (FLAGS.accountant_type == 'Amortized'): target_eps = [max(target_eps)] max_target_eps = max(target_eps) lot_size = (FLAGS.batches_per_lot * FLAGS.batch_size) lots_per_epoch = (NUM_TRAINING_IMAGES / lot_size) for step in xrange(num_steps): epoch = (step / lots_per_epoch) curr_lr = utils.VaryRate(FLAGS.lr, FLAGS.end_lr, FLAGS.lr_saturate_epochs, epoch) curr_eps = utils.VaryRate(FLAGS.eps, FLAGS.end_eps, FLAGS.eps_saturate_epochs, epoch) for _ in xrange(FLAGS.batches_per_lot): _ = sess.run([gd_op], feed_dict={lr: curr_lr, eps: curr_eps, delta: FLAGS.delta}) sys.stderr.write(('step: %d\n' % step)) should_terminate = False terminate_spent_eps_delta = None if (with_privacy and FLAGS.terminate_based_on_privacy): terminate_spent_eps_delta = priv_accountant.get_privacy_spent(sess, target_eps=[max_target_eps])[0] if ((terminate_spent_eps_delta.spent_delta > FLAGS.target_delta) or (terminate_spent_eps_delta.spent_eps > max_target_eps)): should_terminate = True if (((eval_steps > 0) and (((step + 1) % eval_steps) == 0)) or should_terminate): if with_privacy: spent_eps_deltas = priv_accountant.get_privacy_spent(sess, target_eps=target_eps) else: spent_eps_deltas = [accountant.EpsDelta(0, 0)] for (spent_eps, spent_delta) in spent_eps_deltas: sys.stderr.write(('spent privacy: eps %.4f delta %.5g\n' % (spent_eps, spent_delta))) saver.save(sess, save_path=(save_path + '/ckpt')) (train_accuracy, _) = Eval(mnist_train_file, network_parameters, num_testing_images=NUM_TESTING_IMAGES, randomize=True, load_path=save_path) sys.stderr.write(('train_accuracy: %.2f\n' % train_accuracy)) (test_accuracy, mistakes) = Eval(mnist_test_file, network_parameters, num_testing_images=NUM_TESTING_IMAGES, randomize=False, load_path=save_path, save_mistakes=FLAGS.save_mistakes) sys.stderr.write(('eval_accuracy: %.2f\n' % test_accuracy)) curr_time = time.time() elapsed_time = (curr_time - prev_time) prev_time = curr_time results.append({'step': (step + 1), 'elapsed_secs': elapsed_time, 'spent_eps_deltas': spent_eps_deltas, 'train_accuracy': train_accuracy, 'test_accuracy': test_accuracy, 'mistakes': mistakes}) loginfo = {'elapsed_secs': (curr_time - start_time), 'spent_eps_deltas': spent_eps_deltas, 'train_accuracy': train_accuracy, 'test_accuracy': test_accuracy, 'num_training_steps': (step + 1), 'mistakes': mistakes, 'result_series': results} loginfo.update(params) if log_path: with tf.gfile.Open(log_path, 'w') as f: json.dump(loginfo, f, indent=2) f.write('\n') f.close() if should_terminate: break
def Train(mnist_train_file, mnist_test_file, network_parameters, num_steps, save_path, eval_steps=0): 'Train MNIST for a number of steps.\n\n Args:\n mnist_train_file: path of MNIST train data file.\n mnist_test_file: path of MNIST test data file.\n network_parameters: parameters for defining and training the network.\n num_steps: number of steps to run. Here steps = lots\n save_path: path where to save trained parameters.\n eval_steps: evaluate the model every eval_steps.\n\n Returns:\n the result after the final training step.\n\n Raises:\n ValueError: if the accountant_type is not supported.\n ' batch_size = FLAGS.batch_size params = {'accountant_type': FLAGS.accountant_type, 'task_id': 0, 'batch_size': FLAGS.batch_size, 'projection_dimensions': FLAGS.projection_dimensions, 'default_gradient_l2norm_bound': network_parameters.default_gradient_l2norm_bound, 'num_hidden_layers': FLAGS.num_hidden_layers, 'hidden_layer_num_units': FLAGS.hidden_layer_num_units, 'num_examples': NUM_TRAINING_IMAGES, 'learning_rate': FLAGS.lr, 'end_learning_rate': FLAGS.end_lr, 'learning_rate_saturate_epochs': FLAGS.lr_saturate_epochs} if (FLAGS.accountant_type == 'Amortized'): params.update({'flag_eps': FLAGS.eps, 'flag_delta': FLAGS.delta, 'flag_pca_eps': FLAGS.pca_eps, 'flag_pca_delta': FLAGS.pca_delta}) elif (FLAGS.accountant_type == 'Moments'): params.update({'sigma': FLAGS.sigma, 'pca_sigma': FLAGS.pca_sigma}) with tf.Graph().as_default(), tf.Session() as sess, tf.device('/cpu:0'): (images, labels) = MnistInput(mnist_train_file, batch_size, FLAGS.randomize) (logits, projection, training_params) = utils.BuildNetwork(images, network_parameters) cost = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf.one_hot(labels, 10)) cost = (tf.reduce_sum(cost, [0]) / batch_size) if (FLAGS.accountant_type == 'Amortized'): priv_accountant = accountant.AmortizedAccountant(NUM_TRAINING_IMAGES) sigma = None pca_sigma = None with_privacy = (FLAGS.eps > 0) elif (FLAGS.accountant_type == 'Moments'): priv_accountant = accountant.GaussianMomentsAccountant(NUM_TRAINING_IMAGES) sigma = FLAGS.sigma pca_sigma = FLAGS.pca_sigma with_privacy = (FLAGS.sigma > 0) else: raise ValueError(('Undefined accountant type, needs to be Amortized or Moments, but got %s' % FLAGS.accountant)) gaussian_sanitizer = sanitizer.AmortizedGaussianSanitizer(priv_accountant, [(network_parameters.default_gradient_l2norm_bound / batch_size), True]) for var in training_params: if ('gradient_l2norm_bound' in training_params[var]): l2bound = (training_params[var]['gradient_l2norm_bound'] / batch_size) gaussian_sanitizer.set_option(var, sanitizer.ClipOption(l2bound, True)) lr = tf.placeholder(tf.float32) eps = tf.placeholder(tf.float32) delta = tf.placeholder(tf.float32) init_ops = [] if (network_parameters.projection_type == 'PCA'): with tf.variable_scope('pca'): (all_data, _) = MnistInput(mnist_train_file, NUM_TRAINING_IMAGES, False) pca_projection = dp_pca.ComputeDPPrincipalProjection(all_data, network_parameters.projection_dimensions, gaussian_sanitizer, [FLAGS.pca_eps, FLAGS.pca_delta], pca_sigma) assign_pca_proj = tf.assign(projection, pca_projection) init_ops.append(assign_pca_proj) global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step') if with_privacy: gd_op = dp_optimizer.DPGradientDescentOptimizer(lr, [eps, delta], gaussian_sanitizer, sigma=sigma, batches_per_lot=FLAGS.batches_per_lot).minimize(cost, global_step=global_step) else: gd_op = tf.train.GradientDescentOptimizer(lr).minimize(cost) saver = tf.train.Saver() coord = tf.train.Coordinator() _ = tf.train.start_queue_runners(sess=sess, coord=coord) for v in tf.trainable_variables(): sess.run(tf.variables_initializer([v])) sess.run(tf.global_variables_initializer()) sess.run(init_ops) results = [] start_time = time.time() prev_time = start_time filename = 'results-0.json' log_path = os.path.join(save_path, filename) target_eps = [float(s) for s in FLAGS.target_eps.split(',')] if (FLAGS.accountant_type == 'Amortized'): target_eps = [max(target_eps)] max_target_eps = max(target_eps) lot_size = (FLAGS.batches_per_lot * FLAGS.batch_size) lots_per_epoch = (NUM_TRAINING_IMAGES / lot_size) for step in xrange(num_steps): epoch = (step / lots_per_epoch) curr_lr = utils.VaryRate(FLAGS.lr, FLAGS.end_lr, FLAGS.lr_saturate_epochs, epoch) curr_eps = utils.VaryRate(FLAGS.eps, FLAGS.end_eps, FLAGS.eps_saturate_epochs, epoch) for _ in xrange(FLAGS.batches_per_lot): _ = sess.run([gd_op], feed_dict={lr: curr_lr, eps: curr_eps, delta: FLAGS.delta}) sys.stderr.write(('step: %d\n' % step)) should_terminate = False terminate_spent_eps_delta = None if (with_privacy and FLAGS.terminate_based_on_privacy): terminate_spent_eps_delta = priv_accountant.get_privacy_spent(sess, target_eps=[max_target_eps])[0] if ((terminate_spent_eps_delta.spent_delta > FLAGS.target_delta) or (terminate_spent_eps_delta.spent_eps > max_target_eps)): should_terminate = True if (((eval_steps > 0) and (((step + 1) % eval_steps) == 0)) or should_terminate): if with_privacy: spent_eps_deltas = priv_accountant.get_privacy_spent(sess, target_eps=target_eps) else: spent_eps_deltas = [accountant.EpsDelta(0, 0)] for (spent_eps, spent_delta) in spent_eps_deltas: sys.stderr.write(('spent privacy: eps %.4f delta %.5g\n' % (spent_eps, spent_delta))) saver.save(sess, save_path=(save_path + '/ckpt')) (train_accuracy, _) = Eval(mnist_train_file, network_parameters, num_testing_images=NUM_TESTING_IMAGES, randomize=True, load_path=save_path) sys.stderr.write(('train_accuracy: %.2f\n' % train_accuracy)) (test_accuracy, mistakes) = Eval(mnist_test_file, network_parameters, num_testing_images=NUM_TESTING_IMAGES, randomize=False, load_path=save_path, save_mistakes=FLAGS.save_mistakes) sys.stderr.write(('eval_accuracy: %.2f\n' % test_accuracy)) curr_time = time.time() elapsed_time = (curr_time - prev_time) prev_time = curr_time results.append({'step': (step + 1), 'elapsed_secs': elapsed_time, 'spent_eps_deltas': spent_eps_deltas, 'train_accuracy': train_accuracy, 'test_accuracy': test_accuracy, 'mistakes': mistakes}) loginfo = {'elapsed_secs': (curr_time - start_time), 'spent_eps_deltas': spent_eps_deltas, 'train_accuracy': train_accuracy, 'test_accuracy': test_accuracy, 'num_training_steps': (step + 1), 'mistakes': mistakes, 'result_series': results} loginfo.update(params) if log_path: with tf.gfile.Open(log_path, 'w') as f: json.dump(loginfo, f, indent=2) f.write('\n') f.close() if should_terminate: break<|docstring|>Train MNIST for a number of steps. Args: mnist_train_file: path of MNIST train data file. mnist_test_file: path of MNIST test data file. network_parameters: parameters for defining and training the network. num_steps: number of steps to run. Here steps = lots save_path: path where to save trained parameters. eval_steps: evaluate the model every eval_steps. Returns: the result after the final training step. Raises: ValueError: if the accountant_type is not supported.<|endoftext|>
be7b5cbeea5662caee1967b4b3e3085716d32bc808fc74acc244cacdf2bfc284
def getListPos(listIN, trackChr): '\n\tget [start,end] list position\n\tof a trackChr \n\t' listLen = len(listIN) posList = list() downChr = '' for i in range(listLen): upChr = i if ((len(posList) == 0) and (listIN[i] == trackChr)): posList.append(i) elif ((downChr != listIN[upChr]) and (downChr == trackChr)): posList.append((i - 1)) downChr = listIN[upChr] if (listIN[(- 1)] == trackChr): posList.append(i) return posList
get [start,end] list position of a trackChr
misc/pyutils/pyutils/pyutils/__init__.py
getListPos
antonioggsousa/misc-bioinfo-aggs
0
python
def getListPos(listIN, trackChr): '\n\tget [start,end] list position\n\tof a trackChr \n\t' listLen = len(listIN) posList = list() downChr = for i in range(listLen): upChr = i if ((len(posList) == 0) and (listIN[i] == trackChr)): posList.append(i) elif ((downChr != listIN[upChr]) and (downChr == trackChr)): posList.append((i - 1)) downChr = listIN[upChr] if (listIN[(- 1)] == trackChr): posList.append(i) return posList
def getListPos(listIN, trackChr): '\n\tget [start,end] list position\n\tof a trackChr \n\t' listLen = len(listIN) posList = list() downChr = for i in range(listLen): upChr = i if ((len(posList) == 0) and (listIN[i] == trackChr)): posList.append(i) elif ((downChr != listIN[upChr]) and (downChr == trackChr)): posList.append((i - 1)) downChr = listIN[upChr] if (listIN[(- 1)] == trackChr): posList.append(i) return posList<|docstring|>get [start,end] list position of a trackChr<|endoftext|>
7c14aa6730d858237df5eee11bf3495417da12031b74ce6026ffdb629c3e9e0d
def pickIndex(listIN, targetChr): '\n Get the index of a character or integer!\n ' for i in range(len(listIN)): if (str(listIN[i]) == str(targetChr)): return i
Get the index of a character or integer!
misc/pyutils/pyutils/pyutils/__init__.py
pickIndex
antonioggsousa/misc-bioinfo-aggs
0
python
def pickIndex(listIN, targetChr): '\n \n ' for i in range(len(listIN)): if (str(listIN[i]) == str(targetChr)): return i
def pickIndex(listIN, targetChr): '\n \n ' for i in range(len(listIN)): if (str(listIN[i]) == str(targetChr)): return i<|docstring|>Get the index of a character or integer!<|endoftext|>
be5c38523dc7b0c44273b287e3c95e6b4c57b86127ef817e5bd8073a13c8d215
def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=False, criteria_enable=True, timeout=60): '\n Setup all relevant parameters and create scenario\n\n If randomize is True, the scenario parameters are randomized\n ' self._map = CarlaDataProvider.get_map() self._first_vehicle_location = 25 self._first_vehicle_speed = 40 self._reference_waypoint = self._map.get_waypoint(config.trigger_points[0].location) self._other_actor_max_brake = 1.0 self._other_actor_stop_in_front_intersection = 20 self._other_actor_transform = None self.timeout = timeout super(FollowLeadingVehicle, self).__init__('FollowVehicle', ego_vehicles, config, world, debug_mode, criteria_enable=criteria_enable) if randomize: self._ego_other_distance_start = random.randint(4, 8)
Setup all relevant parameters and create scenario If randomize is True, the scenario parameters are randomized
srunner/scenarios/follow_leading_vehicle.py
__init__
goRichard/scenario_runner_fzi
0
python
def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=False, criteria_enable=True, timeout=60): '\n Setup all relevant parameters and create scenario\n\n If randomize is True, the scenario parameters are randomized\n ' self._map = CarlaDataProvider.get_map() self._first_vehicle_location = 25 self._first_vehicle_speed = 40 self._reference_waypoint = self._map.get_waypoint(config.trigger_points[0].location) self._other_actor_max_brake = 1.0 self._other_actor_stop_in_front_intersection = 20 self._other_actor_transform = None self.timeout = timeout super(FollowLeadingVehicle, self).__init__('FollowVehicle', ego_vehicles, config, world, debug_mode, criteria_enable=criteria_enable) if randomize: self._ego_other_distance_start = random.randint(4, 8)
def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=False, criteria_enable=True, timeout=60): '\n Setup all relevant parameters and create scenario\n\n If randomize is True, the scenario parameters are randomized\n ' self._map = CarlaDataProvider.get_map() self._first_vehicle_location = 25 self._first_vehicle_speed = 40 self._reference_waypoint = self._map.get_waypoint(config.trigger_points[0].location) self._other_actor_max_brake = 1.0 self._other_actor_stop_in_front_intersection = 20 self._other_actor_transform = None self.timeout = timeout super(FollowLeadingVehicle, self).__init__('FollowVehicle', ego_vehicles, config, world, debug_mode, criteria_enable=criteria_enable) if randomize: self._ego_other_distance_start = random.randint(4, 8)<|docstring|>Setup all relevant parameters and create scenario If randomize is True, the scenario parameters are randomized<|endoftext|>
e605ffdc4f5ff5aec5c5ac7d87df074dcd3307446398bb3920a361d2bdb30098
def _initialize_actors(self, config): '\n Custom initialization\n ' (first_vehicle_waypoint, _) = get_waypoint_in_distance(self._reference_waypoint, self._first_vehicle_location) self._other_actor_transform = carla.Transform(carla.Location(first_vehicle_waypoint.transform.location.x, first_vehicle_waypoint.transform.location.y, (first_vehicle_waypoint.transform.location.z + 1)), first_vehicle_waypoint.transform.rotation) first_vehicle_transform = carla.Transform(carla.Location(self._other_actor_transform.location.x, self._other_actor_transform.location.y, (self._other_actor_transform.location.z - 500)), self._other_actor_transform.rotation) '\n so the transformation contains two parameters:\n 1. location\n 2. rotation\n \n can be retrieved by transform.location and transform.rotation\n \n ' first_vehicle = CarlaActorPool.request_new_actor('vehicle.nissan.patrol', first_vehicle_transform) '\n The CarlaActorPool caches all scenario relevant actors.\n It works similar to a singelton.\n\n An actor can be created via "request_actor", and access\n is possible via "get_actor_by_id".\n\n Using CarlaActorPool, actors can be shared between scenarios.\n \n \n Method:\n request_new_actor(model, spawn_point, rolename=\'scenario\', hero=False, autopilot=False, random_location=False):\n \n This method tries to create a new actor. If this was\n successful, the new actor is returned, None otherwise.\n \n ' self.other_actors.append(first_vehicle)
Custom initialization
srunner/scenarios/follow_leading_vehicle.py
_initialize_actors
goRichard/scenario_runner_fzi
0
python
def _initialize_actors(self, config): '\n \n ' (first_vehicle_waypoint, _) = get_waypoint_in_distance(self._reference_waypoint, self._first_vehicle_location) self._other_actor_transform = carla.Transform(carla.Location(first_vehicle_waypoint.transform.location.x, first_vehicle_waypoint.transform.location.y, (first_vehicle_waypoint.transform.location.z + 1)), first_vehicle_waypoint.transform.rotation) first_vehicle_transform = carla.Transform(carla.Location(self._other_actor_transform.location.x, self._other_actor_transform.location.y, (self._other_actor_transform.location.z - 500)), self._other_actor_transform.rotation) '\n so the transformation contains two parameters:\n 1. location\n 2. rotation\n \n can be retrieved by transform.location and transform.rotation\n \n ' first_vehicle = CarlaActorPool.request_new_actor('vehicle.nissan.patrol', first_vehicle_transform) '\n The CarlaActorPool caches all scenario relevant actors.\n It works similar to a singelton.\n\n An actor can be created via "request_actor", and access\n is possible via "get_actor_by_id".\n\n Using CarlaActorPool, actors can be shared between scenarios.\n \n \n Method:\n request_new_actor(model, spawn_point, rolename=\'scenario\', hero=False, autopilot=False, random_location=False):\n \n This method tries to create a new actor. If this was\n successful, the new actor is returned, None otherwise.\n \n ' self.other_actors.append(first_vehicle)
def _initialize_actors(self, config): '\n \n ' (first_vehicle_waypoint, _) = get_waypoint_in_distance(self._reference_waypoint, self._first_vehicle_location) self._other_actor_transform = carla.Transform(carla.Location(first_vehicle_waypoint.transform.location.x, first_vehicle_waypoint.transform.location.y, (first_vehicle_waypoint.transform.location.z + 1)), first_vehicle_waypoint.transform.rotation) first_vehicle_transform = carla.Transform(carla.Location(self._other_actor_transform.location.x, self._other_actor_transform.location.y, (self._other_actor_transform.location.z - 500)), self._other_actor_transform.rotation) '\n so the transformation contains two parameters:\n 1. location\n 2. rotation\n \n can be retrieved by transform.location and transform.rotation\n \n ' first_vehicle = CarlaActorPool.request_new_actor('vehicle.nissan.patrol', first_vehicle_transform) '\n The CarlaActorPool caches all scenario relevant actors.\n It works similar to a singelton.\n\n An actor can be created via "request_actor", and access\n is possible via "get_actor_by_id".\n\n Using CarlaActorPool, actors can be shared between scenarios.\n \n \n Method:\n request_new_actor(model, spawn_point, rolename=\'scenario\', hero=False, autopilot=False, random_location=False):\n \n This method tries to create a new actor. If this was\n successful, the new actor is returned, None otherwise.\n \n ' self.other_actors.append(first_vehicle)<|docstring|>Custom initialization<|endoftext|>
9fa13d4761cfcf87cdcafdfcbb3211b043f85c106931ecfec1bd3e15e2a61c1a
def _create_behavior(self): '\n The scenario defined after is a "follow leading vehicle" scenario. After\n invoking this scenario, it will wait for the user controlled vehicle to\n enter the start region, then make the other actor to drive until reaching\n the next intersection. Finally, the user-controlled vehicle has to be close\n enough to the other actor to end the scenario.\n If this does not happen within 60 seconds, a timeout stops the scenario\n ' '\n This class contains an atomic behavior to set the transform\n of an actor.\n \n ActorTransfromSetter(actor, transform)\n ' start_transform = ActorTransformSetter(self.other_actors[0], self._other_actor_transform) driving_to_next_intersection = py_trees.composites.Parallel('DrivingTowardsIntersection', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE) driving_to_next_intersection.add_child(WaypointFollower(self.other_actors[0], self._first_vehicle_speed)) driving_to_next_intersection.add_child(KeepVelocity(self.other_actors[0], 10, name='KeepVelocity')) '\n This is an atomic behavior to follow waypoints indefinitely\n while maintaining a given speed or if given a waypoint plan,\n follows the given plan\n \n def __init__(self, actor, target_speed, plan=None, blackboard_queue_name=None,\n avoid_collision=False, name="FollowWaypoints"):\n ' '\n \n This class contains the trigger (condition) for a distance to the\n next intersection of a scenario\n \n \n def __init__(self, actor, distance, name="InTriggerDistanceToNextIntersection"):\n \n \n the distance between the current actors and the next intersection\n \n ' stop = StopVehicle(self.other_actors[0], self._other_actor_max_brake) endcondition = py_trees.composites.Parallel('Waiting for end position', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ALL) endcondition_part1 = InTriggerDistanceToVehicle(self.other_actors[0], self.ego_vehicles[0], distance=20, name='FinalDistance') '\n \n This class contains the trigger distance (condition) between to actors\n of a scenario\n\n def __init__(self, other_actor, actor, distance, name="TriggerDistanceToVehicle"):\n \n \n ' endcondition_part2 = StandStill(self.ego_vehicles[0], name='StandStill') '\n check if the vehicles stand still (v = 0)\n \n ' endcondition.add_child(endcondition_part1) endcondition.add_child(endcondition_part2) sequence = py_trees.composites.Sequence('Sequence Behavior') sequence.add_child(start_transform) sequence.add_child(driving_to_next_intersection) sequence.add_child(stop) sequence.add_child(endcondition) sequence.add_child(ActorDestroy(self.other_actors[0])) return sequence
The scenario defined after is a "follow leading vehicle" scenario. After invoking this scenario, it will wait for the user controlled vehicle to enter the start region, then make the other actor to drive until reaching the next intersection. Finally, the user-controlled vehicle has to be close enough to the other actor to end the scenario. If this does not happen within 60 seconds, a timeout stops the scenario
srunner/scenarios/follow_leading_vehicle.py
_create_behavior
goRichard/scenario_runner_fzi
0
python
def _create_behavior(self): '\n The scenario defined after is a "follow leading vehicle" scenario. After\n invoking this scenario, it will wait for the user controlled vehicle to\n enter the start region, then make the other actor to drive until reaching\n the next intersection. Finally, the user-controlled vehicle has to be close\n enough to the other actor to end the scenario.\n If this does not happen within 60 seconds, a timeout stops the scenario\n ' '\n This class contains an atomic behavior to set the transform\n of an actor.\n \n ActorTransfromSetter(actor, transform)\n ' start_transform = ActorTransformSetter(self.other_actors[0], self._other_actor_transform) driving_to_next_intersection = py_trees.composites.Parallel('DrivingTowardsIntersection', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE) driving_to_next_intersection.add_child(WaypointFollower(self.other_actors[0], self._first_vehicle_speed)) driving_to_next_intersection.add_child(KeepVelocity(self.other_actors[0], 10, name='KeepVelocity')) '\n This is an atomic behavior to follow waypoints indefinitely\n while maintaining a given speed or if given a waypoint plan,\n follows the given plan\n \n def __init__(self, actor, target_speed, plan=None, blackboard_queue_name=None,\n avoid_collision=False, name="FollowWaypoints"):\n ' '\n \n This class contains the trigger (condition) for a distance to the\n next intersection of a scenario\n \n \n def __init__(self, actor, distance, name="InTriggerDistanceToNextIntersection"):\n \n \n the distance between the current actors and the next intersection\n \n ' stop = StopVehicle(self.other_actors[0], self._other_actor_max_brake) endcondition = py_trees.composites.Parallel('Waiting for end position', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ALL) endcondition_part1 = InTriggerDistanceToVehicle(self.other_actors[0], self.ego_vehicles[0], distance=20, name='FinalDistance') '\n \n This class contains the trigger distance (condition) between to actors\n of a scenario\n\n def __init__(self, other_actor, actor, distance, name="TriggerDistanceToVehicle"):\n \n \n ' endcondition_part2 = StandStill(self.ego_vehicles[0], name='StandStill') '\n check if the vehicles stand still (v = 0)\n \n ' endcondition.add_child(endcondition_part1) endcondition.add_child(endcondition_part2) sequence = py_trees.composites.Sequence('Sequence Behavior') sequence.add_child(start_transform) sequence.add_child(driving_to_next_intersection) sequence.add_child(stop) sequence.add_child(endcondition) sequence.add_child(ActorDestroy(self.other_actors[0])) return sequence
def _create_behavior(self): '\n The scenario defined after is a "follow leading vehicle" scenario. After\n invoking this scenario, it will wait for the user controlled vehicle to\n enter the start region, then make the other actor to drive until reaching\n the next intersection. Finally, the user-controlled vehicle has to be close\n enough to the other actor to end the scenario.\n If this does not happen within 60 seconds, a timeout stops the scenario\n ' '\n This class contains an atomic behavior to set the transform\n of an actor.\n \n ActorTransfromSetter(actor, transform)\n ' start_transform = ActorTransformSetter(self.other_actors[0], self._other_actor_transform) driving_to_next_intersection = py_trees.composites.Parallel('DrivingTowardsIntersection', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE) driving_to_next_intersection.add_child(WaypointFollower(self.other_actors[0], self._first_vehicle_speed)) driving_to_next_intersection.add_child(KeepVelocity(self.other_actors[0], 10, name='KeepVelocity')) '\n This is an atomic behavior to follow waypoints indefinitely\n while maintaining a given speed or if given a waypoint plan,\n follows the given plan\n \n def __init__(self, actor, target_speed, plan=None, blackboard_queue_name=None,\n avoid_collision=False, name="FollowWaypoints"):\n ' '\n \n This class contains the trigger (condition) for a distance to the\n next intersection of a scenario\n \n \n def __init__(self, actor, distance, name="InTriggerDistanceToNextIntersection"):\n \n \n the distance between the current actors and the next intersection\n \n ' stop = StopVehicle(self.other_actors[0], self._other_actor_max_brake) endcondition = py_trees.composites.Parallel('Waiting for end position', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ALL) endcondition_part1 = InTriggerDistanceToVehicle(self.other_actors[0], self.ego_vehicles[0], distance=20, name='FinalDistance') '\n \n This class contains the trigger distance (condition) between to actors\n of a scenario\n\n def __init__(self, other_actor, actor, distance, name="TriggerDistanceToVehicle"):\n \n \n ' endcondition_part2 = StandStill(self.ego_vehicles[0], name='StandStill') '\n check if the vehicles stand still (v = 0)\n \n ' endcondition.add_child(endcondition_part1) endcondition.add_child(endcondition_part2) sequence = py_trees.composites.Sequence('Sequence Behavior') sequence.add_child(start_transform) sequence.add_child(driving_to_next_intersection) sequence.add_child(stop) sequence.add_child(endcondition) sequence.add_child(ActorDestroy(self.other_actors[0])) return sequence<|docstring|>The scenario defined after is a "follow leading vehicle" scenario. After invoking this scenario, it will wait for the user controlled vehicle to enter the start region, then make the other actor to drive until reaching the next intersection. Finally, the user-controlled vehicle has to be close enough to the other actor to end the scenario. If this does not happen within 60 seconds, a timeout stops the scenario<|endoftext|>
d82deee9067da8db0988ec68c114a06335e1732c916bfe603c980528fb08b2bc
def _create_test_criteria(self): '\n A list of all test criteria will be created that is later used\n in parallel behavior tree.\n ' criteria = [] collision_criterion = CollisionTest(self.ego_vehicles[0]) criteria.append(collision_criterion) return criteria
A list of all test criteria will be created that is later used in parallel behavior tree.
srunner/scenarios/follow_leading_vehicle.py
_create_test_criteria
goRichard/scenario_runner_fzi
0
python
def _create_test_criteria(self): '\n A list of all test criteria will be created that is later used\n in parallel behavior tree.\n ' criteria = [] collision_criterion = CollisionTest(self.ego_vehicles[0]) criteria.append(collision_criterion) return criteria
def _create_test_criteria(self): '\n A list of all test criteria will be created that is later used\n in parallel behavior tree.\n ' criteria = [] collision_criterion = CollisionTest(self.ego_vehicles[0]) criteria.append(collision_criterion) return criteria<|docstring|>A list of all test criteria will be created that is later used in parallel behavior tree.<|endoftext|>
cf15b0f862b93c0d598fc2054b8f613860b921f335a9d5a01a9c514ee92f6d77
def __del__(self): '\n Remove all actors upon deletion\n ' self.remove_all_actors()
Remove all actors upon deletion
srunner/scenarios/follow_leading_vehicle.py
__del__
goRichard/scenario_runner_fzi
0
python
def __del__(self): '\n \n ' self.remove_all_actors()
def __del__(self): '\n \n ' self.remove_all_actors()<|docstring|>Remove all actors upon deletion<|endoftext|>
61c7a0844ba285ed06e2fd3c8e69023e6fd6a386ec706c5fb8bcae6edfb05876
def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=False, criteria_enable=True): '\n Setup all relevant parameters and create scenario\n ' self._map = CarlaDataProvider.get_map() self._first_actor_location = 25 self._second_actor_location = (self._first_actor_location + 41) self._first_actor_speed = 40 self._second_actor_speed = 5 self._reference_waypoint = self._map.get_waypoint(config.trigger_points[0].location) self._other_actor_max_brake = 1.0 self._first_actor_transform = None self._second_actor_transform = None super(FollowLeadingVehicleWithObstacle, self).__init__('FollowLeadingVehicleWithObstacle', ego_vehicles, config, world, debug_mode, criteria_enable=criteria_enable) if randomize: self._ego_other_distance_start = random.randint(4, 8)
Setup all relevant parameters and create scenario
srunner/scenarios/follow_leading_vehicle.py
__init__
goRichard/scenario_runner_fzi
0
python
def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=False, criteria_enable=True): '\n \n ' self._map = CarlaDataProvider.get_map() self._first_actor_location = 25 self._second_actor_location = (self._first_actor_location + 41) self._first_actor_speed = 40 self._second_actor_speed = 5 self._reference_waypoint = self._map.get_waypoint(config.trigger_points[0].location) self._other_actor_max_brake = 1.0 self._first_actor_transform = None self._second_actor_transform = None super(FollowLeadingVehicleWithObstacle, self).__init__('FollowLeadingVehicleWithObstacle', ego_vehicles, config, world, debug_mode, criteria_enable=criteria_enable) if randomize: self._ego_other_distance_start = random.randint(4, 8)
def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=False, criteria_enable=True): '\n \n ' self._map = CarlaDataProvider.get_map() self._first_actor_location = 25 self._second_actor_location = (self._first_actor_location + 41) self._first_actor_speed = 40 self._second_actor_speed = 5 self._reference_waypoint = self._map.get_waypoint(config.trigger_points[0].location) self._other_actor_max_brake = 1.0 self._first_actor_transform = None self._second_actor_transform = None super(FollowLeadingVehicleWithObstacle, self).__init__('FollowLeadingVehicleWithObstacle', ego_vehicles, config, world, debug_mode, criteria_enable=criteria_enable) if randomize: self._ego_other_distance_start = random.randint(4, 8)<|docstring|>Setup all relevant parameters and create scenario<|endoftext|>
9b2725d7113fda856c5e66bce75cc18605fcb465507cfa399d68b27732948626
def _initialize_actors(self, config): '\n Custom initialization\n ' (first_actor_waypoint, _) = get_waypoint_in_distance(self._reference_waypoint, self._first_actor_location) (second_actor_waypoint, _) = get_waypoint_in_distance(self._reference_waypoint, self._second_actor_location) first_actor_transform = carla.Transform(carla.Location(first_actor_waypoint.transform.location.x, first_actor_waypoint.transform.location.y, (first_actor_waypoint.transform.location.z - 500)), first_actor_waypoint.transform.rotation) self._first_actor_transform = carla.Transform(carla.Location(first_actor_waypoint.transform.location.x, first_actor_waypoint.transform.location.y, (first_actor_waypoint.transform.location.z + 1)), first_actor_waypoint.transform.rotation) yaw_1 = (second_actor_waypoint.transform.rotation.yaw + 90) second_actor_transform = carla.Transform(carla.Location(second_actor_waypoint.transform.location.x, second_actor_waypoint.transform.location.y, (second_actor_waypoint.transform.location.z - 500)), carla.Rotation(second_actor_waypoint.transform.rotation.pitch, yaw_1, second_actor_waypoint.transform.rotation.roll)) self._second_actor_transform = carla.Transform(carla.Location(second_actor_waypoint.transform.location.x, second_actor_waypoint.transform.location.y, (second_actor_waypoint.transform.location.z + 1)), carla.Rotation(second_actor_waypoint.transform.rotation.pitch, yaw_1, second_actor_waypoint.transform.rotation.roll)) first_actor = CarlaActorPool.request_new_actor('vehicle.nissan.patrol', first_actor_transform) second_actor = CarlaActorPool.request_new_actor('vehicle.diamondback.century', second_actor_transform) self.other_actors.append(first_actor) self.other_actors.append(second_actor)
Custom initialization
srunner/scenarios/follow_leading_vehicle.py
_initialize_actors
goRichard/scenario_runner_fzi
0
python
def _initialize_actors(self, config): '\n \n ' (first_actor_waypoint, _) = get_waypoint_in_distance(self._reference_waypoint, self._first_actor_location) (second_actor_waypoint, _) = get_waypoint_in_distance(self._reference_waypoint, self._second_actor_location) first_actor_transform = carla.Transform(carla.Location(first_actor_waypoint.transform.location.x, first_actor_waypoint.transform.location.y, (first_actor_waypoint.transform.location.z - 500)), first_actor_waypoint.transform.rotation) self._first_actor_transform = carla.Transform(carla.Location(first_actor_waypoint.transform.location.x, first_actor_waypoint.transform.location.y, (first_actor_waypoint.transform.location.z + 1)), first_actor_waypoint.transform.rotation) yaw_1 = (second_actor_waypoint.transform.rotation.yaw + 90) second_actor_transform = carla.Transform(carla.Location(second_actor_waypoint.transform.location.x, second_actor_waypoint.transform.location.y, (second_actor_waypoint.transform.location.z - 500)), carla.Rotation(second_actor_waypoint.transform.rotation.pitch, yaw_1, second_actor_waypoint.transform.rotation.roll)) self._second_actor_transform = carla.Transform(carla.Location(second_actor_waypoint.transform.location.x, second_actor_waypoint.transform.location.y, (second_actor_waypoint.transform.location.z + 1)), carla.Rotation(second_actor_waypoint.transform.rotation.pitch, yaw_1, second_actor_waypoint.transform.rotation.roll)) first_actor = CarlaActorPool.request_new_actor('vehicle.nissan.patrol', first_actor_transform) second_actor = CarlaActorPool.request_new_actor('vehicle.diamondback.century', second_actor_transform) self.other_actors.append(first_actor) self.other_actors.append(second_actor)
def _initialize_actors(self, config): '\n \n ' (first_actor_waypoint, _) = get_waypoint_in_distance(self._reference_waypoint, self._first_actor_location) (second_actor_waypoint, _) = get_waypoint_in_distance(self._reference_waypoint, self._second_actor_location) first_actor_transform = carla.Transform(carla.Location(first_actor_waypoint.transform.location.x, first_actor_waypoint.transform.location.y, (first_actor_waypoint.transform.location.z - 500)), first_actor_waypoint.transform.rotation) self._first_actor_transform = carla.Transform(carla.Location(first_actor_waypoint.transform.location.x, first_actor_waypoint.transform.location.y, (first_actor_waypoint.transform.location.z + 1)), first_actor_waypoint.transform.rotation) yaw_1 = (second_actor_waypoint.transform.rotation.yaw + 90) second_actor_transform = carla.Transform(carla.Location(second_actor_waypoint.transform.location.x, second_actor_waypoint.transform.location.y, (second_actor_waypoint.transform.location.z - 500)), carla.Rotation(second_actor_waypoint.transform.rotation.pitch, yaw_1, second_actor_waypoint.transform.rotation.roll)) self._second_actor_transform = carla.Transform(carla.Location(second_actor_waypoint.transform.location.x, second_actor_waypoint.transform.location.y, (second_actor_waypoint.transform.location.z + 1)), carla.Rotation(second_actor_waypoint.transform.rotation.pitch, yaw_1, second_actor_waypoint.transform.rotation.roll)) first_actor = CarlaActorPool.request_new_actor('vehicle.nissan.patrol', first_actor_transform) second_actor = CarlaActorPool.request_new_actor('vehicle.diamondback.century', second_actor_transform) self.other_actors.append(first_actor) self.other_actors.append(second_actor)<|docstring|>Custom initialization<|endoftext|>
0790c95d2e7a5c011a202b9003f5daa21c877545636ae0e4ee2ee088ca19ae75
def _create_behavior(self): '\n The scenario defined after is a "follow leading vehicle" scenario. After\n invoking this scenario, it will wait for the user controlled vehicle to\n enter the start region, then make the other actor to drive towards obstacle.\n Once obstacle clears the road, make the other actor to drive towards the\n next intersection. Finally, the user-controlled vehicle has to be close\n enough to the other actor to end the scenario.\n If this does not happen within 60 seconds, a timeout stops the scenario\n ' driving_to_next_intersection = py_trees.composites.Parallel('Driving towards Intersection', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE) obstacle_clear_road = py_trees.composites.Parallel('Obstalce clearing road', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE) obstacle_clear_road.add_child(DriveDistance(self.other_actors[1], 4)) obstacle_clear_road.add_child(KeepVelocity(self.other_actors[1], self._second_actor_speed)) stop_near_intersection = py_trees.composites.Parallel('Waiting for end position near Intersection', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE) stop_near_intersection.add_child(WaypointFollower(self.other_actors[0], 35)) stop_near_intersection.add_child(InTriggerDistanceToNextIntersection(self.other_actors[0], 20)) driving_to_next_intersection.add_child(WaypointFollower(self.other_actors[0], self._first_actor_speed)) driving_to_next_intersection.add_child(InTriggerDistanceToVehicle(self.other_actors[1], self.other_actors[0], 15)) endcondition = py_trees.composites.Parallel('Waiting for end position', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ALL) endcondition_part1 = InTriggerDistanceToVehicle(self.other_actors[0], self.ego_vehicles[0], distance=20, name='FinalDistance') endcondition_part2 = StandStill(self.ego_vehicles[0], name='FinalSpeed') endcondition.add_child(endcondition_part1) endcondition.add_child(endcondition_part2) sequence = py_trees.composites.Sequence('Sequence Behavior') sequence.add_child(ActorTransformSetter(self.other_actors[0], self._first_actor_transform)) sequence.add_child(ActorTransformSetter(self.other_actors[1], self._second_actor_transform)) sequence.add_child(driving_to_next_intersection) sequence.add_child(StopVehicle(self.other_actors[0], self._other_actor_max_brake)) sequence.add_child(TimeOut(3)) sequence.add_child(obstacle_clear_road) sequence.add_child(stop_near_intersection) sequence.add_child(StopVehicle(self.other_actors[0], self._other_actor_max_brake)) sequence.add_child(endcondition) sequence.add_child(ActorDestroy(self.other_actors[0])) sequence.add_child(ActorDestroy(self.other_actors[1])) return sequence
The scenario defined after is a "follow leading vehicle" scenario. After invoking this scenario, it will wait for the user controlled vehicle to enter the start region, then make the other actor to drive towards obstacle. Once obstacle clears the road, make the other actor to drive towards the next intersection. Finally, the user-controlled vehicle has to be close enough to the other actor to end the scenario. If this does not happen within 60 seconds, a timeout stops the scenario
srunner/scenarios/follow_leading_vehicle.py
_create_behavior
goRichard/scenario_runner_fzi
0
python
def _create_behavior(self): '\n The scenario defined after is a "follow leading vehicle" scenario. After\n invoking this scenario, it will wait for the user controlled vehicle to\n enter the start region, then make the other actor to drive towards obstacle.\n Once obstacle clears the road, make the other actor to drive towards the\n next intersection. Finally, the user-controlled vehicle has to be close\n enough to the other actor to end the scenario.\n If this does not happen within 60 seconds, a timeout stops the scenario\n ' driving_to_next_intersection = py_trees.composites.Parallel('Driving towards Intersection', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE) obstacle_clear_road = py_trees.composites.Parallel('Obstalce clearing road', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE) obstacle_clear_road.add_child(DriveDistance(self.other_actors[1], 4)) obstacle_clear_road.add_child(KeepVelocity(self.other_actors[1], self._second_actor_speed)) stop_near_intersection = py_trees.composites.Parallel('Waiting for end position near Intersection', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE) stop_near_intersection.add_child(WaypointFollower(self.other_actors[0], 35)) stop_near_intersection.add_child(InTriggerDistanceToNextIntersection(self.other_actors[0], 20)) driving_to_next_intersection.add_child(WaypointFollower(self.other_actors[0], self._first_actor_speed)) driving_to_next_intersection.add_child(InTriggerDistanceToVehicle(self.other_actors[1], self.other_actors[0], 15)) endcondition = py_trees.composites.Parallel('Waiting for end position', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ALL) endcondition_part1 = InTriggerDistanceToVehicle(self.other_actors[0], self.ego_vehicles[0], distance=20, name='FinalDistance') endcondition_part2 = StandStill(self.ego_vehicles[0], name='FinalSpeed') endcondition.add_child(endcondition_part1) endcondition.add_child(endcondition_part2) sequence = py_trees.composites.Sequence('Sequence Behavior') sequence.add_child(ActorTransformSetter(self.other_actors[0], self._first_actor_transform)) sequence.add_child(ActorTransformSetter(self.other_actors[1], self._second_actor_transform)) sequence.add_child(driving_to_next_intersection) sequence.add_child(StopVehicle(self.other_actors[0], self._other_actor_max_brake)) sequence.add_child(TimeOut(3)) sequence.add_child(obstacle_clear_road) sequence.add_child(stop_near_intersection) sequence.add_child(StopVehicle(self.other_actors[0], self._other_actor_max_brake)) sequence.add_child(endcondition) sequence.add_child(ActorDestroy(self.other_actors[0])) sequence.add_child(ActorDestroy(self.other_actors[1])) return sequence
def _create_behavior(self): '\n The scenario defined after is a "follow leading vehicle" scenario. After\n invoking this scenario, it will wait for the user controlled vehicle to\n enter the start region, then make the other actor to drive towards obstacle.\n Once obstacle clears the road, make the other actor to drive towards the\n next intersection. Finally, the user-controlled vehicle has to be close\n enough to the other actor to end the scenario.\n If this does not happen within 60 seconds, a timeout stops the scenario\n ' driving_to_next_intersection = py_trees.composites.Parallel('Driving towards Intersection', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE) obstacle_clear_road = py_trees.composites.Parallel('Obstalce clearing road', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE) obstacle_clear_road.add_child(DriveDistance(self.other_actors[1], 4)) obstacle_clear_road.add_child(KeepVelocity(self.other_actors[1], self._second_actor_speed)) stop_near_intersection = py_trees.composites.Parallel('Waiting for end position near Intersection', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ONE) stop_near_intersection.add_child(WaypointFollower(self.other_actors[0], 35)) stop_near_intersection.add_child(InTriggerDistanceToNextIntersection(self.other_actors[0], 20)) driving_to_next_intersection.add_child(WaypointFollower(self.other_actors[0], self._first_actor_speed)) driving_to_next_intersection.add_child(InTriggerDistanceToVehicle(self.other_actors[1], self.other_actors[0], 15)) endcondition = py_trees.composites.Parallel('Waiting for end position', policy=py_trees.common.ParallelPolicy.SUCCESS_ON_ALL) endcondition_part1 = InTriggerDistanceToVehicle(self.other_actors[0], self.ego_vehicles[0], distance=20, name='FinalDistance') endcondition_part2 = StandStill(self.ego_vehicles[0], name='FinalSpeed') endcondition.add_child(endcondition_part1) endcondition.add_child(endcondition_part2) sequence = py_trees.composites.Sequence('Sequence Behavior') sequence.add_child(ActorTransformSetter(self.other_actors[0], self._first_actor_transform)) sequence.add_child(ActorTransformSetter(self.other_actors[1], self._second_actor_transform)) sequence.add_child(driving_to_next_intersection) sequence.add_child(StopVehicle(self.other_actors[0], self._other_actor_max_brake)) sequence.add_child(TimeOut(3)) sequence.add_child(obstacle_clear_road) sequence.add_child(stop_near_intersection) sequence.add_child(StopVehicle(self.other_actors[0], self._other_actor_max_brake)) sequence.add_child(endcondition) sequence.add_child(ActorDestroy(self.other_actors[0])) sequence.add_child(ActorDestroy(self.other_actors[1])) return sequence<|docstring|>The scenario defined after is a "follow leading vehicle" scenario. After invoking this scenario, it will wait for the user controlled vehicle to enter the start region, then make the other actor to drive towards obstacle. Once obstacle clears the road, make the other actor to drive towards the next intersection. Finally, the user-controlled vehicle has to be close enough to the other actor to end the scenario. If this does not happen within 60 seconds, a timeout stops the scenario<|endoftext|>
d82deee9067da8db0988ec68c114a06335e1732c916bfe603c980528fb08b2bc
def _create_test_criteria(self): '\n A list of all test criteria will be created that is later used\n in parallel behavior tree.\n ' criteria = [] collision_criterion = CollisionTest(self.ego_vehicles[0]) criteria.append(collision_criterion) return criteria
A list of all test criteria will be created that is later used in parallel behavior tree.
srunner/scenarios/follow_leading_vehicle.py
_create_test_criteria
goRichard/scenario_runner_fzi
0
python
def _create_test_criteria(self): '\n A list of all test criteria will be created that is later used\n in parallel behavior tree.\n ' criteria = [] collision_criterion = CollisionTest(self.ego_vehicles[0]) criteria.append(collision_criterion) return criteria
def _create_test_criteria(self): '\n A list of all test criteria will be created that is later used\n in parallel behavior tree.\n ' criteria = [] collision_criterion = CollisionTest(self.ego_vehicles[0]) criteria.append(collision_criterion) return criteria<|docstring|>A list of all test criteria will be created that is later used in parallel behavior tree.<|endoftext|>
cf15b0f862b93c0d598fc2054b8f613860b921f335a9d5a01a9c514ee92f6d77
def __del__(self): '\n Remove all actors upon deletion\n ' self.remove_all_actors()
Remove all actors upon deletion
srunner/scenarios/follow_leading_vehicle.py
__del__
goRichard/scenario_runner_fzi
0
python
def __del__(self): '\n \n ' self.remove_all_actors()
def __del__(self): '\n \n ' self.remove_all_actors()<|docstring|>Remove all actors upon deletion<|endoftext|>
358a871d290cb34dcb19b781570d5f91fadbc719f0e35ee4dece7033de26a426
def add_hpim_interface(interface_name, ipv4=True, ipv6=False): '\n Add a new interface to be controlled by HPIM-DM\n ' if (interface_name == '*'): for interface_name in netifaces.interfaces(): add_hpim_interface(interface_name, ipv4, ipv6) return if (ipv4 and (kernel is not None)): kernel.create_hpim_interface(interface_name=interface_name) if (ipv6 and (kernel_v6 is not None)): kernel_v6.create_hpim_interface(interface_name=interface_name)
Add a new interface to be controlled by HPIM-DM
hpimdm/Main.py
add_hpim_interface
pedrofran12/hpim_dm
1
python
def add_hpim_interface(interface_name, ipv4=True, ipv6=False): '\n \n ' if (interface_name == '*'): for interface_name in netifaces.interfaces(): add_hpim_interface(interface_name, ipv4, ipv6) return if (ipv4 and (kernel is not None)): kernel.create_hpim_interface(interface_name=interface_name) if (ipv6 and (kernel_v6 is not None)): kernel_v6.create_hpim_interface(interface_name=interface_name)
def add_hpim_interface(interface_name, ipv4=True, ipv6=False): '\n \n ' if (interface_name == '*'): for interface_name in netifaces.interfaces(): add_hpim_interface(interface_name, ipv4, ipv6) return if (ipv4 and (kernel is not None)): kernel.create_hpim_interface(interface_name=interface_name) if (ipv6 and (kernel_v6 is not None)): kernel_v6.create_hpim_interface(interface_name=interface_name)<|docstring|>Add a new interface to be controlled by HPIM-DM<|endoftext|>
97a859ecd6ef563db893c193cca868f11fad52cfdbc4f49e807b4d3c416ae296
def add_membership_interface(interface_name, ipv4=True, ipv6=False): '\n Add a new interface to be controlled by IGMP/MLD\n ' if (interface_name == '*'): for interface_name in netifaces.interfaces(): add_membership_interface(interface_name, ipv4, ipv6) return if (ipv4 and (kernel is not None)): kernel.create_membership_interface(interface_name=interface_name) if (ipv6 and (kernel_v6 is not None)): kernel_v6.create_membership_interface(interface_name=interface_name)
Add a new interface to be controlled by IGMP/MLD
hpimdm/Main.py
add_membership_interface
pedrofran12/hpim_dm
1
python
def add_membership_interface(interface_name, ipv4=True, ipv6=False): '\n \n ' if (interface_name == '*'): for interface_name in netifaces.interfaces(): add_membership_interface(interface_name, ipv4, ipv6) return if (ipv4 and (kernel is not None)): kernel.create_membership_interface(interface_name=interface_name) if (ipv6 and (kernel_v6 is not None)): kernel_v6.create_membership_interface(interface_name=interface_name)
def add_membership_interface(interface_name, ipv4=True, ipv6=False): '\n \n ' if (interface_name == '*'): for interface_name in netifaces.interfaces(): add_membership_interface(interface_name, ipv4, ipv6) return if (ipv4 and (kernel is not None)): kernel.create_membership_interface(interface_name=interface_name) if (ipv6 and (kernel_v6 is not None)): kernel_v6.create_membership_interface(interface_name=interface_name)<|docstring|>Add a new interface to be controlled by IGMP/MLD<|endoftext|>
2712c3ac93cce2692e7f28bf1ba39b3e8930ebdbadb0ed5470207acd02977336
def remove_interface(interface_name, hpim=False, membership=False, ipv4=True, ipv6=False): '\n Remove HPIM-DM/IGMP interface\n ' if (interface_name == '*'): for interface_name in netifaces.interfaces(): remove_interface(interface_name, hpim, membership, ipv4, ipv6) return if (ipv4 and (kernel is not None)): kernel.remove_interface(interface_name, hpim=hpim, membership=membership) if (ipv6 and (kernel_v6 is not None)): kernel_v6.remove_interface(interface_name, hpim=hpim, membership=membership)
Remove HPIM-DM/IGMP interface
hpimdm/Main.py
remove_interface
pedrofran12/hpim_dm
1
python
def remove_interface(interface_name, hpim=False, membership=False, ipv4=True, ipv6=False): '\n \n ' if (interface_name == '*'): for interface_name in netifaces.interfaces(): remove_interface(interface_name, hpim, membership, ipv4, ipv6) return if (ipv4 and (kernel is not None)): kernel.remove_interface(interface_name, hpim=hpim, membership=membership) if (ipv6 and (kernel_v6 is not None)): kernel_v6.remove_interface(interface_name, hpim=hpim, membership=membership)
def remove_interface(interface_name, hpim=False, membership=False, ipv4=True, ipv6=False): '\n \n ' if (interface_name == '*'): for interface_name in netifaces.interfaces(): remove_interface(interface_name, hpim, membership, ipv4, ipv6) return if (ipv4 and (kernel is not None)): kernel.remove_interface(interface_name, hpim=hpim, membership=membership) if (ipv6 and (kernel_v6 is not None)): kernel_v6.remove_interface(interface_name, hpim=hpim, membership=membership)<|docstring|>Remove HPIM-DM/IGMP interface<|endoftext|>
0c44a15e1aa71661d5d1ad370a8c12d65eaa65180ec608ffe6119a93c4941c27
def list_neighbors(ipv4=False, ipv6=False): '\n List all neighbors in a human readable format\n ' if ipv4: interfaces_list = interfaces.values() elif ipv6: interfaces_list = interfaces_v6.values() else: return 'Unknown IP family' t = PrettyTable(['Interface', 'Neighbor IP', 'State', 'Hello Hold Time', 'BootTime', 'NeighborSnapshotSN', 'Uptime']) check_time = time.time() for interface in interfaces_list: for neighbor in interface.get_neighbors(): uptime = (check_time - neighbor.time_of_last_update) uptime = (0 if (uptime < 0) else uptime) t.add_row([interface.interface_name, neighbor.ip, neighbor.neighbor_state.__name__, neighbor.hello_hold_time, neighbor.time_of_boot, neighbor.neighbor_snapshot_sn, time.strftime('%H:%M:%S', time.gmtime(uptime))]) print(t) return str(t)
List all neighbors in a human readable format
hpimdm/Main.py
list_neighbors
pedrofran12/hpim_dm
1
python
def list_neighbors(ipv4=False, ipv6=False): '\n \n ' if ipv4: interfaces_list = interfaces.values() elif ipv6: interfaces_list = interfaces_v6.values() else: return 'Unknown IP family' t = PrettyTable(['Interface', 'Neighbor IP', 'State', 'Hello Hold Time', 'BootTime', 'NeighborSnapshotSN', 'Uptime']) check_time = time.time() for interface in interfaces_list: for neighbor in interface.get_neighbors(): uptime = (check_time - neighbor.time_of_last_update) uptime = (0 if (uptime < 0) else uptime) t.add_row([interface.interface_name, neighbor.ip, neighbor.neighbor_state.__name__, neighbor.hello_hold_time, neighbor.time_of_boot, neighbor.neighbor_snapshot_sn, time.strftime('%H:%M:%S', time.gmtime(uptime))]) print(t) return str(t)
def list_neighbors(ipv4=False, ipv6=False): '\n \n ' if ipv4: interfaces_list = interfaces.values() elif ipv6: interfaces_list = interfaces_v6.values() else: return 'Unknown IP family' t = PrettyTable(['Interface', 'Neighbor IP', 'State', 'Hello Hold Time', 'BootTime', 'NeighborSnapshotSN', 'Uptime']) check_time = time.time() for interface in interfaces_list: for neighbor in interface.get_neighbors(): uptime = (check_time - neighbor.time_of_last_update) uptime = (0 if (uptime < 0) else uptime) t.add_row([interface.interface_name, neighbor.ip, neighbor.neighbor_state.__name__, neighbor.hello_hold_time, neighbor.time_of_boot, neighbor.neighbor_snapshot_sn, time.strftime('%H:%M:%S', time.gmtime(uptime))]) print(t) return str(t)<|docstring|>List all neighbors in a human readable format<|endoftext|>
251da9ec8ff438423076257ddbd620243ed1b91ac5cb3cff9bc4c02368c95fbc
def list_enabled_interfaces(ipv4=False, ipv6=False): '\n List all interfaces of the machine (enabled and not enabled for HPIM-DM and IGMP)\n ' if ipv4: t = PrettyTable(['Interface', 'IP', 'HPIM/IGMP Enabled', 'HPIM security', 'IGMP State']) family = netifaces.AF_INET hpim_interfaces = interfaces membership_interfaces = igmp_interfaces elif ipv6: t = PrettyTable(['Interface', 'IP', 'HPIM/MLD Enabled', 'HPIM security', 'MLD State']) family = netifaces.AF_INET6 hpim_interfaces = interfaces_v6 membership_interfaces = mld_interfaces else: return 'Unknown IP family' for interface in netifaces.interfaces(): try: ip = netifaces.ifaddresses(interface)[family][0]['addr'] hpim_enabled = (interface in hpim_interfaces) membership_enabled = (interface in membership_interfaces) enabled = ((str(hpim_enabled) + '/') + str(membership_enabled)) hpim_protection = '-' if (hpim_enabled and hpim_interfaces[interface].is_security_enabled()): hpim_protection = ((str(hpim_interfaces[interface].security_id) + ': ') + hpim_interfaces[interface].hash_function.__name__) membership_state = '-' if membership_enabled: membership_state = membership_interfaces[interface].interface_state.print_state() t.add_row([interface, ip, enabled, hpim_protection, membership_state]) except Exception: continue print(t) return str(t)
List all interfaces of the machine (enabled and not enabled for HPIM-DM and IGMP)
hpimdm/Main.py
list_enabled_interfaces
pedrofran12/hpim_dm
1
python
def list_enabled_interfaces(ipv4=False, ipv6=False): '\n \n ' if ipv4: t = PrettyTable(['Interface', 'IP', 'HPIM/IGMP Enabled', 'HPIM security', 'IGMP State']) family = netifaces.AF_INET hpim_interfaces = interfaces membership_interfaces = igmp_interfaces elif ipv6: t = PrettyTable(['Interface', 'IP', 'HPIM/MLD Enabled', 'HPIM security', 'MLD State']) family = netifaces.AF_INET6 hpim_interfaces = interfaces_v6 membership_interfaces = mld_interfaces else: return 'Unknown IP family' for interface in netifaces.interfaces(): try: ip = netifaces.ifaddresses(interface)[family][0]['addr'] hpim_enabled = (interface in hpim_interfaces) membership_enabled = (interface in membership_interfaces) enabled = ((str(hpim_enabled) + '/') + str(membership_enabled)) hpim_protection = '-' if (hpim_enabled and hpim_interfaces[interface].is_security_enabled()): hpim_protection = ((str(hpim_interfaces[interface].security_id) + ': ') + hpim_interfaces[interface].hash_function.__name__) membership_state = '-' if membership_enabled: membership_state = membership_interfaces[interface].interface_state.print_state() t.add_row([interface, ip, enabled, hpim_protection, membership_state]) except Exception: continue print(t) return str(t)
def list_enabled_interfaces(ipv4=False, ipv6=False): '\n \n ' if ipv4: t = PrettyTable(['Interface', 'IP', 'HPIM/IGMP Enabled', 'HPIM security', 'IGMP State']) family = netifaces.AF_INET hpim_interfaces = interfaces membership_interfaces = igmp_interfaces elif ipv6: t = PrettyTable(['Interface', 'IP', 'HPIM/MLD Enabled', 'HPIM security', 'MLD State']) family = netifaces.AF_INET6 hpim_interfaces = interfaces_v6 membership_interfaces = mld_interfaces else: return 'Unknown IP family' for interface in netifaces.interfaces(): try: ip = netifaces.ifaddresses(interface)[family][0]['addr'] hpim_enabled = (interface in hpim_interfaces) membership_enabled = (interface in membership_interfaces) enabled = ((str(hpim_enabled) + '/') + str(membership_enabled)) hpim_protection = '-' if (hpim_enabled and hpim_interfaces[interface].is_security_enabled()): hpim_protection = ((str(hpim_interfaces[interface].security_id) + ': ') + hpim_interfaces[interface].hash_function.__name__) membership_state = '-' if membership_enabled: membership_state = membership_interfaces[interface].interface_state.print_state() t.add_row([interface, ip, enabled, hpim_protection, membership_state]) except Exception: continue print(t) return str(t)<|docstring|>List all interfaces of the machine (enabled and not enabled for HPIM-DM and IGMP)<|endoftext|>
6a2e631723e75984d8c82681cf0aab91844d99bcfb3998102014c7d5b11a877b
def list_state(ipv4=True, ipv6=False): '\n List IGMP and HPIM-DM state\n For IGMP/MLD list the state of each group, regarding each interface\n For HPIM-DM list all trees and state of each interface\n ' state_text = '' if ipv4: state_text = 'IGMP State:\n{}\n\n\n\nMulticast Routing State:\n{}' elif ipv6: state_text = 'MLD State:\n{}\n\n\n\nMulticast Routing State:\n{}' else: return state_text return state_text.format(list_membership_state(ipv4, ipv6), list_routing_state(ipv4, ipv6))
List IGMP and HPIM-DM state For IGMP/MLD list the state of each group, regarding each interface For HPIM-DM list all trees and state of each interface
hpimdm/Main.py
list_state
pedrofran12/hpim_dm
1
python
def list_state(ipv4=True, ipv6=False): '\n List IGMP and HPIM-DM state\n For IGMP/MLD list the state of each group, regarding each interface\n For HPIM-DM list all trees and state of each interface\n ' state_text = if ipv4: state_text = 'IGMP State:\n{}\n\n\n\nMulticast Routing State:\n{}' elif ipv6: state_text = 'MLD State:\n{}\n\n\n\nMulticast Routing State:\n{}' else: return state_text return state_text.format(list_membership_state(ipv4, ipv6), list_routing_state(ipv4, ipv6))
def list_state(ipv4=True, ipv6=False): '\n List IGMP and HPIM-DM state\n For IGMP/MLD list the state of each group, regarding each interface\n For HPIM-DM list all trees and state of each interface\n ' state_text = if ipv4: state_text = 'IGMP State:\n{}\n\n\n\nMulticast Routing State:\n{}' elif ipv6: state_text = 'MLD State:\n{}\n\n\n\nMulticast Routing State:\n{}' else: return state_text return state_text.format(list_membership_state(ipv4, ipv6), list_routing_state(ipv4, ipv6))<|docstring|>List IGMP and HPIM-DM state For IGMP/MLD list the state of each group, regarding each interface For HPIM-DM list all trees and state of each interface<|endoftext|>
2be607f9f6ab5ca5f4062a5c62aa8283d3875bdf0b4a47c60e481175f8723e7b
def list_membership_state(ipv4=True, ipv6=False): '\n List IGMP/MLD state (state of each group regarding each interface)\n ' t = PrettyTable(['Interface', 'RouterState', 'Group Adress', 'GroupState']) if (ipv4 and (igmp_interfaces is not None)): membership_interfaces = igmp_interfaces elif (ipv6 and (mld_interfaces is not None)): membership_interfaces = mld_interfaces else: membership_interfaces = {} for (interface_name, interface_obj) in list(membership_interfaces.items()): interface_state = interface_obj.interface_state state_txt = interface_state.print_state() print(interface_state.group_state.items()) for (group_addr, group_state) in list(interface_state.group_state.items()): print(group_addr) group_state_txt = group_state.print_state() t.add_row([interface_name, state_txt, group_addr, group_state_txt]) return str(t)
List IGMP/MLD state (state of each group regarding each interface)
hpimdm/Main.py
list_membership_state
pedrofran12/hpim_dm
1
python
def list_membership_state(ipv4=True, ipv6=False): '\n \n ' t = PrettyTable(['Interface', 'RouterState', 'Group Adress', 'GroupState']) if (ipv4 and (igmp_interfaces is not None)): membership_interfaces = igmp_interfaces elif (ipv6 and (mld_interfaces is not None)): membership_interfaces = mld_interfaces else: membership_interfaces = {} for (interface_name, interface_obj) in list(membership_interfaces.items()): interface_state = interface_obj.interface_state state_txt = interface_state.print_state() print(interface_state.group_state.items()) for (group_addr, group_state) in list(interface_state.group_state.items()): print(group_addr) group_state_txt = group_state.print_state() t.add_row([interface_name, state_txt, group_addr, group_state_txt]) return str(t)
def list_membership_state(ipv4=True, ipv6=False): '\n \n ' t = PrettyTable(['Interface', 'RouterState', 'Group Adress', 'GroupState']) if (ipv4 and (igmp_interfaces is not None)): membership_interfaces = igmp_interfaces elif (ipv6 and (mld_interfaces is not None)): membership_interfaces = mld_interfaces else: membership_interfaces = {} for (interface_name, interface_obj) in list(membership_interfaces.items()): interface_state = interface_obj.interface_state state_txt = interface_state.print_state() print(interface_state.group_state.items()) for (group_addr, group_state) in list(interface_state.group_state.items()): print(group_addr) group_state_txt = group_state.print_state() t.add_row([interface_name, state_txt, group_addr, group_state_txt]) return str(t)<|docstring|>List IGMP/MLD state (state of each group regarding each interface)<|endoftext|>
ffa8a879f382af17d5705c8d8b589c3e368661c14be076607580f275d76e1e20
def list_routing_state(ipv4=False, ipv6=False): '\n List HPIM-DM state (all state machines of each tree, regarding each interface)\n ' if (ipv4 and (kernel is not None)): routes = kernel.routing.values() vif_indexes = kernel.vif_index_to_name_dic.keys() dict_index_to_name = kernel.vif_index_to_name_dic elif (ipv6 and (kernel_v6 is not None)): routes = kernel_v6.routing.values() vif_indexes = kernel_v6.vif_index_to_name_dic.keys() dict_index_to_name = kernel_v6.vif_index_to_name_dic else: routes = [] vif_indexes = [] dict_index_to_name = {} routing_entries = [] for a in list(routes): for b in list(a.values()): routing_entries.append(b) t = PrettyTable(['SourceIP', 'GroupIP', 'TreeState', 'Interface', 'InterestState', 'AssertState', 'LocalMembership', 'Is Forwarding?']) for entry in routing_entries: ip = entry.source_ip group = entry.group_ip upstream_if_index = entry.inbound_interface_index tree_state = str(entry._tree_state) for index in vif_indexes: interface_state = entry.interface_state[index] interface_name = dict_index_to_name[index] local_membership = str(interface_state._local_membership_state) try: if (index != upstream_if_index): assert_state = str(interface_state._assert_state) prune_state = str(interface_state._downstream_node_interest_state) is_forwarding = interface_state.is_forwarding() else: assert_state = '--' prune_state = '--' is_forwarding = 'root' except: prune_state = '-' assert_state = '-' is_forwarding = '-' t.add_row([ip, group, tree_state, interface_name, prune_state, assert_state, local_membership, is_forwarding]) return str(t)
List HPIM-DM state (all state machines of each tree, regarding each interface)
hpimdm/Main.py
list_routing_state
pedrofran12/hpim_dm
1
python
def list_routing_state(ipv4=False, ipv6=False): '\n \n ' if (ipv4 and (kernel is not None)): routes = kernel.routing.values() vif_indexes = kernel.vif_index_to_name_dic.keys() dict_index_to_name = kernel.vif_index_to_name_dic elif (ipv6 and (kernel_v6 is not None)): routes = kernel_v6.routing.values() vif_indexes = kernel_v6.vif_index_to_name_dic.keys() dict_index_to_name = kernel_v6.vif_index_to_name_dic else: routes = [] vif_indexes = [] dict_index_to_name = {} routing_entries = [] for a in list(routes): for b in list(a.values()): routing_entries.append(b) t = PrettyTable(['SourceIP', 'GroupIP', 'TreeState', 'Interface', 'InterestState', 'AssertState', 'LocalMembership', 'Is Forwarding?']) for entry in routing_entries: ip = entry.source_ip group = entry.group_ip upstream_if_index = entry.inbound_interface_index tree_state = str(entry._tree_state) for index in vif_indexes: interface_state = entry.interface_state[index] interface_name = dict_index_to_name[index] local_membership = str(interface_state._local_membership_state) try: if (index != upstream_if_index): assert_state = str(interface_state._assert_state) prune_state = str(interface_state._downstream_node_interest_state) is_forwarding = interface_state.is_forwarding() else: assert_state = '--' prune_state = '--' is_forwarding = 'root' except: prune_state = '-' assert_state = '-' is_forwarding = '-' t.add_row([ip, group, tree_state, interface_name, prune_state, assert_state, local_membership, is_forwarding]) return str(t)
def list_routing_state(ipv4=False, ipv6=False): '\n \n ' if (ipv4 and (kernel is not None)): routes = kernel.routing.values() vif_indexes = kernel.vif_index_to_name_dic.keys() dict_index_to_name = kernel.vif_index_to_name_dic elif (ipv6 and (kernel_v6 is not None)): routes = kernel_v6.routing.values() vif_indexes = kernel_v6.vif_index_to_name_dic.keys() dict_index_to_name = kernel_v6.vif_index_to_name_dic else: routes = [] vif_indexes = [] dict_index_to_name = {} routing_entries = [] for a in list(routes): for b in list(a.values()): routing_entries.append(b) t = PrettyTable(['SourceIP', 'GroupIP', 'TreeState', 'Interface', 'InterestState', 'AssertState', 'LocalMembership', 'Is Forwarding?']) for entry in routing_entries: ip = entry.source_ip group = entry.group_ip upstream_if_index = entry.inbound_interface_index tree_state = str(entry._tree_state) for index in vif_indexes: interface_state = entry.interface_state[index] interface_name = dict_index_to_name[index] local_membership = str(interface_state._local_membership_state) try: if (index != upstream_if_index): assert_state = str(interface_state._assert_state) prune_state = str(interface_state._downstream_node_interest_state) is_forwarding = interface_state.is_forwarding() else: assert_state = '--' prune_state = '--' is_forwarding = 'root' except: prune_state = '-' assert_state = '-' is_forwarding = '-' t.add_row([ip, group, tree_state, interface_name, prune_state, assert_state, local_membership, is_forwarding]) return str(t)<|docstring|>List HPIM-DM state (all state machines of each tree, regarding each interface)<|endoftext|>
672e65b2ccecc964c5195b4a25d2a3431a9fecd59cffbcc6aafcad662c4b82b9
def list_sequence_numbers(ipv4=False, ipv6=False): '\n List all stored sequence numbers\n ' if (ipv4 and (interfaces is not None)): hpim_interfaces = interfaces elif (ipv6 and (interfaces_v6 is not None)): hpim_interfaces = interfaces_v6 else: raise Exception('Unknown IP family') t = PrettyTable(['Interface', 'BootTime', 'InterfaceSN']) for (interface_name, interface_obj) in hpim_interfaces.copy().items(): interface_boot_time = interface_obj.time_of_boot interface_sn = interface_obj.sequencer t.add_row([interface_name, interface_boot_time, interface_sn]) table_txt = (str(t) + '\n\n\n') t = PrettyTable(['Neighbor', 'BootTime', 'NeighborSnapshotSN', 'NeighborCheckpointSN']) for interface in hpim_interfaces.values(): for neighbor in interface.get_neighbors(): t.add_row([neighbor.ip, neighbor.time_of_boot, neighbor.neighbor_snapshot_sn, neighbor.checkpoint_sn]) table_txt += (str(t) + '\n\n') t = PrettyTable(['Neighbor', 'Tree', 'LastSN']) for interface in hpim_interfaces.values(): for neighbor in interface.get_neighbors(): neighbor_last_sn = neighbor.last_sequence_number.copy() for (tree, last_sn) in neighbor_last_sn.items(): t.add_row([neighbor.ip, tree, last_sn]) table_txt += str(t) return str(table_txt)
List all stored sequence numbers
hpimdm/Main.py
list_sequence_numbers
pedrofran12/hpim_dm
1
python
def list_sequence_numbers(ipv4=False, ipv6=False): '\n \n ' if (ipv4 and (interfaces is not None)): hpim_interfaces = interfaces elif (ipv6 and (interfaces_v6 is not None)): hpim_interfaces = interfaces_v6 else: raise Exception('Unknown IP family') t = PrettyTable(['Interface', 'BootTime', 'InterfaceSN']) for (interface_name, interface_obj) in hpim_interfaces.copy().items(): interface_boot_time = interface_obj.time_of_boot interface_sn = interface_obj.sequencer t.add_row([interface_name, interface_boot_time, interface_sn]) table_txt = (str(t) + '\n\n\n') t = PrettyTable(['Neighbor', 'BootTime', 'NeighborSnapshotSN', 'NeighborCheckpointSN']) for interface in hpim_interfaces.values(): for neighbor in interface.get_neighbors(): t.add_row([neighbor.ip, neighbor.time_of_boot, neighbor.neighbor_snapshot_sn, neighbor.checkpoint_sn]) table_txt += (str(t) + '\n\n') t = PrettyTable(['Neighbor', 'Tree', 'LastSN']) for interface in hpim_interfaces.values(): for neighbor in interface.get_neighbors(): neighbor_last_sn = neighbor.last_sequence_number.copy() for (tree, last_sn) in neighbor_last_sn.items(): t.add_row([neighbor.ip, tree, last_sn]) table_txt += str(t) return str(table_txt)
def list_sequence_numbers(ipv4=False, ipv6=False): '\n \n ' if (ipv4 and (interfaces is not None)): hpim_interfaces = interfaces elif (ipv6 and (interfaces_v6 is not None)): hpim_interfaces = interfaces_v6 else: raise Exception('Unknown IP family') t = PrettyTable(['Interface', 'BootTime', 'InterfaceSN']) for (interface_name, interface_obj) in hpim_interfaces.copy().items(): interface_boot_time = interface_obj.time_of_boot interface_sn = interface_obj.sequencer t.add_row([interface_name, interface_boot_time, interface_sn]) table_txt = (str(t) + '\n\n\n') t = PrettyTable(['Neighbor', 'BootTime', 'NeighborSnapshotSN', 'NeighborCheckpointSN']) for interface in hpim_interfaces.values(): for neighbor in interface.get_neighbors(): t.add_row([neighbor.ip, neighbor.time_of_boot, neighbor.neighbor_snapshot_sn, neighbor.checkpoint_sn]) table_txt += (str(t) + '\n\n') t = PrettyTable(['Neighbor', 'Tree', 'LastSN']) for interface in hpim_interfaces.values(): for neighbor in interface.get_neighbors(): neighbor_last_sn = neighbor.last_sequence_number.copy() for (tree, last_sn) in neighbor_last_sn.items(): t.add_row([neighbor.ip, tree, last_sn]) table_txt += str(t) return str(table_txt)<|docstring|>List all stored sequence numbers<|endoftext|>
27f5bfebcd0f0d9c190407142d3c629849ea055a86e1ee5e96e030310cf9f015
def list_neighbors_state(ipv4=False, ipv6=False): '\n List all stored state regarding each tree of each neighbor (Upstream and Interest state)\n ' if (ipv4 and (interfaces is not None)): hpim_interfaces = list(interfaces.values()) elif (ipv6 and (interfaces_v6 is not None)): hpim_interfaces = list(interfaces_v6.values()) else: raise Exception('Unknown IP family') t = PrettyTable(['Interface', 'Neighbor', 'Tree', 'RPC Upstream State']) for interface in hpim_interfaces: for neighbor in interface.get_neighbors(): for (tree_id, tree_state) in neighbor.tree_metric_state.copy().items(): t.add_row([interface.interface_name, neighbor.ip, tree_id, tree_state]) table_txt = ('Upstream state:\n' + str(t)) t = PrettyTable(['Interface', 'Neighbor', 'Tree', 'Interest State']) for interface in hpim_interfaces: for neighbor in interface.get_neighbors(): for (tree_id, tree_state) in neighbor.tree_interest_state.copy().items(): t.add_row([interface.interface_name, neighbor.ip, tree_id, tree_state]) table_txt += ('\n\n\nInterest state:\n' + str(t)) return str(table_txt)
List all stored state regarding each tree of each neighbor (Upstream and Interest state)
hpimdm/Main.py
list_neighbors_state
pedrofran12/hpim_dm
1
python
def list_neighbors_state(ipv4=False, ipv6=False): '\n \n ' if (ipv4 and (interfaces is not None)): hpim_interfaces = list(interfaces.values()) elif (ipv6 and (interfaces_v6 is not None)): hpim_interfaces = list(interfaces_v6.values()) else: raise Exception('Unknown IP family') t = PrettyTable(['Interface', 'Neighbor', 'Tree', 'RPC Upstream State']) for interface in hpim_interfaces: for neighbor in interface.get_neighbors(): for (tree_id, tree_state) in neighbor.tree_metric_state.copy().items(): t.add_row([interface.interface_name, neighbor.ip, tree_id, tree_state]) table_txt = ('Upstream state:\n' + str(t)) t = PrettyTable(['Interface', 'Neighbor', 'Tree', 'Interest State']) for interface in hpim_interfaces: for neighbor in interface.get_neighbors(): for (tree_id, tree_state) in neighbor.tree_interest_state.copy().items(): t.add_row([interface.interface_name, neighbor.ip, tree_id, tree_state]) table_txt += ('\n\n\nInterest state:\n' + str(t)) return str(table_txt)
def list_neighbors_state(ipv4=False, ipv6=False): '\n \n ' if (ipv4 and (interfaces is not None)): hpim_interfaces = list(interfaces.values()) elif (ipv6 and (interfaces_v6 is not None)): hpim_interfaces = list(interfaces_v6.values()) else: raise Exception('Unknown IP family') t = PrettyTable(['Interface', 'Neighbor', 'Tree', 'RPC Upstream State']) for interface in hpim_interfaces: for neighbor in interface.get_neighbors(): for (tree_id, tree_state) in neighbor.tree_metric_state.copy().items(): t.add_row([interface.interface_name, neighbor.ip, tree_id, tree_state]) table_txt = ('Upstream state:\n' + str(t)) t = PrettyTable(['Interface', 'Neighbor', 'Tree', 'Interest State']) for interface in hpim_interfaces: for neighbor in interface.get_neighbors(): for (tree_id, tree_state) in neighbor.tree_interest_state.copy().items(): t.add_row([interface.interface_name, neighbor.ip, tree_id, tree_state]) table_txt += ('\n\n\nInterest state:\n' + str(t)) return str(table_txt)<|docstring|>List all stored state regarding each tree of each neighbor (Upstream and Interest state)<|endoftext|>
b31581c7ab340e5e8eabca6399c8eb6d8ca882a1f29aeb544b7f5c4ab2b72eb2
def list_hash_algorithms(): '\n List compatible algorithms to be used on HMAC protection\n ' t = PrettyTable(['HMAC Hash Algorithms']) for alg in hashlib.algorithms_guaranteed: t.add_row([alg]) return str(t)
List compatible algorithms to be used on HMAC protection
hpimdm/Main.py
list_hash_algorithms
pedrofran12/hpim_dm
1
python
def list_hash_algorithms(): '\n \n ' t = PrettyTable(['HMAC Hash Algorithms']) for alg in hashlib.algorithms_guaranteed: t.add_row([alg]) return str(t)
def list_hash_algorithms(): '\n \n ' t = PrettyTable(['HMAC Hash Algorithms']) for alg in hashlib.algorithms_guaranteed: t.add_row([alg]) return str(t)<|docstring|>List compatible algorithms to be used on HMAC protection<|endoftext|>
946a37cdf7db179d4bbe128b46fe88a0307f095aaa45cf0026f2bc160c725f63
def add_security_key(interface_name, security_identifier, hash_function, key, ipv4=False, ipv6=False): '\n Enable HMAC protection in interface_name with security_identifier, HMAC based on hash_function and\n HMAC protection key\n ' if (ipv4 and (kernel is not None)): kernel.add_interface_security(interface_name, security_identifier, hash_function, key) elif (ipv6 and (kernel_v6 is not None)): kernel_v6.add_interface_security(interface_name, security_identifier, hash_function, key)
Enable HMAC protection in interface_name with security_identifier, HMAC based on hash_function and HMAC protection key
hpimdm/Main.py
add_security_key
pedrofran12/hpim_dm
1
python
def add_security_key(interface_name, security_identifier, hash_function, key, ipv4=False, ipv6=False): '\n Enable HMAC protection in interface_name with security_identifier, HMAC based on hash_function and\n HMAC protection key\n ' if (ipv4 and (kernel is not None)): kernel.add_interface_security(interface_name, security_identifier, hash_function, key) elif (ipv6 and (kernel_v6 is not None)): kernel_v6.add_interface_security(interface_name, security_identifier, hash_function, key)
def add_security_key(interface_name, security_identifier, hash_function, key, ipv4=False, ipv6=False): '\n Enable HMAC protection in interface_name with security_identifier, HMAC based on hash_function and\n HMAC protection key\n ' if (ipv4 and (kernel is not None)): kernel.add_interface_security(interface_name, security_identifier, hash_function, key) elif (ipv6 and (kernel_v6 is not None)): kernel_v6.add_interface_security(interface_name, security_identifier, hash_function, key)<|docstring|>Enable HMAC protection in interface_name with security_identifier, HMAC based on hash_function and HMAC protection key<|endoftext|>
565a4a927d9847b3b26ac996c6d06a170c286c24ef4b4ef15255125bf68ddc54
def remove_security_key(interface_name, security_identifier, ipv4=False, ipv6=False): '\n Disable HMAC protection identified by security_identifier on interface interface_name\n ' if (ipv4 and (kernel is not None)): kernel.remove_interface_security(interface_name, security_identifier) elif (ipv6 and (kernel_v6 is not None)): kernel_v6.remove_interface_security(interface_name, security_identifier)
Disable HMAC protection identified by security_identifier on interface interface_name
hpimdm/Main.py
remove_security_key
pedrofran12/hpim_dm
1
python
def remove_security_key(interface_name, security_identifier, ipv4=False, ipv6=False): '\n \n ' if (ipv4 and (kernel is not None)): kernel.remove_interface_security(interface_name, security_identifier) elif (ipv6 and (kernel_v6 is not None)): kernel_v6.remove_interface_security(interface_name, security_identifier)
def remove_security_key(interface_name, security_identifier, ipv4=False, ipv6=False): '\n \n ' if (ipv4 and (kernel is not None)): kernel.remove_interface_security(interface_name, security_identifier) elif (ipv6 and (kernel_v6 is not None)): kernel_v6.remove_interface_security(interface_name, security_identifier)<|docstring|>Disable HMAC protection identified by security_identifier on interface interface_name<|endoftext|>
016512b79a665e5bc179e25b9aa9a7b7f22b56277100ef1571c4ec6acaf10551
def list_instances(): '\n List instance information\n ' t = '{}|{}|{}' return t.format(os.getpid(), hpim_globals.MULTICAST_TABLE_ID, hpim_globals.UNICAST_TABLE_ID)
List instance information
hpimdm/Main.py
list_instances
pedrofran12/hpim_dm
1
python
def list_instances(): '\n \n ' t = '{}|{}|{}' return t.format(os.getpid(), hpim_globals.MULTICAST_TABLE_ID, hpim_globals.UNICAST_TABLE_ID)
def list_instances(): '\n \n ' t = '{}|{}|{}' return t.format(os.getpid(), hpim_globals.MULTICAST_TABLE_ID, hpim_globals.UNICAST_TABLE_ID)<|docstring|>List instance information<|endoftext|>
5ae0f882cd247bcdc999e1e1f6e6375a18b9e0039232ed2d7aebc51223a07975
def change_initial_flood_setting(): '\n Change Initial Flood Setting, used to control the implicit interest of all neighbors\n (in order to flood or ignore initial packets)\n ' hpim_globals.INITIAL_FLOOD_ENABLED ^= True if (kernel is not None): kernel.recheck_all_trees_in_all_interfaces() if (kernel_v6 is not None): kernel_v6.recheck_all_trees_in_all_interfaces() return ('Flood is enabled?: ' + str(hpim_globals.INITIAL_FLOOD_ENABLED))
Change Initial Flood Setting, used to control the implicit interest of all neighbors (in order to flood or ignore initial packets)
hpimdm/Main.py
change_initial_flood_setting
pedrofran12/hpim_dm
1
python
def change_initial_flood_setting(): '\n Change Initial Flood Setting, used to control the implicit interest of all neighbors\n (in order to flood or ignore initial packets)\n ' hpim_globals.INITIAL_FLOOD_ENABLED ^= True if (kernel is not None): kernel.recheck_all_trees_in_all_interfaces() if (kernel_v6 is not None): kernel_v6.recheck_all_trees_in_all_interfaces() return ('Flood is enabled?: ' + str(hpim_globals.INITIAL_FLOOD_ENABLED))
def change_initial_flood_setting(): '\n Change Initial Flood Setting, used to control the implicit interest of all neighbors\n (in order to flood or ignore initial packets)\n ' hpim_globals.INITIAL_FLOOD_ENABLED ^= True if (kernel is not None): kernel.recheck_all_trees_in_all_interfaces() if (kernel_v6 is not None): kernel_v6.recheck_all_trees_in_all_interfaces() return ('Flood is enabled?: ' + str(hpim_globals.INITIAL_FLOOD_ENABLED))<|docstring|>Change Initial Flood Setting, used to control the implicit interest of all neighbors (in order to flood or ignore initial packets)<|endoftext|>
3fd9e8dfd58193b5d59f995c1d0a593b63b71598efa8f4fc8e3a805e054cdaf1
def hold_forwarding_state(): '\n Change Hold Forwarding State Setting, used to hold the forwarding state of an interface that was AW and that became\n AL\n ' hpim_globals.AL_HOLD_FORWARDING_STATE_ENABLED ^= True return ('Hold Forwarding State is enabled?: ' + str(hpim_globals.AL_HOLD_FORWARDING_STATE_ENABLED))
Change Hold Forwarding State Setting, used to hold the forwarding state of an interface that was AW and that became AL
hpimdm/Main.py
hold_forwarding_state
pedrofran12/hpim_dm
1
python
def hold_forwarding_state(): '\n Change Hold Forwarding State Setting, used to hold the forwarding state of an interface that was AW and that became\n AL\n ' hpim_globals.AL_HOLD_FORWARDING_STATE_ENABLED ^= True return ('Hold Forwarding State is enabled?: ' + str(hpim_globals.AL_HOLD_FORWARDING_STATE_ENABLED))
def hold_forwarding_state(): '\n Change Hold Forwarding State Setting, used to hold the forwarding state of an interface that was AW and that became\n AL\n ' hpim_globals.AL_HOLD_FORWARDING_STATE_ENABLED ^= True return ('Hold Forwarding State is enabled?: ' + str(hpim_globals.AL_HOLD_FORWARDING_STATE_ENABLED))<|docstring|>Change Hold Forwarding State Setting, used to hold the forwarding state of an interface that was AW and that became AL<|endoftext|>
ab41509e4009e50935d8cfc6d76e38aab7ac506d0d7d33278a14508627440636
def stop(): '\n Stop process\n ' remove_interface('*', hpim=True, membership=True, ipv4=True, ipv6=True) if (kernel is not None): kernel.exit() if (kernel_v6 is not None): kernel_v6.exit() unicast_routing.stop()
Stop process
hpimdm/Main.py
stop
pedrofran12/hpim_dm
1
python
def stop(): '\n \n ' remove_interface('*', hpim=True, membership=True, ipv4=True, ipv6=True) if (kernel is not None): kernel.exit() if (kernel_v6 is not None): kernel_v6.exit() unicast_routing.stop()
def stop(): '\n \n ' remove_interface('*', hpim=True, membership=True, ipv4=True, ipv6=True) if (kernel is not None): kernel.exit() if (kernel_v6 is not None): kernel_v6.exit() unicast_routing.stop()<|docstring|>Stop process<|endoftext|>
c091c54edf96fd44387a2de64cd63dae865eb2689a280d6e2ca7ecfb2d5b4b53
def test(router_name, server_logger_ip): '\n Test setting.... Used to send logs to a remote server\n ' global logger socketHandler = logging.handlers.SocketHandler(server_logger_ip, logging.handlers.DEFAULT_TCP_LOGGING_PORT) socketHandler.addFilter(RootFilter(router_name)) logger.addHandler(socketHandler)
Test setting.... Used to send logs to a remote server
hpimdm/Main.py
test
pedrofran12/hpim_dm
1
python
def test(router_name, server_logger_ip): '\n \n ' global logger socketHandler = logging.handlers.SocketHandler(server_logger_ip, logging.handlers.DEFAULT_TCP_LOGGING_PORT) socketHandler.addFilter(RootFilter(router_name)) logger.addHandler(socketHandler)
def test(router_name, server_logger_ip): '\n \n ' global logger socketHandler = logging.handlers.SocketHandler(server_logger_ip, logging.handlers.DEFAULT_TCP_LOGGING_PORT) socketHandler.addFilter(RootFilter(router_name)) logger.addHandler(socketHandler)<|docstring|>Test setting.... Used to send logs to a remote server<|endoftext|>
7a2dc4a424d13b7914878b70d08e7d47e62191e1f7f17f2dc4e410f7f589030b
def enable_ipv6_kernel(): '\n Function to explicitly enable IPv6 Multicast Routing stack.\n This may not be enabled by default due to some old linux kernels that may not have IPv6 stack or do not have\n IPv6 multicast routing support\n ' global kernel_v6 from hpimdm.Kernel import Kernel6 kernel_v6 = Kernel6() global interfaces_v6 global mld_interfaces interfaces_v6 = kernel_v6.hpim_interface mld_interfaces = kernel_v6.membership_interface
Function to explicitly enable IPv6 Multicast Routing stack. This may not be enabled by default due to some old linux kernels that may not have IPv6 stack or do not have IPv6 multicast routing support
hpimdm/Main.py
enable_ipv6_kernel
pedrofran12/hpim_dm
1
python
def enable_ipv6_kernel(): '\n Function to explicitly enable IPv6 Multicast Routing stack.\n This may not be enabled by default due to some old linux kernels that may not have IPv6 stack or do not have\n IPv6 multicast routing support\n ' global kernel_v6 from hpimdm.Kernel import Kernel6 kernel_v6 = Kernel6() global interfaces_v6 global mld_interfaces interfaces_v6 = kernel_v6.hpim_interface mld_interfaces = kernel_v6.membership_interface
def enable_ipv6_kernel(): '\n Function to explicitly enable IPv6 Multicast Routing stack.\n This may not be enabled by default due to some old linux kernels that may not have IPv6 stack or do not have\n IPv6 multicast routing support\n ' global kernel_v6 from hpimdm.Kernel import Kernel6 kernel_v6 = Kernel6() global interfaces_v6 global mld_interfaces interfaces_v6 = kernel_v6.hpim_interface mld_interfaces = kernel_v6.membership_interface<|docstring|>Function to explicitly enable IPv6 Multicast Routing stack. This may not be enabled by default due to some old linux kernels that may not have IPv6 stack or do not have IPv6 multicast routing support<|endoftext|>
09874a15a7c6a62a6f2cf9bea904d9e9d7fb6ee97a05c5d2411c4604684e39be
def get_config(): '\n Get live configuration of HPIM-DM process\n ' try: from . import Config return Config.get_yaml_file() except ImportError: return 'PYYAML needs to be installed. Execute "pip3 install pyyaml"'
Get live configuration of HPIM-DM process
hpimdm/Main.py
get_config
pedrofran12/hpim_dm
1
python
def get_config(): '\n \n ' try: from . import Config return Config.get_yaml_file() except ImportError: return 'PYYAML needs to be installed. Execute "pip3 install pyyaml"'
def get_config(): '\n \n ' try: from . import Config return Config.get_yaml_file() except ImportError: return 'PYYAML needs to be installed. Execute "pip3 install pyyaml"'<|docstring|>Get live configuration of HPIM-DM process<|endoftext|>
afab6b778a4f3017ecd813993a25b8b35e91008b7acf730458ed3156b6b485fa
def set_config(file_path): '\n Set configuration of HPIM-DM process\n ' from . import Config try: Config.parse_config_file(file_path) except: import traceback traceback.print_exc()
Set configuration of HPIM-DM process
hpimdm/Main.py
set_config
pedrofran12/hpim_dm
1
python
def set_config(file_path): '\n \n ' from . import Config try: Config.parse_config_file(file_path) except: import traceback traceback.print_exc()
def set_config(file_path): '\n \n ' from . import Config try: Config.parse_config_file(file_path) except: import traceback traceback.print_exc()<|docstring|>Set configuration of HPIM-DM process<|endoftext|>
02a0ef791fe1e371721f53f003a13e5410ccb7ce47b93a4946aa749166eec1b6
def main(): '\n Start process\n ' global logger logger = logging.getLogger('hpim') igmp_logger = logging.getLogger('igmp') mld_logger = logging.getLogger('mld') logger.setLevel(logging.DEBUG) igmp_logger.setLevel(logging.DEBUG) mld_logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.addFilter(RootFilter('')) handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter('%(asctime)-20s %(name)-50s %(tree)-35s %(vif)-2s %(interfacename)-5s %(routername)-2s %(message)s')) logger.addHandler(handler) igmp_logger.addHandler(handler) mld_logger.addHandler(handler) global kernel from hpimdm.Kernel import Kernel4 kernel = Kernel4() global unicast_routing unicast_routing = UnicastRouting.UnicastRouting() global interfaces global igmp_interfaces interfaces = kernel.hpim_interface igmp_interfaces = kernel.membership_interface try: enable_ipv6_kernel() except: pass
Start process
hpimdm/Main.py
main
pedrofran12/hpim_dm
1
python
def main(): '\n \n ' global logger logger = logging.getLogger('hpim') igmp_logger = logging.getLogger('igmp') mld_logger = logging.getLogger('mld') logger.setLevel(logging.DEBUG) igmp_logger.setLevel(logging.DEBUG) mld_logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.addFilter(RootFilter()) handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter('%(asctime)-20s %(name)-50s %(tree)-35s %(vif)-2s %(interfacename)-5s %(routername)-2s %(message)s')) logger.addHandler(handler) igmp_logger.addHandler(handler) mld_logger.addHandler(handler) global kernel from hpimdm.Kernel import Kernel4 kernel = Kernel4() global unicast_routing unicast_routing = UnicastRouting.UnicastRouting() global interfaces global igmp_interfaces interfaces = kernel.hpim_interface igmp_interfaces = kernel.membership_interface try: enable_ipv6_kernel() except: pass
def main(): '\n \n ' global logger logger = logging.getLogger('hpim') igmp_logger = logging.getLogger('igmp') mld_logger = logging.getLogger('mld') logger.setLevel(logging.DEBUG) igmp_logger.setLevel(logging.DEBUG) mld_logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.addFilter(RootFilter()) handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter('%(asctime)-20s %(name)-50s %(tree)-35s %(vif)-2s %(interfacename)-5s %(routername)-2s %(message)s')) logger.addHandler(handler) igmp_logger.addHandler(handler) mld_logger.addHandler(handler) global kernel from hpimdm.Kernel import Kernel4 kernel = Kernel4() global unicast_routing unicast_routing = UnicastRouting.UnicastRouting() global interfaces global igmp_interfaces interfaces = kernel.hpim_interface igmp_interfaces = kernel.membership_interface try: enable_ipv6_kernel() except: pass<|docstring|>Start process<|endoftext|>
471ea61ae531a30ea09a8a77f9fd5c7c58aad03ffd6aa5ca9ef9cc333acf4026
@observe('age') def debug_print(self, change): " Prints out a debug message whenever the person's age changes.\n\n " if self.debug: templ = '{first} {last} is {age} years old.' s = templ.format(first=self.first_name, last=self.last_name, age=self.age) print(s)
Prints out a debug message whenever the person's age changes.
examples/tutorial/employee/employee.py
debug_print
Kochise/enaml
1,080
python
@observe('age') def debug_print(self, change): " \n\n " if self.debug: templ = '{first} {last} is {age} years old.' s = templ.format(first=self.first_name, last=self.last_name, age=self.age) print(s)
@observe('age') def debug_print(self, change): " \n\n " if self.debug: templ = '{first} {last} is {age} years old.' s = templ.format(first=self.first_name, last=self.last_name, age=self.age) print(s)<|docstring|>Prints out a debug message whenever the person's age changes.<|endoftext|>
569e489ccec6f69fb5ca9466f6201d71f147b8943f7c109218983542d6772551
@observe('dob') def update_age(self, change): " Update the person's age whenever their date of birth changes\n\n " now = datetime.datetime.utcnow() age = (now.year - self.dob.year) if (((now.month == self.dob.month) and (now.day < self.dob.day)) or (now.month < self.dob.month)): age -= 1 self.age = age
Update the person's age whenever their date of birth changes
examples/tutorial/employee/employee.py
update_age
Kochise/enaml
1,080
python
@observe('dob') def update_age(self, change): " \n\n " now = datetime.datetime.utcnow() age = (now.year - self.dob.year) if (((now.month == self.dob.month) and (now.day < self.dob.day)) or (now.month < self.dob.month)): age -= 1 self.age = age
@observe('dob') def update_age(self, change): " \n\n " now = datetime.datetime.utcnow() age = (now.year - self.dob.year) if (((now.month == self.dob.month) and (now.day < self.dob.day)) or (now.month < self.dob.month)): age -= 1 self.age = age<|docstring|>Update the person's age whenever their date of birth changes<|endoftext|>
07d075b87d4c7f4ea16f24e5b644eb26d9cba5ac282d3f8747661fc4e37fb411
def ans_post(request, cur_level, tot_level): ' Handling Post requests while answering ' try: player = Player.objects.get(user=request.user) past_sitn = Situation.objects.get(situation_no=player.current_sitn) if (past_sitn.sub == False): op_no = request.POST.get('op_no') option_c = option.objects.get(id=op_no) if option_c.end: player.current_sitn = Situation.objects.get(situation_no=1).situation_no player.level = Situation.objects.get(situation_no=1).level player.score += 1 player.completed_or_dead = True player.save() updateLeaderboard() message = option_c.message return render(request, 'dead.html', {'user': player, 'message': message}) else: player.current_sitn = option_c.next_sit player.score += 1 player.timestamp = t.now() sitn = Situation.objects.get(situation_no=option_c.next_sit) player.level = sitn.level visiteds = player.visited_nodes.split(' ')[0:(- 1)] if (str(sitn.situation_no) not in visiteds): player.visited_nodes += f'{sitn.situation_no} ' player.save() updateLeaderboard() if ((player.level <= tot_level) and (player.level <= cur_level)): if (sitn.sub == True): timer = SituationTimer.objects.get_or_create(player=player, situation=sitn) return render(request, 'subjective_level.html', {'user': player, 'sitn': sitn, 'timepassed': timer[0].timepassed()}) else: options = sitn.options.all() return render(request, 'level.html', {'user': player, 'sitn': sitn, 'options': options}) elif ((player.level <= tot_level) and (player.level > cur_level)): return render(request, 'pls_wait.html', {'user': player}) else: messg = Situation.objects.get(situation_no=player.current_sitn).text player.completed_or_dead = True player.save() return render(request, 'finish.html', {'user': player, 'messg': messg}) else: ans = '' ans = request.POST.get('ans') timer = SituationTimer.objects.get_or_create(player=player, situation=past_sitn) if past_sitn.checkAnswer(ans): timer[0].end_time = t.now() timer[0].save() player.score += timer[0].timedifference() timer[0].delete() player.current_sitn = past_sitn.next_sitn player.timestamp = t.now() sitn = Situation.objects.get(situation_no=player.current_sitn) player.level = sitn.level visiteds = player.visited_nodes.split(' ')[0:(- 1)] if (str(sitn.situation_no) not in visiteds): player.visited_nodes += f'{sitn.situation_no} ' player.save() updateLeaderboard() if ((player.level <= tot_level) and (player.level <= cur_level)): if (sitn.sub == True): new_timer = SituationTimer.objects.get_or_create(player=player, situation=sitn, start_time=t.now()) return render(request, 'subjective_level.html', {'user': player, 'sitn': sitn, 'timepassed': new_timer[0].timepassed()}) else: options = sitn.options.all() return render(request, 'level.html', {'user': player, 'sitn': sitn, 'options': options}) elif ((player.level <= tot_level) and (player.level > cur_level)): return render(request, 'pls_wait.html', {'user': player}) else: messg = Situation.objects.get(situation_no=player.current_sitn).text player.completed_or_dead = True player.save() return render(request, 'finish.html', {'user': player, 'messg': messg}) else: return render(request, 'subjective_level.html', {'user': player, 'sitn': past_sitn, 'timepassed': timer[0].timepassed(), 'status': 302}) except: return render(request, '404.html')
Handling Post requests while answering
mindapp/views.py
ans_post
lugnitdgp/mindersnatch
1
python
def ans_post(request, cur_level, tot_level): ' ' try: player = Player.objects.get(user=request.user) past_sitn = Situation.objects.get(situation_no=player.current_sitn) if (past_sitn.sub == False): op_no = request.POST.get('op_no') option_c = option.objects.get(id=op_no) if option_c.end: player.current_sitn = Situation.objects.get(situation_no=1).situation_no player.level = Situation.objects.get(situation_no=1).level player.score += 1 player.completed_or_dead = True player.save() updateLeaderboard() message = option_c.message return render(request, 'dead.html', {'user': player, 'message': message}) else: player.current_sitn = option_c.next_sit player.score += 1 player.timestamp = t.now() sitn = Situation.objects.get(situation_no=option_c.next_sit) player.level = sitn.level visiteds = player.visited_nodes.split(' ')[0:(- 1)] if (str(sitn.situation_no) not in visiteds): player.visited_nodes += f'{sitn.situation_no} ' player.save() updateLeaderboard() if ((player.level <= tot_level) and (player.level <= cur_level)): if (sitn.sub == True): timer = SituationTimer.objects.get_or_create(player=player, situation=sitn) return render(request, 'subjective_level.html', {'user': player, 'sitn': sitn, 'timepassed': timer[0].timepassed()}) else: options = sitn.options.all() return render(request, 'level.html', {'user': player, 'sitn': sitn, 'options': options}) elif ((player.level <= tot_level) and (player.level > cur_level)): return render(request, 'pls_wait.html', {'user': player}) else: messg = Situation.objects.get(situation_no=player.current_sitn).text player.completed_or_dead = True player.save() return render(request, 'finish.html', {'user': player, 'messg': messg}) else: ans = ans = request.POST.get('ans') timer = SituationTimer.objects.get_or_create(player=player, situation=past_sitn) if past_sitn.checkAnswer(ans): timer[0].end_time = t.now() timer[0].save() player.score += timer[0].timedifference() timer[0].delete() player.current_sitn = past_sitn.next_sitn player.timestamp = t.now() sitn = Situation.objects.get(situation_no=player.current_sitn) player.level = sitn.level visiteds = player.visited_nodes.split(' ')[0:(- 1)] if (str(sitn.situation_no) not in visiteds): player.visited_nodes += f'{sitn.situation_no} ' player.save() updateLeaderboard() if ((player.level <= tot_level) and (player.level <= cur_level)): if (sitn.sub == True): new_timer = SituationTimer.objects.get_or_create(player=player, situation=sitn, start_time=t.now()) return render(request, 'subjective_level.html', {'user': player, 'sitn': sitn, 'timepassed': new_timer[0].timepassed()}) else: options = sitn.options.all() return render(request, 'level.html', {'user': player, 'sitn': sitn, 'options': options}) elif ((player.level <= tot_level) and (player.level > cur_level)): return render(request, 'pls_wait.html', {'user': player}) else: messg = Situation.objects.get(situation_no=player.current_sitn).text player.completed_or_dead = True player.save() return render(request, 'finish.html', {'user': player, 'messg': messg}) else: return render(request, 'subjective_level.html', {'user': player, 'sitn': past_sitn, 'timepassed': timer[0].timepassed(), 'status': 302}) except: return render(request, '404.html')
def ans_post(request, cur_level, tot_level): ' ' try: player = Player.objects.get(user=request.user) past_sitn = Situation.objects.get(situation_no=player.current_sitn) if (past_sitn.sub == False): op_no = request.POST.get('op_no') option_c = option.objects.get(id=op_no) if option_c.end: player.current_sitn = Situation.objects.get(situation_no=1).situation_no player.level = Situation.objects.get(situation_no=1).level player.score += 1 player.completed_or_dead = True player.save() updateLeaderboard() message = option_c.message return render(request, 'dead.html', {'user': player, 'message': message}) else: player.current_sitn = option_c.next_sit player.score += 1 player.timestamp = t.now() sitn = Situation.objects.get(situation_no=option_c.next_sit) player.level = sitn.level visiteds = player.visited_nodes.split(' ')[0:(- 1)] if (str(sitn.situation_no) not in visiteds): player.visited_nodes += f'{sitn.situation_no} ' player.save() updateLeaderboard() if ((player.level <= tot_level) and (player.level <= cur_level)): if (sitn.sub == True): timer = SituationTimer.objects.get_or_create(player=player, situation=sitn) return render(request, 'subjective_level.html', {'user': player, 'sitn': sitn, 'timepassed': timer[0].timepassed()}) else: options = sitn.options.all() return render(request, 'level.html', {'user': player, 'sitn': sitn, 'options': options}) elif ((player.level <= tot_level) and (player.level > cur_level)): return render(request, 'pls_wait.html', {'user': player}) else: messg = Situation.objects.get(situation_no=player.current_sitn).text player.completed_or_dead = True player.save() return render(request, 'finish.html', {'user': player, 'messg': messg}) else: ans = ans = request.POST.get('ans') timer = SituationTimer.objects.get_or_create(player=player, situation=past_sitn) if past_sitn.checkAnswer(ans): timer[0].end_time = t.now() timer[0].save() player.score += timer[0].timedifference() timer[0].delete() player.current_sitn = past_sitn.next_sitn player.timestamp = t.now() sitn = Situation.objects.get(situation_no=player.current_sitn) player.level = sitn.level visiteds = player.visited_nodes.split(' ')[0:(- 1)] if (str(sitn.situation_no) not in visiteds): player.visited_nodes += f'{sitn.situation_no} ' player.save() updateLeaderboard() if ((player.level <= tot_level) and (player.level <= cur_level)): if (sitn.sub == True): new_timer = SituationTimer.objects.get_or_create(player=player, situation=sitn, start_time=t.now()) return render(request, 'subjective_level.html', {'user': player, 'sitn': sitn, 'timepassed': new_timer[0].timepassed()}) else: options = sitn.options.all() return render(request, 'level.html', {'user': player, 'sitn': sitn, 'options': options}) elif ((player.level <= tot_level) and (player.level > cur_level)): return render(request, 'pls_wait.html', {'user': player}) else: messg = Situation.objects.get(situation_no=player.current_sitn).text player.completed_or_dead = True player.save() return render(request, 'finish.html', {'user': player, 'messg': messg}) else: return render(request, 'subjective_level.html', {'user': player, 'sitn': past_sitn, 'timepassed': timer[0].timepassed(), 'status': 302}) except: return render(request, '404.html')<|docstring|>Handling Post requests while answering<|endoftext|>
208c8e69501d55b62f861d1f719bea5febfc5018947181ea2b023acc2dbd4fa6
def ans_nonpost(request): ' Handling requests other than post while answering ' try: player = Player.objects.get(user=request.user) sitn = Situation.objects.get(situation_no=player.current_sitn) visiteds = player.visited_nodes.split(' ')[0:(- 1)] if (str(sitn.situation_no) not in visiteds): player.visited_nodes += f'{sitn.situation_no} ' player.save() if (sitn.sub == True): timer = SituationTimer.objects.get_or_create(player=player, situation=sitn) return render(request, 'subjective_level.html', {'user': player, 'sitn': sitn, 'timepassed': timer[0].timepassed()}) else: options = sitn.options.all() return render(request, 'level.html', {'user': player, 'sitn': sitn, 'options': options}) except Exception as e: print(e) return render(request, '404.html')
Handling requests other than post while answering
mindapp/views.py
ans_nonpost
lugnitdgp/mindersnatch
1
python
def ans_nonpost(request): ' ' try: player = Player.objects.get(user=request.user) sitn = Situation.objects.get(situation_no=player.current_sitn) visiteds = player.visited_nodes.split(' ')[0:(- 1)] if (str(sitn.situation_no) not in visiteds): player.visited_nodes += f'{sitn.situation_no} ' player.save() if (sitn.sub == True): timer = SituationTimer.objects.get_or_create(player=player, situation=sitn) return render(request, 'subjective_level.html', {'user': player, 'sitn': sitn, 'timepassed': timer[0].timepassed()}) else: options = sitn.options.all() return render(request, 'level.html', {'user': player, 'sitn': sitn, 'options': options}) except Exception as e: print(e) return render(request, '404.html')
def ans_nonpost(request): ' ' try: player = Player.objects.get(user=request.user) sitn = Situation.objects.get(situation_no=player.current_sitn) visiteds = player.visited_nodes.split(' ')[0:(- 1)] if (str(sitn.situation_no) not in visiteds): player.visited_nodes += f'{sitn.situation_no} ' player.save() if (sitn.sub == True): timer = SituationTimer.objects.get_or_create(player=player, situation=sitn) return render(request, 'subjective_level.html', {'user': player, 'sitn': sitn, 'timepassed': timer[0].timepassed()}) else: options = sitn.options.all() return render(request, 'level.html', {'user': player, 'sitn': sitn, 'options': options}) except Exception as e: print(e) return render(request, '404.html')<|docstring|>Handling requests other than post while answering<|endoftext|>
f7aba89573b00cc3c2f507033ee2428e4988dc6ecc2bee5199605d46643e9f08
def __init__(self, x, y, z): 'Class constructor\n>>>>>>> f2002266b5ad377e51769e208e400ff6725ae9d2\n Sets initial values for 3 attributes.\n Requires a floating point triple as an\n arguement for the starting position of the particle' self.position = (x, y, z) self.mass = 1.0 self.momentum = (0.0, 0.0, 0.0)
Class constructor >>>>>>> f2002266b5ad377e51769e208e400ff6725ae9d2 Sets initial values for 3 attributes. Requires a floating point triple as an arguement for the starting position of the particle
elementary.py
__init__
chapman-phys220-2018f/cw05-im-not-good-at-team-naes
0
python
def __init__(self, x, y, z): 'Class constructor\n>>>>>>> f2002266b5ad377e51769e208e400ff6725ae9d2\n Sets initial values for 3 attributes.\n Requires a floating point triple as an\n arguement for the starting position of the particle' self.position = (x, y, z) self.mass = 1.0 self.momentum = (0.0, 0.0, 0.0)
def __init__(self, x, y, z): 'Class constructor\n>>>>>>> f2002266b5ad377e51769e208e400ff6725ae9d2\n Sets initial values for 3 attributes.\n Requires a floating point triple as an\n arguement for the starting position of the particle' self.position = (x, y, z) self.mass = 1.0 self.momentum = (0.0, 0.0, 0.0)<|docstring|>Class constructor >>>>>>> f2002266b5ad377e51769e208e400ff6725ae9d2 Sets initial values for 3 attributes. Requires a floating point triple as an arguement for the starting position of the particle<|endoftext|>
48099206ff4163fc9659c70184940382fbbabdafdb6828cd83ea75c4024b2fe8
def impulse(self, px, py, pz): 'Alters the momentum by the impulse amount.\n Requires floating point triple to set impulse\n value.' self.momentum = ((self.momentum[0] + px), (self.momentum[1] + py), (self.momentum[2] + pz))
Alters the momentum by the impulse amount. Requires floating point triple to set impulse value.
elementary.py
impulse
chapman-phys220-2018f/cw05-im-not-good-at-team-naes
0
python
def impulse(self, px, py, pz): 'Alters the momentum by the impulse amount.\n Requires floating point triple to set impulse\n value.' self.momentum = ((self.momentum[0] + px), (self.momentum[1] + py), (self.momentum[2] + pz))
def impulse(self, px, py, pz): 'Alters the momentum by the impulse amount.\n Requires floating point triple to set impulse\n value.' self.momentum = ((self.momentum[0] + px), (self.momentum[1] + py), (self.momentum[2] + pz))<|docstring|>Alters the momentum by the impulse amount. Requires floating point triple to set impulse value.<|endoftext|>
d3d52947000c4eb966115750e26a469e44aa731920e60dd1d8026a3c8640c74c
def move(self, dt): 'Moves particle by one dt.\n Requires time unit for movement measurement.' self.position = ((self.position[0] + ((dt / self.mass) * self.momentum[0])), (self.position[1] + ((dt / self.mass) * self.momentum[1])), (self.position[2] + ((dt / self.mass) * self.momentum[2])))
Moves particle by one dt. Requires time unit for movement measurement.
elementary.py
move
chapman-phys220-2018f/cw05-im-not-good-at-team-naes
0
python
def move(self, dt): 'Moves particle by one dt.\n Requires time unit for movement measurement.' self.position = ((self.position[0] + ((dt / self.mass) * self.momentum[0])), (self.position[1] + ((dt / self.mass) * self.momentum[1])), (self.position[2] + ((dt / self.mass) * self.momentum[2])))
def move(self, dt): 'Moves particle by one dt.\n Requires time unit for movement measurement.' self.position = ((self.position[0] + ((dt / self.mass) * self.momentum[0])), (self.position[1] + ((dt / self.mass) * self.momentum[1])), (self.position[2] + ((dt / self.mass) * self.momentum[2])))<|docstring|>Moves particle by one dt. Requires time unit for movement measurement.<|endoftext|>
6dc9a8ef64eb678bb254f2a72a0558564cf347fc0c9be760fa35524e75c2454f
def test_class_presented(self): 'To support different kinds of objects returned vs. rows,\n there are two wrapper classes for Result.\n ' r1 = self._fixture() r2 = r1.columns(0, 1, 2) assert isinstance(r2, result.Result) m1 = r1.mappings() assert isinstance(m1, result.MappingResult) s1 = r1.scalars(1) assert isinstance(s1, result.ScalarResult)
To support different kinds of objects returned vs. rows, there are two wrapper classes for Result.
test/base/test_result.py
test_class_presented
NickKush/sqlalchemy
5,383
python
def test_class_presented(self): 'To support different kinds of objects returned vs. rows,\n there are two wrapper classes for Result.\n ' r1 = self._fixture() r2 = r1.columns(0, 1, 2) assert isinstance(r2, result.Result) m1 = r1.mappings() assert isinstance(m1, result.MappingResult) s1 = r1.scalars(1) assert isinstance(s1, result.ScalarResult)
def test_class_presented(self): 'To support different kinds of objects returned vs. rows,\n there are two wrapper classes for Result.\n ' r1 = self._fixture() r2 = r1.columns(0, 1, 2) assert isinstance(r2, result.Result) m1 = r1.mappings() assert isinstance(m1, result.MappingResult) s1 = r1.scalars(1) assert isinstance(s1, result.ScalarResult)<|docstring|>To support different kinds of objects returned vs. rows, there are two wrapper classes for Result.<|endoftext|>
646ac84d9387a45c6ee655e997ca7aaf51aa198f07fbed8b14f81d8a17863758
def measure(self): '\n Get recent data\n ' (self.recent_time, self.recent_data) = self.adapter.get_recent_content() self.compute_statistics() LOGGER.debug('Measuring...')
Get recent data
api/src/machines/gaming.py
measure
philipguedes/network-meeseeks
0
python
def measure(self): '\n \n ' (self.recent_time, self.recent_data) = self.adapter.get_recent_content() self.compute_statistics() LOGGER.debug('Measuring...')
def measure(self): '\n \n ' (self.recent_time, self.recent_data) = self.adapter.get_recent_content() self.compute_statistics() LOGGER.debug('Measuring...')<|docstring|>Get recent data<|endoftext|>
e23baa56173188537a15ef99f73bc160383a61b33bb109dfed95c78f9614c557
def freeze(self): '\n Returns True if PLR > 10%\n ' return (self.recent_data['packet_loss_rate'] > 0.1)
Returns True if PLR > 10%
api/src/machines/gaming.py
freeze
philipguedes/network-meeseeks
0
python
def freeze(self): '\n \n ' return (self.recent_data['packet_loss_rate'] > 0.1)
def freeze(self): '\n \n ' return (self.recent_data['packet_loss_rate'] > 0.1)<|docstring|>Returns True if PLR > 10%<|endoftext|>
a247114a9682dfcddd666f9b31b92916b7ce441bf50d0dde49fa9057164c7780
def get_include(): 'Get the include path for C extension headers.\n\n Returns\n -------\n :class:`str`\n ' import os return os.path.join(os.path.dirname(__file__), '_c')
Get the include path for C extension headers. Returns ------- :class:`str`
ms_deisotope/__init__.py
get_include
hkmoon/ms_deisotope
18
python
def get_include(): 'Get the include path for C extension headers.\n\n Returns\n -------\n :class:`str`\n ' import os return os.path.join(os.path.dirname(__file__), '_c')
def get_include(): 'Get the include path for C extension headers.\n\n Returns\n -------\n :class:`str`\n ' import os return os.path.join(os.path.dirname(__file__), '_c')<|docstring|>Get the include path for C extension headers. Returns ------- :class:`str`<|endoftext|>
a886acf3fd710193d33241fbff87b95d3d02cfd4436ebd534bb98fb7b718c1f5
def _get_sockets_fds(self): "Returns sockets dict. If this worker's cmd indicates use of\n a SO_REUSEPORT socket, a new socket is created and bound. This\n new socket's FD replaces original socket's FD in returned dict.\n This method populates `self._sockets` list. This list should be\n let go after `fork()`.\n " sockets_fds = None if ((self.watcher is not None) and (self.watcher.sockets is not None)): sockets_fds = self.watcher._get_sockets_fds() reuseport_sockets = tuple(((sn, s) for (sn, s) in self.watcher.sockets.items() if s.so_reuseport)) for (sn, s) in reuseport_sockets: if (('circus.sockets.%s' % sn) in self.watcher.cmd): sock = CircusSocket.load_from_config(s._cfg) sock.bind_and_listen() sockets_fds[sn] = sock.fileno() self._sockets.append(sock) return sockets_fds
Returns sockets dict. If this worker's cmd indicates use of a SO_REUSEPORT socket, a new socket is created and bound. This new socket's FD replaces original socket's FD in returned dict. This method populates `self._sockets` list. This list should be let go after `fork()`.
circus/process.py
_get_sockets_fds
cdgz/circus
0
python
def _get_sockets_fds(self): "Returns sockets dict. If this worker's cmd indicates use of\n a SO_REUSEPORT socket, a new socket is created and bound. This\n new socket's FD replaces original socket's FD in returned dict.\n This method populates `self._sockets` list. This list should be\n let go after `fork()`.\n " sockets_fds = None if ((self.watcher is not None) and (self.watcher.sockets is not None)): sockets_fds = self.watcher._get_sockets_fds() reuseport_sockets = tuple(((sn, s) for (sn, s) in self.watcher.sockets.items() if s.so_reuseport)) for (sn, s) in reuseport_sockets: if (('circus.sockets.%s' % sn) in self.watcher.cmd): sock = CircusSocket.load_from_config(s._cfg) sock.bind_and_listen() sockets_fds[sn] = sock.fileno() self._sockets.append(sock) return sockets_fds
def _get_sockets_fds(self): "Returns sockets dict. If this worker's cmd indicates use of\n a SO_REUSEPORT socket, a new socket is created and bound. This\n new socket's FD replaces original socket's FD in returned dict.\n This method populates `self._sockets` list. This list should be\n let go after `fork()`.\n " sockets_fds = None if ((self.watcher is not None) and (self.watcher.sockets is not None)): sockets_fds = self.watcher._get_sockets_fds() reuseport_sockets = tuple(((sn, s) for (sn, s) in self.watcher.sockets.items() if s.so_reuseport)) for (sn, s) in reuseport_sockets: if (('circus.sockets.%s' % sn) in self.watcher.cmd): sock = CircusSocket.load_from_config(s._cfg) sock.bind_and_listen() sockets_fds[sn] = sock.fileno() self._sockets.append(sock) return sockets_fds<|docstring|>Returns sockets dict. If this worker's cmd indicates use of a SO_REUSEPORT socket, a new socket is created and bound. This new socket's FD replaces original socket's FD in returned dict. This method populates `self._sockets` list. This list should be let go after `fork()`.<|endoftext|>
1c10cb29a58bee2d09c231c6dd0ac8a5a898d1576d0d3f3f7f8a8112850a31c2
def format_args(self, sockets_fds=None): " It's possible to use environment variables and some other variables\n that are available in this context, when spawning the processes.\n " logger.debug(('cmd: ' + bytestring(self.cmd))) logger.debug(('args: ' + str(self.args))) current_env = ObjectDict(self.env.copy()) format_kwargs = {'wid': self.wid, 'shell': self.shell, 'args': self.args, 'env': current_env, 'working_dir': self.working_dir, 'uid': self.uid, 'gid': self.gid, 'rlimits': self.rlimits, 'executable': self.executable, 'use_fds': self.use_fds} if (sockets_fds is not None): format_kwargs['sockets'] = sockets_fds if (self.watcher is not None): for option in self.watcher.optnames: if ((option not in format_kwargs) and hasattr(self.watcher, option)): format_kwargs[option] = getattr(self.watcher, option) cmd = replace_gnu_args(self.cmd, **format_kwargs) if (('$WID' in cmd) or (self.args and ('$WID' in self.args))): msg = 'Using $WID in the command is deprecated. You should use the python string format instead. In you case, this means replacing the $WID in your command by $(WID).' warnings.warn(msg, DeprecationWarning) self.cmd = cmd.replace('$WID', str(self.wid)) if (self.args is not None): if isinstance(self.args, string_types): args = shlex.split(bytestring(replace_gnu_args(self.args, **format_kwargs))) else: args = [bytestring(replace_gnu_args(arg, **format_kwargs)) for arg in self.args] args = (shlex.split(bytestring(cmd)) + args) else: args = shlex.split(bytestring(cmd)) logger.debug('process args: %s', args) return args
It's possible to use environment variables and some other variables that are available in this context, when spawning the processes.
circus/process.py
format_args
cdgz/circus
0
python
def format_args(self, sockets_fds=None): " It's possible to use environment variables and some other variables\n that are available in this context, when spawning the processes.\n " logger.debug(('cmd: ' + bytestring(self.cmd))) logger.debug(('args: ' + str(self.args))) current_env = ObjectDict(self.env.copy()) format_kwargs = {'wid': self.wid, 'shell': self.shell, 'args': self.args, 'env': current_env, 'working_dir': self.working_dir, 'uid': self.uid, 'gid': self.gid, 'rlimits': self.rlimits, 'executable': self.executable, 'use_fds': self.use_fds} if (sockets_fds is not None): format_kwargs['sockets'] = sockets_fds if (self.watcher is not None): for option in self.watcher.optnames: if ((option not in format_kwargs) and hasattr(self.watcher, option)): format_kwargs[option] = getattr(self.watcher, option) cmd = replace_gnu_args(self.cmd, **format_kwargs) if (('$WID' in cmd) or (self.args and ('$WID' in self.args))): msg = 'Using $WID in the command is deprecated. You should use the python string format instead. In you case, this means replacing the $WID in your command by $(WID).' warnings.warn(msg, DeprecationWarning) self.cmd = cmd.replace('$WID', str(self.wid)) if (self.args is not None): if isinstance(self.args, string_types): args = shlex.split(bytestring(replace_gnu_args(self.args, **format_kwargs))) else: args = [bytestring(replace_gnu_args(arg, **format_kwargs)) for arg in self.args] args = (shlex.split(bytestring(cmd)) + args) else: args = shlex.split(bytestring(cmd)) logger.debug('process args: %s', args) return args
def format_args(self, sockets_fds=None): " It's possible to use environment variables and some other variables\n that are available in this context, when spawning the processes.\n " logger.debug(('cmd: ' + bytestring(self.cmd))) logger.debug(('args: ' + str(self.args))) current_env = ObjectDict(self.env.copy()) format_kwargs = {'wid': self.wid, 'shell': self.shell, 'args': self.args, 'env': current_env, 'working_dir': self.working_dir, 'uid': self.uid, 'gid': self.gid, 'rlimits': self.rlimits, 'executable': self.executable, 'use_fds': self.use_fds} if (sockets_fds is not None): format_kwargs['sockets'] = sockets_fds if (self.watcher is not None): for option in self.watcher.optnames: if ((option not in format_kwargs) and hasattr(self.watcher, option)): format_kwargs[option] = getattr(self.watcher, option) cmd = replace_gnu_args(self.cmd, **format_kwargs) if (('$WID' in cmd) or (self.args and ('$WID' in self.args))): msg = 'Using $WID in the command is deprecated. You should use the python string format instead. In you case, this means replacing the $WID in your command by $(WID).' warnings.warn(msg, DeprecationWarning) self.cmd = cmd.replace('$WID', str(self.wid)) if (self.args is not None): if isinstance(self.args, string_types): args = shlex.split(bytestring(replace_gnu_args(self.args, **format_kwargs))) else: args = [bytestring(replace_gnu_args(arg, **format_kwargs)) for arg in self.args] args = (shlex.split(bytestring(cmd)) + args) else: args = shlex.split(bytestring(cmd)) logger.debug('process args: %s', args) return args<|docstring|>It's possible to use environment variables and some other variables that are available in this context, when spawning the processes.<|endoftext|>
66c514624561b04b2d8dc95b7528395305474a29ffffb9fa6502efd65d7aadc3
@debuglog def send_signal(self, sig): 'Sends a signal **sig** to the process.' logger.debug(('sending signal %s to %s' % (sig, self.pid))) return self._worker.send_signal(sig)
Sends a signal **sig** to the process.
circus/process.py
send_signal
cdgz/circus
0
python
@debuglog def send_signal(self, sig): logger.debug(('sending signal %s to %s' % (sig, self.pid))) return self._worker.send_signal(sig)
@debuglog def send_signal(self, sig): logger.debug(('sending signal %s to %s' % (sig, self.pid))) return self._worker.send_signal(sig)<|docstring|>Sends a signal **sig** to the process.<|endoftext|>
6329d60f6f9ec9aefde5047f7c4f19ccb61e012353a1f2d0196c322a8a611fa0
@debuglog def stop(self): "Stop the process and close stdout/stderr\n\n If the corresponding process is still here\n (normally it's already killed by the watcher),\n a SIGTERM is sent, then a SIGKILL after 1 second.\n\n The shutdown process (SIGTERM then SIGKILL) is\n normally taken by the watcher. So if the process\n is still there here, it's a kind of bad behavior\n because the graceful timeout won't be respected here.\n " try: try: if (self._worker.poll() is None): return self._worker.terminate() finally: if (self._worker.stderr is not None): self._worker.stderr.close() if (self._worker.stdout is not None): self._worker.stdout.close() except NoSuchProcess: pass
Stop the process and close stdout/stderr If the corresponding process is still here (normally it's already killed by the watcher), a SIGTERM is sent, then a SIGKILL after 1 second. The shutdown process (SIGTERM then SIGKILL) is normally taken by the watcher. So if the process is still there here, it's a kind of bad behavior because the graceful timeout won't be respected here.
circus/process.py
stop
cdgz/circus
0
python
@debuglog def stop(self): "Stop the process and close stdout/stderr\n\n If the corresponding process is still here\n (normally it's already killed by the watcher),\n a SIGTERM is sent, then a SIGKILL after 1 second.\n\n The shutdown process (SIGTERM then SIGKILL) is\n normally taken by the watcher. So if the process\n is still there here, it's a kind of bad behavior\n because the graceful timeout won't be respected here.\n " try: try: if (self._worker.poll() is None): return self._worker.terminate() finally: if (self._worker.stderr is not None): self._worker.stderr.close() if (self._worker.stdout is not None): self._worker.stdout.close() except NoSuchProcess: pass
@debuglog def stop(self): "Stop the process and close stdout/stderr\n\n If the corresponding process is still here\n (normally it's already killed by the watcher),\n a SIGTERM is sent, then a SIGKILL after 1 second.\n\n The shutdown process (SIGTERM then SIGKILL) is\n normally taken by the watcher. So if the process\n is still there here, it's a kind of bad behavior\n because the graceful timeout won't be respected here.\n " try: try: if (self._worker.poll() is None): return self._worker.terminate() finally: if (self._worker.stderr is not None): self._worker.stderr.close() if (self._worker.stdout is not None): self._worker.stdout.close() except NoSuchProcess: pass<|docstring|>Stop the process and close stdout/stderr If the corresponding process is still here (normally it's already killed by the watcher), a SIGTERM is sent, then a SIGKILL after 1 second. The shutdown process (SIGTERM then SIGKILL) is normally taken by the watcher. So if the process is still there here, it's a kind of bad behavior because the graceful timeout won't be respected here.<|endoftext|>
209ba79ecefaa4a2d58616ccb234053ac82e28a9336dc60e565cc4fdfe4538c8
def age(self): 'Return the age of the process in seconds.' return (time.time() - self.started)
Return the age of the process in seconds.
circus/process.py
age
cdgz/circus
0
python
def age(self): return (time.time() - self.started)
def age(self): return (time.time() - self.started)<|docstring|>Return the age of the process in seconds.<|endoftext|>
f26e777be08d1f24e66ac19b7f7096cd261e6c02401ce877824329442128c077
def info(self): 'Return process info.\n\n The info returned is a mapping with these keys:\n\n - **mem_info1**: Resident Set Size Memory in bytes (RSS)\n - **mem_info2**: Virtual Memory Size in bytes (VMS).\n - **cpu**: % of cpu usage.\n - **mem**: % of memory usage.\n - **ctime**: process CPU (user + system) time in seconds.\n - **pid**: process id.\n - **username**: user name that owns the process.\n - **nice**: process niceness (between -20 and 20)\n - **cmdline**: the command line the process was run with.\n ' try: info = get_info(self._worker) except NoSuchProcess: return 'No such process (stopped?)' info['age'] = self.age() info['started'] = self.started info['children'] = [] info['wid'] = self.wid for child in self._worker.get_children(): info['children'].append(get_info(child)) return info
Return process info. The info returned is a mapping with these keys: - **mem_info1**: Resident Set Size Memory in bytes (RSS) - **mem_info2**: Virtual Memory Size in bytes (VMS). - **cpu**: % of cpu usage. - **mem**: % of memory usage. - **ctime**: process CPU (user + system) time in seconds. - **pid**: process id. - **username**: user name that owns the process. - **nice**: process niceness (between -20 and 20) - **cmdline**: the command line the process was run with.
circus/process.py
info
cdgz/circus
0
python
def info(self): 'Return process info.\n\n The info returned is a mapping with these keys:\n\n - **mem_info1**: Resident Set Size Memory in bytes (RSS)\n - **mem_info2**: Virtual Memory Size in bytes (VMS).\n - **cpu**: % of cpu usage.\n - **mem**: % of memory usage.\n - **ctime**: process CPU (user + system) time in seconds.\n - **pid**: process id.\n - **username**: user name that owns the process.\n - **nice**: process niceness (between -20 and 20)\n - **cmdline**: the command line the process was run with.\n ' try: info = get_info(self._worker) except NoSuchProcess: return 'No such process (stopped?)' info['age'] = self.age() info['started'] = self.started info['children'] = [] info['wid'] = self.wid for child in self._worker.get_children(): info['children'].append(get_info(child)) return info
def info(self): 'Return process info.\n\n The info returned is a mapping with these keys:\n\n - **mem_info1**: Resident Set Size Memory in bytes (RSS)\n - **mem_info2**: Virtual Memory Size in bytes (VMS).\n - **cpu**: % of cpu usage.\n - **mem**: % of memory usage.\n - **ctime**: process CPU (user + system) time in seconds.\n - **pid**: process id.\n - **username**: user name that owns the process.\n - **nice**: process niceness (between -20 and 20)\n - **cmdline**: the command line the process was run with.\n ' try: info = get_info(self._worker) except NoSuchProcess: return 'No such process (stopped?)' info['age'] = self.age() info['started'] = self.started info['children'] = [] info['wid'] = self.wid for child in self._worker.get_children(): info['children'].append(get_info(child)) return info<|docstring|>Return process info. The info returned is a mapping with these keys: - **mem_info1**: Resident Set Size Memory in bytes (RSS) - **mem_info2**: Virtual Memory Size in bytes (VMS). - **cpu**: % of cpu usage. - **mem**: % of memory usage. - **ctime**: process CPU (user + system) time in seconds. - **pid**: process id. - **username**: user name that owns the process. - **nice**: process niceness (between -20 and 20) - **cmdline**: the command line the process was run with.<|endoftext|>
8ddcfbc43e352863234074abc140b1d7188b42e78f608d8ae05d89cc9ae989c4
def children(self): 'Return a list of children pids.' return [child.pid for child in self._worker.get_children()]
Return a list of children pids.
circus/process.py
children
cdgz/circus
0
python
def children(self): return [child.pid for child in self._worker.get_children()]
def children(self): return [child.pid for child in self._worker.get_children()]<|docstring|>Return a list of children pids.<|endoftext|>
a5a4d610996c304019ae83ca1e45032bf87cfa0fd502842db82a0ad33ce120b6
def is_child(self, pid): 'Return True is the given *pid* is a child of that process.' pids = [child.pid for child in self._worker.get_children()] if (pid in pids): return True return False
Return True is the given *pid* is a child of that process.
circus/process.py
is_child
cdgz/circus
0
python
def is_child(self, pid): pids = [child.pid for child in self._worker.get_children()] if (pid in pids): return True return False
def is_child(self, pid): pids = [child.pid for child in self._worker.get_children()] if (pid in pids): return True return False<|docstring|>Return True is the given *pid* is a child of that process.<|endoftext|>
e38ec016eb6248a306b9bdb52c7037ced7c94c4f0401c91cc42788388017c596
@debuglog def send_signal_child(self, pid, signum): 'Send signal *signum* to child *pid*.' children = dict(((child.pid, child) for child in self._worker.get_children())) try: children[pid].send_signal(signum) except KeyError: raise NoSuchProcess(pid)
Send signal *signum* to child *pid*.
circus/process.py
send_signal_child
cdgz/circus
0
python
@debuglog def send_signal_child(self, pid, signum): children = dict(((child.pid, child) for child in self._worker.get_children())) try: children[pid].send_signal(signum) except KeyError: raise NoSuchProcess(pid)
@debuglog def send_signal_child(self, pid, signum): children = dict(((child.pid, child) for child in self._worker.get_children())) try: children[pid].send_signal(signum) except KeyError: raise NoSuchProcess(pid)<|docstring|>Send signal *signum* to child *pid*.<|endoftext|>
5ef6a6e82ed9a4113fb0afd13be84a744345ff0c28c648737a86b5400af69cd0
@debuglog def send_signal_children(self, signum): 'Send signal *signum* to all children.' for child in self._worker.get_children(): try: child.send_signal(signum) except OSError as e: if (e.errno != errno.ESRCH): raise
Send signal *signum* to all children.
circus/process.py
send_signal_children
cdgz/circus
0
python
@debuglog def send_signal_children(self, signum): for child in self._worker.get_children(): try: child.send_signal(signum) except OSError as e: if (e.errno != errno.ESRCH): raise
@debuglog def send_signal_children(self, signum): for child in self._worker.get_children(): try: child.send_signal(signum) except OSError as e: if (e.errno != errno.ESRCH): raise<|docstring|>Send signal *signum* to all children.<|endoftext|>