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 parse_first_row(row, url_instance): """ Static method that parses a given table row element by executing `Parser.FIRST_ROW_XPATH` and scrapping torrent's id,...
tags = row.xpath(Parser.FIRST_ROW_XPATH) category_url = url_instance.combine(tags[0].get('href')) title = unicode(tags[1].text) # work with the incomplete URL to get str_id torrent_url = tags[1].get('href') str_id = torrent_url.split('details/')[1] str_id = str_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 parse_second_row(row, url): """ Static method that parses a given table row element by using helper methods `Parser.parse_category_subcategory_and_or_quality...
tags = row.findall('./td') category, subcategory, quality, language = Parser.parse_torrent_properties(tags[0]) user_info = tags[1].find('./a') user = user_info.text_content() user_url = url.combine(user_info.get('href')) # Two urls - one is spam, second is torrent 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 parse_torrent_properties(table_datas): """ Static method that parses a given list of table data elements and using helper methods `Parser.is_subcategory`, `P...
output = {'category': table_datas[0].text, 'subcategory': None, 'quality': None, 'language': None} for i in range(1, len(table_datas)): td = table_datas[i] url = td.get('href') params = Parser.get_params(url) if Parser.is_subcategory(params) and not outpu...
<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_torrent_link(table_data): """ Static method that parses list of table data, finds all anchor elements and gets the torrent url. However the torrent url...
anchors = table_data.findall('./a') link_tag = anchors[0] if len(anchors) < 2 else anchors[1] return link_tag.get('href')
<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, max_backoff=32, verbose=False, **kwargs): """Adding retries to requests.get with exponential backoff. Args: url (str): The URL to fetch max_backoff...
sleep_seconds = 1 while sleep_seconds <= max_backoff: try: # you may overwrite `timeout` via `kwargs` response = requests.get(url, **{**{'timeout': 30}, **kwargs}) # for 4xx, return instantly, no hope of success if 400 <= response.status_code < 500: ...
<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_image(self): """This code must be in its own method since the fetch functions need credits to be set. m2m fields are not yet set at the end of either the...
if not self.image: scrape_image(self) # If still no image then use first contributor image if not self.image: contributors = self.get_primary_contributors() if contributors: self.image = contributors[0].image self.save(set_im...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_api(app): """Configure API Endpoints. """
from heman.api.empowering import resources as empowering_resources from heman.api.cch import resources as cch_resources from heman.api.form import resources as form_resources from heman.api import ApiCatchall # Add Empowering resources for resource in empowering_resources: api.add_reso...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_login(app): """Configure login authentification Uses `Flask-Login <https://flask-login.readthedocs.org>`_ """
from heman.auth import login_manager, login login_manager.init_app(app) @app.teardown_request def force_logout(*args, **kwargs): login.logout_user()
<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_DragonDosBinary(self, data, strip_padding=True): """ Dragon DOS Binary Format http://dragon32.info/info/binformt.html Offset: Type: Value: 0 byte $55 Co...
data = bytearray(data) log.debug("Load Dragon DOS Binary Format.") meta_data = struct.unpack(">BBHHHB", data[:9]) machine_type = meta_data[0] if machine_type != 0x55: log.error("ERROR: Machine type wrong: is $%02X but should be $55!", machine_type) self.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 rotatePoint(x, y, rotationDegrees, pivotx=0, pivoty=0): """ Rotates the point at `x` and `y` by `rotationDegrees`. The point is rotated around the origin by ...
# Reuse the code in rotatePoints() return list(rotatePoints([(x, y)], rotationDegrees, pivotx, pivoty))[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 rotatePoints(points, rotationDegrees, pivotx=0, pivoty=0): """ Rotates each x and y tuple in `points`` by `rotationDegrees`. The points are rotated around th...
rotationRadians = math.radians(rotationDegrees % 360) for x, y in points: _checkForIntOrFloat(x) _checkForIntOrFloat(y) x -= pivotx y -= pivoty x, y = x * math.cos(rotationRadians) - y * math.sin(rotationRadians), x * math.sin(rotationRadians) + y * math.cos(rotationRa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def line(x1, y1, x2, y2, thickness=1, endcap=None, _skipFirst=False): """ Returns a generator that produces all of the points in a line between `x1`, `y1` and `x...
if (thickness != 1) or (endcap is not None): raise NotImplementedError('The pybresenham module is under development and the filled and thickness parameters are not implemented. You can contribute at https://github.com/asweigart/pybresenham') _checkForIntOrFloat(x1) _checkForIntOrFloat(y1) _ch...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def emit(self, record): """Store the message, not only the record."""
self.records.append(Record(levelno=record.levelno, levelname=record.levelname, message=self.format(record))) return super(SetupLogChecker, self).emit(record)
<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_generic_pos(self, *tokens): """Check if the different tokens were logged in one record, any level."""
for record in self.records: if all(token in record.message for token in tokens): return # didn't exit, all tokens are not present in the same record msgs = ["Tokens {} not found, all was logged is...".format(tokens)] for record in self.records: m...
<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_pos(self, level, *tokens): """Check if the different tokens were logged in one record, assert by level."""
for record in self.records: if all(record.levelno == level and token in record.message for token in tokens): return # didn't exit, all tokens are not present in the same record level_name = logging.getLevelName(level) msgs = ["Tokens {} not found in {}, all ...
<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_neg(self, level, *tokens): """Check that the different tokens were NOT logged in one record, assert by level."""
for record in self.records: if level is not None and record.levelno != level: continue if all(token in record.message for token in tokens): break else: return # didn't exit, all tokens found in the same record msg = "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 get_consumers(self, _Consumer, channel): """ | ConsumerMixin requirement. | Get the consumers list. :returns: All the consumers. :rtype: list. """
return [_Consumer(queues=[self.queue(channel)], callbacks=[self.main_callback], prefetch_count=self.prefetch_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 start(self, *args, **kwargs): #pylint:disable=unused-argument """ | Launch the consumer. | It can listen forever for messages or just wait for one. :param for...
forever = kwargs.get('forever', True) timeout = kwargs.get('timeout', None) if forever: return self.run(timeout=timeout) elif timeout: next((self.consume(timeout=timeout)), None) else: next((self.consume(limit=1, timeout=timeout)), 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 modelserializer_factory(model, serializer=None, fields=None, exclude=None): """ Returns a ModelSerializer containing fields for the given model. :param model...
# default values serializer = serializer or serializers.ModelSerializer attrs = {'model': model} if fields == '__all__': opts = model._meta.concrete_model._meta attrs['fields'] = [field.name for field in opts.fields if field.serialize] elif fields is not None: attrs['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 get_kube_path(): """Get the current config path. If the KUBECONFIG environment parameter is set, use it. If multiple paths are listed in KUBECONFIG, use the ...
try: path = pathlib.Path(os.environ["KUBECONFIG"].split(':')[0]) except KeyError: path = pathlib.Path.home().joinpath('.kube', 'config') return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self, create_if_not_found=True): """Open a kube config file. If the file does not exist, it creates a new file. """
try: self.data = self._read() # If the file does except FileNotFoundError as e: if create_if_not_found is True: self.data = {} else: raise e # Enforce the following keys exists in data. if 'clusters' not in 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 _read(self): """Read the kube config file. """
stream = self.path.read_text() data = yaml.load(stream) return 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 _write(self, data): """Write data to config file."""
stream = yaml.dump(data, default_flow_style=False) self.path.write_text(stream)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cluster_exists(self, name): """Check if a given cluster exists."""
clusters = self.data['clusters'] for cluster in clusters: if cluster['name'] == name: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cluster(self, name): """Get cluster from kubeconfig."""
clusters = self.data['clusters'] for cluster in clusters: if cluster['name'] == name: return cluster raise KubeConfError("Cluster name not found.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_clusters(self, names=False): """Print contexts."""
clusters = self.get_clusters() if names: clusters = [cluster['name'] for cluster in clusters] pprint.pprint(clusters)
<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_cluster( self, name, server=None, certificate_authority_data=None, **attrs): """Add a cluster to config."""
if self.cluster_exists(name): raise KubeConfError("Cluster with the given name already exists.") clusters = self.get_clusters() # Add parameters. new_cluster = {'name': name, 'cluster':{}} attrs_ = new_cluster['cluster'] if server is not 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 add_to_cluster(self, name, **attrs): """Add attributes to a cluster. """
cluster = self.get_cluster(name=name) attrs_ = cluster['cluster'] attrs_.update(**attrs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_from_cluster(self, name, *args): """Remove attributes from a cluster. """
cluster = self.get_cluster(name=name) attrs_ = cluster['cluster'] for a in args: del attrs_[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 remove_cluster(self, name): """Remove a cluster from kubeconfig. """
cluster = self.get_cluster(name) clusters = self.get_clusters() clusters.remove(cluster)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def user_exists(self, name): """Check if a given user exists."""
users = self.data['users'] for user in users: if user['name'] == name: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user(self, name): """Get user from kubeconfig."""
users = self.data['users'] for user in users: if user['name'] == name: return user raise KubeConfError("user name not found.")
<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_user( self, name, **attrs ): """Add a user to config."""
if self.user_exists(name): raise KubeConfError("user with the given name already exists.") users = self.get_users() # Add parameters. new_user = {'name': name, 'user':{}} attrs_ = new_user['user'] attrs_.update(attrs) users.append(new_user)
<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_to_user(self, name, **attrs): """Add attributes to a user. """
user = self.get_user(name=name) attrs_ = user['user'] attrs_.update(**attrs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_from_user(self, name, *args): """Remove attributes from a user. """
user = self.get_user(name=name) attrs_ = user['user'] for a in args: del attrs_[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 remove_user(self, name): """Remove a user from kubeconfig. """
user = self.get_user(name) users = self.get_users() users.remove(user)
<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_exec_to_user( self, name, env, command, args, **attrs ): """Add an exec option to your user."""
# Add exec option. exec_options = { 'command': command, 'env': env, 'args': args, } exec_options.update(attrs) # Add exec to user. self.add_to_user(name=name, exec=exec_options)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def context_exists(self, name): """Check if a given context exists."""
contexts = self.data['contexts'] for context in contexts: if context['name'] == name: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_context(self, name): """Get context from kubeconfig."""
contexts = self.data['contexts'] for context in contexts: if context['name'] == name: return context raise KubeConfError("context name not found.")
<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_context( self, name, cluster_name=None, user_name=None, namespace_name=None, **attrs ): """Add a context to config."""
if self.context_exists(name): raise KubeConfError("context with the given name already exists.") contexts = self.get_contexts() # Add parameters. new_context = {'name': name, 'context':{}} # Add attributes attrs_ = new_context['context'] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_to_context(self, name, **attrs): """Add attributes to a context. """
context = self.get_context(name=name) attrs_ = context['context'] attrs_.update(**attrs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_from_context(self, name, *args): """Remove attributes from a context. """
context = self.get_context(name=name) attrs_ = context['context'] for a in args: del attrs_[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 remove_context(self, name): """Remove a context from kubeconfig. """
context = self.get_context(name) contexts = self.get_contexts() contexts.remove(context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_current_context(self, name): """Set the current context in kubeconfig."""
if self.context_exists(name): self.data['current-context'] = name else: raise KubeConfError("Context does not exist.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_logging(self, verbosity_lvl=None, format='%(message)s'): """Switches on logging at a given level. :param verbosity_lvl: :param format: """
if not verbosity_lvl: verbosity_lvl = logging.INFO logging.basicConfig(format=format) self.logger.setLevel(verbosity_lvl)
<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_shell_command(self, command, pipe_it=True): """Runs the given shell command. :param command: :return: bool Status """
stdout = None if pipe_it: stdout = PIPE self.logger.debug('Executing shell command: %s' % command) return not bool(Popen(command, shell=True, stdout=stdout).wait())
<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_manage_command(self, command, venv_path, verbose=True): """Runs a given Django manage command in a given virtual environment. :param str command: :param ...
self.logger.debug('Running manage command `%s` for `%s` ...' % (command, venv_path)) self._run_shell_command( '. %s/bin/activate && python %s %s' % (venv_path, self._get_manage_py_path(), command), pipe_it=(not verbose))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def venv_install(self, package_name, venv_path): """Installs a given python package into a given virtual environment. :param str package_name: :param str venv_pa...
self.logger.debug('Installing `%s` into `%s` ...' % (package_name, venv_path)) self._run_shell_command('. %s/bin/activate && pip install -U %s' % (venv_path, package_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 make_venv(self, dj_version): """Creates a virtual environment for a given Django version. :param str dj_version: :rtype: str :return: path to created virtual...
venv_path = self._get_venv_path(dj_version) self.logger.info('Creating virtual environment for Django %s ...' % dj_version) try: create_venv(venv_path, **VENV_CREATE_KWARGS) except ValueError: self.logger.warning('Virtual environment directory already exists. Ski...
<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_apps_dir(self): """Creates an empty directory for symlinks to Django applications. :rtype: str :return: created directory path """
self.logger.info('Creating a directory for symlinks to your Django applications `%s` ...' % self.apps_path) try: os.mkdir(self.apps_path) except OSError: pass # Already exists. return self.apps_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 dispatch_op(self, op_name, args_dict): """Dispatches an operation requested. :param str op_name: :param dict args_dict: """
self.logger.debug('Requested `%s` command with `%s` args.' % (op_name, args_dict)) method = getattr(self, 'op_%s' % op_name, None) if method is None: error_str = '`%s` command is not supported.' % op_name self.logger.error(error_str) raise DjangoDevException(...
<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_venvs(self): """Returns a list of names of available virtual environments. :raises: DjangoDevException on errors :rtype: list :return: list of names """
def raise_(): error_str = 'Virtual environments are not created. Please run `bootstrap` command.' self.logger.error(error_str) raise DjangoDevException(error_str) if not os.path.exists(self.venvs_path): raise_() venvs = os.listdir(self.venvs_pat...
<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_apps(self, only=None): """Returns a list of names of available Django applications, Optionally filters it using `only`. :param list|None only: a list on ...
if not os.path.exists(self.apps_path): error_str = 'It seems that this directory does not contain django-dev project. ' \ 'Use `bootstrap` command to create project in the current directory.' self.logger.error(error_str) raise DjangoDevException(error...
<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_manage_py(self, apps): """Creates manage.py file, with a given list of installed apps. :param list apps: """
self.logger.debug('Creating manage.py ...') with open(self._get_manage_py_path(), mode='w') as f: south_migration_modules = [] for app in apps: south_migration_modules.append("'%(app)s': '%(app)s.south_migrations'" % {'app': app}) f.write(MANAGE_PY %...
<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_list_venvs(self): """Prints out and returns a list of known virtual environments. :rtype: list :return: list of virtual environments """
self.logger.info('Listing known virtual environments ...') venvs = self.get_venvs() for venv in venvs: self.logger.info('Found `%s`' % venv) else: self.logger.info('No virtual environments found in `%s` directory.' % VENVS_DIRNAME) return venvs
<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_list_apps(self): """Prints out and returns a list of known applications. :rtype: list :return: list of applications """
self.logger.info('Listing known applications ...') apps = self.get_apps() for app in apps: self.logger.info('Found `%s`' % app) else: self.logger.info('\nDONE. No applications found in `%s` directory.\n' % APPS_DIRNAME) return apps
<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_bootstrap(self): """Bootstraps django-dev by creating required directory structure."""
self.logger.info('Bootstrapping django-dev directory structure in current directory ...') self.make_venv(DJANGO_DEFAULT_VERSION) venv_path = self.make_venv('1.6.5') self.venv_install('south==1.0.1', venv_path) apps_dir = self.make_apps_dir() self.logger.info('Now you may...
<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_install_package(self, names): """Install packages into virtual envs as to satisfy app requirements. Exact version numbers could be given as in PIP: somede...
venvs = self.get_venvs() for venv in venvs: for name in names: self.venv_install(name, self._get_venv_path(venv))
<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_sint(self): """Converts the word to a BinInt, treating it as a signed number."""
if self._width == 0: return BinInt(0) sbit = 1 << (self._width - 1) return BinInt((self._val - sbit) ^ -sbit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sar(self, count): """Performs an arithmetic right-shift of a BinWord by the given number of bits. Bits shifted out of the word are lost. The word is filled o...
count = operator.index(count) if count < 0: raise ValueError('negative shift') if count > self._width: count = self._width return BinWord(self._width, self.to_sint() >> count, trunc=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 slt(self, other): """Compares two equal-sized BinWords, treating them as signed integers, and returning True if the first is smaller. """
self._check_match(other) return self.to_sint() < other.to_sint()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sle(self, other): """Compares two equal-sized BinWords, treating them as signed integers, and returning True if the first is smaller or equal. """
self._check_match(other) return self.to_sint() <= other.to_sint()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sgt(self, other): """Compares two equal-sized BinWords, treating them as signed integers, and returning True if the first is bigger. """
self._check_match(other) return self.to_sint() > other.to_sint()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sge(self, other): """Compares two equal-sized BinWords, treating them as signed integers, and returning True if the first is bigger or equal. """
self._check_match(other) return self.to_sint() >= other.to_sint()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def concat(cls, *args): """Returns a BinWord made from concatenating several BinWords, in LSB-first order. """
width = 0 val = 0 for arg in args: if not isinstance(arg, BinWord): raise TypeError('need BinWord in concat') val |= arg._val << width width += arg._width return cls(width, val)
<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_sort_function(order): """ Returns a callable similar to the built-in `cmp`, to be used on objects. Takes a list of dictionaries. In each, 'key' must be a...
stable = tuple((d['key'], -1 if d['reverse'] else 1) for d in order) def sort_function(a, b): for name, direction in stable: v = cmp(getattr(a, name) if a else a, getattr(b, name) if b else b) if v != 0: return v * direction return 0 return sort_funct...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_order(self): """ Return a list of dicionaries. See `set_order`. """
return [dict(reverse=r[0], key=r[1]) for r in self.get_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 allow_headers(self, domain, headers, secure=True): """ Allows ``domain`` to push data via the HTTP headers named in ``headers``. As with ``allow_domain``, ``...
if self.site_control == SITE_CONTROL_NONE: raise TypeError( METAPOLICY_ERROR.format("allow headers from a domain") ) self.header_domains[domain] = {'headers': headers, 'secure': secure}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allow_identity(self, fingerprint): """ Allows access from documents digitally signed by the key with ``fingerprint``. In theory, multiple algorithms can be a...
if self.site_control == SITE_CONTROL_NONE: raise TypeError( METAPOLICY_ERROR.format("allow access from signed documents") ) if fingerprint not in self.identities: self.identities.append(fingerprint)
<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_domains_xml(self, document): """ Generates the XML elements for allowed domains. """
for domain, attrs in self.domains.items(): domain_element = document.createElement('allow-access-from') domain_element.setAttribute('domain', domain) if attrs['to_ports'] is not None: domain_element.setAttribute( 'to-ports', ...
<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_header_domains_xml(self, document): """ Generates the XML elements for allowed header domains. """
for domain, attrs in self.header_domains.items(): header_element = document.createElement( 'allow-http-request-headers-from' ) header_element.setAttribute('domain', domain) header_element.setAttribute('headers', ','.join(attrs['headers'])) ...
<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_identities_xml(self, document): """ Generates the XML elements for allowed digital signatures. """
for fingerprint in self.identities: identity_element = document.createElement( 'allow-access-from-identity' ) signatory_element = document.createElement( 'signatory' ) certificate_element = document.createElement( ...
<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_xml_dom(self): """ Collects all options set so far, and produce and return an ``xml.dom.minidom.Document`` representing the corresponding XML. """
if self.site_control == SITE_CONTROL_NONE and \ any((self.domains, self.header_domains, self.identities)): raise TypeError(BAD_POLICY) policy_type = minidom.createDocumentType( qualifiedName='cross-domain-policy', publicId=None, systemId='http...
<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_callbacks(self): '''Eventually, this should be configured, rather than hardcoded''' # checkpoint filepath = os.path.join(CHECKPOINT_DIR, 'weights.best.hdf5') checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='auto') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reverse_with_query(named_url,**kwargs): "Reverse named URL with GET query" q = QueryDict('',mutable=True) q.update(kwargs) return '{}?{}'.format(reverse(named_url),q.urlencode())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_undo(self): """ Are there actions to undo? """
return bool(self._undo) or bool(self._open and self._open[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 end_grouping(self): """ Raises IndexError when no group is open. """
close = self._open.pop() if not close: return if self._open: self._open[-1].extend(close) elif self._undoing: self._redo.append(close) else: self._undo.append(close) self.notify()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def redo(self): """ Performs the top group on the redo stack, if present. Creates an undo group with the same name. Raises RuntimeError if called while undoing. ...
if self._undoing or self._redoing: raise RuntimeError if not self._redo: return group = self._redo.pop() self._redoing = True self.begin_grouping() group.perform() self.set_action_name(group.name) self.end_grouping() 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 register(self, func, *args, **kwargs): """ Record an undo operation. Also clears the redo stack. Raises IndexError when no group is open. """
self._open[-1].append(UndoOperation(func, *args, **kwargs)) if not (self._undoing or self._redoing): self._redo = [] self.notify()
<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_action_name(self, name): """ Set the name of the top group, if present. """
if self._open and name is not None: self._open[-1].name = name self.notify()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def undo(self): """ Raises IndexError if more than one group is open, otherwise closes it and invokes undo_nested_group. """
if self.grouping_level() == 1: self.end_grouping() if self._open: raise IndexError self.undo_nested_group() self.notify()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def undo_action_name(self): """ The name of the top group on the undo stack, or an empty string. """
if self._open: return self._open[-1].name elif self._undo: return self._undo[-1].name 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 undo_nested_group(self): """ Performs the last group opened, or the top group on the undo stack. Creates a redo group with the same name. """
if self._undoing or self._redoing: raise RuntimeError if self._open: group = self._open.pop() elif self._undo: group = self._undo.pop() else: return self._undoing = True self.begin_grouping() group.perform() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dispatch(*funcs): '''Iterates through the functions and calls them with given the parameters and returns the first non-empty result >>> f = dispatch(lambda: None, lambda: 1) >>> f() 1 :param \*funcs: funcs list of dispatched functions :returns: dispatch functoin ''' def _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 preproc_directive(self) -> bool: """Consume a preproc directive."""
self._stream.save_context() if self.read_until("\n", '\\'): return self._stream.validate_context() return self._stream.restore_context()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(workbench): """Connection inititalization routine. """
d = _getContextFactory(getDataPath(), workbench) d.addCallback(_connectWithContextFactory, workbench) return 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 _connectWithContextFactory(ctxFactory, workbench): """Connect using the given context factory. Notifications go to the given workbench. """
endpoint = SSL4ClientEndpoint(reactor, "localhost", 4430, ctxFactory) splash = _Splash(u"Connecting", u"Connecting...") workbench.display(splash) d = endpoint.connect(Factory(workbench)) @d.addBoth def closeSplash(returnValue): workbench.undisplay() return returnValue @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 _getContextFactory(path, workbench): """Get a context factory. If the client already has a credentials at path, use them. Otherwise, generate them at path. N...
try: return succeed(getContextFactory(path)) except IOError: d = prompt(workbench, u"E-mail entry", u"Enter e-mail:") d.addCallback(_makeCredentials, path, workbench) d.addCallback(lambda _result: getContextFactory(path)) return 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 _makeCredentials(email, path, workbench): """Makes client certs and writes them to disk at path. This essentially defers to clarent's ``makeCredentials`` fun...
splash = _Splash(u"SSL credential generation", u"Generating SSL credentials. (This can take a while.)") workbench.display(splash) makeCredentials(path, email) workbench.undisplay()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def npm_install(package, flags=None): """Install a package from NPM."""
command = u'install %s %s' % (package, flags or u'') npm_command(command.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 fasta_iter(handle, header=None): """Iterate over FASTA file and return FASTA entries Args: handle (file): FASTA file handle, can be any iterator so long as ...
# Speed tricks: reduces function calls append = list.append join = str.join strip = str.strip next_line = next if header is None: header = next(handle) # Read first FASTQ entry header # Check if input is text or bytestream if (isinstance(header, bytes)): def next_li...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def embedded_images(X, images, exclusion_radius=None, ax=None, cmap=None, zoom=1, seed=None, frameon=False): '''Plots a subset of images on an axis. Useful for visualizing image embeddings, especially when plotted over a scatterplot. Selects random points to annotate with their corresponding 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 jitterplot(data, positions=None, ax=None, vert=True, scale=0.1, **scatter_kwargs): '''Plots jittered points as a distribution visualizer. Scatter plot arguments default to: marker='.', c='k', alpha=0.75 Also known as a stripplot. See also: boxplot, violinplot, beeswarm ''' if ax is None:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_type(name, library): """ Gets object type by its name and library where it is defined. :param name: an object type name. :param library: a library where ...
if name == None: raise Exception("Class name cannot be null") if library == None: raise Exception("Module name cannot be null") try: module = importlib.import_module(library) return getattr(module, name) except: 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 get_type_by_descriptor(descriptor): """ Gets object type by type descriptor. :param descriptor: a type descriptor that points to an object type :return: the ...
if descriptor == None: raise Exception("Type descriptor cannot be null") return TypeReflector.get_type(descriptor.get_name(), descriptor.get_library())
<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_instance(name, library, *args): """ Creates an instance of an object type specified by its name and library where it is defined. :param name: an objec...
obj_type = TypeReflector.get_type(name, library) if obj_type == None: raise NotFoundException( None, "TYPE_NOT_FOUND", "Type " + name + "," + library + " was not found" ).with_details("type", name).with_details("library", library) return obj_type...
<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_primitive(value): """ Checks if value has primitive type. Primitive types are: numbers, strings, booleans, date and time. Complex (non-primitive types are...
typeCode = TypeConverter.to_type_code(value) return typeCode == TypeCode.String or typeCode == TypeCode.Enum or typeCode == TypeCode.Boolean \ or typeCode == TypeCode.Integer or typeCode == TypeCode.Long \ or typeCode == TypeCode.Float or typeCode == TypeCode.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 restart(self, timeout=None): """Restarts this Splunk instance. The service is unavailable until it has successfully restarted. If a *timeout* value is specif...
msg = { "value": "Restart requested by " + self.username + "via the Splunk SDK for Python"} # This message will be deleted once the server actually restarts. self.messages.create(name="restart_required", **msg) result = self.post("server/control/restart") if timeout is None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, response): """ Reads the current state of the entity from the server. """
results = self._load_state(response) # In lower layers of the SDK, we end up trying to URL encode # text to be dispatched via HTTP. However, these links are already # URL encoded when they arrive, and we need to mark them as such. unquoted_links = dict([(k, UrlEncoded(v, skip_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 create(self, name, **params): """Creates a new entity in this collection. This function makes either one or two roundtrips to the server, depending on the ty...
if not isinstance(name, basestring): raise InvalidNameException("%s is not a valid name for an entity." % name) if 'namespace' in params: namespace = params.pop('namespace') params['owner'] = namespace.owner params['app'] = namespace.app param...