text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_simple_dirs(self, simple_dir: Path) -> List[Path]: """Return a list of simple index directories that should be searched for package indexes when compiling the main index page.""" |
if self.hash_index:
# We are using index page directory hashing, so the directory
# format is /simple/f/foo/. We want to return a list of dirs
# like "simple/f".
subdirs = [simple_dir / x for x in simple_dir.iterdir() if x.is_dir()]
else:
# This is the traditional layout of /simple/foo/. We should
# return a single directory, "simple".
subdirs = [simple_dir]
return subdirs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_package_indexes_in_dir(self, simple_dir):
"""Given a directory that contains simple packages indexes, return a sorted list of normalized package names. This presumes every directory within is a simple package index directory.""" |
packages = sorted(
{
# Filter out all of the "non" normalized names here
canonicalize_name(x)
for x in os.listdir(simple_dir)
}
)
# Package indexes must be in directories, so ignore anything else.
packages = [x for x in packages if os.path.isdir(os.path.join(simple_dir, x))]
return packages |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_configuration(self) -> None: """ Read the configuration from a configuration file """ |
config_file = self.default_config_file
if self.config_file:
config_file = self.config_file
self.config = ConfigParser()
self.config.read(config_file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def metadata_verify(config, args) -> int: """ Crawl all saved JSON metadata or online to check we have all packages if delete - generate a diff of unowned files """ |
all_package_files = [] # type: List[Path]
loop = asyncio.get_event_loop()
mirror_base = config.get("mirror", "directory")
json_base = Path(mirror_base) / "web" / "json"
workers = args.workers or config.getint("mirror", "workers")
executor = concurrent.futures.ThreadPoolExecutor(max_workers=workers)
logger.info(f"Starting verify for {mirror_base} with {workers} workers")
try:
json_files = await loop.run_in_executor(executor, os.listdir, json_base)
except FileExistsError as fee:
logger.error(f"Metadata base dir {json_base} does not exist: {fee}")
return 2
if not json_files:
logger.error("No JSON metadata files found. Can not verify")
return 3
logger.debug(f"Found {len(json_files)} objects in {json_base}")
logger.debug(f"Using a {workers} thread ThreadPoolExecutor")
await async_verify(
config, all_package_files, mirror_base, json_files, args, executor
)
if not args.delete:
return 0
return await delete_files(mirror_base, executor, all_package_files, args.dry_run) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _der_to_pem(der_key, marker):
""" Perform a simple DER to PEM conversion. """ |
pem_key_chunks = [('-----BEGIN %s-----' % marker).encode('utf-8')]
# Limit base64 output lines to 64 characters by limiting input lines to 48 characters.
for chunk_start in range(0, len(der_key), 48):
pem_key_chunks.append(b64encode(der_key[chunk_start:chunk_start + 48]))
pem_key_chunks.append(('-----END %s-----' % marker).encode('utf-8'))
return b'\n'.join(pem_key_chunks) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _der_to_raw(self, der_signature):
"""Convert signature from DER encoding to RAW encoding.""" |
r, s = decode_dss_signature(der_signature)
component_length = self._sig_component_length()
return int_to_bytes(r, component_length) + int_to_bytes(s, component_length) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _raw_to_der(self, raw_signature):
"""Convert signature from RAW encoding to DER encoding.""" |
component_length = self._sig_component_length()
if len(raw_signature) != int(2 * component_length):
raise ValueError("Invalid signature")
r_bytes = raw_signature[:component_length]
s_bytes = raw_signature[component_length:]
r = int_from_bytes(r_bytes, "big")
s = int_from_bytes(s_bytes, "big")
return encode_dss_signature(r, s) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None):
"""Encodes a claims set and returns a JWT string. JWTs are JWS signed objects with a few reserved claims. Args: claims (dict):
A claims set to sign key (str or dict):
The key to use for signing the claim set. Can be individual JWK or JWK set. algorithm (str, optional):
The algorithm to use for signing the the claims. Defaults to HS256. headers (dict, optional):
A set of headers that will be added to the default headers. Any headers that are added as additional headers will override the default headers. access_token (str, optional):
If present, the 'at_hash' claim will be calculated and added to the claims present in the 'claims' parameter. Returns: str: The string representation of the header, claims, and signature. Raises: JWTError: If there is an error encoding the claims. Examples: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' """ |
for time_claim in ['exp', 'iat', 'nbf']:
# Convert datetime to a intDate value in known time-format claims
if isinstance(claims.get(time_claim), datetime):
claims[time_claim] = timegm(claims[time_claim].utctimetuple())
if access_token:
claims['at_hash'] = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
return jws.sign(claims, key, headers=headers, algorithm=algorithm) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode(token, key, algorithms=None, options=None, audience=None, issuer=None, subject=None, access_token=None):
"""Verifies a JWT string's signature and validates reserved claims. Args: token (str):
A signed JWS to be verified. key (str or dict):
A key to attempt to verify the payload with. Can be individual JWK or JWK set. algorithms (str or list):
Valid algorithms that should be used to verify the JWS. audience (str):
The intended audience of the token. If the "aud" claim is included in the claim set, then the audience must be included and must equal the provided claim. issuer (str or iterable):
Acceptable value(s) for the issuer of the token. If the "iss" claim is included in the claim set, then the issuer must be given and the claim in the token must be among the acceptable values. subject (str):
The subject of the token. If the "sub" claim is included in the claim set, then the subject must be included and must equal the provided claim. access_token (str):
An access token string. If the "at_hash" claim is included in the claim set, then the access_token must be included, and it must match the "at_hash" claim. options (dict):
A dictionary of options for skipping validation steps. defaults = { 'verify_signature': True, 'verify_aud': True, 'verify_iat': True, 'verify_exp': True, 'verify_nbf': True, 'verify_iss': True, 'verify_sub': True, 'verify_jti': True, 'verify_at_hash': True, 'require_aud': False, 'require_iat': False, 'require_exp': False, 'require_nbf': False, 'require_iss': False, 'require_sub': False, 'require_jti': False, 'require_at_hash': False, 'leeway': 0, } Returns: dict: The dict representation of the claims set, assuming the signature is valid and all requested data validation passes. Raises: JWTError: If the signature is invalid in any way. ExpiredSignatureError: If the signature has expired. JWTClaimsError: If any claim is invalid in any way. Examples: """ |
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
if options:
defaults.update(options)
verify_signature = defaults.get('verify_signature', True)
try:
payload = jws.verify(token, key, algorithms, verify=verify_signature)
except JWSError as e:
raise JWTError(e)
# Needed for at_hash verification
algorithm = jws.get_unverified_header(token)['alg']
try:
claims = json.loads(payload.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid payload string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid payload string: must be a json object')
_validate_claims(claims, audience=audience, issuer=issuer,
subject=subject, algorithm=algorithm,
access_token=access_token,
options=defaults)
return claims |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_nbf(claims, leeway=0):
"""Validates that the 'nbf' claim is valid. The "nbf" (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the "nbf" claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the "nbf" claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL. Args: claims (dict):
The claims dictionary to validate. leeway (int):
The number of seconds of skew that is allowed. """ |
if 'nbf' not in claims:
return
try:
nbf = int(claims['nbf'])
except ValueError:
raise JWTClaimsError('Not Before claim (nbf) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if nbf > (now + leeway):
raise JWTClaimsError('The token is not yet valid (nbf)') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_exp(claims, leeway=0):
"""Validates that the 'exp' claim is valid. The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the "exp" claim requires that the current date/time MUST be before the expiration date/time listed in the "exp" claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL. Args: claims (dict):
The claims dictionary to validate. leeway (int):
The number of seconds of skew that is allowed. """ |
if 'exp' not in claims:
return
try:
exp = int(claims['exp'])
except ValueError:
raise JWTClaimsError('Expiration Time claim (exp) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if exp < (now - leeway):
raise ExpiredSignatureError('Signature has expired.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_aud(claims, audience=None):
"""Validates that the 'aud' claim is valid. The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected. In the general case, the "aud" value is an array of case- sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the "aud" value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL. Args: claims (dict):
The claims dictionary to validate. audience (str):
The audience that is verifying the token. """ |
if 'aud' not in claims:
# if audience:
# raise JWTError('Audience claim expected, but not in claims')
return
audience_claims = claims['aud']
if isinstance(audience_claims, string_types):
audience_claims = [audience_claims]
if not isinstance(audience_claims, list):
raise JWTClaimsError('Invalid claim format in token')
if any(not isinstance(c, string_types) for c in audience_claims):
raise JWTClaimsError('Invalid claim format in token')
if audience not in audience_claims:
raise JWTClaimsError('Invalid audience') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_iss(claims, issuer=None):
"""Validates that the 'iss' claim is valid. The "iss" (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The "iss" value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL. Args: claims (dict):
The claims dictionary to validate. issuer (str or iterable):
Acceptable value(s) for the issuer that signed the token. """ |
if issuer is not None:
if isinstance(issuer, string_types):
issuer = (issuer,)
if claims.get('iss') not in issuer:
raise JWTClaimsError('Invalid issuer') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_sub(claims, subject=None):
"""Validates that the 'sub' claim is valid. The "sub" (subject) claim identifies the principal that is the subject of the JWT. The claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The "sub" value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL. Args: claims (dict):
The claims dictionary to validate. subject (str):
The subject of the token. """ |
if 'sub' not in claims:
return
if not isinstance(claims['sub'], string_types):
raise JWTClaimsError('Subject must be a string.')
if subject is not None:
if claims.get('sub') != subject:
raise JWTClaimsError('Invalid subject') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b. Unless b==0, the result will have the same sign as b (so that when b is divided by it, the result comes out positive). """ |
while b:
a, b = b, (a % b)
return a |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rsa_recover_prime_factors(n, e, d):
""" Compute factors p and q from the private exponent d. We assume that n has no more than two factors. This function is adapted from code in PyCrypto. """ |
# See 8.2.2(i) in Handbook of Applied Cryptography.
ktot = d * e - 1
# The quantity d*e-1 is a multiple of phi(n), even,
# and can be represented as t*2^s.
t = ktot
while t % 2 == 0:
t = t // 2
# Cycle through all multiplicative inverses in Zn.
# The algorithm is non-deterministic, but there is a 50% chance
# any candidate a leads to successful factoring.
# See "Digitalized Signatures and Public Key Functions as Intractable
# as Factorization", M. Rabin, 1979
spotted = False
a = 2
while not spotted and a < _MAX_RECOVERY_ATTEMPTS:
k = t
# Cycle through all values a^{t*2^i}=a^k
while k < ktot:
cand = pow(a, k, n)
# Check if a^k is a non-trivial root of unity (mod n)
if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
# We have found a number such that (cand-1)(cand+1)=0 (mod n).
# Either of the terms divides n.
p = _gcd(cand + 1, n)
spotted = True
break
k *= 2
# This value was not any good... let's try another!
a += 2
if not spotted:
raise ValueError("Unable to compute factors p and q from exponent d.")
# Found !
q, r = divmod(n, p)
assert r == 0
p, q = sorted((p, q), reverse=True)
return (p, q) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _legacy_private_key_pkcs8_to_pkcs1(pkcs8_key):
"""Legacy RSA private key PKCS8-to-PKCS1 conversion. .. warning:: This is incorrect parsing and only works because the legacy PKCS1-to-PKCS8 encoding was also incorrect. """ |
# Only allow this processing if the prefix matches
# AND the following byte indicates an ASN1 sequence,
# as we would expect with the legacy encoding.
if not pkcs8_key.startswith(LEGACY_INVALID_PKCS8_RSA_HEADER + ASN1_SEQUENCE_ID):
raise ValueError("Invalid private key encoding")
return pkcs8_key[len(LEGACY_INVALID_PKCS8_RSA_HEADER):] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def base64url_decode(input):
"""Helper method to base64url_decode a string. Args: input (str):
A base64url_encoded string to decode. """ |
rem = len(input) % 4
if rem > 0:
input += b'=' * (4 - rem)
return base64.urlsafe_b64decode(input) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def constant_time_string_compare(a, b):
"""Helper for comparing string in constant time, independent of the python version being used. Args: a (str):
A string to compare b (str):
A string to compare """ |
try:
return hmac.compare_digest(a, b)
except AttributeError:
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256):
"""Signs a claims set and returns a JWS string. Args: payload (str):
A string to sign key (str or dict):
The key to use for signing the claim set. Can be individual JWK or JWK set. headers (dict, optional):
A set of headers that will be added to the default headers. Any headers that are added as additional headers will override the default headers. algorithm (str, optional):
The algorithm to use for signing the the claims. Defaults to HS256. Returns: str: The string representation of the header, claims, and signature. Raises: JWSError: If there is an error signing the token. Examples: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' """ |
if algorithm not in ALGORITHMS.SUPPORTED:
raise JWSError('Algorithm %s not supported.' % algorithm)
encoded_header = _encode_header(algorithm, additional_headers=headers)
encoded_payload = _encode_payload(payload)
signed_output = _sign_header_and_claims(encoded_header, encoded_payload, algorithm, key)
return signed_output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify(token, key, algorithms, verify=True):
"""Verifies a JWS string's signature. Args: token (str):
A signed JWS to be verified. key (str or dict):
A key to attempt to verify the payload with. Can be individual JWK or JWK set. algorithms (str or list):
Valid algorithms that should be used to verify the JWS. Returns: str: The str representation of the payload, assuming the signature is valid. Raises: JWSError: If there is an exception verifying a token. Examples: """ |
header, payload, signing_input, signature = _load(token)
if verify:
_verify_signature(signing_input, header, signature, key, algorithms)
return payload |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def construct(key_data, algorithm=None):
""" Construct a Key object for the given algorithm with the given key_data. """ |
# Allow for pulling the algorithm off of the passed in jwk.
if not algorithm and isinstance(key_data, dict):
algorithm = key_data.get('alg', None)
if not algorithm:
raise JWKError('Unable to find a algorithm for key: %s' % key_data)
key_class = get_key(algorithm)
if not key_class:
raise JWKError('Unable to find a algorithm for key: %s' % key_data)
return key_class(key_data, algorithm) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def train(self, dataset):
r"""Train model with given feature. Parameters X : array-like, shape=(n_samples, n_features) Train feature vector. Y : array-like, shape=(n_samples, n_labels) Target labels. Attributes clfs\_ : list of :py:mod:`libact.models` object instances Classifier instances. Returns ------- self : object Retuen self. """ |
X, Y = dataset.format_sklearn()
X = np.array(X)
Y = np.array(Y)
self.n_labels_ = np.shape(Y)[1]
self.n_features_ = np.shape(X)[1]
self.clfs_ = []
for i in range(self.n_labels_):
# TODO should we handle it here or we should handle it before calling
if len(np.unique(Y[:, i])) == 1:
clf = DummyClf()
else:
clf = copy.deepcopy(self.base_clf)
self.clfs_.append(clf)
Parallel(n_jobs=self.n_jobs, backend='threading')(
delayed(_fit_model)(self.clfs_[i], X, Y[:, i])
for i in range(self.n_labels_))
#clf.train(Dataset(X, Y[:, i]))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict(self, X):
r"""Predict labels. Parameters X : array-like, shape=(n_samples, n_features) Feature vector. Returns ------- pred : numpy array, shape=(n_samples, n_labels) Predicted labels of given feature vector. """ |
X = np.asarray(X)
if self.clfs_ is None:
raise ValueError("Train before prediction")
if X.shape[1] != self.n_features_:
raise ValueError('Given feature size does not match')
pred = np.zeros((X.shape[0], self.n_labels_))
for i in range(self.n_labels_):
pred[:, i] = self.clfs_[i].predict(X)
return pred.astype(int) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict_real(self, X):
r"""Predict the probability of being 1 for each label. Parameters X : array-like, shape=(n_samples, n_features) Feature vector. Returns ------- pred : numpy array, shape=(n_samples, n_labels) Predicted probability of each label. """ |
X = np.asarray(X)
if self.clfs_ is None:
raise ValueError("Train before prediction")
if X.shape[1] != self.n_features_:
raise ValueError('given feature size does not match')
pred = np.zeros((X.shape[0], self.n_labels_))
for i in range(self.n_labels_):
pred[:, i] = self.clfs_[i].predict_real(X)[:, 1]
return pred |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def score(self, testing_dataset, criterion='hamming'):
"""Return the mean accuracy on the test dataset Parameters testing_dataset : Dataset object The testing dataset used to measure the perforance of the trained model. criterion : ['hamming', 'f1'] instance-wise criterion. Returns ------- score : float Mean accuracy of self.predict(X) wrt. y. """ |
# TODO check if data in dataset are all correct
X, Y = testing_dataset.format_sklearn()
if criterion == 'hamming':
return np.mean(np.abs(self.predict(X) - Y).mean(axis=1))
elif criterion == 'f1':
Z = self.predict(X)
Z = Z.astype(int)
Y = Y.astype(int)
up = 2*np.sum(Z & Y, axis=1).astype(float)
down1 = np.sum(Z, axis=1)
down2 = np.sum(Y, axis=1)
down = (down1 + down2)
down[down==0] = 1.
up[down==0] = 1.
return np.mean(up / down)
else:
raise NotImplementedError(
"criterion '%s' not implemented" % criterion) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def seed_random_state(seed):
"""Turn seed into np.random.RandomState instance """ |
if (seed is None) or (isinstance(seed, int)):
return np.random.RandomState(seed)
elif isinstance(seed, np.random.RandomState):
return seed
raise ValueError("%r can not be used to generate numpy.random.RandomState"
" instance" % seed) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_cost(y, yhat, cost_matrix):
"""Calculate the cost with given cost matrix y : ground truth yhat : estimation cost_matrix : array-like, shape=(n_classes, n_classes) The ith row, jth column represents the cost of the ground truth being ith class and prediction as jth class. """ |
return np.mean(cost_matrix[list(y), list(yhat)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_query(self, return_score=False):
"""Return the index of the sample to be queried and labeled and selection score of each sample. Read-only. No modification to the internal states. Returns ------- ask_id : int The index of the next unlabeled sample to be queried and labeled. score : list of (index, score) tuple Selection score of unlabled entries, the larger the better. """ |
dataset = self.dataset
self.model.train(dataset)
unlabeled_entry_ids, X_pool = zip(*dataset.get_unlabeled_entries())
if isinstance(self.model, ProbabilisticModel):
dvalue = self.model.predict_proba(X_pool)
elif isinstance(self.model, ContinuousModel):
dvalue = self.model.predict_real(X_pool)
if self.method == 'lc': # least confident
score = -np.max(dvalue, axis=1)
elif self.method == 'sm': # smallest margin
if np.shape(dvalue)[1] > 2:
# Find 2 largest decision values
dvalue = -(np.partition(-dvalue, 2, axis=1)[:, :2])
score = -np.abs(dvalue[:, 0] - dvalue[:, 1])
elif self.method == 'entropy':
score = np.sum(-dvalue * np.log(dvalue), axis=1)
ask_id = np.argmax(score)
if return_score:
return unlabeled_entry_ids[ask_id], \
list(zip(unlabeled_entry_ids, score))
else:
return unlabeled_entry_ids[ask_id] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _vote_disagreement(self, votes):
""" Return the disagreement measurement of the given number of votes. It uses the vote vote to measure the disagreement. Parameters votes : list of int, shape==(n_samples, n_students) The predictions that each student gives to each sample. Returns ------- disagreement : list of float, shape=(n_samples) The vote entropy of the given votes. """ |
ret = []
for candidate in votes:
ret.append(0.0)
lab_count = {}
for lab in candidate:
lab_count[lab] = lab_count.setdefault(lab, 0) + 1
# Using vote entropy to measure disagreement
for lab in lab_count.keys():
ret[-1] -= lab_count[lab] / self.n_students * \
math.log(float(lab_count[lab]) / self.n_students)
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _labeled_uniform_sample(self, sample_size):
"""sample labeled entries uniformly""" |
labeled_entries = self.dataset.get_labeled_entries()
samples = [labeled_entries[
self.random_state_.randint(0, len(labeled_entries))
]for _ in range(sample_size)]
return Dataset(*zip(*samples)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_reward_fn(self):
"""Calculate the reward value""" |
model = copy.copy(self.model)
model.train(self.dataset)
# reward function: Importance-Weighted-Accuracy (IW-ACC) (tau, f)
reward = 0.
for i in range(len(self.queried_hist_)):
reward += self.W[i] * (
model.predict(
self.dataset.data[
self.queried_hist_[i]][0].reshape(1, -1)
)[0] ==
self.dataset.data[self.queried_hist_[i]][1]
)
reward /= (self.dataset.len_labeled() + self.dataset.len_unlabeled())
reward /= self.T
return reward |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_query(self):
"""Calculate the sampling query distribution""" |
# initial query
if self.query_dist is None:
self.query_dist = self.exp4p_.next(-1, None, None)
else:
self.query_dist = self.exp4p_.next(
self.calc_reward_fn(),
self.queried_hist_[-1],
self.dataset.data[self.queried_hist_[-1]][1]
)
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next(self, reward, ask_id, lbl):
"""Taking the label and the reward value of last question and returns the next question to ask.""" |
# first run don't have reward, TODO exception on reward == -1 only once
if reward == -1:
return next(self.exp4p_gen)
else:
# TODO exception on reward in [0, 1]
return self.exp4p_gen.send((reward, ask_id, lbl)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exp4p(self):
"""The generator which implements the main part of Exp4.P. Parameters reward: float The reward value calculated from ALBL. ask_id: integer The entry_id of the sample point ALBL asked. lbl: integer The answer received from asking the entry_id ask_id. Yields ------ q: array-like, shape = [K] The query vector which tells ALBL what kind of distribution if should sample from the unlabeled pool. """ |
while True:
# TODO probabilistic active learning algorithm
# len(self.unlabeled_invert_id_idx) is the number of unlabeled data
query = np.zeros((self.N, len(self.unlabeled_invert_id_idx)))
if self.uniform_sampler:
query[-1, :] = 1. / len(self.unlabeled_invert_id_idx)
for i, model in enumerate(self.query_strategies_):
query[i][self.unlabeled_invert_id_idx[model.make_query()]] = 1
# choice vector, shape = (self.K, )
W = np.sum(self.w)
p = (1 - self.K * self.pmin) * self.w / W + self.pmin
# query vector, shape= = (self.n_unlabeled, )
query_vector = np.dot(p, query)
reward, ask_id, _ = yield query_vector
ask_idx = self.unlabeled_invert_id_idx[ask_id]
rhat = reward * query[:, ask_idx] / query_vector[ask_idx]
# The original advice vector in Exp4.P in ALBL is a identity matrix
yhat = rhat
vhat = 1 / p
self.w = self.w * np.exp(
self.pmin / 2 * (
yhat + vhat * np.sqrt(
np.log(self.N / self.delta) / self.K / self.T
)
)
)
raise StopIteration |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_libsvm_sparse(filename):
"""Imports dataset file in libsvm sparse format""" |
from sklearn.datasets import load_svmlight_file
X, y = load_svmlight_file(filename)
return Dataset(X.toarray().tolist(), y.tolist()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, entry_id, new_label):
""" Updates an entry with entry_id with the given label Parameters entry_id : int entry id of the sample to update. label : {int, None} Label of the sample to be update. """ |
self.data[entry_id] = (self.data[entry_id][0], new_label)
self.modified = True
for callback in self._update_callback:
callback(entry_id, new_label) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_unlabeled_entries(self):
""" Returns list of unlabeled features, along with their entry_ids Returns ------- unlabeled_entries : list of (entry_id, feature) tuple Labeled entries """ |
return [
(idx, entry[0]) for idx, entry in enumerate(self.data)
if entry[1] is None
] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def labeled_uniform_sample(self, sample_size, replace=True):
"""Returns a Dataset object with labeled data only, which is resampled uniformly with given sample size. Parameter `replace` decides whether sampling with replacement or not. Parameters sample_size """ |
if replace:
samples = [
random.choice(self.get_labeled_entries())
for _ in range(sample_size)
]
else:
samples = random.sample(self.get_labeled_entries(), sample_size)
return Dataset(*zip(*samples)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def push_token(self, tok):
"Push a token onto the stack popped by the get_token method"
if self.debug >= 1:
print("shlex: pushing token " + repr(tok))
self.pushback.appendleft(tok) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_next_positional(self):
""" Get the next positional action if it exists. """ |
active_parser = self.active_parsers[-1]
last_positional = self.visited_positionals[-1]
all_positionals = active_parser._get_positional_actions()
if not all_positionals:
return None
if active_parser == last_positional:
return all_positionals[0]
i = 0
for i in range(len(all_positionals)):
if all_positionals[i] == last_positional:
break
if i + 1 < len(all_positionals):
return all_positionals[i + 1]
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def shellcode(executables, use_defaults=True, shell='bash', complete_arguments=None):
'''
Provide the shell code required to register a python executable for use with the argcomplete module.
:param str executables: Executables to be completed (when invoked exactly with this name
:param bool use_defaults: Whether to fallback to readline's default completion when no matches are generated.
:param str shell: Name of the shell to output code for (bash or tcsh)
:param complete_arguments: Arguments to call complete with
:type complete_arguments: list(str) or None
'''
if complete_arguments is None:
complete_options = '-o nospace -o default' if use_defaults else '-o nospace'
else:
complete_options = " ".join(complete_arguments)
if shell == 'bash':
quoted_executables = [quote(i) for i in executables]
executables_list = " ".join(quoted_executables)
code = bashcode % dict(complete_opts=complete_options, executables=executables_list)
else:
code = ""
for executable in executables:
code += tcshcode % dict(executable=executable)
return code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _send(self, message):
""" Private method for send one message. :param SmsMessage message: SmsMessage class instance. :returns: True if message is sended else False :rtype: bool """ |
params = {
'V': SMSPUBLI_API_VERSION,
'UN': SMSPUBLI_USERNAME,
'PWD': SMSPUBLI_PASSWORD,
'R': SMSPUBLI_ROUTE,
'SA': message.from_phone,
'DA': ','.join(message.to),
'M': message.body.encode('latin-1'),
'DC': SMSPUBLI_DC,
'DR': SMSPUBLI_DR,
'UR': message.from_phone
}
if SMSPUBLI_ALLOW_LONG_SMS:
params['LM'] = '1'
response = requests.post(SMSPUBLI_API_URL, params)
if response.status_code != 200:
if not self.fail_silently:
raise
else:
return False
response_msg, response_code = response.content.split(':')
if response_msg == 'OK':
try:
if "," in response_code:
codes = map(int, response_code.split(","))
else:
codes = [int(response_code)]
for code in codes:
if code == -5:
#: TODO send error signal (no $$)
pass
elif code == -3:
#: TODO send error signal (incorrect num)
pass
return True
except (ValueError, TypeError):
if not self.fail_silently:
raise
return False
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_filename(self):
"""Return a unique file name.""" |
if self._fname is None:
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
fname = "%s-%s.log" % (timestamp, abs(id(self)))
self._fname = os.path.join(self.file_path, fname)
return self._fname |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_balance(self):
""" Get balance with provider. """ |
if not SMSGLOBAL_CHECK_BALANCE_COUNTRY:
raise Exception('SMSGLOBAL_CHECK_BALANCE_COUNTRY setting must be set to check balance.')
params = {
'user' : self.get_username(),
'password' : self.get_password(),
'country' : SMSGLOBAL_CHECK_BALANCE_COUNTRY,
}
req = urllib2.Request(SMSGLOBAL_API_URL_CHECKBALANCE, urllib.urlencode(params))
response = urllib2.urlopen(req).read()
# CREDITS:8658.44;COUNTRY:AU;SMS:3764.54;
if response.startswith('ERROR'):
raise Exception('Error retrieving balance: %s' % response.replace('ERROR:', ''))
return dict([(p.split(':')[0].lower(), p.split(':')[1]) for p in response.split(';') if len(p) > 0]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_messages(self, sms_messages):
""" Sends one or more SmsMessage objects and returns the number of sms messages sent. """ |
if not sms_messages:
return
num_sent = 0
for message in sms_messages:
if self._send(message):
num_sent += 1
return num_sent |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_sms(body, from_phone, to, flash=False, fail_silently=False, auth_user=None, auth_password=None, connection=None):
""" Easy wrapper for send a single SMS to a recipient list. :returns: the number of SMSs sent. """ |
from sendsms.message import SmsMessage
connection = connection or get_connection(
username = auth_user,
password = auth_password,
fail_silently = fail_silently
)
return SmsMessage(body=body, from_phone=from_phone, to=to, \
flash=flash, connection=connection).send() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open(self):
"""Initializes sms.sluzba.cz API library.""" |
self.client = SmsGateApi(getattr(settings, 'SMS_SLUZBA_API_LOGIN', ''),
getattr(settings, 'SMS_SLUZBA_API_PASSWORD', ''),
getattr(settings, 'SMS_SLUZBA_API_TIMEOUT', 2),
getattr(settings, 'SMS_SLUZBA_API_USE_SSL', True)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_messages(self, messages):
"""Sending SMS messages via sms.sluzba.cz API. Note: This method returns number of actually sent sms messages not number of SmsMessage instances processed. :param messages: list of sms messages :type messages: list of sendsms.message.SmsMessage instances :returns: number of sent sms messages :rtype: int """ |
count = 0
for message in messages:
message_body = unicodedata.normalize('NFKD', unicode(message.body)).encode('ascii', 'ignore')
for tel_number in message.to:
try:
self.client.send(tel_number, message_body, getattr(settings, 'SMS_SLUZBA_API_USE_POST', True))
except Exception:
if self.fail_silently:
log.exception('Error while sending sms via sms.sluzba.cz backend API.')
else:
raise
else:
count += 1
return count |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _send(self, message):
""" Private method to send one message. :param SmsMessage message: SmsMessage class instance. :returns: True if message is sent else False :rtype: bool """ |
params = {
'EsendexUsername': self.get_username(),
'EsendexPassword': self.get_password(),
'EsendexAccount': self.get_account(),
'EsendexOriginator': message.from_phone,
'EsendexRecipient': ",".join(message.to),
'EsendexBody': message.body,
'EsendexPlainText':'1'
}
if ESENDEX_SANDBOX:
params['EsendexTest'] = '1'
response = requests.post(ESENDEX_API_URL, params)
if response.status_code != 200:
if not self.fail_silently:
raise Exception('Bad status code')
else:
return False
if not response.content.startswith(b'Result'):
if not self.fail_silently:
raise Exception('Bad result')
else:
return False
response = self._parse_response(response.content.decode('utf8'))
if ESENDEX_SANDBOX and response['Result'] == 'Test':
return True
else:
if response['Result'].startswith('OK'):
return True
else:
if not self.fail_silently:
raise Exception('Bad result')
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, fail_silently=False):
""" Sends the sms message """ |
if not self.to:
# Don't bother creating the connection if there's nobody to send to
return 0
res = self.get_connection(fail_silently).send_messages([self])
sms_post_send.send(sender=self, to=self.to, from_phone=self.from_phone, body=self.body)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _send(self, message):
""" A helper method that does the actual sending :param SmsMessage message: SmsMessage class instance. :returns: True if message is sent else False :rtype: bool """ |
params = {
'from': message.from_phone,
'to': ",".join(message.to),
'text': message.body,
'api_key': self.get_api_key(),
'api_secret': self.get_api_secret(),
}
print(params)
logger.debug("POST to %r with body: %r", NEXMO_API_URL, params)
return self.parse(NEXMO_API_URL, requests.post(NEXMO_API_URL, data=params)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_market_summary(self, market):
""" Used to get the last 24 hour summary of all active exchanges in specific coin Endpoint: 1.1 /public/getmarketsummary 2.0 /pub/Market/GetMarketSummary :param market: String literal for the market(ex: BTC-XRP) :type market: str :return: Summaries of active exchanges of a coin in JSON :rtype : dict """ |
return self._api_query(path_dict={
API_V1_1: '/public/getmarketsummary',
API_V2_0: '/pub/Market/GetMarketSummary'
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PUB) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_orderbook(self, market, depth_type=BOTH_ORDERBOOK):
""" Used to get retrieve the orderbook for a given market. The depth_type parameter is IGNORED under v2.0 and both orderbooks are always returned Endpoint: 1.1 /public/getorderbook 2.0 /pub/Market/GetMarketOrderBook :param market: String literal for the market (ex: BTC-LTC) :type market: str :param depth_type: buy, sell or both to identify the type of orderbook to return. Use constants BUY_ORDERBOOK, SELL_ORDERBOOK, BOTH_ORDERBOOK :type depth_type: str :return: Orderbook of market in JSON :rtype : dict """ |
return self._api_query(path_dict={
API_V1_1: '/public/getorderbook',
API_V2_0: '/pub/Market/GetMarketOrderBook'
}, options={'market': market, 'marketname': market, 'type': depth_type}, protection=PROTECTION_PUB) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_market_history(self, market):
""" Used to retrieve the latest trades that have occurred for a specific market. Endpoint: 1.1 /market/getmarkethistory 2.0 NO Equivalent Example :: {'success': True, 'message': '', 'result': [ {'Id': 5625015, 'TimeStamp': '2017-08-31T01:29:50.427', 'Quantity': 7.31008193, 'Price': 0.00177639, 'Total': 0.01298555, 'FillType': 'FILL', 'OrderType': 'BUY'}, ] } :param market: String literal for the market (ex: BTC-LTC) :type market: str :return: Market history in JSON :rtype : dict """ |
return self._api_query(path_dict={
API_V1_1: '/public/getmarkethistory',
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PUB) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buy_limit(self, market, quantity, rate):
""" Used to place a buy order in a specific market. Use buylimit to place limit orders Make sure you have the proper permissions set on your API keys for this call to work Endpoint: 1.1 /market/buylimit 2.0 NO Direct equivalent. Use trade_buy for LIMIT and MARKET buys :param market: String literal for the market (ex: BTC-LTC) :type market: str :param quantity: The amount to purchase :type quantity: float :param rate: The rate at which to place the order. This is not needed for market orders :type rate: float :return: :rtype : dict """ |
return self._api_query(path_dict={
API_V1_1: '/market/buylimit',
}, options={'market': market,
'quantity': quantity,
'rate': rate}, protection=PROTECTION_PRV) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_open_orders(self, market=None):
""" Get all orders that you currently have opened. A specific market can be requested. Endpoint: 1.1 /market/getopenorders 2.0 /key/market/getopenorders :param market: String literal for the market (ie. BTC-LTC) :type market: str :return: Open orders info in JSON :rtype : dict """ |
return self._api_query(path_dict={
API_V1_1: '/market/getopenorders',
API_V2_0: '/key/market/getopenorders'
}, options={'market': market, 'marketname': market} if market else None, protection=PROTECTION_PRV) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_deposit_address(self, currency):
""" Used to generate or retrieve an address for a specific currency Endpoint: 1.1 /account/getdepositaddress 2.0 /key/balance/getdepositaddress :param currency: String literal for the currency (ie. BTC) :type currency: str :return: Address info in JSON :rtype : dict """ |
return self._api_query(path_dict={
API_V1_1: '/account/getdepositaddress',
API_V2_0: '/key/balance/getdepositaddress'
}, options={'currency': currency, 'currencyname': currency}, protection=PROTECTION_PRV) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def withdraw(self, currency, quantity, address, paymentid=None):
""" Used to withdraw funds from your account Endpoint: 1.1 /account/withdraw 2.0 /key/balance/withdrawcurrency :param currency: String literal for the currency (ie. BTC) :type currency: str :param quantity: The quantity of coins to withdraw :type quantity: float :param address: The address where to send the funds. :type address: str :param paymentid: Optional argument for memos, tags, or other supplemental information for cryptos such as XRP. :type paymentid: str :return: :rtype : dict """ |
options = {
'currency': currency,
'quantity': quantity,
'address': address
}
if paymentid:
options['paymentid'] = paymentid
return self._api_query(path_dict={
API_V1_1: '/account/withdraw',
API_V2_0: '/key/balance/withdrawcurrency'
}, options=options, protection=PROTECTION_PRV) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_order_history(self, market=None):
""" Used to retrieve order trade history of account Endpoint: 1.1 /account/getorderhistory 2.0 /key/orders/getorderhistory or /key/market/GetOrderHistory :param market: optional a string literal for the market (ie. BTC-LTC). If omitted, will return for all markets :type market: str :return: order history in JSON :rtype : dict """ |
if market:
return self._api_query(path_dict={
API_V1_1: '/account/getorderhistory',
API_V2_0: '/key/market/GetOrderHistory'
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PRV)
else:
return self._api_query(path_dict={
API_V1_1: '/account/getorderhistory',
API_V2_0: '/key/orders/getorderhistory'
}, protection=PROTECTION_PRV) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_order(self, uuid):
""" Used to get details of buy or sell order Endpoint: 1.1 /account/getorder 2.0 /key/orders/getorder :param uuid: uuid of buy or sell order :type uuid: str :return: :rtype : dict """ |
return self._api_query(path_dict={
API_V1_1: '/account/getorder',
API_V2_0: '/key/orders/getorder'
}, options={'uuid': uuid, 'orderid': uuid}, protection=PROTECTION_PRV) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_markets_by_currency(self, currency):
""" Helper function to see which markets exist for a currency. Endpoint: /public/getmarkets Example :: ['BTC-LTC', 'ETH-LTC', 'USDT-LTC'] :param currency: String literal for the currency (ex: LTC) :type currency: str :return: List of markets that the currency appears in :rtype: list """ |
return [market['MarketName'] for market in self.get_markets()['result']
if market['MarketName'].lower().endswith(currency.lower())] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_pending_withdrawals(self, currency=None):
""" Used to view your pending withdrawals Endpoint: 1.1 NO EQUIVALENT 2.0 /key/balance/getpendingwithdrawals :param currency: String literal for the currency (ie. BTC) :type currency: str :return: pending withdrawals in JSON :rtype : list """ |
return self._api_query(path_dict={
API_V2_0: '/key/balance/getpendingwithdrawals'
}, options={'currencyname': currency} if currency else None,
protection=PROTECTION_PRV) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_candles(self, market, tick_interval):
""" Used to get all tick candles for a market. Endpoint: 1.1 NO EQUIVALENT 2.0 /pub/market/GetTicks Example :: { success: true, message: '', result: [ { O: 421.20630125, H: 424.03951276, L: 421.20630125, C: 421.20630125, V: 0.05187504, T: '2016-04-08T00:00:00', BV: 21.87921187 }, { O: 420.206, H: 420.206, L: 416.78743422, C: 416.78743422, V: 2.42281573, T: '2016-04-09T00:00:00', BV: 1012.63286332 }] } :return: Available tick candles in JSON :rtype: dict """ |
return self._api_query(path_dict={
API_V2_0: '/pub/market/GetTicks'
}, options={
'marketName': market, 'tickInterval': tick_interval
}, protection=PROTECTION_PUB) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def changelist_view(self, request, extra_context=None):
"""Add advanced_filters form to changelist context""" |
if extra_context is None:
extra_context = {}
response = self.adv_filters_handle(request,
extra_context=extra_context)
if response:
return response
return super(AdminAdvancedFiltersMixin, self
).changelist_view(request, extra_context=extra_context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self):
""" De-serialize, decode and return an ORM query stored in b64_query. """ |
if not self.b64_query:
return None
s = QSerializer(base64=True)
return s.loads(self.b64_query) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self, value):
""" Serialize an ORM query, Base-64 encode it and set it to the b64_query field """ |
if not isinstance(value, Q):
raise Exception('Must only be passed a Django (Q)uery object')
s = QSerializer(base64=True)
self.b64_query = s.dumps(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_field_choices(self, fields):
""" Iterate over passed model fields tuple and update initial choices. """ |
return tuple(sorted(
[(fquery, capfirst(fname)) for fquery, fname in fields.items()],
key=lambda f: f[1].lower())
) + self.FIELD_CHOICES |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_query_dict(query_data, model):
""" Take a list of query field dict and return data for form initialization """ |
operator = 'iexact'
if query_data['field'] == '_OR':
query_data['operator'] = operator
return query_data
parts = query_data['field'].split('__')
if len(parts) < 2:
field = parts[0]
else:
if parts[-1] in dict(AdvancedFilterQueryForm.OPERATORS).keys():
field = '__'.join(parts[:-1])
operator = parts[-1]
else:
field = query_data['field']
query_data['field'] = field
mfield = get_fields_from_path(model, query_data['field'])
if not mfield:
raise Exception('Field path "%s" could not be followed to a field'
' in model %s', query_data['field'], model)
else:
mfield = mfield[-1] # get the field object
if query_data['value'] is None:
query_data['operator'] = "isnull"
elif query_data['value'] is True:
query_data['operator'] = "istrue"
elif query_data['value'] is False:
query_data['operator'] = "isfalse"
else:
if isinstance(mfield, DateField):
# this is a date/datetime field
query_data['operator'] = "range" # default
else:
query_data['operator'] = operator # default
if isinstance(query_data.get('value'),
list) and query_data['operator'] == 'range':
date_from = date_to_string(query_data.get('value_from'))
date_to = date_to_string(query_data.get('value_to'))
query_data['value'] = ','.join([date_from, date_to])
return query_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_range_value(self, data):
""" Validates date range by parsing into 2 datetime objects and validating them both. """ |
dtfrom = data.pop('value_from')
dtto = data.pop('value_to')
if dtfrom is dtto is None:
self.errors['value'] = ['Date range requires values']
raise forms.ValidationError([])
data['value'] = (dtfrom, dtto) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_query(self, *args, **kwargs):
""" Returns a Q object from the submitted form """ |
query = Q() # initial is an empty query
query_dict = self._build_query_dict(self.cleaned_data)
if 'negate' in self.cleaned_data and self.cleaned_data['negate']:
query = query & ~Q(**query_dict)
else:
query = query & Q(**query_dict)
return query |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_query(self):
""" Reduces multiple queries into a single usable query """ |
query = Q()
ORed = []
for form in self._non_deleted_forms:
if not hasattr(form, 'cleaned_data'):
continue
if form.cleaned_data['field'] == "_OR":
ORed.append(query)
query = Q()
else:
query = query & form.make_query()
if ORed:
if query: # add last query for OR if any
ORed.append(query)
query = reduce(operator.or_, ORed)
return query |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize_form(self, instance, model, data=None, extra=None):
""" Takes a "finalized" query and generate it's form data """ |
model_fields = self.get_fields_from_model(model, self._filter_fields)
forms = []
if instance:
for field_data in instance.list_fields():
forms.append(
AdvancedFilterQueryForm._parse_query_dict(
field_data, model))
formset = AFQFormSetNoExtra if not extra else AFQFormSet
self.fields_formset = formset(
data=data,
initial=forms or None,
model_fields=model_fields
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login():
""" This route has two purposes. First, it is used by the user to login. Second, it is used by the CAS to respond with the `ticket` after the user logs in successfully. When the user accesses this url, they are redirected to the CAS to login. If the login was successful, the CAS will respond to this route with the ticket in the url. The ticket is then validated. If validation was successful the logged in username is saved in the user's session under the key `CAS_USERNAME_SESSION_KEY` and the user's attributes are saved under the key 'CAS_USERNAME_ATTRIBUTE_KEY' """ |
cas_token_session_key = current_app.config['CAS_TOKEN_SESSION_KEY']
redirect_url = create_cas_login_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGIN_ROUTE'],
flask.url_for('.login', origin=flask.session.get('CAS_AFTER_LOGIN_SESSION_URL'), _external=True))
if 'ticket' in flask.request.args:
flask.session[cas_token_session_key] = flask.request.args['ticket']
if cas_token_session_key in flask.session:
if validate(flask.session[cas_token_session_key]):
if 'CAS_AFTER_LOGIN_SESSION_URL' in flask.session:
redirect_url = flask.session.pop('CAS_AFTER_LOGIN_SESSION_URL')
elif flask.request.args.get('origin'):
redirect_url = flask.request.args['origin']
else:
redirect_url = flask.url_for(
current_app.config['CAS_AFTER_LOGIN'])
else:
del flask.session[cas_token_session_key]
current_app.logger.debug('Redirecting to: {0}'.format(redirect_url))
return flask.redirect(redirect_url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logout():
""" When the user accesses this route they are logged out. """ |
cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = current_app.config['CAS_ATTRIBUTES_SESSION_KEY']
if cas_username_session_key in flask.session:
del flask.session[cas_username_session_key]
if cas_attributes_session_key in flask.session:
del flask.session[cas_attributes_session_key]
if(current_app.config['CAS_AFTER_LOGOUT'] is not None):
redirect_url = create_cas_logout_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGOUT_ROUTE'],
current_app.config['CAS_AFTER_LOGOUT'])
else:
redirect_url = create_cas_logout_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGOUT_ROUTE'])
current_app.logger.debug('Redirecting to: {0}'.format(redirect_url))
return flask.redirect(redirect_url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(ticket):
""" Will attempt to validate the ticket. If validation fails, then False is returned. If validation is successful, then True is returned and the validated username is saved in the session under the key `CAS_USERNAME_SESSION_KEY` while tha validated attributes dictionary is saved under the key 'CAS_ATTRIBUTES_SESSION_KEY'. """ |
cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = current_app.config['CAS_ATTRIBUTES_SESSION_KEY']
current_app.logger.debug("validating token {0}".format(ticket))
cas_validate_url = create_cas_validate_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_VALIDATE_ROUTE'],
flask.url_for('.login', origin=flask.session.get('CAS_AFTER_LOGIN_SESSION_URL'), _external=True),
ticket)
current_app.logger.debug("Making GET request to {0}".format(
cas_validate_url))
xml_from_dict = {}
isValid = False
try:
xmldump = urlopen(cas_validate_url).read().strip().decode('utf8', 'ignore')
xml_from_dict = parse(xmldump)
isValid = True if "cas:authenticationSuccess" in xml_from_dict["cas:serviceResponse"] else False
except ValueError:
current_app.logger.error("CAS returned unexpected result")
if isValid:
current_app.logger.debug("valid")
xml_from_dict = xml_from_dict["cas:serviceResponse"]["cas:authenticationSuccess"]
username = xml_from_dict["cas:user"]
flask.session[cas_username_session_key] = username
if "cas:attributes" in xml_from_dict:
attributes = xml_from_dict["cas:attributes"]
if "cas:memberOf" in attributes:
attributes["cas:memberOf"] = attributes["cas:memberOf"].lstrip('[').rstrip(']').split(',')
for group_number in range(0, len(attributes['cas:memberOf'])):
attributes['cas:memberOf'][group_number] = attributes['cas:memberOf'][group_number].lstrip(' ').rstrip(' ')
flask.session[cas_attributes_session_key] = attributes
else:
current_app.logger.debug("invalid")
return isValid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_url(base, path=None, *query):
""" Create a url. Creates a url by combining base, path, and the query's list of key/value pairs. Escaping is handled automatically. Any key/value pair with a value that is None is ignored. Keyword arguments: base -- The left most part of the url (ex. http://localhost:5000). path -- The path after the base (ex. /foo/bar). query -- A list of key value pairs (ex. [('key', 'value')]). Example usage: 'http://localhost:5000/foo/bar?key1=value&url=http%3A%2F%2Fexample.com' """ |
url = base
# Add the path to the url if it's not None.
if path is not None:
url = urljoin(url, quote(path))
# Remove key/value pairs with None values.
query = filter(lambda pair: pair[1] is not None, query)
# Add the query string to the url
url = urljoin(url, '?{0}'.format(urlencode(list(query))))
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_cas_login_url(cas_url, cas_route, service, renew=None, gateway=None):
""" Create a CAS login URL . Keyword arguments: cas_url -- The url to the CAS (ex. http://sso.pdx.edu) cas_route -- The route where the CAS lives on server (ex. /cas) service -- (ex. http://localhost:5000/login) renew -- "true" or "false" gateway -- "true" or "false" Example usage: 'http://sso.pdx.edu/cas?service=http%3A%2F%2Flocalhost%3A5000' """ |
return create_url(
cas_url,
cas_route,
('service', service),
('renew', renew),
('gateway', gateway),
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_cas_validate_url(cas_url, cas_route, service, ticket, renew=None):
""" Create a CAS validate URL. Keyword arguments: cas_url -- The url to the CAS (ex. http://sso.pdx.edu) cas_route -- The route where the CAS lives on server (ex. /cas/serviceValidate) service -- (ex. http://localhost:5000/login) ticket -- (ex. 'ST-58274-x839euFek492ou832Eena7ee-cas') renew -- "true" or "false" Example usage: 'http://sso.pdx.edu/cas/serviceValidate?service=http%3A%2F%2Flocalhost%3A5000%2Flogin&ticket=ST-58274-x839euFek492ou832Eena7ee-cas' """ |
return create_url(
cas_url,
cas_route,
('service', service),
('ticket', ticket),
('renew', renew),
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def namespace_to_dict(obj):
"""If obj is argparse.Namespace or optparse.Values we'll return a dict representation of it, else return the original object. Redefine this method if using other parsers. :param obj: * :return: :rtype: dict or * """ |
if isinstance(obj, (argparse.Namespace, optparse.Values)):
return vars(obj)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xdg_config_dirs():
"""Returns a list of paths taken from the XDG_CONFIG_DIRS and XDG_CONFIG_HOME environment varibables if they exist """ |
paths = []
if 'XDG_CONFIG_HOME' in os.environ:
paths.append(os.environ['XDG_CONFIG_HOME'])
if 'XDG_CONFIG_DIRS' in os.environ:
paths.extend(os.environ['XDG_CONFIG_DIRS'].split(':'))
else:
paths.append('/etc/xdg')
paths.append('/etc')
return paths |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config_dirs():
"""Return a platform-specific list of candidates for user configuration directories on the system. The candidates are in order of priority, from highest to lowest. The last element is the "fallback" location to be used when no higher-priority config file exists. """ |
paths = []
if platform.system() == 'Darwin':
paths.append(MAC_DIR)
paths.append(UNIX_DIR_FALLBACK)
paths.extend(xdg_config_dirs())
elif platform.system() == 'Windows':
paths.append(WINDOWS_DIR_FALLBACK)
if WINDOWS_DIR_VAR in os.environ:
paths.append(os.environ[WINDOWS_DIR_VAR])
else:
# Assume Unix.
paths.append(UNIX_DIR_FALLBACK)
paths.extend(xdg_config_dirs())
# Expand and deduplicate paths.
out = []
for path in paths:
path = os.path.abspath(os.path.expanduser(path))
if path not in out:
out.append(path)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_yaml(filename):
"""Read a YAML document from a file. If the file cannot be read or parsed, a ConfigReadError is raised. """ |
try:
with open(filename, 'rb') as f:
return yaml.load(f, Loader=Loader)
except (IOError, yaml.error.YAMLError) as exc:
raise ConfigReadError(filename, exc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_template(value):
"""Convert a simple "shorthand" Python value to a `Template`. """ |
if isinstance(value, Template):
# If it's already a Template, pass it through.
return value
elif isinstance(value, abc.Mapping):
# Dictionaries work as templates.
return MappingTemplate(value)
elif value is int:
return Integer()
elif isinstance(value, int):
return Integer(value)
elif isinstance(value, type) and issubclass(value, BASESTRING):
return String()
elif isinstance(value, BASESTRING):
return String(value)
elif isinstance(value, set):
# convert to list to avoid hash related problems
return Choice(list(value))
elif (SUPPORTS_ENUM and isinstance(value, type)
and issubclass(value, enum.Enum)):
return Choice(value)
elif isinstance(value, list):
return OneOf(value)
elif value is float:
return Number()
elif value is None:
return Template()
elif value is dict:
return TypeTemplate(abc.Mapping)
elif value is list:
return TypeTemplate(abc.Sequence)
elif isinstance(value, type):
return TypeTemplate(value)
else:
raise ValueError(u'cannot convert to template: {0!r}'.format(value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def of(cls, value):
"""Given either a dictionary or a `ConfigSource` object, return a `ConfigSource` object. This lets a function accept either type of object as an argument. """ |
if isinstance(value, ConfigSource):
return value
elif isinstance(value, dict):
return ConfigSource(value)
else:
raise TypeError(u'source value must be a dict') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_namespace_dict(cls, obj, dots=False):
"""Recursively replaces all argparse.Namespace and optparse.Values with dicts and drops any keys with None values. Additionally, if dots is True, will expand any dot delimited keys. :param obj: Namespace, Values, or dict to iterate over. Other values will simply be returned. :type obj: argparse.Namespace or optparse.Values or dict or * :param dots: If True, any properties on obj that contain dots (.) will be broken down into child dictionaries. :return: A new dictionary or the value passed if obj was not a dict, Namespace, or Values. :rtype: dict or * """ |
# We expect our root object to be a dict, but it may come in as
# a namespace
obj = namespace_to_dict(obj)
# We only deal with dictionaries
if not isinstance(obj, dict):
return obj
# Get keys iterator
keys = obj.keys() if PY3 else obj.iterkeys()
if dots:
# Dots needs sorted keys to prevent parents from
# clobbering children
keys = sorted(list(keys))
output = {}
for key in keys:
value = obj[key]
if value is None: # Avoid unset options.
continue
save_to = output
result = cls._build_namespace_dict(value, dots)
if dots:
# Split keys by dots as this signifies nesting
split = key.split('.')
if len(split) > 1:
# The last index will be the key we assign result to
key = split.pop()
# Build the dict tree if needed and change where
# we're saving to
for child_key in split:
if child_key in save_to and \
isinstance(save_to[child_key], dict):
save_to = save_to[child_key]
else:
# Clobber or create
save_to[child_key] = {}
save_to = save_to[child_key]
# Save
if key in save_to:
save_to[key].update(result)
else:
save_to[key] = result
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_args(self, namespace, dots=False):
"""Overlay parsed command-line arguments, generated by a library like argparse or optparse, onto this view's value. :param namespace: Dictionary or Namespace to overlay this config with. Supports nested Dictionaries and Namespaces. :type namespace: dict or Namespace :param dots: If True, any properties on namespace that contain dots (.) will be broken down into child dictionaries. :Example: {'foo.bar': 'car'} # Will be turned into {'foo': {'bar': 'car'}} :type dots: bool """ |
self.set(self._build_namespace_dict(namespace, dots)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten(self, redact=False):
"""Create a hierarchy of OrderedDicts containing the data from this view, recursively reifying all views to get their represented values. If `redact` is set, then sensitive values are replaced with the string "REDACTED". """ |
od = OrderedDict()
for key, view in self.items():
if redact and view.redact:
od[key] = REDACTED_TOMBSTONE
else:
try:
od[key] = view.flatten(redact=redact)
except ConfigTypeError:
od[key] = view.get()
return od |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def represent_bool(self, data):
"""Represent bool as 'yes' or 'no' instead of 'true' or 'false'. """ |
if data:
value = u'yes'
else:
value = u'no'
return self.represent_scalar('tag:yaml.org,2002:bool', value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_default_source(self):
"""Add the package's default configuration settings. This looks for a YAML file located inside the package for the module `modname` if it was given. """ |
if self.modname:
if self._package_path:
filename = os.path.join(self._package_path, DEFAULT_FILENAME)
if os.path.isfile(filename):
self.add(ConfigSource(load_yaml(filename), filename, True)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, user=True, defaults=True):
"""Find and read the files for this configuration and set them as the sources for this configuration. To disable either discovered user configuration files or the in-package defaults, set `user` or `defaults` to `False`. """ |
if user:
self._add_user_source()
if defaults:
self._add_default_source() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_file(self, filename):
"""Parses the file as YAML and inserts it into the configuration sources with highest priority. """ |
filename = os.path.abspath(filename)
self.set(ConfigSource(load_yaml(filename), filename)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(self, full=True, redact=False):
"""Dump the Configuration object to a YAML file. The order of the keys is determined from the default configuration file. All keys not in the default configuration will be appended to the end of the file. :param filename: The file to dump the configuration to, or None if the YAML string should be returned instead :type filename: unicode :param full: Dump settings that don't differ from the defaults as well :param redact: Remove sensitive information (views with the `redact` flag set) from the output """ |
if full:
out_dict = self.flatten(redact=redact)
else:
# Exclude defaults when flattening.
sources = [s for s in self.sources if not s.default]
temp_root = RootView(sources)
temp_root.redactions = self.redactions
out_dict = temp_root.flatten(redact=redact)
yaml_out = yaml.dump(out_dict, Dumper=Dumper,
default_flow_style=None, indent=4,
width=1000)
# Restore comments to the YAML text.
default_source = None
for source in self.sources:
if source.default:
default_source = source
break
if default_source and default_source.filename:
with open(default_source.filename, 'rb') as fp:
default_data = fp.read()
yaml_out = restore_yaml_comments(yaml_out,
default_data.decode('utf-8'))
return yaml_out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
"""Remove all sources from this configuration.""" |
super(LazyConfig, self).clear()
self._lazy_suffix = []
self._lazy_prefix = [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self, view, template=None):
"""Get the value for a `ConfigView`. May raise a `NotFoundError` if the value is missing (and the template requires it) or a `ConfigValueError` for invalid values. """ |
if view.exists():
value, _ = view.first()
return self.convert(value, view)
elif self.default is REQUIRED:
# Missing required value. This is an error.
raise NotFoundError(u"{0} not found".format(view.name))
else:
# Missing value, but not required.
return self.default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fail(self, message, view, type_error=False):
"""Raise an exception indicating that a value cannot be accepted. `type_error` indicates whether the error is due to a type mismatch rather than a malformed value. In this case, a more specific exception is raised. """ |
exc_class = ConfigTypeError if type_error else ConfigValueError
raise exc_class(
u'{0}: {1}'.format(view.name, message)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert(self, value, view):
"""Check that the value is an integer. Floats are rounded. """ |
if isinstance(value, int):
return value
elif isinstance(value, float):
return int(value)
else:
self.fail(u'must be a number', view, True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert(self, value, view):
"""Check that the value is an int or a float. """ |
if isinstance(value, NUMERIC_TYPES):
return value
else:
self.fail(
u'must be numeric, not {0}'.format(type(value).__name__),
view,
True
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self, view, template=None):
"""Get a dict with the same keys as the template and values validated according to the value types. """ |
out = AttrDict()
for key, typ in self.subtemplates.items():
out[key] = typ.value(view[key], self)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self, view, template=None):
"""Get a list of items validated against the template. """ |
out = []
for item in view:
out.append(self.subtemplate.value(item, self))
return out |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.