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_fie...
<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 e...
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...
<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'] =...
<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 cl...
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_nam...
<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...
<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, 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 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_kw...
<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.p...
<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...
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 eng...
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=aut...
<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 ...
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...
<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...
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], k...
<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 ke...
rel = { key: { 'data': [], 'links': { 'related': rlink + '/' + key } } } try: for val in vals: rel[key]['data'].append({ 'id': val['rid'], ...
<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: ...
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: st...
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: ...
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: s...
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: ...
<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.ru...
<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, reque...
<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) ...
<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 = \ ...
<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 Typ...
<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, sel...
<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 th...
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(**{ 'deta...
<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 # valid...
<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 produc...
<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_en...
<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": { }, "jso...
<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...
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] ...
<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 t...
h5 = h5py.File(h5file, 'w') for h in headers: h5.create_dataset(h, shape=(0,), maxshape=(None,), dtype=np.float64, chunks=(chunksize,), compression='gzip', ...
<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...
<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 HT...
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 ...
<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...
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 ...
<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(l...
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): ...
<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) ...
<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(so...
<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.h...
<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, ...
<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() unitcon...
<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 ...
<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: ...
<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...
<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) ...
<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...
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...
<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 associate...
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...
<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.c...
<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, ...
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 ...
<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 ...
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']) ...
<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 paym...
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 ...
<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? sk...
<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.objec...
<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...
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 th...
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 m...
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 m...
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 passwor...
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...
<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 re...
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 whet...
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, statu...
<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 Updatin...
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 T...
<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 discov...
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_t...
<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): "...
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, "BlockStorageCou...
<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 ...
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)) ...
<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, ...
<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 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)