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 detach(self, force=False): """ Detach this EBS volume from an EC2 instance. :type force: bool :param force: Forces detachment if the previous detachment atte...
instance_id = None if self.attach_data: instance_id = self.attach_data.instance_id device = None if self.attach_data: device = self.attach_data.device return self.connection.detach_volume(self.id, instance_id, device, force)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attachment_state(self): """ Get the attachment state. """
state = None if self.attach_data: state = self.attach_data.status return state
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def snapshots(self, owner=None, restorable_by=None): """ Get all snapshots related to this volume. Note that this requires that all available snapshots for the a...
rs = self.connection.get_all_snapshots(owner=owner, restorable_by=restorable_by) mine = [] for snap in rs: if snap.volume_id == self.id: mine.append(snap) return mine
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def encrypt(text): 'Encrypt a string using an encryption key based on the django SECRET_KEY' crypt = EncryptionAlgorithm.new(_get_encryption_key()) return crypt.encrypt(to_blocksize(text))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def decrypt(text): 'Decrypt a string using an encryption key based on the django SECRET_KEY' crypt = EncryptionAlgorithm.new(_get_encryption_key()) return crypt.decrypt(text).rstrip(ENCRYPT_PAD_CHARACTER)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def item_object_hook(dct): """ A custom object hook for use when decoding JSON item bodys. This hook will transform Amazon DynamoDB JSON responses to something t...
if len(dct.keys()) > 1: return dct if 'S' in dct: return dct['S'] if 'N' in dct: return convert_num(dct['N']) if 'SS' in dct: return set(dct['SS']) if 'NS' in dct: return set(map(convert_num, dct['NS'])) return dct
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dynamize_attribute_updates(self, pending_updates): """ Convert a set of pending item updates into the structure required by Layer1. """
d = {} for attr_name in pending_updates: action, value = pending_updates[attr_name] if value is None: # DELETE without an attribute value d[attr_name] = {"Action": action} else: d[attr_name] = {"Action": action, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dynamize_range_key_condition(self, range_key_condition): """ Convert a layer2 range_key_condition parameter into the structure required by Layer1. """
d = None if range_key_condition: d = {} for range_value in range_key_condition: range_condition = range_key_condition[range_value] if range_condition == 'BETWEEN': if isinstance(range_value, tuple): avl ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dynamize_scan_filter(self, scan_filter): """ Convert a layer2 scan_filter parameter into the structure required by Layer1. """
d = None if scan_filter: d = {} for attr_name, op, value in scan_filter: if op == 'BETWEEN': if isinstance(value, tuple): avl = [self.dynamize_value(v) for v in value] else: 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 dynamize_expected_value(self, expected_value): """ Convert an expected_value parameter into the data structure required for Layer1. """
d = None if expected_value: d = {} for attr_name in expected_value: attr_value = expected_value[attr_name] if attr_value is True: attr_value = {'Exists': True} elif attr_value is False: attr_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dynamize_last_evaluated_key(self, last_evaluated_key): """ Convert a last_evaluated_key parameter into the data structure required for Layer1. """
d = None if last_evaluated_key: hash_key = last_evaluated_key['HashKeyElement'] d = {'HashKeyElement': self.dynamize_value(hash_key)} if 'RangeKeyElement' in last_evaluated_key: range_key = last_evaluated_key['RangeKeyElement'] d['Rang...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dynamize_request_items(self, batch_list): """ Convert a request_items parameter into the data structure required for Layer1. """
d = None if batch_list: d = {} for batch in batch_list: batch_dict = {} key_list = [] for key in batch.keys: if isinstance(key, tuple): hash_key, range_key = key 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 get_dynamodb_type(self, val): """ Take a scalar Python value and return a string representing the corresponding Amazon DynamoDB type. If the value passed in ...
dynamodb_type = None if is_num(val): dynamodb_type = 'N' elif is_str(val): dynamodb_type = 'S' elif isinstance(val, (set, frozenset)): if False not in map(is_num, val): dynamodb_type = 'NS' elif False not in map(is_str, 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 dynamize_value(self, val): """ Take a scalar Python value and return a dict consisting of the Amazon DynamoDB type specification and the value that needs to ...
def _str(val): """ DynamoDB stores booleans as numbers. True is 1, False is 0. This function converts Python booleans into DynamoDB friendly representation. """ if isinstance(val, bool): return str(int(val)) ret...
<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_key_from_values(self, schema, hash_key, range_key=None): """ Build a Key structure to be used for accessing items in Amazon DynamoDB. This method takes...
dynamodb_key = {} dynamodb_value = self.dynamize_value(hash_key) if dynamodb_value.keys()[0] != schema.hash_key_type: msg = 'Hashkey must be of type: %s' % schema.hash_key_type raise TypeError(msg) dynamodb_key['HashKeyElement'] = dynamodb_value if range_...
<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_table(self, name): """ Retrieve the Table object for an existing table. :type name: str :param name: The name of the desired table. :rtype: :class:`boto....
response = self.layer1.describe_table(name) return Table(self, response)
<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_table(self, table): """ Delete this table and all items in it. After calling this the Table objects status attribute will be set to 'DELETING'. :type ...
response = self.layer1.delete_table(table.name) table.update_from_response(response)
<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_schema(self, hash_key_name, hash_key_proto_value, range_key_name=None, range_key_proto_value=None): """ Create a Schema object used when creating a Ta...
schema = {} hash_key = {} hash_key['AttributeName'] = hash_key_name hash_key_type = self.get_dynamodb_type(hash_key_proto_value) hash_key['AttributeType'] = hash_key_type schema['HashKeyElement'] = hash_key if range_key_name and range_key_proto_value 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 update_item(self, item, expected_value=None, return_values=None): """ Commit pending item updates to Amazon DynamoDB. :type item: :class:`boto.dynamodb.item....
expected_value = self.dynamize_expected_value(expected_value) key = self.build_key_from_values(item.table.schema, item.hash_key, item.range_key) attr_updates = self.dynamize_attribute_updates(item._updates) response = self.layer1.update_item(ite...
<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_item(self, item, expected_value=None, return_values=None): """ Delete the item from Amazon DynamoDB. :type item: :class:`boto.dynamodb.item.Item` :par...
expected_value = self.dynamize_expected_value(expected_value) key = self.build_key_from_values(item.table.schema, item.hash_key, item.range_key) return self.layer1.delete_item(item.table.name, key, expected=expected...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan(self, table, scan_filter=None, attributes_to_get=None, request_limit=None, max_results=None, count=False, exclusive_start_key=None, item_class=Item): ""...
sf = self.dynamize_scan_filter(scan_filter) response = True n = 0 while response: if response is True: pass elif response.has_key("LastEvaluatedKey"): exclusive_start_key = response['LastEvaluatedKey'] 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 photos_search(user_id='', auth=False, tags='', tag_mode='', text='',\ min_upload_date='', max_upload_date='',\ min_taken_date='', max_taken_date='', \ license...
method = 'flickr.photos.search' data = _doget(method, auth=auth, user_id=user_id, tags=tags, text=text,\ min_upload_date=min_upload_date,\ max_upload_date=max_upload_date, \ min_taken_date=min_taken_date, \ max_taken_date=max_taken_date, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def favorites_add(photo_id): """Add a photo to the user's favorites."""
method = 'flickr.favorites.add' _dopost(method, auth=True, photo_id=photo_id) return 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 favorites_remove(photo_id): """Remove a photo from the user's favorites."""
method = 'flickr.favorites.remove' _dopost(method, auth=True, photo_id=photo_id) return 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 groups_pools_getGroups(): """Get a list of groups the auth'd user can post photos to."""
method = 'flickr.groups.pools.getGroups' data = _doget(method, auth=True) groups = [] if isinstance(data.rsp.groups.group, list): for group in data.rsp.groups.group: groups.append(Group(group.id, name=group.name, \ privacy=group.privacy)) 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 tags_getListUserPopular(user_id='', count=''): """Gets the popular tags for a user in dictionary form tag=>count"""
method = 'flickr.tags.getListUserPopular' auth = user_id == '' data = _doget(method, auth=auth, user_id=user_id) result = {} if isinstance(data.rsp.tags.tag, list): for tag in data.rsp.tags.tag: result[tag.text] = tag.count else: result[data.rsp.tags.tag.text] = 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 tags_getrelated(tag): """Gets the related tags for given tag."""
method = 'flickr.tags.getRelated' data = _doget(method, auth=False, tag=tag) if isinstance(data.rsp.tags.tag, list): return [tag.text for tag in data.rsp.tags.tag] else: return [data.rsp.tags.tag.text]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_photo(photo): """Create a Photo object from photo data."""
owner = User(photo.owner) title = photo.title ispublic = photo.ispublic isfriend = photo.isfriend isfamily = photo.isfamily secret = photo.secret server = photo.server p = Photo(photo.id, owner=owner, title=title, ispublic=ispublic,\ isfriend=isfriend, isfamily=isfamily, 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 getLocation(self): """ Return the latitude+longitutde of the picture. Returns None if no location given for this pic. """
method = 'flickr.photos.geo.getLocation' try: data = _doget(method, photo_id=self.id) except FlickrError: # Some other error might have occured too!? return None loc = data.rsp.photo.location return [loc.latitude, loc.longitude]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPhotos(self): """Returns list of Photos."""
method = 'flickr.photosets.getPhotos' data = _doget(method, photoset_id=self.id) photos = data.rsp.photoset.photo p = [] for photo in photos: p.append(Photo(photo.id, title=photo.title, secret=photo.secret, \ server=photo.server)) r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def editPhotos(self, photos, primary=None): """Edit the photos in this set. photos - photos for set primary - primary photo (if None will used current) """
method = 'flickr.photosets.editPhotos' if primary is None: primary = self.primary ids = [photo.id for photo in photos] if primary.id not in ids: ids.append(primary.id) _dopost(method, auth=True, photoset_id=self.id,\ primary...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addPhoto(self, photo): """Add a photo to this set. photo - the photo """
method = 'flickr.photosets.addPhoto' _dopost(method, auth=True, photoset_id=self.id, photo_id=photo.id) self.__count += 1 return 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 delete(self): """Deletes the photoset. """
method = 'flickr.photosets.delete' _dopost(method, auth=True, photoset_id=self.id) return 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 create(cls, photo, title, description=''): """Create a new photoset. photo - primary photo """
if not isinstance(photo, Photo): raise TypeError, "Photo expected" method = 'flickr.photosets.create' data = _dopost(method, auth=True, title=title,\ description=description,\ primary_photo_id=photo.id) set = Ph...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _general_getattr(self, var): """Generic get attribute function."""
if getattr(self, "_%s__%s" % (self.__class__.__name__, var)) is None \ and not self.__loaded: self._load_properties() return getattr(self, "_%s__%s" % (self.__class__.__name__, var))
<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_properties(self): """Load User properties from Flickr."""
method = 'flickr.people.getInfo' data = _doget(method, user_id=self.__id) self.__loaded = True person = data.rsp.person self.__isadmin = person.isadmin self.__ispro = person.ispro self.__icon_server = person.iconserver if int(person.iconserver)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPhotosets(self): """Returns a list of Photosets."""
method = 'flickr.photosets.getList' data = _doget(method, user_id=self.id) sets = [] if isinstance(data.rsp.photosets.photoset, list): for photoset in data.rsp.photosets.photoset: sets.append(Photoset(photoset.id, photoset.title.text,\ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPhotos(self, tags='', per_page='', page=''): """Get a list of photo objects for this group"""
method = 'flickr.groups.pools.getPhotos' data = _doget(method, group_id=self.id, tags=tags,\ per_page=per_page, page=page) photos = [] for photo in data.rsp.photos.photo: photos.append(_parse_photo(photo)) return photos
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, photo): """Adds a Photo to the group"""
method = 'flickr.groups.pools.add' _dopost(method, auth=True, photo_id=photo.id, group_id=self.id) return 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 get_all_keys(self, headers=None, **params): """ This method returns the single key around which this anonymous Bucket was instantiated. :rtype: SimpleResultS...
key = Key(self.name, self.contained_key) return SimpleResultSet([key])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_key(self, key_name=None, key_type=Key.KEY_REGULAR_FILE): """ Creates a new key :type key_name: string :param key_name: The name of the key to create :rty...
if key_name == '-': return Key(self.name, '-', key_type=Key.KEY_STREAM_WRITABLE) else: dir_name = os.path.dirname(key_name) if dir_name and not os.path.exists(dir_name): os.makedirs(dir_name) fp = open(key_name, 'wb') return Ke...
<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_queue(self, queue, force_deletion=False, callback=None): """ Delete an SQS Queue. :type queue: A Queue object :param queue: The SQS queue to be delete...
return self.get_status('DeleteQueue', None, queue.id, callback=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 receive_message(self, queue, number_messages=1, visibility_timeout=None, attributes=None, callback=None): """ Read messages from an SQS Queue. :type queue: A...
params = {'MaxNumberOfMessages' : number_messages} if visibility_timeout: params['VisibilityTimeout'] = visibility_timeout if attributes: self.build_list_params(params, attributes, 'AttributeName') return self.get_list('ReceiveMessage', params, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_message_visibility(self, queue, receipt_handle, visibility_timeout, callback=None): """ Extends the read lock timeout for the specified message from t...
params = {'ReceiptHandle' : receipt_handle, 'VisibilityTimeout' : visibility_timeout} return self.get_status('ChangeMessageVisibility', params, queue.id, callback=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 regions(): """ Get all available regions for the RDS service. :rtype: list :return: A list of :class:`boto.rds.regioninfo.RDSRegionInfo` """
return [RDSRegionInfo(name='us-east-1', endpoint='rds.us-east-1.amazonaws.com'), RDSRegionInfo(name='eu-west-1', endpoint='rds.eu-west-1.amazonaws.com'), RDSRegionInfo(name='us-west-1', endpoint='rds.us-west-1.ama...
<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_all_dbinstances(self, instance_id=None, max_records=None, marker=None): """ Retrieve all the DBInstances in your account. :type instance_id: str :param i...
params = {} if instance_id: params['DBInstanceIdentifier'] = instance_id if max_records: params['MaxRecords'] = max_records if marker: params['Marker'] = marker return self.get_list('DescribeDBInstances', params, [...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_dbinstance(self, id, allocated_storage, instance_class, master_username, master_password, port=3306, engine='MySQL5.1', db_name=None, param_group=None,...
params = {'DBInstanceIdentifier': id, 'AllocatedStorage': allocated_storage, 'DBInstanceClass': instance_class, 'Engine': engine, 'MasterUsername': master_username, 'MasterUserPassword': master_password, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_dbinstance_read_replica(self, id, source_id, instance_class=None, port=3306, availability_zone=None, auto_minor_version_upgrade=None): """ Create a ne...
params = {'DBInstanceIdentifier' : id, 'SourceDBInstanceIdentifier' : source_id} if instance_class: params['DBInstanceClass'] = instance_class if port: params['Port'] = port if availability_zone: params['AvailabilityZone'] = availabi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify_dbinstance(self, id, param_group=None, security_groups=None, preferred_maintenance_window=None, master_password=None, allocated_storage=None, instance_...
params = {'DBInstanceIdentifier' : id} if param_group: params['DBParameterGroupName'] = param_group if security_groups: l = [] for group in security_groups: if isinstance(group, DBSecurityGroup): l.append(group.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 delete_dbinstance(self, id, skip_final_snapshot=False, final_snapshot_id=''): """ Delete an existing DBInstance. :type id: str :param id: Unique identifier f...
params = {'DBInstanceIdentifier' : id} if skip_final_snapshot: params['SkipFinalSnapshot'] = 'true' else: params['SkipFinalSnapshot'] = 'false' params['FinalDBSnapshotIdentifier'] = final_snapshot_id return self.get_object('DeleteDBInstance', params, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_dbparameter_groups(self, groupname=None, max_records=None, marker=None): """ Get all parameter groups associated with your account in a region. :type...
params = {} if groupname: params['DBParameterGroupName'] = groupname if max_records: params['MaxRecords'] = max_records if marker: params['Marker'] = marker return self.get_list('DescribeDBParameterGroups', params, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_dbparameters(self, groupname, source=None, max_records=None, marker=None): """ Get all parameters associated with a ParameterGroup :type groupname: s...
params = {'DBParameterGroupName' : groupname} if source: params['Source'] = source if max_records: params['MaxRecords'] = max_records if marker: params['Marker'] = marker pg = self.get_object('DescribeDBParameters', params, ParameterGroup) ...
<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_parameter_group(self, name, engine='MySQL5.1', description=''): """ Create a new dbparameter group for your account. :type name: string :param name: T...
params = {'DBParameterGroupName': name, 'DBParameterGroupFamily': engine, 'Description' : description} return self.get_object('CreateDBParameterGroup', params, ParameterGroup)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify_parameter_group(self, name, parameters=None): """ Modify a parameter group for your account. :type name: string :param name: The name of the new param...
params = {'DBParameterGroupName': name} for i in range(0, len(parameters)): parameter = parameters[i] parameter.merge(params, i+1) return self.get_list('ModifyDBParameterGroup', params, ParameterGroup, verb='POST')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_parameter_group(self, name, reset_all_params=False, parameters=None): """ Resets some or all of the parameters of a ParameterGroup to the default value...
params = {'DBParameterGroupName':name} if reset_all_params: params['ResetAllParameters'] = 'true' else: params['ResetAllParameters'] = 'false' for i in range(0, len(parameters)): parameter = parameters[i] parameter.merge(params...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorize_dbsecurity_group(self, group_name, cidr_ip=None, ec2_security_group_name=None, ec2_security_group_owner_id=None): """ Add a new rule to an existing...
params = {'DBSecurityGroupName':group_name} if ec2_security_group_name: params['EC2SecurityGroupName'] = ec2_security_group_name if ec2_security_group_owner_id: params['EC2SecurityGroupOwnerId'] = ec2_security_group_owner_id if cidr_ip: params['CIDRIP...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def revoke_dbsecurity_group(self, group_name, ec2_security_group_name=None, ec2_security_group_owner_id=None, cidr_ip=None): """ Remove an existing rule from an ...
params = {'DBSecurityGroupName':group_name} if ec2_security_group_name: params['EC2SecurityGroupName'] = ec2_security_group_name if ec2_security_group_owner_id: params['EC2SecurityGroupOwnerId'] = ec2_security_group_owner_id if cidr_ip: params['CIDRIP...
<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_all_dbsnapshots(self, snapshot_id=None, instance_id=None, max_records=None, marker=None): """ Get information about DB Snapshots. :type snapshot_id: str ...
params = {} if snapshot_id: params['DBSnapshotIdentifier'] = snapshot_id if instance_id: params['DBInstanceIdentifier'] = instance_id if max_records: params['MaxRecords'] = max_records if marker: params['Marker'] = marker r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_dbsnapshot(self, snapshot_id, dbinstance_id): """ Create a new DB snapshot. :type snapshot_id: string :param snapshot_id: The identifier for the DBSna...
params = {'DBSnapshotIdentifier' : snapshot_id, 'DBInstanceIdentifier' : dbinstance_id} return self.get_object('CreateDBSnapshot', params, DBSnapshot)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore_dbinstance_from_dbsnapshot(self, identifier, instance_id, instance_class, port=None, availability_zone=None): """ Create a new DBInstance from a DB s...
params = {'DBSnapshotIdentifier' : identifier, 'DBInstanceIdentifier' : instance_id, 'DBInstanceClass' : instance_class} if port: params['Port'] = port if availability_zone: params['AvailabilityZone'] = availability_zone 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 restore_dbinstance_from_point_in_time(self, source_instance_id, target_instance_id, use_latest=False, restore_time=None, dbinstance_class=None, port=None, ava...
params = {'SourceDBInstanceIdentifier' : source_instance_id, 'TargetDBInstanceIdentifier' : target_instance_id} if use_latest: params['UseLatestRestorableTime'] = 'true' elif restore_time: params['RestoreTime'] = restore_time.isoformat() if dbin...
<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_all_events(self, source_identifier=None, source_type=None, start_time=None, end_time=None, max_records=None, marker=None): """ Get information about even...
params = {} if source_identifier and source_type: params['SourceIdentifier'] = source_identifier params['SourceType'] = source_type if start_time: params['StartTime'] = start_time.isoformat() if end_time: params['EndTime'] = end_time.isofo...
<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(cls, filename, offset=None, encoding="iso-8859-1"): """Read an ID3v1 tag from a file."""
with fileutil.opened(filename, "rb") as file: if offset is None: file.seek(-128, 2) else: file.seek(offset) data = file.read(128) return cls.decode(data, encoding=encoding)
<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_acl(self, acl_or_str, key_name='', headers=None, version_id=None): """sets or changes a bucket's acl. We include a version_id argument to support a polym...
if isinstance(acl_or_str, Policy): raise InvalidAclError('Attempt to set S3 Policy on GS ACL') elif isinstance(acl_or_str, ACL): self.set_xml_acl(acl_or_str.to_xml(), key_name, headers=headers) else: self.set_canned_acl(acl_or_str, key_name, headers=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 set_def_acl(self, acl_or_str, key_name='', headers=None): """sets or changes a bucket's default object acl"""
if isinstance(acl_or_str, Policy): raise InvalidAclError('Attempt to set S3 Policy on GS ACL') elif isinstance(acl_or_str, ACL): self.set_def_xml_acl(acl_or_str.to_xml(), key_name, headers=headers) else: self.set_def_canned_acl(acl_or_str, key_name, headers=h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_acl(self, key_name='', headers=None, version_id=None): """returns a bucket's acl. We include a version_id argument to support a polymorphic interface for...
return self.get_acl_helper(key_name, headers, STANDARD_ACL)
<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_def_xml_acl(self, acl_str, key_name='', headers=None): """sets or changes a bucket's default object"""
return self.set_xml_acl(acl_str, key_name, headers, query_args=DEF_OBJ_ACL)
<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_snapshots(self): """ Returns a list of all completed snapshots for this volume ID. """
ec2 = self.get_ec2_connection() rs = ec2.get_all_snapshots() all_vols = [self.volume_id] + self.past_volume_ids snaps = [] for snapshot in rs: if snapshot.volume_id in all_vols: if snapshot.progress == '100%': snapshot.date = boto....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trim_snapshots(self, delete=False): """ Trim the number of snapshots for this volume. This method always keeps the oldest snapshot. It then uses the paramete...
snaps = self.get_snapshots() # Always keep the oldest and the newest if len(snaps) <= 2: return snaps snaps = snaps[1:-1] now = datetime.datetime.now(snaps[0].date.tzinfo) midnight = datetime.datetime(year=now.year, month=now.month, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_headers(self, token): """Generate auth headers"""
headers = {} token = self.encode_token(token) if self.config["header"]: headers[self.config["header"]] = token if self.config["cookie"]: headers["Set-Cookie"] = dump_cookie( self.config["cookie"], token, httponly=True, max_age=self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_expiration(self, token): """ Calculate token expiration return expiration if the token need to set expiration or refresh, otherwise return None. Ar...
if not token: return None now = datetime.utcnow() time_to_live = self.config["expiration"] if "exp" not in token: return now + timedelta(seconds=time_to_live) elif self.config["refresh"]: exp = datetime.utcfromtimestamp(token["exp"]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_token(self, token): """Decode Authorization token, return None if token invalid"""
key = current_app.secret_key if key is None: if current_app.debug: current_app.logger.debug("app.secret_key not set") return None try: return jwt.decode( token, key, algorithms=[self.config["algorithm"]], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_token(self, token): """Encode Authorization token, return bytes token"""
key = current_app.secret_key if key is None: raise RuntimeError( "please set app.secret_key before generate token") return jwt.encode(token, key, algorithm=self.config["algorithm"])
<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_for_credential_file(self): """ Checks for the existance of an AWS credential file. If the environment variable AWS_CREDENTIAL_FILE is set and points to...
if 'AWS_CREDENTIAL_FILE' in os.environ: path = os.environ['AWS_CREDENTIAL_FILE'] path = os.path.expanduser(path) path = os.path.expandvars(path) if os.path.isfile(path): fp = open(path) lines = fp.readlines() fp.clo...
<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_for_env_url(self): """ First checks to see if a url argument was explicitly passed in. If so, that will be used. If not, it checks for the existence of...
url = self.args.get('url', None) if url: del self.args['url'] if not url and self.EnvURL in os.environ: url = os.environ[self.EnvURL] if url: rslt = urlparse.urlparse(url) if 'is_secure' not in self.args: if rslt.scheme == ...
<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_objects_with_cmodel(self, cmodel_uri, type=None): """ Find objects in Fedora with the specified content model. :param cmodel_uri: content model URI (shou...
uris = self.risearch.get_subjects(modelns.hasModel, cmodel_uri) return [self.get_object(uri, type) for uri in uris]
<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_object(self, pid=None, type=None, create=None): """ Initialize a single object from Fedora, or create a new one, with the same Fedora configuration and c...
objtype = type or self.default_object_type if pid is None: if create is None: create = True else: if create is None: create = False return objtype(self.api, pid, create, default_pidspace=self.default_pidspa...
<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): """Create the write buffer and cache directory."""
if not self._sync and not hasattr(self, '_buffer'): self._buffer = {} if not os.path.exists(self.cache_dir): os.makedirs(self.cache_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self): """Delete the write buffer and cache directory."""
if not self._sync: del self._buffer shutil.rmtree(self.cache_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Sync the write buffer, then close the cache. If a closed :class:`FileCache` object's methods are called, a :exc:`ValueError` will be raised. ...
self.sync() self.sync = self.create = self.delete = self._closed self._write_to_file = self._read_to_file = self._closed self._key_to_filename = self._filename_to_key = self._closed self.__getitem__ = self.__setitem__ = self.__delitem__ = self._closed self.__iter__ = 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 sync(self): """Sync the write buffer with the cache files and clear the buffer. If the :class:`FileCache` object was opened with the optional ``'s'`` *flag* ...
if self._sync: return # opened in sync mode, so skip the manual sync self._sync = True for ekey in self._buffer: filename = self._key_to_filename(ekey) self._write_to_file(filename, self._buffer[ekey]) self._buffer.clear() self._sync = 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 _decode_key(self, key): """Decode key using hex_codec to retrieve the original key. Keys are returned as :class:`str` if serialization is enabled. Keys are r...
bkey = codecs.decode(key.encode(self._keyencoding), 'hex_codec') return bkey.decode(self._keyencoding) if self._serialize else bkey
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _all_filenames(self): """Return a list of absolute cache filenames"""
try: return [os.path.join(self.cache_dir, filename) for filename in os.listdir(self.cache_dir)] except (FileNotFoundError, OSError): 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 _all_keys(self): """Return a list of all encoded key names."""
file_keys = [self._filename_to_key(fn) for fn in self._all_filenames()] if self._sync: return set(file_keys) else: return set(file_keys + list(self._buffer))
<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_to_file(self, filename, bytesvalue): """Write bytesvalue to filename."""
fh, tmp = tempfile.mkstemp() with os.fdopen(fh, self._flag) as f: f.write(self._dumps(bytesvalue)) rename(tmp, filename) os.chmod(filename, self._mode)
<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_from_file(self, filename): """Read data from filename."""
try: with open(filename, 'rb') as f: return self._loads(f.read()) except (IOError, OSError): logger.warning('Error opening file: {}'.format(filename)) 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 getDatastreamDissemination(self, pid, dsID, asOfDateTime=None, stream=False, head=False, rqst_headers=None): """Get a single datastream on a Fedora object; o...
# /objects/{pid}/datastreams/{dsID}/content ? [asOfDateTime] [download] http_args = {} if rqst_headers is None: rqst_headers = {} if asOfDateTime: http_args['asOfDateTime'] = datetime_to_fedoratime(asOfDateTime) url = 'objects/%(pid)s/datastreams/%(dsid)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 getDissemination(self, pid, sdefPid, method, method_params=None): '''Get a service dissemination. .. NOTE: This method not available in REST API until Fedora 3.3 :param pid: object pid :param sDefPid: service definition pid :param method: service method 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 getObjectProfile(self, pid, asOfDateTime=None): """Get top-level information aboug a single Fedora object; optionally, retrieve information as of a particula...
# /objects/{pid} ? [format] [asOfDateTime] http_args = {} if asOfDateTime: http_args['asOfDateTime'] = datetime_to_fedoratime(asOfDateTime) http_args.update(self.format_xml) url = 'objects/%(pid)s' % {'pid': pid} return self.get(url, params=http_args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def listMethods(self, pid, sdefpid=None): '''List available service methods. :param pid: object pid :param sDefPid: service definition pid :rtype: :class:`requests.models.Response` ''' # /objects/{pid}/methods ? [format, datetime] # /objects/{pid}/methods/{sdefpi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def addDatastream(self, pid, dsID, dsLabel=None, mimeType=None, logMessage=None, controlGroup=None, dsLocation=None, altIDs=None, versionable=None, dsState=None, formatURI=None, checksumType=None, checksum=None, content=None): '''Add a new datastream to an existing object. On success, 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 export(self, pid, context=None, format=None, encoding=None, stream=False): '''Export an object to be migrated or archived. :param pid: object pid :param context: export context, one of: public, migrate, archive (default: public) :param format: export form...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getDatastream(self, pid, dsID, asOfDateTime=None, validateChecksum=False): """Get information about a single datastream on a Fedora object; optionally, get i...
# /objects/{pid}/datastreams/{dsID} ? [asOfDateTime] [format] [validateChecksum] http_args = {} if validateChecksum: # fedora only responds to lower-case validateChecksum option http_args['validateChecksum'] = str(validateChecksum).lower() if asOfDateTime: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getDatastreamHistory(self, pid, dsid, format=None): '''Get history information for a datastream. :param pid: object pid :param dsid: datastream id :param format: format :rtype: :class:`requests.models.Response` ''' http_args = {} if format 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 getRelationships(self, pid, subject=None, predicate=None, format=None): '''Get information about relationships on an object. Wrapper function for `Fedora REST API getRelationships <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-getRelationships>`_ :param pid: object ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ingest(self, text, logMessage=None): """Ingest a new object into Fedora. Returns the pid of the new object on success. Return response should have a status o...
# NOTE: ingest method supports additional options for # label/format/namespace/ownerId, etc - but we generally set # those in the foxml that is passed in http_args = {} if logMessage: http_args['logMessage'] = logMessage headers = {'Content-Type': 'text/xml...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def modifyObject(self, pid, label, ownerId, state, logMessage=None): '''Modify object properties. Returned response should have a status of 200 on succuss. :param pid: object pid :param label: object label :param ownerId: object owner :param state: object state ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def purgeDatastream(self, pid, dsID, startDT=None, endDT=None, logMessage=None, force=False): """Purge a datastream, or specific versions of a dastream, from a F...
# /objects/{pid}/datastreams/{dsID} ? [startDT] [endDT] [logMessage] [force] http_args = {} if logMessage: http_args['logMessage'] = logMessage if startDT: http_args['startDT'] = startDT if endDT: http_args['endDT'] = endDT if force: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def purgeObject(self, pid, logMessage=None): """Purge an object from Fedora. Returned response shoudl have a status of 200 on success; response content is a time...
http_args = {} if logMessage: http_args['logMessage'] = logMessage url = 'objects/%(pid)s' % {'pid': pid} return self.delete(url, params=http_args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def purgeRelationship(self, pid, subject, predicate, object, isLiteral=False, datatype=None): '''Remove a relationship from an object. Wrapper function for `Fedora REST API purgeRelationship <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-purgeRelationship>...