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 create_bucket(self, bucket_name, headers=None, location=Location.DEFAULT, policy=None): """ Creates a new located bucket. By default it's in the USA. You can pass Location.EU to create an European bucket. :type bucket_name: string :param bucket_name: The name of the new bucket :type headers: dict :param headers: Additional headers to pass along with the request to AWS. :type location: :class:`boto.s3.connection.Location` :param location: The location of the new bucket :type policy: :class:`boto.s3.acl.CannedACLStrings` :param policy: A canned ACL policy that will be applied to the new key in S3. """
check_lowercase_bucketname(bucket_name) if policy: if headers: headers[self.provider.acl_header] = policy else: headers = {self.provider.acl_header : policy} if location == Location.DEFAULT: data = '' else: data = '<CreateBucketConstraint><LocationConstraint>' + \ location + '</LocationConstraint></CreateBucketConstraint>' response = self.make_request('PUT', bucket_name, headers=headers, data=data) body = response.read() if response.status == 409: raise self.provider.storage_create_error( response.status, response.reason, body) if response.status == 200: return self.bucket_class(self, bucket_name) else: raise self.provider.storage_response_error( response.status, response.reason, 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 gen_decode(iterable): "A generator for de-unsynchronizing a byte iterable." sync = False for b in iterable: if sync and b & 0xE0: warn("Invalid unsynched data", Warning) if not (sync and b == 0x00): yield b sync = (b == 0xFF)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def gen_encode(data): "A generator for unsynchronizing a byte iterable." sync = False for b in data: if sync and (b == 0x00 or b & 0xE0): yield 0x00 # Insert sync char yield b sync = (b == 0xFF) if sync: yield 0x00
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def decode(data): "Decodes a syncsafe integer" value = 0 for b in data: if b > 127: # iTunes bug raise ValueError("Invalid syncsafe integer") value <<= 7 value += b return 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 encode(i, *, width=-1): """Encodes a nonnegative integer into syncsafe format When width > 0, then len(result) == width When width < 0, then len(result) >= abs(width) """
if i < 0: raise ValueError("value is negative") assert width != 0 data = bytearray() while i: data.append(i & 127) i >>= 7 if width > 0 and len(data) > width: raise ValueError("Integer too large") if len(data) < abs(width): data.extend([0] * (abs(width) - len(data))) data.reverse() 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 new_message(self, body=''): """ Create new message of appropriate class. :type body: message body :param body: The body of the newly created message (optional). :rtype: :class:`boto.sqs.message.Message` :return: A new Message object """
m = self.message_class(self, body) m.queue = self return m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self, page_size=10, vtimeout=10): """Utility function to remove all messages from a queue"""
n = 0 l = self.get_messages(page_size, vtimeout) while l: for m in l: self.delete_message(m) n += 1 l = self.get_messages(page_size, vtimeout) return 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 save_to_file(self, fp, sep='\n'): """ Read all messages from the queue and persist them to file-like object. Messages are written to the file and the 'sep' string is written in between messages. Messages are deleted from the queue after being written to the file. Returns the number of messages saved. """
n = 0 m = self.read() while m: n += 1 fp.write(m.get_body()) if sep: fp.write(sep) self.delete_message(m) m = self.read() return 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 save_to_filename(self, file_name, sep='\n'): """ Read all messages from the queue and persist them to local file. Messages are written to the file and the 'sep' string is written in between messages. Messages are deleted from the queue after being written to the file. Returns the number of messages saved. """
fp = open(file_name, 'wb') n = self.save_to_file(fp, sep) fp.close() return 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 load_from_s3(self, bucket, prefix=None): """ Load messages previously saved to S3. """
n = 0 if prefix: prefix = '%s/' % prefix else: prefix = '%s/' % self.id[1:] rs = bucket.list(prefix=prefix) for key in rs: n += 1 m = self.new_message(key.get_contents_as_string()) self.write(m) return 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 load_from_file(self, fp, sep='\n'): """Utility function to load messages from a file-like object to a queue"""
n = 0 body = '' l = fp.readline() while l: if l == sep: m = Message(self, body) self.write(m) n += 1 print 'writing message %d' % n body = '' else: body = body + l l = fp.readline() return 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 load_from_filename(self, file_name, sep='\n'): """Utility function to load messages from a local filename to a queue"""
fp = open(file_name, 'rb') n = self.load_from_file(fp, sep) fp.close() return 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 echo_event(data): """Echo a json dump of an object using click"""
return click.echo(json.dumps(data, sort_keys=True, indent=2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(ctx, host, port, transport_type, timeout, ca_certs): """Connects to a Riemann server to send events or query the index By default, will attempt to contact Riemann on localhost:5555 over TCP. The RIEMANN_HOST and RIEMANN_PORT environment variables can be used to configure the host and port used. Command line parameters will override the environment variables. Use `-T none` to test commands without actually connecting to a server. """
if transport_type == 'udp': if timeout is not None: ctx.fail('--timeout cannot be used with the UDP transport') transport = riemann_client.transport.UDPTransport(host, port) elif transport_type == 'tcp': transport = riemann_client.transport.TCPTransport(host, port, timeout) elif transport_type == 'tls': if ca_certs is None: ctx.fail('--ca-certs must be set when using the TLS transport') transport = riemann_client.transport.TLSTransport( host, port, timeout, ca_certs) elif transport_type == 'none': transport = riemann_client.transport.BlankTransport() ctx.obj = transport
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(transport, time, state, host, description, service, tag, attribute, ttl, metric_f, echo): """Send a single event to Riemann"""
client = CommandLineClient(transport) event = client.create_event({ 'time': time, 'state': state, 'host': host, 'description': description, 'service': service, 'tags': tag, 'attributes': dict(attribute), 'ttl': ttl, 'metric_f': metric_f }) with client: client.send_event(event) if echo: echo_event(client.create_dict(event))
<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(transport, query): """Query the Riemann server"""
with CommandLineClient(transport) as client: echo_event(client.query(query))
<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, attrs): """ Save just these few attributes, not the whole object :param attrs: Attributes to save, key->value dict :type attrs: dict :return: self :rtype: :class:`boto.sdb.db.model.Model` """
assert(isinstance(attrs, dict)), "Argument must be a dict of key->values to save" for prop_name in attrs: value = attrs[prop_name] prop = self.find_property(prop_name) assert(prop), "Property not found: %s" % prop_name self._manager.set_property(prop, self, prop_name, value) self.reload() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_attributes(self, attrs): """ Delete just these attributes, not the whole object. :param attrs: Attributes to save, as a list of string names :type attrs: list :return: self :rtype: :class:`boto.sdb.db.model.Model` """
assert(isinstance(attrs, list)), "Argument must be a list of names of keys to delete." self._manager.domain.delete_attributes(self.id, attrs) self.reload() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_subclass(cls, name): """Find a subclass with a given name"""
if name == cls.__name__: return cls for sc in cls.__sub_classes__: r = sc.find_subclass(name) if r != None: return 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 update(self): """ In the case where you have accessed an existing health check on a load balancer, this method applies this instance's health check values to the load balancer it is attached to. .. note:: This method will not do anything if the :py:attr:`access_point` attribute isn't set, as is the case with a newly instantiated HealthCheck instance. """
if not self.access_point: return new_hc = self.connection.configure_health_check(self.access_point, self) self.interval = new_hc.interval self.target = new_hc.target self.healthy_threshold = new_hc.healthy_threshold self.unhealthy_threshold = new_hc.unhealthy_threshold self.timeout = new_hc.timeout
<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, page=0, itemSet=None): """ Utility method to handle calls to ECS and parsing of responses. """
params['Service'] = "AWSECommerceService" params['Operation'] = action if page: params['ItemPage'] = page response = self.make_request(None, params, "/onca/xml") body = response.read() boto.log.debug(body) if response.status != 200: boto.log.error('%s %s' % (response.status, response.reason)) boto.log.error('%s' % body) raise self.ResponseError(response.status, response.reason, body) if itemSet == None: rs = ItemSet(self, action, params, page) else: rs = itemSet h = handler.XmlHandler(rs, self) xml.sax.parseString(body, h) return rs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_uploads(content, template_path="adminfiles/render/"): """ Replace all uploaded file references in a content string with the results of rendering a template found under ``template_path`` with the ``FileUpload`` instance and the key=value options found in the file reference. content string, it will be replaced with the results of rendering the selected template with ``upload`` set to the ``FileUpload`` instance with slug "my-uploaded-file" and ``options`` set to {'key': 'val', 'key2': 'val2'}. If the given slug is not found, the reference is replaced with the empty string. If ``djangoembed`` or ``django-oembed`` is installed, also replaces OEmbed URLs with the appropriate embed markup. """
def _replace(match): upload, options = parse_match(match) return render_upload(upload, template_path, **options) return oembed_replace(substitute_uploads(content, _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 parse_meta(meta): """ Parse metadata of API Args: meta: metadata of API Returns: tuple(url_prefix, auth_header, resources) """
resources = {} for name in meta: if name.startswith("$"): continue resources[name] = resource = {} for action in meta[name]: if action.startswith("$"): continue url, httpmethod = res_to_url(name, action) resource[action] = { "url": url, "method": httpmethod } url_prefix = meta.get("$url_prefix", "").rstrip("/") return url_prefix, meta["$auth"]["header"].lower(), resources
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_core(url_prefix, auth_header, resources): """Generate res.core.js"""
code = '' code += "function(root, init) {\n" code += " var q = init('%(auth_header)s', '%(url_prefix)s');\n" %\ {'url_prefix': url_prefix, 'auth_header': auth_header} code += " var r = null;\n" for key in resources: code += " r = root.%(key)s = {};\n" % {'key': key} for action, item in resources[key].items(): code += " r.%(action)s = q('%(url)s', '%(method)s');\n" %\ {'action': action, 'url': item['url'], 'method': item['method']} code += "}" return code
<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_code(meta, prefix=None, node=False, min=False): """ Generate res.js Args: meta: tuple(url_prefix, auth_header, resources) or metadata of API Returns: res.js source code """
if isinstance(meta, dict): url_prefix, auth_header, resources = parse_meta(meta) else: url_prefix, auth_header, resources = meta if prefix is not None: url_prefix = prefix core = render_core(url_prefix, auth_header, resources) if min: filename = 'res.web.min.js' else: filename = 'res.web.js' if node: filename = 'res.node.js' base = read_file(filename) return base.replace('"#res.core.js#"', core)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resjs(url, dest='./res.js', prefix=None, node=False, min=False): """Generate res.js and save it"""
meta = requests.get(url, headers={'Accept': 'application/json'}).json() code = generate_code(meta, prefix, node, min) save_file(dest, code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_debug_images(dsym_paths, binary_images): """Given a list of paths and a list of binary images this returns a dictionary of image addresses to the locations on the file system for all found images. """
images_to_load = set() with timedsection('iterimages0'): for image in binary_images: if get_image_cpu_name(image) is not None: images_to_load.add(image['uuid'].lower()) images = {} # Step one: load images that are named by their UUID with timedsection('loadimages-fast'): for uuid in list(images_to_load): for dsym_path in dsym_paths: fn = os.path.join(dsym_path, uuid) if os.path.isfile(fn): images[uuid] = fn images_to_load.discard(uuid) break # Otherwise fall back to loading images from the dsym bundle. Because # this loading strategy is pretty slow we do't actually want to use it # unless we have a path that looks like a bundle. As a result we # find all the paths which are bundles and then only process those. if images_to_load: slow_paths = [] for dsym_path in dsym_paths: if os.path.isdir(os.path.join(dsym_path, 'Contents')): slow_paths.append(dsym_path) with timedsection('loadimages-slow'): for dsym_path in slow_paths: dwarf_base = os.path.join(dsym_path, 'Contents', 'Resources', 'DWARF') if os.path.isdir(dwarf_base): for fn in os.listdir(dwarf_base): # Looks like a UUID we loaded, skip it if fn in images: continue full_fn = os.path.join(dwarf_base, fn) try: di = DebugInfo.open_path(full_fn) except DebugInfoError: continue for variant in di.get_variants(): uuid = str(variant.uuid) if uuid in images_to_load: images[uuid] = full_fn images_to_load.discard(uuid) rv = {} # Now resolve all the images. with timedsection('resolveimages'): for image in binary_images: cpu_name = get_image_cpu_name(image) if cpu_name is None: continue uid = image['uuid'].lower() if uid not in images: continue rv[parse_addr(image['image_addr'])] = images[uid] return rv
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_image(self, addr): """Given an instruction address this locates the image this address is contained in. """
idx = bisect.bisect_left(self._image_addresses, parse_addr(addr)) if idx > 0: return self.images[self._image_addresses[idx - 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 md5sum(content): '''Calculate and returns an MD5 checksum for the specified content. :param content: text content :returns: hex-digest formatted MD5 checksum as a string ''' md5 = hashlib.md5() md5.update(force_bytes(content)) return md5.hexdigest()
<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_list_params(self, params, items, label): """Add an AWS API-compatible parameter list to a dictionary. :type params: dict :param params: The parameter dictionary :type items: list :param items: Items to be included in the list :type label: string :param label: The parameter list's name """
if isinstance(items, basestring): items = [items] for i in range(1, len(items) + 1): params['%s.%d' % (label, i)] = items[i - 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 _make_request(self, action, params=None): """Make a call to the SES API. :type action: string :param action: The API method to use (e.g. SendRawEmail) :type params: dict :param params: Parameters that will be sent as POST data with the API call. """
ct = 'application/x-www-form-urlencoded; charset=UTF-8' headers = {'Content-Type': ct} params = params or {} params['Action'] = action for k, v in params.items(): if isinstance(v, unicode): # UTF-8 encode only if it's Unicode params[k] = v.encode('utf-8') response = super(SESConnection, self).make_request( 'POST', '/', headers=headers, data=urllib.urlencode(params) ) body = response.read() if response.status == 200: list_markers = ('VerifiedEmailAddresses', 'SendDataPoints') e = boto.jsonresponse.Element(list_marker=list_markers) h = boto.jsonresponse.XmlHandler(e, None) h.parse(body) return e else: # HTTP codes other than 200 are considered errors. Go through # some error handling to determine which exception gets raised, self._handle_error(response, 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 _handle_error(self, response, body): """ Handle raising the correct exception, depending on the error. Many errors share the same HTTP response code, meaning we have to get really kludgey and do string searches to figure out what went wrong. """
boto.log.error('%s %s' % (response.status, response.reason)) boto.log.error('%s' % body) if "Address blacklisted." in body: # Delivery failures happened frequently enough with the recipient's # email address for Amazon to blacklist it. After a day or three, # they'll be automatically removed, and delivery can be attempted # again (if you write the code to do so in your application). ExceptionToRaise = ses_exceptions.SESAddressBlacklistedError exc_reason = "Address blacklisted." elif "Email address is not verified." in body: # This error happens when the "Reply-To" value passed to # send_email() hasn't been verified yet. ExceptionToRaise = ses_exceptions.SESAddressNotVerifiedError exc_reason = "Email address is not verified." elif "Daily message quota exceeded." in body: # Encountered when your account exceeds the maximum total number # of emails per 24 hours. ExceptionToRaise = ses_exceptions.SESDailyQuotaExceededError exc_reason = "Daily message quota exceeded." elif "Maximum sending rate exceeded." in body: # Your account has sent above its allowed requests a second rate. ExceptionToRaise = ses_exceptions.SESMaxSendingRateExceededError exc_reason = "Maximum sending rate exceeded." elif "Domain ends with dot." in body: # Recipient address ends with a dot/period. This is invalid. ExceptionToRaise = ses_exceptions.SESDomainEndsWithDotError exc_reason = "Domain ends with dot." else: # This is either a common AWS error, or one that we don't devote # its own exception to. ExceptionToRaise = self.ResponseError exc_reason = response.reason raise ExceptionToRaise(response.status, exc_reason, 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 send_email(self, source, subject, body, to_addresses, cc_addresses=None, bcc_addresses=None, format='text', reply_addresses=None, return_path=None, text_body=None, html_body=None): """Composes an email message based on input data, and then immediately queues the message for sending. :type source: string :param source: The sender's email address. :type subject: string :param subject: The subject of the message: A short summary of the content, which will appear in the recipient's inbox. :type body: string :param body: The message body. :type to_addresses: list of strings or string :param to_addresses: The To: field(s) of the message. :type cc_addresses: list of strings or string :param cc_addresses: The CC: field(s) of the message. :type bcc_addresses: list of strings or string :param bcc_addresses: The BCC: field(s) of the message. :type format: string :param format: The format of the message's body, must be either "text" or "html". :type reply_addresses: list of strings or string :param reply_addresses: The reply-to email address(es) for the message. If the recipient replies to the message, each reply-to address will receive the reply. :type return_path: string :param return_path: The email address to which bounce notifications are to be forwarded. If the message cannot be delivered to the recipient, then an error message will be returned from the recipient's ISP; this message will then be forwarded to the email address specified by the ReturnPath parameter. :type text_body: string :param text_body: The text body to send with this email. :type html_body: string :param html_body: The html body to send with this email. """
format = format.lower().strip() if body is not None: if format == "text": if text_body is not None: raise Warning("You've passed in both a body and a text_body; please choose one or the other.") text_body = body else: if html_body is not None: raise Warning("You've passed in both a body and an html_body; please choose one or the other.") html_body = body params = { 'Source': source, 'Message.Subject.Data': subject, } if return_path: params['ReturnPath'] = return_path if html_body is not None: params['Message.Body.Html.Data'] = html_body if text_body is not None: params['Message.Body.Text.Data'] = text_body if(format not in ("text","html")): raise ValueError("'format' argument must be 'text' or 'html'") if(not (html_body or text_body)): raise ValueError("No text or html body found for mail") self._build_list_params(params, to_addresses, 'Destination.ToAddresses.member') if cc_addresses: self._build_list_params(params, cc_addresses, 'Destination.CcAddresses.member') if bcc_addresses: self._build_list_params(params, bcc_addresses, 'Destination.BccAddresses.member') if reply_addresses: self._build_list_params(params, reply_addresses, 'ReplyToAddresses.member') return self._make_request('SendEmail', 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 send_raw_email(self, raw_message, source=None, destinations=None): """Sends an email message, with header and content specified by the client. The SendRawEmail action is useful for sending multipart MIME emails, with attachments or inline content. The raw text of the message must comply with Internet email standards; otherwise, the message cannot be sent. :type source: string :param source: The sender's email address. Amazon's docs say: If you specify the Source parameter, then bounce notifications and complaints will be sent to this email address. This takes precedence over any Return-Path header that you might include in the raw text of the message. :type raw_message: string :param raw_message: The raw text of the message. The client is responsible for ensuring the following: - Message must contain a header and a body, separated by a blank line. - All required header fields must be present. - Each part of a multipart MIME message must be formatted properly. - MIME content types must be among those supported by Amazon SES. Refer to the Amazon SES Developer Guide for more details. - Content must be base64-encoded, if MIME requires it. :type destinations: list of strings or string :param destinations: A list of destinations for the message. """
params = { 'RawMessage.Data': base64.b64encode(raw_message), } if source: params['Source'] = source if destinations: self._build_list_params(params, destinations, 'Destinations.member') return self._make_request('SendRawEmail', 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_domain(self, domain_name): """ Create a SimpleDB domain. :type domain_name: string :param domain_name: The name of the new domain :rtype: :class:`boto.sdb.domain.Domain` object :return: The newly created domain """
params = {'DomainName':domain_name} d = self.get_object('CreateDomain', params, Domain) d.name = domain_name return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_domain(self, domain_or_name): """ Delete a SimpleDB domain. .. caution:: This will delete the domain and all items within the domain. :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object. :param domain_or_name: Either the name of a domain or a Domain object :rtype: bool :return: True if successful """
domain, domain_name = self.get_domain_and_name(domain_or_name) params = {'DomainName':domain_name} return self.get_status('DeleteDomain', 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 domain_metadata(self, domain_or_name): """ Get the Metadata for a SimpleDB domain. :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object. :param domain_or_name: Either the name of a domain or a Domain object :rtype: :class:`boto.sdb.domain.DomainMetaData` object :return: The newly created domain metadata object """
domain, domain_name = self.get_domain_and_name(domain_or_name) params = {'DomainName':domain_name} d = self.get_object('DomainMetadata', params, DomainMetaData) d.domain = domain return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_attributes(self, domain_or_name, item_name, attribute_names=None, consistent_read=False, item=None): """ Retrieve attributes for a given item in a domain. :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object. :param domain_or_name: Either the name of a domain or a Domain object :type item_name: string :param item_name: The name of the item whose attributes are being retrieved. :type attribute_names: string or list of strings :param attribute_names: An attribute name or list of attribute names. This parameter is optional. If not supplied, all attributes will be retrieved for the item. :type consistent_read: bool :param consistent_read: When set to true, ensures that the most recent data is returned. :type item: :class:`boto.sdb.item.Item` :keyword item: Instead of instantiating a new Item object, you may specify one to update. :rtype: :class:`boto.sdb.item.Item` :return: An Item with the requested attribute name/values set on it """
domain, domain_name = self.get_domain_and_name(domain_or_name) params = {'DomainName' : domain_name, 'ItemName' : item_name} if consistent_read: params['ConsistentRead'] = 'true' if attribute_names: if not isinstance(attribute_names, list): attribute_names = [attribute_names] self.build_list_params(params, attribute_names, 'AttributeName') response = self.make_request('GetAttributes', params) body = response.read() if response.status == 200: if item == None: item = self.item_cls(domain, item_name) h = handler.XmlHandler(item, self) xml.sax.parseString(body, h) return item else: raise SDBResponseError(response.status, response.reason, 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 delete_attributes(self, domain_or_name, item_name, attr_names=None, expected_value=None): """ Delete attributes from a given item in a domain. :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object. :param domain_or_name: Either the name of a domain or a Domain object :type item_name: string :param item_name: The name of the item whose attributes are being deleted. :type attributes: dict, list or :class:`boto.sdb.item.Item` :param attributes: Either a list containing attribute names which will cause all values associated with that attribute name to be deleted or a dict or Item containing the attribute names and keys and list of values to delete as the value. If no value is supplied, all attribute name/values for the item will be deleted. :type expected_value: list :param expected_value: If supplied, this is a list or tuple consisting of a single attribute name and expected value. The list can be of the form: * ['name', 'value'] In which case the call will first verify that the attribute "name" of this item has a value of "value". If it does, the delete will proceed, otherwise a ConditionalCheckFailed error will be returned. The list can also be of the form: * ['name', True|False] which will simply check for the existence (True) or non-existence (False) of the attribute. :rtype: bool :return: True if successful """
domain, domain_name = self.get_domain_and_name(domain_or_name) params = {'DomainName':domain_name, 'ItemName' : item_name} if attr_names: if isinstance(attr_names, list): self._build_name_list(params, attr_names) elif isinstance(attr_names, dict) or isinstance(attr_names, self.item_cls): self._build_name_value_list(params, attr_names) if expected_value: self._build_expected_value(params, expected_value) return self.get_status('DeleteAttributes', 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_vpcs(self, vpc_ids=None, filters=None): """ Retrieve information about your VPCs. You can filter results to return information only about those VPCs that match your search parameters. Otherwise, all VPCs associated with your account are returned. :type vpc_ids: list :param vpc_ids: A list of strings with the desired VPC ID's :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. Possible filter keys are: - *state*, the state of the VPC (pending or available) - *cidrBlock*, CIDR block of the VPC - *dhcpOptionsId*, the ID of a set of DHCP options :rtype: list :return: A list of :class:`boto.vpc.vpc.VPC` """
params = {} if vpc_ids: self.build_list_params(params, vpc_ids, 'VpcId') if filters: i = 1 for filter in filters: params[('Filter.%d.Name' % i)] = filter[0] params[('Filter.%d.Value.1' % i)] = filter[1] i += 1 return self.get_list('DescribeVpcs', params, [('item', VPC)])
<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_route_tables(self, route_table_ids=None, filters=None): """ Retrieve information about your routing tables. You can filter results to return information only about those route tables that match your search parameters. Otherwise, all route tables associated with your account are returned. :type route_table_ids: list :param route_table_ids: A list of strings with the desired route table IDs. :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. :rtype: list :return: A list of :class:`boto.vpc.routetable.RouteTable` """
params = {} if route_table_ids: self.build_list_params(params, route_table_ids, "RouteTableId") if filters: self.build_filter_params(params, dict(filters)) return self.get_list('DescribeRouteTables', params, [('item', RouteTable)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def associate_route_table(self, route_table_id, subnet_id): """ Associates a route table with a specific subnet. :type route_table_id: str :param route_table_id: The ID of the route table to associate. :type subnet_id: str :param subnet_id: The ID of the subnet to associate with. :rtype: str :return: The ID of the association created """
params = { 'RouteTableId': route_table_id, 'SubnetId': subnet_id } result = self.get_object('AssociateRouteTable', params, ResultSet) return result.associationId
<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_route(self, route_table_id, destination_cidr_block, gateway_id=None, instance_id=None): """ Creates a new route in the route table within a VPC. The route's target can be either a gateway attached to the VPC or a NAT instance in the VPC. :type route_table_id: str :param route_table_id: The ID of the route table for the route. :type destination_cidr_block: str :param destination_cidr_block: The CIDR address block used for the destination match. :type gateway_id: str :param gateway_id: The ID of the gateway attached to your VPC. :type instance_id: str :param instance_id: The ID of a NAT instance in your VPC. :rtype: bool :return: True if successful """
params = { 'RouteTableId': route_table_id, 'DestinationCidrBlock': destination_cidr_block } if gateway_id is not None: params['GatewayId'] = gateway_id elif instance_id is not None: params['InstanceId'] = instance_id return self.get_status('CreateRoute', 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_route(self, route_table_id, destination_cidr_block): """ Deletes a route from a route table within a VPC. :type route_table_id: str :param route_table_id: The ID of the route table with the route. :type destination_cidr_block: str :param destination_cidr_block: The CIDR address block used for destination match. :rtype: bool :return: True if successful """
params = { 'RouteTableId': route_table_id, 'DestinationCidrBlock': destination_cidr_block } return self.get_status('DeleteRoute', 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_internet_gateways(self, internet_gateway_ids=None, filters=None): """ Get a list of internet gateways. You can filter results to return information about only those gateways that you're interested in. :type internet_gateway_ids: list :param internet_gateway_ids: A list of strings with the desired gateway IDs. :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. """
params = {} if internet_gateway_ids: self.build_list_params(params, internet_gateway_ids, 'InternetGatewayId') if filters: self.build_filter_params(params, dict(filters)) return self.get_list('DescribeInternetGateways', params, [('item', InternetGateway)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach_internet_gateway(self, internet_gateway_id, vpc_id): """ Attach an internet gateway to a specific VPC. :type internet_gateway_id: str :param internet_gateway_id: The ID of the internet gateway to delete. :type vpc_id: str :param vpc_id: The ID of the VPC to attach to. :rtype: Bool :return: True if successful """
params = { 'InternetGatewayId': internet_gateway_id, 'VpcId': vpc_id } return self.get_status('AttachInternetGateway', 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 detach_internet_gateway(self, internet_gateway_id, vpc_id): """ Detach an internet gateway from a specific VPC. :type internet_gateway_id: str :param internet_gateway_id: The ID of the internet gateway to delete. :type vpc_id: str :param vpc_id: The ID of the VPC to attach to. :rtype: Bool :return: True if successful """
params = { 'InternetGatewayId': internet_gateway_id, 'VpcId': vpc_id } return self.get_status('DetachInternetGateway', 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_customer_gateways(self, customer_gateway_ids=None, filters=None): """ Retrieve information about your CustomerGateways. You can filter results to return information only about those CustomerGateways that match your search parameters. Otherwise, all CustomerGateways associated with your account are returned. :type customer_gateway_ids: list :param customer_gateway_ids: A list of strings with the desired CustomerGateway ID's :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. Possible filter keys are: - *state*, the state of the CustomerGateway (pending,available,deleting,deleted) - *type*, the type of customer gateway (ipsec.1) - *ipAddress* the IP address of customer gateway's internet-routable external inteface :rtype: list :return: A list of :class:`boto.vpc.customergateway.CustomerGateway` """
params = {} if customer_gateway_ids: self.build_list_params(params, customer_gateway_ids, 'CustomerGatewayId') if filters: i = 1 for filter in filters: params[('Filter.%d.Name' % i)] = filter[0] params[('Filter.%d.Value.1')] = filter[1] i += 1 return self.get_list('DescribeCustomerGateways', params, [('item', CustomerGateway)])
<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_customer_gateway(self, type, ip_address, bgp_asn): """ Create a new Customer Gateway :type type: str :param type: Type of VPN Connection. Only valid valid currently is 'ipsec.1' :type ip_address: str :param ip_address: Internet-routable IP address for customer's gateway. Must be a static address. :type bgp_asn: str :param bgp_asn: Customer gateway's Border Gateway Protocol (BGP) Autonomous System Number (ASN) :rtype: The newly created CustomerGateway :return: A :class:`boto.vpc.customergateway.CustomerGateway` object """
params = {'Type' : type, 'IpAddress' : ip_address, 'BgpAsn' : bgp_asn} return self.get_object('CreateCustomerGateway', params, CustomerGateway)
<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_vpn_gateways(self, vpn_gateway_ids=None, filters=None): """ Retrieve information about your VpnGateways. You can filter results to return information only about those VpnGateways that match your search parameters. Otherwise, all VpnGateways associated with your account are returned. :type vpn_gateway_ids: list :param vpn_gateway_ids: A list of strings with the desired VpnGateway ID's :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. Possible filter keys are: - *state*, the state of the VpnGateway (pending,available,deleting,deleted) - *type*, the type of customer gateway (ipsec.1) - *availabilityZone*, the Availability zone the VPN gateway is in. :rtype: list :return: A list of :class:`boto.vpc.customergateway.VpnGateway` """
params = {} if vpn_gateway_ids: self.build_list_params(params, vpn_gateway_ids, 'VpnGatewayId') if filters: i = 1 for filter in filters: params[('Filter.%d.Name' % i)] = filter[0] params[('Filter.%d.Value.1')] = filter[1] i += 1 return self.get_list('DescribeVpnGateways', params, [('item', VpnGateway)])
<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_vpn_gateway(self, type, availability_zone=None): """ Create a new Vpn Gateway :type type: str :param type: Type of VPN Connection. Only valid valid currently is 'ipsec.1' :type availability_zone: str :param availability_zone: The Availability Zone where you want the VPN gateway. :rtype: The newly created VpnGateway :return: A :class:`boto.vpc.vpngateway.VpnGateway` object """
params = {'Type' : type} if availability_zone: params['AvailabilityZone'] = availability_zone return self.get_object('CreateVpnGateway', params, VpnGateway)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach_vpn_gateway(self, vpn_gateway_id, vpc_id): """ Attaches a VPN gateway to a VPC. :type vpn_gateway_id: str :param vpn_gateway_id: The ID of the vpn_gateway to attach :type vpc_id: str :param vpc_id: The ID of the VPC you want to attach the gateway to. :rtype: An attachment :return: a :class:`boto.vpc.vpngateway.Attachment` """
params = {'VpnGatewayId': vpn_gateway_id, 'VpcId' : vpc_id} return self.get_object('AttachVpnGateway', params, Attachment)
<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_subnets(self, subnet_ids=None, filters=None): """ Retrieve information about your Subnets. You can filter results to return information only about those Subnets that match your search parameters. Otherwise, all Subnets associated with your account are returned. :type subnet_ids: list :param subnet_ids: A list of strings with the desired Subnet ID's :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. Possible filter keys are: - *state*, the state of the Subnet (pending,available) - *vpdId*, the ID of teh VPC the subnet is in. - *cidrBlock*, CIDR block of the subnet - *availabilityZone*, the Availability Zone the subnet is in. :rtype: list :return: A list of :class:`boto.vpc.subnet.Subnet` """
params = {} if subnet_ids: self.build_list_params(params, subnet_ids, 'SubnetId') if filters: i = 1 for filter in filters: params[('Filter.%d.Name' % i)] = filter[0] params[('Filter.%d.Value.1' % i)] = filter[1] i += 1 return self.get_list('DescribeSubnets', params, [('item', Subnet)])
<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_subnet(self, vpc_id, cidr_block, availability_zone=None): """ Create a new Subnet :type vpc_id: str :param vpc_id: The ID of the VPC where you want to create the subnet. :type cidr_block: str :param cidr_block: The CIDR block you want the subnet to cover. :type availability_zone: str :param availability_zone: The AZ you want the subnet in :rtype: The newly created Subnet :return: A :class:`boto.vpc.customergateway.Subnet` object """
params = {'VpcId' : vpc_id, 'CidrBlock' : cidr_block} if availability_zone: params['AvailabilityZone'] = availability_zone return self.get_object('CreateSubnet', params, Subnet)
<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_dhcp_options(self, dhcp_options_ids=None): """ Retrieve information about your DhcpOptions. :type dhcp_options_ids: list :param dhcp_options_ids: A list of strings with the desired DhcpOption ID's :rtype: list :return: A list of :class:`boto.vpc.dhcpoptions.DhcpOptions` """
params = {} if dhcp_options_ids: self.build_list_params(params, dhcp_options_ids, 'DhcpOptionsId') return self.get_list('DescribeDhcpOptions', params, [('item', DhcpOptions)])
<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_dhcp_options(self, vpc_id, cidr_block, availability_zone=None): """ Create a new DhcpOption :type vpc_id: str :param vpc_id: The ID of the VPC where you want to create the subnet. :type cidr_block: str :param cidr_block: The CIDR block you want the subnet to cover. :type availability_zone: str :param availability_zone: The AZ you want the subnet in :rtype: The newly created DhcpOption :return: A :class:`boto.vpc.customergateway.DhcpOption` object """
params = {'VpcId' : vpc_id, 'CidrBlock' : cidr_block} if availability_zone: params['AvailabilityZone'] = availability_zone return self.get_object('CreateDhcpOption', params, DhcpOptions)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def associate_dhcp_options(self, dhcp_options_id, vpc_id): """ Associate a set of Dhcp Options with a VPC. :type dhcp_options_id: str :param dhcp_options_id: The ID of the Dhcp Options :type vpc_id: str :param vpc_id: The ID of the VPC. :rtype: bool :return: True if successful """
params = {'DhcpOptionsId': dhcp_options_id, 'VpcId' : vpc_id} return self.get_status('AssociateDhcpOptions', 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_vpn_connections(self, vpn_connection_ids=None, filters=None): """ Retrieve information about your VPN_CONNECTIONs. You can filter results to return information only about those VPN_CONNECTIONs that match your search parameters. Otherwise, all VPN_CONNECTIONs associated with your account are returned. :type vpn_connection_ids: list :param vpn_connection_ids: A list of strings with the desired VPN_CONNECTION ID's :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. Possible filter keys are: - *state*, the state of the VPN_CONNECTION pending,available,deleting,deleted - *type*, the type of connection, currently 'ipsec.1' - *customerGatewayId*, the ID of the customer gateway associated with the VPN - *vpnGatewayId*, the ID of the VPN gateway associated with the VPN connection :rtype: list :return: A list of :class:`boto.vpn_connection.vpnconnection.VpnConnection` """
params = {} if vpn_connection_ids: self.build_list_params(params, vpn_connection_ids, 'Vpn_ConnectionId') if filters: i = 1 for filter in filters: params[('Filter.%d.Name' % i)] = filter[0] params[('Filter.%d.Value.1')] = filter[1] i += 1 return self.get_list('DescribeVpnConnections', params, [('item', VpnConnection)])
<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_vpn_connection(self, type, customer_gateway_id, vpn_gateway_id): """ Create a new VPN Connection. :type type: str :param type: The type of VPN Connection. Currently only 'ipsec.1' is supported :type customer_gateway_id: str :param customer_gateway_id: The ID of the customer gateway. :type vpn_gateway_id: str :param vpn_gateway_id: The ID of the VPN gateway. :rtype: The newly created VpnConnection :return: A :class:`boto.vpc.vpnconnection.VpnConnection` object """
params = {'Type' : type, 'CustomerGatewayId' : customer_gateway_id, 'VpnGatewayId' : vpn_gateway_id} return self.get_object('CreateVpnConnection', params, VpnConnection)
<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_cur_file_size(fp, position_to_eof=False): """ Returns size of file, optionally leaving fp positioned at EOF. """
if not position_to_eof: cur_pos = fp.tell() fp.seek(0, os.SEEK_END) cur_file_size = fp.tell() if not position_to_eof: fp.seek(cur_pos, os.SEEK_SET) return cur_file_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 _attempt_resumable_download(self, key, fp, headers, cb, num_cb, torrent, version_id): """ Attempts a resumable download. Raises ResumableDownloadException if any problems occur. """
cur_file_size = get_cur_file_size(fp, position_to_eof=True) if (cur_file_size and self.etag_value_for_current_download and self.etag_value_for_current_download == key.etag.strip('"\'')): # Try to resume existing transfer. if cur_file_size > key.size: raise ResumableDownloadException( '%s is larger (%d) than %s (%d).\nDeleting tracker file, so ' 'if you re-try this download it will start from scratch' % (fp.name, cur_file_size, str(storage_uri_for_key(key)), key.size), ResumableTransferDisposition.ABORT) elif cur_file_size == key.size: if key.bucket.connection.debug >= 1: print 'Download complete.' return if key.bucket.connection.debug >= 1: print 'Resuming download.' headers = headers.copy() headers['Range'] = 'bytes=%d-%d' % (cur_file_size, key.size - 1) cb = ByteTranslatingCallbackHandler(cb, cur_file_size).call self.download_start_point = cur_file_size else: if key.bucket.connection.debug >= 1: print 'Starting new resumable download.' self._save_tracker_info(key) self.download_start_point = 0 # Truncate the file, in case a new resumable download is being # started atop an existing file. fp.truncate(0) # Disable AWSAuthConnection-level retry behavior, since that would # cause downloads to restart from scratch. key.get_file(fp, headers, cb, num_cb, torrent, version_id, override_num_retries=0) fp.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 get_redirect_url(self, request, callback, parameters=None): """Build authentication redirect url."""
args = self.get_redirect_args(request, callback=callback) additional = parameters or {} args.update(additional) params = urlencode(args) return '{0}?{1}'.format(self.authorization_url, 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_request_token(self, request, callback): """Fetch the OAuth request token. Only required for OAuth 1.0."""
callback = force_text(request.build_absolute_uri(callback)) try: response = self.request('post', self.request_token_url, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch request token: {0}'.format(e)) return None else: return response.text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_cards(jokers=False, num_jokers=0): """ Builds a list containing a full French deck of 52 Card instances. The cards are sorted according to ``DEFAULT_RANKS``. .. note: Adding jokers may break some functions & methods at the moment. :arg bool jokers: Whether or not to include jokers in the deck. :arg int num_jokers: The number of jokers to include. :returns: A list containing a full French deck of 52 Card instances. """
new_deck = [] if jokers: new_deck += [Card("Joker", None) for i in xrange(num_jokers)] new_deck += [Card(value, suit) for value in VALUES for suit in SUITS] return new_deck
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_sorted(cards, ranks=None): """ Checks whether the given cards are sorted by the given ranks. :arg cards: The cards to check. Can be a ``Stack``, ``Deck``, or ``list`` of ``Card`` isntances. :arg dict ranks: The ranks to check against. Default is DEFAULT_RANKS. :returns: ``True`` or ``False``. """
ranks = ranks or DEFAULT_RANKS sorted_cards = sort_cards(cards, ranks) if cards == sorted_cards or cards[::-1] == sorted_cards: return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_term(card, term): """ Checks a given search term against a given card's full name, suit, value, and abbreviation. :arg Card card: The card to check. :arg str term: The search term to check for. Can be a card full name, suit, value, or abbreviation. :returns: ``True`` or ``False``. """
check_list = [ x.lower() for x in [card.name, card.suit, card.value, card.abbrev, card.suit[0], card.value[0]] ] term = term.lower() for check in check_list: if check == term: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_cards(filename=None): """ Open cards from a txt file. :arg str filename: The filename of the deck file to open. If no filename given, defaults to "cards-YYYYMMDD.txt", where "YYYYMMDD" is the year, month, and day. For example, "cards-20140711.txt". :returns: The opened cards, as a list. """
filename = filename or "cards-%s.txt" % (time.strftime("%Y%m%d")) with open(filename, "r") as deck_file: card_data = [line.rstrip("\n") for line in deck_file.readlines()] cards = [None] * len(card_data) for i, card in enumerate(card_data): card = card.split() cards[i] = Card(card[0], card[1]) return cards
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_card(cards, remove=False): """ Returns a random card from the Stack. If ``remove=True``, it will also remove the card from the deck. :arg bool remove: Whether or not to remove the card from the deck. :returns: A random Card object, from the Stack. """
if not remove: return random.choice(cards) else: i = random.randrange(len(cards)) card = cards[i] del cards[i] return card
<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_cards(cards, filename=None): """ Save the given cards, in plain text, to a txt file. :arg cards: The cards to save. Can be a ``Stack``, ``Deck``, or ``list``. :arg str filename: The filename to use for the cards file. If no filename given, defaults to "cards-YYYYMMDD.txt", where "YYYYMMDD" is the year, month, and day. For example, "cards-20140711.txt". """
filename = filename or "cards-%s.txt" % (time.strftime("%Y%m%d")) with open(filename, "w") as deck_file: card_reprs = ["%s %s\n" % (card.value, card.suit) for card in cards] card_reprs[-1] = card_reprs[-1].rstrip("\n") for card in card_reprs: deck_file.write(card)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_card_indices(cards, indices, ranks=None): """ Sorts the given Deck indices by the given ranks. Must also supply the ``Stack``, ``Deck``, or ``list`` that the indices are from. :arg cards: The cards the indices are from. Can be a ``Stack``, ``Deck``, or ``list`` :arg list indices: The indices to sort. :arg dict ranks: The rank dict to reference for sorting. If ``None``, it will default to ``DEFAULT_RANKS``. :returns: The sorted indices. """
ranks = ranks or DEFAULT_RANKS if ranks.get("suits"): indices = sorted( indices, key=lambda x: ranks["suits"][cards[x].suit] if cards[x].suit != None else 0 ) if ranks.get("values"): indices = sorted( indices, key=lambda x: ranks["values"][cards[x].value] ) return indices
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_cards(cards, ranks=None): """ Sorts a given list of cards, either by poker ranks, or big two ranks. :arg cards: The cards to sort. :arg dict ranks: The rank dict to reference for sorting. If ``None``, it will default to ``DEFAULT_RANKS``. :returns: The sorted cards. """
ranks = ranks or DEFAULT_RANKS if ranks.get("suits"): cards = sorted( cards, key=lambda x: ranks["suits"][x.suit] if x.suit != None else 0 ) if ranks.get("values"): cards = sorted( cards, key=lambda x: ranks["values"][x.value] ) return cards
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_map_element(self, item_type, value): """Decode a single element for a map"""
import urllib key = value if ":" in value: key, value = value.split(':',1) key = urllib.unquote(key) if Model in item_type.mro(): value = item_type(id=value) else: value = self.decode(item_type, value) return (key, 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 encode_string(self, value): """Convert ASCII, Latin-1 or UTF-8 to pure Unicode"""
if not isinstance(value, str): return value try: return unicode(value, 'utf-8') except: # really, this should throw an exception. # in the interest of not breaking current # systems, however: arr = [] for ch in value: arr.append(unichr(ord(ch))) return u"".join(arr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count(self, cls, filters, quick=True, sort_by=None, select=None): """ Get the number of results that would be returned in this query """
query = "select count(*) from `%s` %s" % (self.domain.name, self._build_filter_part(cls, filters, sort_by, select)) count = 0 for row in self.domain.select(query): count += int(row['Count']) if quick: return count return count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_all_decendents(self, cls): """Get all decendents for a given class"""
decendents = {} for sc in cls.__sub_classes__: decendents[sc.__name__] = sc decendents.update(self._get_all_decendents(sc)) return decendents
<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(self, validate=False): """ Update the data associated with this snapshot by querying EC2. :type validate: bool :param validate: By default, if EC2 returns no data about the snapshot the update method returns quietly. If the validate param is True, however, it will raise a ValueError exception if no data is returned from EC2. """
rs = self.connection.get_all_snapshots([self.id]) if len(rs) > 0: self._update(rs[0]) elif validate: raise ValueError('%s is not a valid Snapshot ID' % self.id) return self.progress
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ne(self, other, ranks=None): """ Compares the card against another card, ``other``, and checks whether the card is not equal to ``other``, based on the given rank dict. :arg Card other: The second Card to compare. :arg dict ranks: The ranks to refer to for comparisons. :returns: ``True`` or ``False``. """
ranks = ranks or DEFAULT_RANKS if isinstance(other, Card): if ranks.get("suits"): return ( ranks["values"][self.value] != ranks["values"][other.value] or ranks["suits"][self.suit] != ranks["suits"][other.suit] ) else: return ranks[self.value] != ranks[other.value] else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def index_config(request): '''This view returns the index configuration of the current application as JSON. Currently, this consists of a Solr index url and the Fedora content models that this application expects to index. .. Note:: By default, Fedora system content models (such as ``fedora-system:ContentModel-3.0``) are excluded. Any application that actually wants to index such objects will need to customize this view to include them. ''' #Ensure permission to this resource is allowed. Currently based on IP only. if _permission_denied_check(request): return HttpResponseForbidden('Access to this web service was denied.', content_type='text/html') content_list = getattr(settings, 'EUL_INDEXER_CONTENT_MODELS', []) # Generate an automatic list of lists of content models (one list for each defined type) # if no content model settings exist if not content_list: for cls in six.itervalues(DigitalObject.defined_types): # by default, Fedora system content models are excluded content_group = [model for model in getattr(cls, 'CONTENT_MODELS', []) if not model.startswith('info:fedora/fedora-system:')] # if the group of content models is not empty, add it to the list if content_group: content_list.append(content_group) response = { 'CONTENT_MODELS': content_list, 'SOLR_URL': settings.SOLR_SERVER_URL } return HttpResponse(json.dumps(response), content_type='application/json')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _permission_denied_check(request): '''Internal function to verify that access to this webservice is allowed. Currently, based on the value of EUL_INDEXER_ALLOWED_IPS in settings.py. :param request: HttpRequest ''' allowed_ips = settings.EUL_INDEXER_ALLOWED_IPS if allowed_ips != "ANY" and not request.META['REMOTE_ADDR'] in allowed_ips: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, validate=False): """ Update the instance's state information by making a call to fetch the current instance attributes from the service. :type validate: bool :param validate: By default, if EC2 returns no data about the instance the update method returns quietly. If the validate param is True, however, it will raise a ValueError exception if no data is returned from EC2. """
rs = self.connection.get_all_instances([self.id]) if len(rs) > 0: r = rs[0] for i in r.instances: if i.id == self.id: self._update(i) elif validate: raise ValueError('%s is not a valid Instance ID' % self.id) return self.state
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def terminate(self): """ Terminate the instance """
rs = self.connection.terminate_instances([self.id]) if len(rs) > 0: self._update(rs[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 stop(self, force=False): """ Stop the instance :type force: bool :param force: Forces the instance to stop :rtype: list :return: A list of the instances stopped """
rs = self.connection.stop_instances([self.id], force) if len(rs) > 0: self._update(rs[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 modify_attribute(self, attribute, value): """ Changes an attribute of this instance :type attribute: string :param attribute: The attribute you wish to change. AttributeName - Expected value (default) instanceType - A valid instance type (m1.small) kernel - Kernel ID (None) ramdisk - Ramdisk ID (None) userData - Base64 encoded String (None) disableApiTermination - Boolean (true) instanceInitiatedShutdownBehavior - stop|terminate rootDeviceName - device name (None) :type value: string :param value: The new value for the attribute :rtype: bool :return: Whether the operation succeeded or not """
return self.connection.modify_instance_attribute(self.id, attribute, 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 get_all_load_balancers(self, load_balancer_names=None): """ Retrieve all load balancers associated with your account. :type load_balancer_names: list :keyword load_balancer_names: An optional list of load balancer names. :rtype: :py:class:`boto.resultset.ResultSet` :return: A ResultSet containing instances of :class:`boto.ec2.elb.loadbalancer.LoadBalancer` """
params = {} if load_balancer_names: self.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') return self.get_list('DescribeLoadBalancers', params, [('member', LoadBalancer)])
<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_availability_zones(self, load_balancer_name, zones_to_add): """ Add availability zones to an existing Load Balancer All zones must be in the same region as the Load Balancer Adding zones that are already registered with the Load Balancer has no effect. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type zones: List of strings :param zones: The name of the zone(s) to add. :rtype: List of strings :return: An updated list of zones for this Load Balancer. """
params = {'LoadBalancerName' : load_balancer_name} self.build_list_params(params, zones_to_add, 'AvailabilityZones.member.%d') return self.get_list('EnableAvailabilityZonesForLoadBalancer', params, 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 disable_availability_zones(self, load_balancer_name, zones_to_remove): """ Remove availability zones from an existing Load Balancer. All zones must be in the same region as the Load Balancer. Removing zones that are not registered with the Load Balancer has no effect. You cannot remove all zones from an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type zones: List of strings :param zones: The name of the zone(s) to remove. :rtype: List of strings :return: An updated list of zones for this Load Balancer. """
params = {'LoadBalancerName' : load_balancer_name} self.build_list_params(params, zones_to_remove, 'AvailabilityZones.member.%d') return self.get_list('DisableAvailabilityZonesForLoadBalancer', params, 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 register_instances(self, load_balancer_name, instances): """ Add new Instances to an existing Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type instances: List of strings :param instances: The instance ID's of the EC2 instances to add. :rtype: List of strings :return: An updated list of instances for this Load Balancer. """
params = {'LoadBalancerName' : load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('RegisterInstancesWithLoadBalancer', params, [('member', InstanceInfo)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deregister_instances(self, load_balancer_name, instances): """ Remove Instances from an existing Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type instances: List of strings :param instances: The instance ID's of the EC2 instances to remove. :rtype: List of strings :return: An updated list of instances for this Load Balancer. """
params = {'LoadBalancerName' : load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DeregisterInstancesFromLoadBalancer', params, [('member', InstanceInfo)])
<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_instance_health(self, load_balancer_name, instances=None): """ Get current state of all Instances registered to an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type instances: List of strings :param instances: The instance ID's of the EC2 instances to return status for. If not provided, the state of all instances will be returned. :rtype: List of :class:`boto.ec2.elb.instancestate.InstanceState` :return: list of state info for instances in this Load Balancer. """
params = {'LoadBalancerName' : load_balancer_name} if instances: self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DescribeInstanceHealth', params, [('member', InstanceState)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_health_check(self, name, health_check): """ Define a health check for the EndPoints. :type name: string :param name: The mnemonic name associated with the load balancer :type health_check: :class:`boto.ec2.elb.healthcheck.HealthCheck` :param health_check: A HealthCheck object populated with the desired values. :rtype: :class:`boto.ec2.elb.healthcheck.HealthCheck` :return: The updated :class:`boto.ec2.elb.healthcheck.HealthCheck` """
params = {'LoadBalancerName' : name, 'HealthCheck.Timeout' : health_check.timeout, 'HealthCheck.Target' : health_check.target, 'HealthCheck.Interval' : health_check.interval, 'HealthCheck.UnhealthyThreshold' : health_check.unhealthy_threshold, 'HealthCheck.HealthyThreshold' : health_check.healthy_threshold} return self.get_object('ConfigureHealthCheck', params, HealthCheck)
<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_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): """ Sets the certificate that terminates the specified listener's SSL connections. The specified certificate replaces any prior certificate that was used on the same LoadBalancer and port. """
params = { 'LoadBalancerName' : lb_name, 'LoadBalancerPort' : lb_port, 'SSLCertificateId' : ssl_certificate_id, } return self.get_status('SetLoadBalancerListenerSSLCertificate', 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_app_cookie_stickiness_policy(self, name, lb_name, policy_name): """ Generates a stickiness policy with sticky session lifetimes that follow that of an application-generated cookie. This policy can only be associated with HTTP listeners. This policy is similar to the policy created by CreateLBCookieStickinessPolicy, except that the lifetime of the special Elastic Load Balancing cookie follows the lifetime of the application-generated cookie specified in the policy configuration. The load balancer only inserts a new stickiness cookie when the application response includes a new application cookie. If the application cookie is explicitly removed or expires, the session stops being sticky until a new application cookie is issued. """
params = { 'CookieName' : name, 'LoadBalancerName' : lb_name, 'PolicyName' : policy_name, } return self.get_status('CreateAppCookieStickinessPolicy', 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_lb_policy(self, lb_name, policy_name): """ Deletes a policy from the LoadBalancer. The specified policy must not be enabled for any listeners. """
params = { 'LoadBalancerName' : lb_name, 'PolicyName' : policy_name, } return self.get_status('DeleteLoadBalancerPolicy', 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 remove_missing_keys(src_dict, target_dict): """ Remove keys from target_dict that are not available in src_dict :param src_dict: source dictionary to search for :param target_dict: target dictionary where keys should be removed """
for key in list(target_dict.keys()): if key not in src_dict: target_dict.pop(key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_dirs(path): """ Creates all directories mentioned in the given path. Useful to write a new file with the specified path. It carefully skips the file-name in the given path. :param path: Path of a file or directory """
fname = os.path.basename(path) # if file name exists in path, skip the filename if fname.__contains__('.'): path = os.path.dirname(path) if not os.path.exists(path): os.makedirs(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 fetch_data(self): """Method returns results from response of Yahoo YQL API. It should returns always python list."""
if relativedelta(self.end_date, self.start_date).years <= const.ONE_YEAR: data = self.request.send(self.symbol, self.start_date, self.end_date) else: data = self.fetch_chunk_data() return self.clean(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 register_hit_type(self, title, description, reward, duration, keywords=None, approval_delay=None, qual_req=None): """ Register a new HIT Type title, description are strings reward is a Price object duration can be a timedelta, or an object castable to an int """
params = dict( Title=title, Description=description, AssignmentDurationInSeconds= self.duration_as_seconds(duration), ) params.update(MTurkConnection.get_price_as_price(reward).get_as_params('Reward')) if keywords: params['Keywords'] = self.get_keywords_as_string(keywords) if approval_delay is not None: d = self.duration_as_seconds(approval_delay) params['AutoApprovalDelayInSeconds'] = d if qual_req is not None: params.update(qual_req.get_as_params()) return self._process_request('RegisterHITType', 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_email_notification(self, hit_type, email, event_types=None): """ Performs a SetHITTypeNotification operation to set email notification for a specified HIT type """
return self._set_notification(hit_type, 'Email', email, event_types)
<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_rest_notification(self, hit_type, url, event_types=None): """ Performs a SetHITTypeNotification operation to set REST notification for a specified HIT type """
return self._set_notification(hit_type, 'REST', url, event_types)
<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_notification(self, hit_type, transport, destination, event_types=None): """ Common SetHITTypeNotification operation to set notification for a specified HIT type """
assert type(hit_type) is str, "hit_type argument should be a string." params = {'HITTypeId': hit_type} # from the Developer Guide: # The 'Active' parameter is optional. If omitted, the active status of # the HIT type's notification specification is unchanged. All HIT types # begin with their notification specifications in the "inactive" status. notification_params = {'Destination': destination, 'Transport': transport, 'Version': boto.mturk.notification.NotificationMessage.NOTIFICATION_VERSION, 'Active': True, } # add specific event types if required if event_types: self.build_list_params(notification_params, event_types, 'EventType') # Set up dict of 'Notification.1.Transport' etc. values notification_rest_params = {} num = 1 for key in notification_params: notification_rest_params['Notification.%d.%s' % (num, key)] = notification_params[key] # Update main params dict params.update(notification_rest_params) # Execute operation return self._process_request('SetHITTypeNotification', params)