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_activities(self, activity_ids=None, max_records=50):
""" Get all activies for this group. """ |
return self.connection.get_all_activities(self, activity_ids,
max_records) |
<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_response(self, action, params, path='/', parent=None, verb='GET', list_marker='Set'):
""" Utility method to handle calls to IAM and parsing of responses.... |
if not parent:
parent = self
response = self.make_request(action, params, path, verb)
body = response.read()
boto.log.debug(body)
if response.status == 200:
e = boto.jsonresponse.Element(list_marker=list_marker,
p... |
<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, path_prefix='/', marker=None, max_items=None):
""" List the groups that have the specified path prefix. :type path_prefix: string :param... |
params = {}
if path_prefix:
params['PathPrefix'] = path_prefix
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListGroups', params,
list_marker='Group... |
<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_group(self, group_name, marker=None, max_items=None):
""" Return a list of users that are in the specified group. :type group_name: string :param group_n... |
params = {'GroupName' : group_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('GetGroup', params, list_marker='Users') |
<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_group_policies(self, group_name, marker=None, max_items=None):
""" List the names of the policies associated with the specified group. :type group_na... |
params = {'GroupName' : group_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListGroupPolicies', params,
list_marker='PolicyNames') |
<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_group_policy(self, group_name, policy_name):
""" Deletes the specified policy document for the specified group. :type group_name: string :param group_... |
params = {'GroupName' : group_name,
'PolicyName' : policy_name}
return self.get_response('DeleteGroupPolicy', 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 get_all_users(self, path_prefix='/', marker=None, max_items=None):
""" List the users that have the specified path prefix. :type path_prefix: string :param p... |
params = {'PathPrefix' : path_prefix}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListUsers', params, list_marker='Users') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user(self, user_name=None):
""" Retrieve information about the specified user. If the user_name is not specified, the user_name is determined implicitly ... |
params = {}
if user_name:
params['UserName'] = user_name
return self.get_response('GetUser', 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_user_policies(self, user_name, marker=None, max_items=None):
""" List the names of the policies associated with the specified user. :type user_name: ... |
params = {'UserName' : user_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListUserPolicies', params,
list_marker='PolicyNames') |
<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_user_policy(self, user_name, policy_name):
""" Deletes the specified policy document for the specified user. :type user_name: string :param user_name:... |
params = {'UserName' : user_name,
'PolicyName' : policy_name}
return self.get_response('DeleteUserPolicy', 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 get_groups_for_user(self, user_name, marker=None, max_items=None):
""" List the groups that a specified user belongs to. :type user_name: string :param user_... |
params = {'UserName' : user_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListGroupsForUser', params,
list_marker='Groups') |
<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_access_keys(self, user_name, marker=None, max_items=None):
""" Get all access keys associated with an account. :type user_name: string :param user_na... |
params = {'UserName' : user_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListAccessKeys', params,
list_marker='AccessKeyMetadata') |
<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_access_key(self, access_key_id, status, user_name=None):
""" Changes the status of the specified access key from Active to Inactive or vice versa. Thi... |
params = {'AccessKeyId' : access_key_id,
'Status' : status}
if user_name:
params['UserName'] = user_name
return self.get_response('UpdateAccessKey', 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_access_key(self, access_key_id, user_name=None):
""" Delete an access key associated with a user. If the user_name is not specified, it is determined ... |
params = {'AccessKeyId' : access_key_id}
if user_name:
params['UserName'] = user_name
return self.get_response('DeleteAccessKey', 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_signing_certs(self, marker=None, max_items=None, user_name=None):
""" Get all signing certificates associated with an account. If the user_name is no... |
params = {}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
if user_name:
params['UserName'] = user_name
return self.get_response('ListSigningCertificates',
params, list_marker... |
<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_signing_cert(self, cert_id, status, user_name=None):
""" Change the status of the specified signing certificate from Active to Inactive or vice versa.... |
params = {'CertificateId' : cert_id,
'Status' : status}
if user_name:
params['UserName'] = user_name
return self.get_response('UpdateSigningCertificate', 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 upload_signing_cert(self, cert_body, user_name=None):
""" Uploads an X.509 signing certificate and associates it with the specified user. If the user_name is... |
params = {'CertificateBody' : cert_body}
if user_name:
params['UserName'] = user_name
return self.get_response('UploadSigningCertificate', 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 delete_signing_cert(self, cert_id, user_name=None):
""" Delete a signing certificate associated with a user. If the user_name is not specified, it is determi... |
params = {'CertificateId' : cert_id}
if user_name:
params['UserName'] = user_name
return self.get_response('DeleteSigningCertificate', 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_server_certs(self, path_prefix='/', marker=None, max_items=None):
""" Lists the server certificates that have the specified path prefix. If none exis... |
params = {}
if path_prefix:
params['PathPrefix'] = path_prefix
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListServerCertificates',
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 upload_server_cert(self, cert_name, cert_body, private_key, cert_chain=None, path=None):
""" Uploads a server certificate entity for the AWS Account. The ser... |
params = {'ServerCertificateName' : cert_name,
'CertificateBody' : cert_body,
'PrivateKey' : private_key}
if cert_chain:
params['CertificateChain'] = cert_chain
if path:
params['Path'] = path
return self.get_response('UploadSer... |
<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_mfa_devices(self, user_name, marker=None, max_items=None):
""" Get all MFA devices associated with an account. :type user_name: string :param user_na... |
params = {'UserName' : user_name}
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
return self.get_response('ListMFADevices',
params, list_marker='MFADevices') |
<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_mfa_device(self, user_name, serial_number, auth_code_1, auth_code_2):
""" Enables the specified MFA device and associates it with the specified user. ... |
params = {'UserName' : user_name,
'SerialNumber' : serial_number,
'AuthenticationCode1' : auth_code_1,
'AuthenticationCode2' : auth_code_2}
return self.get_response('EnableMFADevice', 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 deactivate_mfa_device(self, user_name, serial_number):
""" Deactivates the specified MFA device and removes it from association with the user. :type user_nam... |
params = {'UserName' : user_name,
'SerialNumber' : serial_number}
return self.get_response('DeactivateMFADevice', 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 resync_mfa_device(self, user_name, serial_number, auth_code_1, auth_code_2):
""" Syncronizes the specified MFA device with the AWS servers. :type user_name: ... |
params = {'UserName' : user_name,
'SerialNumber' : serial_number,
'AuthenticationCode1' : auth_code_1,
'AuthenticationCode2' : auth_code_2}
return self.get_response('ResyncMFADevice', 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 update_login_profile(self, user_name, password):
""" Resets the password associated with the user's login profile. :type user_name: string :param user_name: ... |
params = {'UserName' : user_name,
'Password' : password}
return self.get_response('UpdateLoginProfile', 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_signin_url(self, service='ec2'):
""" Get the URL where IAM users can use their login profile to sign in to this account's console. :type service: string ... |
alias = self.get_account_alias()
if not alias:
raise Exception('No alias associated with this account. Please use iam.create_account_alias() first.')
return "https://%s.signin.aws.amazon.com/console/%s" % (alias, service) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next(self):
"""Special paging functionality""" |
if self.iter == None:
self.iter = iter(self.objs)
try:
return self.iter.next()
except StopIteration:
self.iter = None
self.objs = []
if int(self.page) < int(self.total_pages):
self.page += 1
self._connec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def xread(file, length):
"Read exactly length bytes from file; raise EOFError if file ends sooner."
data = file.read(length)
if len(data) != length:
raise EOFError
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def opened(filename, mode):
"Open filename, or do nothing if filename is already an open file object"
if isinstance(filename, str):
file = open(filename, mode)
try:
yield file
finally:
if not file.closed:
file.close()
else:
yield 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 replace_chunk(filename, offset, length, chunk, in_place=True, max_mem=5):
"""Replace length bytes of data with chunk, starting at offset. Any KeyboardInterru... |
with suppress_interrupt():
_replace_chunk(filename, offset, length, chunk, in_place, max_mem) |
<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_chunk(src, dst, length):
"Copy length bytes from file src to file dst."
BUFSIZE = 128 * 1024
while length > 0:
l = min(BUFSIZE, length)
buf = src.read(l)
assert len(buf) == l
dst.write(buf)
length -= l |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def symbolize(self, dsym_path, image_vmaddr, image_addr, instruction_addr, cpu_name, symbolize_inlined=False):
"""Symbolizes a single frame based on the informat... |
if self._closed:
raise RuntimeError('Symbolizer is closed')
dsym_path = normalize_dsym_path(dsym_path)
image_vmaddr = parse_addr(image_vmaddr)
if not image_vmaddr:
di = self._symbolizer.get_debug_info(dsym_path)
if di is not None:
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 list_tables(self, limit=None, start_table=None):
""" Return a list of table names associated with the current account and endpoint. :type limit: int :param l... |
data = {}
if limit:
data['Limit'] = limit
if start_table:
data['ExclusiveStartTableName'] = start_table
json_input = json.dumps(data)
return self.make_request('ListTables', json_input) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_table(self, table_name):
""" Returns information about the table including current state of the table, primary key schema and when the table was cre... |
data = {'TableName' : table_name}
json_input = json.dumps(data)
return self.make_request('DescribeTable', json_input) |
<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_table(self, table_name, schema, provisioned_throughput):
""" Add a new table to your account. The table name must be unique among those associated wit... |
data = {'TableName' : table_name,
'KeySchema' : schema,
'ProvisionedThroughput': provisioned_throughput}
json_input = json.dumps(data)
response_dict = self.make_request('CreateTable', json_input)
return response_dict |
<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_name):
""" Deletes the table and all of it's data. After this request the table will be in the DELETING state until DynamoDB complet... |
data = {'TableName': table_name}
json_input = json.dumps(data)
return self.make_request('DeleteTable', json_input) |
<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_item(self, table_name, key, attributes_to_get=None, consistent_read=False, object_hook=None):
""" Return a set of attributes for an item that matches the... |
data = {'TableName': table_name,
'Key': key}
if attributes_to_get:
data['AttributesToGet'] = attributes_to_get
if consistent_read:
data['ConsistentRead'] = True
json_input = json.dumps(data)
response = self.make_request('GetItem', json_inp... |
<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, table_name, key, expected=None, return_values=None, object_hook=None):
""" Delete an item and all of it's attributes by primary key. You ca... |
data = {'TableName' : table_name,
'Key' : key}
if expected:
data['Expected'] = expected
if return_values:
data['ReturnValues'] = return_values
json_input = json.dumps(data)
return self.make_request('DeleteItem', json_input,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self, table_name, hash_key_value, range_key_conditions=None, attributes_to_get=None, limit=None, consistent_read=False, scan_index_forward=True, exclusi... |
data = {'TableName': table_name,
'HashKeyValue': hash_key_value}
if range_key_conditions:
data['RangeKeyCondition'] = range_key_conditions
if attributes_to_get:
data['AttributesToGet'] = attributes_to_get
if limit:
data['Limit'] = limi... |
<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_name, scan_filter=None, attributes_to_get=None, limit=None, count=False, exclusive_start_key=None, object_hook=None):
""" Perform a scan of ... |
data = {'TableName': table_name}
if scan_filter:
data['ScanFilter'] = scan_filter
if attributes_to_get:
data['AttributesToGet'] = attributes_to_get
if limit:
data['Limit'] = limit
if count:
data['Count'] = True
if exclusive... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_bg(img, th=(240, 255)):
""" Removes similar colored background in the given image. :param img: Input image :param th: Tuple(2) Background color thresh... |
if img.size == 0:
return img
img = gray3(img)
# delete rows with complete background color
h, w = img.shape[:2]
i = 0
while i < h:
mask = np.logical_or(img[i, :, :] < th[0], img[i, :, :] > th[1])
if not mask.any():
img = np.delete(img, i, axis=0)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_bg(img, padding, color=COL_WHITE):
""" Adds a padding to the given image as background of specified color :param img: Input image. :param padding: consta... |
img = gray3(img)
h, w, d = img.shape
new_img = np.ones((h + 2*padding, w + 2*padding, d)) * color[:d]
new_img = new_img.astype(np.uint8)
set_img_box(new_img, (padding, padding, w, h), img)
return new_img |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def img_box(img, box):
""" Selects the sub-image inside the given box :param img: Image to crop from :param box: Box to crop from. Box can be either Box object o... |
if isinstance(box, tuple):
box = Box.from_tup(box)
if len(img.shape) == 3:
return img[box.y:box.y + box.height, box.x:box.x + box.width, :]
else:
return img[box.y:box.y + box.height, box.x:box.x + box.width] |
<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_text_img(img, text, pos, box=None, color=None, thickness=1, scale=1, vertical=False):
""" Adds the given text in the image. :param img: Input image :para... |
if color is None:
color = COL_WHITE
text = str(text)
top_left = pos
if box is not None:
top_left = box.move(pos).to_int().top_left()
if top_left[0] > img.shape[1]:
return
if vertical:
if box is not None:
h, w, d = box.height, box.width, 3
... |
<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_rect(img, box, color=None, thickness=1):
""" Draws a bounding box inside the image. :param img: Input image :param box: Box object that defines the bound... |
if color is None:
color = COL_GRAY
box = box.to_int()
cv.rectangle(img, box.top_left(), box.bottom_right(), color, thickness) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collage(imgs, size, padding=10, bg=COL_BLACK):
""" Constructs a collage of same-sized images with specified padding. :param imgs: Array of images. Either 1d-... |
# make 2d array
if not isinstance(imgs[0], list):
imgs = [imgs]
h, w = imgs[0][0].shape[:2]
nrows, ncols = size
nr, nc = nrows * h + (nrows-1) * padding, ncols * w + (ncols-1) * padding
res = np.ones((nr, nc, 3), dtype=np.uint8) * np.array(bg, dtype=np.uint8)
for r in range(nrows... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def each_img(img_dir):
""" Reads and iterates through each image file in the given directory """ |
for fname in utils.each_img(img_dir):
fname = os.path.join(img_dir, fname)
yield cv.imread(fname), fname |
<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_state(self, value, reason, data=None):
""" Temporarily sets the state of an alarm. :type value: str :param value: OK | ALARM | INSUFFICIENT_DATA :type re... |
return self.connection.set_alarm_state(self.name, reason, value, 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 add_alarm_action(self, action_arn=None):
""" Adds an alarm action, represented as an SNS topic, to this alarm. What do do when alarm is triggered. :type acti... |
if not action_arn:
return # Raise exception instead?
self.actions_enabled = 'true'
self.alarm_actions.append(action_arn) |
<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_insufficient_data_action(self, action_arn=None):
""" Adds an insufficient_data action, represented as an SNS topic, to this alarm. What to do when the in... |
if not action_arn:
return
self.actions_enabled = 'true'
self.insufficient_data_actions.append(action_arn) |
<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_ok_action(self, action_arn=None):
""" Adds an ok action, represented as an SNS topic, to this alarm. What to do when the ok state is reached. :type actio... |
if not action_arn:
return
self.actions_enabled = 'true'
self.ok_actions.append(action_arn) |
<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_session_token(self, duration=None, force_new=False):
""" Return a valid session token. Because retrieving new tokens from the Secure Token Service is a f... |
token_key = '%s:%s' % (self.region.name, self.provider.access_key)
token = self._check_token_cache(token_key, duration)
if force_new or not token:
boto.log.debug('fetching a new token for %s' % token_key)
self._mutex.acquire()
token = self._get_session_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 set_topic_attributes(self, topic, attr_name, attr_value):
""" Get attributes of a Topic :type topic: string :param topic: The ARN of the topic. :type attr_na... |
params = {'ContentType' : 'JSON',
'TopicArn' : topic,
'AttributeName' : attr_name,
'AttributeValue' : attr_value}
response = self.make_request('SetTopicAttributes', params, '/', 'GET')
body = response.read()
if response.status == 200... |
<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_permission(self, topic, label, account_ids, actions):
""" Adds a statement to a topic's access control policy, granting access for the specified AWS acco... |
params = {'ContentType' : 'JSON',
'TopicArn' : topic,
'Label' : label}
self.build_list_params(params, account_ids, 'AWSAccountId')
self.build_list_params(params, actions, 'ActionName')
response = self.make_request('AddPermission', params, '/', 'GET')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subscribe_sqs_queue(self, topic, queue):
""" Subscribe an SQS queue to a topic. This is convenience method that handles most of the complexity involved in us... |
t = queue.id.split('/')
q_arn = 'arn:aws:sqs:%s:%s:%s' % (queue.connection.region.name,
t[1], t[2])
resp = self.subscribe(topic, 'sqs', q_arn)
policy = queue.get_attributes('Policy')
if 'Version' not in policy:
policy['Versio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unsubscribe(self, subscription):
""" Allows endpoint owner to delete subscription. Confirmation message will be delivered. :type subscription: string :param ... |
params = {'ContentType' : 'JSON',
'SubscriptionArn' : subscription}
response = self.make_request('Unsubscribe', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
boto.log.error('%s %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 get_all_subscriptions(self, next_token=None):
""" Get list of all subscriptions. :type next_token: string :param next_token: Token returned by the previous c... |
params = {'ContentType' : 'JSON'}
if next_token:
params['NextToken'] = next_token
response = self.make_request('ListSubscriptions', params, '/', 'GET')
body = response.read()
if response.status == 200:
return json.loads(body)
else:
bot... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_caller_instruction(self, token_type="Unrestricted", transaction_id=None):
""" Set us up as a caller This will install a new caller_token into the FPS... |
response = self.install_payment_instruction("MyRole=='Caller';",
token_type=token_type,
transaction_id=transaction_id)
body = response.read()
if(response.status == 200):
rs = Resu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_marketplace_registration_url(self, returnURL, pipelineName, maxFixedFee=0.0, maxVariableFee=0.0, recipientPaysFee=True, **params):
""" Generate the URL ... |
# use the sandbox authorization endpoint if we're using the
# sandbox for API calls.
endpoint_host = 'authorize.payments.amazon.com'
if 'sandbox' in self.host:
endpoint_host = 'authorize.payments-sandbox.amazon.com'
base = "/cobranded-ui/actions/start"
para... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_url(self, returnURL, paymentReason, pipelineName, transactionAmount, **params):
""" Generate the URL with the signature required for a transaction """ |
# use the sandbox authorization endpoint if we're using the
# sandbox for API calls.
endpoint_host = 'authorize.payments.amazon.com'
if 'sandbox' in self.host:
endpoint_host = 'authorize.payments-sandbox.amazon.com'
base = "/cobranded-ui/actions/start"
para... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pay(self, transactionAmount, senderTokenId, recipientTokenId=None, callerTokenId=None, chargeFeeTo="Recipient", callerReference=None, senderReference=None, re... |
params = {}
params['SenderTokenId'] = senderTokenId
# this is for 2008-09-17 specification
params['TransactionAmount.Amount'] = str(transactionAmount)
params['TransactionAmount.CurrencyCode'] = "USD"
#params['TransactionAmount'] = str(transactionAmount)
params['C... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_transaction_status(self, transactionId):
""" Returns the status of a given transaction. """ |
params = {}
params['TransactionId'] = transactionId
response = self.make_request("GetTransactionStatus", params)
body = response.read()
if(response.status == 200):
rs = ResultSet()
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def settle(self, reserveTransactionId, transactionAmount=None):
""" Charges for a reserved payment. """ |
params = {}
params['ReserveTransactionId'] = reserveTransactionId
if(transactionAmount != None):
params['TransactionAmount'] = transactionAmount
response = self.make_request("Settle", params)
body = response.read()
if(response.status == 200):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refund(self, callerReference, transactionId, refundAmount=None, callerDescription=None):
""" Refund a transaction. This refunds the full amount by default un... |
params = {}
params['CallerReference'] = callerReference
params['TransactionId'] = transactionId
if(refundAmount != None):
params['RefundAmount'] = refundAmount
if(callerDescription != None):
params['CallerDescription'] = callerDescription
... |
<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_pdf(path_jinja2, template_name, path_outfile, template_kwargs=None):
'''Helper function for building a pdf from a latex jinja2 template
:param path_jinja2: the root directory for latex jinja2 templates
:param template_name: the relative path, to path_jinja2, to the desired
jinja2 Latex te... |
<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_html(path_jinja2, template_name, path_outfile, template_kwargs=None):
'''Helper function for building an html from a latex jinja2 template
:param path_jinja2: the root directory for latex jinja2 templates
:param template_name: the relative path, to path_jinja2, to the desired
jinja2 Latex... |
<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_docx(path_jinja2, template_name, path_outfile, template_kwargs=None):
'''Helper function for building a docx file from a latex jinja2 template
:param path_jinja2: the root directory for latex jinja2 templates
:param template_name: the relative path, to path_jinja2, to the desired
jinja2 L... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, uri=None, resources=None, index_only=False):
"""Read sitemap from a URI including handling sitemapindexes. If index_only is True then individual s... |
try:
fh = URLopener().open(uri)
self.num_files += 1
except IOError as e:
raise IOError(
"Failed to load sitemap/sitemapindex from %s (%s)" %
(uri, str(e)))
# Get the Content-Length if we can (works fine for local files)
... |
<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_component_sitemap( self, sitemapindex_uri, sitemap_uri, sitemap, sitemapindex_is_file):
"""Read a component sitemap of a Resource List with index. Each ... |
if (sitemapindex_is_file):
if (not self.is_file_uri(sitemap_uri)):
# Attempt to map URI to local file
remote_uri = sitemap_uri
sitemap_uri = self.mapper.src_to_dst(remote_uri)
self.logger.info(
"Mapped %s to local f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requires_multifile(self):
"""Return False or the number of component sitemaps required. In the case that no len() is available for self.resources then then s... |
if (self.max_sitemap_entries is None or
len(self) <= self.max_sitemap_entries):
return(False)
return(int(math.ceil(len(self) / float(self.max_sitemap_entries)))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_xml_index(self, basename="/tmp/sitemap.xml"):
"""Return a string of the index for a large list that is split. All we need to do is determine the number of... |
num_parts = self.requires_multifile()
if (not num_parts):
raise ListBaseIndexError(
"Request for sitemapindex for list with only %d entries when max_sitemap_entries is set to %s" %
(len(self), str(
self.max_sitemap_entries)))
index... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_xml_part(self, basename="/tmp/sitemap.xml", part_number=0):
"""Return a string of component sitemap number part_number. Used in the case of a large list t... |
if (not self.requires_multifile()):
raise ListBaseIndexError(
"Request for component sitemap for list with only %d entries when max_sitemap_entries is set to %s" %
(len(self), str(
self.max_sitemap_entries)))
start = part_number * self.max... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, basename='/tmp/sitemap.xml'):
"""Write one or a set of sitemap files to disk. resources is a ResourceContainer that may be an ResourceList or a C... |
# Access resources through iterator only
resources_iter = iter(self.resources)
(chunk, nxt) = self.get_resources_chunk(resources_iter)
s = self.new_sitemap()
if (nxt is not None):
# Have more than self.max_sitemap_entries => sitemapindex
if (not self.allo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index_as_xml(self):
"""XML serialization of this list taken to be sitemapindex entries.""" |
self.default_capability()
s = self.new_sitemap()
return s.resources_as_xml(self, sitemapindex=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_resources_chunk(self, resource_iter, first=None):
"""Return next chunk of resources from resource_iter, and next item. If first parameter is specified th... |
chunk = ListBase(md=self.md.copy(), ln=list(self.ln))
chunk.capability_name = self.capability_name
chunk.default_capability()
if (first is not None):
chunk.add(first)
for r in resource_iter:
chunk.add(r)
if (len(chunk) >= self.max_sitemap_entr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _basis_spline_factory(coef, degree, knots, der, ext):
"""Return a B-Spline given some coefficients.""" |
return functools.partial(interpolate.splev, tck=(knots, coef, degree), der=der, ext=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 derivatives_factory(cls, coef, degree, knots, ext, **kwargs):
""" Given some coefficients, return a the derivative of a B-spline. """ |
return cls._basis_spline_factory(coef, degree, knots, 1, 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 functions_factory(cls, coef, degree, knots, ext, **kwargs):
""" Given some coefficients, return a B-spline. """ |
return cls._basis_spline_factory(coef, degree, knots, 0, 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 set_master(self, url):
"""Set the master url that this object works with.""" |
m = urlparse(url)
self.master_scheme = m.scheme
self.master_netloc = m.netloc
self.master_path = os.path.dirname(m.path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_authority_over(self, url):
"""Return True of the current master has authority over url. In strict mode checks scheme, server and path. Otherwise checks j... |
s = urlparse(url)
if (s.scheme != self.master_scheme):
return(False)
if (s.netloc != self.master_netloc):
if (not s.netloc.endswith('.' + self.master_netloc)):
return(False)
# Maybe should allow parallel for 3+ components, eg. a.example.org,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def admin_permission_factory(admin_view):
"""Default factory for creating a permission for an admin. It tries to load a :class:`invenio_access.permissions.Permis... |
try:
pkg_resources.get_distribution('invenio-access')
from invenio_access import Permission
except pkg_resources.DistributionNotFound:
from flask_principal import Permission
return Permission(action_admin_access) |
<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_conns(cred, providers):
"""Collect node data asynchronously using gevent lib.""" |
cld_svc_map = {"aws": conn_aws,
"azure": conn_az,
"gcp": conn_gcp,
"alicloud": conn_ali}
sys.stdout.write("\rEstablishing Connections: ")
sys.stdout.flush()
busy_obj = busy_disp_on()
conn_fn = [[cld_svc_map[x.rstrip('1234567890')], cred[x], ... |
<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_data(conn_objs, providers):
"""Refresh node data using existing connection-objects.""" |
cld_svc_map = {"aws": nodes_aws,
"azure": nodes_az,
"gcp": nodes_gcp,
"alicloud": nodes_ali}
sys.stdout.write("\rCollecting Info: ")
sys.stdout.flush()
busy_obj = busy_disp_on()
collec_fn = [[cld_svc_map[x.rstrip('1234567890')], conn_objs[x]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def busy_disp_off(dobj):
"""Turn OFF busy_display to indicate completion.""" |
dobj.kill(block=False)
sys.stdout.write("\033[D \033[D")
sys.stdout.flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def busy_display():
"""Display animation to show activity.""" |
sys.stdout.write("\033[?25l") # cursor off
sys.stdout.flush()
for x in range(1800):
symb = ['\\', '|', '/', '-']
sys.stdout.write("\033[D{}".format(symb[x % 4]))
sys.stdout.flush()
gevent.sleep(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 conn_aws(cred, crid):
"""Establish connection to AWS service.""" |
driver = get_driver(Provider.EC2)
try:
aws_obj = driver(cred['aws_access_key_id'],
cred['aws_secret_access_key'],
region=cred['aws_default_region'])
except SSLError as e:
abort_err("\r SSL Error with AWS: {}".format(e))
except InvalidCre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nodes_aws(c_obj):
"""Get node objects from AWS.""" |
aws_nodes = []
try:
aws_nodes = c_obj.list_nodes()
except BaseHTTPError as e:
abort_err("\r HTTP Error with AWS: {}".format(e))
aws_nodes = adj_nodes_aws(aws_nodes)
return aws_nodes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adj_nodes_aws(aws_nodes):
"""Adjust details specific to AWS.""" |
for node in aws_nodes:
node.cloud = "aws"
node.cloud_disp = "AWS"
node.private_ips = ip_to_str(node.private_ips)
node.public_ips = ip_to_str(node.public_ips)
node.zone = node.extra['availability']
node.size = node.extra['instance_type']
node.type = node.extra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conn_az(cred, crid):
"""Establish connection to Azure service.""" |
driver = get_driver(Provider.AZURE_ARM)
try:
az_obj = driver(tenant_id=cred['az_tenant_id'],
subscription_id=cred['az_sub_id'],
key=cred['az_app_id'],
secret=cred['az_app_sec'])
except SSLError as e:
abort_err("\r SSL E... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nodes_az(c_obj):
"""Get node objects from Azure.""" |
az_nodes = []
try:
az_nodes = c_obj.list_nodes()
except BaseHTTPError as e:
abort_err("\r HTTP Error with Azure: {}".format(e))
az_nodes = adj_nodes_az(az_nodes)
return az_nodes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adj_nodes_az(az_nodes):
"""Adjust details specific to Azure.""" |
for node in az_nodes:
node.cloud = "azure"
node.cloud_disp = "Azure"
node.private_ips = ip_to_str(node.private_ips)
node.public_ips = ip_to_str(node.public_ips)
node.zone = node.extra['location']
node.size = node.extra['properties']['hardwareProfile']['vmSize']
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conn_gcp(cred, crid):
"""Establish connection to GCP.""" |
gcp_auth_type = cred.get('gcp_auth_type', "S")
if gcp_auth_type == "A": # Application Auth
gcp_crd_ia = CONFIG_DIR + ".gcp_libcloud_a_auth." + cred['gcp_proj_id']
gcp_crd = {'user_id': cred['gcp_client_id'],
'key': cred['gcp_client_sec'],
'project': cred['... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nodes_gcp(c_obj):
"""Get node objects from GCP.""" |
gcp_nodes = []
try:
gcp_nodes = c_obj.list_nodes(ex_use_disk_cache=True)
except BaseHTTPError as e:
abort_err("\r HTTP Error with GCP: {}".format(e))
gcp_nodes = adj_nodes_gcp(gcp_nodes)
return gcp_nodes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adj_nodes_gcp(gcp_nodes):
"""Adjust details specific to GCP.""" |
for node in gcp_nodes:
node.cloud = "gcp"
node.cloud_disp = "GCP"
node.private_ips = ip_to_str(node.private_ips)
node.public_ips = ip_to_str(node.public_ips)
node.zone = node.extra['zone'].name
return gcp_nodes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conn_ali(cred, crid):
"""Establish connection to AliCloud service.""" |
driver = get_driver(Provider.ALIYUN_ECS)
try:
ali_obj = driver(cred['ali_access_key_id'],
cred['ali_access_key_secret'],
region=cred['ali_region'])
except SSLError as e:
abort_err("\r SSL Error with AliCloud: {}".format(e))
except Invali... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nodes_ali(c_obj):
"""Get node objects from AliCloud.""" |
ali_nodes = []
try:
ali_nodes = c_obj.list_nodes()
except BaseHTTPError as e:
abort_err("\r HTTP Error with AliCloud: {}".format(e))
ali_nodes = adj_nodes_ali(ali_nodes)
return ali_nodes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adj_nodes_ali(ali_nodes):
"""Adjust details specific to AliCloud.""" |
for node in ali_nodes:
node.cloud = "alicloud"
node.cloud_disp = "AliCloud"
node.private_ips = ip_to_str(node.extra['vpc_attributes']['private_ip_address'])
node.public_ips = ip_to_str(node.public_ips)
node.zone = node.extra['zone_id']
node.size = node.extra['instanc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extendMarkdown(self, md, md_globals):
""" Add an instance of FigcaptionProcessor to BlockParser. """ |
# def_list = 'def_list' in md.registeredExtensions
md.parser.blockprocessors.add(
'figcaption', FigcaptionProcessor(md.parser), '<ulist') |
<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(self, uri=None, fh=None, str_data=None, **kwargs):
"""Parse a single XML document for this list. Accepts either a uri (uri or default if parameter not ... |
if (uri is not None):
try:
fh = URLopener().open(uri)
except IOError as e:
raise Exception(
"Failed to load sitemap/sitemapindex from %s (%s)" %
(uri, str(e)))
elif (str_data is not None):
fh = i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, basename="/tmp/resynclist.xml"):
"""Write a single sitemap or sitemapindex XML document. Must be overridden to support multi-file lists. """ |
self.default_capability()
fh = open(basename, 'w')
s = self.new_sitemap()
s.resources_as_xml(self, fh=fh, sitemapindex=self.sitemapindex)
fh.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.