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 execute(cls, instance, async=True, countdown=2, is_heavy_task=False, **kwargs): """ Execute high level-operation """
cls.pre_apply(instance, async=async, **kwargs) result = cls.apply_signature(instance, async=async, countdown=countdown, is_heavy_task=is_heavy_task, **kwargs) cls.post_apply(instance, async=async, **kwargs) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_signature(cls, instance, async=True, countdown=None, is_heavy_task=False, **kwargs): """ Serialize input data and apply signature """
serialized_instance = utils.serialize_instance(instance) signature = cls.get_task_signature(instance, serialized_instance, **kwargs) link = cls.get_success_signature(instance, serialized_instance, **kwargs) link_error = cls.get_failure_signature(instance, serialized_instance, **kwargs)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_callback(cls, callback, result): """ Synchronously execute callback """
if not callback.immutable: callback.args = (result.id, ) + callback.args callback.apply()
<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_disabled_action(view): """ Checks whether Link action is disabled. """
if not isinstance(view, core_views.ActionsViewSet): return False action = getattr(view, 'action', None) return action in view.disabled_actions if action is not None else 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_allowed_methods(self, callback): """ Return a list of the valid HTTP methods for this endpoint. """
if hasattr(callback, 'actions'): return [method.upper() for method in callback.actions.keys() if method != 'head'] return [ method for method in callback.cls().allowed_methods if method not in ('OPTIONS', 'HEAD') ]
<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_view(self, callback, method, request=None): """ Given a callback, return an actual view instance. """
view = super(WaldurSchemaGenerator, self).create_view(callback, method, request) if is_disabled_action(view): view.exclude_from_schema = True return view
<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_description(self, path, method, view): """ Determine a link description. This will be based on the method docstring if one exists, or else the class docs...
description = super(WaldurSchemaGenerator, self).get_description(path, method, view) permissions_description = get_permissions_description(view, method) if permissions_description: description += '\n\n' + permissions_description if description else permissions_description ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_error_message(sender, instance, name, source, target, **kwargs): """ Delete error message if instance state changed from erred """
if source != StateMixin.States.ERRED: return instance.error_message = '' instance.save(update_fields=['error_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 _make_value(self, value): """Instantiates an enum with an arbitrary value."""
member = self.__new__(self, value) member.__init__(value) return member
<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(cls, value, default=_no_default): """Parses an enum member name or value into an enum member. Accepts the following types: - Members of this enum class...
if isinstance(value, cls): return value elif isinstance(value, six.integer_types) and not isinstance(value, EnumBase): e = cls._value_to_member.get(value, _no_default) else: e = cls._name_to_member.get(value, _no_default) if e is _no_default or not 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 parse(cls, value, default=_no_default): """Parses a flag integer or string into a Flags instance. Accepts the following types: - Members of this enum class. ...
if isinstance(value, cls): return value elif isinstance(value, int): e = cls._make_value(value) else: if not value: e = cls._make_value(0) else: r = 0 for k in value.split(","): 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 get_permission_checks(self, request, view): """ Get permission checks that will be executed for current action. """
if view.action is None: return [] # if permissions are defined for view directly - use them. if hasattr(view, view.action + '_permissions'): return getattr(view, view.action + '_permissions') # otherwise return view-level permissions + extra view permissions ...
<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_function(self, function): """ Registers the function to the server's default fixed function manager. """
#noinspection PyTypeChecker if not len(self.settings.FUNCTION_MANAGERS): raise ConfigurationError( 'Where have the default function manager gone?!') self.settings.FUNCTION_MANAGERS[0].add_function(function)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_raw_field(key): """ When ElasticSearch analyzes string, it breaks it into parts. In order make query for not-analyzed exact string values, we should u...
subfield = django_settings.WALDUR_CORE.get('ELASTICSEARCH', {}).get('raw_subfield', 'keyword') return '%s.%s' % (camel_case_to_underscore(key), subfield)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decorate(decorator_cls, *args, **kwargs): """Creates a decorator function that applies the decorator_cls that was passed in."""
global _wrappers wrapper_cls = _wrappers.get(decorator_cls, None) if wrapper_cls is None: class PythonWrapper(decorator_cls): pass wrapper_cls = PythonWrapper wrapper_cls.__name__ = decorator_cls.__name__ + "PythonWrapper" _wrappers[decorator_cls] = wrapper_cl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deprecated(replacement_description): """States that method is deprecated. :param replacement_description: Describes what must be used instead. :return: the o...
def decorate(fn_or_class): if isinstance(fn_or_class, type): pass # Can't change __doc__ of type objects else: try: fn_or_class.__doc__ = "This API point is obsolete. %s\n\n%s" % ( replacement_description, fn_or_class...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_result(converter): """Decorator that can convert the result of a function call."""
def decorate(fn): @inspection.wraps(fn) def new_fn(*args, **kwargs): return converter(fn(*args, **kwargs)) return new_fn return decorate
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retry(exception_cls, max_tries=10, sleep=0.05): """Decorator for retrying a function if it throws an exception. :param exception_cls: an exception type or a ...
assert max_tries > 0 def with_max_retries_call(delegate): for i in xrange(0, max_tries): try: return delegate() except exception_cls: if i + 1 == max_tries: raise time.sleep(sleep) def outer(fn): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decorator_of_context_manager(ctxt): """Converts a context manager into a decorator. This decorator will run the decorated function in the context of the mana...
def decorator_fn(*outer_args, **outer_kwargs): def decorator(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): with ctxt(*outer_args, **outer_kwargs): return fn(*args, **kwargs) return wrapper return decorator if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_error(self, error): """ A helper function, gets standard information from the error. """
error_type = type(error) if error.error_type == ET_CLIENT: error_type_name = 'Client' else: error_type_name = 'Server' return { 'type': error_type_name, 'name': error_type.__name__, 'prefix': getattr(error_type, '__module__', '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_quota_change(self, quota_deltas, raise_exception=False): """ Get error messages about object and his ancestor quotas that will be exceeded if quota_...
errors = [] for name, delta in six.iteritems(quota_deltas): quota = self.quotas.get(name=name) if quota.is_exceeded(delta): errors.append('%s quota limit: %s, requires %s (%s)\n' % ( quota.name, quota.limit, quota.usage + delta, quota.scope)) ...
<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_sum_of_quotas_as_dict(cls, scopes, quota_names=None, fields=['usage', 'limit']): """ Return dictionary with sum of all scopes' quotas. Dictionary format:...
if not scopes: return {} if quota_names is None: quota_names = cls.get_quotas_names() scope_models = set([scope._meta.model for scope in scopes]) if len(scope_models) > 1: raise exceptions.QuotaError(_('All scopes have to be instances of the same mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scope_types(self, request, *args, **kwargs): """ Returns a list of scope types acceptable by events filter. """
return response.Response(utils.get_scope_types_mapping().keys())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_from_file(self, index, filename): """Import this instrument's settings from the given file. Will automatically add the instrument's synth and table to...
with open(filename, 'r') as fp: self._import_from_struct(index, json.load(fp))
<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_lsdsng(filename): """Load a Project from a ``.lsdsng`` file. :param filename: the name of the file from which to load :rtype: :py:class:`pylsdj.Project`...
# Load preamble data so that we know the name and version of the song with open(filename, 'rb') as fp: preamble_data = bread.parse(fp, spec.lsdsng_preamble) with open(filename, 'rb') as fp: # Skip the preamble this time around fp.seek(int(len(preamble_data) / 8)) # Load c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_srm(filename): """Load a Project from an ``.srm`` file. :param filename: the name of the file from which to load :rtype: :py:class:`pylsdj.Project` """
# .srm files are just decompressed projects without headers # In order to determine the file's size in compressed blocks, we have to # compress it first with open(filename, 'rb') as fp: raw_data = fp.read() compressed_data = filepack.compress(raw_data) factory = BlockFactory() w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def song(self): """the song associated with the project"""
if self._song is None: self._song = Song(self._song_data) return self._song
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, filename): """Save a project in .lsdsng format to the target file. :param filename: the name of the file to which to save :deprecated: use ``save_...
with open(filename, 'wb') as fp: writer = BlockWriter() factory = BlockFactory() preamble_dummy_bytes = bytearray([0] * 9) preamble = bread.parse( preamble_dummy_bytes, spec.lsdsng_preamble) preamble.name = self.name pream...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_srm(self, filename): """Save a project in .srm format to the target file. :param filename: the name of the file to which to save """
with open(filename, 'wb') as fp: raw_data = bread.write(self._song_data, spec.song) fp.write(raw_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 phase_type(self, value): '''compresses the waveform horizontally; one of ``"normal"``, ``"resync"``, ``"resync2"``''' self._params.phase_type = value self._overwrite_lock.disable()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, filename, callback=_noop_callback): """Save this file. :param filename: the file to which to save the .sav file :type filename: str :param callbac...
with open(filename, 'wb') as fp: self._save(fp, callback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split(compressed_data, segment_size, block_factory): """Splits compressed data into blocks. :param compressed_data: the compressed data to split :param segme...
# Split compressed data into blocks segments = [] current_segment_start = 0 index = 0 data_size = len(compressed_data) while index < data_size: current_byte = compressed_data[index] if index < data_size - 1: next_byte = compressed_data[index + 1] 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 renumber_block_keys(blocks): """Renumber a block map's indices so that tehy match the blocks' block switch statements. :param blocks a block map to renumber ...
# There is an implicit block switch to the 0th block at the start of the # file byte_switch_keys = [0] block_keys = list(blocks.keys()) # Scan the blocks, recording every block switch statement for block in list(blocks.values()): i = 0 while i < len(block.data) - 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 merge(blocks): """Merge the given blocks into a contiguous block of compressed data. :param blocks: the list of blocks :rtype: a list of compressed bytes """
current_block = blocks[sorted(blocks.keys())[0]] compressed_data = [] eof = False while not eof: data_size_to_append = None next_block = None i = 0 while i < len(current_block.data) - 1: current_byte = current_block.data[i] next_byte = current...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pad(segment, size): """Add zeroes to a segment until it reaches a certain size. :param segment: the segment to pad :param size: the size to which to pad the ...
for i in range(size - len(segment)): segment.append(0) assert len(segment) == 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 decompress(compressed_data): """Decompress data that has been compressed by the filepack algorithm. :param compressed_data: an array of compressed data bytes...
raw_data = [] index = 0 while index < len(compressed_data): current = compressed_data[index] index += 1 if current == RLE_BYTE: directive = compressed_data[index] index += 1 if directive == RLE_BYTE: raw_data.append(RLE_BYTE) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compress(raw_data): """Compress raw bytes with the filepack algorithm. :param raw_data: an array of raw data bytes to compress :rtype: a list of compressed b...
raw_data = bytearray(raw_data) compressed_data = [] data_size = len(raw_data) index = 0 next_bytes = [-1, -1, -1] def is_default_instrument(index): if index + len(DEFAULT_INSTRUMENT_FILEPACK) > len(raw_data): return False instr_bytes = raw_data[index:index + len(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name_without_zeroes(name): """ Return a human-readable name without LSDJ's trailing zeroes. :param name: the name from which to strip zeroes :rtype: the name...
first_zero = name.find(b'\0') if first_zero == -1: return name else: return str(name[:first_zero])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table(self): """a ```pylsdj.Table``` referencing the instrument's table, or None if the instrument doesn't have a table"""
if hasattr(self.data, 'table_on') and self.data.table_on: assert_index_sane(self.data.table, len(self.song.tables)) return self.song.tables[self.data.table]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_lsdinst(self, struct_data): """import from an lsdinst struct"""
self.name = struct_data['name'] self.automate = struct_data['data']['automate'] self.pan = struct_data['data']['pan'] if self.table is not None: self.table.import_lsdinst(struct_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 export_to_file(self, filename): """Export this instrument's settings to a file. :param filename: the name of the file """
instr_json = self.export_struct() with open(filename, 'w') as fp: json.dump(instr_json, fp, indent=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 write_wav(self, filename): """Write this sample to a WAV file. :param filename: the file to which to write """
wave_output = None try: wave_output = wave.open(filename, 'w') wave_output.setparams(WAVE_PARAMS) frames = bytearray([x << 4 for x in self.sample_data]) wave_output.writeframes(frames) finally: if wave_output 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 read_wav(self, filename): """Read sample data for this sample from a WAV file. :param filename: the file from which to read """
wave_input = None try: wave_input = wave.open(filename, 'r') wave_frames = bytearray( wave_input.readframes(wave_input.getnframes())) self.sample_data = [x >> 4 for x in wave_frames] finally: if wave_input 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 get_device_address(device): """ find the local ip address on the given device """
if device is None: return None command = ['ip', 'route', 'list', 'dev', device] ip_routes = subprocess.check_output(command).strip() for line in ip_routes.split('\n'): seen = '' for a in line.split(): if seen == 'src': return a seen = 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 get_default_net_device(): """ Find the device where the default route is. """
with open('/proc/net/route') as fh: for line in fh: iface, dest, _ = line.split(None, 2) if dest == '00000000': return iface 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 add_missing_optional_args_with_value_none(args, optional_args): ''' Adds key-value pairs to the passed dictionary, so that afterwards, the dictionary can be used without needing to check for KeyErrors. If the keys passed as a second argument are not present, they are added with ...
<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_presence_of_mandatory_args(args, mandatory_args): ''' Checks whether all mandatory arguments are passed. This function aims at methods with many arguments which are passed as kwargs so that the order in which the are passed does not matter. :args: The dictionary passed as arg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def monkey_patch_migration_template(self, app, fixture_path): """ Monkey patch the django.db.migrations.writer.MIGRATION_TEMPLATE Monkey patching django.db.migra...
self._MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE module_split = app.module.__name__.split('.') if len(module_split) == 1: module_import = "import %s\n" % module_split[0] else: module_import = "from %s import %s\n" % ( '.'.join(module_split[:-...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def migration_exists(self, app, fixture_path): """ Return true if it looks like a migration already exists. """
base_name = os.path.basename(fixture_path) # Loop through all migrations for migration_path in glob.glob(os.path.join(app.path, 'migrations', '*.py')): if base_name in open(migration_path).read(): 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 create_migration(self, app, fixture_path): """ Create a data migration for app that uses fixture_path. """
self.monkey_patch_migration_template(app, fixture_path) out = StringIO() management.call_command('makemigrations', app.label, empty=True, stdout=out) self.restore_migration_template() self.stdout.write(out.getvalue())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def instantiate_for_read_and_search(handle_server_url, reverselookup_username, reverselookup_password, **config): ''' Initialize client with read access and with search function. :param handle_server_url: The URL of the Handle Server. May be None (then, the default 'https://hdl.hand...
<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_value_from_handle(self, handle, key, handlerecord_json=None): ''' Retrieve a single value from a single Handle. If several entries with this key exist, the methods returns the first one. If the handle does not exist, the method will raise a HandleNotFoundException. :para...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete_handle_value(self, handle, key): ''' Delete a key-value pair from a handle record. If the key exists more than once, all key-value pairs with this key are deleted. :param handle: Handle from whose record the entry should be deleted. :param key: Key to be deleted. Also...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete_handle(self, handle, *other): '''Delete the handle and its handle record. If the Handle is not found, an Exception is raised. :param handle: Handle to be deleted. :param other: Deprecated. This only exists to catch wrong method usage by users who are used to delete handle...
<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_handle(self, handle, location, checksum=None, additional_URLs=None, overwrite=False, **extratypes): ''' Registers a new Handle with given name. If the handle already exists and overwrite is not set to True, the method will throw an exception. :param handle: The full...
<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_handlerecord_indices_for_key(self, key, list_of_entries): ''' Finds the Handle entry indices of all entries that have a specific type. *Important:* It finds the Handle System indices! These are not the python indices of the list, so they can not be used for itera...
<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_handle_record_if_necessary(self, handle, handlerecord_json): ''' Returns the handle record if it is None or if its handle is not the same as the specified handle. ''' if handlerecord_json is None: handlerecord_json = self.retrieve_handle_record_json(han...
<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_entry(self, entrytype, data, index, ttl=None): ''' Create an entry of any type except HS_ADMIN. :param entrytype: THe type of entry to create, e.g. 'URL' or 'checksum' or ... Note: For entries of type 'HS_ADMIN', please use __create_admin_entry(). For 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 __create_admin_entry(self, handleowner, permissions, index, handle, ttl=None): ''' Create an entry of type "HS_ADMIN". :param username: The username, i.e. a handle with an index (index:prefix/suffix). The value referenced by the index contains authentcation informati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth_access(self, auth_code): """ verify the fist authorization response url code response data 返回值字段 字段类型 字段说明 access_token string 用户授权的唯一票据,用于调用微博的开放接口,同时也...
data = { 'client_id': self.client_id, 'client_secret': self.client_secret, 'grant_type': 'authorization_code', 'code': auth_code, 'redirect_uri': self.redirect_url } return self.request("post", "access_token", data=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 check_if_username_exists(self, username): ''' Check if the username handles exists. :param username: The username, in the form index:prefix/suffix :raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException` :raises: :exc:`~b2handle.handleexceptions.GenericHandleError`...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def publish_metric(self, metric_name, metric_value, epoch_seconds=None): '''Record a single hit on a given metric. Args: metric_name: The name of the metric to record with Carbon. metric_value: The value to record with Carbon. epoch_seconds: Optionally specify the ti...
<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_repeating_metric(self, metric_name, frequency, getter): '''Record hits to a metric at a specified interval. Args: metric_name: The name of the metric to record with Carbon. frequency: The frequency with which to poll the getter and record the value with Carbon. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show(): """Try showing the most desirable GUI This function cycles through the currently registered graphical user interfaces, if any, and presents it to the...
parent = None current = QtWidgets.QApplication.activeWindow() while current: parent = current current = parent.parent() window = (_discover_gui() or _show_no_gui)(parent) return window
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dock(window): """ Expecting a window to parent into a Nuke panel, that is dockable. """
# Deleting existing dock # There is a bug where existing docks are kept in-memory when closed via UI if self._dock: print("Deleting existing dock...") parent = self._dock dialog = None stacked_widget = None main_windows = [] # Getting dock parents w...
<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_index_from_handle(handle_with_index): ''' Returns index and handle separately, in a tuple. :handle_with_index: The handle string with an index (e.g. 500:prefix/suffix) :return: index and handle as a tuple. ''' split = handle_with_index.split(':') if len(split) == 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 create_authentication_string(username, password): ''' Creates an authentication string from the username and password. :username: Username. :password: Password. :return: The encoded string. ''' username_utf8 = username.encode('utf-8') userpw_utf8 = password.encode('utf-8') 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 make_request_log_message(**args): ''' Creates a string containing all relevant information about a request made to the Handle System, for logging purposes. :handle: The handle that the request is about. :url: The url the request is sent to. :headers: The headers sent along with the requ...
<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_module(fdr, fqname, path = None): '''Find a loader for module or package `fqname`. This method will be called with the fully qualified name of the module. If the finder is installed on `sys.meta_path`, it will receive a second argument, which is `None` for a top-level module, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_module(ldr, fqname): '''Load `fqname` from under `ldr.fspath`. The `fqname` argument is the fully qualified module name, eg. "spam.eggs.ham". As explained above, when :: finder.find_module("spam.eggs.ham") is called, "spam.eggs" has already been imported and added 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 zthread_fork(ctx, func, *args, **kwargs): """ Create an attached thread. An attached thread gets a ctx and a PAIR pipe back to its parent. It must monitor it...
a = ctx.socket(zmq.PAIR) a.setsockopt(zmq.LINGER, 0) a.setsockopt(zmq.RCVHWM, 100) a.setsockopt(zmq.SNDHWM, 100) a.setsockopt(zmq.SNDTIMEO, 5000) a.setsockopt(zmq.RCVTIMEO, 5000) b = ctx.socket(zmq.PAIR) b.setsockopt(zmq.LINGER, 0) b.setsockopt(zmq.RCVHWM, 100) b.setsockopt(zmq....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _remap(object, name, value, safe=True): """Prevent accidental assignment of existing members Arguments: object (object): Parent of new attribute name (str):...
if os.getenv("QT_TESTING") is not None and safe: # Cannot alter original binding. if hasattr(object, name): raise AttributeError("Cannot override existing name: " "%s.%s" % (object.__name__, name)) # Cannot alter classes of functions 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 log_instantiation(LOGGER, classname, args, forbidden, with_date=False): ''' Log the instantiation of an object to the given logger. :LOGGER: A logger to log to. Please see module "logging". :classname: The name of the class that is being instantiated. :args: A dictionary of arguments pa...
<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_params(params): """ convert dict value if value is bool type, False -> "false" True -> "true" """
if params is not None: new_params = copy.deepcopy(params) new_params = dict((k, v) for k, v in new_params.items() if v is not None) for key, value in new_params.items(): if isinstance(value, bool): new_params[key] = "true" if value else "false" return new...
<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_revlookup_auth_string(self, username, password): ''' Creates and sets the authentication string for accessing the reverse lookup servlet. No return, the string is set as an attribute to the client instance. :param username: Username. :param password: Pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_from_JSON(json_filename): ''' Create a new instance of a PIDClientCredentials with information read from a local JSON file. :param json_filename: The path to the json credentials file. The json file should have the following format: .. code:: json ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fixture(app, fixtures, fixtures_dir='fixtures', raise_does_not_exist=False, reversible=True, models=[]): """ Load fixtures using a data migration. The migrat...
fixture_path = os.path.join(app.__path__[0], fixtures_dir) if isinstance(fixtures, string_types): fixtures = [fixtures] def get_format(fixture): return os.path.splitext(fixture)[1][1:] def get_objects(): for fixture in fixtures: with open(os.path.join(fixture_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 nonzero(self): """ Get all non-zero bits """
return [i for i in xrange(self.size()) if self.test(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 tohexstring(self): """ Returns a hexadecimal string """
val = self.tostring() st = "{0:0x}".format(int(val, 2)) return st.zfill(len(self.bitmap)*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 fromhexstring(cls, hexstring): """ Construct BitMap from hex string """
bitstring = format(int(hexstring, 16), "0" + str(len(hexstring)/4) + "b") return cls.fromstring(bitstring)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromstring(cls, bitstring): """ Construct BitMap from string """
nbits = len(bitstring) bm = cls(nbits) for i in xrange(nbits): if bitstring[-i-1] == '1': bm.set(i) elif bitstring[-i-1] != '0': raise Exception("Invalid bit string!") return bm
<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_valid_https_verify(value): ''' Get a value that can be the boolean representation of a string or a boolean itself and returns It as a boolean. If this is not the case, It returns a string. :value: The HTTPS_verify input value. A string can be passed as a path to a CA_BUNDLE 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 setup(self): """Initialize filter just before it will be used."""
super(CleanCSSFilter, self).setup() self.root = current_app.config.get('COLLECT_STATIC_ROOT')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rebase_opt(self): """Determine which option name to use."""
if not hasattr(self, '_rebase_opt'): # out = b"MAJOR.MINOR.REVISION" // b"3.4.19" or b"4.0.0" out, err = Popen( ['cleancss', '--version'], stdout=PIPE).communicate() ver = int(out[:out.index(b'.')]) self._rebase_opt = ['--root', self.root] if ver ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def input(self, _in, out, **kw): """Input filtering."""
args = [self.binary or 'cleancss'] + self.rebase_opt if self.extra_args: args.extend(self.extra_args) self.subprocess(args, out, _in)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output(self, _in, out, **kwargs): """Wrap translation in Angular module."""
out.write( 'angular.module("{0}", ["gettext"]).run(' '["gettextCatalog", function (gettextCatalog) {{'.format( self.catalog_name ) ) out.write(_in.read()) out.write('}]);')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def input(self, _in, out, **kwargs): """Process individual translation file."""
language_code = _re_language_code.search(_in.read()).group( 'language_code' ) _in.seek(0) # move at the begining after matching the language catalog = read_po(_in) out.write('gettextCatalog.setStrings("{0}", '.format(language_code)) out.write(json.dumps({ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve_info(self): """Query the Github API to retrieve the needed infos."""
path = urlparse(self.url).path path = path.split('/')[1:] sanity_filter = re.compile('[\da-z-_]+', re.IGNORECASE) self.product = sanity_filter.match(path[0]).group(0) self.component = sanity_filter.match(path[1]).group(0) self.issue_id = int(path[3]) github_ur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disk_cache(cls, basename, function, *args, method=True, **kwargs): """ Cache the return value in the correct cache directory. Set 'method' to false for stati...
@utility.disk_cache(basename, cls.directory(), method=method) def wrapper(*args, **kwargs): return function(*args, **kwargs) return wrapper(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(cls, url, filename=None): """ Download a file into the correct cache directory. """
return utility.download(url, cls.directory(), filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def directory(cls, prefix=None): """ Path that should be used for caching. Different for all subclasses. """
prefix = prefix or utility.read_config().directory name = cls.__name__.lower() directory = os.path.expanduser(os.path.join(prefix, name)) utility.ensure_directory(directory) return directory
<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_last_rconfiguration_id(topic_id, remoteci_id, db_conn=None): """Get the rconfiguration_id of the last job run by the remoteci. :param topic_id: the topic...
db_conn = db_conn or flask.g.db_conn __TABLE = models.JOBS query = sql.select([__TABLE.c.rconfiguration_id]). \ order_by(sql.desc(__TABLE.c.created_at)). \ where(sql.and_(__TABLE.c.topic_id == topic_id, __TABLE.c.remoteci_id == remoteci_id)). \ limit(1) rc...
<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_remoteci_configuration(topic_id, remoteci_id, db_conn=None): """Get a remoteci configuration. This will iterate over each configuration in a round robin ...
db_conn = db_conn or flask.g.db_conn last_rconfiguration_id = get_last_rconfiguration_id( topic_id, remoteci_id, db_conn=db_conn) _RCONFIGURATIONS = models.REMOTECIS_RCONFIGURATIONS _J_RCONFIGURATIONS = models.JOIN_REMOTECIS_RCONFIGURATIONS query = sql.select([_RCONFIGURATIONS]). \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ignore_whitespace_text_nodes(cls, wrapped_node): """ Find and delete any text nodes containing nothing but whitespace in in the given node and its descendent...
for child in wrapped_node.children: if child.is_text and child.value.strip() == '': child.delete() else: cls.ignore_whitespace_text_nodes(child)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_existence_and_get(id, table, name=None, get_id=False): """Verify the existence of a resource in the database and then return it if it exists, accordin...
where_clause = table.c.id == id if name: where_clause = table.c.name == name if 'state' in table.columns: where_clause = sql.and_(table.c.state != 'archived', where_clause) query = sql.select([table]).where(where_clause) result = flask.g.db_conn.execute(query).fetchone() 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 user_topic_ids(user): """Retrieve the list of topics IDs a user has access to."""
if user.is_super_admin() or user.is_read_only_user(): query = sql.select([models.TOPICS]) else: query = (sql.select([models.JOINS_TOPICS_TEAMS.c.topic_id]) .select_from( models.JOINS_TOPICS_TEAMS.join( models.TOPICS, sql.and_(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 verify_team_in_topic(user, topic_id): """Verify that the user's team does belongs to the given topic. If the user is an admin or read only user then it belon...
if user.is_super_admin() or user.is_read_only_user(): return if str(topic_id) not in user_topic_ids(user): raise dci_exc.Unauthorized()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _format_level_2(rows, list_embeds, embed_many): """ From the _format_level_1 function we have a list of rows. Because of using joins, we have as many rows as...
def _uniqify_list(list_of_dicts): # list() for py34 result = [] set_ids = set() for v in list_of_dicts: if v['id'] in set_ids: continue set_ids.add(v['id']) result.append(v) return result row_ids_to_embed_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 common_values_dict(): """Build a basic values object used in every create method. All our resources contain a same subset of value. Instead of redoing this c...
now = datetime.datetime.utcnow().isoformat() etag = utils.gen_etag() values = { 'id': utils.gen_uuid(), 'created_at': now, 'updated_at': now, 'etag': etag } return 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_identity(identity): """Returns some information about the currently authenticated identity"""
return flask.Response( json.dumps( { 'identity': { 'id': identity.id, 'etag': identity.etag, 'name': identity.name, 'fullname': identity.fullname, 'email': identity.email, ...