repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
Clinical-Genomics/trailblazer
trailblazer/server/api.py
analyses
def analyses(): """Display analyses.""" per_page = int(request.args.get('per_page', 50)) page = int(request.args.get('page', 1)) query = store.analyses(status=request.args.get('status'), query=request.args.get('query'), is_visible=request.args.get('i...
python
def analyses(): """Display analyses.""" per_page = int(request.args.get('per_page', 50)) page = int(request.args.get('page', 1)) query = store.analyses(status=request.args.get('status'), query=request.args.get('query'), is_visible=request.args.get('i...
[ "def", "analyses", "(", ")", ":", "per_page", "=", "int", "(", "request", ".", "args", ".", "get", "(", "'per_page'", ",", "50", ")", ")", "page", "=", "int", "(", "request", ".", "args", ".", "get", "(", "'page'", ",", "1", ")", ")", "query", ...
Display analyses.
[ "Display", "analyses", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/server/api.py#L27-L43
Clinical-Genomics/trailblazer
trailblazer/server/api.py
analysis
def analysis(analysis_id): """Display a single analysis.""" analysis_obj = store.analysis(analysis_id) if analysis_obj is None: return abort(404) if request.method == 'PUT': analysis_obj.update(request.json) store.commit() data = analysis_obj.to_dict() data['failed_jobs...
python
def analysis(analysis_id): """Display a single analysis.""" analysis_obj = store.analysis(analysis_id) if analysis_obj is None: return abort(404) if request.method == 'PUT': analysis_obj.update(request.json) store.commit() data = analysis_obj.to_dict() data['failed_jobs...
[ "def", "analysis", "(", "analysis_id", ")", ":", "analysis_obj", "=", "store", ".", "analysis", "(", "analysis_id", ")", "if", "analysis_obj", "is", "None", ":", "return", "abort", "(", "404", ")", "if", "request", ".", "method", "==", "'PUT'", ":", "ana...
Display a single analysis.
[ "Display", "a", "single", "analysis", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/server/api.py#L47-L60
ozgurgunes/django-manifest
manifest/accounts/utils.py
get_gravatar
def get_gravatar(email, size=80, default='identicon'): """ Get's a Gravatar for a email address. :param size: The size in pixels of one side of the Gravatar's square image. Optional, if not supplied will default to ``80``. :param default: Defines what should be displayed if no imag...
python
def get_gravatar(email, size=80, default='identicon'): """ Get's a Gravatar for a email address. :param size: The size in pixels of one side of the Gravatar's square image. Optional, if not supplied will default to ``80``. :param default: Defines what should be displayed if no imag...
[ "def", "get_gravatar", "(", "email", ",", "size", "=", "80", ",", "default", "=", "'identicon'", ")", ":", "if", "defaults", ".", "ACCOUNTS_GRAVATAR_SECURE", ":", "base_url", "=", "'https://secure.gravatar.com/avatar/'", "else", ":", "base_url", "=", "'http://www....
Get's a Gravatar for a email address. :param size: The size in pixels of one side of the Gravatar's square image. Optional, if not supplied will default to ``80``. :param default: Defines what should be displayed if no image is found for this user. Optional argument which defau...
[ "Get", "s", "a", "Gravatar", "for", "a", "email", "address", "." ]
train
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/utils.py#L10-L52
ozgurgunes/django-manifest
manifest/accounts/utils.py
login_redirect
def login_redirect(redirect=None, user=None): """ Redirect user after successful sign in. First looks for a ``requested_redirect``. If not supplied will fall-back to the user specific account page. If all fails, will fall-back to the standard Django ``LOGIN_REDIRECT_URL`` setting. Returns a strin...
python
def login_redirect(redirect=None, user=None): """ Redirect user after successful sign in. First looks for a ``requested_redirect``. If not supplied will fall-back to the user specific account page. If all fails, will fall-back to the standard Django ``LOGIN_REDIRECT_URL`` setting. Returns a strin...
[ "def", "login_redirect", "(", "redirect", "=", "None", ",", "user", "=", "None", ")", ":", "if", "redirect", ":", "return", "redirect", "elif", "user", "is", "not", "None", ":", "return", "defaults", ".", "ACCOUNTS_LOGIN_REDIRECT_URL", "%", "{", "'username'"...
Redirect user after successful sign in. First looks for a ``requested_redirect``. If not supplied will fall-back to the user specific account page. If all fails, will fall-back to the standard Django ``LOGIN_REDIRECT_URL`` setting. Returns a string defining the URI to go next. :param redirect: ...
[ "Redirect", "user", "after", "successful", "sign", "in", "." ]
train
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/utils.py#L54-L77
ozgurgunes/django-manifest
manifest/accounts/utils.py
generate_sha1
def generate_sha1(string, salt=None): """ Generates a sha1 hash for supplied string. Doesn't need to be very secure because it's not used for password checking. We got Django for that. :param string: The string that needs to be encrypted. :param salt: Optionally define your own sal...
python
def generate_sha1(string, salt=None): """ Generates a sha1 hash for supplied string. Doesn't need to be very secure because it's not used for password checking. We got Django for that. :param string: The string that needs to be encrypted. :param salt: Optionally define your own sal...
[ "def", "generate_sha1", "(", "string", ",", "salt", "=", "None", ")", ":", "if", "not", "salt", ":", "salt", "=", "hashlib", ".", "sha1", "(", "str", "(", "random", ".", "random", "(", ")", ")", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexd...
Generates a sha1 hash for supplied string. Doesn't need to be very secure because it's not used for password checking. We got Django for that. :param string: The string that needs to be encrypted. :param salt: Optionally define your own salt. If none is supplied, will use a random...
[ "Generates", "a", "sha1", "hash", "for", "supplied", "string", ".", "Doesn", "t", "need", "to", "be", "very", "secure", "because", "it", "s", "not", "used", "for", "password", "checking", ".", "We", "got", "Django", "for", "that", "." ]
train
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/utils.py#L79-L98
ozgurgunes/django-manifest
manifest/accounts/utils.py
get_datetime_now
def get_datetime_now(): """ Returns datetime object with current point in time. In Django 1.4+ it uses Django's django.utils.timezone.now() which returns an aware or naive datetime that represents the current point in time when ``USE_TZ`` in project's settings is True or False respectively. In ...
python
def get_datetime_now(): """ Returns datetime object with current point in time. In Django 1.4+ it uses Django's django.utils.timezone.now() which returns an aware or naive datetime that represents the current point in time when ``USE_TZ`` in project's settings is True or False respectively. In ...
[ "def", "get_datetime_now", "(", ")", ":", "try", ":", "from", "django", ".", "utils", "import", "timezone", "return", "timezone", ".", "now", "(", ")", "except", "ImportError", ":", "return", "datetime", ".", "datetime", ".", "now", "(", ")" ]
Returns datetime object with current point in time. In Django 1.4+ it uses Django's django.utils.timezone.now() which returns an aware or naive datetime that represents the current point in time when ``USE_TZ`` in project's settings is True or False respectively. In older versions of Django it uses dat...
[ "Returns", "datetime", "object", "with", "current", "point", "in", "time", "." ]
train
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/utils.py#L113-L127
dusktreader/py-buzz
examples/handle_errors.py
complex_handle_errors
def complex_handle_errors(): """ This function demonstrates a more complex usage of the handle_errors ctx_mgr. The following features are demonstrated:: * Handling a specific exception type with ``exception_class`` * Absorbing exceptions by setting ``re_raise`` to ``False`` * Branching wi...
python
def complex_handle_errors(): """ This function demonstrates a more complex usage of the handle_errors ctx_mgr. The following features are demonstrated:: * Handling a specific exception type with ``exception_class`` * Absorbing exceptions by setting ``re_raise`` to ``False`` * Branching wi...
[ "def", "complex_handle_errors", "(", ")", ":", "print", "(", "\"Demonstrating complex handle_errors example\"", ")", "def", "_handler_function", "(", "err", ",", "final_message", ",", "trace", ")", ":", "\"\"\"\n This function is a helper function for handling an excepti...
This function demonstrates a more complex usage of the handle_errors ctx_mgr. The following features are demonstrated:: * Handling a specific exception type with ``exception_class`` * Absorbing exceptions by setting ``re_raise`` to ``False`` * Branching with ``do_except``, ``do_else``, and ``do_f...
[ "This", "function", "demonstrates", "a", "more", "complex", "usage", "of", "the", "handle_errors", "ctx_mgr", ".", "The", "following", "features", "are", "demonstrated", "::" ]
train
https://github.com/dusktreader/py-buzz/blob/f2fd97abe158a1688188647992a5be6531058ec3/examples/handle_errors.py#L32-L67
pytroll/posttroll
posttroll/message.py
is_valid_data
def is_valid_data(obj): """Check if data is JSON serializable. """ if obj: try: tmp = json.dumps(obj, default=datetime_encoder) del tmp except (TypeError, UnicodeDecodeError): return False return True
python
def is_valid_data(obj): """Check if data is JSON serializable. """ if obj: try: tmp = json.dumps(obj, default=datetime_encoder) del tmp except (TypeError, UnicodeDecodeError): return False return True
[ "def", "is_valid_data", "(", "obj", ")", ":", "if", "obj", ":", "try", ":", "tmp", "=", "json", ".", "dumps", "(", "obj", ",", "default", "=", "datetime_encoder", ")", "del", "tmp", "except", "(", "TypeError", ",", "UnicodeDecodeError", ")", ":", "retu...
Check if data is JSON serializable.
[ "Check", "if", "data", "is", "JSON", "serializable", "." ]
train
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message.py#L85-L94
pytroll/posttroll
posttroll/message.py
datetime_decoder
def datetime_decoder(dct): """Decode datetimes to python objects. """ if isinstance(dct, list): pairs = enumerate(dct) elif isinstance(dct, dict): pairs = dct.items() result = [] for key, val in pairs: if isinstance(val, six.string_types): try: ...
python
def datetime_decoder(dct): """Decode datetimes to python objects. """ if isinstance(dct, list): pairs = enumerate(dct) elif isinstance(dct, dict): pairs = dct.items() result = [] for key, val in pairs: if isinstance(val, six.string_types): try: ...
[ "def", "datetime_decoder", "(", "dct", ")", ":", "if", "isinstance", "(", "dct", ",", "list", ")", ":", "pairs", "=", "enumerate", "(", "dct", ")", "elif", "isinstance", "(", "dct", ",", "dict", ")", ":", "pairs", "=", "dct", ".", "items", "(", ")"...
Decode datetimes to python objects.
[ "Decode", "datetimes", "to", "python", "objects", "." ]
train
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message.py#L224-L244
pytroll/posttroll
posttroll/message.py
_decode
def _decode(rawstr): """Convert a raw string to a Message. """ # Check for the magick word. try: rawstr = rawstr.decode('utf-8') except (AttributeError, UnicodeEncodeError): pass except (UnicodeDecodeError): try: rawstr = rawstr.decode('iso-8859-1') ex...
python
def _decode(rawstr): """Convert a raw string to a Message. """ # Check for the magick word. try: rawstr = rawstr.decode('utf-8') except (AttributeError, UnicodeEncodeError): pass except (UnicodeDecodeError): try: rawstr = rawstr.decode('iso-8859-1') ex...
[ "def", "_decode", "(", "rawstr", ")", ":", "# Check for the magick word.", "try", ":", "rawstr", "=", "rawstr", ".", "decode", "(", "'utf-8'", ")", "except", "(", "AttributeError", ",", "UnicodeEncodeError", ")", ":", "pass", "except", "(", "UnicodeDecodeError",...
Convert a raw string to a Message.
[ "Convert", "a", "raw", "string", "to", "a", "Message", "." ]
train
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message.py#L247-L306
pytroll/posttroll
posttroll/message.py
_encode
def _encode(msg, head=False, binary=False): """Convert a Message to a raw string. """ rawstr = str(_MAGICK) + u"{0:s} {1:s} {2:s} {3:s} {4:s}".format( msg.subject, msg.type, msg.sender, msg.time.isoformat(), msg.version) if not head and msg.data: if not binary and isinstance(msg.data, s...
python
def _encode(msg, head=False, binary=False): """Convert a Message to a raw string. """ rawstr = str(_MAGICK) + u"{0:s} {1:s} {2:s} {3:s} {4:s}".format( msg.subject, msg.type, msg.sender, msg.time.isoformat(), msg.version) if not head and msg.data: if not binary and isinstance(msg.data, s...
[ "def", "_encode", "(", "msg", ",", "head", "=", "False", ",", "binary", "=", "False", ")", ":", "rawstr", "=", "str", "(", "_MAGICK", ")", "+", "u\"{0:s} {1:s} {2:s} {3:s} {4:s}\"", ".", "format", "(", "msg", ".", "subject", ",", "msg", ".", "type", ",...
Convert a Message to a raw string.
[ "Convert", "a", "Message", "to", "a", "raw", "string", "." ]
train
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message.py#L318-L335
pytroll/posttroll
posttroll/message.py
_getsender
def _getsender(): """Return local sender. Don't use the getpass module, it looks at various environment variables and is unreliable. """ import os import pwd import socket host = socket.gethostname() user = pwd.getpwuid(os.getuid())[0] return "%s@%s" % (user, host)
python
def _getsender(): """Return local sender. Don't use the getpass module, it looks at various environment variables and is unreliable. """ import os import pwd import socket host = socket.gethostname() user = pwd.getpwuid(os.getuid())[0] return "%s@%s" % (user, host)
[ "def", "_getsender", "(", ")", ":", "import", "os", "import", "pwd", "import", "socket", "host", "=", "socket", ".", "gethostname", "(", ")", "user", "=", "pwd", ".", "getpwuid", "(", "os", ".", "getuid", "(", ")", ")", "[", "0", "]", "return", "\"...
Return local sender. Don't use the getpass module, it looks at various environment variables and is unreliable.
[ "Return", "local", "sender", ".", "Don", "t", "use", "the", "getpass", "module", "it", "looks", "at", "various", "environment", "variables", "and", "is", "unreliable", "." ]
train
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message.py#L344-L354
pytroll/posttroll
posttroll/message.py
Message._validate
def _validate(self): """Validate a messages attributes. """ if not is_valid_subject(self.subject): raise MessageError("Invalid subject: '%s'" % self.subject) if not is_valid_type(self.type): raise MessageError("Invalid type: '%s'" % self.type) if not is_va...
python
def _validate(self): """Validate a messages attributes. """ if not is_valid_subject(self.subject): raise MessageError("Invalid subject: '%s'" % self.subject) if not is_valid_type(self.type): raise MessageError("Invalid type: '%s'" % self.type) if not is_va...
[ "def", "_validate", "(", "self", ")", ":", "if", "not", "is_valid_subject", "(", "self", ".", "subject", ")", ":", "raise", "MessageError", "(", "\"Invalid subject: '%s'\"", "%", "self", ".", "subject", ")", "if", "not", "is_valid_type", "(", "self", ".", ...
Validate a messages attributes.
[ "Validate", "a", "messages", "attributes", "." ]
train
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message.py#L188-L199
Syndace/python-x3dh
x3dh/state.py
State.__generateSPK
def __generateSPK(self): """ Generate a new PK and sign its public key using the IK, add the timestamp aswell to allow for periodic rotations. """ key = self.__KeyPair.generate() key_serialized = self.__PublicKeyEncoder.encodePublicKey( key.pub, ...
python
def __generateSPK(self): """ Generate a new PK and sign its public key using the IK, add the timestamp aswell to allow for periodic rotations. """ key = self.__KeyPair.generate() key_serialized = self.__PublicKeyEncoder.encodePublicKey( key.pub, ...
[ "def", "__generateSPK", "(", "self", ")", ":", "key", "=", "self", ".", "__KeyPair", ".", "generate", "(", ")", "key_serialized", "=", "self", ".", "__PublicKeyEncoder", ".", "encodePublicKey", "(", "key", ".", "pub", ",", "self", ".", "__curve", ")", "s...
Generate a new PK and sign its public key using the IK, add the timestamp aswell to allow for periodic rotations.
[ "Generate", "a", "new", "PK", "and", "sign", "its", "public", "key", "using", "the", "IK", "add", "the", "timestamp", "aswell", "to", "allow", "for", "periodic", "rotations", "." ]
train
https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L152-L171
Syndace/python-x3dh
x3dh/state.py
State.__generateOTPKs
def __generateOTPKs(self, num_otpks = None): """ Generate the given amount of OTPKs. :param num_otpks: Either an integer or None. If the value of num_otpks is None, set it to the max_num_otpks value of the configuration. """ if num_otpks == None: nu...
python
def __generateOTPKs(self, num_otpks = None): """ Generate the given amount of OTPKs. :param num_otpks: Either an integer or None. If the value of num_otpks is None, set it to the max_num_otpks value of the configuration. """ if num_otpks == None: nu...
[ "def", "__generateOTPKs", "(", "self", ",", "num_otpks", "=", "None", ")", ":", "if", "num_otpks", "==", "None", ":", "num_otpks", "=", "self", ".", "__max_num_otpks", "otpks", "=", "[", "]", "for", "_", "in", "range", "(", "num_otpks", ")", ":", "otpk...
Generate the given amount of OTPKs. :param num_otpks: Either an integer or None. If the value of num_otpks is None, set it to the max_num_otpks value of the configuration.
[ "Generate", "the", "given", "amount", "of", "OTPKs", "." ]
train
https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L174-L195
Syndace/python-x3dh
x3dh/state.py
State.__kdf
def __kdf(self, secret_key_material): """ :param secret_key_material: A bytes-like object encoding the secret key material. :returns: A bytes-like object encoding the shared secret key. """ salt = b"\x00" * self.__hash_function().digest_size if self.__curve == "25519": ...
python
def __kdf(self, secret_key_material): """ :param secret_key_material: A bytes-like object encoding the secret key material. :returns: A bytes-like object encoding the shared secret key. """ salt = b"\x00" * self.__hash_function().digest_size if self.__curve == "25519": ...
[ "def", "__kdf", "(", "self", ",", "secret_key_material", ")", ":", "salt", "=", "b\"\\x00\"", "*", "self", ".", "__hash_function", "(", ")", ".", "digest_size", "if", "self", ".", "__curve", "==", "\"25519\"", ":", "input_key_material", "=", "b\"\\xFF\"", "*...
:param secret_key_material: A bytes-like object encoding the secret key material. :returns: A bytes-like object encoding the shared secret key.
[ ":", "param", "secret_key_material", ":", "A", "bytes", "-", "like", "object", "encoding", "the", "secret", "key", "material", ".", ":", "returns", ":", "A", "bytes", "-", "like", "object", "encoding", "the", "shared", "secret", "key", "." ]
train
https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L201-L224
Syndace/python-x3dh
x3dh/state.py
State.__checkSPKTimestamp
def __checkSPKTimestamp(self): """ Check whether the SPK is too old and generate a new one in that case. """ if time.time() - self.__spk["timestamp"] > self.__spk_timeout: self.__generateSPK()
python
def __checkSPKTimestamp(self): """ Check whether the SPK is too old and generate a new one in that case. """ if time.time() - self.__spk["timestamp"] > self.__spk_timeout: self.__generateSPK()
[ "def", "__checkSPKTimestamp", "(", "self", ")", ":", "if", "time", ".", "time", "(", ")", "-", "self", ".", "__spk", "[", "\"timestamp\"", "]", ">", "self", ".", "__spk_timeout", ":", "self", ".", "__generateSPK", "(", ")" ]
Check whether the SPK is too old and generate a new one in that case.
[ "Check", "whether", "the", "SPK", "is", "too", "old", "and", "generate", "a", "new", "one", "in", "that", "case", "." ]
train
https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L230-L236
Syndace/python-x3dh
x3dh/state.py
State.__refillOTPKs
def __refillOTPKs(self): """ If the amount of available OTPKs fell under the minimum, refills the OTPKs up to the maximum limit again. """ remainingOTPKs = len(self.__otpks) if remainingOTPKs < self.__min_num_otpks: self.__generateOTPKs(self.__max_num_otpks ...
python
def __refillOTPKs(self): """ If the amount of available OTPKs fell under the minimum, refills the OTPKs up to the maximum limit again. """ remainingOTPKs = len(self.__otpks) if remainingOTPKs < self.__min_num_otpks: self.__generateOTPKs(self.__max_num_otpks ...
[ "def", "__refillOTPKs", "(", "self", ")", ":", "remainingOTPKs", "=", "len", "(", "self", ".", "__otpks", ")", "if", "remainingOTPKs", "<", "self", ".", "__min_num_otpks", ":", "self", ".", "__generateOTPKs", "(", "self", ".", "__max_num_otpks", "-", "remain...
If the amount of available OTPKs fell under the minimum, refills the OTPKs up to the maximum limit again.
[ "If", "the", "amount", "of", "available", "OTPKs", "fell", "under", "the", "minimum", "refills", "the", "OTPKs", "up", "to", "the", "maximum", "limit", "again", "." ]
train
https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L238-L247
Syndace/python-x3dh
x3dh/state.py
State.hideFromPublicBundle
def hideFromPublicBundle(self, otpk_pub): """ Hide a one-time pre key from the public bundle. :param otpk_pub: The public key of the one-time pre key to hide, encoded as a bytes-like object. """ self.__checkSPKTimestamp() for otpk in self.__otpks: ...
python
def hideFromPublicBundle(self, otpk_pub): """ Hide a one-time pre key from the public bundle. :param otpk_pub: The public key of the one-time pre key to hide, encoded as a bytes-like object. """ self.__checkSPKTimestamp() for otpk in self.__otpks: ...
[ "def", "hideFromPublicBundle", "(", "self", ",", "otpk_pub", ")", ":", "self", ".", "__checkSPKTimestamp", "(", ")", "for", "otpk", "in", "self", ".", "__otpks", ":", "if", "otpk", ".", "pub", "==", "otpk_pub", ":", "self", ".", "__otpks", ".", "remove",...
Hide a one-time pre key from the public bundle. :param otpk_pub: The public key of the one-time pre key to hide, encoded as a bytes-like object.
[ "Hide", "a", "one", "-", "time", "pre", "key", "from", "the", "public", "bundle", "." ]
train
https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L250-L264
Syndace/python-x3dh
x3dh/state.py
State.deleteOTPK
def deleteOTPK(self, otpk_pub): """ Delete a one-time pre key, either publicly visible or hidden. :param otpk_pub: The public key of the one-time pre key to delete, encoded as a bytes-like object. """ self.__checkSPKTimestamp() for otpk in self.__otpks: ...
python
def deleteOTPK(self, otpk_pub): """ Delete a one-time pre key, either publicly visible or hidden. :param otpk_pub: The public key of the one-time pre key to delete, encoded as a bytes-like object. """ self.__checkSPKTimestamp() for otpk in self.__otpks: ...
[ "def", "deleteOTPK", "(", "self", ",", "otpk_pub", ")", ":", "self", ".", "__checkSPKTimestamp", "(", ")", "for", "otpk", "in", "self", ".", "__otpks", ":", "if", "otpk", ".", "pub", "==", "otpk_pub", ":", "self", ".", "__otpks", ".", "remove", "(", ...
Delete a one-time pre key, either publicly visible or hidden. :param otpk_pub: The public key of the one-time pre key to delete, encoded as a bytes-like object.
[ "Delete", "a", "one", "-", "time", "pre", "key", "either", "publicly", "visible", "or", "hidden", "." ]
train
https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L267-L285
Syndace/python-x3dh
x3dh/state.py
State.getPublicBundle
def getPublicBundle(self): """ Fill a PublicBundle object with the public bundle data of this State. :returns: An instance of PublicBundle, filled with the public data of this State. """ self.__checkSPKTimestamp() ik_pub = self.__ik.pub spk_pub = self.__sp...
python
def getPublicBundle(self): """ Fill a PublicBundle object with the public bundle data of this State. :returns: An instance of PublicBundle, filled with the public data of this State. """ self.__checkSPKTimestamp() ik_pub = self.__ik.pub spk_pub = self.__sp...
[ "def", "getPublicBundle", "(", "self", ")", ":", "self", ".", "__checkSPKTimestamp", "(", ")", "ik_pub", "=", "self", ".", "__ik", ".", "pub", "spk_pub", "=", "self", ".", "__spk", "[", "\"key\"", "]", ".", "pub", "spk_sig", "=", "self", ".", "__spk", ...
Fill a PublicBundle object with the public bundle data of this State. :returns: An instance of PublicBundle, filled with the public data of this State.
[ "Fill", "a", "PublicBundle", "object", "with", "the", "public", "bundle", "data", "of", "this", "State", "." ]
train
https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L291-L305
Syndace/python-x3dh
x3dh/state.py
State.changed
def changed(self): """ Read, whether this State has changed since it was loaded/since this flag was last cleared. :returns: A boolean indicating, whether the public bundle data has changed since last reading this flag. Clears the flag when reading. """ ...
python
def changed(self): """ Read, whether this State has changed since it was loaded/since this flag was last cleared. :returns: A boolean indicating, whether the public bundle data has changed since last reading this flag. Clears the flag when reading. """ ...
[ "def", "changed", "(", "self", ")", ":", "self", ".", "__checkSPKTimestamp", "(", ")", "changed", "=", "self", ".", "_changed", "self", ".", "_changed", "=", "False", "return", "changed" ]
Read, whether this State has changed since it was loaded/since this flag was last cleared. :returns: A boolean indicating, whether the public bundle data has changed since last reading this flag. Clears the flag when reading.
[ "Read", "whether", "this", "State", "has", "changed", "since", "it", "was", "loaded", "/", "since", "this", "flag", "was", "last", "cleared", "." ]
train
https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L308-L323
Syndace/python-x3dh
x3dh/state.py
State.getSharedSecretActive
def getSharedSecretActive( self, other_public_bundle, allow_zero_otpks = False ): """ Do the key exchange, as the active party. This involves selecting keys from the passive parties' public bundle. :param other_public_bundle: An instance of PublicBundle, fill...
python
def getSharedSecretActive( self, other_public_bundle, allow_zero_otpks = False ): """ Do the key exchange, as the active party. This involves selecting keys from the passive parties' public bundle. :param other_public_bundle: An instance of PublicBundle, fill...
[ "def", "getSharedSecretActive", "(", "self", ",", "other_public_bundle", ",", "allow_zero_otpks", "=", "False", ")", ":", "self", ".", "__checkSPKTimestamp", "(", ")", "other_ik", "=", "self", ".", "__KeyPair", "(", "pub", "=", "other_public_bundle", ".", "ik", ...
Do the key exchange, as the active party. This involves selecting keys from the passive parties' public bundle. :param other_public_bundle: An instance of PublicBundle, filled with the public data of the passive party. :param allow_zero_otpks: A flag indicating whether bundles with ...
[ "Do", "the", "key", "exchange", "as", "the", "active", "party", ".", "This", "involves", "selecting", "keys", "from", "the", "passive", "parties", "public", "bundle", "." ]
train
https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L329-L438
Syndace/python-x3dh
x3dh/state.py
State.getSharedSecretPassive
def getSharedSecretPassive( self, passive_exchange_data, allow_no_otpk = False, keep_otpk = False ): """ Do the key exchange, as the passive party. This involves retrieving data about the key exchange from the active party. :param passive_exchange_dat...
python
def getSharedSecretPassive( self, passive_exchange_data, allow_no_otpk = False, keep_otpk = False ): """ Do the key exchange, as the passive party. This involves retrieving data about the key exchange from the active party. :param passive_exchange_dat...
[ "def", "getSharedSecretPassive", "(", "self", ",", "passive_exchange_data", ",", "allow_no_otpk", "=", "False", ",", "keep_otpk", "=", "False", ")", ":", "self", ".", "__checkSPKTimestamp", "(", ")", "other_ik", "=", "self", ".", "__KeyPair", "(", "pub", "=", ...
Do the key exchange, as the passive party. This involves retrieving data about the key exchange from the active party. :param passive_exchange_data: A structure generated by the active party, which contains data requried to complete the key exchange. See the "to_other" part of t...
[ "Do", "the", "key", "exchange", "as", "the", "passive", "party", ".", "This", "involves", "retrieving", "data", "about", "the", "key", "exchange", "from", "the", "active", "party", "." ]
train
https://github.com/Syndace/python-x3dh/blob/a6cec1ae858121b88bef1b178f5cda5e43d5c391/x3dh/state.py#L440-L545
kislyuk/tweak
tweak/__init__.py
Config.save
def save(self, mode=0o600): """ Serialize the config data to the user home directory. :param mode: The octal Unix mode (permissions) for the config file. """ if self._parent is not None: self._parent.save(mode=mode) else: config_dir = os.path.dirn...
python
def save(self, mode=0o600): """ Serialize the config data to the user home directory. :param mode: The octal Unix mode (permissions) for the config file. """ if self._parent is not None: self._parent.save(mode=mode) else: config_dir = os.path.dirn...
[ "def", "save", "(", "self", ",", "mode", "=", "0o600", ")", ":", "if", "self", ".", "_parent", "is", "not", "None", ":", "self", ".", "_parent", ".", "save", "(", "mode", "=", "mode", ")", "else", ":", "config_dir", "=", "os", ".", "path", ".", ...
Serialize the config data to the user home directory. :param mode: The octal Unix mode (permissions) for the config file.
[ "Serialize", "the", "config", "data", "to", "the", "user", "home", "directory", "." ]
train
https://github.com/kislyuk/tweak/blob/0fec5fa8a21e46713c565a996f41c8b7c6793166/tweak/__init__.py#L148-L166
daskol/nls
nls/model.py
Problem.model
def model(self, *args, **kwargs): """ Piority of Arguments: Arguments passed in `kwargs` has the most piority, 'param' key in `kwargs` has less piority than `kwargs` and dictionary arguments in `args` have the least piority. Other arguments are ignored. Argument List: model -...
python
def model(self, *args, **kwargs): """ Piority of Arguments: Arguments passed in `kwargs` has the most piority, 'param' key in `kwargs` has less piority than `kwargs` and dictionary arguments in `args` have the least piority. Other arguments are ignored. Argument List: model -...
[ "def", "model", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'filename'", "in", "kwargs", ":", "return", "self", ".", "modelFromFile", "(", "kwargs", "[", "'filename'", "]", ")", "if", "'params'", "in", "kwargs", ":", "par...
Piority of Arguments: Arguments passed in `kwargs` has the most piority, 'param' key in `kwargs` has less piority than `kwargs` and dictionary arguments in `args` have the least piority. Other arguments are ignored. Argument List: model - set model type, default value 'default'; ...
[ "Piority", "of", "Arguments", ":", "Arguments", "passed", "in", "kwargs", "has", "the", "most", "piority", "param", "key", "in", "kwargs", "has", "less", "piority", "than", "kwargs", "and", "dictionary", "arguments", "in", "args", "have", "the", "least", "pi...
train
https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/model.py#L32-L72
daskol/nls
nls/model.py
AbstractModel.getChemicalPotential
def getChemicalPotential(self, solution): """Call solver in order to calculate chemical potential. """ if isinstance(solution, Solution): solution = solution.getSolution() self.mu = self.solver.chemicalPotential(solution) return self.mu
python
def getChemicalPotential(self, solution): """Call solver in order to calculate chemical potential. """ if isinstance(solution, Solution): solution = solution.getSolution() self.mu = self.solver.chemicalPotential(solution) return self.mu
[ "def", "getChemicalPotential", "(", "self", ",", "solution", ")", ":", "if", "isinstance", "(", "solution", ",", "Solution", ")", ":", "solution", "=", "solution", ".", "getSolution", "(", ")", "self", ".", "mu", "=", "self", ".", "solver", ".", "chemica...
Call solver in order to calculate chemical potential.
[ "Call", "solver", "in", "order", "to", "calculate", "chemical", "potential", "." ]
train
https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/model.py#L196-L203
daskol/nls
nls/model.py
AbstractModel.store
def store(self, filename=None, label=None, desc=None, date=None): """Store object to mat-file. TODO: determine format specification """ date = date if date else datetime.now() date = date.replace(microsecond=0).isoformat() filename = filename if filename else date + '.mat' ...
python
def store(self, filename=None, label=None, desc=None, date=None): """Store object to mat-file. TODO: determine format specification """ date = date if date else datetime.now() date = date.replace(microsecond=0).isoformat() filename = filename if filename else date + '.mat' ...
[ "def", "store", "(", "self", ",", "filename", "=", "None", ",", "label", "=", "None", ",", "desc", "=", "None", ",", "date", "=", "None", ")", ":", "date", "=", "date", "if", "date", "else", "datetime", ".", "now", "(", ")", "date", "=", "date", ...
Store object to mat-file. TODO: determine format specification
[ "Store", "object", "to", "mat", "-", "file", ".", "TODO", ":", "determine", "format", "specification" ]
train
https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/model.py#L257-L284
daskol/nls
nls/model.py
AbstractModel.restore
def restore(self, filename): """Restore object from mat-file. TODO: determine format specification """ matfile = loadmat(filename) matfile['originals'] = matfile['originals'][0, 0] if matfile['dim'] == 1: matfile['init_solution'] = matfile['init_solution'][0, :] ...
python
def restore(self, filename): """Restore object from mat-file. TODO: determine format specification """ matfile = loadmat(filename) matfile['originals'] = matfile['originals'][0, 0] if matfile['dim'] == 1: matfile['init_solution'] = matfile['init_solution'][0, :] ...
[ "def", "restore", "(", "self", ",", "filename", ")", ":", "matfile", "=", "loadmat", "(", "filename", ")", "matfile", "[", "'originals'", "]", "=", "matfile", "[", "'originals'", "]", "[", "0", ",", "0", "]", "if", "matfile", "[", "'dim'", "]", "==",...
Restore object from mat-file. TODO: determine format specification
[ "Restore", "object", "from", "mat", "-", "file", ".", "TODO", ":", "determine", "format", "specification" ]
train
https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/model.py#L286-L314
daskol/nls
nls/model.py
Solution.getDampingIntegral
def getDampingIntegral(self): """Calculate integral of damping terms of hamiltonian using rectangular method. """ reservoir = self.getReservoir() density = self.getDensity() length = self.model.getSpatialStep() if self.solution.ndim == 1: nodes = self.model.g...
python
def getDampingIntegral(self): """Calculate integral of damping terms of hamiltonian using rectangular method. """ reservoir = self.getReservoir() density = self.getDensity() length = self.model.getSpatialStep() if self.solution.ndim == 1: nodes = self.model.g...
[ "def", "getDampingIntegral", "(", "self", ")", ":", "reservoir", "=", "self", ".", "getReservoir", "(", ")", "density", "=", "self", ".", "getDensity", "(", ")", "length", "=", "self", ".", "model", ".", "getSpatialStep", "(", ")", "if", "self", ".", "...
Calculate integral of damping terms of hamiltonian using rectangular method.
[ "Calculate", "integral", "of", "damping", "terms", "of", "hamiltonian", "using", "rectangular", "method", "." ]
train
https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/model.py#L350-L365
daskol/nls
nls/model.py
Solution.store
def store(self, filename=None, label=None, desc=None, date=None): """Store object to mat-file. TODO: determine format specification """ date = datetime.now() if date is None else date filename = filename if filename else date.replace(microsecond=0).isoformat() + '.mat' def store...
python
def store(self, filename=None, label=None, desc=None, date=None): """Store object to mat-file. TODO: determine format specification """ date = datetime.now() if date is None else date filename = filename if filename else date.replace(microsecond=0).isoformat() + '.mat' def store...
[ "def", "store", "(", "self", ",", "filename", "=", "None", ",", "label", "=", "None", ",", "desc", "=", "None", ",", "date", "=", "None", ")", ":", "date", "=", "datetime", ".", "now", "(", ")", "if", "date", "is", "None", "else", "date", "filena...
Store object to mat-file. TODO: determine format specification
[ "Store", "object", "to", "mat", "-", "file", ".", "TODO", ":", "determine", "format", "specification" ]
train
https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/model.py#L500-L519
daskol/nls
nls/model.py
Solution.restore
def restore(self, filename): """Restore object from mat-file. TODO: determine format specification """ matfile = loadmat(filename) if matfile['dim'] == 1: matfile['solution'] = matfile['solution'][0, :] self.elapsed_time = matfile['elapsed_time'][0, 0] self....
python
def restore(self, filename): """Restore object from mat-file. TODO: determine format specification """ matfile = loadmat(filename) if matfile['dim'] == 1: matfile['solution'] = matfile['solution'][0, :] self.elapsed_time = matfile['elapsed_time'][0, 0] self....
[ "def", "restore", "(", "self", ",", "filename", ")", ":", "matfile", "=", "loadmat", "(", "filename", ")", "if", "matfile", "[", "'dim'", "]", "==", "1", ":", "matfile", "[", "'solution'", "]", "=", "matfile", "[", "'solution'", "]", "[", "0", ",", ...
Restore object from mat-file. TODO: determine format specification
[ "Restore", "object", "from", "mat", "-", "file", ".", "TODO", ":", "determine", "format", "specification" ]
train
https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/model.py#L521-L532
fudge-py/fudge
fudge/util.py
fmt_val
def fmt_val(val, shorten=True): """Format a value for inclusion in an informative text string. """ val = repr(val) max = 50 if shorten: if len(val) > max: close = val[-1] val = val[0:max-4] + "..." if close in (">", "'", '"', ']', '}', ')'): ...
python
def fmt_val(val, shorten=True): """Format a value for inclusion in an informative text string. """ val = repr(val) max = 50 if shorten: if len(val) > max: close = val[-1] val = val[0:max-4] + "..." if close in (">", "'", '"', ']', '}', ')'): ...
[ "def", "fmt_val", "(", "val", ",", "shorten", "=", "True", ")", ":", "val", "=", "repr", "(", "val", ")", "max", "=", "50", "if", "shorten", ":", "if", "len", "(", "val", ")", ">", "max", ":", "close", "=", "val", "[", "-", "1", "]", "val", ...
Format a value for inclusion in an informative text string.
[ "Format", "a", "value", "for", "inclusion", "in", "an", "informative", "text", "string", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/util.py#L15-L27
fudge-py/fudge
fudge/util.py
fmt_dict_vals
def fmt_dict_vals(dict_vals, shorten=True): """Returns list of key=val pairs formatted for inclusion in an informative text string. """ items = dict_vals.items() if not items: return [fmt_val(None, shorten=shorten)] return ["%s=%s" % (k, fmt_val(v, shorten=shorten)) for k,v in items]
python
def fmt_dict_vals(dict_vals, shorten=True): """Returns list of key=val pairs formatted for inclusion in an informative text string. """ items = dict_vals.items() if not items: return [fmt_val(None, shorten=shorten)] return ["%s=%s" % (k, fmt_val(v, shorten=shorten)) for k,v in items]
[ "def", "fmt_dict_vals", "(", "dict_vals", ",", "shorten", "=", "True", ")", ":", "items", "=", "dict_vals", ".", "items", "(", ")", "if", "not", "items", ":", "return", "[", "fmt_val", "(", "None", ",", "shorten", "=", "shorten", ")", "]", "return", ...
Returns list of key=val pairs formatted for inclusion in an informative text string.
[ "Returns", "list", "of", "key", "=", "val", "pairs", "formatted", "for", "inclusion", "in", "an", "informative", "text", "string", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/util.py#L29-L36
Clinical-Genomics/trailblazer
trailblazer/mip/start.py
MipCli.build_command
def build_command(self, config, **kwargs): """Builds the command to execute MIP.""" command = ['perl', self.script, CLI_OPTIONS['config']['option'], config] for key, value in kwargs.items(): # enable passing in flags as "False" - shouldn't add command if value: ...
python
def build_command(self, config, **kwargs): """Builds the command to execute MIP.""" command = ['perl', self.script, CLI_OPTIONS['config']['option'], config] for key, value in kwargs.items(): # enable passing in flags as "False" - shouldn't add command if value: ...
[ "def", "build_command", "(", "self", ",", "config", ",", "*", "*", "kwargs", ")", ":", "command", "=", "[", "'perl'", ",", "self", ".", "script", ",", "CLI_OPTIONS", "[", "'config'", "]", "[", "'option'", "]", ",", "config", "]", "for", "key", ",", ...
Builds the command to execute MIP.
[ "Builds", "the", "command", "to", "execute", "MIP", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/start.py#L48-L59
Clinical-Genomics/trailblazer
trailblazer/mip/start.py
MipCli.execute
def execute(self, command): """Start a new MIP run.""" process = subprocess.Popen( command, preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL) ) return process
python
def execute(self, command): """Start a new MIP run.""" process = subprocess.Popen( command, preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL) ) return process
[ "def", "execute", "(", "self", ",", "command", ")", ":", "process", "=", "subprocess", ".", "Popen", "(", "command", ",", "preexec_fn", "=", "lambda", ":", "signal", ".", "signal", "(", "signal", ".", "SIGPIPE", ",", "signal", ".", "SIG_DFL", ")", ")",...
Start a new MIP run.
[ "Start", "a", "new", "MIP", "run", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/start.py#L63-L69
thespacedoctor/sherlock
sherlock/commonutils/update_wiki_pages.py
update_wiki_pages.update
def update(self): """ Update wiki pages See class docstring for usage """ self.log.debug('starting the ``update`` method') if "sherlock wiki root" not in self.settings: print "Sherlock wiki settings not found in settings file" return sta...
python
def update(self): """ Update wiki pages See class docstring for usage """ self.log.debug('starting the ``update`` method') if "sherlock wiki root" not in self.settings: print "Sherlock wiki settings not found in settings file" return sta...
[ "def", "update", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``update`` method'", ")", "if", "\"sherlock wiki root\"", "not", "in", "self", ".", "settings", ":", "print", "\"Sherlock wiki settings not found in settings file\"", "return...
Update wiki pages See class docstring for usage
[ "Update", "wiki", "pages" ]
train
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/commonutils/update_wiki_pages.py#L91-L115
thespacedoctor/sherlock
sherlock/commonutils/update_wiki_pages.py
update_wiki_pages._get_table_infos
def _get_table_infos( self, trimmed=False): """query the sherlock-catalogues database table metadata """ self.log.debug('starting the ``_get_table_infos`` method') sqlQuery = u""" SELECT * FROM crossmatch_catalogues.tcs_helper_catalogue_tables_info wh...
python
def _get_table_infos( self, trimmed=False): """query the sherlock-catalogues database table metadata """ self.log.debug('starting the ``_get_table_infos`` method') sqlQuery = u""" SELECT * FROM crossmatch_catalogues.tcs_helper_catalogue_tables_info wh...
[ "def", "_get_table_infos", "(", "self", ",", "trimmed", "=", "False", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_get_table_infos`` method'", ")", "sqlQuery", "=", "u\"\"\"\n SELECT * FROM crossmatch_catalogues.tcs_helper_catalogue_tables_inf...
query the sherlock-catalogues database table metadata
[ "query", "the", "sherlock", "-", "catalogues", "database", "table", "metadata" ]
train
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/commonutils/update_wiki_pages.py#L117-L145
thespacedoctor/sherlock
sherlock/commonutils/update_wiki_pages.py
update_wiki_pages._get_view_infos
def _get_view_infos( self, trimmed=False): """query the sherlock-catalogues database view metadata """ self.log.debug('starting the ``_get_view_infos`` method') sqlQuery = u""" SELECT v.*, t.description as "master table" FROM crossmatch_catalogues.tcs...
python
def _get_view_infos( self, trimmed=False): """query the sherlock-catalogues database view metadata """ self.log.debug('starting the ``_get_view_infos`` method') sqlQuery = u""" SELECT v.*, t.description as "master table" FROM crossmatch_catalogues.tcs...
[ "def", "_get_view_infos", "(", "self", ",", "trimmed", "=", "False", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_get_view_infos`` method'", ")", "sqlQuery", "=", "u\"\"\"\n SELECT v.*, t.description as \"master table\" FROM crossmatch_catalog...
query the sherlock-catalogues database view metadata
[ "query", "the", "sherlock", "-", "catalogues", "database", "view", "metadata" ]
train
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/commonutils/update_wiki_pages.py#L147-L175
thespacedoctor/sherlock
sherlock/commonutils/update_wiki_pages.py
update_wiki_pages._get_stream_view_infos
def _get_stream_view_infos( self, trimmed=False): """query the sherlock-catalogues database streamed data tables' metadata """ self.log.debug('starting the ``_get_stream_view_infos`` method') sqlQuery = u""" SELECT * FROM crossmatch_catalogues.tcs_hel...
python
def _get_stream_view_infos( self, trimmed=False): """query the sherlock-catalogues database streamed data tables' metadata """ self.log.debug('starting the ``_get_stream_view_infos`` method') sqlQuery = u""" SELECT * FROM crossmatch_catalogues.tcs_hel...
[ "def", "_get_stream_view_infos", "(", "self", ",", "trimmed", "=", "False", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_get_stream_view_infos`` method'", ")", "sqlQuery", "=", "u\"\"\"\n SELECT * FROM crossmatch_catalogues.tcs_helper_catalogu...
query the sherlock-catalogues database streamed data tables' metadata
[ "query", "the", "sherlock", "-", "catalogues", "database", "streamed", "data", "tables", "metadata" ]
train
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/commonutils/update_wiki_pages.py#L177-L205
thespacedoctor/sherlock
sherlock/commonutils/update_wiki_pages.py
update_wiki_pages._create_md_tables
def _create_md_tables( self, tableData, viewData, streamData ): """generate markdown format tables from the database query results **Key Arguments:** - ``tableData`` -- the sherlock-catalogues database table metadata. - ``viewData`` -- the she...
python
def _create_md_tables( self, tableData, viewData, streamData ): """generate markdown format tables from the database query results **Key Arguments:** - ``tableData`` -- the sherlock-catalogues database table metadata. - ``viewData`` -- the she...
[ "def", "_create_md_tables", "(", "self", ",", "tableData", ",", "viewData", ",", "streamData", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_create_md_tables`` method'", ")", "header", "=", "u\"\"\"\n| <sub>Table Name</sub> | <sub>Description</sub> | ...
generate markdown format tables from the database query results **Key Arguments:** - ``tableData`` -- the sherlock-catalogues database table metadata. - ``viewData`` -- the sherlock-catalogues database view metadata. - ``streamData`` -- the sherlock-catalogues database strea...
[ "generate", "markdown", "format", "tables", "from", "the", "database", "query", "results" ]
train
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/commonutils/update_wiki_pages.py#L207-L350
thespacedoctor/sherlock
sherlock/commonutils/update_wiki_pages.py
update_wiki_pages._write_wiki_pages
def _write_wiki_pages( self): """write the markdown formated content of the database tables' metadata to local wiki pages """ self.log.debug('starting the ``_write_wiki_pages`` method') pathToWriteFile = self.settings[ "sherlock wiki root"] + "/Crossmatch-Catalog...
python
def _write_wiki_pages( self): """write the markdown formated content of the database tables' metadata to local wiki pages """ self.log.debug('starting the ``_write_wiki_pages`` method') pathToWriteFile = self.settings[ "sherlock wiki root"] + "/Crossmatch-Catalog...
[ "def", "_write_wiki_pages", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_write_wiki_pages`` method'", ")", "pathToWriteFile", "=", "self", ".", "settings", "[", "\"sherlock wiki root\"", "]", "+", "\"/Crossmatch-Catalogue Tables.md\"",...
write the markdown formated content of the database tables' metadata to local wiki pages
[ "write", "the", "markdown", "formated", "content", "of", "the", "database", "tables", "metadata", "to", "local", "wiki", "pages" ]
train
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/commonutils/update_wiki_pages.py#L352-L392
thespacedoctor/sherlock
sherlock/commonutils/update_wiki_pages.py
update_wiki_pages._update_github
def _update_github( self): """commit the changes and push them to github """ self.log.debug('starting the ``_update_github`` method') from subprocess import Popen, PIPE, STDOUT gdir = self.settings["sherlock wiki root"] cmd = """cd %(gdir)s && git add --all &...
python
def _update_github( self): """commit the changes and push them to github """ self.log.debug('starting the ``_update_github`` method') from subprocess import Popen, PIPE, STDOUT gdir = self.settings["sherlock wiki root"] cmd = """cd %(gdir)s && git add --all &...
[ "def", "_update_github", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_update_github`` method'", ")", "from", "subprocess", "import", "Popen", ",", "PIPE", ",", "STDOUT", "gdir", "=", "self", ".", "settings", "[", "\"sherlock ...
commit the changes and push them to github
[ "commit", "the", "changes", "and", "push", "them", "to", "github" ]
train
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/commonutils/update_wiki_pages.py#L394-L409
kakulukia/django-undeletable
django_undeletable/models.py
AbstractUser.email_user
def email_user( self, subject, message, from_email=settings.DEFAULT_FROM_EMAIL, **kwargs ): """ Sends an email to this User. If settings.EMAIL_OVERRIDE_ADDRESS is set, this mail will be redirected to the alternate mail address. """ receiver = self.email if ...
python
def email_user( self, subject, message, from_email=settings.DEFAULT_FROM_EMAIL, **kwargs ): """ Sends an email to this User. If settings.EMAIL_OVERRIDE_ADDRESS is set, this mail will be redirected to the alternate mail address. """ receiver = self.email if ...
[ "def", "email_user", "(", "self", ",", "subject", ",", "message", ",", "from_email", "=", "settings", ".", "DEFAULT_FROM_EMAIL", ",", "*", "*", "kwargs", ")", ":", "receiver", "=", "self", ".", "email", "if", "settings", ".", "EMAIL_OVERRIDE_ADDRESS", ":", ...
Sends an email to this User. If settings.EMAIL_OVERRIDE_ADDRESS is set, this mail will be redirected to the alternate mail address.
[ "Sends", "an", "email", "to", "this", "User", ".", "If", "settings", ".", "EMAIL_OVERRIDE_ADDRESS", "is", "set", "this", "mail", "will", "be", "redirected", "to", "the", "alternate", "mail", "address", "." ]
train
https://github.com/kakulukia/django-undeletable/blob/565ae7c07ba0279a8cf768a96046f0f4ecbc0467/django_undeletable/models.py#L213-L225
Clinical-Genomics/trailblazer
trailblazer/cli/clean.py
clean
def clean(context, days_ago, yes): """Clean up files from "old" analyses runs.""" number_of_days_ago = dt.datetime.now() - dt.timedelta(days=days_ago) analyses = context.obj['store'].analyses( status='completed', before=number_of_days_ago, deleted=False, ) for analysis_obj in...
python
def clean(context, days_ago, yes): """Clean up files from "old" analyses runs.""" number_of_days_ago = dt.datetime.now() - dt.timedelta(days=days_ago) analyses = context.obj['store'].analyses( status='completed', before=number_of_days_ago, deleted=False, ) for analysis_obj in...
[ "def", "clean", "(", "context", ",", "days_ago", ",", "yes", ")", ":", "number_of_days_ago", "=", "dt", ".", "datetime", ".", "now", "(", ")", "-", "dt", ".", "timedelta", "(", "days", "=", "days_ago", ")", "analyses", "=", "context", ".", "obj", "["...
Clean up files from "old" analyses runs.
[ "Clean", "up", "files", "from", "old", "analyses", "runs", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/cli/clean.py#L14-L29
thespacedoctor/sherlock
sherlock/commonutils/get_crossmatch_catalogues_column_map.py
get_crossmatch_catalogues_column_map
def get_crossmatch_catalogues_column_map( dbConn, log): """*Query the sherlock-catalogues helper tables to generate a map of the important columns of each catalogue* Within your sherlock-catalogues database you need to manually map the inhomogeneous column-names from the sherlock-catalogues to ...
python
def get_crossmatch_catalogues_column_map( dbConn, log): """*Query the sherlock-catalogues helper tables to generate a map of the important columns of each catalogue* Within your sherlock-catalogues database you need to manually map the inhomogeneous column-names from the sherlock-catalogues to ...
[ "def", "get_crossmatch_catalogues_column_map", "(", "dbConn", ",", "log", ")", ":", "log", ".", "debug", "(", "'starting the ``get_crossmatch_catalogues_column_map`` function'", ")", "# GRAB THE NAMES OF THE IMPORTANT COLUMNS FROM DATABASE", "sqlQuery", "=", "u\"\"\"\n SELEC...
*Query the sherlock-catalogues helper tables to generate a map of the important columns of each catalogue* Within your sherlock-catalogues database you need to manually map the inhomogeneous column-names from the sherlock-catalogues to an internal homogeneous name-set which includes *ra*, *dec*, *redshift*, *objec...
[ "*", "Query", "the", "sherlock", "-", "catalogues", "helper", "tables", "to", "generate", "a", "map", "of", "the", "important", "columns", "of", "each", "catalogue", "*" ]
train
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/commonutils/get_crossmatch_catalogues_column_map.py#L20-L77
Clinical-Genomics/trailblazer
trailblazer/mip/miplog.py
job_ids
def job_ids(log_stream): """Grep out all lines with scancel example.""" id_rows = [line for line in log_stream if 'scancel' in line] jobs = [id_row.strip()[-7:-1] for id_row in id_rows] return jobs
python
def job_ids(log_stream): """Grep out all lines with scancel example.""" id_rows = [line for line in log_stream if 'scancel' in line] jobs = [id_row.strip()[-7:-1] for id_row in id_rows] return jobs
[ "def", "job_ids", "(", "log_stream", ")", ":", "id_rows", "=", "[", "line", "for", "line", "in", "log_stream", "if", "'scancel'", "in", "line", "]", "jobs", "=", "[", "id_row", ".", "strip", "(", ")", "[", "-", "7", ":", "-", "1", "]", "for", "id...
Grep out all lines with scancel example.
[ "Grep", "out", "all", "lines", "with", "scancel", "example", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/miplog.py#L3-L7
ARMmbed/autoversion
src/auto_version/config.py
get_or_create_config
def get_or_create_config(path, config): """Using TOML format, load config from given path, or write out example based on defaults""" if os.path.isfile(path): with open(path) as fh: _LOG.debug("loading config from %s", os.path.abspath(path)) config._inflate(toml.load(fh)) else...
python
def get_or_create_config(path, config): """Using TOML format, load config from given path, or write out example based on defaults""" if os.path.isfile(path): with open(path) as fh: _LOG.debug("loading config from %s", os.path.abspath(path)) config._inflate(toml.load(fh)) else...
[ "def", "get_or_create_config", "(", "path", ",", "config", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "with", "open", "(", "path", ")", "as", "fh", ":", "_LOG", ".", "debug", "(", "\"loading config from %s\"", ",", "os", ...
Using TOML format, load config from given path, or write out example based on defaults
[ "Using", "TOML", "format", "load", "config", "from", "given", "path", "or", "write", "out", "example", "based", "on", "defaults" ]
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/config.py#L81-L93
ARMmbed/autoversion
src/auto_version/config.py
AutoVersionConfig._deflate
def _deflate(cls): """Prepare for serialisation - returns a dictionary""" data = {k: v for k, v in vars(cls).items() if not k.startswith("_")} return {Constants.CONFIG_KEY: data}
python
def _deflate(cls): """Prepare for serialisation - returns a dictionary""" data = {k: v for k, v in vars(cls).items() if not k.startswith("_")} return {Constants.CONFIG_KEY: data}
[ "def", "_deflate", "(", "cls", ")", ":", "data", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "vars", "(", "cls", ")", ".", "items", "(", ")", "if", "not", "k", ".", "startswith", "(", "\"_\"", ")", "}", "return", "{", "Constants", "....
Prepare for serialisation - returns a dictionary
[ "Prepare", "for", "serialisation", "-", "returns", "a", "dictionary" ]
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/config.py#L68-L71
ARMmbed/autoversion
src/auto_version/config.py
AutoVersionConfig._inflate
def _inflate(cls, data): """Update config by deserialising input dictionary""" for k, v in data[Constants.CONFIG_KEY].items(): setattr(cls, k, v) return cls._deflate()
python
def _inflate(cls, data): """Update config by deserialising input dictionary""" for k, v in data[Constants.CONFIG_KEY].items(): setattr(cls, k, v) return cls._deflate()
[ "def", "_inflate", "(", "cls", ",", "data", ")", ":", "for", "k", ",", "v", "in", "data", "[", "Constants", ".", "CONFIG_KEY", "]", ".", "items", "(", ")", ":", "setattr", "(", "cls", ",", "k", ",", "v", ")", "return", "cls", ".", "_deflate", "...
Update config by deserialising input dictionary
[ "Update", "config", "by", "deserialising", "input", "dictionary" ]
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/config.py#L74-L78
fudge-py/fudge
fudge/patcher.py
with_patched_object
def with_patched_object(obj, attr_name, patched_value): """Decorator that patches an object before the decorated method is called and restores it afterwards. This is a wrapper around :func:`fudge.patcher.patch_object` Example:: >>> from fudge import with_patched_object >>> class Sessi...
python
def with_patched_object(obj, attr_name, patched_value): """Decorator that patches an object before the decorated method is called and restores it afterwards. This is a wrapper around :func:`fudge.patcher.patch_object` Example:: >>> from fudge import with_patched_object >>> class Sessi...
[ "def", "with_patched_object", "(", "obj", ",", "attr_name", ",", "patched_value", ")", ":", "def", "patcher", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "method_call", "(", "*", "m_args", ",", "*", "*", "m_kw", ")", ":", "patched...
Decorator that patches an object before the decorated method is called and restores it afterwards. This is a wrapper around :func:`fudge.patcher.patch_object` Example:: >>> from fudge import with_patched_object >>> class Session: ... state = 'clean' ... >>> @wi...
[ "Decorator", "that", "patches", "an", "object", "before", "the", "decorated", "method", "is", "called", "and", "restores", "it", "afterwards", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/patcher.py#L136-L167
fudge-py/fudge
fudge/patcher.py
patch_object
def patch_object(obj, attr_name, patched_value): """Patches an object and returns an instance of :class:`fudge.patcher.PatchHandler` for later restoration. Note that if *obj* is not an object but a path to a module then it will be imported. You may want to use a more convenient wrapper :func:`with_patched...
python
def patch_object(obj, attr_name, patched_value): """Patches an object and returns an instance of :class:`fudge.patcher.PatchHandler` for later restoration. Note that if *obj* is not an object but a path to a module then it will be imported. You may want to use a more convenient wrapper :func:`with_patched...
[ "def", "patch_object", "(", "obj", ",", "attr_name", ",", "patched_value", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "str", ",", "unicode", ")", ")", ":", "obj_path", "=", "adjusted_path", "=", "obj", "done", "=", "False", "exc", "=", "None",...
Patches an object and returns an instance of :class:`fudge.patcher.PatchHandler` for later restoration. Note that if *obj* is not an object but a path to a module then it will be imported. You may want to use a more convenient wrapper :func:`with_patched_object` or :func:`patched_context` Example:: ...
[ "Patches", "an", "object", "and", "returns", "an", "instance", "of", ":", "class", ":", "fudge", ".", "patcher", ".", "PatchHandler", "for", "later", "restoration", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/patcher.py#L208-L287
fudge-py/fudge
fudge/patcher.py
PatchHandler.patch
def patch(self, patched_value): """Set a new value for the attribute of the object.""" try: if self.getter: setattr(self.getter_class, self.attr_name, patched_value) else: setattr(self.orig_object, self.attr_name, patched_value) except Type...
python
def patch(self, patched_value): """Set a new value for the attribute of the object.""" try: if self.getter: setattr(self.getter_class, self.attr_name, patched_value) else: setattr(self.orig_object, self.attr_name, patched_value) except Type...
[ "def", "patch", "(", "self", ",", "patched_value", ")", ":", "try", ":", "if", "self", ".", "getter", ":", "setattr", "(", "self", ".", "getter_class", ",", "self", ".", "attr_name", ",", "patched_value", ")", "else", ":", "setattr", "(", "self", ".", ...
Set a new value for the attribute of the object.
[ "Set", "a", "new", "value", "for", "the", "attribute", "of", "the", "object", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/patcher.py#L309-L326
fudge-py/fudge
fudge/patcher.py
PatchHandler.restore
def restore(self): """Restore the saved value for the attribute of the object.""" if self.proxy_object is None: if self.getter: setattr(self.getter_class, self.attr_name, self.getter) elif self.is_local: setattr(self.orig_object, self.attr_name, se...
python
def restore(self): """Restore the saved value for the attribute of the object.""" if self.proxy_object is None: if self.getter: setattr(self.getter_class, self.attr_name, self.getter) elif self.is_local: setattr(self.orig_object, self.attr_name, se...
[ "def", "restore", "(", "self", ")", ":", "if", "self", ".", "proxy_object", "is", "None", ":", "if", "self", ".", "getter", ":", "setattr", "(", "self", ".", "getter_class", ",", "self", ".", "attr_name", ",", "self", ".", "getter", ")", "elif", "sel...
Restore the saved value for the attribute of the object.
[ "Restore", "the", "saved", "value", "for", "the", "attribute", "of", "the", "object", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/patcher.py#L328-L341
Clinical-Genomics/trailblazer
trailblazer/mip/files.py
parse_config
def parse_config(data: dict) -> dict: """Parse MIP config file. Args: data (dict): raw YAML input from MIP analysis config file Returns: dict: parsed data """ return { 'email': data.get('email'), 'family': data['family_id'], 'samples': [{ 'id': s...
python
def parse_config(data: dict) -> dict: """Parse MIP config file. Args: data (dict): raw YAML input from MIP analysis config file Returns: dict: parsed data """ return { 'email': data.get('email'), 'family': data['family_id'], 'samples': [{ 'id': s...
[ "def", "parse_config", "(", "data", ":", "dict", ")", "->", "dict", ":", "return", "{", "'email'", ":", "data", ".", "get", "(", "'email'", ")", ",", "'family'", ":", "data", "[", "'family_id'", "]", ",", "'samples'", ":", "[", "{", "'id'", ":", "s...
Parse MIP config file. Args: data (dict): raw YAML input from MIP analysis config file Returns: dict: parsed data
[ "Parse", "MIP", "config", "file", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/files.py#L9-L31
Clinical-Genomics/trailblazer
trailblazer/mip/files.py
parse_sampleinfo
def parse_sampleinfo(data: dict) -> dict: """Parse MIP sample info file. Args: data (dict): raw YAML input from MIP qc sample info file Returns: dict: parsed data """ genome_build = data['human_genome_build'] genome_build_str = f"{genome_build['source']}{genome_build['version'...
python
def parse_sampleinfo(data: dict) -> dict: """Parse MIP sample info file. Args: data (dict): raw YAML input from MIP qc sample info file Returns: dict: parsed data """ genome_build = data['human_genome_build'] genome_build_str = f"{genome_build['source']}{genome_build['version'...
[ "def", "parse_sampleinfo", "(", "data", ":", "dict", ")", "->", "dict", ":", "genome_build", "=", "data", "[", "'human_genome_build'", "]", "genome_build_str", "=", "f\"{genome_build['source']}{genome_build['version']}\"", "if", "'svdb'", "in", "data", "[", "'program'...
Parse MIP sample info file. Args: data (dict): raw YAML input from MIP qc sample info file Returns: dict: parsed data
[ "Parse", "MIP", "sample", "info", "file", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/files.py#L34-L100
Clinical-Genomics/trailblazer
trailblazer/mip/files.py
parse_qcmetrics
def parse_qcmetrics(metrics: dict) -> dict: """Parse MIP qc metrics file. Args: metrics (dict): raw YAML input from MIP qc metrics file Returns: dict: parsed data """ data = { 'versions': { 'freebayes': metrics['program']['freebayes']['version'], 'gat...
python
def parse_qcmetrics(metrics: dict) -> dict: """Parse MIP qc metrics file. Args: metrics (dict): raw YAML input from MIP qc metrics file Returns: dict: parsed data """ data = { 'versions': { 'freebayes': metrics['program']['freebayes']['version'], 'gat...
[ "def", "parse_qcmetrics", "(", "metrics", ":", "dict", ")", "->", "dict", ":", "data", "=", "{", "'versions'", ":", "{", "'freebayes'", ":", "metrics", "[", "'program'", "]", "[", "'freebayes'", "]", "[", "'version'", "]", ",", "'gatk'", ":", "metrics", ...
Parse MIP qc metrics file. Args: metrics (dict): raw YAML input from MIP qc metrics file Returns: dict: parsed data
[ "Parse", "MIP", "qc", "metrics", "file", ".", "Args", ":", "metrics", "(", "dict", ")", ":", "raw", "YAML", "input", "from", "MIP", "qc", "metrics", "file" ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/files.py#L103-L168
Clinical-Genomics/trailblazer
trailblazer/mip/files.py
parse_peddy_sexcheck
def parse_peddy_sexcheck(handle: TextIO): """Parse Peddy sexcheck output.""" data = {} samples = csv.DictReader(handle) for sample in samples: data[sample['sample_id']] = { 'predicted_sex': sample['predicted_sex'], 'het_ratio': float(sample['het_ratio']), 'err...
python
def parse_peddy_sexcheck(handle: TextIO): """Parse Peddy sexcheck output.""" data = {} samples = csv.DictReader(handle) for sample in samples: data[sample['sample_id']] = { 'predicted_sex': sample['predicted_sex'], 'het_ratio': float(sample['het_ratio']), 'err...
[ "def", "parse_peddy_sexcheck", "(", "handle", ":", "TextIO", ")", ":", "data", "=", "{", "}", "samples", "=", "csv", ".", "DictReader", "(", "handle", ")", "for", "sample", "in", "samples", ":", "data", "[", "sample", "[", "'sample_id'", "]", "]", "=",...
Parse Peddy sexcheck output.
[ "Parse", "Peddy", "sexcheck", "output", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/files.py#L171-L181
Clinical-Genomics/trailblazer
trailblazer/mip/files.py
parse_chanjo_sexcheck
def parse_chanjo_sexcheck(handle: TextIO): """Parse Chanjo sex-check output.""" samples = csv.DictReader(handle, delimiter='\t') for sample in samples: return { 'predicted_sex': sample['sex'], 'x_coverage': float(sample['#X_coverage']), 'y_coverage': float(sample[...
python
def parse_chanjo_sexcheck(handle: TextIO): """Parse Chanjo sex-check output.""" samples = csv.DictReader(handle, delimiter='\t') for sample in samples: return { 'predicted_sex': sample['sex'], 'x_coverage': float(sample['#X_coverage']), 'y_coverage': float(sample[...
[ "def", "parse_chanjo_sexcheck", "(", "handle", ":", "TextIO", ")", ":", "samples", "=", "csv", ".", "DictReader", "(", "handle", ",", "delimiter", "=", "'\\t'", ")", "for", "sample", "in", "samples", ":", "return", "{", "'predicted_sex'", ":", "sample", "[...
Parse Chanjo sex-check output.
[ "Parse", "Chanjo", "sex", "-", "check", "output", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/files.py#L184-L192
ozgurgunes/django-manifest
manifest/core/decorators.py
owner_required
def owner_required(Model=None): """ Usage: @owner_required(Entry) def manage_entry(request, pk=None, object=None): @owner_required() def entry_delete(*args, **kwargs): kwargs["post_delete_redirect"] = reverse('manage_blogs') return delete_object(*args, **kwargs) """...
python
def owner_required(Model=None): """ Usage: @owner_required(Entry) def manage_entry(request, pk=None, object=None): @owner_required() def entry_delete(*args, **kwargs): kwargs["post_delete_redirect"] = reverse('manage_blogs') return delete_object(*args, **kwargs) """...
[ "def", "owner_required", "(", "Model", "=", "None", ")", ":", "def", "decorator", "(", "view_func", ")", ":", "def", "_wrapped_view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "user", "=", "request", ".", "user", "grant", "...
Usage: @owner_required(Entry) def manage_entry(request, pk=None, object=None): @owner_required() def entry_delete(*args, **kwargs): kwargs["post_delete_redirect"] = reverse('manage_blogs') return delete_object(*args, **kwargs)
[ "Usage", ":" ]
train
https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/core/decorators.py#L7-L52
capless/valley
valley/utils/imports.py
import_util
def import_util(imp): ''' Lazily imports a utils (class, function,or variable) from a module) from a string. @param imp: ''' mod_name, obj_name = imp.rsplit('.', 1) mod = importlib.import_module(mod_name) return getattr(mod, obj_name)
python
def import_util(imp): ''' Lazily imports a utils (class, function,or variable) from a module) from a string. @param imp: ''' mod_name, obj_name = imp.rsplit('.', 1) mod = importlib.import_module(mod_name) return getattr(mod, obj_name)
[ "def", "import_util", "(", "imp", ")", ":", "mod_name", ",", "obj_name", "=", "imp", ".", "rsplit", "(", "'.'", ",", "1", ")", "mod", "=", "importlib", ".", "import_module", "(", "mod_name", ")", "return", "getattr", "(", "mod", ",", "obj_name", ")" ]
Lazily imports a utils (class, function,or variable) from a module) from a string. @param imp:
[ "Lazily", "imports", "a", "utils", "(", "class", "function", "or", "variable", ")", "from", "a", "module", ")", "from", "a", "string", "." ]
train
https://github.com/capless/valley/blob/491e4203e428a9e92264e204d44a1df96a570bbc/valley/utils/imports.py#L4-L14
ARMmbed/autoversion
src/auto_version/cli.py
get_cli
def get_cli(): """Load cli options""" parser = argparse.ArgumentParser( prog="auto_version", description="auto version v%s: a tool to control version numbers" % __version__, ) parser.add_argument( "--target", action="append", default=[], help="Files contai...
python
def get_cli(): """Load cli options""" parser = argparse.ArgumentParser( prog="auto_version", description="auto version v%s: a tool to control version numbers" % __version__, ) parser.add_argument( "--target", action="append", default=[], help="Files contai...
[ "def", "get_cli", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "\"auto_version\"", ",", "description", "=", "\"auto version v%s: a tool to control version numbers\"", "%", "__version__", ",", ")", "parser", ".", "add_argument", ...
Load cli options
[ "Load", "cli", "options" ]
train
https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/cli.py#L9-L71
bskinn/stdio-mgr
src/stdio_mgr/stdio_mgr.py
stdio_mgr
def stdio_mgr(in_str=""): r"""Subsitute temporary text buffers for `stdio` in a managed context. Context manager. Substitutes empty :cls:`~io.StringIO`\ s for :cls:`sys.stdout` and :cls:`sys.stderr`, and a :cls:`TeeStdin` for :cls:`sys.stdin` within the managed context. Upon exiting the conte...
python
def stdio_mgr(in_str=""): r"""Subsitute temporary text buffers for `stdio` in a managed context. Context manager. Substitutes empty :cls:`~io.StringIO`\ s for :cls:`sys.stdout` and :cls:`sys.stderr`, and a :cls:`TeeStdin` for :cls:`sys.stdin` within the managed context. Upon exiting the conte...
[ "def", "stdio_mgr", "(", "in_str", "=", "\"\"", ")", ":", "old_stdin", "=", "sys", ".", "stdin", "old_stdout", "=", "sys", ".", "stdout", "old_stderr", "=", "sys", ".", "stderr", "new_stdout", "=", "StringIO", "(", ")", "new_stderr", "=", "StringIO", "("...
r"""Subsitute temporary text buffers for `stdio` in a managed context. Context manager. Substitutes empty :cls:`~io.StringIO`\ s for :cls:`sys.stdout` and :cls:`sys.stderr`, and a :cls:`TeeStdin` for :cls:`sys.stdin` within the managed context. Upon exiting the context, the original stream object...
[ "r", "Subsitute", "temporary", "text", "buffers", "for", "stdio", "in", "a", "managed", "context", "." ]
train
https://github.com/bskinn/stdio-mgr/blob/dff9f326528aac67d7ca0dc0a86ce3dffa3e0d39/src/stdio_mgr/stdio_mgr.py#L139-L196
andrewda/frc-livescore
livescore/simpleocr_utils/opencv_utils.py
draw_segments
def draw_segments(image, segments, color=(255, 0, 0), line_width=1): """draws segments on image""" for segment in segments: x, y, w, h = segment cv2.rectangle(image, (x, y), (x + w, y + h), color, line_width)
python
def draw_segments(image, segments, color=(255, 0, 0), line_width=1): """draws segments on image""" for segment in segments: x, y, w, h = segment cv2.rectangle(image, (x, y), (x + w, y + h), color, line_width)
[ "def", "draw_segments", "(", "image", ",", "segments", ",", "color", "=", "(", "255", ",", "0", ",", "0", ")", ",", "line_width", "=", "1", ")", ":", "for", "segment", "in", "segments", ":", "x", ",", "y", ",", "w", ",", "h", "=", "segment", "c...
draws segments on image
[ "draws", "segments", "on", "image" ]
train
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/opencv_utils.py#L105-L109
andrewda/frc-livescore
livescore/simpleocr_utils/opencv_utils.py
draw_lines
def draw_lines(image, ys, color=(255, 0, 0), line_width=1): """draws horizontal lines""" for y in ys: cv2.line(image, (0, y), (image.shape[1], y), color, line_width)
python
def draw_lines(image, ys, color=(255, 0, 0), line_width=1): """draws horizontal lines""" for y in ys: cv2.line(image, (0, y), (image.shape[1], y), color, line_width)
[ "def", "draw_lines", "(", "image", ",", "ys", ",", "color", "=", "(", "255", ",", "0", ",", "0", ")", ",", "line_width", "=", "1", ")", ":", "for", "y", "in", "ys", ":", "cv2", ".", "line", "(", "image", ",", "(", "0", ",", "y", ")", ",", ...
draws horizontal lines
[ "draws", "horizontal", "lines" ]
train
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/opencv_utils.py#L112-L115
Clinical-Genomics/trailblazer
trailblazer/mip/sacct.py
time_to_sec
def time_to_sec(time_str: str) -> int: """Convert time in string format to seconds. Skipping seconds since sometimes the last column is truncated for entries where >10 days. """ total_sec = 0 if '-' in time_str: # parse out days days, time_str = time_str.split('-') total...
python
def time_to_sec(time_str: str) -> int: """Convert time in string format to seconds. Skipping seconds since sometimes the last column is truncated for entries where >10 days. """ total_sec = 0 if '-' in time_str: # parse out days days, time_str = time_str.split('-') total...
[ "def", "time_to_sec", "(", "time_str", ":", "str", ")", "->", "int", ":", "total_sec", "=", "0", "if", "'-'", "in", "time_str", ":", "# parse out days", "days", ",", "time_str", "=", "time_str", ".", "split", "(", "'-'", ")", "total_sec", "+=", "(", "i...
Convert time in string format to seconds. Skipping seconds since sometimes the last column is truncated for entries where >10 days.
[ "Convert", "time", "in", "string", "format", "to", "seconds", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/sacct.py#L9-L27
Clinical-Genomics/trailblazer
trailblazer/mip/sacct.py
convert_job
def convert_job(row: list) -> dict: """Convert sacct row to dict.""" state = row[-2] start_time_raw = row[-4] end_time_raw = row[-3] if state not in ('PENDING', 'CANCELLED'): start_time = datetime.strptime(start_time_raw, '%Y-%m-%dT%H:%M:%S') if state != 'RUNNING': end_ti...
python
def convert_job(row: list) -> dict: """Convert sacct row to dict.""" state = row[-2] start_time_raw = row[-4] end_time_raw = row[-3] if state not in ('PENDING', 'CANCELLED'): start_time = datetime.strptime(start_time_raw, '%Y-%m-%dT%H:%M:%S') if state != 'RUNNING': end_ti...
[ "def", "convert_job", "(", "row", ":", "list", ")", "->", "dict", ":", "state", "=", "row", "[", "-", "2", "]", "start_time_raw", "=", "row", "[", "-", "4", "]", "end_time_raw", "=", "row", "[", "-", "3", "]", "if", "state", "not", "in", "(", "...
Convert sacct row to dict.
[ "Convert", "sacct", "row", "to", "dict", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/sacct.py#L30-L59
Clinical-Genomics/trailblazer
trailblazer/mip/sacct.py
parse_sacct
def parse_sacct(sacct_stream): """Parse out information from sacct status output.""" rows = (line.split() for line in sacct_stream) # filter rows that begin with a SLURM job id relevant_rows = (row for row in rows if row[0].isdigit()) jobs = [convert_job(row) for row in relevant_rows] return job...
python
def parse_sacct(sacct_stream): """Parse out information from sacct status output.""" rows = (line.split() for line in sacct_stream) # filter rows that begin with a SLURM job id relevant_rows = (row for row in rows if row[0].isdigit()) jobs = [convert_job(row) for row in relevant_rows] return job...
[ "def", "parse_sacct", "(", "sacct_stream", ")", ":", "rows", "=", "(", "line", ".", "split", "(", ")", "for", "line", "in", "sacct_stream", ")", "# filter rows that begin with a SLURM job id", "relevant_rows", "=", "(", "row", "for", "row", "in", "rows", "if",...
Parse out information from sacct status output.
[ "Parse", "out", "information", "from", "sacct", "status", "output", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/sacct.py#L62-L68
Clinical-Genomics/trailblazer
trailblazer/mip/sacct.py
filter_jobs
def filter_jobs(sacct_jobs, failed=True): """Filter jobs that have a FAILED etc. status.""" categories = FAILED_CATEGORIES if failed else NORMAL_CATEGORIES filtered_jobs = [job for job in sacct_jobs if job['state'] in categories] return filtered_jobs
python
def filter_jobs(sacct_jobs, failed=True): """Filter jobs that have a FAILED etc. status.""" categories = FAILED_CATEGORIES if failed else NORMAL_CATEGORIES filtered_jobs = [job for job in sacct_jobs if job['state'] in categories] return filtered_jobs
[ "def", "filter_jobs", "(", "sacct_jobs", ",", "failed", "=", "True", ")", ":", "categories", "=", "FAILED_CATEGORIES", "if", "failed", "else", "NORMAL_CATEGORIES", "filtered_jobs", "=", "[", "job", "for", "job", "in", "sacct_jobs", "if", "job", "[", "'state'",...
Filter jobs that have a FAILED etc. status.
[ "Filter", "jobs", "that", "have", "a", "FAILED", "etc", ".", "status", "." ]
train
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/sacct.py#L71-L75
andrewda/frc-livescore
livescore/simpleocr_utils/segmentation_aux.py
guess_segments_lines
def guess_segments_lines(segments, lines, nearline_tolerance=5.0): """ given segments, outputs a array of line numbers, or -1 if it doesn't belong to any """ ys = segments[:, 1] closeness = numpy.abs(numpy.subtract.outer(ys, lines)) # each row a y, each collumn a distance to each line line_...
python
def guess_segments_lines(segments, lines, nearline_tolerance=5.0): """ given segments, outputs a array of line numbers, or -1 if it doesn't belong to any """ ys = segments[:, 1] closeness = numpy.abs(numpy.subtract.outer(ys, lines)) # each row a y, each collumn a distance to each line line_...
[ "def", "guess_segments_lines", "(", "segments", ",", "lines", ",", "nearline_tolerance", "=", "5.0", ")", ":", "ys", "=", "segments", "[", ":", ",", "1", "]", "closeness", "=", "numpy", ".", "abs", "(", "numpy", ".", "subtract", ".", "outer", "(", "ys"...
given segments, outputs a array of line numbers, or -1 if it doesn't belong to any
[ "given", "segments", "outputs", "a", "array", "of", "line", "numbers", "or", "-", "1", "if", "it", "doesn", "t", "belong", "to", "any" ]
train
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/segmentation_aux.py#L88-L99
andrewda/frc-livescore
livescore/simpleocr_utils/segmentation_aux.py
contained_segments_matrix
def contained_segments_matrix(segments): """ givens a n*n matrix m, n=len(segments), in which m[i,j] means segments[i] is contained inside segments[j] """ x1, y1 = segments[:, 0], segments[:, 1] x2, y2 = x1 + segments[:, 2], y1 + segments[:, 3] n = len(segments) x1so, x2so, y1so, y2so =...
python
def contained_segments_matrix(segments): """ givens a n*n matrix m, n=len(segments), in which m[i,j] means segments[i] is contained inside segments[j] """ x1, y1 = segments[:, 0], segments[:, 1] x2, y2 = x1 + segments[:, 2], y1 + segments[:, 3] n = len(segments) x1so, x2so, y1so, y2so =...
[ "def", "contained_segments_matrix", "(", "segments", ")", ":", "x1", ",", "y1", "=", "segments", "[", ":", ",", "0", "]", ",", "segments", "[", ":", ",", "1", "]", "x2", ",", "y2", "=", "x1", "+", "segments", "[", ":", ",", "2", "]", ",", "y1",...
givens a n*n matrix m, n=len(segments), in which m[i,j] means segments[i] is contained inside segments[j]
[ "givens", "a", "n", "*", "n", "matrix", "m", "n", "=", "len", "(", "segments", ")", "in", "which", "m", "[", "i", "j", "]", "means", "segments", "[", "i", "]", "is", "contained", "inside", "segments", "[", "j", "]" ]
train
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/segmentation_aux.py#L102-L120
andrewda/frc-livescore
livescore/simpleocr_utils/segmentation_aux.py
SegmentOrderer._process
def _process(self, segments): """sort segments in read order - left to right, up to down""" # sort_f= lambda r: max_line_width*(r[1]/max_line_height)+r[0] # segments= sorted(segments, key=sort_f) # segments= segments_to_numpy( segments ) # return segments mlh, mlw = self....
python
def _process(self, segments): """sort segments in read order - left to right, up to down""" # sort_f= lambda r: max_line_width*(r[1]/max_line_height)+r[0] # segments= sorted(segments, key=sort_f) # segments= segments_to_numpy( segments ) # return segments mlh, mlw = self....
[ "def", "_process", "(", "self", ",", "segments", ")", ":", "# sort_f= lambda r: max_line_width*(r[1]/max_line_height)+r[0]", "# segments= sorted(segments, key=sort_f)", "# segments= segments_to_numpy( segments )", "# return segments", "mlh", ",", "mlw", "=", "self", ".", "max_lin...
sort segments in read order - left to right, up to down
[ "sort", "segments", "in", "read", "order", "-", "left", "to", "right", "up", "to", "down" ]
train
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/segmentation_aux.py#L11-L21
andrewda/frc-livescore
livescore/simpleocr_utils/segmentation_aux.py
LineFinder._guess_lines
def _guess_lines(ys, max_lines=50, confidence_minimum=0.0): """guesses and returns text inter-line distance, number of lines, y_position of first line""" ys = ys.astype(numpy.float32) compactness_list, means_list, diffs, deviations = [], [], [], [] start_n = 1 for k in range(star...
python
def _guess_lines(ys, max_lines=50, confidence_minimum=0.0): """guesses and returns text inter-line distance, number of lines, y_position of first line""" ys = ys.astype(numpy.float32) compactness_list, means_list, diffs, deviations = [], [], [], [] start_n = 1 for k in range(star...
[ "def", "_guess_lines", "(", "ys", ",", "max_lines", "=", "50", ",", "confidence_minimum", "=", "0.0", ")", ":", "ys", "=", "ys", ".", "astype", "(", "numpy", ".", "float32", ")", "compactness_list", ",", "means_list", ",", "diffs", ",", "deviations", "="...
guesses and returns text inter-line distance, number of lines, y_position of first line
[ "guesses", "and", "returns", "text", "inter", "-", "line", "distance", "number", "of", "lines", "y_position", "of", "first", "line" ]
train
https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/segmentation_aux.py#L26-L63
pytroll/posttroll
posttroll/message_broadcaster.py
DesignatedReceiversSender._send_to_address
def _send_to_address(self, address, data, timeout=10): """send data to *address* and *port* without verification of response. """ # Socket to talk to server socket = get_context().socket(REQ) try: socket.setsockopt(LINGER, timeout * 1000) if address.find("...
python
def _send_to_address(self, address, data, timeout=10): """send data to *address* and *port* without verification of response. """ # Socket to talk to server socket = get_context().socket(REQ) try: socket.setsockopt(LINGER, timeout * 1000) if address.find("...
[ "def", "_send_to_address", "(", "self", ",", "address", ",", "data", ",", "timeout", "=", "10", ")", ":", "# Socket to talk to server", "socket", "=", "get_context", "(", ")", ".", "socket", "(", "REQ", ")", "try", ":", "socket", ".", "setsockopt", "(", ...
send data to *address* and *port* without verification of response.
[ "send", "data", "to", "*", "address", "*", "and", "*", "port", "*", "without", "verification", "of", "response", "." ]
train
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message_broadcaster.py#L55-L72
pytroll/posttroll
posttroll/message_broadcaster.py
MessageBroadcaster._run
def _run(self): """Broadcasts forever. """ self._is_running = True network_fail = False try: while self._do_run: try: if network_fail is True: LOGGER.info("Network connection re-established!") ...
python
def _run(self): """Broadcasts forever. """ self._is_running = True network_fail = False try: while self._do_run: try: if network_fail is True: LOGGER.info("Network connection re-established!") ...
[ "def", "_run", "(", "self", ")", ":", "self", ".", "_is_running", "=", "True", "network_fail", "=", "False", "try", ":", "while", "self", ".", "_do_run", ":", "try", ":", "if", "network_fail", "is", "True", ":", "LOGGER", ".", "info", "(", "\"Network c...
Broadcasts forever.
[ "Broadcasts", "forever", "." ]
train
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/message_broadcaster.py#L127-L150
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.from_json
def from_json(self, json): """Create resource out of JSON data. :param json: JSON dict. :return: Resource with a type defined by the given JSON data. """ res_type = json['sys']['type'] if ResourceType.Array.value == res_type: return self.create_array(json) ...
python
def from_json(self, json): """Create resource out of JSON data. :param json: JSON dict. :return: Resource with a type defined by the given JSON data. """ res_type = json['sys']['type'] if ResourceType.Array.value == res_type: return self.create_array(json) ...
[ "def", "from_json", "(", "self", ",", "json", ")", ":", "res_type", "=", "json", "[", "'sys'", "]", "[", "'type'", "]", "if", "ResourceType", ".", "Array", ".", "value", "==", "res_type", ":", "return", "self", ".", "create_array", "(", "json", ")", ...
Create resource out of JSON data. :param json: JSON dict. :return: Resource with a type defined by the given JSON data.
[ "Create", "resource", "out", "of", "JSON", "data", "." ]
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L34-L51
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.create_entry
def create_entry(self, json): """Create :class:`.resources.Entry` from JSON. :param json: JSON dict. :return: Entry instance. """ sys = json['sys'] ct = sys['contentType']['sys']['id'] fields = json['fields'] raw_fields = copy.deepcopy(fields) # ...
python
def create_entry(self, json): """Create :class:`.resources.Entry` from JSON. :param json: JSON dict. :return: Entry instance. """ sys = json['sys'] ct = sys['contentType']['sys']['id'] fields = json['fields'] raw_fields = copy.deepcopy(fields) # ...
[ "def", "create_entry", "(", "self", ",", "json", ")", ":", "sys", "=", "json", "[", "'sys'", "]", "ct", "=", "sys", "[", "'contentType'", "]", "[", "'sys'", "]", "[", "'id'", "]", "fields", "=", "json", "[", "'fields'", "]", "raw_fields", "=", "cop...
Create :class:`.resources.Entry` from JSON. :param json: JSON dict. :return: Entry instance.
[ "Create", ":", "class", ":", ".", "resources", ".", "Entry", "from", "JSON", "." ]
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L64-L101
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.create_asset
def create_asset(json): """Create :class:`.resources.Asset` from JSON. :param json: JSON dict. :return: Asset instance. """ result = Asset(json['sys']) file_dict = json['fields']['file'] result.fields = json['fields'] result.url = file_dict['url'] ...
python
def create_asset(json): """Create :class:`.resources.Asset` from JSON. :param json: JSON dict. :return: Asset instance. """ result = Asset(json['sys']) file_dict = json['fields']['file'] result.fields = json['fields'] result.url = file_dict['url'] ...
[ "def", "create_asset", "(", "json", ")", ":", "result", "=", "Asset", "(", "json", "[", "'sys'", "]", ")", "file_dict", "=", "json", "[", "'fields'", "]", "[", "'file'", "]", "result", ".", "fields", "=", "json", "[", "'fields'", "]", "result", ".", ...
Create :class:`.resources.Asset` from JSON. :param json: JSON dict. :return: Asset instance.
[ "Create", ":", "class", ":", ".", "resources", ".", "Asset", "from", "JSON", "." ]
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L104-L115
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.create_content_type
def create_content_type(json): """Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance. """ result = ContentType(json['sys']) for field in json['fields']: field_id = field['id'] del field['id'] ...
python
def create_content_type(json): """Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance. """ result = ContentType(json['sys']) for field in json['fields']: field_id = field['id'] del field['id'] ...
[ "def", "create_content_type", "(", "json", ")", ":", "result", "=", "ContentType", "(", "json", "[", "'sys'", "]", ")", "for", "field", "in", "json", "[", "'fields'", "]", ":", "field_id", "=", "field", "[", "'id'", "]", "del", "field", "[", "'id'", ...
Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance.
[ "Create", ":", "class", ":", ".", "resource", ".", "ContentType", "from", "JSON", "." ]
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L118-L134
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.convert_value
def convert_value(value, field): """Given a :class:`.fields.Field` and a value, ensure that the value matches the given type, otherwise attempt to convert it. :param value: field value. :param field: :class:`.fields.Field` instance. :return: Result value. """ clz...
python
def convert_value(value, field): """Given a :class:`.fields.Field` and a value, ensure that the value matches the given type, otherwise attempt to convert it. :param value: field value. :param field: :class:`.fields.Field` instance. :return: Result value. """ clz...
[ "def", "convert_value", "(", "value", ",", "field", ")", ":", "clz", "=", "field", ".", "field_type", "if", "clz", "is", "Boolean", ":", "if", "not", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "bool", "(", "value", ")", "elif", "clz...
Given a :class:`.fields.Field` and a value, ensure that the value matches the given type, otherwise attempt to convert it. :param value: field value. :param field: :class:`.fields.Field` instance. :return: Result value.
[ "Given", "a", ":", "class", ":", ".", "fields", ".", "Field", "and", "a", "value", "ensure", "that", "the", "value", "matches", "the", "given", "type", "otherwise", "attempt", "to", "convert", "it", "." ]
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L148-L186
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.process_array_items
def process_array_items(self, array, json): """Iterate through all `items` and create a resource for each. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary. """ for item in...
python
def process_array_items(self, array, json): """Iterate through all `items` and create a resource for each. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary. """ for item in...
[ "def", "process_array_items", "(", "self", ",", "array", ",", "json", ")", ":", "for", "item", "in", "json", "[", "'items'", "]", ":", "key", "=", "None", "processed", "=", "self", ".", "from_json", "(", "item", ")", "if", "isinstance", "(", "processed...
Iterate through all `items` and create a resource for each. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary.
[ "Iterate", "through", "all", "items", "and", "create", "a", "resource", "for", "each", "." ]
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L189-L209
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.process_array_includes
def process_array_includes(self, array, json): """Iterate through all `includes` and create a resource for every item. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary. """ ...
python
def process_array_includes(self, array, json): """Iterate through all `includes` and create a resource for every item. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary. """ ...
[ "def", "process_array_includes", "(", "self", ",", "array", ",", "json", ")", ":", "includes", "=", "json", ".", "get", "(", "'includes'", ")", "or", "{", "}", "for", "key", "in", "array", ".", "items_mapped", ".", "keys", "(", ")", ":", "if", "key",...
Iterate through all `includes` and create a resource for every item. In addition map the resources under the `items_mapped` by the resource id and type. :param array: Array resource. :param json: Raw JSON dictionary.
[ "Iterate", "through", "all", "includes", "and", "create", "a", "resource", "for", "every", "item", "." ]
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L211-L224
contentful-labs/contentful.py
contentful/cda/serialization.py
ResourceFactory.create_array
def create_array(self, json): """Create :class:`.resources.Array` from JSON. :param json: JSON dict. :return: Array instance. """ result = Array(json['sys']) result.total = json['total'] result.skip = json['skip'] result.limit = json['limit'] resu...
python
def create_array(self, json): """Create :class:`.resources.Array` from JSON. :param json: JSON dict. :return: Array instance. """ result = Array(json['sys']) result.total = json['total'] result.skip = json['skip'] result.limit = json['limit'] resu...
[ "def", "create_array", "(", "self", ",", "json", ")", ":", "result", "=", "Array", "(", "json", "[", "'sys'", "]", ")", "result", ".", "total", "=", "json", "[", "'total'", "]", "result", ".", "skip", "=", "json", "[", "'skip'", "]", "result", ".",...
Create :class:`.resources.Array` from JSON. :param json: JSON dict. :return: Array instance.
[ "Create", ":", "class", ":", ".", "resources", ".", "Array", "from", "JSON", "." ]
train
https://github.com/contentful-labs/contentful.py/blob/d9eb4a68abcad33e4766e2be8c7b35e605210b5a/contentful/cda/serialization.py#L226-L242
fudge-py/fudge
fudge/__init__.py
with_fakes
def with_fakes(method): """Decorator that calls :func:`fudge.clear_calls` before method() and :func:`fudge.verify` afterwards. """ @wraps(method) def apply_clear_and_verify(*args, **kw): clear_calls() method(*args, **kw) verify() # if no exceptions return apply_clear_and_veri...
python
def with_fakes(method): """Decorator that calls :func:`fudge.clear_calls` before method() and :func:`fudge.verify` afterwards. """ @wraps(method) def apply_clear_and_verify(*args, **kw): clear_calls() method(*args, **kw) verify() # if no exceptions return apply_clear_and_veri...
[ "def", "with_fakes", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "apply_clear_and_verify", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "clear_calls", "(", ")", "method", "(", "*", "args", ",", "*", "*", "kw", ")", "verify...
Decorator that calls :func:`fudge.clear_calls` before method() and :func:`fudge.verify` afterwards.
[ "Decorator", "that", "calls", ":", "func", ":", "fudge", ".", "clear_calls", "before", "method", "()", "and", ":", "func", ":", "fudge", ".", "verify", "afterwards", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L162-L170
fudge-py/fudge
fudge/__init__.py
Registry.clear_calls
def clear_calls(self): """Clears out any calls that were made on previously registered fake objects and resets all call stacks. You do not need to use this directly. Use fudge.clear_calls() """ self.clear_actual_calls() for stack in self.call_stacks: stack.r...
python
def clear_calls(self): """Clears out any calls that were made on previously registered fake objects and resets all call stacks. You do not need to use this directly. Use fudge.clear_calls() """ self.clear_actual_calls() for stack in self.call_stacks: stack.r...
[ "def", "clear_calls", "(", "self", ")", ":", "self", ".", "clear_actual_calls", "(", ")", "for", "stack", "in", "self", ".", "call_stacks", ":", "stack", ".", "reset", "(", ")", "for", "fake", ",", "call_order", "in", "self", ".", "get_expected_call_order"...
Clears out any calls that were made on previously registered fake objects and resets all call stacks. You do not need to use this directly. Use fudge.clear_calls()
[ "Clears", "out", "any", "calls", "that", "were", "made", "on", "previously", "registered", "fake", "objects", "and", "resets", "all", "call", "stacks", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L43-L53
fudge-py/fudge
fudge/__init__.py
Registry.verify
def verify(self): """Ensure all expected calls were called, raise AssertionError otherwise. You do not need to use this directly. Use fudge.verify() """ try: for exp in self.get_expected_calls(): exp.assert_called() exp.assert_times_c...
python
def verify(self): """Ensure all expected calls were called, raise AssertionError otherwise. You do not need to use this directly. Use fudge.verify() """ try: for exp in self.get_expected_calls(): exp.assert_called() exp.assert_times_c...
[ "def", "verify", "(", "self", ")", ":", "try", ":", "for", "exp", "in", "self", ".", "get_expected_calls", "(", ")", ":", "exp", ".", "assert_called", "(", ")", "exp", ".", "assert_times_called", "(", ")", "for", "fake", ",", "call_order", "in", "self"...
Ensure all expected calls were called, raise AssertionError otherwise. You do not need to use this directly. Use fudge.verify()
[ "Ensure", "all", "expected", "calls", "were", "called", "raise", "AssertionError", "otherwise", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L87-L100
fudge-py/fudge
fudge/__init__.py
ExpectedCallOrder.assert_order_met
def assert_order_met(self, finalize=False): """assert that calls have been made in the right order.""" error = None actual_call_len = len(self._actual_calls) expected_call_len = len(self._call_order) if actual_call_len == 0: error = "Not enough calls were made" ...
python
def assert_order_met(self, finalize=False): """assert that calls have been made in the right order.""" error = None actual_call_len = len(self._actual_calls) expected_call_len = len(self._call_order) if actual_call_len == 0: error = "Not enough calls were made" ...
[ "def", "assert_order_met", "(", "self", ",", "finalize", "=", "False", ")", ":", "error", "=", "None", "actual_call_len", "=", "len", "(", "self", ".", "_actual_calls", ")", "expected_call_len", "=", "len", "(", "self", ".", "_call_order", ")", "if", "actu...
assert that calls have been made in the right order.
[ "assert", "that", "calls", "have", "been", "made", "in", "the", "right", "order", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L482-L522
fudge-py/fudge
fudge/__init__.py
Fake.expects_call
def expects_call(self): """The fake must be called. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() This is useful for when you stub out a function as opposed to a class. For example:: ...
python
def expects_call(self): """The fake must be called. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() This is useful for when you stub out a function as opposed to a class. For example:: ...
[ "def", "expects_call", "(", "self", ")", ":", "self", ".", "_callable", "=", "ExpectedCall", "(", "self", ",", "call_name", "=", "self", ".", "_name", ",", "callable", "=", "True", ")", "return", "self" ]
The fake must be called. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge ...
[ "The", "fake", "must", "be", "called", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L777-L805
fudge-py/fudge
fudge/__init__.py
Fake.is_callable
def is_callable(self): """The fake can be called. This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge >>> remove = Fake('os.remove').is_callable() >>> remove('some/path') """ self._callable ...
python
def is_callable(self): """The fake can be called. This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge >>> remove = Fake('os.remove').is_callable() >>> remove('some/path') """ self._callable ...
[ "def", "is_callable", "(", "self", ")", ":", "self", ".", "_callable", "=", "Call", "(", "self", ",", "call_name", "=", "self", ".", "_name", ",", "callable", "=", "True", ")", "return", "self" ]
The fake can be called. This is useful for when you stub out a function as opposed to a class. For example:: >>> import fudge >>> remove = Fake('os.remove').is_callable() >>> remove('some/path')
[ "The", "fake", "can", "be", "called", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L807-L819
fudge-py/fudge
fudge/__init__.py
Fake.calls
def calls(self, call): """Redefine a call. The fake method will execute your function. I.E.:: >>> f = Fake().provides('hello').calls(lambda: 'Why, hello there') >>> f.hello() 'Why, hello there' """ exp = self._get_current_call() exp.call_re...
python
def calls(self, call): """Redefine a call. The fake method will execute your function. I.E.:: >>> f = Fake().provides('hello').calls(lambda: 'Why, hello there') >>> f.hello() 'Why, hello there' """ exp = self._get_current_call() exp.call_re...
[ "def", "calls", "(", "self", ",", "call", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "exp", ".", "call_replacement", "=", "call", "return", "self" ]
Redefine a call. The fake method will execute your function. I.E.:: >>> f = Fake().provides('hello').calls(lambda: 'Why, hello there') >>> f.hello() 'Why, hello there'
[ "Redefine", "a", "call", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L832-L844
fudge-py/fudge
fudge/__init__.py
Fake.expects
def expects(self, call_name): """Expect a call. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() If the method *call_name* is never called, then raise an error. I.E.:: >>> session = Fake('...
python
def expects(self, call_name): """Expect a call. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() If the method *call_name* is never called, then raise an error. I.E.:: >>> session = Fake('...
[ "def", "expects", "(", "self", ",", "call_name", ")", ":", "if", "call_name", "in", "self", ".", "_declared_calls", ":", "return", "self", ".", "next_call", "(", "for_method", "=", "call_name", ")", "self", ".", "_last_declared_call_name", "=", "call_name", ...
Expect a call. .. doctest:: :hide: >>> import fudge >>> fudge.clear_expectations() >>> fudge.clear_calls() If the method *call_name* is never called, then raise an error. I.E.:: >>> session = Fake('session').expects('open').expects('close'...
[ "Expect", "a", "call", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L846-L879
fudge-py/fudge
fudge/__init__.py
Fake.next_call
def next_call(self, for_method=None): """Start expecting or providing multiple calls. .. note:: next_call() cannot be used in combination with :func:`fudge.Fake.times_called` Up until calling this method, calls are infinite. For example, before next_call() ... :: >>> from...
python
def next_call(self, for_method=None): """Start expecting or providing multiple calls. .. note:: next_call() cannot be used in combination with :func:`fudge.Fake.times_called` Up until calling this method, calls are infinite. For example, before next_call() ... :: >>> from...
[ "def", "next_call", "(", "self", ",", "for_method", "=", "None", ")", ":", "last_call_name", "=", "self", ".", "_last_declared_call_name", "if", "for_method", ":", "if", "for_method", "not", "in", "self", ".", "_declared_calls", ":", "raise", "FakeDeclarationErr...
Start expecting or providing multiple calls. .. note:: next_call() cannot be used in combination with :func:`fudge.Fake.times_called` Up until calling this method, calls are infinite. For example, before next_call() ... :: >>> from fudge import Fake >>> f = Fake().pro...
[ "Start", "expecting", "or", "providing", "multiple", "calls", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L914-L1016
fudge-py/fudge
fudge/__init__.py
Fake.provides
def provides(self, call_name): """Provide a call. The call acts as a stub -- no error is raised if it is not called.:: >>> session = Fake('session').provides('open').provides('close') >>> import fudge >>> fudge.clear_expectations() # from any previously declared fak...
python
def provides(self, call_name): """Provide a call. The call acts as a stub -- no error is raised if it is not called.:: >>> session = Fake('session').provides('open').provides('close') >>> import fudge >>> fudge.clear_expectations() # from any previously declared fak...
[ "def", "provides", "(", "self", ",", "call_name", ")", ":", "if", "call_name", "in", "self", ".", "_declared_calls", ":", "return", "self", ".", "next_call", "(", "for_method", "=", "call_name", ")", "self", ".", "_last_declared_call_name", "=", "call_name", ...
Provide a call. The call acts as a stub -- no error is raised if it is not called.:: >>> session = Fake('session').provides('open').provides('close') >>> import fudge >>> fudge.clear_expectations() # from any previously declared fakes >>> fudge.clear_calls() ...
[ "Provide", "a", "call", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1018-L1040
fudge-py/fudge
fudge/__init__.py
Fake.raises
def raises(self, exc): """Set last call to raise an exception class or instance. For example:: >>> import fudge >>> db = fudge.Fake('db').provides('insert').raises(ValueError("not enough parameters for insert")) >>> db.insert() Traceback (most recent cal...
python
def raises(self, exc): """Set last call to raise an exception class or instance. For example:: >>> import fudge >>> db = fudge.Fake('db').provides('insert').raises(ValueError("not enough parameters for insert")) >>> db.insert() Traceback (most recent cal...
[ "def", "raises", "(", "self", ",", "exc", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "exp", ".", "exception_to_raise", "=", "exc", "return", "self" ]
Set last call to raise an exception class or instance. For example:: >>> import fudge >>> db = fudge.Fake('db').provides('insert').raises(ValueError("not enough parameters for insert")) >>> db.insert() Traceback (most recent call last): ... ...
[ "Set", "last", "call", "to", "raise", "an", "exception", "class", "or", "instance", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1042-L1057
fudge-py/fudge
fudge/__init__.py
Fake.remember_order
def remember_order(self): """Verify that subsequent :func:`fudge.Fake.expects` are called in the right order. For example:: >>> import fudge >>> db = fudge.Fake('db').remember_order().expects('insert').expects('update') >>> db.update() Traceback (most re...
python
def remember_order(self): """Verify that subsequent :func:`fudge.Fake.expects` are called in the right order. For example:: >>> import fudge >>> db = fudge.Fake('db').remember_order().expects('insert').expects('update') >>> db.update() Traceback (most re...
[ "def", "remember_order", "(", "self", ")", ":", "if", "self", ".", "_callable", ":", "raise", "FakeDeclarationError", "(", "\"remember_order() cannot be used for Fake(callable=True) or Fake(expect_call=True)\"", ")", "self", ".", "_expected_call_order", "=", "ExpectedCallOrde...
Verify that subsequent :func:`fudge.Fake.expects` are called in the right order. For example:: >>> import fudge >>> db = fudge.Fake('db').remember_order().expects('insert').expects('update') >>> db.update() Traceback (most recent call last): ... ...
[ "Verify", "that", "subsequent", ":", "func", ":", "fudge", ".", "Fake", ".", "expects", "are", "called", "in", "the", "right", "order", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1059-L1096
fudge-py/fudge
fudge/__init__.py
Fake.returns
def returns(self, val): """Set the last call to return a value. Set a static value to return when a method is called. I.E.:: >>> f = Fake().provides('get_number').returns(64) >>> f.get_number() 64 """ exp = self._get_current_call() exp.retu...
python
def returns(self, val): """Set the last call to return a value. Set a static value to return when a method is called. I.E.:: >>> f = Fake().provides('get_number').returns(64) >>> f.get_number() 64 """ exp = self._get_current_call() exp.retu...
[ "def", "returns", "(", "self", ",", "val", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "exp", ".", "return_val", "=", "val", "return", "self" ]
Set the last call to return a value. Set a static value to return when a method is called. I.E.:: >>> f = Fake().provides('get_number').returns(64) >>> f.get_number() 64
[ "Set", "the", "last", "call", "to", "return", "a", "value", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1098-L1110
fudge-py/fudge
fudge/__init__.py
Fake.returns_fake
def returns_fake(self, *args, **kwargs): """Set the last call to return a new :class:`fudge.Fake`. Any given arguments are passed to the :class:`fudge.Fake` constructor Take note that this is different from the cascading nature of other methods. This will return an instance of the *ne...
python
def returns_fake(self, *args, **kwargs): """Set the last call to return a new :class:`fudge.Fake`. Any given arguments are passed to the :class:`fudge.Fake` constructor Take note that this is different from the cascading nature of other methods. This will return an instance of the *ne...
[ "def", "returns_fake", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "endpoint", "=", "kwargs", ".", "get", "(", "'name'", ",", "exp", ".", "call_name", ")", "name", "=", "...
Set the last call to return a new :class:`fudge.Fake`. Any given arguments are passed to the :class:`fudge.Fake` constructor Take note that this is different from the cascading nature of other methods. This will return an instance of the *new* Fake, not self, so you should be careful ...
[ "Set", "the", "last", "call", "to", "return", "a", "new", ":", "class", ":", "fudge", ".", "Fake", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1112-L1139
fudge-py/fudge
fudge/__init__.py
Fake.times_called
def times_called(self, n): """Set the number of times an object can be called. When working with provided calls, you'll only see an error if the expected call count is exceeded :: >>> auth = Fake('auth').provides('login').times_called(1) >>> auth.login() >>>...
python
def times_called(self, n): """Set the number of times an object can be called. When working with provided calls, you'll only see an error if the expected call count is exceeded :: >>> auth = Fake('auth').provides('login').times_called(1) >>> auth.login() >>>...
[ "def", "times_called", "(", "self", ",", "n", ")", ":", "if", "self", ".", "_last_declared_call_name", ":", "actual_last_call", "=", "self", ".", "_declared_calls", "[", "self", ".", "_last_declared_call_name", "]", "if", "isinstance", "(", "actual_last_call", "...
Set the number of times an object can be called. When working with provided calls, you'll only see an error if the expected call count is exceeded :: >>> auth = Fake('auth').provides('login').times_called(1) >>> auth.login() >>> auth.login() Traceback (m...
[ "Set", "the", "number", "of", "times", "an", "object", "can", "be", "called", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1141-L1176
fudge-py/fudge
fudge/__init__.py
Fake.with_args
def with_args(self, *args, **kwargs): """Set the last call to expect specific argument values. The app under test must send all declared arguments and keyword arguments otherwise your test will raise an AssertionError. For example: .. doctest:: >>> import fudge ...
python
def with_args(self, *args, **kwargs): """Set the last call to expect specific argument values. The app under test must send all declared arguments and keyword arguments otherwise your test will raise an AssertionError. For example: .. doctest:: >>> import fudge ...
[ "def", "with_args", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "if", "args", ":", "exp", ".", "expected_args", "=", "args", "if", "kwargs", ":", "exp", ".", "expected_kwar...
Set the last call to expect specific argument values. The app under test must send all declared arguments and keyword arguments otherwise your test will raise an AssertionError. For example: .. doctest:: >>> import fudge >>> counter = fudge.Fake('counter').expects('in...
[ "Set", "the", "last", "call", "to", "expect", "specific", "argument", "values", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1178-L1243
fudge-py/fudge
fudge/__init__.py
Fake.with_matching_args
def with_matching_args(self, *args, **kwargs): """Set the last call to expect specific argument values if those arguments exist. Unlike :func:`fudge.Fake.with_args` use this if you want to only declare expectations about matching arguments. Any unknown keyword arguments used by the app...
python
def with_matching_args(self, *args, **kwargs): """Set the last call to expect specific argument values if those arguments exist. Unlike :func:`fudge.Fake.with_args` use this if you want to only declare expectations about matching arguments. Any unknown keyword arguments used by the app...
[ "def", "with_matching_args", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "if", "args", ":", "exp", ".", "expected_matching_args", "=", "args", "if", "kwargs", ":", "exp", "."...
Set the last call to expect specific argument values if those arguments exist. Unlike :func:`fudge.Fake.with_args` use this if you want to only declare expectations about matching arguments. Any unknown keyword arguments used by the app under test will be allowed. For example, you can...
[ "Set", "the", "last", "call", "to", "expect", "specific", "argument", "values", "if", "those", "arguments", "exist", "." ]
train
https://github.com/fudge-py/fudge/blob/b283fbc1a41900f3f5845b10b8c2ef9136a67ebc/fudge/__init__.py#L1245-L1283