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 build_relational_field(self, field_name, relation_info):
""" Create fields for forward and reverse relationships. """ |
field_class = self.serializer_related_field
field_kwargs = get_relation_kwargs(field_name, relation_info)
to_field = field_kwargs.pop('to_field', None)
if to_field and not relation_info.related_model._meta.get_field(to_field).primary_key:
field_kwargs['slug_field'] = to_field
field_class = self.serializer_related_to_field
# `view_name` is only valid for hyperlinked relationships.
if not issubclass(field_class, HyperlinkedRelatedField):
field_kwargs.pop('view_name', None)
return field_class, field_kwargs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def include_extra_kwargs(self, kwargs, extra_kwargs):
""" Include any 'extra_kwargs' that have been included for this field, possibly removing any incompatible existing keyword arguments. """ |
if extra_kwargs.get('read_only', False):
for attr in [
'required', 'default', 'allow_blank', 'allow_null',
'min_length', 'max_length', 'min_value', 'max_value',
'validators', 'queryset'
]:
kwargs.pop(attr, None)
if extra_kwargs.get('default') and kwargs.get('required') is False:
kwargs.pop('required')
if extra_kwargs.get('read_only', kwargs.get('read_only', False)):
extra_kwargs.pop('required', None) # Read only fields should always omit the 'required' argument.
kwargs.update(extra_kwargs)
return kwargs |
<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_extra_kwargs(self):
""" Return a dictionary mapping field names to a dictionary of additional keyword arguments. """ |
extra_kwargs = getattr(self.Meta, 'extra_kwargs', {})
read_only_fields = getattr(self.Meta, 'read_only_fields', None)
if read_only_fields is not None:
for field_name in read_only_fields:
kwargs = extra_kwargs.get(field_name, {})
kwargs['read_only'] = True
extra_kwargs[field_name] = kwargs
return extra_kwargs |
<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_model_fields(self, field_names, declared_fields, extra_kwargs):
""" Returns all the model fields that are being mapped to by fields on the serializer class. Returned as a dict of 'model field name' -> 'model field'. Used internally by `get_uniqueness_field_options`. """ |
model = getattr(self.Meta, 'model')
model_fields = {}
for field_name in field_names:
if field_name in declared_fields:
# If the field is declared on the serializer
field = declared_fields[field_name]
source = field.source or field_name
else:
try:
source = extra_kwargs[field_name]['source']
except KeyError:
source = field_name
if '.' in source or source == '*':
# Model fields will always have a simple source mapping,
# they can't be nested attribute lookups.
continue
try:
field = model._meta.get_field(source)
if isinstance(field, DjangoModelField):
model_fields[source] = field
except FieldDoesNotExist:
pass
return 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 get_validators(self):
""" Determine the set of validators to use when instantiating serializer. """ |
# If the validators have been declared explicitly then use that.
validators = getattr(getattr(self, 'Meta', None), 'validators', None)
if validators is not None:
return validators[:]
# Otherwise use the default set of validators.
return (
self.get_unique_together_validators() +
self.get_unique_for_date_validators()
) |
<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_unique_together_validators(self):
""" Determine a default set of validators for any unique_together contraints. """ |
model_class_inheritance_tree = (
[self.Meta.model] +
list(self.Meta.model._meta.parents.keys())
)
# The field names we're passing though here only include fields
# which may map onto a model field. Any dotted field name lookups
# cannot map to a field, and must be a traversal, so we're not
# including those.
field_names = {
field.source for field in self.fields.values()
if (field.source != '*') and ('.' not in field.source)
}
# Note that we make sure to check `unique_together` both on the
# base model class, but also on any parent classes.
validators = []
for parent_class in model_class_inheritance_tree:
for unique_together in parent_class._meta.unique_together:
if field_names.issuperset(set(unique_together)):
validator = UniqueTogetherValidator(
queryset=parent_class._default_manager,
fields=unique_together
)
validators.append(validator)
return validators |
<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_nested_field(self, field_name, relation_info, nested_depth):
""" Create nested fields for forward and reverse relationships. """ |
class NestedSerializer(HyperlinkedModelSerializer):
class Meta:
model = relation_info.related_model
depth = nested_depth - 1
field_class = NestedSerializer
field_kwargs = get_nested_relation_kwargs(relation_info)
return field_class, field_kwargs |
<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_url(self, url):
""" Get an absolute URL from a given one. """ |
if url.startswith('/'):
url = '%s%s' % (self.base_url, url)
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 get_soup(self, *args, **kwargs):
""" Shortcut for ``get`` which returns a ``BeautifulSoup`` element """ |
return BeautifulSoup(self.get(*args, **kwargs).text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_soup(self, *args, **kwargs):
""" Shortcut for ``post`` which returns a ``BeautifulSoup`` element """ |
return BeautifulSoup(self.post(*args, **kwargs).text) |
<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_results_soup(self, year=None):
""" ``get_soup`` on the results page. The page URL depends on the year. """ |
if year is None:
year = self.year
year = YEARS.get(year, year)
return self.get_soup(URLS['results'][year]) |
<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(self, year, firstname, lastname, passwd, with_year=True):
""" Authenticate an user """ |
firstname = firstname.upper()
lastname = lastname.upper()
if with_year and not self.set_year(year):
return False
url = URLS['login']
params = {
'prenom': firstname,
'nom': lastname,
'pwd': passwd,
}
soup = self.post_soup(url, data=params)
return not soup.select('font[color=red]') |
<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_year(self, year):
""" Set an user's year. This is required on magma just before the login. It's called by default by ``login``. """ |
self.year = YEARS.get(year, year)
data = {'idCursus': self.year}
soup = self.post_soup('/~etudiant/login.php', data=data)
return bool(soup.select('ul.rMenu-hor')) |
<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_return_code_enum():
""" Creates an IntEnum containing all the XTT return codes. Finds all return codes by scanning the FFI for items whose names match the pattern "XTT_RETURN_<X>". The name of the result enum value is the suffix "<X>". """ |
prefix = 'XTT_RETURN_'
codes = {k[len(prefix):]:v for (k, v) in vars(_lib).items() if k.startswith(prefix)}
return IntEnum('ReturnCode', codes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Client(engine="couchbase", host="", auth="", database="", logger=None, verbose=True):
""" Return new database client Arguments engine <str> defines which engine to use, currently supports "couchdb" and "couchbase" host <str|couchdb.Server> host url, when using couchdb this can also be a server instance auth <str> bucket_auth for couchbase, auth for couchdb database <str> database name for couchdb logger <Logger> python logger instance """ |
if engine == "couchbase":
from twentyc.database.couchbase.client import CouchbaseClient
return CouchbaseClient(
host, bucket_auth=auth, logger=logger
)
elif engine == "couchdb":
from twentyc.database.couchdb.client import CouchDBClient
return CouchDBClient(
host, database, auth=auth, logger=logger, verbose=verbose
)
elif engine == "dummydb":
from twentyc.database.dummydb.client import DummyDBClient
return DummyDBClient()
else:
raise InvalidEngineException(engine) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _serialize_data(self, data):
""" Turn the data into a JSON API compliant resource object WARN: This function has both side effects & a return. It's complete shit because it mutates data & yet returns a new doc. FIX. :spec: jsonapi.org/format/#document-resource-objects :param data: dict for serializing :return: dict resource in JSON API format """ |
rels = {}
rlink = rid_url(data['rtype'], data['rid'])
doc = {
'id': data.pop('rid'),
'type': data.pop('rtype'),
'links': {
'self': rlink,
},
}
for key, val in data['to_many'].items():
rels.update(self._serialize_to_many(key, val, rlink))
del data['to_many']
for key, val in data['to_one'].items():
rels.update(self._serialize_to_one(key, val, rlink))
del data['to_one']
if data:
doc['attributes'] = data
if rels:
doc['relationships'] = rels
return doc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _serialize_pages(self):
""" Return a JSON API compliant pagination links section If the paginator has a value for a given link then this method will also add the same links to the response objects `link` header according to the guidance of RFC 5988. Falcon has a native add_link helper for forming the `link` header according to RFC 5988. :return: dict of links used for pagination """ |
pages = self.req.pages.to_dict()
links = {}
for key, val in pages.items():
if val:
params = self.req.params
params.update(val)
links[key] = '%s?%s' % (self.req.path, urlencode(params))
self.resp.add_link(links[key], key)
else:
links[key] = val
return links |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _serialize_to_many(self, key, vals, rlink):
""" Make a to_many JSON API compliant :spec: jsonapi.org/format/#document-resource-object-relationships :param key: the string name of the relationship field :param vals: array of dict's containing `rid` & `rtype` keys for the to_many, empty array if no values, & None if the to_manys values are unknown :return: dict as documented in the spec link """ |
rel = {
key: {
'data': [],
'links': {
'related': rlink + '/' + key
}
}
}
try:
for val in vals:
rel[key]['data'].append({
'id': val['rid'],
'type': val['rtype'],
})
except TypeError:
del rel[key]['data']
return rel |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _serialize_to_one(self, key, val, rlink):
""" Make a to_one JSON API compliant :spec: jsonapi.org/format/#document-resource-object-relationships :param key: the string name of the relationship field :param val: dict containing `rid` & `rtype` keys for the to_one & None if the to_one is null :return: dict as documented in the spec link """ |
data = None
if val and val['rid']:
data = {'id': val['rid'], 'type': val['rtype']}
return {
key: {
'data': data,
'links': {
'related': rlink + '/' + key
}
}
} |
<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_uuid(value):
""" UUID 128-bit validator """ |
if value and not isinstance(value, UUID):
try:
return UUID(str(value), version=4)
except (AttributeError, ValueError):
raise ValidationError('not a valid UUID')
return 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 get_namespace_url(module, version):
"""Get a BEL namespace file from Artifactory given the name and version. :param str module: :param str version: :type: str """ |
module = module.strip('/')
return '{module}/{name}'.format(
module=get_namespace_module_url(module),
name=get_namespace_file_name(module, version),
) |
<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_annotation_url(module, version):
"""Get a BEL annotation file from artifactory given the name and version. :param str module: :param str version: :type: str """ |
module = module.strip('/')
return '{module}/{name}'.format(
module=get_annotation_module_url(module),
name=get_annotation_file_name(module, version),
) |
<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_knowledge_url(module, version):
"""Get a BEL knowledge file from Artifactory given the name and version. :param str module: :param str version: :rtype: str """ |
module = module.strip('/')
return '{module}/{name}'.format(
module=get_knowledge_module_url(module),
name=get_knowledge_file_name(module, version),
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def local_path(path):
""" Return the absolute path relative to the root of this project """ |
current = os.path.dirname(__file__)
root = current
return os.path.abspath(os.path.join(root, path)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _register_resources(self, api_dirs, do_checks):
'''Register all Apis, Resources and Models with the application.'''
msg = 'Looking-up for APIs in the following directories: {}'
log.debug(msg.format(api_dirs))
if do_checks:
check_and_load(api_dirs)
else:
msg = 'Loading module "{}" from directory "{}"'
for loader, mname, _ in pkgutil.walk_packages(api_dirs):
sys.path.append(os.path.abspath(loader.path))
log.debug(msg.format(mname, loader.path))
import_module(mname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _mount_resources(self):
'''Mount all registered resources onto the application.'''
rules = []
self.callback_map = {}
for ep in Resource:
for rule, callback in ep.get_routing_tuples():
log.debug('Path "{}" mapped to "{}"'.format(
rule.rule, rule.endpoint))
rules.append(rule)
self.callback_map[rule.endpoint] = callback
self.url_map = Map(rules) |
<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_coroutine(self, request, start_response):
'''Try to dispapch the request and get the matching coroutine.'''
adapter = self.url_map.bind_to_environ(request.environ)
resource, kwargs = adapter.match()
callback = self.callback_map[resource]
inject_extra_args(callback, request, kwargs)
return callback(request, start_response, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def SetAuth(self, style, user=None, password=None):
'''Change auth style, return object to user.
'''
self.auth_style, self.auth_user, self.auth_pass = \
style, user, password
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 AddHeader(self, header, value):
'''Add a header to send.
'''
self.user_headers.append((header, value))
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 __addcookies(self):
'''Add cookies from self.cookies to request in self.h
'''
for cname, morsel in self.cookies.items():
attrs = []
value = morsel.get('version', '')
if value != '' and value != '0':
attrs.append('$Version=%s' % value)
attrs.append('%s=%s' % (cname, morsel.coded_value))
value = morsel.get('path')
if value:
attrs.append('$Path=%s' % value)
value = morsel.get('domain')
if value:
attrs.append('$Domain=%s' % value)
self.h.putheader('Cookie', "; ".join(attrs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def ReceiveRaw(self, **kw):
'''Read a server reply, unconverted to any format and return it.
'''
if self.data: return self.data
trace = self.trace
while 1:
response = self.h.getresponse()
self.reply_code, self.reply_msg, self.reply_headers, self.data = \
response.status, response.reason, response.msg, response.read()
if trace:
print >>trace, "_" * 33, time.ctime(time.time()), "RESPONSE:"
for i in (self.reply_code, self.reply_msg,):
print >>trace, str(i)
print >>trace, "-------"
print >>trace, str(self.reply_headers)
print >>trace, self.data
saved = None
for d in response.msg.getallmatchingheaders('set-cookie'):
if d[0] in [ ' ', '\t' ]:
saved += d.strip()
else:
if saved: self.cookies.load(saved)
saved = d.strip()
if saved: self.cookies.load(saved)
if response.status == 401:
if not callable(self.http_callbacks.get(response.status,None)):
raise RuntimeError, 'HTTP Digest Authorization Failed'
self.http_callbacks[response.status](response)
continue
if response.status != 100: break
# The httplib doesn't understand the HTTP continuation header.
# Horrible internals hack to patch things up.
self.h._HTTPConnection__state = httplib._CS_REQ_SENT
self.h._HTTPConnection__response = None
return self.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 ReceiveSOAP(self, readerclass=None, **kw):
'''Get back a SOAP message.
'''
if self.ps: return self.ps
if not self.IsSOAP():
raise TypeError(
'Response is "%s", not "text/xml"' % self.reply_headers.type)
if len(self.data) == 0:
raise TypeError('Received empty response')
self.ps = ParsedSoap(self.data,
readerclass=readerclass or self.readerclass,
encodingStyle=kw.get('encodingStyle'))
if self.sig_handler is not None:
self.sig_handler.verify(self.ps)
return self.ps |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def ReceiveFault(self, **kw):
'''Parse incoming message as a fault. Raise TypeError if no
fault found.
'''
self.ReceiveSOAP(**kw)
if not self.ps.IsAFault():
raise TypeError("Expected SOAP Fault not found")
return FaultFromFaultMessage(self.ps) |
<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_child(self, node):
'''for rpc-style map each message part to a class in typesmodule
'''
try:
tc = self.gettypecode(self.typesmodule, node)
except:
self.logger.debug('didnt find typecode for "%s" in typesmodule: %s',
node.localName, self.typesmodule)
tc = TC.Any(aslist=1)
return tc.parse(node, self.ps)
self.logger.debug('parse child with typecode : %s', tc)
try:
return tc.parse(node, self.ps)
except Exception:
self.logger.debug('parse failed try Any : %s', tc)
tc = TC.Any(aslist=1)
return tc.parse(node, self.ps) |
<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_creds(self, req):
""" Get the username & password from the Authorization header If the header is actually malformed where Basic Auth was indicated by the request then an InvalidAuthSyntax exception is raised. Otherwise an AuthRequired exception since it's unclear in this scenario if the requestor was even aware Authentication was required & if so which "scheme". Calls _validate_auth_scheme first & bubbles up it's exceptions. :return: tuple (username, password) :raise: AuthRequired, InvalidAuthSyntax """ |
self._validate_auth_scheme(req)
try:
creds = naked(req.auth.split(' ')[1])
creds = b64decode(creds)
username, password = creds.split(':')
return username, password
except IndexError:
raise InvalidAuthSyntax(**{
'detail': 'You are using the Basic Authentication scheme as '
'required to login but your Authorization header is '
'completely missing the login credentials.',
'links': 'tools.ietf.org/html/rfc2617#section-2',
})
except TypeError:
raise InvalidAuthSyntax(**{
'detail': 'Our API failed to base64 decode your Basic '
'Authentication login credentials in the '
'Authorization header. They seem to be malformed.',
'links': 'tools.ietf.org/html/rfc2617#section-2',
})
except ValueError:
raise InvalidAuthSyntax(**{
'detail': 'Our API failed to identify a username & password '
'in your Basic Authentication Authorization header '
'after decoding them. The username or password is '
'either missing or not separated by a ":" per the '
'spec. Either way the credentials are malformed.',
'links': 'tools.ietf.org/html/rfc2617#section-2',
}) |
<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_page(self, uri, path):
"""Update page content.""" |
if uri in self._pages:
self._pages[uri].update()
else:
self._pages[uri] = Page(uri=uri, path=path) |
<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_labels(self):
"""Updates list of available labels.""" |
labels = set()
for page in self.get_pages():
for label in page.labels:
labels.add(label)
to_delete = self._labels - labels
for label in labels:
self._labels.add(label)
for label in to_delete:
self._labels.discard(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_pages(self, label=None):
"""Returns list of pages with specified label.""" |
return (
page for page in sorted(
self._pages.values(), key=lambda i: i.created, reverse=True
) if ((not label or label in page.labels) and page.visible)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _requests(self, url, method='GET', headers=None, params=None, data=None, errors=None):
''' a helper method for relaying requests from client to api '''
title = '%s._requests' % self.__class__.__name__
# import dependencies
from time import time
import requests
# validate access token
if not self._access_token:
self.access_token()
if self.retrieve_details:
self._get_products()
# refresh token
current_time = time()
if current_time > self.expires_at:
self.access_token()
if self.retrieve_details:
self._get_products()
# construct request kwargs
request_kwargs = {
'url': url,
'headers': {
'Authorization': 'Bearer %s' % self._access_token,
'Accept': 'application/json;v=2'
},
'params': {},
'data': {}
}
if headers:
request_kwargs['headers'].update(headers)
if params:
request_kwargs['params'].update(params)
if data:
request_kwargs['data'].update(data)
# send request
if method == 'POST':
try:
response = requests.post(**request_kwargs)
except Exception:
if self.requests_handler:
request_kwargs['method'] = 'POST'
request_object = requests.Request(**request_kwargs)
return self.requests_handler(request_object)
else:
raise
elif method == 'GET':
try:
response = requests.get(**request_kwargs)
except Exception:
if self.requests_handler:
request_kwargs['method'] = 'GET'
request_object = requests.Request(**request_kwargs)
return self.requests_handler(request_object)
else:
raise
else:
raise ValueError('%s(method='') must be either GET or POST' % title)
# handle response
response_details = self.response_handler.handle(response, errors)
return response_details |
<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_products(self):
''' a method to retrieve account product details at initialization '''
# request product list
products_request = self.account_products()
if products_request['error']:
raise Exception(products_request['error'])
# construct list of product ids
product_ids = []
for product in products_request["json"]["entries"]:
product_ids.append(product['productId'])
# construct default product map
self.products = {}
# request product details
for id in product_ids:
product_request = self.account_product(id)
if product_request['error']:
raise Exception(product_request['error'])
self.products[id] = product_request['json']
return self.products |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def access_token(self):
''' a method to acquire an oauth access token '''
title = '%s.access_token' % self.__class__.__name__
# import dependencies
from time import time
import requests
# construct request kwargs
request_kwargs = {
'url': self.token_endpoint,
'data': {
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': 'client_credentials'
}
}
# send request
try:
current_time = time()
response = requests.post(**request_kwargs)
except Exception:
if self.requests_handler:
request_kwargs['method'] = 'POST'
request_object = requests.Request(**request_kwargs)
return self.requests_handler(request_object)
else:
raise
response_details = self.response_handler.handle(response)
if response_details['json']:
self._access_token = response_details['json']['access_token']
expires_in = response_details['json']['expires_in']
self.expires_at = current_time + expires_in
return self._access_token |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def account_products(self):
''' a method to retrieve a list of the account products
returns:
{
"error": "",
"code": 200,
"method": "GET",
"url": "https://...",
"headers": { },
"json": {
"entries": [
{
"productId": "3000",
"productName": "Capital One 360 Savings Account"
}
]
}
}
'''
title = '%s.account_products' % self.__class__.__name__
# construct url
url = self.deposits_endpoint + 'account-products'
# send request
details = self._requests(url)
return details |
<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_instructor_term_list_name(instructor_netid, year, quarter):
""" Return the list address of UW instructor email list for the given year and quarter """ |
return "{uwnetid}_{quarter}{year}".format(
uwnetid=instructor_netid,
quarter=quarter.lower()[:2],
year=str(year)[-2:]) |
<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_template_path(self, meta=None, **kwargs):
"""
Formats template_name_path_pattern with kwargs given.
""" |
if 'template_name_suffix' not in kwargs or kwargs.get('template_name_suffix') is None:
kwargs['template_name_suffix'] = self.get_template_name_suffix()
return self.template_name_path_pattern.format(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def threenum(h5file, var, post_col='mult'):
""" Calculates the three number summary for a variable. The three number summary is the minimum, maximum and the mean of the data. Traditionally one would summerise data with the five number summary: max, min, 1st, 2nd (median), 3rd quartile. But quantiles are hard to calculate without sorting the data which hard to do out-of-core. """ |
f = h5py.File(h5file, 'r')
d = f[var]
w = f[post_col]
s = d.chunks[0]
n = d.shape[0]
maxval = -np.abs(d[0])
minval = np.abs(d[0])
total = 0
wsum = 0
for x in range(0, n, s):
aN = ~np.logical_or(np.isnan(d[x:x+s]), np.isinf(d[x:x+s]))
d_c = d[x:x+s][aN]
w_c = w[x:x+s][aN]
chunk_max = np.max(d_c)
chunk_min = np.min(d_c)
maxval = chunk_max if chunk_max > maxval else maxval
minval = chunk_min if chunk_min < minval else minval
total += np.sum(w_c*d_c)
wsum += np.sum(w_c)
f.close()
mean = total/float(wsum)
return (minval, maxval, mean) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filechunk(f, chunksize):
"""Iterator that allow for piecemeal processing of a file.""" |
while True:
chunk = tuple(itertools.islice(f, chunksize))
if not chunk:
return
yield np.loadtxt(iter(chunk), dtype=np.float64) |
<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_chain( txtfiles, headers, h5file, chunksize):
"""Converts chain in plain text format into HDF5 format. Keyword arguments: txtfiles -- list of paths to the plain text chains. headers -- name of each column. h5file -- where to put the resulting HDF5 file. chunksize -- how large the HDF5 chunk, i.e. number of rows. Chunking - How to pick a chunksize TODO Optimal chunk size unknown, our usage make caching irrelevant, and we use all read variable. Larger size should make compression more efficient, and less require less IO reads. Measurements needed. """ |
h5 = h5py.File(h5file, 'w')
for h in headers:
h5.create_dataset(h,
shape=(0,),
maxshape=(None,),
dtype=np.float64,
chunks=(chunksize,),
compression='gzip',
shuffle=True)
for txtfile in txtfiles:
d = np.loadtxt(txtfile, dtype=np.float64)
if len(d.shape) == 1:
d = np.array([d])
dnrows = d.shape[0]
for pos, h in enumerate(headers):
x = h5[h]
xnrows = x.shape[0]
x.resize(dnrows+xnrows, axis=0)
x[xnrows:] = d[:,pos]
h5.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getAvailableClassesInModule(prooveModule):
""" return a list of all classes in the given module that dont begin with '_' """ |
l = tuple(x[1] for x in inspect.getmembers(prooveModule, inspect.isclass))
l = [x for x in l if x.__name__[0] != "_"]
return l |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getAvailableClassesInPackage(package):
""" return a list of all classes in the given package whose modules dont begin with '_' """ |
l = list(x[1] for x in inspect.getmembers(package, inspect.isclass))
modules = list(x[1] for x in inspect.getmembers(package, inspect.ismodule))
for m in modules:
l.extend(list(x[1] for x in inspect.getmembers(m, inspect.isclass)))
l = [x for x in l if x.__name__[0] != "_"]
n = 0
while n < len(l):
cls = l[n]
if not cls.__module__.startswith(package.__name__):
l.pop(n)
n -= 1
n += 1
return l |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getClassInPackageFromName(className, pkg):
""" get a class from name within a package """ |
# TODO: more efficiency!
n = getAvClassNamesInPackage(pkg)
i = n.index(className)
c = getAvailableClassesInPackage(pkg)
return c[i] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getClassInModuleFromName(className, module):
""" get a class from name within a module """ |
n = getAvClassNamesInModule(module)
i = n.index(className)
c = getAvailableClassesInModule(module)
return c[i] |
<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_prototype(sample_dimension, parameter_kind_base='user', parameter_kind_options=[], state_stay_probabilities=[0.6, 0.6, 0.7]):
"""Create a prototype HTK model file using a feature file. """ |
parameter_kind = create_parameter_kind(base=parameter_kind_base,
options=parameter_kind_options)
transition = create_transition(state_stay_probabilities)
state_count = len(state_stay_probabilities)
states = []
for i in range(state_count):
state = create_gmm(np.zeros(sample_dimension),
np.ones(sample_dimension),
weights=None,
gconsts=None)
states.append(state)
hmms = [create_hmm(states, transition)]
macros = [create_options(vector_size=sample_dimension,
parameter_kind=parameter_kind)]
model = create_model(macros, hmms)
return model |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_hmms(input_model, mapping):
"""Create a new HTK HMM model given a model and a mapping dictionary. :param input_model: The model to transform of type dict :param mapping: A dictionary from string -> list(string) :return: The transformed model of type dict """ |
output_model = copy.copy(input_model)
o_hmms = []
for i_hmm in input_model['hmms']:
i_hmm_name = i_hmm['name']
o_hmm_names = mapping.get(i_hmm_name, [i_hmm_name])
for o_hmm_name in o_hmm_names:
o_hmm = copy.copy(i_hmm)
o_hmm['name'] = o_hmm_name
o_hmms.append(o_hmm)
output_model['hmms'] = o_hmms
return output_model |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DecoratorMixin(decorator):
""" Converts a decorator written for a function view into a mixin for a class-based view. :: LoginRequiredMixin = DecoratorMixin(login_required) class MyView(LoginRequiredMixin):
pass class SomeView(DecoratorMixin(some_decorator), DecoratorMixin(something_else)):
pass """ |
class Mixin(object):
__doc__ = decorator.__doc__
@classmethod
def as_view(cls, *args, **kwargs):
view = super(Mixin, cls).as_view(*args, **kwargs)
return decorator(view)
Mixin.__name__ = str('DecoratorMixin(%s)' % decorator.__name__)
return Mixin |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def seq_list_nested(b, d, x=0, top_level=True):
'''
Create a nested list of iteratively increasing values.
b: branching factor
d: max depth
x: starting value (default = 0)
'''
x += 1
if d == 0:
ret = [x]
else:
val = x
ret = []
for i in range(b):
lst, x = seq_list_nested(b, d-1, x, False)
ret.extend(lst)
ret = [val, ret]
if top_level:
return ret
else:
return ret, x |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def Opaque(uri, tc, ps, **keywords):
'''Resolve a URI and return its content as a string.
'''
source = urllib.urlopen(uri, **keywords)
enc = source.info().getencoding()
if enc in ['7bit', '8bit', 'binary']: return source.read()
data = StringIO.StringIO()
mimetools.decode(source, data, enc)
return data.getvalue() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def XML(uri, tc, ps, **keywords):
'''Resolve a URI and return its content as an XML DOM.
'''
source = urllib.urlopen(uri, **keywords)
enc = source.info().getencoding()
if enc in ['7bit', '8bit', 'binary']:
data = source
else:
data = StringIO.StringIO()
mimetools.decode(source, data, enc)
data.seek(0)
dom = ps.readerclass().fromStream(data)
return _child_elements(dom)[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 GetSOAPPart(self):
'''Get the SOAP body part.
'''
head, part = self.parts[0]
return StringIO.StringIO(part.getvalue()) |
<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(self, uri):
'''Get the content for the bodypart identified by the uri.
'''
if uri.startswith('cid:'):
# Content-ID, so raise exception if not found.
head, part = self.id_dict[uri[4:]]
return StringIO.StringIO(part.getvalue())
if self.loc_dict.has_key(uri):
head, part = self.loc_dict[uri]
return StringIO.StringIO(part.getvalue())
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 load_from_file(cls, file_path):
"""Load the meta data given a file_path or empty meta data""" |
data = None
if os.path.exists(file_path):
metadata_file = open(file_path)
data = json.loads(metadata_file.read())
return cls(initial=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 bind_and_save(self, lxc):
"""Binds metadata to an LXC and saves it""" |
bound_meta = self.bind(lxc)
bound_meta.save()
return bound_meta |
<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, report):
""" Add the items from the given report. """ |
self.tp.extend(pack_boxes(report.tp, self.title))
self.fp.extend(pack_boxes(report.fp, self.title))
self.fn.extend(pack_boxes(report.fn, self.title)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_scale(cls, gold_number, precision, recall, title):
""" deprecated, for backward compactbility try to use from_score """ |
tp_count = get_numerator(recall, gold_number)
positive_count = get_denominator(precision, tp_count)
fp_count = positive_count - tp_count
fn_count = gold_number - tp_count
scale_report = cls(['tp'] * tp_count,
['fp'] * fp_count,
['fn'] * fn_count,
title)
return scale_report |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def worker(work_unit):
'''Expects a WorkUnit from coordinated, obtains a config, and runs
traverse_extract_fetch
'''
if 'config' not in work_unit.spec:
raise coordinate.exceptions.ProgrammerError(
'could not run extraction without global config')
web_conf = Config()
unitconf = work_unit.spec['config']
#logger.info(unitconf)
with yakonfig.defaulted_config([coordinate, kvlayer, dblogger, web_conf],
config=unitconf):
traverse_extract_fetch(web_conf, work_unit.key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def name_filter(keywords, names):
'''
Returns the first keyword from the list, unless
that keyword is one of the names in names, in which case
it continues to the next keyword.
Since keywords consists of tuples, it just returns the first
element of the tuple, the keyword. It also adds double
quotes around the keywords, as is appropriate for google queries.
Input Arguments:
keywords -- a list of (keyword, strength) tuples
names -- a list of names to be skipped
'''
name_set = set(name.lower() for name in names)
for key_tuple in keywords:
if not key_tuple[0] in name_set:
return '\"' + key_tuple[0] +'\"'
## returns empty string if we run out, which we shouldn't
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 _resolve_prefix(celt, prefix):
'''resolve prefix to a namespaceURI. If None or
empty str, return default namespace or None.
Parameters:
celt -- element node
prefix -- xmlns:prefix, or empty str or None
'''
namespace = None
while _is_element(celt):
if prefix:
namespaceURI = _find_xmlns_prefix(celt, prefix)
else:
namespaceURI = _find_default_namespace(celt)
if namespaceURI: break
celt = celt.parentNode
else:
if prefix:
raise EvaluateException, 'cant resolve xmlns:%s' %prefix
return namespaceURI |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _valid_encoding(elt):
'''Does this node have a valid encoding?
'''
enc = _find_encstyle(elt)
if not enc or enc == _SOAP.ENC: return 1
for e in enc.split():
if e.startswith(_SOAP.ENC):
# XXX Is this correct? Once we find a Sec5 compatible
# XXX encoding, should we check that all the rest are from
# XXX that same base? Perhaps. But since the if test above
# XXX will surely get 99% of the cases, leave it for now.
return 1
return 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 _backtrace(elt, dom):
'''Return a "backtrace" from the given element to the DOM root,
in XPath syntax.
'''
s = ''
while elt != dom:
name, parent = elt.nodeName, elt.parentNode
if parent is None: break
matches = [ c for c in _child_elements(parent)
if c.nodeName == name ]
if len(matches) == 1:
s = '/' + name + s
else:
i = matches.index(elt) + 1
s = ('/%s[%d]' % (name, i)) + s
elt = parent
return 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 connect(self):
'''
Connects to the IRC server with the options defined in `config`
'''
self._connect()
try:
self._listen()
except (KeyboardInterrupt, SystemExit):
pass
finally:
self.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _listen(self):
""" Constantly listens to the input from the server. Since the messages come in pieces, we wait until we receive 1 or more full lines to start parsing. A new line is defined as ending in \r\n in the RFC, but some servers separate by \n. This script takes care of both. """ |
while True:
self._inbuffer = self._inbuffer + self.socket.recv(1024)
# Some IRC servers disregard the RFC and split lines by \n rather than \r\n.
temp = self._inbuffer.split("\n")
self._inbuffer = temp.pop()
for line in temp:
# Strip \r from \r\n for RFC-compliant IRC servers.
line = line.rstrip('\r')
if self.config['verbose']: print line
self._run_listeners(line) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _run_listeners(self, line):
""" Each listener's associated regular expression is matched against raw IRC input. If there is a match, the listener's associated function is called with all the regular expression's matched subgroups. """ |
for regex, callbacks in self.listeners.iteritems():
match = regex.match(line)
if not match:
continue
for callback in callbacks:
callback(*match.groups()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _strip_prefix(self, message):
""" Checks if the bot was called by a user. Returns the suffix if so. Prefixes include the bot's nick as well as a set symbol. """ |
if not hasattr(self, "name_regex"):
"""
regex example:
^(((BotA|BotB)[,:]?\s+)|%)(.+)$
names = [BotA, BotB]
prefix = %
"""
names = self.config['names']
prefix = self.config['prefix']
name_regex_str = r'^(?:(?:(%s)[,:]?\s+)|%s)(.+)$' % (re.escape("|".join(names)), prefix)
self.name_regex = re.compile(name_regex_str, re.IGNORECASE)
search = self.name_regex.search(message)
if search:
return search.groups()[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 _connect(self):
"Connects a socket to the server using options defined in `config`."
self.socket = socket.socket()
self.socket.connect((self.config['host'], self.config['port']))
self.cmd("NICK %s" % self.config['nick'])
self.cmd("USER %s %s bla :%s" %
(self.config['ident'], self.config['host'], self.config['realname'])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interpret_contribution_entry(entry):
"""Interpret data fields within a CO-TRACER contributions report. Interpret the contribution amount, contribution date, filed date, amended, and amendment fields of the provided entry. All dates (contribution and filed) are interpreted together and, if any fails, all will retain their original value. Likewise, amended and amendment are interpreted together and if one is malformed, both will retain their original value. Entry may be edited in place and side-effects are possible in coupled code. However, client code should use the return value to guard against future changes. A value with the key 'AmountsInterpreted' will be set to True or False in the returned entry if floating point values are successfully interpreted (ContributionAmount) or not respectively. A value with the key 'DatesInterpreted' will be set to True or False in the returned entry if ISO 8601 strings are successfully interpreted (ContributionDate and FiledDate) or not respectively. A value with the key 'BooleanFieldsInterpreted' will be set to True or False in the returned entry if boolean strings are successfully interpreted (Amended and Amendment) or not respectively. @param entry: The contribution report data to manipulate / interpret. @type entry: dict @return: The entry passed @raise ValueError: Raised if any expected field cannot be found in entry. """ |
try:
new_contribution_amount = float(entry['ContributionAmount'])
entry['AmountsInterpreted'] = True
entry['ContributionAmount'] = new_contribution_amount
except ValueError:
entry['AmountsInterpreted'] = False
except TypeError:
entry['AmountsInterpreted'] = False
except AttributeError:
entry['AmountsInterpreted'] = False
try:
contribution_date = parse_iso_str(entry['ContributionDate'])
filed_date = parse_iso_str(entry['FiledDate'])
entry['DatesInterpreted'] = True
entry['ContributionDate'] = contribution_date
entry['FiledDate'] = filed_date
except ValueError:
entry['DatesInterpreted'] = False
except TypeError:
entry['DatesInterpreted'] = False
except AttributeError:
entry['DatesInterpreted'] = False
try:
amended = parse_yes_no_str(entry['Amended'])
amendment = parse_yes_no_str(entry['Amendment'])
entry['BooleanFieldsInterpreted'] = True
entry['Amended'] = amended
entry['Amendment'] = amendment
except ValueError:
entry['BooleanFieldsInterpreted'] = False
except TypeError:
entry['BooleanFieldsInterpreted'] = False
except AttributeError:
entry['BooleanFieldsInterpreted'] = False
return entry |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interpret_expenditure_entry(entry):
"""Interpret data fields within a CO-TRACER expediture report. Interpret the expenditure amount, expenditure date, filed date, amended, and amendment fields of the provided entry. All dates (expenditure and filed) are interpreted together and, if any fails, all will retain their original value. Likewise, amended and amendment are interpreted together and if one is malformed, both will retain their original value. Entry may be edited in place and side-effects are possible in coupled code. However, client code should use the return value to guard against future changes. A value with the key 'AmountsInterpreted' will be set to True or False in the returned entry if floating point values are successfully interpreted (ExpenditureAmount) or not respectively. A value with the key 'DatesInterpreted' will be set to True or False in the returned entry if ISO 8601 strings are successfully interpreted (ExpenditureDate and FiledDate) or not respectively. A value with the key 'BooleanFieldsInterpreted' will be set to True or False in the returned entry if boolean strings are successfully interpreted (Amended and Amendment) or not respectively. @param entry: The expenditure report data to manipulate / interpret. @type entry: dict @return: The entry passed @raise ValueError: Raised if any expected field cannot be found in entry. """ |
try:
expenditure_amount = float(entry['ExpenditureAmount'])
entry['AmountsInterpreted'] = True
entry['ExpenditureAmount'] = expenditure_amount
except ValueError:
entry['AmountsInterpreted'] = False
try:
expenditure_date = parse_iso_str(entry['ExpenditureDate'])
filed_date = parse_iso_str(entry['FiledDate'])
entry['DatesInterpreted'] = True
entry['ExpenditureDate'] = expenditure_date
entry['FiledDate'] = filed_date
except ValueError:
entry['DatesInterpreted'] = False
try:
amended = parse_yes_no_str(entry['Amended'])
amendment = parse_yes_no_str(entry['Amendment'])
entry['BooleanFieldsInterpreted'] = True
entry['Amended'] = amended
entry['Amendment'] = amendment
except ValueError:
entry['BooleanFieldsInterpreted'] = False
return entry |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interpret_loan_entry(entry):
"""Interpret data fields within a CO-TRACER loan report. Interpret the payment amount, loan amount, interest rate, interest payment, loan balance, payment date, filed date, loan date, amended, and amendment fields of the provided entry. All dates (payment, filed, and loan) are interpreted together and, if any fails, all will retain their original value. Likewise, amended and amendment are interpreted together and if one is malformed, both will retain their original value. Finally, the payment amount, loan amount, interest rate, interest payment, and loan balance will be interpreted transactionally and, if any fail, all will retain their original value. Entry may be edited in place and side-effects are possible in coupled code. However, client code should use the return value to guard against future changes. A value with the key 'AmountsInterpreted' will be set to True or False in the returned entry if floating point values are successfully interpreted or not respectively. A value with the key 'DatesInterpreted' will be set to True or False in the returned entry if ISO 8601 strings are successfully interpreted or not respectively. A value with the key 'BooleanFieldsInterpreted' will be set to True or False in the returned entry if boolean strings are successfully interpreted or not respectively. @param entry: The loan report data to manipulate / interpret. @type entry: dict @return: The entry passed @raise ValueError: Raised if any expected field cannot be found in entry. """ |
try:
payment_amount = float(entry['PaymentAmount'])
loan_amount = float(entry['LoanAmount'])
interest_rate = float(entry['InterestRate'])
interest_payment = float(entry['InterestPayment'])
loan_balance = float(entry['LoanBalance'])
entry['AmountsInterpreted'] = True
entry['PaymentAmount'] = payment_amount
entry['LoanAmount'] = loan_amount
entry['InterestRate'] = interest_rate
entry['InterestPayment'] = interest_payment
entry['LoanBalance'] = loan_balance
except ValueError:
entry['AmountsInterpreted'] = False
try:
payment_date = parse_iso_str(entry['PaymentDate'])
filed_date = parse_iso_str(entry['FiledDate'])
loan_date = parse_iso_str(entry['LoanDate'])
entry['DatesInterpreted'] = True
entry['PaymentDate'] = payment_date
entry['FiledDate'] = filed_date
entry['LoanDate'] = loan_date
except ValueError:
entry['DatesInterpreted'] = False
try:
amended = parse_yes_no_str(entry['Amended'])
amendment = parse_yes_no_str(entry['Amendment'])
entry['BooleanFieldsInterpreted'] = True
entry['Amended'] = amended
entry['Amendment'] = amendment
except ValueError:
entry['BooleanFieldsInterpreted'] = False
return entry |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_file(self, path, dryrun):
""" Add header to all files. """ |
if dryrun:
return path
# get file's current header
with open(path, "r") as infile:
head = infile.read(len(self.__header))
# normalize line breaks
if self.__normalize_br:
head = head.replace("\r\n", "\n")
# already contain header? skip
if head == self.__header:
return path
# add header to file
self.push_header(path)
# return processed file
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def csv_list(models, attr, link=False, separator=", "):
"""Return a comma-separated list of models, optionaly with a link.""" |
values = []
for model in models:
value = getattr(model, attr)
if link and hasattr(model, "get_admin_url") and callable(model.get_admin_url):
value = get_admin_html_link(model, label=value)
values.append(value)
return separator.join(values) |
<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_admin_url(obj, page=None):
"""Return the URL to admin pages for this object.""" |
if obj is None:
return None
if page is None:
page = "change"
if page not in ADMIN_ALL_PAGES:
raise ValueError("Invalid page name '{}'. Available pages are: {}.".format(page, ADMIN_ALL_PAGES))
app_label = obj.__class__._meta.app_label
object_name = obj.__class__._meta.object_name.lower()
if page in ADMIN_GLOBAL_PAGES:
url_name = page
else:
url_name = "{}_{}_{}".format(app_label, object_name, page)
if page == "app_list":
url_args = (app_label,)
elif page == "view_on_site":
content_type = ContentType.objects.get_for_model(obj.__class__)
url_args = (content_type, obj._get_pk_val())
elif page in ADMIN_DETAIL_PAGES:
url_args = (obj._get_pk_val(),)
else:
url_args = None
return reverse("admin:{}".format(url_name), args=url_args) |
<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_fieldset_index(fieldsets, index_or_name):
""" Return the index of a fieldset in the ``fieldsets`` list. Args: fieldsets (list):
The original ``fieldsets`` list. index_or_name (int or str):
The value of the reference element, or directly its numeric index. Returns: (int) The index of the fieldset in the ``fieldsets`` list. """ |
if isinstance(index_or_name, six.integer_types):
return index_or_name
for key, value in enumerate(fieldsets):
if value[0] == index_or_name:
return key
raise KeyError("Key not found: '{}'.".format(index_or_name)) |
<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_list_index(lst, index_or_name):
""" Return the index of an element in the list. Args: lst (list):
The list. index_or_name (int or str):
The value of the reference element, or directly its numeric index. Returns: (int) The index of the element in the list. """ |
if isinstance(index_or_name, six.integer_types):
return index_or_name
return lst.index(index_or_name) |
<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_value(self, value, timeout):
""" Sets a new value and extends its expiration. :param value: a new cached value. :param timeout: a expiration timeout in milliseconds. """ |
self.value = value
self.expiration = time.perf_counter() * 1000 + timeout |
<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_password():
"""Create a random password The password is made by taking a uuid and passing it though sha1sum. We may change this in future to gain more entropy. This is based on the tripleo command os-make-password """ |
uuid_str = six.text_type(uuid.uuid4()).encode("UTF-8")
return hashlib.sha1(uuid_str).hexdigest() |
<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_overcloud_passwords(output_file="tripleo-overcloud-passwords"):
"""Create the passwords needed for the overcloud This will create the set of passwords required by the overcloud, store them in the output file path and return a dictionary of passwords. If the file already exists the existing passwords will be returned instead, """ |
if os.path.isfile(output_file):
with open(output_file) as f:
return dict(line.split('=') for line in f.read().splitlines())
password_names = (
"OVERCLOUD_ADMIN_PASSWORD",
"OVERCLOUD_ADMIN_TOKEN",
"OVERCLOUD_CEILOMETER_PASSWORD",
"OVERCLOUD_CEILOMETER_SECRET",
"OVERCLOUD_CINDER_PASSWORD",
"OVERCLOUD_DEMO_PASSWORD",
"OVERCLOUD_GLANCE_PASSWORD",
"OVERCLOUD_HEAT_PASSWORD",
"OVERCLOUD_HEAT_STACK_DOMAIN_PASSWORD",
"OVERCLOUD_NEUTRON_PASSWORD",
"OVERCLOUD_NOVA_PASSWORD",
"OVERCLOUD_SWIFT_HASH",
"OVERCLOUD_SWIFT_PASSWORD",
)
passwords = dict((p, _generate_password()) for p in password_names)
with open(output_file, 'w') as f:
for name, password in passwords.items():
f.write("{0}={1}\n".format(name, password))
return passwords |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_hypervisor_stats(compute_client, nodes=1, memory=0, vcpu=0):
"""Check the Hypervisor stats meet a minimum value Check the hypervisor stats match the required counts. This is an implementation of a command in TripleO with the same name. :param compute_client: Instance of Nova client :type compute_client: novaclient.client.v2.Client :param nodes: The number of nodes to wait for, defaults to 1. :type nodes: int :param memory: The amount of memory to wait for in MB, defaults to 0. :type memory: int :param vcpu: The number of vcpus to wait for, defaults to 0. :type vcpu: int """ |
statistics = compute_client.hypervisors.statistics().to_dict()
if all([statistics['count'] >= nodes,
statistics['memory_mb'] >= memory,
statistics['vcpus'] >= vcpu]):
return statistics
else:
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 wait_for_stack_ready(orchestration_client, stack_name):
"""Check the status of an orchestration stack Get the status of an orchestration stack and check whether it is complete or failed. :param orchestration_client: Instance of Orchestration client :type orchestration_client: heatclient.v1.client.Client :param stack_name: Name or UUID of stack to retrieve :type stack_name: string """ |
SUCCESSFUL_MATCH_OUTPUT = "(CREATE|UPDATE)_COMPLETE"
FAIL_MATCH_OUTPUT = "(CREATE|UPDATE)_FAILED"
while True:
stack = orchestration_client.stacks.get(stack_name)
if not stack:
return False
status = stack.stack_status
if re.match(SUCCESSFUL_MATCH_OUTPUT, status):
return True
if re.match(FAIL_MATCH_OUTPUT, status):
print("Stack failed with status: {}".format(
stack.stack_status_reason, file=sys.stderr))
return False
time.sleep(10) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_for_provision_state(baremetal_client, node_uuid, provision_state, loops=10, sleep=1):
"""Wait for a given Provisioning state in Ironic Discoverd Updating the provisioning state is an async operation, we need to wait for it to be completed. :param baremetal_client: Instance of Ironic client :type baremetal_client: ironicclient.v1.client.Client :param node_uuid: The Ironic node UUID :type node_uuid: str :param provision_state: The provisioning state name to wait for :type provision_state: str :param loops: How many times to loop :type loops: int :param sleep: How long to sleep between loops :type sleep: int """ |
for _ in range(0, loops):
node = baremetal_client.node.get(node_uuid)
if node is None:
# The node can't be found in ironic, so we don't need to wait for
# the provision state
return True
if node.provision_state == provision_state:
return True
time.sleep(sleep)
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 wait_for_node_discovery(discoverd_client, auth_token, discoverd_url, node_uuids, loops=220, sleep=10):
"""Check the status of Node discovery in Ironic discoverd Gets the status and waits for them to complete. :param discoverd_client: Ironic Discoverd client :type discoverd_client: ironic_discoverd.client :param auth_token: Authorisation token used by discoverd client :type auth_token: string :param discoverd_url: URL used by the discoverd client :type discoverd_url: string :param node_uuids: List of Node UUID's to wait for discovery :type node_uuids: [string, ] :param loops: How many times to loop :type loops: int :param sleep: How long to sleep between loops :type sleep: int """ |
log = logging.getLogger(__name__ + ".wait_for_node_discovery")
node_uuids = node_uuids[:]
for _ in range(0, loops):
for node_uuid in node_uuids:
status = discoverd_client.get_status(
node_uuid,
base_url=discoverd_url,
auth_token=auth_token)
if status['finished']:
log.debug("Discover finished for node {0} (Error: {1})".format(
node_uuid, status['error']))
node_uuids.remove(node_uuid)
yield node_uuid, status
if not len(node_uuids):
raise StopIteration
time.sleep(sleep)
if len(node_uuids):
log.error("Discovery didn't finish for nodes {0}".format(
','.join(node_uuids))) |
<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_environment_file(path="~/overcloud-env.json", control_scale=1, compute_scale=1, ceph_storage_scale=0, block_storage_scale=0, swift_storage_scale=0):
"""Create a heat environment file Create the heat environment file with the scale parameters. :param control_scale: Scale value for control roles. :type control_scale: int :param compute_scale: Scale value for compute roles. :type compute_scale: int :param ceph_storage_scale: Scale value for ceph storage roles. :type ceph_storage_scale: int :param block_storage_scale: Scale value for block storage roles. :type block_storage_scale: int :param swift_storage_scale: Scale value for swift storage roles. :type swift_storage_scale: int """ |
env_path = os.path.expanduser(path)
with open(env_path, 'w+') as f:
f.write(json.dumps({
"parameters": {
"ControllerCount": control_scale,
"ComputeCount": compute_scale,
"CephStorageCount": ceph_storage_scale,
"BlockStorageCount": block_storage_scale,
"ObjectStorageCount": swift_storage_scale}
}))
return env_path |
<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_nodes_state(baremetal_client, nodes, transition, target_state, skipped_states=()):
"""Make all nodes available in the baremetal service for a deployment For each node, make it available unless it is already available or active. Available nodes can be used for a deployment and an active node is already in use. :param baremetal_client: Instance of Ironic client :type baremetal_client: ironicclient.v1.client.Client :param nodes: List of Baremetal Nodes :type nodes: [ironicclient.v1.node.Node] :param transition: The state to set for a node. The full list of states can be found in ironic.common.states. :type transition: string :param target_state: The expected result state for a node. For example when transitioning to 'manage' the result is 'manageable' :type target_state: string :param skipped_states: A set of states to skip, for example 'active' nodes are already deployed and the state can't always be changed. :type skipped_states: iterable of strings """ |
log = logging.getLogger(__name__ + ".set_nodes_state")
for node in nodes:
if node.provision_state in skipped_states:
continue
log.debug(
"Setting provision state from {0} to '{1} for Node {2}"
.format(node.provision_state, transition, node.uuid))
baremetal_client.node.set_provision_state(node.uuid, transition)
if not wait_for_provision_state(baremetal_client, node.uuid,
target_state):
print("FAIL: State not updated for Node {0}".format(
node.uuid, file=sys.stderr))
else:
yield node.uuid |
<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_hiera_key(key_name):
"""Retrieve a key from the hiera store :param password_name: Name of the key to retrieve :type password_name: type """ |
command = ["hiera", key_name]
p = subprocess.Popen(command, stdout=subprocess.PIPE)
out, err = p.communicate()
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 remove_known_hosts(overcloud_ip):
"""For a given IP address remove SSH keys from the known_hosts file""" |
known_hosts = os.path.expanduser("~/.ssh/known_hosts")
if os.path.exists(known_hosts):
command = ['ssh-keygen', '-R', overcloud_ip, '-f', known_hosts]
subprocess.check_call(command) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_checksum(filepath):
"""Calculate md5 checksum on file :param filepath: Full path to file (e.g. /home/stack/image.qcow2) :type filepath: string """ |
checksum = hashlib.md5()
with open(filepath, 'rb') as f:
for fragment in iter(lambda: f.read(65536), ''):
checksum.update(fragment)
return checksum.hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Do the thing""" |
username = os.environ["GITHUB_USERNAME"]
password = os.environ["GITHUB_PASSWORD"]
# Unless you have an LSST account you'd want to change these
baseurl = "https://logging.lsst.codes/oauth2/start"
authpage = "https://logging.lsst.codes/app/kibana"
session = bses.Session(oauth2_username=username,
oauth2_password=password,
authentication_base_url=baseurl)
resp = session.get(authpage)
print(resp)
if resp.status_code == 200:
print(resp.content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _assert_correct_model(model_to_check, model_reference, obj_name):
""" Helper that asserts the model_to_check is the model_reference or one of its subclasses. If not, raise an ImplementationError, using "obj_name" to describe the name of the argument. """ |
if not issubclass(model_to_check, model_reference):
raise ConfigurationException('The %s model must be a subclass of %s'
% (obj_name, model_reference.__name__)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_end_signal(self):
""" Catch some system signals to handle them internaly """ |
try:
signal.signal(signal.SIGTERM, self.catch_end_signal)
signal.signal(signal.SIGINT, self.catch_end_signal)
except ValueError:
self.log('Signals cannot be caught in a Thread', level='warning') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop_handling_end_signal(self):
""" Stop handling the SIGINT and SIGTERM signals """ |
try:
signal.signal(signal.SIGTERM, signal.SIG_DFL)
signal.signal(signal.SIGINT, signal.SIG_DFL)
except ValueError:
self.log('Signals cannot be caught in a Thread', level='warning') |
<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_logger(self):
""" Prepare the logger, using self.logger_name and self.logger_level """ |
self.logger = logging.getLogger(self.logger_name)
self.logger.setLevel(self.logger_level) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def id(self):
""" Return an identifier for the worker to use in logging """ |
if not hasattr(self, '_id'):
self._id = str(threading.current_thread().ident + id(self))[-6:]
return self._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 must_stop(self):
""" Return True if the worker must stop when the current loop is over. """ |
return bool(self.terminate_gracefuly and self.end_signal_caught
or self.num_loops >= self.max_loops or self.end_forced
or self.wanted_end_date and datetime.utcnow() >= self.wanted_end_date) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.