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 dynacRepresentation(self):
""" Return the Dynac representation of this cavity instance. """ |
return ['CAVMC', [
[self.cavID.val],
[self.xesln.val, self.phase.val, self.fieldReduction.val, self.isec.val, 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 from_dynacRepr(cls, pynacRepr):
""" Construct a ``AccGap`` instance from the Pynac lattice element """ |
pynacList = pynacRepr[1][0]
L = float(pynacList[3])
TTF = float(pynacList[4])
TTFprime = float(pynacList[5])
TTFprimeprime = float(pynacList[13])
EField = float(pynacList[10])
phase = float(pynacList[11])
F = float(pynacList[14])
atten = float(py... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dynacRepresentation(self):
""" Return the Dynac representation of this accelerating gap instance. """ |
details = [
self.gapID.val,
self.energy.val,
self.beta.val,
self.L.val,
self.TTF.val,
self.TTFprime.val,
self.S.val,
self.SP.val,
self.quadLength.val,
self.quadStrength.val,
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_dynacRepr(cls, pynacRepr):
""" Construct a ``Set4DAperture`` instance from the Pynac lattice element """ |
energyDefnFlag = int(pynacRepr[1][0][0])
energy = float(pynacRepr[1][0][1])
phase = float(pynacRepr[1][0][2])
x = float(pynacRepr[1][0][3])
y = float(pynacRepr[1][0][4])
radius = float(pynacRepr[1][0][5])
return cls(energy, phase, x, y, radius, energyDefnFlag) |
<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_dynacRepr(cls, pynacRepr):
""" Construct a ``Steerer`` instance from the Pynac lattice element """ |
f = float(pynacRepr[1][0][0])
p = 'HV'[int(pynacRepr[1][0][1])]
return cls(f, p) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dynacRepresentation(self):
""" Return the Dynac representation of this steerer instance. """ |
if self.plane.val == 'H':
p = 0
elif self.plane.val == 'V':
p = 1
return ['STEER', [[self.field_strength.val], [p]]] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
""" parse command line opts and run a skeleton file when called from the command line, ligament looks in the current working directory for a file cal... |
options = None
try:
options, args = getopt.gnu_getopt(
sys.argv[1:],
"whqv",
["watch", "help", "query", "verbose"])
except getopt.GetoptError as e:
print e
print_helptext()
exit(1)
should_watch = False
query_skeleton = 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 _getter(self, obj):
"""Called when the parent element tries to get this property value. :param obj: parent object. """ |
result = None
if self._fget_ is not None:
result = self._fget_(obj)
if result is None:
result = getattr(obj, self._attrname(), self._default_)
# notify parent schema about returned value
if isinstance(obj, Schema):
obj._getvalue(self, resul... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setter(self, obj, value):
"""Called when the parent element tries to set this property value. :param obj: parent object. :param value: new value to use. If ... |
if isinstance(value, DynamicValue): # execute lambda values.
fvalue = value()
else:
fvalue = value
self._validate(data=fvalue, owner=obj)
if self._fset_ is not None:
self._fset_(obj, fvalue)
else:
setattr(obj, self._attrname()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _deleter(self, obj):
"""Called when the parent element tries to delete this property value. :param obj: parent object. """ |
if self._fdel_ is not None:
self._fdel_(obj)
else:
delattr(obj, self._attrname())
# notify parent schema about value deletion.
if isinstance(obj, Schema):
obj._delvalue(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 _validate(self, data, owner=None):
"""Validate input data in returning an empty list if true. :param data: data to validate with this schema. :param Schema o... |
if isinstance(data, DynamicValue):
data = data()
if data is None and not self.nullable:
raise ValueError('Value can not be null')
elif data is not None:
isdict = isinstance(data, dict)
for name, schema in iteritems(self.getschemas()):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getschemas(cls):
"""Get inner schemas by name. :return: ordered dict by name. :rtype: OrderedDict """ |
members = getmembers(cls, lambda member: isinstance(member, Schema))
result = OrderedDict()
for name, member in members:
result[name] = member
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_ability_desc(ability):
"""Return the description matching the given ability name. Check abilities.json in the same directory.""" |
srcpath = path.dirname(__file__)
try:
f = open(path.join(srcpath, 'abilities.json'), 'r')
except IOError:
get_abilities()
f = open(path.join(srcpath, 'abilities.json'), 'r')
finally:
with f:
return json.load(f)[ability].encode('utf-8') |
<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_move_data(move):
"""Return the index number for the given move name. Check moves.json in the same directory.""" |
srcpath = path.dirname(__file__)
try:
f = open(path.join(srcpath, 'moves.json'), 'r')
except IOError:
get_moves()
f = open(path.join(srcpath, 'moves.json'), 'r')
finally:
with f:
return json.load(f)[move] |
<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(self):
"""Registers SSH key with provider.""" |
log.info('Installing ssh key, %s' % self.name)
self.consul.create_ssh_pub_key(self.name, self.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 find_existing(self):
""" Searches for existing server instances with matching tags. To match, the existing instances must also be "running". """ |
instances = self.consul.find_servers(self.tags)
maxnames = len(instances)
while instances:
i = instances.pop(0)
server_id = i[A.server.ID]
if self.namespace.add_if_unique(server_id):
log.info('Found existing server, %s' % server_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 wait_for_running(self):
"""Waits for found servers to be operational""" |
self.server_attrs = self.consul.find_running(
self.server_attrs,
self.launch_timeout_s,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self):
"""Launches a new server instance.""" |
self.server_attrs = self.consul.create_server(
"%s-%s" % (self.stack.name, self.name),
self.disk_image_id,
self.instance_type,
self.ssh_key_name,
tags=self.tags,
availability_zone=self.availability_zone,
... |
<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_to_inventory(self):
"""Adds host to stack inventory""" |
if not self.server_attrs:
return
for addy in self.server_attrs[A.server.PUBLIC_IPS]:
self.stack.add_host(addy, self.groups, self.hostvars) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def define(self):
"""Defines a new server.""" |
self.server_def = self.consul.define_server(
self.name,
self.server_tpl,
self.server_tpl_rev,
self.instance_type,
self.ssh_key_name,
tags=self.tags,
availability_zone=self.availability_zone,
... |
<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_existing(self):
""" Finds existing rule in secgroup. Populates ``self.create_these_rules`` and ``self.delete_these_rules``. """ |
sg = self.consul.find_secgroup(self.name)
current = sg.rules
log.debug('Current rules: %s' % current)
log.debug('Intended rules: %s' % self.rules)
exp_rules = []
for rule in self.rules:
exp = (
rule[A.secgroup.PROTOCOL],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_rule_changes(self):
""" Makes the security group rules match what is defined in the Bang config file. """ |
# TODO: add error handling
for rule in self.delete_these_rules:
self.consul.delete_secgroup_rule(rule)
log.info("Revoked: %s" % rule)
for rule in self.create_these_rules:
args = rule + (self.name, )
self.consul.create_secgroup_rule(*args)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self):
"""Creates a new bucket""" |
self.consul.create_bucket("%s-%s" % (self.stack.name, self.name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self):
"""Creates a new database""" |
self.db_attrs = self.consul.create_db(
self.instance_name,
self.instance_type,
self.admin_username,
self.admin_password,
db_name=self.db_name,
storage_size_gb=self.storage_size,
timeout_s=self.launch... |
<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_to_inventory(self):
"""Adds db host to stack inventory""" |
host = self.db_attrs.pop(A.database.HOST)
self.stack.add_host(
host,
self.groups,
self.db_attrs
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self):
"""Creates a new load balancer""" |
required_nodes = self._get_required_nodes()
self.lb_attrs = self.consul.create_lb(
self.instance_name,
protocol=self.protocol,
port=self.port,
nodes=required_nodes,
node_port=str(self.backend_port),
algorith... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_nodes(self):
"""Ensure that the LB's nodes matches the stack""" |
# Since load balancing runs after server provisioning,
# the servers should already be created regardless of
# whether this was a preexisting load balancer or not.
# We also have the existing nodes, because add_to_inventory
# has been called already
required_nodes = 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 add_to_inventory(self):
"""Adds lb IPs to stack inventory""" |
if self.lb_attrs:
self.lb_attrs = self.consul.lb_details(
self.lb_attrs[A.loadbalancer.ID]
)
host = self.lb_attrs['virtualIps'][0]['address']
self.stack.add_lb_secgroup(self.name, [host], self.backend_port)
self.stack.add_h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_dependencies(self):
""" evaluate each of the data dependencies of this build target, returns the resulting dict""" |
return dict(
[((key, self.data_dependencies[key])
if type(self.data_dependencies[key]) != DeferredDependency
else (key, self.data_dependencies[key].resolve()))
for key in self.data_dependencies]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_and_build(self):
""" resolves the dependencies of this build target and builds it """ |
pdebug("resolving and building task '%s'" % self.name,
groups=["build_task"])
indent_text(indent="++2")
toret = self.build(**self.resolve_dependencies())
indent_text(indent="--2")
return toret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_response(self, request, response):
""" Sets the cache and deals with caching headers if needed """ |
if not self.should_cache(request, response):
# We don't need to update the cache, just return
return response
response = self.patch_headers(response)
self.set_cache(request, response)
return 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 keys(self):
"""Create an ordered dict of the names and values of key fields.""" |
keys = OrderedDict()
def order_key(_):
(k, v) = _
cache_key = getattr(type(self), k)
return cache_key.order
items = [(k, getattr(type(self), k)) for k
in dir(type(self))
]
items = [(k, v) for (k, v)
in items
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self):
"""Serialize all the fields into one string.""" |
keys = self._all_keys()
serdata = {}
for fieldname, value in self._data.items():
serdata[fieldname] = getattr(type(self), fieldname).python_to_cache(value)
return json.dumps(serdata) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deserialize(cls, string):
"""Reconstruct a previously serialized string back into an instance of a ``CacheModel``.""" |
data = json.loads(string)
for fieldname, value in data.items():
data[fieldname] = getattr(cls, fieldname).cache_to_python(value)
return cls(**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 save(self, expires=None):
"""Save a copy of the object into the cache.""" |
if expires is None:
expires = self.expires
s = self.serialize()
key = self._key(self._all_keys())
_cache.set(key, s, expires) |
<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(cls, **kwargs):
"""Get a copy of the type from the cache and reconstruct it.""" |
data = cls._get(**kwargs)
if data is None:
new = cls()
new.from_miss(**kwargs)
return new
return cls.deserialize(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 get_or_create(cls, **kwargs):
"""Get a copy of the type from the cache, or create a new one.""" |
data = cls._get(**kwargs)
if data is None:
return cls(**kwargs), True
return cls.deserialize(data), 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 from_miss(self, **kwargs):
"""Called to initialize an instance when it is not found in the cache. For example, if your CacheModel should pull data from the d... |
raise type(self).Missing(type(self)(**kwargs).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 delete(self):
"""Deleting any existing copy of this object from the cache.""" |
key = self._key(self._all_keys())
_cache.delete(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 overlay_config(base, overlay):
'''Overlay one configuration over another.
This overlays `overlay` on top of `base` as follows:
* If either isn't a dictionary, returns `overlay`.
* Any key in `base` not present in `overlay` is present in the
result with its original value.
* Any key in `o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def diff_config(base, target):
'''Find the differences between two configurations.
This finds a delta configuration from `base` to `target`, such that
calling :func:`overlay_config` with `base` and the result of this
function yields `target`. This works as follows:
* If both are identical (of any... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pformat(tree):
"""Recursively formats a tree into a nice string representation. Example Input: yahoo = tt.Tree(tt.Node("CEO")) yahoo.root.add(tt.Node("Infra"... |
if tree.empty():
return ''
buf = six.StringIO()
for line in _pformat(tree.root, 0):
buf.write(line + "\n")
return buf.getvalue().strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path_iter(self, include_self=True):
"""Yields back the path from this node to the root node.""" |
if include_self:
node = self
else:
node = self.parent
while node is not None:
yield node
node = node.parent |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def child_count(self, only_direct=True):
"""Returns how many children this node has, either only the direct children of this node or inclusive of all children no... |
if not only_direct:
count = 0
for _node in self.dfs_iter():
count += 1
return count
return len(self._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 index(self, item):
"""Finds the child index of a given item, searchs in added order.""" |
index_at = None
for (i, child) in enumerate(self._children):
if child.item == item:
index_at = i
break
if index_at is None:
raise ValueError("%s is not contained in any child" % (item))
return index_at |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish_state(self, state):
"""Publish thing state to AWS IoT. Args: state (dict):
object state. Must be JSON serializable (i.e., not have circular referenc... |
message = json.dumps({'state': {'reported': state}})
self.client.publish(self.topic, message)
self._state = state |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_kpoint(line):
"""Is this line the start of a new k-point block""" |
# Try to parse the k-point; false otherwise
toks = line.split()
# k-point header lines have 4 tokens
if len(toks) != 4:
return False
try:
# K-points are centered at the origin
xs = [float(x) for x in toks[:3]]
# Weights are in [0,1]
w = float(toks[3])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_kpoint(line, lines):
"""Parse the k-point and then continue to iterate over the band energies and occupations""" |
toks = line.split()
kpoint = [float(x) for x in toks[:3]]
weight = float(toks[-1])
newline = next(lines)
bands_up = []
occ_up = []
bands_down = []
occ_down = []
ispin = None
while len(newline.split()) > 0:
toks = newline.split()
if ispin is 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 parse(cls, op):
"""Gets the enum for the op code Args: op: value of the op code (will be casted to int) Returns: The enum that matches the op code """ |
for event in cls:
if event.value == int(op):
return 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 run(self):
"""Runs the thread This method handles sending the heartbeat to the Discord websocket server, so the connection can remain open and the bot remain... |
while self.should_run:
try:
self.logger.debug('Sending heartbeat, seq ' + last_sequence)
self.ws.send(json.dumps({
'op': 1,
'd': last_sequence
}))
except Exception as e:
self.logger.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 _setup_logger(self, logging_level: int, log_to_console: bool):
"""Sets up the internal logger Args: logging_level: what logging level to use log_to_console: ... |
self.logger = logging.getLogger('discord')
self.logger.handlers = []
self.logger.setLevel(logging_level)
formatter = logging.Formatter(style='{', fmt='{asctime} [{levelname}] {message}', datefmt='%Y-%m-%d %H:%M:%S')
file_handler = logging.FileHandler('pycord.log')
file_h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \ -> Union[List[Dict[str, Any]], Dict[str, Any], None]: """Make an... |
url = Pycord.url_base + path
self.logger.debug(f'Making {method} request to "{url}"')
if method == 'GET':
r = requests.get(url, headers=self._build_headers())
elif method == 'POST':
r = requests.post(url, headers=self._build_headers(), json=data)
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 _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection This method receiv... |
if isinstance(raw, bytes):
decoded = zlib.decompress(raw, 15, 10490000).decode('utf-8')
else:
decoded = raw
data = json.loads(decoded)
if data.get('s') is not None:
global last_sequence
last_sequence = str(data['s'])
self.logge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ws_on_error(self, ws: websocket.WebSocketApp, error: Exception):
"""Callback for receiving errors from the websocket connection Args: ws: websocket connecti... |
self.logger.error(f'Got error from websocket connection: {str(error)}') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ws_on_close(self, ws: websocket.WebSocketApp):
"""Callback for closing the websocket connection Args: ws: websocket connection (now closed) """ |
self.connected = False
self.logger.error('Websocket closed')
self._reconnect_websocket() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ws_on_open(self, ws: websocket.WebSocketApp):
"""Callback for sending the initial authentication data This "payload" contains the required data to authentic... |
payload = {
'op': WebSocketEvent.IDENTIFY.value,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'Pycord',
'$device': 'Pycord',
'$referrer': '',
... |
<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_to_websocket(self):
"""Call this method to make the connection to the Discord websocket This method is not blocking, so you'll probably want to call ... |
self.logger.info('Making websocket connection')
try:
if hasattr(self, '_ws'):
self._ws.close()
except:
self.logger.debug('Couldn\'t terminate previous websocket connection')
self._ws = websocket.WebSocketApp(
self._get_websocket_addres... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect_from_websocket(self):
"""Disconnects from the websocket Args: None """ |
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self.logger.info('Stopped keep alive thread')
try:
self.logger.warning('Disconnecting from websocket')
... |
<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_status(self, name: str = None):
"""Updates the bot's status This is used to get the game that the bot is "playing" or to clear it. If you want to set a g... |
game = None
if name:
game = {
'name': name
}
payload = {
'op': WebSocketEvent.STATUS_UPDATE.value,
'd': {
'game': game,
'status': 'online',
'afk': False,
'since': 0.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_guild_info(self, id: str) -> Dict[str, Any]: """Get a guild's information by its id Args: id: snowflake id of the guild Returns: Dictionary data for the g... |
return self._query(f'guilds/{id}', '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 get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]: """Get a list of channels in the guild Args: guild_id: id of the guild to fetch channels from Re... |
return self._query(f'guilds/{guild_id}/channels', '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 get_channel_info(self, id: str) -> Dict[str, Any]: """Get a chanel's information by its id Args: id: snowflake id of the chanel Returns: Dictionary data for t... |
return self._query(f'channels/{id}', '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 get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]: """Get a list of members in the guild Args: guild_id: snowflake id of the guild Returns: List ... |
return self._query(f'guilds/{guild_id}/members', '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 get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]: """Get a guild member by their id Args: guild_id: snowflake id of the guild mem... |
return self._query(f'guilds/{guild_id}/members/{member_id}', '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 get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]: """Gets all the roles for the specified guild Args: guild_id: snowflake id of the guild Retu... |
return self._query(f'guilds/{guild_id}/roles', '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 set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles This method takes a list of **role ids** that you want the... |
self._query(f'guilds/{guild_id}/members/{member_id}', 'PATCH', {'roles': roles}, expected_status=204) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def command(self, name: str) -> Callable: """Decorator to wrap methods to register them as commands The argument to this method is the command that you want to tr... |
def inner(f: Callable):
self._commands.append((name, f))
return inner |
<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_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback This method can be used instead of the ``@comm... |
self._commands.append((name, f)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_csv_to_dataframe(data_file, config, use_target=True):
""" Parses the given data file following the data model of the given configuration. @return: pa... |
names, dtypes = [], []
model = config.get_data_model()
for feature in model:
assert feature.get_name() not in names, "Two features can't have the same name."
if not use_target and feature.is_target():
continue
names.append(feature.get_name())
data = pd.read_csv(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 mark_for_update(self):
'''
Note that a change has been made so all Statuses need update
'''
self.pub_statuses.exclude(status=UNPUBLISHED).update(status=NEEDS_UPDATE)
push_key.delay(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 set_cookie(self, key, value, domain=None, path='/', secure=False, httponly=True):
"""Set a cookie. Args: key (:obj:`str`):
Cookie name value (:obj:`str`):
... |
self._cookies[key] = value
if domain:
self._cookies[key]['domain'] = domain
if path:
self._cookies[key]['path'] = path
if secure:
self._cookies[key]['secure'] = secure
if httponly:
self._cookies[key]['httponly'] = httponly |
<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_content(self, content, content_length=None):
"""Set content for the response. Args: content (:obj:`str` or :obj:`iterable`):
Response content. Can be ei... |
if content_length is not None:
self._content_length = content_length
self._content = content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bake(self, start_response):
"""Bakes the response and returns the content. Args: start_response (:obj:`callable`):
Callback method that accepts status code ... |
if isinstance(self._content, six.text_type):
self._content = self._content.encode('utf8')
if self._content_length is None:
self._content_length = len(self._content)
self._headers[HttpResponseHeaders.CONTENT_LENGTH] = \
str(self._content_length)
head... |
<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_redirect(self, url, status=HttpStatusCodes.HTTP_303):
"""Helper method to set a redirect response. Args: url (:obj:`str`):
URL to redirect to status (:o... |
self.set_status(status)
self.set_content('')
self.set_header(HttpResponseHeaders.LOCATION, 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 set_json(self, obj, status=HttpStatusCodes.HTTP_200):
"""Helper method to set a JSON response. Args: obj (:obj:`object`):
JSON serializable object status (:... |
obj = json.dumps(obj, sort_keys=True, default=lambda x: str(x))
self.set_status(status)
self.set_header(HttpResponseHeaders.CONTENT_TYPE, 'application/json')
self.set_content(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 find_rak():
""" Find our instance of Rak, navigating Local's and possible blueprints. """ |
if hasattr(current_app, 'rak'):
return getattr(current_app, 'rak')
else:
if hasattr(current_app, 'blueprints'):
blueprints = getattr(current_app, 'blueprints')
for blueprint_name in blueprints:
if hasattr(blueprints[blueprint_name], 'rak'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intent(self, intent_name):
"""Decorator routes an Rogo IntentRequest. Functions decorated as an intent are registered as the view function for the Intent's U... |
def decorator(f):
self._intent_view_funcs[intent_name] = f
@wraps(f)
def wrapper(*args, **kw):
self._flask_view_func(*args, **kw)
return f
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 make_anchor_id(self):
"""Return string to use as URL anchor for this comment. """ |
result = re.sub(
'[^a-zA-Z0-9_]', '_', self.user + '_' + self.timestamp)
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 make_url(self, my_request, anchor_id=None):
"""Make URL to this comment. :arg my_request: The request object where this comment is seen from. :arg anchor_id=... |
if anchor_id is None:
anchor_id = self.make_anchor_id()
result = '{}?{}#{}'.format(
my_request.path, urllib.parse.urlencode(my_request.args),
anchor_id)
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 to_dict(self):
"""Return description of self in dict format. This is useful for serializing to something like json later. """ |
jdict = {
'user': self.user,
'summary': self.summary,
'body': self.body,
'markup': self.markup,
'url': self.url,
'timestamp': self.timestamp
}
return jdict |
<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_display_mode(self, mytz, fmt):
"""Set the display mode for self. :arg mytz: A pytz.timezone object. :arg fmt: A format string for strftime. ~-~-~-~-~-~-~... |
my_stamp = dateutil.parser.parse(self.timestamp)
tz_stamp = my_stamp.astimezone(
mytz) if my_stamp.tzinfo is not None else my_stamp
self.display_timestamp = tz_stamp.strftime(fmt) |
<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_comment_section(self, force_reload=False, reverse=False):
"""Get CommentSection instance representing all comments for thread. :arg force_reload=False: W... |
if self.content is not None and not force_reload:
return self.content
if self.thread_id is None:
self.thread_id = self.lookup_thread_id()
self.content = self.lookup_comments(reverse=reverse)
return self.content |
<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_attachment_location(self, location):
"""Validate a proposed attachment location. :arg location: String representing location to put attachment. ~-~-... |
if not re.compile(self.valid_attachment_loc_re).match(location):
raise ValueError(
'Bad chars in attachment location. Must match %s' % (
self.valid_attachment_loc_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 lookup_thread_id(self):
"Lookup the thread id as path to comment file."
path = os.path.join(self.realm, self.topic + '.csv')
return 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 lookup_comments(self, reverse=False):
"Implement as required by parent to lookup comments in file system."
comments = []
if self.thread_id is None:
self.thread_id = self.lookup_thread_id()
path = self.thread_id
with open(self.thread_id, 'r', newline='') as fdesc:... |
<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_thread(self, body):
"""Implement create_thread as required by parent. This basically just calls add_comment with allow_create=True and then builds a r... |
self.add_comment(body, allow_create=True)
the_response = Response()
the_response.code = "OK"
the_response.status_code = 200 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_comment(self, body, allow_create=False, allow_hashes=False,
summary=None):
"Implement as required by parent to store comment in CSV file."
if allow_hashes:
raise ValueError('allow_hashes not implemented for %s yet' % (
self.__class__.__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 pascal_row(n):
""" Returns n-th row of Pascal's triangle """ |
result = [1]
x, numerator = 1, n
for denominator in range(1, n // 2 + 1):
x *= numerator
x /= denominator
result.append(x)
numerator -= 1
if n & 1 == 0:
result.extend(reversed(result[:-1]))
else:
result.extend(reversed(result))
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 create_salt(length: int=128) -> bytes: """ Create a new salt :param int length: How many bytes should the salt be long? :return: The salt :rtype: bytes """ |
return b''.join(bytes([SystemRandom().randint(0, 255)]) for _ in range(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 __get_connection(self) -> redis.Redis: """ Get a Redis connection :return: Redis connection instance :rtype: redis.Redis """ |
if self.__redis_use_socket:
r = redis.from_url(
'unix://{:s}?db={:d}'.format(
self.__redis_host,
self.__redis_db
)
)
else:
r = redis.from_url(
'redis://{:s}:{:d}/{:d}'.format(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _encode_item(self, item: str) -> str: """ If anonymization is on, an item gets salted and hashed here. :param str item: :return: Hashed item, if anonymization... |
assert item is not None
if not self.__redis_conf['anonymization']:
return item
connection = self.__get_connection()
salt = connection.get(self.__redis_conf['salt_key'])
if salt is None:
salt = create_salt()
connection.set(self.__redis_conf['sa... |
<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_ttl(self, item: str) -> int: """ Get the amount of time a specific item will remain in the database. :param str item: The item to get the TTL for :retur... |
connection = self.__get_connection()
ttl = connection.ttl(item)
BlackRed.__release_connection(connection)
return 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 get_watchlist_ttl(self, item: str) -> int: """ Get the amount of time a specific item will remain on the watchlist. :param str item: The item to get the TTL f... |
assert item is not None
item = self._encode_item(item)
return self.__get_ttl(self.__redis_conf['watchlist_template'].format(item)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_not_blocked(self, item: str) -> bool: """ Check if an item is _not_ already on the blacklist :param str item: The item to check :return: True, when the ite... |
assert item is not None
item = self._encode_item(item)
connection = self.__get_connection()
key = self.__redis_conf['blacklist_template'].format(item)
value = connection.get(key)
if value is None:
BlackRed.__release_connection(connection)
return T... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_fail(self, item: str) -> None: """ Log a failed action for an item. If the fail count for this item reaches the threshold, the item is moved to the blackl... |
assert item is not None
item = self._encode_item(item)
if self.is_blocked(item):
return
connection = self.__get_connection()
key = self.__redis_conf['watchlist_template'].format(item)
value = connection.get(key)
if value is None:
connectio... |
<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_task(self, func):
"""Start up a task""" |
task = self.loop.create_task(func(self))
self._started_tasks.append(task)
def done_callback(done_task):
self._started_tasks.remove(done_task)
task.add_done_callback(done_callback)
return task |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, loop=None):
"""Actually run the application :param loop: Custom event loop or None for default """ |
if loop is None:
loop = asyncio.get_event_loop()
self.loop = loop
loop.run_until_complete(self.startup())
for func in self.tasks:
self.start_task(func)
try:
task = self.start_task(self.main_task)
loop.run_until_complete(task)
... |
<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_git_blob(commit_ref, path, repo_dir='.'):
"""Get text from a git blob. Parameters commit_ref : str Any SHA or git tag that can resolve into a commit in ... |
repo = git.Repo(repo_dir)
tree = repo.tree(commit_ref)
dirname, fname = os.path.split(path)
text = None
if dirname == '':
text = _read_blob(tree, fname)
else:
components = path.split(os.sep)
text = _read_blob_in_tree(tree, components)
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_blob_in_tree(tree, components):
"""Recursively open trees to ultimately read a blob""" |
if len(components) == 1:
# Tree is direct parent of blob
return _read_blob(tree, components[0])
else:
# Still trees to open
dirname = components.pop(0)
for t in tree.traverse():
if t.name == dirname:
return _read_blob_in_tree(t, components) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def absolute_git_root_dir(fpath=""):
"""Absolute path to the git root directory containing a given file or directory. """ |
if len(fpath) == 0:
dirname_str = os.getcwd()
else:
dirname_str = os.path.dirname(fpath)
dirname_str = os.path.abspath(dirname_str)
dirnames = dirname_str.split(os.sep)
n = len(dirnames)
for i in xrange(n):
# is there a .git directory at this level?
# FIXME hack
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.