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 calculate_infixop(self, node, previous, next_node):
"""Create new node for infixop""" |
previous_position = (previous.last_line, previous.last_col - 1)
position = (next_node.first_line, next_node.first_col + 1)
possible = []
for ch in OPERATORS[node.__class__]:
try:
pos = self.operators[ch].find_previous(position)
if previous_position < pos[1] < position:
possible.append(pos)
except KeyError:
pass
if not possible:
raise ValueError("not a single {} between {} and {}".format(
OPERATORS[node.__class__], previous_position, position))
return NodeWithPosition(
*min(possible, key=lambda x: tuple(map(sub, position, x[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 calculate_unaryop(self, node, next_node):
"""Create new node for unaryop""" |
position = (next_node.first_line, next_node.first_col + 1)
possible = []
for ch in OPERATORS[node.__class__]:
try:
pos = self.operators[ch].find_previous(position)
if pos[1] < position:
possible.append(pos)
except KeyError:
pass
return NodeWithPosition(
*min(possible, key=lambda x: tuple(map(sub, position, x[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 uid_something_colon(self, node):
""" Creates op_pos for node from uid to colon """ |
node.op_pos = [
NodeWithPosition(node.uid, (node.first_line, node.first_col))
]
position = (node.body[0].first_line, node.body[0].first_col)
last, first = self.operators[':'].find_previous(position)
node.op_pos.append(NodeWithPosition(last, first))
return last |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def optional_else(self, node, last):
""" Create op_pos for optional else """ |
if node.orelse:
min_first_max_last(node, node.orelse[-1])
if 'else' in self.operators:
position = (node.orelse[0].first_line, node.orelse[0].first_col)
_, efirst = self.operators['else'].find_previous(position)
if efirst and efirst > last:
elast, _ = self.operators[':'].find_previous(position)
node.op_pos.append(NodeWithPosition(elast, efirst)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comma_separated_list(self, node, subnodes):
"""Process comma separated list """ |
for item in subnodes:
position = (item.last_line, item.last_col)
first, last = find_next_comma(self.lcode, position)
if first: # comma exists
node.op_pos.append(NodeWithPosition(last, first)) |
<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_next_comma(self, node, sub):
"""Find comma after sub andd add NodeWithPosition in node""" |
position = (sub.last_line, sub.last_col)
first, last = find_next_comma(self.lcode, position)
if first: # comma exists
node.op_pos.append(NodeWithPosition(last, first)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fields(self):
""" Provides an iterable for all model fields. """ |
for attr, value in self._meta.fields.items():
if isinstance(value, Field):
yield attr, 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 wrap(self, data):
""" Wraps and consumes an arbitrary dictionary into the model. """ |
for name, field in self.fields:
try:
self._state[name] = field.consume(
self._state.get(name, None), data[name])
except KeyError:
self._state[name] = 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 validate(self):
""" Validates all field values for the model. """ |
errors = {}
for name, field in self.fields:
try:
field.validate(self._state.get(name))
except Exception as e:
errors[name] = e
if len(errors) is not 0:
raise Exception(errors)
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:
async def save(self):
""" Persists the model to the database. If the model holds no primary key, a new one will automatically created by RethinkDB. Otherwise it will overwrite the current model persisted to the database. """ |
if hasattr(self, "before_save"):
self.before_save()
query = r.table(self.table_name)
if self._state.get("id"):
query = query \
.get(self._state.get("id")) \
.update(self.__db_repr, return_changes=True)
else:
query = query \
.insert(self.__db_repr, return_changes=True)
resp = await query.run(await conn.get())
try:
changes = resp["changes"]
if len(changes) > 0:
self.wrap(resp["changes"][0]["new_val"])
except KeyError:
raise UnexpectedDbResponse()
if resp["skipped"] > 0:
raise UnexpectedDbResponse(
"Model with id `%s` not found in the database." %
self._state.get("id"))
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:
async def delete(self):
""" Deletes the model from the database. """ |
await r.table_name(self.table_name) \
.get(self.id) \
.delete() \
.run(await conn.get()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _raw_split(itxt):
""" Parse HTML from text into array filled with tags end text. Source code is little bit unintutive, because it is state machine parser. For better understanding, look at http://bit.ly/1rXRcJj Example:: ['<html>', '<tag params="true">', '</html>'] Args: itxt (str):
Input HTML text, which will be parsed. Returns: list: List of strings (input splitted to tags and text). """ |
echr = ""
buff = ["", "", "", ""]
content = ""
array = []
next_state = 0
inside_tag = False
escaped = False
COMMENT_START = ["-", "!", "<"]
COMMENT_END = ["-", "-"]
gc.disable()
for c in itxt:
# content
if next_state == StateEnum.content:
if c == "<":
if content:
array.append(content)
content = c
next_state = StateEnum.tag
inside_tag = False
else:
content += c
# html tag
elif next_state == StateEnum.tag:
if c == ">":
array.append(content + c)
content = ""
next_state = StateEnum.content
elif c == "'" or c == '"':
echr = c
content += c
next_state = StateEnum.parameter
elif c == "-" and buff[:3] == COMMENT_START:
if content[:-3]:
array.append(content[:-3])
content = content[-3:] + c
next_state = StateEnum.comment
else:
if c == "<": # jump back into tag instead of content
array.append(content)
inside_tag = True
content = ""
content += c
# quotes "" / ''
elif next_state == StateEnum.parameter:
if c == echr and not escaped: # end of quotes
next_state = StateEnum.tag
# unescaped end of line - this is good for invalid HTML like
# <a href=something">..., because it allows recovery
if c == "\n" and not escaped and buff[0] == ">":
next_state = StateEnum.content
inside_tag = False
content += c
escaped = not escaped if c == "\\" else False
# html comments
elif next_state == StateEnum.comment:
if c == ">" and buff[:2] == COMMENT_END:
next_state = StateEnum.tag if inside_tag else StateEnum.content
inside_tag = False
array.append(content + c)
content = ""
else:
content += c
# rotate buffer
buff = _rotate_buff(buff)
buff[0] = c
gc.enable()
if content:
array.append(content)
return array |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _indexOfEndTag(istack):
""" Go through `istack` and search endtag. Element at first index is considered as opening tag. Args: istack (list):
List of :class:`.HTMLElement` objects. Returns: int: Index of end tag or 0 if not found. """ |
if len(istack) <= 0:
return 0
if not istack[0].isOpeningTag():
return 0
cnt = 0
opener = istack[0]
for index, el in enumerate(istack[1:]):
if el.isOpeningTag() and \
el.getTagName().lower() == opener.getTagName().lower():
cnt += 1
elif el.isEndTagTo(opener):
if cnt == 0:
return index + 1
cnt -= 1
return 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 _parseDOM(istack):
""" Recursively go through element array and create DOM. Args: istack (list):
List of :class:`.HTMLElement` objects. Returns: list: DOM tree as list. """ |
ostack = []
end_tag_index = 0
def neither_nonpair_or_end_or_comment(el):
return not (el.isNonPairTag() or el.isEndTag() or el.isComment())
index = 0
while index < len(istack):
el = istack[index]
# check if this is pair tag
end_tag_index = _indexOfEndTag(istack[index:])
if end_tag_index == 0 and neither_nonpair_or_end_or_comment(el):
el.isNonPairTag(True)
if end_tag_index == 0:
if not el.isEndTag():
ostack.append(el)
else:
el.childs = _parseDOM(istack[index + 1: end_tag_index + index])
el.endtag = istack[end_tag_index + index] # reference to endtag
el.endtag.openertag = el
ostack.append(el)
ostack.append(el.endtag)
index = end_tag_index + index
index += 1
return ostack |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makeDoubleLinked(dom, parent=None):
""" Standard output from `dhtmlparser` is single-linked tree. This will make it double-linked. Args: dom (obj):
:class:`.HTMLElement` instance. parent (obj, default None):
Don't use this, it is used in recursive call. """ |
dom.parent = parent
for child in dom.childs:
child.parent = dom
makeDoubleLinked(child, dom) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeTags(dom):
""" Remove all tags from `dom` and obtain plaintext representation. Args: dom (str, obj, array):
str, HTMLElement instance or array of elements. Returns: str: Plain string without tags. """ |
# python 2 / 3 shill
try:
string_type = basestring
except NameError:
string_type = str
# initialize stack with proper value (based on dom parameter)
element_stack = None
if type(dom) in [list, tuple]:
element_stack = dom
elif isinstance(dom, HTMLElement):
element_stack = dom.childs if dom.isTag() else [dom]
elif isinstance(dom, string_type):
element_stack = parseString(dom).childs
else:
element_stack = dom
# remove all tags
output = ""
while element_stack:
el = element_stack.pop(0)
if not (el.isTag() or el.isComment() or not el.getTagName()):
output += el.__str__()
if el.childs:
element_stack = el.childs + element_stack
return 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 has_method(obj, name):
""" Checks if object has a method with specified name. :param obj: an object to introspect. :param name: a name of the method to check. :return: true if the object has the method and false if it doesn't. """ |
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Method name cannot be null")
name = name.lower()
for method_name in dir(obj):
if method_name.lower() != name:
continue
method = getattr(obj, method_name)
if MethodReflector._is_method(method, method_name):
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 invoke_method(obj, name, *args):
""" Invokes an object method by its name with specified parameters. :param obj: an object to invoke. :param name: a name of the method to invoke. :param args: a list of method arguments. :return: the result of the method invocation or null if method returns void. """ |
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Method name cannot be null")
name = name.lower()
try:
for method_name in dir(obj):
if method_name.lower() != name:
continue
method = getattr(obj, method_name)
if MethodReflector._is_method(method, method_name):
return method(*args)
except:
pass
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 get_method_names(obj):
""" Gets names of all methods implemented in specified object. :param obj: an object to introspect. :return: a list with method names. """ |
method_names = []
for method_name in dir(obj):
method = getattr(obj, method_name)
if MethodReflector._is_method(method, method_name):
method_names.append(method_name)
return method_names |
<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_to_delivery_stream(events, stream_name):
"""Sends a list of events to a Firehose delivery stream.""" |
if not events:
logger.info("No events provided: nothing delivered to Firehose")
return
records = []
for event in events:
if not isinstance(event, str):
# csv events already have a newline
event = json.dumps(event) + "\n"
records.append({"Data": event})
firehose = boto3.client("firehose")
logger.info("Delivering %s records to Firehose stream '%s'",
len(records), stream_name)
resp = firehose.put_record_batch(
DeliveryStreamName=stream_name,
Records=records)
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_to_kinesis_stream(events, stream_name, partition_key=None, packer=None, serializer=json.dumps):
"""Sends events to a Kinesis stream.""" |
if not events:
logger.info("No events provided: nothing delivered to Firehose")
return
records = []
for event in events:
if not partition_key:
partition_key_value = str(uuid.uuid4())
elif hasattr(partition_key, "__call__"):
partition_key_value = partition_key(event)
else:
partition_key_value = partition_key
if not isinstance(event, str):
event = serializer(event)
if packer:
event = packer(event)
record = {"Data": event,
"PartitionKey": partition_key_value}
records.append(record)
kinesis = boto3.client("kinesis")
resp = kinesis.put_records(StreamName=stream_name, Records=records)
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_app(self, app):
"""Register the extension with the application. Args: app (flask.Flask):
The application to register with. """ |
app.url_rule_class = partial(NavigationRule, copilot=self)
app.context_processor(self.inject_context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inject_context(self):
"""Return a dict used for a template context.""" |
navbar = filter(lambda entry: entry.visible, self.navbar_entries)
return {'navbar': navbar} |
<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_entry(self, navbar_kwargs):
"""Register a navbar entry with the copilot. Args: navbar_kwargs (dict):
Arguments passed to the :class:`NavbarEntry` instance. """ |
# Add a new rule for each level in the path.
path = navbar_kwargs.pop('path')
# If a single object is used rather than an iterable (including
# a single string), wrap it before using.
if not hasattr(path, '__iter__') or isinstance(path, basestring):
path = [path]
entry_group = self.navbar_entries
# HACK: I'd like to intelligently replace the URL rule in the
# case where the intended rule is provided, but the function has
# already created a blank "placeholder" rule for it. There are
# probably nicer ways to approach this, but it works.
for name, is_last in iter_islast(path):
kwargs = deepcopy(navbar_kwargs)
kwargs['name'] = name
for existing_entry in entry_group:
# If there's an existing entry for this "link", use it
# instead of creating a new one. If this existing entry
# has no rule and this is the last item in ``path``, the
# rule was intended to be assigned to this entry, so
# overwrite the blank rule with the one provided via
# ``navbar_kwargs``.
if existing_entry.name == name:
entry = existing_entry
if is_last:
entry.endpoint = kwargs['endpoint']
break
else:
# If we can't find an existing entry, create one with a
# blank endpoint. If this rule is not the final one in
# the list, the endpoint was not intended for this, so
# don't assign it.
if not is_last:
kwargs['endpoint'] = None
entry = NavbarEntry(**kwargs)
entry_group.add(entry)
entry_group = entry.children |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reversed(self):
"""Create a connectivity matrix where each incoming edge becomes outgoing.""" |
n_rows = len(self)
reversed = DirectedAdjacencyMatrix(n_rows, self.dtype)
for r, row in enumerate(py.prog_iter(self)):
for c in row:
reversed[c].append(r)
return reversed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crc7(data):
""" Compute CRC of a whole message. """ |
crc = 0
for c in data:
crc = CRC7_TABLE[crc ^ c]
return crc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unhandledInput(event, workbench, launcher):
"""Handles input events that weren't handled anywhere else. """ |
if event == "ctrl w":
raise urwid.ExitMainLoop()
elif event == "esc":
workbench.clear()
workbench.display(launcher)
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 _runPopUp(workbench, popUp):
"""Displays the pop-up on the workbench and gets a completion notification deferred. When that fires, undisplay the pop-up and return the result of the notification deferred verbatim. """ |
workbench.display(popUp)
d = popUp.notifyCompleted()
d.addCallback(_popUpCompleted, workbench)
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 display(self, tool):
"""Displays the given tool above the current layer, and sets the title to its name. """ |
self._tools.append(tool)
self._justDisplay(tool) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _justDisplay(self, tool):
""" Displays the given tool. Does not register it in the tools list. """ |
self.header.title.set_text(tool.name)
body, _options = self.widget.contents["body"]
overlay = urwid.Overlay(tool.widget, body, *tool.position)
self._surface = urwid.AttrMap(overlay, "foreground")
self.widget.contents["body"] = self._surface, 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 undisplay(self):
"""Undisplays the top tool. This actually forces a complete re-render. """ |
self._tools.pop()
self._justClear()
for tool in self._tools:
self._justDisplay(tool) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _makeButtons(self):
"""Makes buttons and wires them up. """ |
self.button = button = urwid.Button(u"OK")
urwid.connect_signal(button, "click", self._completed)
return [self.button] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _makeTextWidgets(self):
"""Makes an editable prompt widget. """ |
self.prompt = urwid.Edit(self.promptText, multiline=False)
return [self.prompt] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _secrets_table_name(environment=None, stage=None):
"""Name of the secrets table associated to a humilis deployment.""" |
if environment is None:
environment = os.environ.get("HUMILIS_ENVIRONMENT")
if stage is None:
stage = os.environ.get("HUMILIS_STAGE")
if environment:
if stage:
return "{environment}-{stage}-secrets".format(**locals())
else:
return "{environment}-secrets".format(**locals()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _state_table_name(environment=None, layer=None, stage=None):
"""The name of the state table associated to a humilis deployment.""" |
if environment is None:
# For backwards compatiblity
environment = os.environ.get("HUMILIS_ENVIRONMENT")
if layer is None:
layer = os.environ.get("HUMILIS_LAYER")
if stage is None:
stage = os.environ.get("HUMILIS_STAGE")
if environment:
if stage:
return "{environment}-{layer}-{stage}-state".format(
**locals())
else:
return "{environment}-{layer}-state".format(**locals()) |
<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_secret_from_vault( key, environment=None, stage=None, namespace=None, wait_exponential_multiplier=50, wait_exponential_max=5000, stop_max_delay=10000):
"""Retrieves a secret from the secrets vault.""" |
# Get the encrypted secret from DynamoDB
table_name = _secrets_table_name(environment=environment, stage=stage)
if namespace:
key = "{}:{}".format(namespace, key)
if table_name is None:
logger.warning("Can't produce secrets table name: unable to retrieve "
"secret '{}'".format(key))
return
client = boto3.client('dynamodb')
logger.info("Retriving key '{}' from table '{}'".format(
key, table_name))
@retry(retry_on_exception=_is_critical_exception,
wait_exponential_multiplier=wait_exponential_multiplier,
wait_exponential_max=wait_exponential_max,
stop_max_delay=stop_max_delay)
def get_item():
try:
return client.get_item(
TableName=table_name,
Key={'id': {'S': key}}).get('Item', {}).get(
'value', {}).get('B')
except Exception as err:
if _is_dynamodb_critical_exception(err):
raise CriticalError(err)
else:
raise
encrypted = get_item()
if encrypted is None:
return
# Decrypt using KMS
client = boto3.client('kms')
try:
value = client.decrypt(CiphertextBlob=encrypted)['Plaintext'].decode()
except ClientError:
logger.error("KMS error when trying to decrypt secret")
traceback.print_exc()
return
try:
value = json.loads(value)
except (TypeError, ValueError):
# It's ok, the client should know how to deal with the value
pass
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 get_secret(key, *args, **kwargs):
"""Retrieves a secret.""" |
env_value = os.environ.get(key.replace('.', '_').upper())
if not env_value:
# Backwards compatibility: the deprecated secrets vault
return _get_secret_from_vault(key, *args, **kwargs)
return env_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_state_batch(keys, namespace=None, consistent=True):
"""Get a batch of items from the state store.""" |
ukeys = set(keys)
if namespace:
ns_keys = ["{}:{}".format(namespace, key) for key in ukeys]
uvalues = {k: v for k, v
in zip(ukeys, get_item_batch(ns_keys, consistent=consistent))}
return list(zip(keys, (uvalues[k] for k in keys))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_state_batch(keys, values, namespace=None, ttl=3600*24*365):
"""Set a batch of items in the state store.""" |
keys, values = zip(*{k: v for k, v in zip(keys, values)}.items())
if namespace:
keys = ["{}:{}".format(namespace, key) for key in keys]
return set_item_batch(keys, values, ttl) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_state(key, value, namespace=None, table_name=None, environment=None, layer=None, stage=None, shard_id=None, consistent=True, serializer=json.dumps, wait_exponential_multiplier=500, wait_exponential_max=5000, stop_max_delay=10000, ttl=None):
"""Set Lambda state value.""" |
if table_name is None:
table_name = _state_table_name(environment=environment, layer=layer,
stage=stage)
if not table_name:
msg = ("Can't produce state table name: unable to set state "
"item '{}'".format(key))
logger.error(msg)
raise StateTableError(msg)
return
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(table_name)
logger.info("Putting {} -> {} in DynamoDB table {}".format(key, value,
table_name))
if serializer:
try:
value = serializer(value)
except TypeError:
logger.error(
"Value for state key '{}' is not json-serializable".format(
key))
raise
if namespace:
key = "{}:{}".format(namespace, key)
if shard_id:
key = "{}:{}".format(shard_id, key)
item = {"id": key, "value": value}
if ttl:
item["ttl"] = {"N": str(int(time.time() + ttl))}
@retry(retry_on_exception=_is_critical_exception,
wait_exponential_multiplier=500,
wait_exponential_max=5000,
stop_max_delay=10000)
def put_item():
try:
return table.put_item(Item=item)
except Exception as err:
if _is_dynamodb_critical_exception(err):
raise CriticalError(err)
else:
raise
resp = put_item()
logger.info("Response from DynamoDB: '{}'".format(resp))
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_state(key, namespace=None, table_name=None, environment=None, layer=None, stage=None, shard_id=None, consistent=True, wait_exponential_multiplier=500, wait_exponential_max=5000, stop_max_delay=10000):
"""Delete Lambda state value.""" |
if table_name is None:
table_name = _state_table_name(environment=environment, layer=layer,
stage=stage)
if not table_name:
msg = ("Can't produce state table name: unable to set state "
"item '{}'".format(key))
logger.error(msg)
raise StateTableError(msg)
return
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(table_name)
logger.info("Deleting {} in DynamoDB table {}".format(key, table_name))
if namespace:
key = "{}:{}".format(namespace, key)
if shard_id:
key = "{}:{}".format(shard_id, key)
@retry(retry_on_exception=_is_critical_exception,
wait_exponential_multiplier=500,
wait_exponential_max=5000,
stop_max_delay=10000)
def delete_item():
try:
return table.delete_item(Key={"id": key})
except Exception as err:
if _is_dynamodb_critical_exception(err):
raise CriticalError(err)
else:
raise
resp = delete_item()
logger.info("Response from DynamoDB: '{}'".format(resp))
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def produce_context(namespace, context_id, max_delay=None):
"""Produce event context.""" |
try:
context_obj = get_context(namespace, context_id)
logger.info("Found context '%s:%s'", namespace, context_id)
except ContextError:
logger.info("Context '%s:%s' not found", namespace, context_id)
if max_delay is not None:
max_delay = float(max_delay)
logger.info("Context error handled with max_delay=%s", max_delay)
if not max_delay \
or arrival_delay_greater_than(context_id, max_delay):
context_obj = {}
logger.info(
"Timeout: waited %s seconds for context '%s'",
max_delay, context_id)
else:
msg = "Context '{}' not found: resorting".format(context_id)
raise OutOfOrderError(msg)
return context_obj |
<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_context(namespace, context_id):
"""Get stored context object.""" |
context_obj = get_state(context_id, namespace=namespace)
if not context_obj:
raise ContextError("Context '{}' not found in namespace '{}'".format(
context_id, namespace))
return context_obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def arrival_delay_greater_than(item_id, delay, namespace="_expected_arrival"):
"""Check if an item arrival is delayed more than a given amount.""" |
expected = get_state(item_id, namespace=namespace)
now = time.time()
if expected and (now - expected) > delay:
logger.error("Timeout: waited %s seconds for parent.", delay)
return True
elif expected:
logger.info("Still out of order but no timeout: %s-%s <= %s.",
now, expected, delay)
return False
elif delay > 0:
logger.info("Storing expected arrival time (%s) for context '%s'",
datetime.fromtimestamp(now).isoformat(), item_id)
set_state(item_id, now, namespace=namespace)
return False
else:
logger.info("Event is out of order but not waiting for parent.")
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(name, stype, **kwargs):
"""Returns the rcParams specified in the style file given by `name` and `stype`. Parameters name: str The name of the style. stype: str Any of ('context', 'style', 'palette'). kwargs: - stylelib_url: str Overwrite the value in the local config with the specified url. - ignore_cache: bool Ignore files in the cache and force loading from the stylelib. Raises ------ ValueError: If `stype` is not any of ('context', 'style', 'palette') Returns ------- rcParams: dict The parameter dict of the file. """ |
stype = str(stype)
params = {}
if stype in MPLS_STYPES:
params.update(__get(name, stype, **kwargs))
else:
raise ValueError('unexpected stype: {}! Must be any of {!r}'.format(stype, MPLS_STYPES))
# color palette hack
if params.get('axes.prop_cycle'):
params['axes.prop_cycle'] = mpl.rcsetup.cycler('color', params['axes.prop_cycle'])
return 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 collect(context=None, style=None, palette=None, **kwargs):
"""Returns the merged rcParams dict of the specified context, style, and palette. Parameters context: str style: str palette: str kwargs: - Returns ------- rcParams: dict The merged parameter dicts of the specified context, style, and palette. Notes ----- The rcParams dicts are loaded and updated in the order: context, style, palette. That means if a context parameter is also defined in the style or palette dict, it will be overwritten. There is currently no checking being done to avoid this. """ |
params = {}
if context:
params.update(get(context, 'context', **kwargs))
if style:
params.update(get(style, 'style', **kwargs))
if palette:
params.update(get(palette, 'palette', **kwargs))
return 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 str_to_num(i, exact_match=True):
""" Attempts to convert a str to either an int or float """ |
# TODO: Cleanup -- this is really ugly
if not isinstance(i, str):
return i
try:
if not exact_match:
return int(i)
elif str(int(i)) == i:
return int(i)
elif str(float(i)) == i:
return float(i)
else:
pass
except ValueError:
pass
return 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 make_link(title, url, blank=False):
""" Make a HTML link out of an URL. Args: title (str):
Text to show for the link. url (str):
URL the link will point to. blank (bool):
If True, appends target=_blank, noopener and noreferrer to the <a> element. Defaults to False. """ |
attrs = 'href="%s"' % url
if blank:
attrs += ' target="_blank" rel="noopener noreferrer"'
return '<a %s>%s</a>' % (attrs, title) |
<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_asset_url(self, path):
""" Get the URL of an asset. If asset hashes are added and one exists for the path, it will be appended as a query string. Args: path (str):
Path to the file, relative to your "assets" directory. """ |
url = self.root_url + '/assets/' + path
if path in self.asset_hash:
url += '?' + self.asset_hash[path]
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_pages(self, path='pages'):
""" Look through a directory for markdown files and add them as pages. """ |
pages_path = os.path.join(self.root_path, path)
pages = []
for file in _listfiles(pages_path):
page_dir = os.path.relpath(os.path.dirname(file), pages_path)
if page_dir == '.':
page_dir = None
pages.append(self.cm.Page.from_file(file, directory=page_dir))
self.cm.add_pages(pages) |
<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_posts(self, path='posts'):
""" Look through a directory for markdown files and add them as posts. """ |
path = os.path.join(self.root_path, path)
self.cm.add_posts([
self.cm.Post.from_file(file)
for file in _listfiles(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 copy_assets(self, path='assets'):
""" Copy assets into the destination directory. """ |
path = os.path.join(self.root_path, path)
for root, _, files in os.walk(path):
for file in files:
fullpath = os.path.join(root, file)
relpath = os.path.relpath(fullpath, path)
copy_to = os.path.join(self._get_dist_path(relpath, directory='assets'))
LOG.debug('copying %r to %r', fullpath, copy_to)
shutil.copyfile(fullpath, copy_to) |
<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_asset_hashes(self, path='dist/assets'):
""" Scan through a directory and add hashes for each file found. """ |
for fullpath in _listfiles(os.path.join(self.root_path, path)):
relpath = fullpath.replace(self.root_path + '/' + path + '/', '')
md5sum = hashlib.md5(open(fullpath, 'rb').read()).hexdigest()
LOG.debug('MD5 of %s (%s): %s', fullpath, relpath, md5sum)
self.asset_hash[relpath] = md5sum |
<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_posts(self, num=None, tag=None, private=False):
""" Get all the posts added to the blog. Args: num (int):
Optional. If provided, only return N posts (sorted by date, most recent first). tag (Tag):
Optional. If provided, only return posts that have a specific tag. private (bool):
By default (if False), private posts are not included. If set to True, private posts will also be included. """ |
posts = self.posts
if not private:
posts = [post for post in posts if post.public]
if tag:
posts = [post for post in posts if tag in post.tags]
if num:
return posts[:num]
return posts |
<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_pages(self):
""" Generate HTML out of the pages added to the blog. """ |
for page in self.pages:
self.generate_page(page.slug, template='page.html.jinja', page=page) |
<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_posts(self):
""" Generate single-post HTML files out of posts added to the blog. Will not generate front page, archives or tag files - those have to be generated separately. """ |
for post in self.posts:
self.generate_page(
['posts', post.slug],
template='post.html.jinja',
post=post,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_tags(self):
""" Generate one HTML page for each tag, each containing all posts that match that tag. """ |
for tag in self.tags:
posts = self.get_posts(tag=tag, private=True)
self.generate_page(['tags', tag.slug],
template='archive.html.jinja', posts=posts) |
<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_page(self, path, template, **kwargs):
""" Generate the HTML for a single page. You usually don't need to call this method manually, it is used by a lot of other, more end-user friendly methods. Args: path (str):
Where to place the page relative to the root URL. Usually something like "index", "about-me", "projects/example", etc. template (str):
Which jinja template to use to render the page. **kwargs: Kwargs will be passed on to the jinja template. Also, if the `page` kwarg is passed, its directory attribute will be prepended to the path. """ |
directory = None
if kwargs.get('page'):
directory = kwargs['page'].dir
path = self._get_dist_path(path, directory=directory)
if not path.endswith('.html'):
path = path + '.html'
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
html = self._get_template(template).render(**kwargs)
with open(path, 'w+') as file:
file.write(html) |
<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_index(self, num_posts=5):
""" Generate the front page, aka index.html. """ |
posts = self.get_posts(num=num_posts)
self.generate_page('index', template='index.html.jinja', posts=posts) |
<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_rss(self, path='rss.xml', only_excerpt=True, https=False):
""" Generate the RSS feed. Args: path (str):
Where to save the RSS file. Make sure that your jinja templates refer to the same path using <link>. only_excerpt (bool):
If True (the default), don't include the full body of posts in the RSS. Instead, include the first paragraph and a "read more" link to your website. https (bool):
If True, links inside the RSS with relative scheme (e.g. //example.com/something) will be set to HTTPS. If False (the default), they will be set to plain HTTP. """ |
feed = russell.feed.get_rss_feed(self, only_excerpt=only_excerpt, https=https)
feed.rss_file(self._get_dist_path(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 generate_sitemap(self, path='sitemap.xml', https=False):
""" Generate an XML sitemap. Args: path (str):
The name of the file to write to. https (bool):
If True, links inside the sitemap with relative scheme (e.g. example.com/something) will be set to HTTPS. If False (the default), they will be set to plain HTTP. """ |
sitemap = russell.sitemap.generate_sitemap(self, https=https)
self.write_file(path, sitemap) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_file(self, path, contents):
""" Write a file of any type to the destination path. Useful for files like robots.txt, manifest.json, and so on. Args: path (str):
The name of the file to write to. contents (str or bytes):
The contents to write. """ |
path = self._get_dist_path(path)
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
if isinstance(contents, bytes):
mode = 'wb+'
else:
mode = 'w'
with open(path, mode) as file:
file.write(contents) |
<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_travis(token, slug, log):
""" Enable Travis automatically for the given repo. this need to have access to the GitHub token. """ |
# Done with github directly. Login to travis
travis = TravisPy.github_auth(token, uri='https://api.travis-ci.org')
user = travis.user()
log.info('Travis user: %s', user.name)
# Ask travis to sync with github, try to fetch created repo with exponentially decaying time.
last_sync = user.synced_at
log.info('syncing Travis with Github, this can take a while...')
repo = travis._session.post(travis._session.uri+'/users/sync')
for i in range(10):
try:
sleep((1.5)**i)
repo = travis.repo(slug)
if travis.user().synced_at == last_sync:
raise ValueError('synced not really done, travis.repo() can be a duplicate')
log.info('\nsyncing done')
break
# TODO: find the right exception here
except Exception:
pass
## todo , warn if not found
# Enable travis hook for this repository
log.info('Enabling Travis-CI hook for this repository')
resp = travis._session.put(travis._session.uri+"/hooks/",
json={
"hook": {
"id": repo.id ,
"active": True
}
},
)
if resp.json()['result'] is True:
log.info('Travis hook for this repository is now enabled.')
log.info('Continuous integration test should be triggered every time you push code to github')
else:
log.info("I was not able to set up Travis hooks... something went wrong.")
return user |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_layout(proposal, user=None, repo=None, log=None):
""" generate the project template proposal is the name of the project, user is an object containing some information about the user. - full name, - github username - email """ |
proposal = proposal.lower()
#context_file = os.path.expanduser('~/.cookiecutters/cookiecutter-pypackage/cookiecutter.json')
#context = generate_context(context_file)
# os.chdir('..')
# context['cookiecutter']['full_name'] = user.name
# context['cookiecutter']['email'] = user.email
# context['cookiecutter']['github_username'] = user.login
# context['cookiecutter']['project_name'] = proposal
# context['cookiecutter']['repo_name'] = proposal.lower()
try:
os.mkdir(proposal)
except FileExistsError:
log.info('Skip directory structure, as project seem to already exists')
with open('.gitignore', 'w') as f:
f.write('''
*.pyc
__pycache__
/build/
/dist/
''')
with open( '/'.join([proposal, '__init__.py']), 'w') as f:
f.write('''
"""
a simple package
"""
__version__ = '0.0.1'
''')
travis_yml()
#generate_files(
# repo_dir=os.path.expanduser('~/.cookiecutters/cookiecutter-pypackage/'),
# context=context
# )
log.info('Workig in %s', os.getcwd())
os.listdir('.')
subprocess.call(['git','add','.'], )
subprocess.call(['git','commit',"-am'initial commit of %s'" % proposal])
subprocess.call(['git', "push", "origin", "master:master"]) |
<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_db_user(username, password=None, flags=None):
"""Create a databse user.""" |
flags = flags or u'-D -A -R'
sudo(u'createuser %s %s' % (flags, username), user=u'postgres')
if password:
change_db_user_password(username, 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 excute_query(query, db=None, flags=None, use_sudo=False, **kwargs):
"""Execute remote psql query.""" |
flags = flags or u''
if db:
flags = u"%s -d %s" % (flags, db)
command = u'psql %s -c "%s"' % (flags, query)
if use_sudo:
sudo(command, user='postgres', **kwargs)
else:
run(command, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def db_user_exists(username):
"""Return True if the DB user already exists. """ |
qry = u"""SELECT COUNT(*) FROM pg_roles where rolname = \'{username}\';"""
output = StringIO()
excute_query(
qry.format(username=username),
flags="-Aqt",
use_sudo=True,
stdout=output
)
# FIXME: is there a way to get fabric to not clutter the output
# with "[127.0.0.1] out:" on each line?
lines = output.getvalue().splitlines()
return lines and lines[0].endswith('out: 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 change_db_user_password(username, password):
"""Change a db user's password.""" |
sql = "ALTER USER %s WITH PASSWORD '%s'" % (username, password)
excute_query(sql, use_sudo=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_db(name, owner=None, encoding=u'UTF-8', template='template1', **kwargs):
"""Create a Postgres database.""" |
flags = u''
if encoding:
flags = u'-E %s' % encoding
if owner:
flags = u'%s -O %s' % (flags, owner)
if template and template != 'template1':
flags = u'%s --template=%s' % (flags, template)
sudo('createdb %s %s' % (flags, name), user='postgres', **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_pg_hba_conf(template_name=None, pg_version=None, pg_cluster='main', restart=True):
""" Upload configuration for pg_hba.conf If the version is not given it will be guessed. """ |
template_name = template_name or u'postgres/pg_hba.conf'
version = pg_version or detect_version()
config = {'version': version, 'cluster': pg_cluster}
destination = u'/etc/postgresql/%(version)s/%(cluster)s/pg_hba.conf' % config
upload_template(template_name, destination, use_sudo=True)
if restart:
restart_service(u'postgresql') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_version():
"""Parse the output of psql to detect Postgres version.""" |
version_regex = re.compile(r'\(PostgreSQL\) (?P<major>\d)\.(?P<minor>\d)\.(?P<bugfix>\d)')
pg_version = None
with hide('running', 'stdout', 'stderr'):
output = run('psql --version')
match = version_regex.search(output)
if match:
result = match.groupdict()
if 'major' in result and 'minor' in result:
pg_version = u'%(major)s.%(minor)s' % result
if not pg_version:
abort(u"Error: Could not determine Postgres version of the server.")
return pg_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 reset_cluster(pg_cluster='main', pg_version=None, encoding=u'UTF-8', locale=u'en_US.UTF-8'):
"""Drop and restore a given cluster.""" |
warning = u'You are about to drop the %s cluster. This cannot be undone.' \
u' Are you sure you want to continue?' % pg_cluster
if confirm(warning, default=False):
version = pg_version or detect_version()
config = {'version': version, 'cluster': pg_cluster,
'encoding': encoding, 'locale': locale}
sudo(u'pg_dropcluster --stop %(version)s %(cluster)s' % config,
user='postgres', warn_only=True)
sudo(u'pg_createcluster --start -e %(encoding)s --locale %(locale)s'
u' %(version)s %(cluster)s' % config, user='postgres')
else:
abort(u"Dropping %s cluster aborted by user input." % pg_cluster) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_request_model(cls, validate=True):
""" Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. The model will be passed to the handler as the last positional argument. :: @require_request_model(Model) async def handle_model(request, model):
return 200, model """ |
def decorator(handler):
async def new_handler(request, *args, **kwargs):
body = await request.json()
model = cls(**body)
if validate:
model.validate()
return await handler(request, model, *args, **kwargs)
return new_handler
return decorator |
<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_csv(csv_file, options, ensemble_list=None):
""" Read csv and return molList, otherwise print error and exit. """ |
name, ext = os.path.splitext(csv_file)
try:
if ext == '.gz':
f = gzip.open(csv_file, 'rb')
else:
f = open(csv_file, 'rU')
except IOError:
print(" \n '{f}' could not be opened\n".format(f=os.path.basename(csv_file)))
sys.exit(1)
csv_reader = csv.reader(f)
molList = []
line_number = 1
for line in csv_reader:
if line_number == 1:
if ensemble_list:
prop_indices = read_header(line, options, ensemble_list)
else:
prop_indices = read_header(line, options)
else:
mol = Molecule()
if ensemble_list:
mol = read_line(line, options, prop_indices, mol, ensemble_list)
else:
mol = read_line(line, options, prop_indices, mol)
if mol == 1:
print(" skipping molecule {m}\n".format(m=(line_number - 1)))
else:
molList.append(mol)
line_number += 1
return molList |
<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_rules(specs):
"""Adapts the list of anillo urlmapping specs into a list of werkzeug rules or rules subclasses. :param list specs: A list of anillo url mapping specs. :return: generator """ |
for spec in specs:
if "context" in spec:
yield Context(spec["context"], list(_build_rules(spec.get("routes", []))))
else:
rulespec = spec.copy()
match = rulespec.pop("match")
name = rulespec.pop("name")
yield Rule(match, endpoint=name, **rulespec) |
<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_urlmapping(urls, strict_slashes=False, **kwargs):
"""Convers the anillo urlmappings list into werkzeug Map instance. :return: a werkzeug Map instance :rtype: Map """ |
rules = _build_rules(urls)
return Map(rules=list(rules), strict_slashes=strict_slashes, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_match_error_handler(exc):
""" Default implementation for match error handling. """ |
if isinstance(exc, NotFound):
return http.NotFound()
elif isinstance(exc, MethodNotAllowed):
return http.MethodNotAllowed()
elif isinstance(exc, RequestRedirect):
return redirect(exc.new_url)
else:
raise exc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def r_oauth_login(self):
""" Route for OAuth2 Login :param next next url :type str :return: Redirects to OAuth Provider Login URL """ |
session['next'] = request.args.get('next','')
callback_url = self.authcallback
if callback_url is None:
callback_url = url_for('.r_oauth_authorized', _external=True)
return self.authobj.authorize(callback=callback_url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_session(func=None, *, storage=MemoryStorage):
""" A middleware that adds the session management to the request. This middleware optionally accepts a `storage` keyword only parameter for provide own session storage implementation. If it is not provided, the in memory session storage will be used. :param storage: A storage factory/constructor. :type storage: callable or class """ |
if func is None:
return functools.partial(wrap_session, storage=storage)
# Initialize the storage
storage = storage()
def wrapper(request, *args, **kwargs):
session_key = storage.get_session_key(request)
request.session = storage.retrieve(request, session_key)
response = func(request, *args, **kwargs)
storage.store(request, response, session_key, request.session)
storage.persist_session_key(request, response, session_key)
return response
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_added_dimensions(self, n):
""" Adds n dimensions and returns the Rect. If n < 0, removes dimensions. """ |
if n > 0:
return Rect(np.pad(self.data, ((0, 0), (0, n)), 'constant'))
return Rect(self.data[:, :self.dimensions + 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 clamped(self, point_or_rect):
""" Returns the point or rectangle clamped to this rectangle. """ |
if isinstance(point_or_rect, Rect):
return Rect(np.minimum(self.mins, point_or_rect.mins),
np.maximum(self.maxes, point_or_rect.maxes))
return np.clip(point_or_rect, self.mins, self.maxes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rectified(self):
""" Fixes swaped min-max pairs. """ |
return Rect(np.minimum(self.mins, self.maxes),
np.maximum(self.maxes, self.mins)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self, *args, **kwargs):
#pylint:disable=unused-argument """ | Launch the SSE consumer. | It can listen forever for messages or just wait for one. :param limit: If set, the consumer listens for a limited number of events. :type limit: int :param timeout: If set, the consumer listens for an event for a limited time. :type timeout: int :rtype: None """ |
limit = kwargs.get('limit', None)
timeout = kwargs.get('timeout', None)
self.run(limit=limit, timeout=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 phrase(min_size, max_size = None):
""" Generates a random phrase which consists of few words separated by spaces. The first word is capitalized, others are not. :param min_size: (optional) minimum string length. :param max_size: maximum string length. :return: a random phrase. """ |
max_size = max_size if max_size != None else min_size
size = RandomInteger.next_integer(min_size, max_size)
if size <= 0:
return ""
result = ""
result += random.choice(_all_words)
while len(result) < size:
result += " " + random.choice(_all_words).lower()
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def words(min_size, max_size = None):
""" Generates a random text that consists of random number of random words separated by spaces. :param min_size: (optional) a minimum number of words. :param max_size: a maximum number of words. :return: a random text. """ |
max_size = max_size if max_size != None else min_size
result = ""
count = RandomInteger.next_integer(min_size, max_size)
for i in range(count):
result += random.choice(_all_words)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def text(min_size, max_size):
""" Generates a random text, consisting of first names, last names, colors, stuffs, adjectives, verbs, and punctuation marks. :param min_size: minimum amount of words to generate. Text will contain 'minSize' words if 'maxSize' is omitted. :param max_size: (optional) maximum amount of words to generate. :return: a random text. """ |
max_size = max_size if max_size != None else min_size
size = RandomInteger.next_integer(min_size, max_size)
result = ""
result += random.choice(_all_words)
while len(result) < size:
next = random.choice(_all_words)
if RandomBoolean.chance(4, 6):
next = " " + next.lower()
elif RandomBoolean.chance(2, 5):
next = random.choice(":,-") + next.lower()
elif RandomBoolean.chance(3, 5):
next = random.choice(":,-") + " " + next.lower()
else:
next = random.choice(".!?") + " " + next
result += next
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_form_params(func):
""" A middleware that parses the url-encoded body and attach the result to the request `form_params` attribute. This middleware also merges the parsed value with the existing `params` attribute in same way as `wrap_query_params` is doing. """ |
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
if ctype == "application/x-www-form-urlencoded":
params = {}
for key, value in parse_qs(request.body.decode("utf-8")).items():
if len(value) == 1:
params[key] = value[0]
else:
params[key] = value
request.params = merge_dicts(getattr(request, "params", None), params)
request.form_params = params
return func(request, *args, **kwargs)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_query_params(func):
""" A middleware that parses the urlencoded params from the querystring and attach it to the request `query_params` attribute. This middleware also merges the parsed value with the existing `params` attribute in same way as `wrap_form_params` is doing. """ |
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
params = {}
for key, value in parse_qs(request.query_string.decode("utf-8")).items():
if len(value) == 1:
params[key] = value[0]
else:
params[key] = value
request.params = merge_dicts(getattr(request, "params", None), params)
request.query_params = params
return func(request, *args, **kwargs)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_node(cls, *args, **kwargs):
"""Initializes an ast node with the provided attributes. Python 2.6+ supports this in the node class initializers, but Python 2.5 does not, so this is intended to be an equivalent. """ |
node = cls()
for name, value in zip(cls._fields, args):
setattr(node, name, value)
for name, value in kwargs:
setattr(node, name, value)
return node |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_the(node, node_type):
"""Extracts the node of type node_type from the provided node. - If the node is itself of node_type, returns node. - If the node is a suite, it must contain exactly one node of the provided type in its body. """ |
if isinstance(node, node_type):
return node
try:
body = node.body
except AttributeError:
raise cypy.Error(
"Expecting suite containing a single %s, or a %s, but got %s." %
(node_type.__name__, node_type.__name__, type(node).__name__))
if len(body) != 1 or not isinstance(body[0], node_type):
raise cypy.Error(
"The body must contain exactly one node of type %s." %
node_type.__name__)
return body[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 get_version():
"""Use git describe to get version from tag""" |
proc = subprocess.Popen(
("git", "describe", "--tag", "--always"),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
output, _ = proc.communicate()
result = output.decode("utf-8").strip()
if proc.returncode != 0:
sys.stderr.write(
">>> Git Describe Error:\n " +
result
)
return "1+unknown"
split = result.split("-", 1)
version = "+".join(split).replace("-", ".")
if len(split) > 1:
sys.stderr.write(
">>> Please verify the commit tag:\n " +
version + "\n"
)
return 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 get_file(fn):
"""Returns file contents in unicode as list.""" |
fn = os.path.join(os.path.dirname(__file__), 'data', fn)
f = open(fn, 'rb')
lines = [line.decode('utf-8').strip() for line in f.readlines()]
return lines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name_generator(names=None):
"""Creates a generator for generating names. :arg names: list or tuple of names you want to use; defaults to ENGLISH_MONARCHS :returns: generator for names Example:: from eadred.helpers import name_generator gen = name_generator() for i in range(50):
mymodel = SomeModel(name=gen.next()) mymodel.save() Example 2: u'James II' u'Stephen of Blois' u'James I' .. Note:: This gives full names for a "name" field. It's probably not useful for broken down name fields like "firstname", "lastname", etc. """ |
if names is None:
names = ENGLISH_MONARCHS
while True:
yield text_type(random.choice(names)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def email_generator(names=None, domains=None, unique=False):
"""Creates a generator for generating email addresses. :arg names: list of names to use; defaults to ENGLISH_MONARCHS lowercased, ascii-fied, and stripped of whitespace :arg domains: list of domains to use; defaults to DOMAINS :arg unique: True if you want the username part of the email addresses to be unique :returns: generator Example:: from eadred.helpers import email_generator gen = email_generator() for i in range(50):
mymodel = SomeModel(email=gen.next()) mymodel.save() Example 2: 'eadwig@example.net' 'henrybeauclerc@mail1.example.org' 'williamrufus@example.com' """ |
if names is None:
names = [name.encode('ascii', 'ignore').lower().replace(b' ', b'')
for name in ENGLISH_MONARCHS]
if domains is None:
domains = DOMAINS
if unique:
uniquifyer = lambda: str(next(_unique_counter))
else:
uniquifyer = lambda: ''
while True:
yield '{0}{1}@{2}'.format(
random.choice(names), uniquifyer(), random.choice(domains)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def paragraph_generator(sentences=None):
"""Creates a generator for generating paragraphs. :arg sentences: list or tuple of sentences you want to use; defaults to LOREM :returns: generator Example:: from eadred.helpers import paragraph_generator gen = paragraph_generator() for i in range(50):
mymodel = SomeModel(description=gen.next()) mymodel.save() """ |
if sentences is None:
sentences = LOREM
while True:
# Paragraph consists of 1-7 sentences.
paragraph = [random.choice(sentences)
for num in range(random.randint(1, 7))]
yield u' '.join(paragraph) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_dotted_path(path):
""" Takes a dotted path to a member name in a module, and returns the member after importing it. """ |
# stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path)
try:
module_path, member_name = path.rsplit(".", 1)
module = import_module(module_path)
return getattr(module, member_name)
except (ValueError, ImportError, AttributeError) as e:
raise ImportError('Could not import the name: {}: {}'.format(path, e)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def discoverAuthEndpoints(authDomain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True, headers={}):
"""Find the authorization or redirect_uri endpoints for the given authDomain. Only scan html element matching all criteria in look_in. optionally the content to be scanned can be given as an argument. :param authDomain: the URL of the domain to handle :param content: the content to be scanned for the authorization endpoint :param look_in: dictionary with name, id and class_. only element matching all of these will be scanned :param test_urls: optional flag to test URLs for validation :param validateCerts: optional flag to enforce HTTPS certificates if present :param headers: optional headers to send with any request :rtype: list of authorization endpoints """ |
if test_urls:
ronkyuu.URLValidator(message='invalid domain URL')(authDomain)
if content:
result = {'status': requests.codes.ok,
'headers': None,
'content': content
}
else:
r = requests.get(authDomain, verify=validateCerts, headers=headers)
result = {'status': r.status_code,
'headers': r.headers
}
# check for character encodings and use 'correct' data
if 'charset' in r.headers.get('content-type', ''):
result['content'] = r.text
else:
result['content'] = r.content
result.update({'authorization_endpoint': set(), 'redirect_uri': set(), 'authDomain': authDomain})
if result['status'] == requests.codes.ok:
if 'link' in r.headers:
all_links = r.headers['link'].split(',', 1)
for link in all_links:
if ';' in link:
link_parts = link.split(';')
for s in link_parts[1:]:
if 'rel=' in s:
href = link_parts[0].strip()
rel = s.strip().replace('rel=', '').replace('"', '')
break
url = urlparse(href[1:-1])
if url.scheme in ('http', 'https') and rel in ('authorization_endpoint', 'redirect_uri'):
result[rel].add(url)
all_links = BeautifulSoup(result['content'], _html_parser, parse_only=SoupStrainer(**look_in)).find_all('link')
for link in all_links:
rel = link.get('rel', None)[0]
if rel in ('authorization_endpoint', 'redirect_uri'):
href = link.get('href', None)
if href:
url = urlparse(href)
if url.scheme in ('http', 'https'):
result[rel].add(url)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validateAuthCode(code, redirect_uri, client_id, state=None, validationEndpoint='https://indieauth.com/auth', headers={}):
"""Call authorization endpoint to validate given auth code. :param code: the auth code to validate :param redirect_uri: redirect_uri for the given auth code :param client_id: where to find the auth endpoint for the given auth code :param state: state for the given auth code :param validationEndpoint: URL to make the validation request at :param headers: optional headers to send with any request :rtype: True if auth code is valid """ |
payload = {'code': code,
'redirect_uri': redirect_uri,
'client_id': client_id,
}
if state is not None:
payload['state'] = state
authURL = None
authEndpoints = discoverAuthEndpoints(client_id, headers=headers)
for url in authEndpoints['authorization_endpoint']:
authURL = url
break
if authURL is not None:
validationEndpoint = ParseResult(authURL.scheme, authURL.netloc, authURL.path, '', '', '').geturl()
r = requests.post(validationEndpoint, verify=True, data=payload, headers=headers)
result = { 'status': r.status_code,
'headers': r.headers
}
if 'charset' in r.headers.get('content-type', ''):
result['content'] = r.text
else:
result['content'] = r.content
if r.status_code == requests.codes.ok:
result['response'] = parse_qs(result['content'])
return result |
<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_params(url, ignore_empty=False):
""" Static method that parses a given `url` and retrieves `url`'s parameters. Could also ignore empty value parameters. Handles parameters-only urls as `q=banana&peel=false`. :param str url: url to parse :param bool ignore_empty: ignore empty value parameter or not :return: dictionary of params and their values :rtype: dict """ |
try:
params_start_index = url.index('?')
except ValueError:
params_start_index = 0
params_string = url[params_start_index + 1:]
params_dict = {}
for pair in params_string.split('&'):
if not pair:
continue
splitted = pair.split('=')
param, value = splitted
if not value and ignore_empty:
continue
value = int(value) if value.isdigit() else value
params_dict[param] = value
return params_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_date(table_data):
""" Static method that parses a given table data element with `Url.DATE_STRPTIME_FORMAT` and creates a `date` object from td's text contnet. :param lxml.HtmlElement table_data: table_data tag to parse :return: date object from td's text date :rtype: datetime.date """ |
text = table_data.text.split('Added on ')
# Then it's 'Added today'. Hacky
if len(text) < 2:
return date.today()
# Looks like ['', 'Thursday, Mar 05, 2015']
return datetime.strptime(text[1], Parser.DATE_STRPTIME_FORMAT).date() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.