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 push_front(self, value): '''Appends a copy of ``value`` to the beginning of the list.''' self.cache.push_front(self.value_pickler.dumps(value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def aggregate(self, kwargs): '''Aggregate lookup parameters.''' meta = self._meta fields = meta.dfields field_lookups = {} for name, value in iteritems(kwargs): bits = name.split(JSPLITTER) field_name = bits.pop(0) if field_name not in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def models_from_model(model, include_related=False, exclude=None): '''Generator of all model in model.''' if exclude is None: exclude = set() if model and model not in exclude: exclude.add(model) if isinstance(model, ModelType) and not model._meta.abstract: yield 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 unregister(self, model=None): '''Unregister a ``model`` if provided, otherwise it unregister all registered models. Return a list of unregistered model managers or ``None`` if no managers were removed.''' if model is not None: try: manager = self._registered_models.pop(mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def execute_script(self, name, keys, *args, **options): '''Execute a script. makes sure all required scripts are loaded. ''' script = get_script(name) if not script: raise redis.RedisError('No such script "%s"' % name) address = self.address() if addr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def query(self, model): '''Return a query for ``model`` when it needs to be indexed. ''' session = self.router.session() fields = tuple((f.name for f in model._meta.scalarfields if f.type == 'text')) qs = session.query(model).load_only(*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 intervals(self, startdate, enddate, parseinterval=None): '''Given a ``startdate`` and an ``enddate`` dates, evaluate the date intervals from which data is not available. It return a list of two-dimensional tuples containing start and end date for the interval. The list could cont...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def merged_series(cls, *series, **kwargs): '''Merge ``series`` and return the results without storing data in the backend server.''' router, backend = cls.check_router(None, *series) if backend: target = router.register(cls(), backend) router.session().add(target) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def backend_fields(self, fields): '''Return a two elements tuple containing a list of fields names and a list of field attribute names.''' dfields = self.dfields processed = set() names = [] atts = [] pkname = self.pkname() for name in 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 as_dict(self): '''Model metadata in a dictionary''' pk = self.pk id_type = 3 if pk.type == 'auto': id_type = 1 return {'id_name': pk.name, 'id_type': id_type, 'sorted': bool(self.ordering), 'autoincr': 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 loadedfields(self): '''Generator of fields loaded from database''' if self._loadedfields is None: for field in self._meta.scalarfields: yield field else: fields = self._meta.dfields processed = set() for name in self._loadedfiel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def clone(self, **data): '''Utility method for cloning the instance as a new object. :parameter data: additional which override field data. :rtype: a new instance of this class. ''' meta = self._meta session = self.session pkname = meta.pkname() pkvalue = data.pop(pkname, 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 title(self): ''' Returns the axis instance where the title will be printed ''' return self.title_left(on=False), self.title_center(on=False), \ self.title_right(on=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 footer(self): ''' Returns the axis instance where the footer will be printed ''' return self.footer_left(on=False), self.footer_center(on=False), \ self.footer_right(on=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 top_right(self): ''' Returns the axis instance at the top right of the page, where the postage stamp and aperture is displayed ''' res = self.body_top_right[self.tcount]() self.tcount += 1 return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def left(self): ''' Returns the current axis instance on the left side of the page where each successive light curve is displayed ''' res = self.body_left[self.lcount]() self.lcount += 1 return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def right(self): ''' Returns the current axis instance on the right side of the page, where cross-validation information is displayed ''' res = self.body_right[self.rcount]() self.rcount += 1 return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def body(self): ''' Returns the axis instance where the light curves will be shown ''' res = self._body[self.bcount]() self.bcount += 1 return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def hashmodel(model, library=None): '''Calculate the Hash id of metaclass ``meta``''' library = library or 'python-stdnet' meta = model._meta sha = hashlib.sha1(to_bytes('{0}({1})'.format(library, meta))) hash = sha.hexdigest()[:8] meta.hash = hash if hash in _model_dict: rai...
<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(self, callback, sender=None): '''Bind a ``callback`` for a given ``sender``.''' key = (_make_id(callback), _make_id(sender)) self.callbacks.append((key, callback))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fire(self, sender=None, **params): '''Fire callbacks from a ``sender``.''' keys = (_make_id(None), _make_id(sender)) results = [] for (_, key), callback in self.callbacks: if key in keys: results.append(callback(self, sender, **params)) retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Channel(EPIC, campaign=None): ''' Returns the channel number for a given EPIC target. ''' if campaign is None: campaign = Campaign(EPIC) if hasattr(campaign, '__len__'): raise AttributeError( "Please choose a campaign/season for this target: %s." % campaign) try...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Module(EPIC, campaign=None): ''' Returns the module number for a given EPIC target. ''' channel = Channel(EPIC, campaign=campaign) nums = {2: 1, 3: 5, 4: 9, 6: 13, 7: 17, 8: 21, 9: 25, 10: 29, 11: 33, 12: 37, 13: 41, 14: 45, 15: 49, 16: 53, 17: 57, 18: 61, 19: 65, 20: 6...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Channels(module): ''' Returns the channels contained in the given K2 module. ''' nums = {2: 1, 3: 5, 4: 9, 6: 13, 7: 17, 8: 21, 9: 25, 10: 29, 11: 33, 12: 37, 13: 41, 14: 45, 15: 49, 16: 53, 17: 57, 18: 61, 19: 65, 20: 69, 22: 73, 23: 77, 24: 81} if module ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def GetSources(ID, darcsec=None, stars_only=False): ''' Grabs the EPIC coordinates from the TPF and searches MAST for other EPIC targets within the same aperture. :param int ID: The 9-digit :py:obj:`EPIC` number of the target :param float darcsec: The search radius in arcseconds. \ Defau...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def SaturationFlux(EPIC, campaign=None, **kwargs): ''' Returns the well depth for the target. If any of the target's pixels have flux larger than this value, they are likely to be saturated and cause charge bleeding. The well depths were obtained from Table 13 of the Kepler instrument handbook. We 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 GetStars(campaign, module, model='nPLD', **kwargs): ''' Returns de-trended light curves for all stars on a given module in a given campaign. ''' # Get the channel numbers channels = Channels(module) assert channels is not None, "No channels available on this module." # Get the EPI...
<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_info(response): '''Parse the response of Redis's INFO command into a Python dict. In doing so, convert byte data into unicode.''' info = {} response = response.decode('utf-8') def get_value(value): if ',' and '=' not in value: return value sub_dict = {} ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def zdiffstore(self, dest, keys, withscores=False): '''Compute the difference of multiple sorted. The difference of sets specified by ``keys`` into a new sorted set in ``dest``. ''' keys = (dest,) + tuple(keys) wscores = 'withscores' if withscores 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 zpopbyrank(self, name, start, stop=None, withscores=False, desc=False): '''Pop a range by rank. ''' stop = stop if stop is not None else start return self.execute_script('zpop', (name,), 'rank', start, stop, int(desc), int(withscores), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lnprior(x): """Return the log prior given parameter vector `x`."""
per, t0, b = x if b < -1 or b > 1: return -np.inf elif per < 7 or per > 10: return -np.inf elif t0 < 1978 or t0 > 1979: return -np.inf else: 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 lnlike(x, star): """Return the log likelihood given parameter vector `x`."""
ll = lnprior(x) if np.isinf(ll): return ll, (np.nan, np.nan) per, t0, b = x model = TransitModel('b', per=per, t0=t0, b=b, rhos=10.)(star.time) like, d, vard = star.lnlike(model, full_output=True) ll += like return ll, (d,)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def permitted_query(self, query, group, operations): '''Change the ``query`` so that only instances for which ``group`` has roles with permission on ``operations`` are returned.''' session = query.session models = session.router user = group.user if user.is_superuser: # super-u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_app(self, app, session=None, parameters=None): """Initializes snow extension Set config default and find out which client type to use :param app: App pa...
if parameters is not None and not isinstance(parameters, ParamsBuilder): raise InvalidUsage("parameters should be a pysnow.ParamsBuilder object, not %r" % type(parameters).__name__) self._session = session self._parameters = parameters app.config.setdefault('SNOW_INSTANCE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connection(self): """Snow connection instance, stores a `pysnow.Client` instance and `pysnow.Resource` instances Creates a new :class:`pysnow.Client` object ...
ctx = stack.top.app if ctx is not None: if not hasattr(ctx, 'snow'): if self._client_type_oauth: if not self._token_updater: warnings.warn("No token updater has been set. Token refreshes will be ignored.") cli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def usage(): """Print out a usage message"""
global options l = len(options['long']) options['shortlist'] = [s for s in options['short'] if s is not ":"] print("python -m behave2cucumber [-h] [-d level|--debug=level]") for i in range(l): print(" -{0}|--{1:20} {2}".format(options['shortlist'][i], options['long'][i], options['descr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def direction(theta, phi): '''Return the direction vector of a cylinder defined by the spherical coordinates theta and phi. ''' return np.array([np.cos(phi) * np.sin(theta), np.sin(phi) * np.sin(theta), np.cos(theta)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def projection_matrix(w): '''Return the projection matrix of a direction w.''' return np.identity(3) - np.dot(np.reshape(w, (3,1)), np.reshape(w, (1, 3)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def skew_matrix(w): '''Return the skew matrix of a direction w.''' return np.array([[0, -w[2], w[1]], [w[2], 0, -w[0]], [-w[1], w[0], 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 calc_A(Ys): '''Return the matrix A from a list of Y vectors.''' return sum(np.dot(np.reshape(Y, (3,1)), np.reshape(Y, (1, 3))) for Y in Ys)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calc_A_hat(A, S): '''Return the A_hat matrix of A given the skew matrix S''' return np.dot(S, np.dot(A, np.transpose(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 G(w, Xs): '''Calculate the G function given a cylinder direction w and a list of data points Xs to be fitted.''' n = len(Xs) P = projection_matrix(w) Ys = [np.dot(P, X) for X in Xs] A = calc_A(Ys) A_hat = calc_A_hat(A, skew_matrix(w)) u = sum(np.dot(Y, Y) for Y in Ys) / n v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def C(w, Xs): '''Calculate the cylinder center given the cylinder direction and a list of data points. ''' n = len(Xs) P = projection_matrix(w) Ys = [np.dot(P, X) for X in Xs] A = calc_A(Ys) A_hat = calc_A_hat(A, skew_matrix(w)) return np.dot(A_hat, sum(np.dot(Y, Y) * Y for Y in Ys...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def r(w, Xs): '''Calculate the radius given the cylinder direction and a list of data points. ''' n = len(Xs) P = projection_matrix(w) c = C(w, Xs) return np.sqrt(sum(np.dot(c - X, np.dot(P, c - X)) for X in Xs) / n)
<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, request, key): """Validate an email with the given key"""
try: email_val = EmailAddressValidation.objects.get(validation_key=key) except EmailAddressValidation.DoesNotExist: messages.error(request, _('The email address you are trying to ' 'verify either has already been verified' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, request, key): """Remove an email address, validated or not."""
request.DELETE = http.QueryDict(request.body) email_addr = request.DELETE.get('email') user_id = request.DELETE.get('user') if not email_addr: return http.HttpResponseBadRequest() try: email = EmailAddressValidation.objects.get(address=email_addr, ...
<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, request, key): """Set an email address as primary address."""
request.UPDATE = http.QueryDict(request.body) email_addr = request.UPDATE.get('email') user_id = request.UPDATE.get('user') if not email_addr: return http.HttpResponseBadRequest() try: email = EmailAddress.objects.get(address=email_addr, ...
<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_env_setting(setting): """ Get the environment setting or return exception """
try: return os.environ[setting] except KeyError: error_msg = "Set the %s env variable" % setting raise ImproperlyConfigured(error_msg)
<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_social_account(account, url): """Verifies if a social account is valid. Examples: True 'http://twitter.com') False """
request = urllib2.Request(urlparse.urljoin(url, account)) request.get_method = lambda: 'HEAD' try: response = urllib2.urlopen(request) except urllib2.HTTPError: return False return response.code == 200
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fitting_rmsd(w_fit, C_fit, r_fit, Xs): '''Calculate the RMSD of fitting.''' return np.sqrt(sum((geometry.point_line_distance(p, C_fit, w_fit) - r_fit) ** 2 for p in Xs) / len(Xs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def basic_parse(response, buf_size=ijson.backend.BUFSIZE): """ Iterator yielding unprefixed events. Parameters: - response: a stream response from requests """
lexer = iter(IncrementalJsonParser.lexer(response, buf_size)) for value in ijson.backend.parse_value(lexer): yield value try: next(lexer) except StopIteration: pass else: raise ijson.common.JSONError('Additional 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 drop_connection(self, name, database=None): """ Force server to close current client subscription connection to the server @param str name: The name of the s...
request_executor = self._store.get_request_executor(database) command = DropSubscriptionConnectionCommand(name) request_executor.execute(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 execute_from_command_line(argv=None): """ A simple method that runs a ManagementUtility. """
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "colab.settings") from django.conf import settings if not hasattr(settings, 'SECRET_KEY') and 'initconfig' in sys.argv: command = initconfig.Command() command.handle() else: utility = ManagementUtility(argv) utility.execut...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def normalize(v): '''Normalize a vector based on its 2 norm.''' if 0 == np.linalg.norm(v): return v return v / np.linalg.norm(v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rotation_matrix_from_axis_and_angle(u, theta): '''Calculate a rotation matrix from an axis and an angle.''' x = u[0] y = u[1] z = u[2] s = np.sin(theta) c = np.cos(theta) return np.array([[c + x**2 * (1 - c), x * y * (1 - c) - z * s, x * z * (1 - c) + y * 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 point_line_distance(p, l_p, l_v): '''Calculate the distance between a point and a line defined by a point and a direction vector. ''' l_v = normalize(l_v) u = p - l_p return np.linalg.norm(u - np.dot(u, l_v) * l_v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raw_query(self, query, query_parameters=None): """ To get all the document that equal to the query @param str query: The rql query @param dict query_paramete...
self.assert_no_raw_query() if len(self._where_tokens) != 0 or len(self._select_tokens) != 0 or len( self._order_by_tokens) != 0 or len(self._group_by_tokens) != 0: raise InvalidOperationException( "You can only use raw_query on a new query, without applying ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def where_equals(self, field_name, value, exact=False): """ To get all the document that equal to the value in the given field_name @param str field_name: The fi...
if field_name is None: raise ValueError("None field_name is invalid") field_name = Query.escape_if_needed(field_name) self._add_operator_if_needed() token = "equals" if self.negate: self.negate = False token = "not_equals" self.last...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def where(self, exact=False, **kwargs): """ To get all the document that equal to the value within kwargs with the specific key @param bool exact: If True gettin...
for field_name in kwargs: if isinstance(kwargs[field_name], list): self.where_in(field_name, kwargs[field_name], exact) else: self.where_equals(field_name, kwargs[field_name], exact) 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 search(self, field_name, search_terms, operator=QueryOperator.OR): """ For more complex text searching @param str field_name: The field name in the index you...
if field_name is None: raise ValueError("None field_name is invalid") field_name = Query.escape_if_needed(field_name) self._add_operator_if_needed() self.negate_if_needed(field_name) self.last_equality = {field_name: "(" + search_terms + ")" if ' ' in search_terms...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def where_ends_with(self, field_name, value): """ To get all the document that ends with the value in the giving field_name @param str field_name:The field name ...
if field_name is None: raise ValueError("None field_name is invalid") field_name = Query.escape_if_needed(field_name) self._add_operator_if_needed() self.negate_if_needed(field_name) self.last_equality = {field_name: value} token = _Token(field_name=field_n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def where_in(self, field_name, values, exact=False): """ Check that the field has one of the specified values @param str field_name: Name of the field @param str...
field_name = Query.escape_if_needed(field_name) self._add_operator_if_needed() self.negate_if_needed(field_name) token = _Token(field_name=field_name, value=self.add_query_parameter(list(Utils.unpack_iterable(values))), token="in", exact=exact) token.writ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_facets(self, facets, start=0, page_size=None): """ Query the facets results for this query using the specified list of facets with the given start and pag...
if len(facets) == 0: raise ValueError("Facets must contain at least one entry", "facets") str_query = self.__str__() facet_query = FacetQuery(str_query, None, facets, start, page_size, query_parameters=self.query_parameters, wait_for_non_stale_resul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def show_G_distribution(data): '''Show the distribution of the G function.''' Xs, t = fitting.preprocess_data(data) Theta, Phi = np.meshgrid(np.linspace(0, np.pi, 50), np.linspace(0, 2 * np.pi, 50)) G = [] for i in range(len(Theta)): G.append([]) for j in range(len(Theta[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 show_fit(w_fit, C_fit, r_fit, Xs): '''Plot the fitting given the fitted axis direction, the fitted center, the fitted radius and the data points. ''' fig = plt.figure() ax = fig.gca(projection='3d') # Plot the data points ax.scatter([X[0] for X in Xs], [X[1] for X in Xs], [X[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 find_window(self, highlight_locations): """Getting the HIGHLIGHT_NUM_CHARS_BEFORE_MATCH setting to find how many characters before the first word found shoul...
if len(self.text_block) <= self.max_length: return (0, self.max_length) num_chars_before = getattr( settings, 'HIGHLIGHT_NUM_CHARS_BEFORE_MATCH', 0 ) best_start, best_end = super(ColabHighlighter, self).find_window( highligh...
<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): """ Try to login and set the internal session id. Please note: - Any failed login resets all existing session ids, even of other users. - SIDs e...
response = self.session.get(self.base_url + '/login_sid.lua', timeout=10) xml = ET.fromstring(response.text) if xml.find('SID').text == "0000000000000000": challenge = xml.find('Challenge').text url = self.base_url + "/login_sid.lua" response = self.session.g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_response(self, challenge, password): """Calculate response for the challenge-response authentication"""
to_hash = (challenge + "-" + password).encode("UTF-16LE") hashed = hashlib.md5(to_hash).hexdigest() return "{0}-{1}".format(challenge, hashed)
<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_actors(self): """ Returns a list of Actor objects for querying SmartHome devices. This is currently the only working method for getting temperature data....
devices = self.homeautoswitch("getdevicelistinfos") xml = ET.fromstring(devices) actors = [] for device in xml.findall('device'): actors.append(Actor(fritzbox=self, device=device)) return actors
<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_actor_by_ain(self, ain): """ Return a actor identified by it's ain or return None """
for actor in self.get_actors(): if actor.actor_id == ain: return actor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def homeautoswitch(self, cmd, ain=None, param=None): """ Call a switch method. Should only be used by internal library functions. """
assert self.sid, "Not logged in" params = { 'switchcmd': cmd, 'sid': self.sid, } if param is not None: params['param'] = param if ain: params['ain'] = ain url = self.base_url + '/webservices/homeautoswitch.lua' res...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_switch_actors(self): """ Get information about all actors This needs 1+(5n) requests where n = number of actors registered Deprecated, use get_actors ins...
actors = {} for ain in self.homeautoswitch("getswitchlist").split(','): actors[ain] = { 'name': self.homeautoswitch("getswitchname", ain), 'state': bool(self.homeautoswitch("getswitchstate", ain)), 'present': bool(self.homeautoswitch("getswitc...
<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_devices(self): """ Return a list of devices. Deprecated, use get_actors instead. """
url = self.base_url + '/net/home_auto_query.lua' response = self.session.get(url, params={ 'sid': self.sid, 'command': 'AllOutletStates', 'xhr': 0, }, timeout=15) response.raise_for_status() data = response.json() count = int(data["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 get_consumption(self, deviceid, timerange="10"): """ Return all available energy consumption data for the device. You need to divice watt_values by 100 and v...
tranges = ("10", "24h", "month", "year") if timerange not in tranges: raise ValueError( "Unknown timerange. Possible values are: {0}".format(tranges) ) url = self.base_url + "/net/home_auto_query.lua" response = self.session.get(url, params={ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_logs(self): """ Return the system logs since the last reboot. """
assert BeautifulSoup, "Please install bs4 to use this method" url = self.base_url + "/system/syslog.lua" response = self.session.get(url, params={ 'sid': self.sid, 'stylemode': 'print', }, timeout=15) response.raise_for_status() entries = [] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def seen_nonce(id, nonce, timestamp): """ Returns True if the Hawk nonce has been seen already. """
key = '{id}:{n}:{ts}'.format(id=id, n=nonce, ts=timestamp) if cache.get(key): log.warning('replay attack? already processed nonce {k}' .format(k=key)) return True else: log.debug('caching nonce {k}'.format(k=key)) cache.set(key, 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 cli(context, host, username, password): """ FritzBox SmartHome Tool \b Provides the following functions: - A easy to use library for querying SmartHome actor...
context.obj = FritzBox(host, username, password)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def actors(context): """Display a list of actors"""
fritz = context.obj fritz.login() for actor in fritz.get_actors(): click.echo("{} ({} {}; AIN {} )".format( actor.name, actor.manufacturer, actor.productname, actor.actor_id, )) if actor.has_temperature: click.echo("Temp: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch_on(context, ain): """Switch an actor's power to ON"""
context.obj.login() actor = context.obj.get_actor_by_ain(ain) if actor: click.echo("Switching {} on".format(actor.name)) actor.switch_on() else: click.echo("Actor not found: {}".format(ain))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch_state(context, ain): """Get an actor's power state"""
context.obj.login() actor = context.obj.get_actor_by_ain(ain) if actor: click.echo("State for {} is: {}".format(ain,'ON' if actor.get_state() else 'OFF')) else: click.echo("Actor not found: {}".format(ain))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch_toggle(context, ain): """Toggle an actor's power state"""
context.obj.login() actor = context.obj.get_actor_by_ain(ain) if actor: if actor.get_state(): actor.switch_off() click.echo("State for {} is now OFF".format(ain)) else: actor.switch_on() click.echo("State for {} is now ON".format(ain)) els...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logs(context, format): """Show system logs since last reboot"""
fritz = context.obj fritz.login() messages = fritz.get_logs() if format == "plain": for msg in messages: merged = "{} {} {}".format(msg.date, msg.time, msg.message.encode("UTF-8")) click.echo(merged) if format == "json": entries = [msg._asdict() for msg in ...
<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_temperature(self, temp): """ Sets the temperature in celcius """
# Temperature is send to fritz.box a little weird param = 16 + ( ( temp - 8 ) * 2 ) if param < 16: param = 253 logger.info("Actor " + self.name + ": Temperature control set to off") elif param >= 56: param = 254 logger.info("Actor " + 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_builder_openshift_url(self): """ url of OpenShift where builder will connect """
key = "builder_openshift_url" url = self._get_deprecated(key, self.conf_section, key) if url is None: logger.warning("%r not found, falling back to get_openshift_base_uri()", key) url = self.get_openshift_base_uri() 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 load(self): """ Extract tabular data as |TableData| instances from a CSV file. |load_source_desc_file| :return: Loaded table data. |load_table_name_desc| ===...
self._validate() self._logger.logging_load() self.encoding = get_file_encoding(self.source, self.encoding) if six.PY3: self._csv_reader = csv.reader( io.open(self.source, "r", encoding=self.encoding), delimiter=self.delimiter, ...
<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(self): """ Extract tabular data as |TableData| instances from a CSV text object. |load_source_desc_text| :return: Loaded table data. |load_table_name_de...
self._validate() self._logger.logging_load() self._csv_reader = csv.reader( six.StringIO(self.source.strip()), delimiter=self.delimiter, quotechar=self.quotechar, strict=True, skipinitialspace=True, ) formatter = CsvT...
<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_params(self, **kwargs): """ set parameters according to specification these parameters are accepted: :param pulp_secret: str, resource name of pulp secre...
# Here we cater to the koji "scratch" build type, this will disable # all plugins that might cause importing of data to koji self.scratch = kwargs.pop('scratch', False) # When true, it indicates build was automatically started by # OpenShift via a trigger, for instance ImageCha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_ist_trigger(self): """Return True if this BuildConfig has ImageStreamTag trigger."""
triggers = self.template['spec'].get('triggers', []) if not triggers: return False for trigger in triggers: if trigger['type'] == 'ImageChange' and \ trigger['imageChange']['from']['kind'] == 'ImageStreamTag': return True retur...
<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_secret_for_plugin(self, secret, plugin=None, mount_path=None): """ Sets secret for plugin, if no plugin specified it will also set general secret :param ...
has_plugin_conf = False if plugin is not None: has_plugin_conf = self.dj.dock_json_has_plugin_conf(plugin[0], plugin[1]) if 'secrets' in self.template['spec']['strategy']['customStrategy']: if not plugin or ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust_for_triggers(self): """Remove trigger-related plugins when needed If there are no triggers defined, it's assumed the feature is disabled and all trigg...
triggers = self.template['spec'].get('triggers', []) remove_plugins = [ ("prebuild_plugins", "check_and_set_rebuild"), ("prebuild_plugins", "stop_autorebuild_if_disabled"), ] should_remove = False if triggers and (self.is_custom_base_image() or self.is_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust_for_custom_base_image(self): """ Disable plugins to handle builds depending on whether or not this is a build from a custom base image. """
plugins = [] if self.is_custom_base_image(): # Plugins irrelevant to building base images. plugins.append(("prebuild_plugins", "pull_base_image")) plugins.append(("prebuild_plugins", "koji_parent")) plugins.append(("prebuild_plugins", "inject_parent_image...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_koji(self): """ if there is yum repo specified, don't pick stuff from koji """
phase = 'prebuild_plugins' plugin = 'koji' if not self.dj.dock_json_has_plugin_conf(phase, plugin): return if self.spec.yum_repourls.value: logger.info("removing koji from request " "because there is yum repo specified") 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 render_sendmail(self): """ if we have smtp_host and smtp_from, configure sendmail plugin, else remove it """
phase = 'exit_plugins' plugin = 'sendmail' if not self.dj.dock_json_has_plugin_conf(phase, plugin): return if self.spec.smtp_host.value and self.spec.smtp_from.value: self.dj.dock_json_set_arg(phase, plugin, 'url', self.spec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_fetch_maven_artifacts(self): """Configure fetch_maven_artifacts plugin"""
phase = 'prebuild_plugins' plugin = 'fetch_maven_artifacts' if not self.dj.dock_json_has_plugin_conf(phase, plugin): return koji_hub = self.spec.kojihub.value koji_root = self.spec.kojiroot.value if not koji_hub and not koji_root: logger.info('R...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_pulp_pull(self): """ If a pulp registry is specified, use pulp_pull plugin """
# pulp_pull is a multi-phase plugin phases = ('postbuild_plugins', 'exit_plugins') plugin = 'pulp_pull' for phase in phases: if not self.dj.dock_json_has_plugin_conf(phase, plugin): continue pulp_registry = self.spec.pulp_registry.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 render_pulp_sync(self): """ If a pulp registry is specified, use the pulp plugin as well as the delete_from_registry to delete the image after sync """
if not self.dj.dock_json_has_plugin_conf('postbuild_plugins', 'pulp_sync'): return pulp_registry = self.spec.pulp_registry.value # Find which registry to use docker_registry = None registry_secret = None regi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_pulp_tag(self): """ Configure the pulp_tag plugin. """
if not self.dj.dock_json_has_plugin_conf('postbuild_plugins', 'pulp_tag'): return pulp_registry = self.spec.pulp_registry.value if pulp_registry: self.dj.dock_json_set_arg('postbuild_plugins', 'pulp_tag', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_group_manifests(self): """ Configure the group_manifests plugin. Group is always set to false for now. """
if not self.dj.dock_json_has_plugin_conf('postbuild_plugins', 'group_manifests'): return push_conf = self.dj.dock_json_get_plugin_conf('postbuild_plugins', 'group_manifests') args = push_conf.setdefault('args', {}) # mod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_customizations(self): """ Customize prod_inner for site specific customizations """
disable_plugins = self.customize_conf.get('disable_plugins', []) if not disable_plugins: logger.debug("No site-specific plugins to disable") else: for plugin_dict in disable_plugins: try: self.dj.remove_plugin( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_json_capture(osbs, os_conf, capture_dir): """ Only used for setting up the testing framework. """
try: os.mkdir(capture_dir) except OSError: pass finally: osbs.os._con.request = ResponseSaver(capture_dir, os_conf.get_openshift_api_uri(), os_conf.get_k8s_api_uri(), ...