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 contribute_to_class(self, cls, name): """ Makes sure thumbnail gets set when image field initialized. """
super(SizedImageField, self).contribute_to_class(cls, name) signals.post_init.connect(self._set_thumbnail, sender=cls)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pre_save(self, model_instance, add): """ Resizes, commits image to storage, and returns field's value just before saving. """
file = getattr(model_instance, self.attname) if file and not file._committed: file.name = self._clean_file_name(model_instance, file.name) file.file = self._resize_image(model_instance, file) file.save(file.name, file, save=False) return file
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clean_file_name(self, model_instance, filename): """ We need to make sure we know the full file name before we save the thumbnail so we can be sure the name...
available_name = self.storage.get_available_name( self.generate_filename(model_instance, filename)) return os.path.basename(available_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 _create_thumbnail(self, model_instance, thumbnail, image_name): """ Resizes and saves the thumbnail image """
thumbnail = self._do_resize(thumbnail, self.thumbnail_size) full_image_name = self.generate_filename(model_instance, image_name) thumbnail_filename = _get_thumbnail_filename(full_image_name) thumb = self._get_simple_uploaded_file(thumbnail, thumbnail_filename) self.storage.save(...
<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_thumbnail(self, instance=None, **kwargs): """ Sets a `thumbnail` attribute on the image field class. On thumbnail you can access name, url, path attribu...
image_field = getattr(instance, self.name) if image_field: thumbnail_filename = _get_thumbnail_filename(image_field.name) thumbnail_field = ThumbnailField(thumbnail_filename, self.storage) setattr(image_field, 'thumbnail', thumbnail_field)
<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(self, **kwargs): """Create a new Application. Args: **kwargs: Arbitrary keyword arguments, including: name (str): A name for the new Application. Ret...
resource = self.resource.create(kwargs) if 'admin_token' in kwargs: resource.context.authorize('Gem-Application', api_token=resource.api_token, admin_token=kwargs['admin_token']) app = self.wrap(resource) ...
<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_mfa(self): """Return the currently-valid MFA token for this application."""
token = str(self.totp.now()) # PyOTP doesn't pre-pad tokens shorter than 6 characters # ROTP does, so we have to. while len(token) < 6: token = '0{}'.format(token) return 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 reset(self, *args): """Resets any of the tokens for this Application. Note that you may have to reauthenticate afterwards. Usage: application.reset('api_toke...
self.resource = self.resource.reset(list(args)) 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 get_users(self, fetch=True): """Return this Applications's users object, populating it if fetch is True."""
return Users(self.resource.users, self.client, populate=fetch)
<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_wallets(self, fetch=False): """Return this Applications's wallets object, populating it if fetch is True."""
return Wallets( self.resource.wallets, self.client, populate=fetch, application=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 get_netki_domains(self, fetch=False): """Return the Applications NetkiDomains object, populating it if fetch is True."""
return NetkiDomains( self.resource.netki_domains, self.client, populate=fetch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def os_info(): """Returns os data. """
return { 'uname': dict(platform.uname()._asdict()), 'path': os.environ.get('PATH', '').split(':'), 'shell': os.environ.get('SHELL', '/bin/sh'), }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def network_info(): """Returns hostname, ipv4 and ipv6. """
def extract(host, family): return socket.getaddrinfo(host, None, family)[0][4][0] host = socket.gethostname() response = { 'hostname': host, 'ipv4': None, 'ipv6': None } with suppress(IndexError, socket.gaierror): response['ipv4'] = extract(host, socket.AF_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 mac_addr_info(): """Returns mac address. """
mac = get_mac() if mac == get_mac(): # not random generated hexa = '%012x' % mac value = ':'.join(hexa[i:i+2] for i in range(0, 12, 2)) else: value = None return {'mac': 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 interfaces_info(): """Returns interfaces data. """
def replace(value): if value == netifaces.AF_LINK: return 'link' if value == netifaces.AF_INET: return 'ipv4' if value == netifaces.AF_INET6: return 'ipv6' return value results = {} for iface in netifaces.interfaces(): addrs = net...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gateways_info(): """Returns gateways data. """
data = netifaces.gateways() results = {'default': {}} with suppress(KeyError): results['ipv4'] = data[netifaces.AF_INET] results['default']['ipv4'] = data['default'][netifaces.AF_INET] with suppress(KeyError): results['ipv6'] = data[netifaces.AF_INET6] results['default'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memory_data(): """Returns memory data. """
vm = psutil.virtual_memory() sw = psutil.swap_memory() return { 'virtual': { 'total': mark(vm.total, 'bytes'), 'free': mark(vm.free, 'bytes'), 'percent': mark(vm.percent, 'percentage') }, 'swap': { 'total': mark(sw.total, 'bytes'), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def devices_data(): """Returns devices data. """
response = {} for part in psutil.disk_partitions(): device = part.device response[device] = { 'device': device, 'mountpoint': part.mountpoint, 'fstype': part.fstype, 'opts': part.opts, } if part.mountpoint: usage = psut...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def integrator(integrand,xmin,xmax,n_points,factor=2): ''' Creating theoretical curve for 2D model functions integrator function ''' integral_vector = np.empty([n_points+1]) dx = (xmax-xmin)/n_points # integrate for i in xrange(n_points+1): xnow = xmin + i * dx integral,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rotate(f,x,theta=0): ''' Returns a function that takes as input the 1D vector along the angle given a function that takes in 2D input ''' f_R = lambda b: f(np.array([[x*np.cos(theta)-b*np.sin(theta)], [x*np.sin(theta)+b*np.cos(theta)]])) return f_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 check_failed_login(self): """ 'Private method', check failed logins, it's used for wath_login decorator """
last_attempt = self.get_last_failed_access_attempt() if not last_attempt: # create a new entry user_access = self._FailedAccessAttemptModel(ip_address=self.ip) elif last_attempt: user_access = last_attempt if self.request.method == 'POST': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optional_data_directories(self): """ Data directories entries are somewhat wierd. First of all they have no direct type information in it, the type is assume...
base_offset = self.pe_header_offset +\ COFF_Header.get_size() +\ OptionalHeader_StandardFields.get_size() +\ OptionalHeader_WindowsFields.get_size() for i in range(0, self.optional_windows_fields.NumberOfRvaAndSizes): offset = base_offset + i*OptionalHea...
<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_rva(self, rva): """ RVAs are supposed to be used with the image of the file in memory. There's no direct algorithm to calculate the offset of an RVA ...
containing_section = self.get_section_of_rva(rva) in_section_offset = containing_section.PointerToRawData -\ containing_section.VirtualAddress return in_section_offset + rva
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dir_import_table(self): """ import table is terminated by a all-null entry, so we have to check for that """
import_header = list(self.optional_data_directories)[1] import_offset = self.resolve_rva(import_header.VirtualAddress) i = 0 while True: offset = import_offset + i*Import_DirectoryTable.get_size() idt = Import_DirectoryTable(self.stream, offset, 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 get_number(message, limit=4): """ convert Chinese to pinyin and extract useful numbers attention: 1. only for integer 2. before apply this method, the messag...
words = pinyin.get_pinyin(message).split('-') numbers = [] tmp = '' count = 0 for w in words: if re.search(r'\W', w, re.A): for s in list(w): if s in special_char.keys(): count += 1 tmp += special_char[s] el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def evalMetric(self, x, method=None): '''Evaluates the density matching metric at a given design point. :param iterable x: values of the design variables, this is passed as the first argument to the function fqoi :return: metric_value - value of the metric evaluated at the design ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getPDF(self): '''Function that gets vectors of the pdf and target at the last design evaluated. :return: tuple of q values, pdf values, target values ''' if hasattr(self, '_qplot'): return self._qplot, self._hplot, self._tplot else: raise 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 errorBand(x, yAvg, yStd, yDensity, plt, n_colors=None): """ plot error-band around avg where colour equals to point density """
dmn = yDensity.min() dmx = yDensity.max() if n_colors is None: n_colors = dmx - dmn + 1 print(n_colors) cm = plt.cm.get_cmap('Blues', lut=n_colors) # normalize (0...1): relDensity = (yDensity - dmn) / (dmx - dmn) # limit the number of densities to n_colors: bins = np.lins...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPage(url, contextFactory=None, *args, **kwargs): """Download a web page as a string. Download a page. Return a deferred, which will callback with a page (...
scheme, host, port, path = client._parse(url) factory = client.HTTPClientFactory(url, *args, **kwargs) if scheme == 'https': if contextFactory is None: raise RuntimeError, 'must provide a contextFactory' conn = reactor.connectSSL(host, port, factory, contextFactory) 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 Send(self, url, opname, pyobj, nsdict={}, soapaction=None, chain=None, **kw): """Returns a ProcessingChain which needs to be passed to Receive if Send is bei...
url = url or self.url cookies = None if chain is not None: cookies = chain.flow.cookies d = {} d.update(self.nsdict) d.update(nsdict) if soapaction is not None: self.addHTTPHeader('SOAPAction', soapaction) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def stream_array(self, generator): '''Helper function to stream content as an array of JSON values.''' def chunkify(generator): log.debug('Data Stream STARTED') yield '['.encode() # In order to have commas only after the first value, we take the # first va...
<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_500(self, request, exception): '''Internal server error.''' id_ = str(uuid.uuid4())[:6].upper() msg = 'Internal server error: 500. Unique error identifier is {}' msg = msg.format(id_) log.error('HTTP 500 [Message - {}]: {}'.format(id_, msg)) log.error('HTTP 50...
<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(self, name, network): """Create a new Account object and add it to this Accounts collection. Args: name (str): Account name network (str): Type of c...
if not network in SUPPORTED_NETWORKS: raise ValueError('Network not valid!') account = self.wrap(self.resource.create(dict(name=name, network=network))) self.add(account) return account
<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, **kwargs): """Update the Account resource with specified content. Args: name (str): Human-readable name for the account Returns: the updated Ac...
return self.__class__(self.resource.update(kwargs), self.client, wallet=self.wallet)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pay(self, payees, change_account=None, utxo_confirmations=6, mfa_token=None, redirect_uri=None): """Create, verify, and sign a new Transaction. If this Accou...
# Check that wallet is unlocked if self.wallet.is_locked(): raise DecryptionError("This wallet must be unlocked with " "wallet.unlock(passphrase)") # First create the unsigned tx. content = dict(payees=payees, utxo_co...
<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_addresses(self, fetch=False): """Return the Account's addresses object, populating it if fetch is True."""
return Addresses(self.resource.addresses, self.client, populate=fetch)
<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_netki_names(self, fetch=False): """Return the Account's NetkiNames object, populating it if fetch is True."""
return NetkiNames(self.resource.netki_names, self.client, populate=fetch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def truncate_html(html, *args, **kwargs): """Truncates HTML string. :param html: The HTML string or parsed element tree (with :func:`html5lib.parse`). :param kwa...
if hasattr(html, 'getchildren'): etree = html else: etree = html5lib.parse(html) walker = html5lib.getTreeWalker('etree') stream = walker(etree) stream = TruncationFilter(stream, *args, **kwargs) serializer = html5lib.serializer.HTMLSerializer() serialized = serializer.se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_allowed(func): """Check user password, when is correct, then run decorated function. :returns: decorated function """
@wraps(func) def _is_allowed(user, *args, **kwargs): password = kwargs.pop('password', None) if user.check_password(password): return func(user, *args, **kwargs) else: raise NotAllowedError() # add password parameter to function signature sig = inspect.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 do_get(self, args): '''Get labels directly connected to a content item.''' for label in self.label_store.directly_connected(args.content_id): if args.value is None or label.value.value == args.value: self.stdout.write('{0}\n'.format(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 do_connected(self, args): '''Find a connected component from positive labels on an item.''' connected = self.label_store.connected_component(args.content_id) for label in connected: self.stdout.write('{0}\n'.format(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 wait(self): """Waits for all submitted jobs to complete."""
logging.info("waiting for {} jobs to complete".format(len(self.submissions))) while not self.shutdown: time.sleep(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_dropped_files(self, sha256, environment_id, target_dir): """Downloads the dropped files for this sample into target_dir. Returns the list of files e...
download_url = '{}/api/sample-dropped-files/{}?environmentId={}&apikey={}&secret={}'.format( self.url, sha256, environment_id, self.api_key, self.secret) with warnings.catch_warnings(): warnings.simplefilter("ignore") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_memory_dump(self, sha256, environment_id, dest_dir): """Downloads the given memory dump into the given directory. Returns a tuple of a list of files...
dest_path = os.path.join(dest_dir, 'memory.zip') if self.download(sha256, environment_id, VXSTREAM_DOWNLOAD_MEMORY, dest_path) is None: return None with open(dest_path, 'rb') as fp: blob = fp.read(1024) if b'No dump files available' in blob: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def data(self): '''email content for this message''' # return data after any initial offset, plus content offset to # skip header, up to the size of this message return self.mmap[self.content_offset + self._offset: self._offset + self.size]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self, props=None, value=None): """ Copy the Overlay possibly overriding props. """
return Overlay(self.text, (self.start, self.end), props=props or self.props, value=value or self.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 match(self, props=None, rng=None, offset=None): """ Provide any of the args and match or dont. :param props: Should be a subset of my props. :param rng: Exac...
if rng: s, e = rng else: e = s = None return ((e is None or self.end == e) and (s is None or self.start == s)) and \ (props is None or props.issubset(self.props)) and \ (offset is None or self.start >= offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overlays_at(self, key): """ Key may be a slice or a point. """
if isinstance(key, slice): s, e, _ = key.indices(len(self.text)) else: s = e = key return [o for o in self.overlays if o.start in Rng(s, e)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overlay(self, matchers, force=False): """ Given a list of matchers create overlays based on them. Normally I will remember what overlays were run this way an...
for m in matchers: if m in self._ran_matchers: continue self._ran_matchers.append(m) self.overlays += list(m.offset_overlays(self)) self.overlays.sort(key=lambda o: o.start, reverse=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 evil(expr, lookup, operators, cast, reducer, tokenizer): """evil evaluates an expression according to the eval description given. :param expr: An expression ...
operators = OrderedDict((op[0], op[1:]) for op in operators) if "(" in operators or ")" in operators: raise ValueError("( and ) are reserved operators") operator_tokens = ["(", ")"] + operators.keys() tokens = iter(tokenizer(expr, operator_tokens)) levels = [[]] while 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 op(token, func, left=False, right=False): """op provides a more verbose syntax for declaring operators. :param token: The string token of the operator. Usual...
both = (left == right) return (token, func, OP_BOTH if both else OP_LEFT if left else OP_RIGHT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def globlookup(pattern, root): """globlookup finds filesystem objects whose relative path matches the given pattern. :param pattern: The pattern to wish to match...
for subdir, dirnames, filenames in os.walk(root): d = subdir[len(root) + 1:] files = (os.path.join(d, f) for f in filenames) for f in fnmatch.filter(files, pattern): yield f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_get(self, req, resp, rid, related): """ Find the related model & serialize it back If the parent resource of the related model doesn't exist then abort on...
signals.pre_req.send(self.model) signals.pre_req_find.send(self.model) if not hasattr(self.model, related): abort(InvalidURL(**{ 'detail': 'The "%s" resource does not have a related ' 'resource named "%s". This is an error, check ' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recv_data(self): """ Grab the next frame and put it on the matrix. """
data, addr = self.sock.recvfrom(self.packetsize) matrix = map(ord, data.strip()) if len(matrix) == self.packetsize: self.matrix = matrix[:-4]
<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): """ Generate the output from the matrix. """
pixels = len(self.matrix) for x in range(self.width): for y in range(self.height): pixel = y * self.width * 3 + x * 3 #TODO: sometimes the matrix is not as big as it should if pixel < pixels: pygame.draw.circle(self.screen,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gameloop(self): """ Loop through all the necessary stuff and end execution when Ctrl+C was hit. """
try: while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.eve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getname(obj): """ Return the most qualified name of an object :param obj: object to fetch name :return: name of ``obj`` """
for name_attribute in ('__qualname__', '__name__'): try: # an object always has a class, as per Python data model return getattr(obj, name_attribute, getattr(obj.__class__, name_attribute)) except AttributeError: pass raise TypeError('object of type %r does 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 wraplet(cls, *cls_args, **cls_kwargs): """ Create a factory to produce a Wrapper from a slave factory :param cls_args: positional arguments to provide to the...
if cls.__init_slave__ in (None, WrapperMixin.__init_slave__): raise TypeError('type %r does not implement the wraplet protocol' % getname(cls)) def wrapper_factory(slave_factory): """Factory to create a new class by wrapping ``slave_factory``""" class Wraplet(cls): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self, request): """ Returns a `User` if a correct username and password have been supplied using HTTP Basic authentication. Otherwise returns `N...
auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'basic': return None if len(auth) == 1: msg = _('Invalid basic header. No credentials provided.') raise exceptions.AuthenticationFailed(msg) elif len(auth) > 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 authenticate_credentials(self, userid, password): """ Authenticate the userid and password against username and password. """
credentials = { get_user_model().USERNAME_FIELD: userid, 'password': password } user = authenticate(**credentials) if user is None: raise exceptions.AuthenticationFailed(_('Invalid username/password.')) if not user.is_active: 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 enforce_csrf(self, request): """ Enforce CSRF validation for session based authentication. """
reason = CSRFCheck().process_view(request, None, (), {}) if reason: # CSRF failed, bail with explicit error message raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_enum(pred, enum): """ Create a new enumeration containing only items filtered from another enumeration. Hidden enum items in the original enumeration ...
def _items(): for item in enum: yield EnumItem( item.value, item.desc, not pred(item), **item._extra) return Enum('Filtered from {!r}'.format(enum), list(_items()))
<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_pairs(cls, doc, pairs): """ Construct an enumeration from an iterable of pairs. :param doc: See `Enum.__init__`. :type pairs: ``Iterable[Tuple[unicode, ...
values = (EnumItem(value, desc) for value, desc in pairs) return cls(doc=doc, values=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(self, value): """ Get an enumeration item for an enumeration value. :param unicode value: Enumeration value. :raise InvalidEnumItem: If ``value`` does no...
_nothing = object() item = self._values.get(value, _nothing) if item is _nothing: raise InvalidEnumItem(value) return item
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extra(self, value, extra_name, default=None): """ Get the additional enumeration value for ``extra_name``. :param unicode value: Enumeration value. :param st...
try: return self.get(value).get(extra_name, default) except InvalidEnumItem: return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_all(self, **names): """ Find all items with matching extra values. :param \*\*names: Extra values to match. :rtype: ``Iterable[`EnumItem`]`` """
values = names.items() if len(values) != 1: raise ValueError('Only one query is allowed at a time') name, value = values[0] for item in self: if item.get(name) == value: yield item
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand_args(cmd_args): """split command args to args list returns a list of args :param cmd_args: command args, can be tuple, list or str """
if isinstance(cmd_args, (tuple, list)): args_list = list(cmd_args) else: args_list = shlex.split(cmd_args) return args_list
<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_service(station: str) -> Service: """ Returns the preferred service for a given station """
for prefix in PREFERRED: if station.startswith(prefix): return PREFERRED[prefix] # type: ignore return NOAA
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_err(self, body: str, key: str = 'report path') -> InvalidRequest: """ Returns an InvalidRequest exception with formatted error message """
msg = f'Could not find {key} in {self.__class__.__name__} response\n' return InvalidRequest(msg + body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch(self, station: str) -> str: """ Fetches a report string from the service """
valid_station(station) try: resp = getattr(requests, self.method.lower())(self.url.format(self.rtype, station)) if resp.status_code != 200: raise SourceError(f'{self.__class__.__name__} server returned {resp.status_code}') except requests.exceptions.Conne...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract(self, raw: str, station: str = None) -> str: """ Extracts the raw_report element from XML response """
resp = parsexml(raw) try: report = resp['response']['data'][self.rtype.upper()] except KeyError: raise self.make_err(raw) # Find report string if isinstance(report, dict): report = report['raw_text'] elif isinstance(report, list) and 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 _extract(self, raw: str, station: str = None) -> str: """ Extracts the report message from XML response """
resp = parsexml(raw) try: report = resp['response']['body']['items']['item'][self.rtype.lower() + 'Msg'] except KeyError: raise self.make_err(raw) # Replace line breaks report = report.replace('\n', '') # Remove excess leading and trailing 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 _extract(self, raw: str, station: str) -> str: # type: ignore """ Extracts the reports message using string finding """
report = raw[raw.find(station.upper() + ' '):] report = report[:report.find(' =')] return 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 set_weather_from_metar( metar: typing.Union[Metar.Metar, str], in_file: typing.Union[str, Path], out_file: typing.Union[str, Path] = None ) -> typing.Tuple[ty...
error, metar = custom_metar.CustomMetar.get_metar(metar) if error: return error, None if metar: LOGGER.debug('METAR: %s', metar.code) in_file = elib.path.ensure_file(in_file) if out_file is None: out_file = in_file else: out_file = elib.path.ensure_file(out_f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pull_schedule_loop(self): """ Called every 16 minutes to pull a new version of the schedule """
try: self.pull_schedule() delay = 16*60 except ScheduleError, e: self.l.exception("ScheduleError while pulling schedule. "+ "Retrying in 5m") delay = 5*60 if not self.running: return self.scheduler...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jiggle_source_code(self): # type: () ->int """ Updates version of central package """
changed = 0 for file_name in self.file_inventory.source_files: to_write = [] # self.create_missing(file_name, file_name) if not os.path.isfile(file_name): continue all_source = self.file_opener.read_this(file_name) if "__versi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jiggle_config_file(self): # type: () ->int """ Update ini, cfg, conf """
changed = 0 # setup.py related. setup.py itself should read __init__.py or __version__.py other_files = ["setup.cfg"] for file_name in other_files: filepath = os.path.join(self.SRC, file_name) # only create setup.cfg if we have setup.py 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 _getConfiguration(self): """ Load application configuration files. :return: <dict> """
configDirectoryPath = os.path.join("application", "config") config = Config(configDirectoryPath) configData = config.getData() # setting application parameters reactor.suggestThreadPoolSize( int(configData["performance"]["threadPoolSize"]) ) 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 _getInterfaces(self): """ Load application communication interfaces. :return: <dict> """
interfaces = {} interfacesPath = os.path.join("application", "interface") interfaceList = os.listdir(interfacesPath) for file in interfaceList: interfaceDirectoryPath = os.path.join(interfacesPath, file) if not os.path.isdir(interfaceDirectoryPath) or file.star...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getModules(self): """ Import and load application modules. :return: <dict> """
modules = {} modulesPath = os.path.join("application", "module") moduleList = os.listdir(modulesPath) for moduleName in moduleList: modulePath = os.path.join(modulesPath, moduleName, "module.py") if not os.path.isfile(modulePath): continue ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addModel(self, moduleName, modelName, model): """ Add a model instance to the application model pool. :param moduleName: <str> module name in which the model...
modelIdentifier = "{}.{}".format(moduleName, modelName) if modelIdentifier not in self._models: self._models[modelIdentifier] = model else: message = "Application - addModel() - " \ "A model with the identifier {} already exists." \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getModel(self, modelIdentifier): """ Return the requested model. :param modelIdentifier: <str> model identifier :return: <object> model instance """
if modelIdentifier in self._models: return self._models[modelIdentifier] else: message = "Application - getModel() - " \ "Model with identifier {} does not exist." \ .format(modelIdentifier) raise Exception(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _loadViperServices(self): """ Load application bundled services. :return: <void> """
servicesPath = os.path.join( os.path.dirname(os.path.realpath(__file__)), "service" ) for serviceFile in os.listdir(servicesPath): if serviceFile.startswith("__") or serviceFile.startswith("."): continue serviceName = serviceFile....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addService(self, moduleName, serviceName, service): """ Add a service instance to the application service pool. :param moduleName: <str> module name in which...
serviceIdentifier = "{}.{}".format(moduleName, serviceName) if serviceIdentifier not in self._services: self._services[serviceIdentifier] = service else: message = "Application - addService() - " \ "A service with the identifier {} already exists." ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getService(self, serviceIdentifier): """ Return the requested service instance. :param serviceIdentifier: <str> service identifier :return: <object> service ...
if serviceIdentifier in self._services: return self._services[serviceIdentifier] else: message = "Application - getService() - " \ "Service with identifier {} does not exist." \ .format(serviceIdentifier) raise Exception(me...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, *number): """Adds all parameters interpreted as integers"""
return self._format_result(sum( # positional arguments are always strings [int(n) for n in number]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subtract(self, number1, number2): """Subtracts number2 from number1"""
return self._format_result(int(number1) - int(number2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def items(self): """Expose all grafts. """
accumulator = Accumulator() for graft in load_grafts(): accumulator.spawn(graft()) response = await accumulator.join() return response.items()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conf_merger(user_dict, variable): """ Merge global configuration with user's personal configuration. Global configuration has always higher priority. """
if variable not in globals().keys(): raise NameError("Unknown variable '%s'." % variable) if variable not in user_dict: return globals()[variable] return globals()[variable] and user_dict[variable]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def len(self, queue_name): """ Returns the length of the queue. :param queue_name: The name of the queue. Usually handled by the ``Gator`` instance. :type queue_...
try: stats = self.conn.stats_tube(queue_name) except beanstalkc.CommandFailed as err: if err[1] == 'NOT_FOUND': return 0 raise return stats.get('current-jobs-ready', 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 add_facets(engine_result, facet_features=None): '''Adds facets to search results. Construct a new result payload with `facets` added as a new top-level property that carries a mapping from unicode strings to lists of content_ids. The `facet_features` lists the names of :class:`~dossier.fc.Stri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def vectorizable_features(fcs): '''Discovers the ordered set of vectorizable features in ``fcs``. Returns a list of feature names, sorted lexicographically. Feature names are only included if the corresponding features are vectorizable (i.e., they are an instance of :class:`collections.Mapping`). ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dissimilarities(feature_names, fcs): '''Computes the pairwise dissimilarity matrices. This returns a dictionary mapping each name in ``feature_names`` to a pairwise dissimilarities matrix. The dissimilaritiy scores correspond to ``1 - kernel`` between each feature of each pair of feature collec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def probabilities(self): '''Trains a model and predicts recommendations. If the query feature collection could not be found or if there is insufficient training data, an empty list is returned. Otherwise, a list of content objects (tuples of content id and feature collection) 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 train(self, content_objs, idx_labels): '''Trains and returns a model using sklearn. If there are new labels to add, they can be added, returns an sklearn model which can be used for prediction and getting features. This method may return ``None`` if there is insufficient ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def noun_phrases_as_tokens(text): '''Generate a bag of lists of unnormalized tokens representing noun phrases from ``text``. This is built around python's nltk library for getting Noun Phrases (NPs). This is all documented in the NLTK Book http://www.nltk.org/book/ch03.html and blog posts that cite...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def noun_phrases(text, included_unnormalized=False): '''applies normalization to the terms found by noun_phrases_as_tokens and joins on '_'. :rtype: list of phrase strings with spaces replaced by ``_``. ''' lemmatizer = nltk.WordNetLemmatizer() stemmer = nltk.stem.porter.PorterStemmer() 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 _makeCertificate(key, email, _utcnow=datetime.utcnow): """Make the certificate for the client using the given key and e-mail address. """
# Create a certificate for this key. cert = X509() cert.set_pubkey(key) # Set the subject. subject = cert.get_subject() subject.CN = u"Crypto 101 Client" subject.emailAddress = email # Expiration dates. Mandatory. now = _utcnow() start = now.replace(hour=0, minute=0, second=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 makeCredentials(path, email): """Make credentials for the client from given e-mail address and store them in the directory at path. """
key = _generateKey() cert = _makeCertificate(key, email) certPath = path.child("client.pem") certPath.alwaysCreate = True with certPath.open("wb") as pemFile: pemFile.write(dump_privatekey(FILETYPE_PEM, key)) pemFile.write(dump_certificate(FILETYPE_PEM, cert))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getContextFactory(path): """Get a context factory for the client from keys already stored at path. Raises IOError if the credentials didn't exist. """
with path.child("client.pem").open() as pemFile: cert = PrivateCertificate.loadPEM(pemFile.read()) certOptions = cert.options() # TODO: verify server cert (see #1) certOptions.method = SSL.SSLv23_METHOD ctxFactory = SecureCiphersContextFactory(certOptions) return ctxFactory