Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
SetupState.addfinalizer
(self, finalizer, colitem)
attach a finalizer to the given colitem. if colitem is None, this will add a finalizer that is called at the end of teardown_all().
attach a finalizer to the given colitem. if colitem is None, this will add a finalizer that is called at the end of teardown_all().
def addfinalizer(self, finalizer, colitem): """ attach a finalizer to the given colitem. if colitem is None, this will add a finalizer that is called at the end of teardown_all(). """ assert colitem and not isinstance(colitem, tuple) assert callable(finalizer) # a...
[ "def", "addfinalizer", "(", "self", ",", "finalizer", ",", "colitem", ")", ":", "assert", "colitem", "and", "not", "isinstance", "(", "colitem", ",", "tuple", ")", "assert", "callable", "(", "finalizer", ")", "# assert colitem in self.stack # some unit tests don't ...
[ 428, 4 ]
[ 436, 66 ]
python
en
['en', 'en', 'en']
True
SetupState.prepare
(self, colitem)
setup objects along the collector chain to the test-method and teardown previously setup objects.
setup objects along the collector chain to the test-method and teardown previously setup objects.
def prepare(self, colitem): """ setup objects along the collector chain to the test-method and teardown previously setup objects.""" needed_collectors = colitem.listchain() self._teardown_towards(needed_collectors) # check if the last collection node has raised an error ...
[ "def", "prepare", "(", "self", ",", "colitem", ")", ":", "needed_collectors", "=", "colitem", ".", "listchain", "(", ")", "self", ".", "_teardown_towards", "(", "needed_collectors", ")", "# check if the last collection node has raised an error", "for", "col", "in", ...
[ 482, 4 ]
[ 498, 21 ]
python
en
['en', 'en', 'en']
True
Address.String
(self)
Returns a string representation of this address.
Returns a string representation of this address.
def String(self): """Returns a string representation of this address. """ return self.Street+"\n"+self.ZipCode+" "+self.City+", "+self.State
[ "def", "String", "(", "self", ")", ":", "return", "self", ".", "Street", "+", "\"\\n\"", "+", "self", ".", "ZipCode", "+", "\" \"", "+", "self", ".", "City", "+", "\", \"", "+", "self", ".", "State" ]
[ 32, 4 ]
[ 35, 74 ]
python
en
['en', 'en', 'en']
True
Individual.jeeves_restrict_Individuallabel_ForReligiousAffiliation
( individual, ctxt)
Only individuals of profile type 1 can see religious affiliation.
Only individuals of profile type 1 can see religious affiliation.
def jeeves_restrict_Individuallabel_ForReligiousAffiliation( individual, ctxt): """ Only individuals of profile type 1 can see religious affiliation. """ return ctxt != None and ctxt.profiletype==1 \ and ctxt.individual==individual
[ "def", "jeeves_restrict_Individuallabel_ForReligiousAffiliation", "(", "individual", ",", "ctxt", ")", ":", "return", "ctxt", "!=", "None", "and", "ctxt", ".", "profiletype", "==", "1", "and", "ctxt", ".", "individual", "==", "individual" ]
[ 161, 4 ]
[ 166, 43 ]
python
en
['en', 'en', 'en']
True
new_class
(name, bases=(), kwds=None, exec_body=None)
Create a class object dynamically using the appropriate metaclass.
Create a class object dynamically using the appropriate metaclass.
def new_class(name, bases=(), kwds=None, exec_body=None): """Create a class object dynamically using the appropriate metaclass.""" meta, ns, kwds = prepare_class(name, bases, kwds) if exec_body is not None: exec_body(ns) return meta(name, bases, ns, **kwds)
[ "def", "new_class", "(", "name", ",", "bases", "=", "(", ")", ",", "kwds", "=", "None", ",", "exec_body", "=", "None", ")", ":", "meta", ",", "ns", ",", "kwds", "=", "prepare_class", "(", "name", ",", "bases", ",", "kwds", ")", "if", "exec_body", ...
[ 56, 0 ]
[ 61, 40 ]
python
en
['en', 'en', 'en']
True
prepare_class
(name, bases=(), kwds=None)
Call the __prepare__ method of the appropriate metaclass. Returns (metaclass, namespace, kwds) as a 3-tuple *metaclass* is the appropriate metaclass *namespace* is the prepared class namespace *kwds* is an updated copy of the passed in kwds argument with any 'metaclass' entry removed. If no kwds a...
Call the __prepare__ method of the appropriate metaclass.
def prepare_class(name, bases=(), kwds=None): """Call the __prepare__ method of the appropriate metaclass. Returns (metaclass, namespace, kwds) as a 3-tuple *metaclass* is the appropriate metaclass *namespace* is the prepared class namespace *kwds* is an updated copy of the passed in kwds argument...
[ "def", "prepare_class", "(", "name", ",", "bases", "=", "(", ")", ",", "kwds", "=", "None", ")", ":", "if", "kwds", "is", "None", ":", "kwds", "=", "{", "}", "else", ":", "kwds", "=", "dict", "(", "kwds", ")", "# Don't alter the provided mapping", "i...
[ 63, 0 ]
[ 93, 25 ]
python
en
['en', 'en', 'en']
True
_calculate_meta
(meta, bases)
Calculate the most derived metaclass.
Calculate the most derived metaclass.
def _calculate_meta(meta, bases): """Calculate the most derived metaclass.""" winner = meta for base in bases: base_meta = type(base) if issubclass(winner, base_meta): continue if issubclass(base_meta, winner): winner = base_meta continue #...
[ "def", "_calculate_meta", "(", "meta", ",", "bases", ")", ":", "winner", "=", "meta", "for", "base", "in", "bases", ":", "base_meta", "=", "type", "(", "base", ")", "if", "issubclass", "(", "winner", ",", "base_meta", ")", ":", "continue", "if", "issub...
[ 95, 0 ]
[ 110, 17 ]
python
en
['en', 'en', 'en']
True
coroutine
(func)
Convert regular generator function to a coroutine.
Convert regular generator function to a coroutine.
def coroutine(func): """Convert regular generator function to a coroutine.""" if not callable(func): raise TypeError('types.coroutine() expects a callable') if (func.__class__ is FunctionType and getattr(func, '__code__', None).__class__ is CodeType): co_flags = func.__code__.co_f...
[ "def", "coroutine", "(", "func", ")", ":", "if", "not", "callable", "(", "func", ")", ":", "raise", "TypeError", "(", "'types.coroutine() expects a callable'", ")", "if", "(", "func", ".", "__class__", "is", "FunctionType", "and", "getattr", "(", "func", ","...
[ 210, 0 ]
[ 262, 18 ]
python
en
['en', 'jv', 'en']
True
inject_into_urllib3
()
Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.
Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.
def inject_into_urllib3(): "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support." _validate_dependencies_met() util.SSLContext = PyOpenSSLContext util.ssl_.SSLContext = PyOpenSSLContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_PYOPENSSL = True util.ssl_.IS_PYOPENSS...
[ "def", "inject_into_urllib3", "(", ")", ":", "_validate_dependencies_met", "(", ")", "util", ".", "SSLContext", "=", "PyOpenSSLContext", "util", ".", "ssl_", ".", "SSLContext", "=", "PyOpenSSLContext", "util", ".", "HAS_SNI", "=", "HAS_SNI", "util", ".", "ssl_",...
[ 114, 0 ]
[ 124, 33 ]
python
en
['en', 'en', 'en']
True
extract_from_urllib3
()
Undo monkey-patching by :func:`inject_into_urllib3`.
Undo monkey-patching by :func:`inject_into_urllib3`.
def extract_from_urllib3(): "Undo monkey-patching by :func:`inject_into_urllib3`." util.SSLContext = orig_util_SSLContext util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_PYOPENSSL = False util.ssl_.IS_PYOPENSSL = Fal...
[ "def", "extract_from_urllib3", "(", ")", ":", "util", ".", "SSLContext", "=", "orig_util_SSLContext", "util", ".", "ssl_", ".", "SSLContext", "=", "orig_util_SSLContext", "util", ".", "HAS_SNI", "=", "orig_util_HAS_SNI", "util", ".", "ssl_", ".", "HAS_SNI", "=",...
[ 127, 0 ]
[ 135, 34 ]
python
en
['en', 'ny', 'sw']
False
_validate_dependencies_met
()
Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met.
Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met.
def _validate_dependencies_met(): """ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. """ # Method added in `cryptography==1.1`; not available in older versions from cryptography.x509.extensions import Extensions if getattr(Exten...
[ "def", "_validate_dependencies_met", "(", ")", ":", "# Method added in `cryptography==1.1`; not available in older versions", "from", "cryptography", ".", "x509", ".", "extensions", "import", "Extensions", "if", "getattr", "(", "Extensions", ",", "\"get_extension_for_class\"", ...
[ 138, 0 ]
[ 161, 9 ]
python
en
['en', 'error', 'th']
False
_dnsname_to_stdlib
(name)
Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to ...
Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version.
def _dnsname_to_stdlib(name): """ Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and ...
[ "def", "_dnsname_to_stdlib", "(", "name", ")", ":", "def", "idna_encode", "(", "name", ")", ":", "\"\"\"\n Borrowed wholesale from the Python Cryptography Project. It turns out\n that we can't just safely call `idna.encode`: it can explode for\n wildcard names. This avoi...
[ 164, 0 ]
[ 204, 15 ]
python
en
['en', 'error', 'th']
False
get_subj_alt_name
(peer_cert)
Given an PyOpenSSL certificate, provides all the subject alternative names.
Given an PyOpenSSL certificate, provides all the subject alternative names.
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is...
[ "def", "get_subj_alt_name", "(", "peer_cert", ")", ":", "# Pass the cert to cryptography, which has much better APIs for this.", "if", "hasattr", "(", "peer_cert", ",", "\"to_cryptography\"", ")", ":", "cert", "=", "peer_cert", ".", "to_cryptography", "(", ")", "else", ...
[ 207, 0 ]
[ 258, 16 ]
python
en
['en', 'error', 'th']
False
parse_env_flags
(args, flags)
Look for flags set by environment variables.
Look for flags set by environment variables.
def parse_env_flags(args, flags): """ Look for flags set by environment variables. """ san_flags = ','.join(re.findall('-fsanitize=((?:[a-z]+,?)+)', flags)) nosan_flags = ','.join(re.findall('-fno-sanitize=((?:[a-z]+,?)+)', flags)) def set_sanitizer(sanitizer, default, san, nosan): if s...
[ "def", "parse_env_flags", "(", "args", ",", "flags", ")", ":", "san_flags", "=", "','", ".", "join", "(", "re", ".", "findall", "(", "'-fsanitize=((?:[a-z]+,?)+)'", ",", "flags", ")", ")", "nosan_flags", "=", "','", ".", "join", "(", "re", ".", "findall"...
[ 118, 0 ]
[ 144, 15 ]
python
en
['en', 'error', 'th']
False
compiler_version
(cc, cxx)
Determines the compiler and version. Only works for clang and gcc.
Determines the compiler and version. Only works for clang and gcc.
def compiler_version(cc, cxx): """ Determines the compiler and version. Only works for clang and gcc. """ cc_version_bytes = subprocess.check_output([cc, "--version"]) cxx_version_bytes = subprocess.check_output([cxx, "--version"]) compiler = None version = None if b'clang' in cc_ver...
[ "def", "compiler_version", "(", "cc", ",", "cxx", ")", ":", "cc_version_bytes", "=", "subprocess", ".", "check_output", "(", "[", "cc", ",", "\"--version\"", "]", ")", "cxx_version_bytes", "=", "subprocess", ".", "check_output", "(", "[", "cxx", ",", "\"--ve...
[ 147, 0 ]
[ 166, 28 ]
python
en
['en', 'error', 'th']
False
HorizonMiddleware._process_request
(self, request)
Adds data necessary for Horizon to function to the request.
Adds data necessary for Horizon to function to the request.
def _process_request(self, request): """Adds data necessary for Horizon to function to the request.""" request.horizon = {'dashboard': None, 'panel': None, 'async_messages': []} if not hasattr(request, "user") or not request.user.is_authenti...
[ "def", "_process_request", "(", "self", ",", "request", ")", ":", "request", ".", "horizon", "=", "{", "'dashboard'", ":", "None", ",", "'panel'", ":", "None", ",", "'async_messages'", ":", "[", "]", "}", "if", "not", "hasattr", "(", "request", ",", "\...
[ 57, 4 ]
[ 118, 33 ]
python
en
['en', 'en', 'en']
True
HorizonMiddleware.process_exception
(self, request, exception)
Catches internal Horizon exception classes. Exception classes such as NotAuthorized, NotFound and Http302 are caught and handles them gracefully.
Catches internal Horizon exception classes.
def process_exception(self, request, exception): """Catches internal Horizon exception classes. Exception classes such as NotAuthorized, NotFound and Http302 are caught and handles them gracefully. """ if isinstance(exception, (exceptions.NotAuthorized, ...
[ "def", "process_exception", "(", "self", ",", "request", ",", "exception", ")", ":", "if", "isinstance", "(", "exception", ",", "(", "exceptions", ".", "NotAuthorized", ",", "exceptions", ".", "NotAuthenticated", ")", ")", ":", "auth_url", "=", "settings", "...
[ 120, 4 ]
[ 156, 57 ]
python
en
['en', 'en', 'en']
True
HorizonMiddleware._process_response
(self, request, response)
Convert HttpResponseRedirect to HttpResponse if request is via ajax. This is to allow ajax request to redirect url.
Convert HttpResponseRedirect to HttpResponse if request is via ajax.
def _process_response(self, request, response): """Convert HttpResponseRedirect to HttpResponse if request is via ajax. This is to allow ajax request to redirect url. """ if request.is_ajax() and hasattr(request, 'horizon'): queued_msgs = request.horizon['async_messages'] ...
[ "def", "_process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "request", ".", "is_ajax", "(", ")", "and", "hasattr", "(", "request", ",", "'horizon'", ")", ":", "queued_msgs", "=", "request", ".", "horizon", "[", "'async_message...
[ 163, 4 ]
[ 211, 23 ]
python
en
['en', 'zh', 'en']
True
TestSecuritygroup.test_securitygroup_create_delete
(self)
tests the security group creation and deletion functionalities: * creates a new security group * verifies the security group appears in the security groups table * deletes the newly created security group * verifies the security group does not appear in the table after deletio...
tests the security group creation and deletion functionalities:
def test_securitygroup_create_delete(self): """tests the security group creation and deletion functionalities: * creates a new security group * verifies the security group appears in the security groups table * deletes the newly created security group * verifies the security gro...
[ "def", "test_securitygroup_create_delete", "(", "self", ")", ":", "self", ".", "_create_securitygroup", "(", ")", "self", ".", "_delete_securitygroup", "(", ")" ]
[ 72, 4 ]
[ 82, 36 ]
python
en
['en', 'en', 'en']
True
TestSecuritygroup.test_managerules_create_delete_by_row
(self)
tests the manage rules creation and deletion functionalities: * create a new security group * verifies the security group appears in the security groups table * creates a new rule * verifies the rule appears in the rules table * delete the newly created rule * verifies t...
tests the manage rules creation and deletion functionalities:
def test_managerules_create_delete_by_row(self): """tests the manage rules creation and deletion functionalities: * create a new security group * verifies the security group appears in the security groups table * creates a new rule * verifies the rule appears in the rules table ...
[ "def", "test_managerules_create_delete_by_row", "(", "self", ")", ":", "self", ".", "_create_securitygroup", "(", ")", "self", ".", "_add_rule", "(", ")", "self", ".", "_delete_rule_by_row_action", "(", ")", "self", ".", "_delete_securitygroup", "(", ")" ]
[ 84, 4 ]
[ 100, 36 ]
python
en
['en', 'en', 'en']
True
TestSecuritygroup.test_managerules_create_delete_by_table
(self)
tests the manage rules creation and deletion functionalities: * create a new security group * verifies the security group appears in the security groups table * creates a new rule * verifies the rule appears in the rules table * delete the newly created rule * verifies t...
tests the manage rules creation and deletion functionalities:
def test_managerules_create_delete_by_table(self): """tests the manage rules creation and deletion functionalities: * create a new security group * verifies the security group appears in the security groups table * creates a new rule * verifies the rule appears in the rules tabl...
[ "def", "test_managerules_create_delete_by_table", "(", "self", ")", ":", "self", ".", "_create_securitygroup", "(", ")", "self", ".", "_add_rule", "(", ")", "self", ".", "_delete_rule_by_table_action", "(", ")", "self", ".", "_delete_securitygroup", "(", ")" ]
[ 102, 4 ]
[ 118, 36 ]
python
en
['en', 'en', 'en']
True
extract_cqt
(samples, sample_rate, cqt_hop_length)
Transforms the contents of a wav/mp3 file into a series of CQT frames.
Transforms the contents of a wav/mp3 file into a series of CQT frames.
def extract_cqt(samples, sample_rate, cqt_hop_length): """Transforms the contents of a wav/mp3 file into a series of CQT frames.""" cqt = np.abs(librosa.core.cqt( samples, sample_rate, hop_length=cqt_hop_length, fmin=CQT_FMIN, n_bins=CQT_N_BINS, bins_per_octave=CQT_BINS_PER_OCTAV...
[ "def", "extract_cqt", "(", "samples", ",", "sample_rate", ",", "cqt_hop_length", ")", ":", "cqt", "=", "np", ".", "abs", "(", "librosa", ".", "core", ".", "cqt", "(", "samples", ",", "sample_rate", ",", "hop_length", "=", "cqt_hop_length", ",", "fmin", "...
[ 46, 0 ]
[ 58, 12 ]
python
en
['en', 'en', 'en']
True
align_cpp
(samples, sample_rate, ns, cqt_hop_length, sf2_path, penalty_mul=1.0, band_radius_seconds=.5)
Aligns the notesequence to the wav file using C++ DTW. Args: samples: Samples to align. sample_rate: Sample rate for samples. ns: The source notesequence to align. cqt_hop_length: Hop length to use for CQT calculations. sf2_path: Path to SF2 file for synthesis. penalty_mul: Penalty multiplier...
Aligns the notesequence to the wav file using C++ DTW.
def align_cpp(samples, sample_rate, ns, cqt_hop_length, sf2_path, penalty_mul=1.0, band_radius_seconds=.5): """Aligns the notesequence to the wav file using C++ DTW. Args: samples: Samples to align. sample_rate: Sample rate...
[ "def", "align_cpp", "(", "samples", ",", "sample_rate", ",", "ns", ",", "cqt_hop_length", ",", "sf2_path", ",", "penalty_mul", "=", "1.0", ",", "band_radius_seconds", "=", ".5", ")", ":", "logging", ".", "info", "(", "'Synthesizing'", ")", "ns_samples", "=",...
[ 61, 0 ]
[ 177, 26 ]
python
en
['en', 'en', 'en']
True
check
(actions, request, target=None)
Wrapper of the configurable policy method.
Wrapper of the configurable policy method.
def check(actions, request, target=None): """Wrapper of the configurable policy method.""" policy_check = utils_settings.import_setting("POLICY_CHECK_FUNCTION") if policy_check: return policy_check(actions, request, target) return True
[ "def", "check", "(", "actions", ",", "request", ",", "target", "=", "None", ")", ":", "policy_check", "=", "utils_settings", ".", "import_setting", "(", "\"POLICY_CHECK_FUNCTION\"", ")", "if", "policy_check", ":", "return", "policy_check", "(", "actions", ",", ...
[ 17, 0 ]
[ 25, 15 ]
python
en
['en', 'en', 'en']
True
update_mean_var_count_from_moments
(mean, var, count, batch_mean, batch_var, batch_count, max_past_samples)
Courtesy of OpenAI Baselines.
Courtesy of OpenAI Baselines.
def update_mean_var_count_from_moments(mean, var, count, batch_mean, batch_var, batch_count, max_past_samples): """Courtesy of OpenAI Baselines.""" if max_past_samples is not None: # pretend we never have more than n past samples, this will guarantee a constant convergence rate count = min(count...
[ "def", "update_mean_var_count_from_moments", "(", "mean", ",", "var", ",", "count", ",", "batch_mean", ",", "batch_var", ",", "batch_count", ",", "max_past_samples", ")", ":", "if", "max_past_samples", "is", "not", "None", ":", "# pretend we never have more than n pas...
[ 44, 0 ]
[ 60, 39 ]
python
en
['en', 'st', 'en']
True
extract_keys
(list_of_dicts, *keys)
Turn a lists of dicts into a tuple of lists, with one entry for every given key.
Turn a lists of dicts into a tuple of lists, with one entry for every given key.
def extract_keys(list_of_dicts, *keys): """Turn a lists of dicts into a tuple of lists, with one entry for every given key.""" res = [] for k in keys: res.append([d[k] for d in list_of_dicts]) return tuple(res)
[ "def", "extract_keys", "(", "list_of_dicts", ",", "*", "keys", ")", ":", "res", "=", "[", "]", "for", "k", "in", "keys", ":", "res", ".", "append", "(", "[", "d", "[", "k", "]", "for", "d", "in", "list_of_dicts", "]", ")", "return", "tuple", "(",...
[ 87, 0 ]
[ 92, 21 ]
python
en
['en', 'en', 'en']
True
calculate_discounted_sum
(x, dones, discount, x_last=None)
Computing cumulative sum (of something) for the trajectory, taking episode termination into consideration. :param x: ndarray of shape [num_steps, num_envs] :param dones: ndarray of shape [num_steps, num_envs] :param discount: float in range [0,1] :param x_last: iterable of shape [num_envs], value a...
Computing cumulative sum (of something) for the trajectory, taking episode termination into consideration. :param x: ndarray of shape [num_steps, num_envs] :param dones: ndarray of shape [num_steps, num_envs] :param discount: float in range [0,1] :param x_last: iterable of shape [num_envs], value a...
def calculate_discounted_sum(x, dones, discount, x_last=None): """ Computing cumulative sum (of something) for the trajectory, taking episode termination into consideration. :param x: ndarray of shape [num_steps, num_envs] :param dones: ndarray of shape [num_steps, num_envs] :param discount: float i...
[ "def", "calculate_discounted_sum", "(", "x", ",", "dones", ",", "discount", ",", "x_last", "=", "None", ")", ":", "x_last", "=", "np", ".", "zeros_like", "(", "x", "[", "0", "]", ")", "if", "x_last", "is", "None", "else", "np", ".", "array", "(", "...
[ 99, 0 ]
[ 114, 25 ]
python
en
['en', 'error', 'th']
False
calculate_gae
(rewards, dones, values, gamma, gae_lambda)
Computing discounted cumulative sum, taking episode terminations into consideration. Follows the Generalized Advantage Estimation algorithm. See unit tests for details. :param rewards: actual environment rewards :param dones: True if absorbing state is reached :param values: estimated values ...
Computing discounted cumulative sum, taking episode terminations into consideration. Follows the Generalized Advantage Estimation algorithm. See unit tests for details.
def calculate_gae(rewards, dones, values, gamma, gae_lambda): """ Computing discounted cumulative sum, taking episode terminations into consideration. Follows the Generalized Advantage Estimation algorithm. See unit tests for details. :param rewards: actual environment rewards :param dones: Tru...
[ "def", "calculate_gae", "(", "rewards", ",", "dones", ",", "values", ",", "gamma", ",", "gae_lambda", ")", ":", "assert", "len", "(", "rewards", ")", "==", "len", "(", "dones", ")", "assert", "len", "(", "rewards", ")", "+", "1", "==", "len", "(", ...
[ 117, 0 ]
[ 140, 79 ]
python
en
['en', 'error', 'th']
False
num_env_steps
(infos)
Calculate number of environment frames in a batch of experience.
Calculate number of environment frames in a batch of experience.
def num_env_steps(infos): """Calculate number of environment frames in a batch of experience.""" total_num_frames = 0 for info in infos: total_num_frames += info.get('num_frames', 1) return total_num_frames
[ "def", "num_env_steps", "(", "infos", ")", ":", "total_num_frames", "=", "0", "for", "info", "in", "infos", ":", "total_num_frames", "+=", "info", ".", "get", "(", "'num_frames'", ",", "1", ")", "return", "total_num_frames" ]
[ 143, 0 ]
[ 149, 27 ]
python
en
['en', 'en', 'en']
True
Factory.get_wheel_cache_entry
(self, link, name)
Look up the link in the wheel cache. If ``preparer.require_hashes`` is True, don't use the wheel cache, because cached wheels, always built locally, have different hashes than the files downloaded from the index server and thus throw false hash mismatches. Furthermore, cached wheels at ...
Look up the link in the wheel cache.
def get_wheel_cache_entry(self, link, name): # type: (Link, Optional[str]) -> Optional[CacheEntry] """Look up the link in the wheel cache. If ``preparer.require_hashes`` is True, don't use the wheel cache, because cached wheels, always built locally, have different hashes than t...
[ "def", "get_wheel_cache_entry", "(", "self", ",", "link", ",", "name", ")", ":", "# type: (Link, Optional[str]) -> Optional[CacheEntry]", "if", "self", ".", "_wheel_cache", "is", "None", "or", "self", ".", "preparer", ".", "require_hashes", ":", "return", "None", ...
[ 295, 4 ]
[ 311, 9 ]
python
en
['en', 'en', 'en']
True
parse_uri
(uri)
Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri)
Parses a URI using the regex given in Appendix B of RFC 3986.
def parse_uri(uri): """Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri) """ groups = URI.match(uri).groups() return (groups[1], groups[3], groups[4], groups[6], groups[8])
[ "def", "parse_uri", "(", "uri", ")", ":", "groups", "=", "URI", ".", "match", "(", "uri", ")", ".", "groups", "(", ")", "return", "(", "groups", "[", "1", "]", ",", "groups", "[", "3", "]", ",", "groups", "[", "4", "]", ",", "groups", "[", "6...
[ 20, 0 ]
[ 26, 66 ]
python
en
['en', 'en', 'en']
True
CacheController._urlnorm
(cls, uri)
Normalize the URL to create a safe key for the cache
Normalize the URL to create a safe key for the cache
def _urlnorm(cls, uri): """Normalize the URL to create a safe key for the cache""" (scheme, authority, path, query, fragment) = parse_uri(uri) if not scheme or not authority: raise Exception("Only absolute URIs are allowed. uri = %s" % uri) scheme = scheme.lower() au...
[ "def", "_urlnorm", "(", "cls", ",", "uri", ")", ":", "(", "scheme", ",", "authority", ",", "path", ",", "query", ",", "fragment", ")", "=", "parse_uri", "(", "uri", ")", "if", "not", "scheme", "or", "not", "authority", ":", "raise", "Exception", "(",...
[ 42, 4 ]
[ 59, 25 ]
python
en
['en', 'en', 'en']
True
CacheController.cached_request
(self, request)
Return a cached response if it exists in the cache, otherwise return False.
Return a cached response if it exists in the cache, otherwise return False.
def cached_request(self, request): """ Return a cached response if it exists in the cache, otherwise return False. """ cache_url = self.cache_url(request.url) logger.debug('Looking up "%s" in the cache', cache_url) cc = self.parse_cache_control(request.headers) ...
[ "def", "cached_request", "(", "self", ",", "request", ")", ":", "cache_url", "=", "self", ".", "cache_url", "(", "request", ".", "url", ")", "logger", ".", "debug", "(", "'Looking up \"%s\" in the cache'", ",", "cache_url", ")", "cc", "=", "self", ".", "pa...
[ 119, 4 ]
[ 228, 20 ]
python
en
['en', 'error', 'th']
False
CacheController.cache_response
(self, request, response, body=None, status_codes=None)
Algorithm for caching requests. This assumes a requests Response object.
Algorithm for caching requests.
def cache_response(self, request, response, body=None, status_codes=None): """ Algorithm for caching requests. This assumes a requests Response object. """ # From httplib2: Don't cache 206's since we aren't going to # handle byte range requests cac...
[ "def", "cache_response", "(", "self", ",", "request", ",", "response", ",", "body", "=", "None", ",", "status_codes", "=", "None", ")", ":", "# From httplib2: Don't cache 206's since we aren't going to", "# handle byte range requests", "cacheable_status_codes",...
[ 246, 4 ]
[ 335, 21 ]
python
en
['en', 'error', 'th']
False
CacheController.update_cached_response
(self, request, response)
On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one. This should only ever be called when we've sent an ETag and gotten a 304 as the response.
On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one.
def update_cached_response(self, request, response): """On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one. This should only ever be called when we've sent an ETag and gotten a 304 as the response. """ cache_url =...
[ "def", "update_cached_response", "(", "self", ",", "request", ",", "response", ")", ":", "cache_url", "=", "self", ".", "cache_url", "(", "request", ".", "url", ")", "cached_response", "=", "self", ".", "serializer", ".", "loads", "(", "request", ",", "sel...
[ 337, 4 ]
[ 375, 30 ]
python
en
['en', 'en', 'en']
True
Finder.find_module
(self, fullname, path=None)
An abstract method that should find a module. The fullname is a str and the optional path is a str or None. Returns a Loader object or None.
An abstract method that should find a module. The fullname is a str and the optional path is a str or None. Returns a Loader object or None.
def find_module(self, fullname, path=None): """An abstract method that should find a module. The fullname is a str and the optional path is a str or None. Returns a Loader object or None. """
[ "def", "find_module", "(", "self", ",", "fullname", ",", "path", "=", "None", ")", ":" ]
[ 39, 4 ]
[ 43, 11 ]
python
en
['en', 'en', 'en']
True
MetaPathFinder.find_module
(self, fullname, path)
Return a loader for the module. If no module is found, return None. The fullname is a str and the path is a list of strings or None. This method is deprecated in favor of finder.find_spec(). If find_spec() exists then backwards-compatible functionality is provided for this met...
Return a loader for the module.
def find_module(self, fullname, path): """Return a loader for the module. If no module is found, return None. The fullname is a str and the path is a list of strings or None. This method is deprecated in favor of finder.find_spec(). If find_spec() exists then backwards-compati...
[ "def", "find_module", "(", "self", ",", "fullname", ",", "path", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'find_spec'", ")", ":", "return", "None", "found", "=", "self", ".", "find_spec", "(", "fullname", ",", "path", ")", "return", "found"...
[ 53, 4 ]
[ 67, 58 ]
python
en
['en', 'en', 'en']
True
MetaPathFinder.invalidate_caches
(self)
An optional method for clearing the finder's cache, if any. This method is used by importlib.invalidate_caches().
An optional method for clearing the finder's cache, if any. This method is used by importlib.invalidate_caches().
def invalidate_caches(self): """An optional method for clearing the finder's cache, if any. This method is used by importlib.invalidate_caches(). """
[ "def", "invalidate_caches", "(", "self", ")", ":" ]
[ 69, 4 ]
[ 72, 11 ]
python
en
['en', 'en', 'en']
True
PathEntryFinder.find_loader
(self, fullname)
Return (loader, namespace portion) for the path entry. The fullname is a str. The namespace portion is a sequence of path entries contributing to part of a namespace package. The sequence may be empty. If loader is not None, the portion will be ignored. The portion will be di...
Return (loader, namespace portion) for the path entry.
def find_loader(self, fullname): """Return (loader, namespace portion) for the path entry. The fullname is a str. The namespace portion is a sequence of path entries contributing to part of a namespace package. The sequence may be empty. If loader is not None, the portion will ...
[ "def", "find_loader", "(", "self", ",", "fullname", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'find_spec'", ")", ":", "return", "None", ",", "[", "]", "found", "=", "self", ".", "find_spec", "(", "fullname", ")", "if", "found", "is", "not"...
[ 85, 4 ]
[ 110, 27 ]
python
en
['en', 'en', 'en']
True
PathEntryFinder.invalidate_caches
(self)
An optional method for clearing the finder's cache, if any. This method is used by PathFinder.invalidate_caches().
An optional method for clearing the finder's cache, if any. This method is used by PathFinder.invalidate_caches().
def invalidate_caches(self): """An optional method for clearing the finder's cache, if any. This method is used by PathFinder.invalidate_caches(). """
[ "def", "invalidate_caches", "(", "self", ")", ":" ]
[ 114, 4 ]
[ 117, 11 ]
python
en
['en', 'en', 'en']
True
Loader.create_module
(self, spec)
Return a module to initialize and into which to load. This method should raise ImportError if anything prevents it from creating a new module. It may return None to indicate that the spec should create the new module.
Return a module to initialize and into which to load.
def create_module(self, spec): """Return a module to initialize and into which to load. This method should raise ImportError if anything prevents it from creating a new module. It may return None to indicate that the spec should create the new module. """ # By default, ...
[ "def", "create_module", "(", "self", ",", "spec", ")", ":", "# By default, defer to default semantics for the new module.", "return", "None" ]
[ 126, 4 ]
[ 134, 19 ]
python
en
['en', 'en', 'en']
True
Loader.load_module
(self, fullname)
Return the loaded module. The module must be added to sys.modules and have import-related attributes set properly. The fullname is a str. ImportError is raised on failure. This method is deprecated in favor of loader.exec_module(). If exec_module() exists then it is used to p...
Return the loaded module.
def load_module(self, fullname): """Return the loaded module. The module must be added to sys.modules and have import-related attributes set properly. The fullname is a str. ImportError is raised on failure. This method is deprecated in favor of loader.exec_module(). If ...
[ "def", "load_module", "(", "self", ",", "fullname", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'exec_module'", ")", ":", "raise", "ImportError", "return", "_bootstrap", ".", "_load_module_shim", "(", "self", ",", "fullname", ")" ]
[ 139, 4 ]
[ 154, 59 ]
python
en
['en', 'fy', 'en']
True
Loader.module_repr
(self, module)
Return a module's repr. Used by the module type when the method does not raise NotImplementedError. This method is deprecated.
Return a module's repr.
def module_repr(self, module): """Return a module's repr. Used by the module type when the method does not raise NotImplementedError. This method is deprecated. """ # The exception will cause ModuleType.__repr__ to ignore this method. raise NotImplementedError
[ "def", "module_repr", "(", "self", ",", "module", ")", ":", "# The exception will cause ModuleType.__repr__ to ignore this method.", "raise", "NotImplementedError" ]
[ 156, 4 ]
[ 166, 33 ]
python
en
['en', 'co', 'en']
True
ResourceLoader.get_data
(self, path)
Abstract method which when implemented should return the bytes for the specified path. The path must be a str.
Abstract method which when implemented should return the bytes for the specified path. The path must be a str.
def get_data(self, path): """Abstract method which when implemented should return the bytes for the specified path. The path must be a str.""" raise IOError
[ "def", "get_data", "(", "self", ",", "path", ")", ":", "raise", "IOError" ]
[ 179, 4 ]
[ 182, 21 ]
python
en
['en', 'en', 'en']
True
InspectLoader.is_package
(self, fullname)
Optional method which when implemented should return whether the module is a package. The fullname is a str. Returns a bool. Raises ImportError if the module cannot be found.
Optional method which when implemented should return whether the module is a package. The fullname is a str. Returns a bool.
def is_package(self, fullname): """Optional method which when implemented should return whether the module is a package. The fullname is a str. Returns a bool. Raises ImportError if the module cannot be found. """ raise ImportError
[ "def", "is_package", "(", "self", ",", "fullname", ")", ":", "raise", "ImportError" ]
[ 194, 4 ]
[ 200, 25 ]
python
en
['en', 'en', 'en']
True
InspectLoader.get_code
(self, fullname)
Method which returns the code object for the module. The fullname is a str. Returns a types.CodeType if possible, else returns None if a code object does not make sense (e.g. built-in module). Raises ImportError if the module cannot be found.
Method which returns the code object for the module.
def get_code(self, fullname): """Method which returns the code object for the module. The fullname is a str. Returns a types.CodeType if possible, else returns None if a code object does not make sense (e.g. built-in module). Raises ImportError if the module cannot be found. ...
[ "def", "get_code", "(", "self", ",", "fullname", ")", ":", "source", "=", "self", ".", "get_source", "(", "fullname", ")", "if", "source", "is", "None", ":", "return", "None", "return", "self", ".", "source_to_code", "(", "source", ")" ]
[ 202, 4 ]
[ 213, 42 ]
python
en
['en', 'en', 'en']
True
InspectLoader.get_source
(self, fullname)
Abstract method which should return the source code for the module. The fullname is a str. Returns a str. Raises ImportError if the module cannot be found.
Abstract method which should return the source code for the module. The fullname is a str. Returns a str.
def get_source(self, fullname): """Abstract method which should return the source code for the module. The fullname is a str. Returns a str. Raises ImportError if the module cannot be found. """ raise ImportError
[ "def", "get_source", "(", "self", ",", "fullname", ")", ":", "raise", "ImportError" ]
[ 216, 4 ]
[ 222, 25 ]
python
en
['en', 'en', 'en']
True
InspectLoader.source_to_code
(data, path='<string>')
Compile 'data' into a code object. The 'data' argument can be anything that compile() can handle. The'path' argument should be where the data was retrieved (when applicable).
Compile 'data' into a code object.
def source_to_code(data, path='<string>'): """Compile 'data' into a code object. The 'data' argument can be anything that compile() can handle. The'path' argument should be where the data was retrieved (when applicable).""" return compile(data, path, 'exec', dont_inherit=True)
[ "def", "source_to_code", "(", "data", ",", "path", "=", "'<string>'", ")", ":", "return", "compile", "(", "data", ",", "path", ",", "'exec'", ",", "dont_inherit", "=", "True", ")" ]
[ 225, 4 ]
[ 230, 61 ]
python
en
['it', 'en', 'en']
True
ExecutionLoader.get_filename
(self, fullname)
Abstract method which should return the value that __file__ is to be set to. Raises ImportError if the module cannot be found.
Abstract method which should return the value that __file__ is to be set to.
def get_filename(self, fullname): """Abstract method which should return the value that __file__ is to be set to. Raises ImportError if the module cannot be found. """ raise ImportError
[ "def", "get_filename", "(", "self", ",", "fullname", ")", ":", "raise", "ImportError" ]
[ 248, 4 ]
[ 254, 25 ]
python
en
['en', 'en', 'en']
True
ExecutionLoader.get_code
(self, fullname)
Method to return the code object for fullname. Should return None if not applicable (e.g. built-in module). Raise ImportError if the module cannot be found.
Method to return the code object for fullname.
def get_code(self, fullname): """Method to return the code object for fullname. Should return None if not applicable (e.g. built-in module). Raise ImportError if the module cannot be found. """ source = self.get_source(fullname) if source is None: return None...
[ "def", "get_code", "(", "self", ",", "fullname", ")", ":", "source", "=", "self", ".", "get_source", "(", "fullname", ")", "if", "source", "is", "None", ":", "return", "None", "try", ":", "path", "=", "self", ".", "get_filename", "(", "fullname", ")", ...
[ 256, 4 ]
[ 270, 52 ]
python
en
['en', 'no', 'en']
True
SourceLoader.path_mtime
(self, path)
Return the (int) modification time for the path (str).
Return the (int) modification time for the path (str).
def path_mtime(self, path): """Return the (int) modification time for the path (str).""" if self.path_stats.__func__ is SourceLoader.path_stats: raise IOError return int(self.path_stats(path)['mtime'])
[ "def", "path_mtime", "(", "self", ",", "path", ")", ":", "if", "self", ".", "path_stats", ".", "__func__", "is", "SourceLoader", ".", "path_stats", ":", "raise", "IOError", "return", "int", "(", "self", ".", "path_stats", "(", "path", ")", "[", "'mtime'"...
[ 301, 4 ]
[ 305, 50 ]
python
en
['en', 'en', 'en']
True
SourceLoader.path_stats
(self, path)
Return a metadata dict for the source pointed to by the path (str). Possible keys: - 'mtime' (mandatory) is the numeric timestamp of last source code modification; - 'size' (optional) is the size in bytes of the source code.
Return a metadata dict for the source pointed to by the path (str). Possible keys: - 'mtime' (mandatory) is the numeric timestamp of last source code modification; - 'size' (optional) is the size in bytes of the source code.
def path_stats(self, path): """Return a metadata dict for the source pointed to by the path (str). Possible keys: - 'mtime' (mandatory) is the numeric timestamp of last source code modification; - 'size' (optional) is the size in bytes of the source code. """ if...
[ "def", "path_stats", "(", "self", ",", "path", ")", ":", "if", "self", ".", "path_mtime", ".", "__func__", "is", "SourceLoader", ".", "path_mtime", ":", "raise", "IOError", "return", "{", "'mtime'", ":", "self", ".", "path_mtime", "(", "path", ")", "}" ]
[ 307, 4 ]
[ 316, 47 ]
python
en
['en', 'en', 'en']
True
SourceLoader.set_data
(self, path, data)
Write the bytes to the path (if possible). Accepts a str path and data as bytes. Any needed intermediary directories are to be created. If for some reason the file cannot be written because of permissions, fail silently.
Write the bytes to the path (if possible).
def set_data(self, path, data): """Write the bytes to the path (if possible). Accepts a str path and data as bytes. Any needed intermediary directories are to be created. If for some reason the file cannot be written because of permissions, fail silently. """
[ "def", "set_data", "(", "self", ",", "path", ",", "data", ")", ":" ]
[ 318, 4 ]
[ 326, 11 ]
python
en
['en', 'en', 'en']
True
_rewrite_test
(config, fn)
Try to read and rewrite *fn* and return the code object.
Try to read and rewrite *fn* and return the code object.
def _rewrite_test(config, fn): """Try to read and rewrite *fn* and return the code object.""" state = config._assertstate try: stat = fn.stat() source = fn.read("rb") except EnvironmentError: return None, None if ASCII_IS_DEFAULT_ENCODING: # ASCII is the default encod...
[ "def", "_rewrite_test", "(", "config", ",", "fn", ")", ":", "state", "=", "config", ".", "_assertstate", "try", ":", "stat", "=", "fn", ".", "stat", "(", ")", "source", "=", "fn", ".", "read", "(", "\"rb\"", ")", "except", "EnvironmentError", ":", "r...
[ 286, 0 ]
[ 337, 19 ]
python
en
['en', 'en', 'en']
True
_make_rewritten_pyc
(state, source_stat, pyc, co)
Try to dump rewritten code to *pyc*.
Try to dump rewritten code to *pyc*.
def _make_rewritten_pyc(state, source_stat, pyc, co): """Try to dump rewritten code to *pyc*.""" if sys.platform.startswith("win"): # Windows grants exclusive access to open files and doesn't have atomic # rename, so just write into the final file. _write_pyc(state, co, source_stat, pyc)...
[ "def", "_make_rewritten_pyc", "(", "state", ",", "source_stat", ",", "pyc", ",", "co", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"win\"", ")", ":", "# Windows grants exclusive access to open files and doesn't have atomic", "# rename, so just writ...
[ 340, 0 ]
[ 351, 36 ]
python
en
['en', 'en', 'en']
True
_read_pyc
(source, pyc, trace=lambda x: None)
Possibly read a pytest pyc containing rewritten code. Return rewritten code if successful or None if not.
Possibly read a pytest pyc containing rewritten code.
def _read_pyc(source, pyc, trace=lambda x: None): """Possibly read a pytest pyc containing rewritten code. Return rewritten code if successful or None if not. """ try: fp = open(pyc, "rb") except IOError: return None with fp: try: mtime = int(source.mtime()) ...
[ "def", "_read_pyc", "(", "source", ",", "pyc", ",", "trace", "=", "lambda", "x", ":", "None", ")", ":", "try", ":", "fp", "=", "open", "(", "pyc", ",", "\"rb\"", ")", "except", "IOError", ":", "return", "None", "with", "fp", ":", "try", ":", "mti...
[ 354, 0 ]
[ 384, 17 ]
python
en
['en', 'en', 'en']
True
rewrite_asserts
(mod, module_path=None, config=None)
Rewrite the assert statements in mod.
Rewrite the assert statements in mod.
def rewrite_asserts(mod, module_path=None, config=None): """Rewrite the assert statements in mod.""" AssertionRewriter(module_path, config).run(mod)
[ "def", "rewrite_asserts", "(", "mod", ",", "module_path", "=", "None", ",", "config", "=", "None", ")", ":", "AssertionRewriter", "(", "module_path", ",", "config", ")", ".", "run", "(", "mod", ")" ]
[ 387, 0 ]
[ 389, 51 ]
python
en
['en', 'de', 'en']
True
_saferepr
(obj)
Get a safe repr of an object for assertion error messages. The assertion formatting (util.format_explanation()) requires newlines to be escaped since they are a special character for it. Normally assertion.util.format_explanation() does this but for a custom repr it is possible to contain one of the sp...
Get a safe repr of an object for assertion error messages.
def _saferepr(obj): """Get a safe repr of an object for assertion error messages. The assertion formatting (util.format_explanation()) requires newlines to be escaped since they are a special character for it. Normally assertion.util.format_explanation() does this but for a custom repr it is possib...
[ "def", "_saferepr", "(", "obj", ")", ":", "repr", "=", "py", ".", "io", ".", "saferepr", "(", "obj", ")", "if", "isinstance", "(", "repr", ",", "six", ".", "text_type", ")", ":", "t", "=", "six", ".", "text_type", "else", ":", "t", "=", "six", ...
[ 392, 0 ]
[ 408, 42 ]
python
en
['en', 'lb', 'en']
True
_format_assertmsg
(obj)
Format the custom assertion message given. For strings this simply replaces newlines with '\n~' so that util.format_explanation() will preserve them instead of escaping newlines. For other objects py.io.saferepr() is used first.
Format the custom assertion message given.
def _format_assertmsg(obj): """Format the custom assertion message given. For strings this simply replaces newlines with '\n~' so that util.format_explanation() will preserve them instead of escaping newlines. For other objects py.io.saferepr() is used first. """ # reprlib appears to have a b...
[ "def", "_format_assertmsg", "(", "obj", ")", ":", "# reprlib appears to have a bug which means that if a string", "# contains a newline it gets escaped, however if an object has a", "# .__repr__() which contains newlines it does not get escaped.", "# However in either case we want to preserve the ...
[ 414, 0 ]
[ 439, 12 ]
python
en
['en', 'en', 'en']
True
set_location
(node, lineno, col_offset)
Set node location information recursively.
Set node location information recursively.
def set_location(node, lineno, col_offset): """Set node location information recursively.""" def _fix(node, lineno, col_offset): if "lineno" in node._attributes: node.lineno = lineno if "col_offset" in node._attributes: node.col_offset = col_offset for child in as...
[ "def", "set_location", "(", "node", ",", "lineno", ",", "col_offset", ")", ":", "def", "_fix", "(", "node", ",", "lineno", ",", "col_offset", ")", ":", "if", "\"lineno\"", "in", "node", ".", "_attributes", ":", "node", ".", "lineno", "=", "lineno", "if...
[ 515, 0 ]
[ 525, 15 ]
python
da
['es', 'da', 'en']
False
AssertionRewritingHook.mark_rewrite
(self, *names)
Mark import names as needing to be rewritten. The named module or package as well as any nested modules will be rewritten on import.
Mark import names as needing to be rewritten.
def mark_rewrite(self, *names): """Mark import names as needing to be rewritten. The named module or package as well as any nested modules will be rewritten on import. """ already_imported = (set(names) .intersection(sys.modules) ...
[ "def", "mark_rewrite", "(", "self", ",", "*", "names", ")", ":", "already_imported", "=", "(", "set", "(", "names", ")", ".", "intersection", "(", "sys", ".", "modules", ")", ".", "difference", "(", "self", ".", "_rewritten_names", ")", ")", "for", "na...
[ 175, 4 ]
[ 188, 40 ]
python
en
['en', 'en', 'en']
True
AssertionRewritingHook._register_with_pkg_resources
(cls)
Ensure package resources can be loaded from this loader. May be called multiple times, as the operation is idempotent.
Ensure package resources can be loaded from this loader. May be called multiple times, as the operation is idempotent.
def _register_with_pkg_resources(cls): """ Ensure package resources can be loaded from this loader. May be called multiple times, as the operation is idempotent. """ try: import pkg_resources # access an attribute in case a deferred importer is present ...
[ "def", "_register_with_pkg_resources", "(", "cls", ")", ":", "try", ":", "import", "pkg_resources", "# access an attribute in case a deferred importer is present", "pkg_resources", ".", "__name__", "except", "ImportError", ":", "return", "# Since pytest tests are always located i...
[ 230, 4 ]
[ 244, 78 ]
python
en
['en', 'error', 'th']
False
AssertionRewritingHook.get_data
(self, pathname)
Optional PEP302 get_data API.
Optional PEP302 get_data API.
def get_data(self, pathname): """Optional PEP302 get_data API. """ with open(pathname, 'rb') as f: return f.read()
[ "def", "get_data", "(", "self", ",", "pathname", ")", ":", "with", "open", "(", "pathname", ",", "'rb'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
[ 246, 4 ]
[ 250, 27 ]
python
en
['en', 'su', 'en']
True
AssertionRewriter.run
(self, mod)
Find all assert statements in *mod* and rewrite them.
Find all assert statements in *mod* and rewrite them.
def run(self, mod): """Find all assert statements in *mod* and rewrite them.""" if not mod.body: # Nothing to do. return # Insert some special imports at the top of the module but after any # docstrings and __future__ imports. aliases = [ast.alias(py.built...
[ "def", "run", "(", "self", ",", "mod", ")", ":", "if", "not", "mod", ".", "body", ":", "# Nothing to do.", "return", "# Insert some special imports at the top of the module but after any", "# docstrings and __future__ imports.", "aliases", "=", "[", "ast", ".", "alias",...
[ 585, 4 ]
[ 637, 39 ]
python
en
['en', 'en', 'en']
True
AssertionRewriter.variable
(self)
Get a new variable.
Get a new variable.
def variable(self): """Get a new variable.""" # Use a character invalid in python identifiers to avoid clashing. name = "@py_assert" + str(next(self.variable_counter)) self.variables.append(name) return name
[ "def", "variable", "(", "self", ")", ":", "# Use a character invalid in python identifiers to avoid clashing.", "name", "=", "\"@py_assert\"", "+", "str", "(", "next", "(", "self", ".", "variable_counter", ")", ")", "self", ".", "variables", ".", "append", "(", "n...
[ 643, 4 ]
[ 648, 19 ]
python
en
['en', 'en', 'en']
True
AssertionRewriter.assign
(self, expr)
Give *expr* a name.
Give *expr* a name.
def assign(self, expr): """Give *expr* a name.""" name = self.variable() self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr)) return ast.Name(name, ast.Load())
[ "def", "assign", "(", "self", ",", "expr", ")", ":", "name", "=", "self", ".", "variable", "(", ")", "self", ".", "statements", ".", "append", "(", "ast", ".", "Assign", "(", "[", "ast", ".", "Name", "(", "name", ",", "ast", ".", "Store", "(", ...
[ 650, 4 ]
[ 654, 41 ]
python
en
['en', 'en', 'en']
True
AssertionRewriter.display
(self, expr)
Call py.io.saferepr on the expression.
Call py.io.saferepr on the expression.
def display(self, expr): """Call py.io.saferepr on the expression.""" return self.helper("saferepr", expr)
[ "def", "display", "(", "self", ",", "expr", ")", ":", "return", "self", ".", "helper", "(", "\"saferepr\"", ",", "expr", ")" ]
[ 656, 4 ]
[ 658, 44 ]
python
en
['en', 'en', 'en']
True
AssertionRewriter.helper
(self, name, *args)
Call a helper in this module.
Call a helper in this module.
def helper(self, name, *args): """Call a helper in this module.""" py_name = ast.Name("@pytest_ar", ast.Load()) attr = ast.Attribute(py_name, "_" + name, ast.Load()) return ast_Call(attr, list(args), [])
[ "def", "helper", "(", "self", ",", "name", ",", "*", "args", ")", ":", "py_name", "=", "ast", ".", "Name", "(", "\"@pytest_ar\"", ",", "ast", ".", "Load", "(", ")", ")", "attr", "=", "ast", ".", "Attribute", "(", "py_name", ",", "\"_\"", "+", "na...
[ 660, 4 ]
[ 664, 45 ]
python
en
['en', 'gd', 'en']
True
AssertionRewriter.builtin
(self, name)
Return the builtin called *name*.
Return the builtin called *name*.
def builtin(self, name): """Return the builtin called *name*.""" builtin_name = ast.Name("@py_builtins", ast.Load()) return ast.Attribute(builtin_name, name, ast.Load())
[ "def", "builtin", "(", "self", ",", "name", ")", ":", "builtin_name", "=", "ast", ".", "Name", "(", "\"@py_builtins\"", ",", "ast", ".", "Load", "(", ")", ")", "return", "ast", ".", "Attribute", "(", "builtin_name", ",", "name", ",", "ast", ".", "Loa...
[ 666, 4 ]
[ 669, 60 ]
python
en
['en', 'en', 'en']
True
AssertionRewriter.explanation_param
(self, expr)
Return a new named %-formatting placeholder for expr. This creates a %-formatting placeholder for expr in the current formatting context, e.g. ``%(py0)s``. The placeholder and expr are placed in the current format context so that it can be used on the next call to .pop_format_context()...
Return a new named %-formatting placeholder for expr.
def explanation_param(self, expr): """Return a new named %-formatting placeholder for expr. This creates a %-formatting placeholder for expr in the current formatting context, e.g. ``%(py0)s``. The placeholder and expr are placed in the current format context so that it can be ...
[ "def", "explanation_param", "(", "self", ",", "expr", ")", ":", "specifier", "=", "\"py\"", "+", "str", "(", "next", "(", "self", ".", "variable_counter", ")", ")", "self", ".", "explanation_specifiers", "[", "specifier", "]", "=", "expr", "return", "\"%(\...
[ 671, 4 ]
[ 682, 38 ]
python
en
['da', 'en', 'en']
True
AssertionRewriter.push_format_context
(self)
Create a new formatting context. The format context is used for when an explanation wants to have a variable value formatted in the assertion message. In this case the value required can be added using .explanation_param(). Finally .pop_format_context() is used to format a str...
Create a new formatting context.
def push_format_context(self): """Create a new formatting context. The format context is used for when an explanation wants to have a variable value formatted in the assertion message. In this case the value required can be added using .explanation_param(). Finally .pop_format...
[ "def", "push_format_context", "(", "self", ")", ":", "self", ".", "explanation_specifiers", "=", "{", "}", "self", ".", "stack", ".", "append", "(", "self", ".", "explanation_specifiers", ")" ]
[ 684, 4 ]
[ 696, 54 ]
python
en
['it', 'en', 'en']
True
AssertionRewriter.pop_format_context
(self, expl_expr)
Format the %-formatted string with current format context. The expl_expr should be an ast.Str instance constructed from the %-placeholders created by .explanation_param(). This will add the required code to format said string to .on_failure and return the ast.Name instance of the forma...
Format the %-formatted string with current format context.
def pop_format_context(self, expl_expr): """Format the %-formatted string with current format context. The expl_expr should be an ast.Str instance constructed from the %-placeholders created by .explanation_param(). This will add the required code to format said string to .on_failure a...
[ "def", "pop_format_context", "(", "self", ",", "expl_expr", ")", ":", "current", "=", "self", ".", "stack", ".", "pop", "(", ")", "if", "self", ".", "stack", ":", "self", ".", "explanation_specifiers", "=", "self", ".", "stack", "[", "-", "1", "]", "...
[ 698, 4 ]
[ 715, 41 ]
python
en
['en', 'en', 'en']
True
AssertionRewriter.generic_visit
(self, node)
Handle expressions we don't have custom code for.
Handle expressions we don't have custom code for.
def generic_visit(self, node): """Handle expressions we don't have custom code for.""" assert isinstance(node, ast.expr) res = self.assign(node) return res, self.explanation_param(self.display(res))
[ "def", "generic_visit", "(", "self", ",", "node", ")", ":", "assert", "isinstance", "(", "node", ",", "ast", ".", "expr", ")", "res", "=", "self", ".", "assign", "(", "node", ")", "return", "res", ",", "self", ".", "explanation_param", "(", "self", "...
[ 717, 4 ]
[ 721, 61 ]
python
en
['en', 'en', 'en']
True
AssertionRewriter.visit_Assert
(self, assert_)
Return the AST statements to replace the ast.Assert instance. This rewrites the test of an assertion to provide intermediate values and replace it with an if statement which raises an assertion error with a detailed explanation in case the expression is false.
Return the AST statements to replace the ast.Assert instance.
def visit_Assert(self, assert_): """Return the AST statements to replace the ast.Assert instance. This rewrites the test of an assertion to provide intermediate values and replace it with an if statement which raises an assertion error with a detailed explanation in case the exp...
[ "def", "visit_Assert", "(", "self", ",", "assert_", ")", ":", "if", "isinstance", "(", "assert_", ".", "test", ",", "ast", ".", "Tuple", ")", "and", "self", ".", "config", "is", "not", "None", ":", "fslocation", "=", "(", "self", ".", "module_path", ...
[ 723, 4 ]
[ 773, 30 ]
python
en
['en', 'en', 'en']
True
AssertionRewriter.visit_Call_35
(self, call)
visit `ast.Call` nodes on Python3.5 and after
visit `ast.Call` nodes on Python3.5 and after
def visit_Call_35(self, call): """ visit `ast.Call` nodes on Python3.5 and after """ new_func, func_expl = self.visit(call.func) arg_expls = [] new_args = [] new_kwargs = [] for arg in call.args: res, expl = self.visit(arg) arg_expl...
[ "def", "visit_Call_35", "(", "self", ",", "call", ")", ":", "new_func", ",", "func_expl", "=", "self", ".", "visit", "(", "call", ".", "func", ")", "arg_expls", "=", "[", "]", "new_args", "=", "[", "]", "new_kwargs", "=", "[", "]", "for", "arg", "i...
[ 834, 4 ]
[ 859, 30 ]
python
en
['en', 'error', 'th']
False
AssertionRewriter.visit_Call_legacy
(self, call)
visit `ast.Call nodes on 3.4 and below`
visit `ast.Call nodes on 3.4 and below`
def visit_Call_legacy(self, call): """ visit `ast.Call nodes on 3.4 and below` """ new_func, func_expl = self.visit(call.func) arg_expls = [] new_args = [] new_kwargs = [] new_star = new_kwarg = None for arg in call.args: res, expl = se...
[ "def", "visit_Call_legacy", "(", "self", ",", "call", ")", ":", "new_func", ",", "func_expl", "=", "self", ".", "visit", "(", "call", ".", "func", ")", "arg_expls", "=", "[", "]", "new_args", "=", "[", "]", "new_kwargs", "=", "[", "]", "new_star", "=...
[ 866, 4 ]
[ 895, 30 ]
python
en
['en', 'error', 'th']
False
test_module_level_skip_error
(testdir)
Verify that using pytest.skip at module level causes a collection error
Verify that using pytest.skip at module level causes a collection error
def test_module_level_skip_error(testdir): """ Verify that using pytest.skip at module level causes a collection error """ testdir.makepyfile(""" import pytest @pytest.skip def test_func(): assert True """) result = testdir.runpytest() result.stdout.fnmatc...
[ "def", "test_module_level_skip_error", "(", "testdir", ")", ":", "testdir", ".", "makepyfile", "(", "\"\"\"\n import pytest\n @pytest.skip\n def test_func():\n assert True\n \"\"\"", ")", "result", "=", "testdir", ".", "runpytest", "(", ")", "...
[ 996, 0 ]
[ 1009, 5 ]
python
en
['en', 'error', 'th']
False
test_module_level_skip_with_allow_module_level
(testdir)
Verify that using pytest.skip(allow_module_level=True) is allowed
Verify that using pytest.skip(allow_module_level=True) is allowed
def test_module_level_skip_with_allow_module_level(testdir): """ Verify that using pytest.skip(allow_module_level=True) is allowed """ testdir.makepyfile(""" import pytest pytest.skip("skip_module_level", allow_module_level=True) def test_func(): assert 0 """) ...
[ "def", "test_module_level_skip_with_allow_module_level", "(", "testdir", ")", ":", "testdir", ".", "makepyfile", "(", "\"\"\"\n import pytest\n pytest.skip(\"skip_module_level\", allow_module_level=True)\n\n def test_func():\n assert 0\n \"\"\"", ")", "resu...
[ 1012, 0 ]
[ 1026, 5 ]
python
en
['en', 'error', 'th']
False
test_invalid_skip_keyword_parameter
(testdir)
Verify that using pytest.skip() with unknown parameter raises an error
Verify that using pytest.skip() with unknown parameter raises an error
def test_invalid_skip_keyword_parameter(testdir): """ Verify that using pytest.skip() with unknown parameter raises an error """ testdir.makepyfile(""" import pytest pytest.skip("skip_module_level", unknown=1) def test_func(): assert 0 """) result = testdir.r...
[ "def", "test_invalid_skip_keyword_parameter", "(", "testdir", ")", ":", "testdir", ".", "makepyfile", "(", "\"\"\"\n import pytest\n pytest.skip(\"skip_module_level\", unknown=1)\n\n def test_func():\n assert 0\n \"\"\"", ")", "result", "=", "testdir", ...
[ 1029, 0 ]
[ 1043, 5 ]
python
en
['en', 'error', 'th']
False
TestXFail.test_strict_sanity
(self, testdir)
sanity check for xfail(strict=True): a failing test should behave exactly like a normal xfail.
sanity check for xfail(strict=True): a failing test should behave exactly like a normal xfail.
def test_strict_sanity(self, testdir): """sanity check for xfail(strict=True): a failing test should behave exactly like a normal xfail. """ p = testdir.makepyfile(""" import pytest @pytest.mark.xfail(reason='unsupported feature', strict=True) def test...
[ "def", "test_strict_sanity", "(", "self", ",", "testdir", ")", ":", "p", "=", "testdir", ".", "makepyfile", "(", "\"\"\"\n import pytest\n @pytest.mark.xfail(reason='unsupported feature', strict=True)\n def test_foo():\n assert 0\n \...
[ 370, 4 ]
[ 385, 30 ]
python
en
['en', 'en', 'en']
True
Command.__init__
(self, dist)
Create and initialize a new Command object. Most importantly, invokes the 'initialize_options()' method, which is the real initializer and depends on the actual command being instantiated.
Create and initialize a new Command object. Most importantly, invokes the 'initialize_options()' method, which is the real initializer and depends on the actual command being instantiated.
def __init__(self, dist): """Create and initialize a new Command object. Most importantly, invokes the 'initialize_options()' method, which is the real initializer and depends on the actual command being instantiated. """ # late import because of mutual dependence betwee...
[ "def", "__init__", "(", "self", ",", "dist", ")", ":", "# late import because of mutual dependence between these classes", "from", "distutils", ".", "dist", "import", "Distribution", "if", "not", "isinstance", "(", "dist", ",", "Distribution", ")", ":", "raise", "Ty...
[ 46, 4 ]
[ 91, 26 ]
python
en
['en', 'en', 'en']
True
Command.initialize_options
(self)
Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies between options; generally, 'initialize_option...
Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies between options; generally, 'initialize_option...
def initialize_options(self): """Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies betwe...
[ "def", "initialize_options", "(", "self", ")", ":", "raise", "RuntimeError", "(", "\"abstract method -- subclass %s must override\"", "%", "self", ".", "__class__", ")" ]
[ 122, 4 ]
[ 133, 44 ]
python
en
['en', 'en', 'en']
True
Command.finalize_options
(self)
Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if 'foo' depends on 'bar', then...
Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if 'foo' depends on 'bar', then...
def finalize_options(self): """Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: ...
[ "def", "finalize_options", "(", "self", ")", ":", "raise", "RuntimeError", "(", "\"abstract method -- subclass %s must override\"", "%", "self", ".", "__class__", ")" ]
[ 135, 4 ]
[ 147, 44 ]
python
en
['en', 'en', 'en']
True
Command.run
(self)
A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in 'finalize_options()'. All terminal output and files...
A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in 'finalize_options()'. All terminal output and files...
def run(self): """A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in 'finalize_options()'. All...
[ "def", "run", "(", "self", ")", ":", "raise", "RuntimeError", "(", "\"abstract method -- subclass %s must override\"", "%", "self", ".", "__class__", ")" ]
[ 164, 4 ]
[ 175, 44 ]
python
en
['en', 'fr', 'en']
True
Command.announce
(self, msg, level=1)
If the current verbosity level is of greater than or equal to 'level' print 'msg' to stdout.
If the current verbosity level is of greater than or equal to 'level' print 'msg' to stdout.
def announce(self, msg, level=1): """If the current verbosity level is of greater than or equal to 'level' print 'msg' to stdout. """ log.log(level, msg)
[ "def", "announce", "(", "self", ",", "msg", ",", "level", "=", "1", ")", ":", "log", ".", "log", "(", "level", ",", "msg", ")" ]
[ 177, 4 ]
[ 181, 27 ]
python
en
['en', 'en', 'en']
True
Command.debug_print
(self, msg)
Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.
Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.
def debug_print(self, msg): """Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true. """ from distutils.debug import DEBUG if DEBUG: print(msg) sys.stdout.flush()
[ "def", "debug_print", "(", "self", ",", "msg", ")", ":", "from", "distutils", ".", "debug", "import", "DEBUG", "if", "DEBUG", ":", "print", "(", "msg", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
[ 183, 4 ]
[ 190, 30 ]
python
en
['en', 'en', 'en']
True
Command.ensure_string
(self, option, default=None)
Ensure that 'option' is a string; if not defined, set it to 'default'.
Ensure that 'option' is a string; if not defined, set it to 'default'.
def ensure_string(self, option, default=None): """Ensure that 'option' is a string; if not defined, set it to 'default'. """ self._ensure_stringlike(option, "string", default)
[ "def", "ensure_string", "(", "self", ",", "option", ",", "default", "=", "None", ")", ":", "self", ".", "_ensure_stringlike", "(", "option", ",", "\"string\"", ",", "default", ")" ]
[ 216, 4 ]
[ 220, 58 ]
python
en
['en', 'en', 'en']
True
Command.ensure_string_list
(self, option)
r"""Ensure that 'option' is a list of strings. If 'option' is currently a string, we split it either on /,\s*/ or /\s+/, so "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become ["foo", "bar", "baz"].
r"""Ensure that 'option' is a list of strings. If 'option' is currently a string, we split it either on /,\s*/ or /\s+/, so "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become ["foo", "bar", "baz"].
def ensure_string_list(self, option): r"""Ensure that 'option' is a list of strings. If 'option' is currently a string, we split it either on /,\s*/ or /\s+/, so "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become ["foo", "bar", "baz"]. """ val = getattr(self, ...
[ "def", "ensure_string_list", "(", "self", ",", "option", ")", ":", "val", "=", "getattr", "(", "self", ",", "option", ")", "if", "val", "is", "None", ":", "return", "elif", "isinstance", "(", "val", ",", "str", ")", ":", "setattr", "(", "self", ",", ...
[ 222, 4 ]
[ 241, 38 ]
python
en
['en', 'en', 'en']
True
Command.ensure_filename
(self, option)
Ensure that 'option' is the name of an existing file.
Ensure that 'option' is the name of an existing file.
def ensure_filename(self, option): """Ensure that 'option' is the name of an existing file.""" self._ensure_tested_string(option, os.path.isfile, "filename", "'%s' does not exist or is not a file")
[ "def", "ensure_filename", "(", "self", ",", "option", ")", ":", "self", ".", "_ensure_tested_string", "(", "option", ",", "os", ".", "path", ".", "isfile", ",", "\"filename\"", ",", "\"'%s' does not exist or is not a file\"", ")" ]
[ 250, 4 ]
[ 254, 74 ]
python
en
['en', 'en', 'en']
True
Command.set_undefined_options
(self, src_cmd, *option_pairs)
Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between 'initialize_options()' and 'finalize_options()'. Usually calle...
Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between 'initialize_options()' and 'finalize_options()'. Usually calle...
def set_undefined_options(self, src_cmd, *option_pairs): """Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between 'in...
[ "def", "set_undefined_options", "(", "self", ",", "src_cmd", ",", "*", "option_pairs", ")", ":", "# Option_pairs: list of (src_option, dst_option) tuples", "src_cmd_obj", "=", "self", ".", "distribution", ".", "get_command_obj", "(", "src_cmd", ")", "src_cmd_obj", ".", ...
[ 270, 4 ]
[ 289, 75 ]
python
en
['en', 'en', 'en']
True
Command.get_finalized_command
(self, command, create=1)
Wrapper around Distribution's 'get_command_obj()' method: find (create if necessary and 'create' is true) the command object for 'command', call its 'ensure_finalized()' method, and return the finalized command object.
Wrapper around Distribution's 'get_command_obj()' method: find (create if necessary and 'create' is true) the command object for 'command', call its 'ensure_finalized()' method, and return the finalized command object.
def get_finalized_command(self, command, create=1): """Wrapper around Distribution's 'get_command_obj()' method: find (create if necessary and 'create' is true) the command object for 'command', call its 'ensure_finalized()' method, and return the finalized command object. """ ...
[ "def", "get_finalized_command", "(", "self", ",", "command", ",", "create", "=", "1", ")", ":", "cmd_obj", "=", "self", ".", "distribution", ".", "get_command_obj", "(", "command", ",", "create", ")", "cmd_obj", ".", "ensure_finalized", "(", ")", "return", ...
[ 291, 4 ]
[ 299, 22 ]
python
en
['en', 'de', 'en']
True
Command.run_command
(self, command)
Run some other command: uses the 'run_command()' method of Distribution, which creates and finalizes the command object if necessary and then invokes its 'run()' method.
Run some other command: uses the 'run_command()' method of Distribution, which creates and finalizes the command object if necessary and then invokes its 'run()' method.
def run_command(self, command): """Run some other command: uses the 'run_command()' method of Distribution, which creates and finalizes the command object if necessary and then invokes its 'run()' method. """ self.distribution.run_command(command)
[ "def", "run_command", "(", "self", ",", "command", ")", ":", "self", ".", "distribution", ".", "run_command", "(", "command", ")" ]
[ 307, 4 ]
[ 312, 46 ]
python
en
['en', 'en', 'en']
True
Command.get_sub_commands
(self)
Determine the sub-commands that are relevant in the current distribution (ie., that need to be run). This is based on the 'sub_commands' class attribute: each tuple in that list may include a method that we call to determine if the subcommand needs to be run for the current distribution...
Determine the sub-commands that are relevant in the current distribution (ie., that need to be run). This is based on the 'sub_commands' class attribute: each tuple in that list may include a method that we call to determine if the subcommand needs to be run for the current distribution...
def get_sub_commands(self): """Determine the sub-commands that are relevant in the current distribution (ie., that need to be run). This is based on the 'sub_commands' class attribute: each tuple in that list may include a method that we call to determine if the subcommand needs to be ...
[ "def", "get_sub_commands", "(", "self", ")", ":", "commands", "=", "[", "]", "for", "(", "cmd_name", ",", "method", ")", "in", "self", ".", "sub_commands", ":", "if", "method", "is", "None", "or", "method", "(", "self", ")", ":", "commands", ".", "ap...
[ 314, 4 ]
[ 325, 23 ]
python
en
['en', 'en', 'en']
True
Command.copy_file
(self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1)
Copy a file respecting verbose, dry-run and force flags. (The former two default to whatever is in the Distribution object, and the latter defaults to false for commands that don't define it.)
Copy a file respecting verbose, dry-run and force flags. (The former two default to whatever is in the Distribution object, and the latter defaults to false for commands that don't define it.)
def copy_file(self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1): """Copy a file respecting verbose, dry-run and force flags. (The former two default to whatever is in the Distribution object, and the latter defaults to false for commands that don't ...
[ "def", "copy_file", "(", "self", ",", "infile", ",", "outfile", ",", "preserve_mode", "=", "1", ",", "preserve_times", "=", "1", ",", "link", "=", "None", ",", "level", "=", "1", ")", ":", "return", "file_util", ".", "copy_file", "(", "infile", ",", ...
[ 339, 4 ]
[ 346, 56 ]
python
en
['en', 'en', 'en']
True
Command.copy_tree
(self, infile, outfile, preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1)
Copy an entire directory tree respecting verbose, dry-run, and force flags.
Copy an entire directory tree respecting verbose, dry-run, and force flags.
def copy_tree(self, infile, outfile, preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1): """Copy an entire directory tree respecting verbose, dry-run, and force flags. """ return dir_util.copy_tree(infile, outfile, preserve_mode, ...
[ "def", "copy_tree", "(", "self", ",", "infile", ",", "outfile", ",", "preserve_mode", "=", "1", ",", "preserve_times", "=", "1", ",", "preserve_symlinks", "=", "0", ",", "level", "=", "1", ")", ":", "return", "dir_util", ".", "copy_tree", "(", "infile", ...
[ 348, 4 ]
[ 355, 71 ]
python
en
['en', 'en', 'en']
True
Command.move_file
(self, src, dst, level=1)
Move a file respecting dry-run flag.
Move a file respecting dry-run flag.
def move_file (self, src, dst, level=1): """Move a file respecting dry-run flag.""" return file_util.move_file(src, dst, dry_run=self.dry_run)
[ "def", "move_file", "(", "self", ",", "src", ",", "dst", ",", "level", "=", "1", ")", ":", "return", "file_util", ".", "move_file", "(", "src", ",", "dst", ",", "dry_run", "=", "self", ".", "dry_run", ")" ]
[ 357, 4 ]
[ 359, 66 ]
python
en
['id', 'en', 'en']
True
Command.spawn
(self, cmd, search_path=1, level=1)
Spawn an external command respecting dry-run flag.
Spawn an external command respecting dry-run flag.
def spawn(self, cmd, search_path=1, level=1): """Spawn an external command respecting dry-run flag.""" from distutils.spawn import spawn spawn(cmd, search_path, dry_run=self.dry_run)
[ "def", "spawn", "(", "self", ",", "cmd", ",", "search_path", "=", "1", ",", "level", "=", "1", ")", ":", "from", "distutils", ".", "spawn", "import", "spawn", "spawn", "(", "cmd", ",", "search_path", ",", "dry_run", "=", "self", ".", "dry_run", ")" ]
[ 361, 4 ]
[ 364, 53 ]
python
en
['en', 'lb', 'en']
True
Command.make_file
(self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1)
Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a different message printed if 'outfile' already exists and is newer than all files listed in 'infiles'. If the...
Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a different message printed if 'outfile' already exists and is newer than all files listed in 'infiles'. If the...
def make_file(self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1): """Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a differe...
[ "def", "make_file", "(", "self", ",", "infiles", ",", "outfile", ",", "func", ",", "args", ",", "exec_msg", "=", "None", ",", "skip_msg", "=", "None", ",", "level", "=", "1", ")", ":", "if", "skip_msg", "is", "None", ":", "skip_msg", "=", "\"skipping...
[ 372, 4 ]
[ 402, 31 ]
python
en
['en', 'en', 'en']
True
add_track_to_sequence
(note_sequence, instrument, notes, is_drum=False, program=0)
Adds instrument track to NoteSequence.
Adds instrument track to NoteSequence.
def add_track_to_sequence(note_sequence, instrument, notes, is_drum=False, program=0): """Adds instrument track to NoteSequence.""" for pitch, velocity, start_time, end_time in notes: note = note_sequence.not...
[ "def", "add_track_to_sequence", "(", "note_sequence", ",", "instrument", ",", "notes", ",", "is_drum", "=", "False", ",", "program", "=", "0", ")", ":", "for", "pitch", ",", "velocity", ",", "start_time", ",", "end_time", "in", "notes", ":", "note", "=", ...
[ 32, 0 ]
[ 48, 41 ]
python
en
['en', 'en', 'en']
True
ProtoTestCase._AssertProtoEquals
(self, a, b, msg=None)
Asserts that a and b are the same proto. Uses ProtoEq() first, as it returns correct results for floating point attributes, and then use assertProtoEqual() in case of failure as it provides good error messages. Args: a: a proto. b: another proto. msg: Optional message to report on fa...
Asserts that a and b are the same proto.
def _AssertProtoEquals(self, a, b, msg=None): # pylint:disable=invalid-name """Asserts that a and b are the same proto. Uses ProtoEq() first, as it returns correct results for floating point attributes, and then use assertProtoEqual() in case of failure as it provides good error messages. Args: ...
[ "def", "_AssertProtoEquals", "(", "self", ",", "a", ",", "b", ",", "msg", "=", "None", ")", ":", "# pylint:disable=invalid-name", "if", "not", "compare", ".", "ProtoEq", "(", "a", ",", "b", ")", ":", "compare", ".", "assertProtoEqual", "(", "self", ",", ...
[ 180, 2 ]
[ 193, 75 ]
python
en
['en', 'en', 'en']
True