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 get_reviewable_hits(self, hit_type=None, status='Reviewable', sort_by='Expiration', sort_direction='Ascending', page_size=10, page_number=1):
""" Retrieve th... |
params = {'Status' : status,
'SortProperty' : sort_by,
'SortDirection' : sort_direction,
'PageSize' : page_size,
'PageNumber' : page_number}
# Handle optional hit_type argument
if hit_type is not None:
params.u... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_hits(self):
""" Return all of a Requester's HITs Despite what search_hits says, it does not return all hits, but instead returns a page of hits. This... |
page_size = 100
search_rs = self.search_hits(page_size=page_size)
total_records = int(search_rs.TotalNumResults)
get_page_hits = lambda(page): self.search_hits(page_size=page_size, page_number=page)
page_nums = self._get_pages(page_size, total_records)
hit_sets = itertoo... |
<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_assignments(self, hit_id, status=None, sort_by='SubmitTime', sort_direction='Ascending', page_size=10, page_number=1, response_groups=None):
""" Retrieve... |
params = {'HITId' : hit_id,
'SortProperty' : sort_by,
'SortDirection' : sort_direction,
'PageSize' : page_size,
'PageNumber' : page_number}
if status is not None:
params['AssignmentStatus'] = status
# Handle o... |
<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_reviewing(self, hit_id, revert=None):
""" Update a HIT with a status of Reviewable to have a status of Reviewing, or reverts a Reviewing HIT back to the ... |
params = {'HITId' : hit_id,}
if revert:
params['Revert'] = revert
return self._process_request('SetHITAsReviewing', 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 disable_hit(self, hit_id, response_groups=None):
""" Remove a HIT from the Mechanical Turk marketplace, approves all submitted assignments that have not alre... |
params = {'HITId' : hit_id,}
# Handle optional response groups argument
if response_groups:
self.build_list_params(params, response_groups, 'ResponseGroup')
return self._process_request('DisableHIT', 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_help(self, about, help_type='Operation'):
""" Return information about the Mechanical Turk Service operations and response group NOTE - this is basically... |
params = {'About': about, 'HelpType': help_type,}
return self._process_request('Help', 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 grant_bonus(self, worker_id, assignment_id, bonus_price, reason):
""" Issues a payment of money from your account to a Worker. To be eligible for a bonus, th... |
params = bonus_price.get_as_params('BonusAmount', 1)
params['WorkerId'] = worker_id
params['AssignmentId'] = assignment_id
params['Reason'] = reason
return self._process_request('GrantBonus', 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 block_worker(self, worker_id, reason):
""" Block a worker from working on my tasks. """ |
params = {'WorkerId': worker_id, 'Reason': reason}
return self._process_request('BlockWorker', 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 unblock_worker(self, worker_id, reason):
""" Unblock a worker from working on my tasks. """ |
params = {'WorkerId': worker_id, 'Reason': reason}
return self._process_request('UnblockWorker', 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 notify_workers(self, worker_ids, subject, message_text):
""" Send a text message to workers. """ |
params = {'Subject' : subject,
'MessageText': message_text}
self.build_list_params(params, worker_ids, 'WorkerId')
return self._process_request('NotifyWorkers', 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_qualification_type(self, name, description, status, keywords=None, retry_delay=None, test=None, answer_key=None, answer_key_xml=None, test_duration=Non... |
params = {'Name' : name,
'Description' : description,
'QualificationTypeStatus' : status,
}
if retry_delay is not None:
params['RetryDelayInSeconds'] = retry_delay
if test is not None:
assert(isinstance(test, Questi... |
<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_keywords_as_string(keywords):
""" Returns a comma+space-separated string of keywords from either a list or a string """ |
if type(keywords) is list:
keywords = ', '.join(keywords)
if type(keywords) is str:
final_keywords = keywords
elif type(keywords) is unicode:
final_keywords = keywords.encode('utf-8')
elif keywords is None:
final_keywords = ""
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_price_as_price(reward):
""" Returns a Price data structure from either a float or a Price """ |
if isinstance(reward, Price):
final_price = reward
else:
final_price = Price(reward)
return final_price |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _has_expired(self):
""" Has this HIT expired yet? """ |
expired = False
if hasattr(self, 'Expiration'):
now = datetime.datetime.utcnow()
expiration = datetime.datetime.strptime(self.Expiration, '%Y-%m-%dT%H:%M:%SZ')
expired = (now >= expiration)
else:
raise ValueError("ERROR: Request for expired proper... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def versioned_bucket_lister(bucket, prefix='', delimiter='', key_marker='', version_id_marker='', headers=None):
""" A generator function for listing versions in... |
more_results = True
k = None
while more_results:
rs = bucket.get_all_versions(prefix=prefix, key_marker=key_marker,
version_id_marker=version_id_marker,
delimiter=delimiter, 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 multipart_upload_lister(bucket, key_marker='', upload_id_marker='', headers=None):
""" A generator function for listing multipart uploads in a bucket. """ |
more_results = True
k = None
while more_results:
rs = bucket.get_all_multipart_uploads(key_marker=key_marker,
upload_id_marker=upload_id_marker,
headers=headers)
for k in rs:
yield k
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_attributes(self, item_name, attributes, replace=True, expected_value=None):
""" Store attributes for a given item. :type item_name: string :param item_na... |
return self.connection.put_attributes(self, item_name, attributes,
replace, expected_value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def batch_put_attributes(self, items, replace=True):
""" Store attributes for multiple items. :type items: dict or dict-like object :param items: A dictionary-li... |
return self.connection.batch_put_attributes(self, items, replace) |
<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_attributes(self, item_name, attribute_name=None, consistent_read=False, item=None):
""" Retrieve attributes for a given item. :type item_name: string :pa... |
return self.connection.get_attributes(self, item_name, attribute_name,
consistent_read, item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_attributes(self, item_name, attributes=None, expected_values=None):
""" Delete attributes from a given item. :type item_name: string :param item_name:... |
return self.connection.delete_attributes(self, item_name, attributes,
expected_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 select(self, query='', next_token=None, consistent_read=False, max_items=None):
""" Returns a set of Attributes for item names within domain_name that match ... |
return SelectResultSet(self, query, max_items=max_items, next_token=next_token,
consistent_read=consistent_read) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_xml(self, doc):
"""Load this domain based on an XML document""" |
import xml.sax
handler = DomainDumpParser(self)
xml.sax.parse(doc, handler)
return handler |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isModified(self):
"""Check if either the datastream content or profile fields have changed and should be saved to Fedora. :rtype: boolean """ |
# NOTE: only check content digest if locally cached content is set
# (content already pulled or new content set); otherwise this
# results in pulling content down to checksum it !
return self.info_modified or \
self._content and self._content_digest() != self.digest |
<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, logmessage=None):
"""Save datastream content and any changed datastream profile information to Fedora. :rtype: boolean for success """ |
if self.as_of_date is not None:
raise RuntimeError('Saving is not implemented for datastream versions')
save_opts = {}
if self.info_modified:
if self.label:
save_opts['dsLabel'] = self.label
if self.mimetype:
save_opts['mimeTy... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def undo_last_save(self, logMessage=None):
"""Undo the last change made to the datastream content and profile, effectively reverting to the object state in Fedor... |
# NOTE: currently not clearing any of the object caches and backups
# of fedora content and datastream info, as it is unclear what (if anything)
# should be cleared
if self.versionable:
# if this is a versioned datastream, get datastream history
# and purge the ... |
<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_chunked_content(self, chunksize=4096):
'''Generator that returns the datastream content in chunks, so
larger datastreams can be used without reading the entire
contents into memory.'''
# get the datastream dissemination, but return the actual http response
r = self.obj.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 replace_uri(self, src, dest):
"""Replace a uri reference everywhere it appears in the graph with another one. It could appear as the subject, predicate, or o... |
# NB: The hypothetical statement <src> <src> <src> will be removed
# and re-added several times. The subject block will remove it and
# add <dest> <src> <src>. The predicate block will remove that and
# add <dest> <dest> <src>. The object block will then remove that
# and add <... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_ingest(self):
"""If the RDF datastream refers to the object by the default dummy uriref then we need to replace that dummy reference with a real one... |
# see also commentary on DigitalObject.DUMMY_URIREF
self.replace_uri(self.obj.DUMMY_URIREF, self.obj.uriref) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getDatastreamProfile(self, dsid, date=None):
"""Get information about a particular datastream belonging to this object. :param dsid: datastream id :rtype: :c... |
# NOTE: used by DatastreamObject
if self._create:
return None
r = self.api.getDatastream(self.pid, dsid, asOfDateTime=date)
return parse_xml_object(DatastreamProfile, r.content, r.url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _undo_save(self, datastreams, logMessage=None):
"""Takes a list of datastreams and a datetime, run undo save on all of them, and returns a list of the datast... |
return [ds for ds in datastreams if self.dscache[ds].undo_last_save(logMessage)] |
<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_datastreams(self):
""" Get all datastreams that belong to this object. Returns a dictionary; key is datastream id, value is an :class:`ObjectDatastream`... |
if self._create:
# FIXME: should we default to the datastreams defined in code?
return {}
else:
# NOTE: can be accessed as a cached class property via ds_list
r = self.api.listDatastreams(self.pid)
dsobj = parse_xml_object(ObjectDatastreams, 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 has_model(self, model):
""" Check if this object subscribes to the specified content model. :param model: URI for the content model, as a string (currently o... |
# TODO:
# - accept DigitalObject for model?
# - convert model pid to info:fedora/ form if not passed in that way?
try:
rels = self.rels_ext.content
except RequestFailed:
# if rels-ext can't be retrieved, confirm this object does not have a RELS-EXT
... |
<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_models(self):
""" Get a list of content models the object subscribes to. """ |
try:
rels = self.rels_ext.content
except RequestFailed:
# if rels-ext can't be retrieved, confirm this object does not have a RELS-EXT
# (in which case, it does not have any content models)
if "RELS-EXT" not in self.ds_list.keys():
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 delete_auto_scaling_group(self, name, force_delete=False):
""" Deletes the specified auto scaling group if the group has no instances and no scaling activiti... |
if(force_delete):
params = {'AutoScalingGroupName': name, 'ForceDelete': 'true'}
else:
params = {'AutoScalingGroupName': name}
return self.get_object('DeleteAutoScalingGroup', params, Request) |
<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_launch_configuration(self, launch_config):
""" Creates a new Launch Configuration. :type launch_config: :class:`boto.ec2.autoscale.launchconfig.Launch... |
params = {'ImageId': launch_config.image_id,
'LaunchConfigurationName': launch_config.name,
'InstanceType': launch_config.instance_type}
if launch_config.key_name:
params['KeyName'] = launch_config.key_name
if launch_config.user_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 create_scaling_policy(self, scaling_policy):
""" Creates a new Scaling Policy. :type scaling_policy: :class:`boto.ec2.autoscale.policy.ScalingPolicy` :param ... |
params = {'AdjustmentType': scaling_policy.adjustment_type,
'AutoScalingGroupName': scaling_policy.as_name,
'PolicyName': scaling_policy.name,
'ScalingAdjustment': scaling_policy.scaling_adjustment}
if scaling_policy.cooldown 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_all_groups(self, names=None, max_records=None, next_token=None):
""" Returns a full description of each Auto Scaling group in the given list. This includ... |
params = {}
if max_records:
params['MaxRecords'] = max_records
if next_token:
params['NextToken'] = next_token
if names:
self.build_list_params(params, names, 'AutoScalingGroupNames')
return self.get_list('DescribeAutoScalingGroups', 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_launch_configurations(self, **kwargs):
""" Returns a full description of the launch configurations given the specified names. If no names are specifi... |
params = {}
max_records = kwargs.get('max_records', None)
names = kwargs.get('names', None)
if max_records is not None:
params['MaxRecords'] = max_records
if names:
self.build_list_params(params, names, 'LaunchConfigurationNames')
next_token = kwa... |
<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_activities(self, autoscale_group, activity_ids=None, max_records=None, next_token=None):
""" Get all activities for the given autoscaling group. This... |
name = autoscale_group
if isinstance(autoscale_group, AutoScalingGroup):
name = autoscale_group.name
params = {'AutoScalingGroupName' : name}
if max_records:
params['MaxRecords'] = max_records
if next_token:
params['NextToken'] = next_token
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_scheduled_action(self, scheduled_action_name, autoscale_group=None):
""" Deletes a previously scheduled action. :type scheduled_action_name: str :para... |
params = {'ScheduledActionName': scheduled_action_name}
if autoscale_group:
params['AutoScalingGroupName'] = autoscale_group
return self.get_status('DeleteScheduledAction', 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 terminate_instance(self, instance_id, decrement_capacity=True):
""" Terminates the specified instance. The desired group size can also be adjusted, if desire... |
params = {'InstanceId': instance_id}
if decrement_capacity:
params['ShouldDecrementDesiredCapacity'] = 'true'
else:
params['ShouldDecrementDesiredCapacity'] = 'false'
return self.get_object('TerminateInstanceInAutoScalingGroup', 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 delete_policy(self, policy_name, autoscale_group=None):
""" Delete a policy. :type policy_name: str :param policy_name: The name or ARN of the policy to dele... |
params = {'PolicyName': policy_name}
if autoscale_group:
params['AutoScalingGroupName'] = autoscale_group
return self.get_status('DeletePolicy', 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_autoscaling_instances(self, instance_ids=None, max_records=None, next_token=None):
""" Returns a description of each Auto Scaling instance in the ins... |
params = {}
if instance_ids:
self.build_list_params(params, instance_ids, 'InstanceIds')
if max_records:
params['MaxRecords'] = max_records
if next_token:
params['NextToken'] = next_token
return self.get_list('DescribeAutoScalingInstances',
... |
<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_policies(self, as_group=None, policy_names=None, max_records=None, next_token=None):
""" Returns descriptions of what each policy does. This action s... |
params = {}
if as_group:
params['AutoScalingGroupName'] = as_group
if policy_names:
self.build_list_params(params, policy_names, 'PolicyNames')
if max_records:
params['MaxRecords'] = max_records
if next_token:
params['NextToken'] =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def suspend_processes(self, as_group, scaling_processes=None):
""" Suspends Auto Scaling processes for an Auto Scaling group. :type as_group: string :param as_gr... |
params = {'AutoScalingGroupName': as_group}
if scaling_processes:
self.build_list_params(params, scaling_processes, 'ScalingProcesses')
return self.get_status('SuspendProcesses', 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 resume_processes(self, as_group, scaling_processes=None):
""" Resumes Auto Scaling processes for an Auto Scaling group. :type as_group: string :param as_grou... |
params = {'AutoScalingGroupName': as_group}
if scaling_processes:
self.build_list_params(params, scaling_processes, 'ScalingProcesses')
return self.get_status('ResumeProcesses', 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_scheduled_group_action(self, as_group, name, time, desired_capacity=None, min_size=None, max_size=None):
""" Creates a scheduled scaling action for a ... |
params = {'AutoScalingGroupName': as_group,
'ScheduledActionName': name,
'Time': time.isoformat()}
if desired_capacity is not None:
params['DesiredCapacity'] = desired_capacity
if min_size is not None:
params['MinSize'] = min_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 disable_metrics_collection(self, as_group, metrics=None):
""" Disables monitoring of group metrics for the Auto Scaling group specified in AutoScalingGroupNa... |
params = {'AutoScalingGroupName': as_group}
if metrics:
self.build_list_params(params, metrics, 'Metrics')
return self.get_status('DisableMetricsCollection', 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 enable_metrics_collection(self, as_group, granularity, metrics=None):
""" Enables monitoring of group metrics for the Auto Scaling group specified in AutoSca... |
params = {'AutoScalingGroupName': as_group,
'Granularity': granularity}
if metrics:
self.build_list_params(params, metrics, 'Metrics')
return self.get_status('EnableMetricsCollection', 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 set_instance_health(self, instance_id, health_status, should_respect_grace_period=True):
""" Explicitly set the health status of an instance. :type instance_... |
params = {'InstanceId': instance_id,
'HealthStatus': health_status}
if should_respect_grace_period:
params['ShouldRespectGracePeriod'] = 'true'
else:
params['ShouldRespectGracePeriod'] = 'false'
return self.get_status('SetInstanceHealth', 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_tags(self, filters=None, max_records=None, next_token=None):
""" Lists the Auto Scaling group tags. This action supports pagination by returning a to... |
params = {}
if max_records:
params['MaxRecords'] = max_records
if next_token:
params['NextToken'] = next_token
return self.get_list('DescribeTags', params,
[('member', Tag)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_or_update_tags(self, tags):
""" Creates new tags or updates existing tags for an Auto Scaling group. :type tags: List of :class:`boto.ec2.autoscale.ta... |
params = {}
for i, tag in enumerate(tags):
tag.build_params(params, i+1)
return self.get_status('CreateOrUpdateTags', params, 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 open_read(self, headers=None, query_args='', override_num_retries=None, response_headers=None):
""" Open this key for reading :type headers: dict :param head... |
if self.resp == None:
self.mode = 'r'
provider = self.bucket.connection.provider
self.resp = self.bucket.connection.make_request(
'GET', self.bucket.name, self.name, headers,
query_args=query_args,
override_num_retries=overrid... |
<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_storage_class(self, new_storage_class, dst_bucket=None):
""" Change the storage class of an existing key. Depending on whether a different destination... |
if new_storage_class == 'STANDARD':
return self.copy(self.bucket.name, self.name,
reduced_redundancy=False, preserve_acl=True)
elif new_storage_class == 'REDUCED_REDUNDANCY':
return self.copy(self.bucket.name, self.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 copy(self, dst_bucket, dst_key, metadata=None, reduced_redundancy=False, preserve_acl=False, encrypt_key=False):
""" Copy this Key to another bucket. :type d... |
dst_bucket = self.bucket.connection.lookup(dst_bucket)
if reduced_redundancy:
storage_class = 'REDUCED_REDUNDANCY'
else:
storage_class = self.storage_class
return dst_bucket.copy_key(dst_key, self.bucket.name,
self.name, metadat... |
<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 this key from S3 """ |
return self.bucket.delete_key(self.name, version_id=self.version_id) |
<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_url(self, expires_in, method='GET', headers=None, query_auth=True, force_http=False, response_headers=None, expires_in_absolute=False):
""" Generate... |
return self.bucket.connection.generate_url(expires_in, method,
self.bucket.name, self.name,
headers, query_auth,
force_http,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_contents_from_filename(self, filename, headers=None, replace=True, cb=None, num_cb=10, policy=None, md5=None, reduced_redundancy=False, encrypt_key=False)... |
fp = open(filename, 'rb')
self.set_contents_from_file(fp, headers, replace, cb, num_cb,
policy, md5, reduced_redundancy,
encrypt_key=encrypt_key)
fp.close() |
<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_contents_to_file(self, fp, headers=None, cb=None, num_cb=10, torrent=False, version_id=None, res_download_handler=None, response_headers=None):
""" Retri... |
if self.bucket != None:
if res_download_handler:
res_download_handler.get_file(self, fp, headers, cb, num_cb,
torrent=torrent,
version_id=version_id)
else:
self.ge... |
<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_email_grant(self, permission, email_address, headers=None):
""" Convenience method that provides a quick way to add an email grant to a key. This method ... |
policy = self.get_acl(headers=headers)
policy.acl.add_email_grant(permission, email_address)
self.set_acl(policy, 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 add_user_grant(self, permission, user_id, headers=None, display_name=None):
""" Convenience method that provides a quick way to add a canonical user grant to... |
policy = self.get_acl()
policy.acl.add_user_grant(permission, user_id,
display_name=display_name)
self.set_acl(policy, 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 get_obj(self, name):
""" Returns the AWS object associated with a given option. The heuristics used are a bit lame. If the option name contains the word 'buc... |
val = self.get(name)
if not val:
return None
if name.find('queue') >= 0:
obj = boto.lookup('sqs', val)
if obj:
obj.set_message_class(ServiceMessage)
elif name.find('bucket') >= 0:
obj = boto.lookup('s3', val)
elif n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export_json(data, status, headers):
""" Creates a JSON response JSON content is encoded by utf-8, not unicode escape. Args: data: any type object that can du... |
dumped = json.dumps(data, ensure_ascii=False)
resp = current_app.response_class(
dumped, status=status, headers=headers,
content_type='application/json; charset=utf-8')
return resp |
<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(self, cidr_ip=None, ec2_group=None):
""" Add a new rule to this DBSecurity group. You need to pass in either a CIDR block to authorize or and EC2 S... |
if isinstance(ec2_group, SecurityGroup):
group_name = ec2_group.name
group_owner_id = ec2_group.owner_id
else:
group_name = None
group_owner_id = None
return self.connection.authorize_dbsecurity_group(self.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 revoke(self, cidr_ip=None, ec2_group=None):
""" Revoke access to a CIDR range or EC2 SecurityGroup. You need to pass in either a CIDR block or an EC2 Securit... |
if isinstance(ec2_group, SecurityGroup):
group_name = ec2_group.name
group_owner_id = ec2_group.owner_id
return self.connection.revoke_dbsecurity_group(
self.name,
ec2_security_group_name=group_name,
ec2_security_group_owner_id... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def part_lister(mpupload, part_number_marker=None):
""" A generator function for listing parts of a multipart upload. """ |
more_results = True
part = None
while more_results:
parts = mpupload.get_all_parts(None, part_number_marker)
for part in parts:
yield part
part_number_marker = mpupload.next_part_number_marker
more_results= mpupload.is_truncated |
<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_parts(self, max_parts=None, part_number_marker=None):
""" Return the uploaded parts of this MultiPart Upload. This is a lower-level method that requi... |
self._parts = []
query_args = 'uploadId=%s' % self.id
if max_parts:
query_args += '&max-parts=%d' % max_parts
if part_number_marker:
query_args += '&part-number-marker=%s' % part_number_marker
response = self.bucket.connection.make_request('GET', self.buc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_part_from_key(self, src_bucket_name, src_key_name, part_num, start=None, end=None):
""" Copy another part of this MultiPart Upload. :type src_bucket_nam... |
if part_num < 1:
raise ValueError('Part numbers must be greater than zero')
query_args = 'uploadId=%s&partNumber=%d' % (self.id, part_num)
if start is not None and end is not None:
rng = 'bytes=%s-%s' % (start, end)
provider = self.bucket.connection.provider
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complete_upload(self):
""" Complete the MultiPart Upload operation. This method should be called when all parts of the file have been successfully uploaded t... |
xml = self.to_xml()
return self.bucket.complete_multipart_upload(self.key_name,
self.id, 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 __placeSellOrder(self, tick):
''' place sell order '''
if self.__position < 0:
return
share=self.__position
order=Order(accountId=self.__strategy.accountId,
action=Action.SELL,
is_market=True,
sym... |
<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_callback_url(self, provider):
"""Return the callback url for this provider.""" |
info = self.model._meta.app_label, self.model._meta.model_name
return reverse('admin:%s_%s_callback' % info, kwargs={'provider': provider.id}) |
<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_login_redirect(self, provider, account):
"""Return url to redirect authenticated users.""" |
info = self.model._meta.app_label, self.model._meta.model_name
# inline import to prevent circular imports.
from .admin import PRESERVED_FILTERS_SESSION_KEY
preserved_filters = self.request.session.get(PRESERVED_FILTERS_SESSION_KEY, None)
redirect_url = reverse('admin:%s_%s_chan... |
<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_redirect(self, provider, reason):
"""Return url to redirect on login failure.""" |
info = self.model._meta.app_label, self.model._meta.model_name
return reverse('admin:%s_%s_changelist' % info) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_login_failure(self, provider, reason):
"""Message user and redirect on error.""" |
logger.error('Authenication Failure: {0}'.format(reason))
messages.error(self.request, 'Authenication Failed. Please try again')
return redirect(self.get_error_redirect(provider, reason)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sshclient_from_instance(instance, ssh_key_file, host_key_file='~/.ssh/known_hosts', user_name='root', ssh_pwd=None):
""" Create and return an SSHClient objec... |
s = FakeServer(instance, ssh_key_file)
return SSHClient(s, host_key_file, user_name, ssh_pwd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open(self, filename, mode='r', bufsize=-1):
""" Open a file on the remote system and return a file-like object. """ |
sftp_client = self.open_sftp()
return sftp_client.open(filename, mode, bufsize) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, command):
""" Execute a command on the remote host. Return a tuple containing an integer status and a two strings, the first containing stdout and ... |
boto.log.debug('running:%s on %s' % (command, self.server.instance_id))
status = 0
try:
t = self._ssh_client.exec_command(command)
except paramiko.SSHException:
status = 1
std_out = t[1].read()
std_err = t[2].read()
t[0].close()
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 run_pty(self, command):
""" Execute a command on the remote host with a pseudo-terminal. Returns a string containing the output of the command. """ |
boto.log.debug('running:%s on %s' % (command, self.server.instance_id))
channel = self._ssh_client.get_transport().open_session()
channel.get_pty()
channel.exec_command(command)
return channel.recv(1024) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def factory(feature):
""" Factory to choose feature extractor :param feature: name of the feature :return: Feature extractor function """ |
if feature == 'hog':
return hog
elif feature == 'deep':
return deep
elif feature == 'gray':
return gray
elif feature == 'lab':
return lab
elif feature == 'luv':
return luv
elif feature == 'hsv':
return hsv
elif feature == 'hls':
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 hog(img, options=None):
""" HOG feature extractor. :param img: :param options: :return: HOG Feature for given image The output will have channels same as num... |
op = _DEF_HOG_OPTS.copy()
if options is not None:
op.update(options)
img = gray(img)
img_fd = skimage.feature.hog(img,
orientations=op['orientations'],
pixels_per_cell=op['cell_size'],
cells_per_... |
<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_file(self, fp, headers=None, cb=None, num_cb=10, torrent=False):
""" Retrieves a file from a Key :type fp: file :param fp: File pointer to put the data i... |
if self.key_type & self.KEY_STREAM_READABLE:
raise BotoClientError('Stream is not Readable')
elif self.key_type & self.KEY_STREAM_WRITABLE:
key_file = self.fp
else:
key_file = open(self.full_path, 'rb')
try:
shutil.copyfileobj(key_file, 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 set_contents_from_file(self, fp, headers=None, replace=True, cb=None, num_cb=10, policy=None, md5=None):
""" Store an object in a file using the name of the ... |
if self.key_type & self.KEY_STREAM_WRITABLE:
raise BotoClientError('Stream is not writable')
elif self.key_type & self.KEY_STREAM_READABLE:
key_file = self.fp
else:
if not replace and os.path.exists(self.full_path):
return
key_file... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_contents_as_string(self, headers=None, cb=None, num_cb=10, torrent=False):
""" Retrieve file data from the Key, and return contents as a string. :type he... |
fp = StringIO.StringIO()
self.get_contents_to_file(fp)
return fp.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 enclosing_box(boxes):
""" Finds a new box that exactly encloses all the given boxes. :param boxes: Array of Box objects :return: Box object that encloses all... |
x = max(0, min([box.x for box in boxes]))
y = max(0, min([box.y for box in boxes]))
x2 = max([box.bottom_right()[0] for box in boxes])
y2 = max([box.bottom_right()[1] for box in boxes])
return Box.from_xy(x, y, x2, y2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def left_most(boxes):
""" Finds the left most box out of the given boxes. :param boxes: Array of Box objects :return: The left-most Box object """ |
x_list = [(box.x, box) for box in boxes]
x_list.sort()
return x_list[0][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 right_most(boxes):
""" Finds the right most box out of the given boxes. :param boxes: Array of Box objects :return: The right-most Box object """ |
x_list = [(box.x, box) for box in boxes]
x_list.sort()
return x_list[-1][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 intersection_box(box1, box2):
""" Finds an intersection box that is common to both given boxes. :param box1: Box object 1 :param box2: Box object 2 :return: ... |
b1_x2, b1_y2 = box1.bottom_right()
b2_x2, b2_y2 = box2.bottom_right()
x, y = max(box1.x, box2.x), max(box1.y, box2.y)
x2, y2 = min(b1_x2, b2_x2), min(b1_y2, b2_y2)
w, h = max(0, x2-x), max(0, y2-y)
return Box(x, y, w, 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 overlaps(self, box, th=0.0001):
""" Check whether this box and given box overlaps at least by given threshold. :param box: Box to compare with :param th: Thr... |
int_box = Box.intersection_box(self, box)
small_box = self if self.smaller(box) else box
return True if int_box.area() / small_box.area() >= th 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 expand(self, percentage):
""" Expands the box co-ordinates by given percentage on four sides. Ignores negative values. :param percentage: Percentage to expan... |
ex_h = math.ceil(self.height * percentage / 100)
ex_w = math.ceil(self.width * percentage / 100)
x = max(0, self.x - ex_w)
y = max(0, self.y - ex_h)
x2 = self.x + self.width + ex_w
y2 = self.y + self.height + ex_h
return Box.from_xy(x, y, x2, y2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def padding(self, px):
""" Add padding around four sides of box :param px: padding value in pixels. Can be an array in the format of [top right bottom left] or s... |
# if px is not an array, have equal padding all sides
if not isinstance(px, list):
px = [px] * 4
x = max(0, self.x - px[3])
y = max(0, self.y - px[0])
x2 = self.x + self.width + px[1]
y2 = self.y + self.height + px[2]
return Box.from_xy(x, y, x2, y2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pos_by_percent(self, x_percent, y_percent):
""" Finds a point inside the box that is exactly at the given percentage place. :param x_percent: how much percen... |
x = round(x_percent * self.width)
y = round(y_percent * self.height)
return int(x), int(y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pip_version(self):
"""Version of installed pip.""" |
if not self._pip_exists:
return None
if not hasattr(self, '_pip_version'):
# don't call `self._execute_pip` here as that method calls this one
output = self._execute(self._pip + ['-V'], log=False).split()[1]
self._pip_version = tuple([int(n) for n in outp... |
<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):
"""Executes `virtualenv` to create a new environment.""" |
if self.readonly:
raise VirtualenvReadonlyException()
args = ['virtualenv']
if self.system_site_packages:
args.append('--system-site-packages')
if self.python is None:
args.append(self.name)
else:
args.extend(['-p', self.python, se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _execute_pip(self, args, log=True):
""" Executes pip commands. :param args: Arguments to pass to pip (list[str]) :param log: Log the output to a file [defaul... |
# Copy the pip calling arguments so they can be extended
exec_args = list(self._pip)
# Older versions of pip don't support the version check argument.
# Fixes https://github.com/sjkingo/virtualenv-api/issues/35
if self.pip_version[0] >= 6:
exec_args.append('--disab... |
<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(self, args, log=True):
"""Executes the given command inside the environment and returns the output.""" |
if not self._ready:
self.open_or_create()
output = ''
error = ''
try:
proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
returncode = proc.returncod... |
<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_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True.""" |
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_text(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 _write_to_error(self, s, truncate=False):
"""Writes the given output to the error file, appending unless `truncate` is True.""" |
# if truncate is True, set write mode to truncate
with open(self._errorfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(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 _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be used as a naive way to verify that the environment is installed.""" |
return os.path.isfile(os.path.join(self.path, 'bin', 'pip')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upgrade(self, package, force=False):
"""Shortcut method to upgrade a package. If `force` is set to True, the package and all of its dependencies will be rein... |
self.install(package, upgrade=True, force=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 upgrade_all(self):
""" Upgrades all installed packages to their latest versions. """ |
for pkg in self.installed_package_names:
self.install(pkg, upgrade=True) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.