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 sign(conf):
"""Sign in and get money.""" |
try:
v2ex = V2ex(conf.config)
v2ex.login()
balance = v2ex.get_money()
click.echo(balance)
except KeyError:
click.echo('Keyerror, please check your config file.')
except IndexError:
click.echo('Please check your username and password.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(conf, count):
"""Read log file.""" |
file_path = os.path.join(path.abspath(conf.config['log_directory']),
'v2ex.log')
for line in deque(open(file_path, encoding='utf-8'), int(count)):
click.echo(line, nl=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 last(conf):
"""How long you have kept signing in.""" |
try:
v2ex = V2ex(conf.config)
v2ex.login()
last_date = v2ex.get_last()
click.echo(last_date)
except KeyError:
click.echo('Keyerror, please check your config file.')
except IndexError:
click.echo('Please check your username and password.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_uploads(text):
""" Return a generator yielding uploads referenced in the given text. """ |
uploads = []
for match in UPLOAD_RE.finditer(text):
try:
upload = FileUpload.objects.get(slug=match.group(1))
except FileUpload.DoesNotExist:
continue
yield upload |
<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_match(match):
""" Accept an re match object resulting from an ``UPLOAD_RE`` match and return a two-tuple where the first element is the corresponding `... |
try:
upload = FileUpload.objects.get(slug=match.group(1))
except FileUpload.DoesNotExist:
upload = None
options = parse_options(match.group(2))
return (upload, options) |
<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(self, jokers=False, num_jokers=0):
""" Builds a standard 52 card French deck of Card instances. :arg bool jokers: Whether or not to include jokers in t... |
jokers = jokers or self.jokers
num_jokers = num_jokers or self.num_jokers
self.decks_used += 1
self.cards += build_cards(jokers, num_jokers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deal(self, num=1, rebuild=False, shuffle=False, end=TOP):
""" Returns a list of cards, which are removed from the deck. :arg int num: The number of cards to ... |
_num = num
rebuild = rebuild or self.rebuild
re_shuffle = shuffle or self.re_shuffle
self_size = self.size
if rebuild or num <= self_size:
dealt_cards = [None] * num
elif num > self_size:
dealt_cards = [None] * self_size
while num > 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 socket_recvall(socket, length, bufsize=4096):
"""A helper method to read of bytes from a socket to a maximum length""" |
data = b""
while len(data) < length:
data += socket.recv(bufsize)
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 send(self, message):
"""Sends a message, but does not return a response :returns: None - can't receive a response over UDP """ |
self.socket.sendto(message.SerializeToString(), self.address)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
"""Connects to the given host""" |
self.socket = socket.create_connection(self.address, self.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 send(self, message):
"""Sends a message to a Riemann server and returns it's response :param message: The message to send to the Riemann server :returns: The... |
message = message.SerializeToString()
self.socket.sendall(struct.pack('!I', len(message)) + message)
length = struct.unpack('!I', self.socket.recv(4))[0]
response = riemann_client.riemann_pb2.Msg()
response.ParseFromString(socket_recvall(self.socket, length))
if not re... |
<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(self, message):
"""Adds a message to the list, returning a fake 'ok' response :returns: A response message with ``ok = True`` """ |
for event in message.events:
self.events.append(event)
reply = riemann_client.riemann_pb2.Msg()
reply.ok = True
return reply |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _in_version(self, *versions):
"Returns true if this frame is in any of the specified versions of ID3."
for version in versions:
if (self._version == version
or (isinstance(self._version, collections.Container)
and version in self._version)):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _spec(self, name):
"Return the named spec."
for s in self._framespec:
if s.name == name:
return s
raise ValueError("Unknown spec: " + name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exists(self, callback=None):
""" Returns True if the key exists :rtype: bool :return: Whether the key exists on S3 """ |
def existence_tested(response):
if callable(callback):
callback(bool(response))
self.bucket.lookup(self.name, callback=existence_tested) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_contents_to_filename(self, filename, headers=None, cb=None, num_cb=10, torrent=False, version_id=None, res_download_handler=None, response_headers=None, c... |
fp = open(filename, 'wb')
def got_contents_to_filename(response):
fp.close()
# if last_modified date was sent from s3, try to set file's timestamp
if self.last_modified != None:
try:
modified_tuple = rfc822.parsedate_tz(self.last_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 check_tag_data(data):
"Raise a ValueError if DATA doesn't seem to be a well-formed ID3 tag."
if len(data) < 10:
raise ValueError("Tag too short")
if data[0:3] != b"ID3":
raise ValueError("Missing ID3 identifier")
if data[3] >= 5 or data[4] != 0:
raise ValueError("Unknown ID3 ... |
<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_raw_tag_data(filename):
"Return the ID3 tag in FILENAME as a raw byte string."
with open(filename, "rb") as file:
try:
(cls, offset, length) = stagger.tags.detect_tag(file)
except stagger.NoTagError:
return bytes()
file.seek(offset)
return file.rea... |
<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_raw_tag_data(filename, data, act=True, verbose=False):
"Replace the ID3 tag in FILENAME with DATA."
check_tag_data(data)
with open(filename, "rb+") as file:
try:
(cls, offset, length) = stagger.tags.detect_tag(file)
except stagger.NoTagError:
(offset, length) ... |
<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_message(self, queue, message):
""" Delete a message from a queue. :type queue: A :class:`boto.sqs.queue.Queue` object :param queue: The Queue from whi... |
params = {'ReceiptHandle' : message.receipt_handle}
return self.get_status('DeleteMessage', params, queue.id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_message_from_handle(self, queue, receipt_handle):
""" Delete a message from a queue, given a receipt handle. :type queue: A :class:`boto.sqs.queue.Que... |
params = {'ReceiptHandle' : receipt_handle}
return self.get_status('DeleteMessage', params, queue.id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_message_batch(self, queue, messages):
""" Delivers up to 10 messages to a queue in a single request. :type queue: A :class:`boto.sqs.queue.Queue` object... |
params = {}
for i, msg in enumerate(messages):
p_name = 'SendMessageBatchRequestEntry.%i.Id' % (i+1)
params[p_name] = msg[0]
p_name = 'SendMessageBatchRequestEntry.%i.MessageBody' % (i+1)
params[p_name] = msg[1]
p_name = 'SendMessageBatchReque... |
<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_queues(self, prefix=''):
""" Retrieves all queues. :keyword str prefix: Optionally, only return queues that start with this value. :rtype: list :retu... |
params = {}
if prefix:
params['QueueNamePrefix'] = prefix
return self.get_list('ListQueues', params, [('QueueUrl', Queue)]) |
<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_queue(self, queue_name):
""" Retrieves the queue with the given name, or ``None`` if no match was found. :param str queue_name: The name of the queue to ... |
rs = self.get_all_queues(queue_name)
for q in rs:
if q.url.endswith(queue_name):
return q
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def increase_and_check_counter(self):
''' increase counter by one and check whether a period is end '''
self.counter += 1
self.counter %= self.period
if not self.counter:
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 match_one(template, image, options=None):
""" Match template and find exactly one match in the Image using specified features. :param template: Template Imag... |
heatmap, scale = multi_feat_match(template, image, options)
min_val, _, min_loc, _ = cv.minMaxLoc(heatmap)
top_left = tuple(scale * x for x in min_loc)
score = min_val
h, w = template.shape[:2]
return Box(top_left[0], top_left[1], w, h), score |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def feature_match(template, image, options=None):
""" Match template and image by extracting specified feature :param template: Template image :param image: Sear... |
op = _DEF_TM_OPT.copy()
if options is not None:
op.update(options)
feat = fe.factory(op['feature'])
tmpl_f = feat(template, op)
img_f = feat(image, op)
scale = image.shape[0] / img_f.shape[0]
heatmap = match_template(tmpl_f, img_f, op)
return heatmap, scale |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_template(template, image, options=None):
""" Multi channel template matching using simple correlation distance :param template: Template image :param i... |
# If the input has max of 3 channels, use the faster OpenCV matching
if len(image.shape) <= 3 and image.shape[2] <= 3:
return match_template_opencv(template, image, options)
op = _DEF_TM_OPT.copy()
if options is not None:
op.update(options)
template = img_utils.gray3(template)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_template_opencv(template, image, options):
""" Match template using OpenCV template matching implementation. Limited by number of channels as maximum o... |
# if image has more than 3 channels, use own implementation
if len(image.shape) > 3:
return match_template(template, image, options)
op = _DEF_TM_OPT.copy()
if options is not None:
op.update(options)
method = cv.TM_CCORR_NORMED
if op['normalize'] and op['distance'] == 'euclide... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resp_json(resp):
""" Get JSON from response if success, raise requests.HTTPError otherwise. Args: resp: requests.Response or flask.Response Retuens: JSON val... |
if isinstance(resp, flask.Response):
if 400 <= resp.status_code < 600:
msg = resp.status
try:
result = loads(resp.data.decode("utf-8"))
if isinstance(result, str):
msg = "%s, %s" % (resp.status, result)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_event(data):
"""Translates a dictionary of event attributes to an Event object :param dict data: The attributes to be set on the event :returns: A pro... |
event = riemann_client.riemann_pb2.Event()
event.host = socket.gethostname()
event.tags.extend(data.pop('tags', []))
for key, value in data.pop('attributes', {}).items():
attribute = event.attributes.add()
attribute.key, attribute.value = key, value
for... |
<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_events(self, events):
"""Sends multiple events to Riemann in a single message :param events: A list or iterable of ``Event`` objects :returns: The respo... |
message = riemann_client.riemann_pb2.Msg()
for event in events:
message.events.add().MergeFrom(event)
return self.transport.send(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def events(self, *events):
"""Sends multiple events in a single message :param \*events: event dictionaries for :py:func:`create_event` :returns: The response me... |
return self.send_events(self.create_event(e) for e in events) |
<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_dict(event):
"""Translates an Event object to a dictionary of event attributes All attributes are included, so ``create_dict(create_event(input))`` ma... |
data = dict()
for descriptor, value in event.ListFields():
if descriptor.name == 'tags':
value = list(value)
elif descriptor.name == 'attributes':
value = dict(((a.key, a.value) for a in value))
data[descriptor.name] = 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 send_events(self, events):
"""Adds multiple events to the queued message :returns: None - nothing has been sent to the Riemann server yet """ |
for event in events:
self.queue.events.add().MergeFrom(event)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetValidHostsForCert(cert):
"""Returns a list of valid host globs for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. Returns: ... |
if 'subjectAltName' in cert:
return [x[1] for x in cert['subjectAltName'] if x[0].lower() == 'dns']
else:
return [x[0][1] for x in cert['subject']
if x[0][0].lower() == 'commonname'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ValidateCertificateHostname(cert, hostname):
"""Validates that a given hostname is valid for an SSL certificate. Args: cert: A dictionary representing an SSL... |
hosts = GetValidHostsForCert(cert)
boto.log.debug(
"validating server certificate: hostname=%s, certificate hosts=%s",
hostname, hosts)
for host in hosts:
host_re = host.replace('.', '\.').replace('*', '[^.]*')
if re.search('^%s$' % (host_re,), hostname, re.I):
return True
return Fals... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, cards, end=TOP):
""" Adds the given list of ``Card`` instances to the top of the stack. :arg cards: The cards to add to the ``Stack``. Can be a sin... |
if end is TOP:
try:
self.cards += cards
except:
self.cards += [cards]
elif end is BOTTOM:
try:
self.cards.extendleft(cards)
except:
self.cards.extendleft([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 deal(self, num=1, end=TOP):
""" Returns a list of cards, which are removed from the Stack. :arg int num: The number of cards to deal. :arg str end: Which end... |
ends = {TOP: self.cards.pop, BOTTOM: self.cards.popleft}
self_size = self.size
if num <= self_size:
dealt_cards = [None] * num
else:
num = self_size
dealt_cards = [None] * self_size
if self_size:
for n in xrange(num):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def empty(self, return_cards=False):
""" Empties the stack, removing all cards from it, and returns them. :arg bool return_cards: Whether or not to return the ca... |
cards = list(self.cards)
self.cards = []
if return_cards:
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 find(self, term, limit=0, sort=False, ranks=None):
""" Searches the stack for cards with a value, suit, name, or abbreviation matching the given argument, 't... |
ranks = ranks or self.ranks
found_indices = []
count = 0
if not limit:
for i, card in enumerate(self.cards):
if check_term(card, term):
found_indices.append(i)
else:
for i, card in enumerate(self.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 get_list(self, terms, limit=0, sort=False, ranks=None):
""" Get the specified cards from the stack. :arg term: The search term. Can be a card full name, valu... |
ranks = ranks or self.ranks
got_cards = []
try:
indices = self.find_list(terms, limit=limit)
got_cards = [self.cards[i] for i in indices if self.cards[i]
not in got_cards]
self.cards = [v for i, v in enumerate(self.cards) if
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 insert(self, card, indice=-1):
""" Insert a given card into the stack at a given indice. :arg Card card: The card to insert into the stack. :arg int indice: ... |
self_size = len(self.cards)
if indice in [0, -1]:
if indice == -1:
self.cards.append(card)
else:
self.cards.appendleft(card)
elif indice != self_size:
half_x, half_y = self.split(indice)
self.cards = list(half_x.ca... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert_list(self, cards, indice=-1):
""" Insert a list of given cards into the stack at a given indice. :arg list cards: The list of cards to insert into the... |
self_size = len(self.cards)
if indice in [0, -1]:
if indice == -1:
self.cards += cards
else:
self.cards.extendleft(cards)
elif indice != self_size:
half_x, half_y = self.split(indice)
self.cards = list(half_x.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 is_sorted(self, ranks=None):
""" Checks whether the stack is sorted. :arg dict ranks: The rank dict to reference for checking. If ``None``, it will default t... |
ranks = ranks or self.ranks
return check_sorted(self, ranks) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shuffle(self, times=1):
""" Shuffles the Stack. .. note:: Shuffling large numbers of cards (100,000+) may take a while. :arg int times: The number of times t... |
for _ in xrange(times):
random.shuffle(self.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 sort(self, ranks=None):
""" Sorts the stack, either by poker ranks, or big two ranks. :arg dict ranks: The rank dict to reference for sorting. If ``None``, i... |
ranks = ranks or self.ranks
self.cards = sort_cards(self.cards, ranks) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split(self, indice=None):
""" Splits the Stack, either in half, or at the given indice, into two separate Stacks. :arg int indice: Optional. The indice to sp... |
self_size = self.size
if self_size > 1:
if not indice:
mid = self_size // 2
return Stack(cards=self[0:mid]), Stack(cards=self[mid::])
else:
return Stack(cards=self[0:indice]), Stack(cards=self[indice::])
else:
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 abort(code, error=None, message=None):
""" Abort with suitable error response Args: code (int):
status code error (str):
error symbol or flask.Response mes... |
if error is None:
flask_abort(code)
elif isinstance(error, Response):
error.status_code = code
flask_abort(code, response=error)
else:
body = {
"status": code,
"error": error,
"message": message
}
flask_abort(code, response... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export(rv, code=None, headers=None):
""" Create a suitable response Args: rv: return value of action code: status code headers: response headers Returns: fla... |
if isinstance(rv, ResponseBase):
return make_response(rv, code, headers)
else:
if code is None:
code = 200
mediatype = request.accept_mimetypes.best_match(
exporters.keys(), default='application/json')
return exporters[mediatype](rv, code, headers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_docs(docs, marks):
""" Parse YAML syntax content from docs If docs is None, return {} If docs has no YAML content, return {"$desc": docs} Else, parse Y... |
if docs is None:
return {}
indexs = []
for mark in marks:
i = docs.find(mark)
if i >= 0:
indexs.append(i)
if not indexs:
return {"$desc": textwrap.dedent(docs).strip()}
start = min(indexs)
start = docs.rfind("\n", 0, start)
yamltext = textwrap.ded... |
<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_data():
""" Get request data based on request.method If method is GET or DELETE, get data from request.args If method is POST, PATCH or PUT, get ... |
method = request.method.lower()
if method in ["get", "delete"]:
return request.args
elif method in ["post", "put", "patch"]:
if request.mimetype == 'application/json':
try:
return request.get_json()
except:
abort(400, "InvalidData", "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 get_title(desc, default=None):
"""Get title of desc""" |
if not desc:
return default
lines = desc.strip('\n').split('\n')
if not lines:
return default
return lines[0].lstrip('# ').rstrip(' ') |
<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_action(self, fn, schema_parser, meta):
""" Make resource's method an action Validate input, output by schema in meta. If no input schema, call fn withou... |
validate_input = validate_output = None
if "$input" in meta:
with MarkKey("$input"):
validate_input = schema_parser.parse(meta["$input"])
if "$output" in meta:
with MarkKey("$output"):
validate_output = schema_parser.parse(meta["$output"])... |
<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_view(self, action_group):
""" Create a view function Check permission and Dispatch request to action by request.method """ |
def view(*args, **kwargs):
try:
httpmathod = request.method.lower()
if httpmathod not in action_group:
abort(405)
resp = self._before_request()
if resp is None:
fn = action_group[httpmathod]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regions():
""" Get all available regions for the SNS service. :rtype: list :return: A list of :class:`boto.regioninfo.RegionInfo` instances """ |
return [RegionInfo(name='us-east-1',
endpoint='sns.us-east-1.amazonaws.com',
connection_cls=SNSConnection),
RegionInfo(name='eu-west-1',
endpoint='sns.eu-west-1.amazonaws.com',
connection_cls=SNSConnection),
... |
<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_tag(self, key, value=''):
""" Add a tag to this object. Tag's are stored by AWS and can be used to organize and filter resources. Adding a tag involves a... |
status = self.connection.create_tags([self.id], {key : value})
if self.tags is None:
self.tags = TagSet()
self.tags[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 remove_tag(self, key, value=None):
""" Remove a tag from this object. Removing a tag involves a round-trip to the EC2 service. :type key: str :param key: The... |
if value:
tags = {key : value}
else:
tags = [key]
status = self.connection.delete_tags([self.id], tags)
if key in self.tags:
del self.tags[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 read(self, frame, data):
"Returns a list of values, eats all of data."
seq = []
while data:
elem, data = self.spec.read(frame, data)
seq.append(elem)
return seq, 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 to_xml(self):
"""Get this batch as XML""" |
assert self.connection != None
s = '<?xml version="1.0" encoding="UTF-8"?>\n'
s += '<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/%s/">\n' % self.connection.Version
for p in self.paths:
s += ' <Path>%s</Path>\n' % self.escape(p)
s += ' <CallerRe... |
<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_messages(self, num_messages=1, visibility_timeout=None, attributes=None, callback=None):
""" Get a variable number of messages. :type num_messages: int :... |
return self.connection.receive_message(self, number_messages=num_messages,
visibility_timeout=visibility_timeout,
attributes=attributes, callback=callback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_message(self, message, callback=None):
""" Delete a message from the queue. :type message: :class:`boto.sqs.message.Message` :param message: The :clas... |
return self.connection.delete_message(self, message, callback=callback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_query(self, symbol, start_date, end_date):
"""Method returns prepared request query for Yahoo YQL API.""" |
query = \
'select * from yahoo.finance.historicaldata where symbol = "%s" and startDate = "%s" and endDate = "%s"' \
% (symbol, start_date, end_date)
return 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 send(self, symbol, start_date, end_date):
"""Method sends request to Yahoo YQL API.""" |
query = self.prepare_query(symbol, start_date, end_date)
self.parameters['q'] = query
response = requests.get(self.api, params=self.parameters).json()
results = response['query']['results']['quote']
return results |
<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, method, url, post_data=None, body=None):
""" Make a request on this connection """ |
if not self.connection:
self._connect()
try:
self.connection.close()
except:
pass
self.connection.connect()
headers = {}
if self.auth_header:
headers["Authorization"] = self.auth_header
self.connection.request(metho... |
<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_object(self, obj, expected_value=None):
""" Marshal the object and do a PUT """ |
doc = self.marshal_object(obj)
if obj.id:
url = "/%s/%s" % (self.db_name, obj.id)
else:
url = "/%s" % (self.db_name)
resp = self._make_request("PUT", url, body=doc.toxml())
new_obj = self.get_object_from_doc(obj.__class__, None, parse(resp))
obj.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 unmarshal_props(self, fp, cls=None, id=None):
""" Same as unmarshalling an object, except it returns from "get_props_from_doc" """ |
if isinstance(fp, str) or isinstance(fp, unicode):
doc = parseString(fp)
else:
doc = parse(fp)
return self.get_props_from_doc(cls, id, doc) |
<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 DB instance's status information by making a call to fetch the current instance attributes from the service. :ty... |
rs = self.connection.get_all_dbinstances(self.id)
if len(rs) > 0:
for i in rs:
if i.id == self.id:
self.__dict__.update(i.__dict__)
elif validate:
raise ValueError('%s is not a valid Instance ID' % self.id)
return self.status |
<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, skip_final_snapshot=False, final_snapshot_id=''):
""" Delete this DBInstance. :type skip_final_snapshot: bool :param skip_final_snapshot: This par... |
return self.connection.delete_dbinstance(self.id,
skip_final_snapshot,
final_snapshot_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modify(self, param_group=None, security_groups=None, preferred_maintenance_window=None, master_password=None, allocated_storage=None, instance_class=None, bac... |
return self.connection.modify_dbinstance(self.id,
param_group,
security_groups,
preferred_maintenance_window,
maste... |
<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(self, limit, offset=0):
"""Not currently fully supported, but we can use this to allow them to set a limit in a chainable method""" |
self.limit = limit
self.offset = offset
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 from_json(cls, json_doc):
""" Create and return a new Session Token based on the contents of a JSON document. :type json_doc: str :param json_doc: A string c... |
d = json.loads(json_doc)
token = cls()
token.__dict__.update(d)
return 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 load(cls, file_path):
""" Create and return a new Session Token based on the contents of a previously saved JSON-format file. :type file_path: str :param fil... |
fp = open(file_path)
json_doc = fp.read()
fp.close()
return cls.from_json(json_doc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self):
""" Return a Python dict containing the important information about this Session Token. """ |
return {'access_key': self.access_key,
'secret_key': self.secret_key,
'session_token': self.session_token,
'expiration': self.expiration,
'request_id': self.request_id} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, file_path):
""" Persist a Session Token to a file in JSON format. :type path: str :param path: The fully qualified path to the file where the the ... |
fp = open(file_path, 'wb')
json.dump(self.to_dict(), fp)
fp.close()
os.chmod(file_path, 0600) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_expired(self, time_offset_seconds=0):
""" Checks to see if the Session Token is expired or not. By default it will check to see if the Session Token is ex... |
now = datetime.datetime.utcnow()
if time_offset_seconds:
now = now + datetime.timedelta(seconds=time_offset_seconds)
ts = boto.utils.parse_ts(self.expiration)
delta = ts - now
return delta.total_seconds() <= 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_cron(self, name, minute, hour, mday, month, wday, who, command, env=None):
""" Add an entry to the system crontab. """ |
raise NotImplementedError |
<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_location(self, ip, detailed=False):
"""Returns a dictionary with location data or False on failure. Amount of information about IP contained in the dicti... |
seek = self._get_pos(ip)
if seek > 0:
return self._parse_location(seek, detailed=detailed)
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 get_locations(self, ip, detailed=False):
"""Returns a list of dictionaries with location data or False on failure. Argument `ip` must be an iterable object. ... |
if isinstance(ip, str):
ip = [ip]
seek = map(self._get_pos, ip)
return [self._parse_location(elem, detailed=detailed) if elem > 0 else False for elem in seek] |
<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_auth_handler(host, config, provider, requested_capability=None):
"""Finds an AuthHandler that is ready to authenticate. Lists through all the registered ... |
ready_handlers = []
auth_handlers = boto.plugin.get_plugin(AuthHandler, requested_capability)
total_handlers = len(auth_handlers)
for handler in auth_handlers:
try:
ready_handlers.append(handler(host, config, provider))
except boto.auth_handler.NotReadyToAuthenticate:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def headers_to_sign(self, http_request):
""" Select the headers from the request that need to be included in the StringToSign. """ |
headers_to_sign = {}
headers_to_sign = {'Host' : self.host}
for name, value in http_request.headers.items():
lname = name.lower()
if lname.startswith('x-amz'):
headers_to_sign[name] = value
return headers_to_sign |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def canonical_headers(self, headers_to_sign):
""" Return the headers that need to be included in the StringToSign in their canonical form by converting all heade... |
l = ['%s:%s'%(n.lower().strip(),
headers_to_sign[n].strip()) for n in headers_to_sign]
l.sort()
return '\n'.join(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 string_to_sign(self, http_request):
""" Return the canonical StringToSign as well as a dict containing the original version of all headers that were included... |
headers_to_sign = self.headers_to_sign(http_request)
canonical_headers = self.canonical_headers(headers_to_sign)
string_to_sign = '\n'.join([http_request.method,
http_request.path,
'',
ca... |
<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_auth(self, req, **kwargs):
""" Add AWS3 authentication to a request. :type req: :class`boto.connection.HTTPRequest` :param req: The HTTPRequest object. "... |
# This could be a retry. Make sure the previous
# authorization header is removed first.
if 'X-Amzn-Authorization' in req.headers:
del req.headers['X-Amzn-Authorization']
req.headers['X-Amz-Date'] = formatdate(usegmt=True)
req.headers['X-Amz-Security-Token'] = 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 is_capable(cls, requested_capability):
"""Returns true if the requested capability is supported by this plugin """ |
for c in requested_capability:
if not c in cls.capability:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self):
""" Returns the next connection in this pool that is ready to be reused. Returns None of there aren't any. """ |
# Discard ready connections that are too old.
self.clean()
# Return the first connection that is ready, and remove it
# from the queue. Connections that aren't ready are returned
# to the end of the queue with an updated time, on the
# assumption that somebody is activ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean(self):
""" Get rid of stale connections. """ |
# Note that we do not close the connection here -- somebody
# may still be reading from it.
while len(self.queue) > 0 and self._pair_stale(self.queue[0]):
self.queue.pop(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 put_http_connection(self, host, is_secure, conn):
""" Adds a connection to the pool of connections that can be reused for the named host. """ |
with self.mutex:
key = (host, is_secure)
if key not in self.host_to_pool:
self.host_to_pool[key] = HostConnectionPool()
self.host_to_pool[key].put(conn) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean(self):
""" Clean up the stale connections in all of the pools, and then get rid of empty pools. Pools clean themselves every time a connection is fetch... |
with self.mutex:
now = time.time()
if self.last_clean_time + self.CLEAN_INTERVAL < now:
to_remove = []
for (host, pool) in self.host_to_pool.items():
pool.clean()
if pool.size() == 0:
to_remo... |
<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, method, path, headers=None, data='', host=None, auth_path=None, sender=None, override_num_retries=None):
"""Makes a request to the server,... |
http_request = self.build_base_http_request(method, path, auth_path,
{}, headers, data, host)
return self._mexe(http_request, sender, override_num_retries) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetFilePathsWithDialog(fileTypes=[]):
""" Multipul File Select with dialog fileTypes: you can choise file extension ex) fileTypes=[('Excel Files', '.xlsx')] ... |
root = tkinter.Tk()
root.withdraw()
filepath = filedialog.askopenfilenames(
filetypes=fileTypes, parent=root)
if isinstance(filepath, str):
fileList = filepath.split(" ")
elif isinstance(filepath, tuple):
fileList = list(filepath)
elif isinstance(filepath, list):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetRadioButtonSelect(selectList, title="Select", msg=""):
""" Create radio button window for option selection title: Window name mag: Label of the radio butt... |
root = tkinter.Tk()
root.title(title)
val = tkinter.IntVar()
val.set(0)
if msg != "":
tkinter.Label(root, text=msg).pack()
index = 0
for item in selectList:
tkinter.Radiobutton(root, text=item, variable=val,
value=index).pack(anchor=tkinter.W)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetListSelect(selectList, title="Select", msg=""):
""" Create list with selectList, and then return seleced string and index title: Window name mag: Label of... |
root = tkinter.Tk()
root.title(title)
label = tkinter.Label(root, text=msg)
label.pack()
listbox = tkinter.Listbox(root)
for i in selectList:
listbox.insert(tkinter.END, i)
listbox.pack()
tkinter.Button(root, text="OK", fg="black", command=root.quit).pack()
root.mainloop(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetCheckButtonSelect(selectList, title="Select", msg=""):
""" Get selected check button options title: Window name mag: Label of the check button return sele... |
root = tkinter.Tk()
root.title(title)
label = tkinter.Label(root, text=msg)
label.pack()
optList = []
for item in selectList:
opt = tkinter.BooleanVar()
opt.set(False)
tkinter.Checkbutton(root, text=item, variable=opt).pack()
optList.append(opt)
tkinter.Bu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetEntries(dataList, title="Select", msg=""):
""" Get entries of the list title: Window name mag: Label of the check button return data dictionary like: {'y'... |
root = tkinter.Tk()
root.title(title)
label = tkinter.Label(root, text=msg)
label.pack()
entries = []
for item in dataList:
tkinter.Label(root, text=item).pack()
entry = tkinter.Entry(root)
entry.pack()
entries.append(entry)
# print entries
tkinter.But... |
<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_rule(self, ip_protocol, from_port, to_port, src_group_name, src_group_owner_id, cidr_ip):
""" Add a rule to the SecurityGroup object. Note that this meth... |
rule = IPPermissions(self)
rule.ip_protocol = ip_protocol
rule.from_port = from_port
rule.to_port = to_port
self.rules.append(rule)
rule.add_grant(src_group_name, src_group_owner_id, cidr_ip) |
<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_rule(self, ip_protocol, from_port, to_port, src_group_name, src_group_owner_id, cidr_ip):
""" Remove a rule to the SecurityGroup object. Note that thi... |
target_rule = None
for rule in self.rules:
if rule.ip_protocol == ip_protocol:
if rule.from_port == from_port:
if rule.to_port == to_port:
target_rule = rule
target_grant = None
for g... |
<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_to_region(self, region, name=None):
""" Create a copy of this security group in another region. Note that the new security group will be a separate enti... |
if region.name == self.region:
raise BotoClientError('Unable to copy to the same Region')
conn_params = self.connection.get_params()
rconn = region.connect(**conn_params)
sg = rconn.create_security_group(name or self.name, self.description)
source_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 instances(self):
""" Find all of the current instances that are running within this security group. :rtype: list of :class:`boto.ec2.instance.Instance` :retu... |
# It would be more efficient to do this with filters now
# but not all services that implement EC2 API support filters.
instances = []
rs = self.connection.get_all_instances()
for reservation in rs:
uses_group = [g.name for g in reservation.groups if g.name == self.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 build_post_policy(self, expiration_time, conditions):
""" Taken from the AWS book Python examples and modified for use with boto """ |
assert type(expiration_time) == time.struct_time, \
'Policy document must include a valid expiration Time object'
# Convert conditions object mappings to condition statements
return '{"expiration": "%s",\n"conditions": [%s]}' % \
(time.strftime(boto.utils.ISO8601, expi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.