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 from_etree(tree):
"""Constructs an executable form a given ElementTree structure. :param tree: :type tree: xml.etree.ElementTree.ElementTree :rtype: Executab... |
exe = Executable(tree)
exe.category = tree.findtext('category')
exe.version = tree.findtext('version')
exe.title = tree.findtext('title') or exe.name
exe.description = tree.findtext('description')
exe.license = tree.findtext('license') or "unknown"
exe.contribut... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def NoExclusions(self):
"""Determine that there are no exclusion criterion in play :return: True if there is no real boundary specification of any kind. Simple m... |
if len(self.start_bounds) + len(self.target_rs) + len(self.ignored_rs) == 0:
return BoundaryCheck.chrom == -1
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 set_address(self, host, port):
"""Add host and port attributes""" |
self.host = host
self.port = port |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, host=None, port=None):
"""Connects to given host address and port.""" |
host = self.host if host is None else host
port = self.port if port is None else port
self.socket.connect(host, port) |
<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_file_message(self, filename):
"""Send message inside the given file.""" |
data = self._readFile(filename)
self.print_debug_message(data)
self.socket.send(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_message(self, message):
"""Send a given message to the remote host.""" |
self.print_debug_message(message)
self.socket.send(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modified_after(first_path, second_path):
"""Returns True if first_path's mtime is higher than second_path's mtime.""" |
try:
first_mtime = os.stat(first_path).st_mtime
except EnvironmentError:
return False
try:
second_mtime = os.stat(second_path).st_mtime
except EnvironmentError:
return True
return first_mtime > second_mtime |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_packet(self, packet, ip, port):
""" React to incoming packet :param packet: Packet to handle :type packet: T >= paps.si.app.message.APPMessage :param ip:... |
msg_type = packet.header.message_type
if msg_type == MsgType.JOIN:
self._do_join_packet(packet, ip, port)
elif msg_type == MsgType.UNJOIN:
self._do_unjoin_packet(packet, ip, port)
elif msg_type == MsgType.UPDATE:
self._do_update_packet(packet, ip, po... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_join_packet(self, packet, ip, port):
""" React to join packet - add a client to this server :param packet: Packet from client that wants to join :type pa... |
self.debug("()")
device_id = packet.header.device_id
key = u"{}:{}".format(ip, port)
if device_id == Id.REQUEST:
device_id = self._new_device_id(key)
client = self._clients.get(device_id, {})
data = {}
if packet.payload:
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_unjoin_packet(self, packet, ip, port):
""" React to unjoin packet - remove a client from this server :param packet: Packet from client that wants to join... |
self.debug("()")
device_id = packet.header.device_id
if device_id <= Id.SERVER:
self.error("ProtocolViolation: Invalid device id")
return
client = self._clients.get(device_id)
if not client:
self.error("ProtocolViolation: Client is not regist... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _new_device_id(self, key):
""" Generate a new device id or return existing device id for key :param key: Key for device :type key: unicode :return: The devic... |
device_id = Id.SERVER + 1
if key in self._key2deviceId:
return self._key2deviceId[key]
while device_id in self._clients:
device_id += 1
return device_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 _init_multicast_socket(self):
""" Init multicast socket :rtype: None """ |
self.debug("()")
# Create a UDP socket
self._multicast_socket = socket.socket(
socket.AF_INET,
socket.SOCK_DGRAM
)
# Allow reuse of addresses
self._multicast_socket.setsockopt(
socket.SOL_SOCKET,
socket.SO_REUSEADDR,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _shutdown_multicast_socket(self):
""" Shutdown multicast socket :rtype: None """ |
self.debug("()")
self._drop_membership_multicast_socket()
self._listening.remove(self._multicast_socket)
self._multicast_socket.close()
self._multicast_socket = 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 _add_membership_multicast_socket(self):
""" Make membership request to multicast :rtype: None """ |
self._membership_request = socket.inet_aton(self._multicast_group) \
+ socket.inet_aton(self._multicast_ip)
# Send add membership request to socket
# See http://www.tldp.org/HOWTO/Multicast-HOWTO-6.html
# for explanation of sockopts
self._multicast_socket.setsockopt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _drop_membership_multicast_socket(self):
""" Drop membership to multicast :rtype: None """ |
# Leave group
self._multicast_socket.setsockopt(
socket.IPPROTO_IP,
socket.IP_DROP_MEMBERSHIP,
self._membership_request
)
self._membership_request = 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 evert(iterable: Iterable[Dict[str, Tuple]]) -> Iterable[Iterable[Dict[str, Any]]]:
'''Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def extend(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Extend base by updating with the extension.
**Arguments**
:``base``: dictionary to have keys updated or added
:``extension``: dictionary to update base with
**Return Value(s)**
Resulting dictionary from up... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def merge(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Merge extension into base recursively.
**Argumetnts**
:``base``: dictionary to overlay values onto
:``extension``: dictionary to overlay with
**Return Value(s)**
Resulting dictionary from overlaying extensi... |
<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_directory(module_basename: str, directory: str, sort_key = None) -> None:
'''Load all python modules in directory and directory's children.
Parameters
----------
:``module_basename``: module name prefix for loaded modules
:``directory``: directory to load python modules from
:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _filenames_to_modulenames(filenames: Iterable[str], modulename_prefix: str, filename_prefix: str = '') -> Iterable[str]:
'''Convert given filenames to module names.
Any filename that does not have a corresponding module name will be dropped
from the result (i.e. __init__.py).
Parameters
------... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_any_event(self, event):
"""Called whenever a FS event occurs.""" |
self.updated = True
if self._changed:
self._changed() |
<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(prefix = ''):
'''Add start and stop logging messages to the function.
Parameters
----------
:``prefix``: a prefix for the function name (optional)
'''
function = None
if inspect.isfunction(prefix):
prefix, function = '', prefix
def _(function):
@functools.wr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spec(self):
"""Return a dict with values that can be fed directly into SelectiveRowGenerator""" |
return dict(
headers=self.header_lines,
start=self.start_line,
comments=self.comment_lines,
end=self.end_line
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def picture(self, row):
"""Create a simplified character representation of the data row, which can be pattern matched with a regex """ |
template = '_Xn'
types = (type(None), binary_type, int)
def guess_type(v):
try:
v = text_type(v).strip()
except ValueError:
v = binary_type(v).strip()
#v = v.decode('ascii', 'replace').strip()
if not bool(v)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coalesce_headers(cls, header_lines):
"""Collects headers that are spread across multiple lines into a single row""" |
header_lines = [list(hl) for hl in header_lines if bool(hl)]
if len(header_lines) == 0:
return []
if len(header_lines) == 1:
return header_lines[0]
# If there are gaps in the values of a line, copy them forward, so there
# is some value in every posit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_recursive(function, iterable):
""" Apply function recursively to every item or value of iterable and returns a new iterable object with the results. """ |
if isiterable(iterable):
dataOut = iterable.__class__()
for i in iterable:
if isinstance(dataOut, dict):
dataOut[i] = map_recursive(function, iterable[i])
else:
# convert to list and append
if not isinstance(dataOut, list):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_card(self, index=-1, cache=True, remove=True):
""" Retrieve a card any number of cards from the top. Returns a ``Card`` object loaded from a library if o... |
if len(self.cards) < index:
return None
retriever = self.cards.pop if remove else self.cards.__getitem__
code = retriever(index)
if self.library:
return self.library.load_card(code, cache)
else:
return code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def top_cards(self, number=1, cache=True, remove=True):
""" Retrieve the top number of cards as ``Librarian.Card`` objects in a list in order of top to bottom mo... |
getter = partial(self.get_card(cache=cache, remove=remove))
return [getter(index=i) for i in range(number)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_top_cards(self, other, number=1):
""" Move the top `number` of cards to the top of some `other` deck. By default only one card will be moved if `number`... |
other.cards.append(reversed(self.cards[-number:])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contians_attribute(self, attribute):
""" Returns how many cards in the deck have the specified attribute. This method requires a library to be stored in the ... |
if self.library is None:
return 0
load = self.library.load_card
matches = 0
for code in self.cards:
card = load(code)
if card.has_attribute(attribute):
matches += 1
return matches |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contains_info(self, key, value):
""" Returns how many cards in the deck have the specified value under the specified key in their info data. This method requ... |
if self.library is None:
return 0
load = self.library.load_card
matches = 0
for code in self.cards:
card = load(code)
if card.get_info(key) == value:
matches += 1
return matches |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
"""Connect to MQTT server and wait for server to acknowledge""" |
if not self.connect_attempted:
self.connect_attempted = True
self.client.connect(self.host, port=self.port)
self.client.loop_start()
while not self.connected:
log.info('waiting for MQTT connection...')
time.sleep(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 publish(self, topic, message):
"""Publish an MQTT message to a topic.""" |
self.connect()
log.info('publish {}'.format(message))
self.client.publish(topic, message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_abilities():
"""Visit Bulbapedia and pull names and descriptions from the table, 'list of Abilities.' Save as JSON.""" |
page = requests.get('http://bulbapedia.bulbagarden.net/wiki/Ability')
soup = bs4.BeautifulSoup(page.text)
table = soup.find("table", {"class": "sortable"})
tablerows = [tr for tr in table.children if tr != '\n'][1:]
abilities = {}
for tr in tablerows:
cells = tr.find_all('td')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_from_techshop_ws(tws_url):
"""Scrapes data from techshop.ws.""" |
r = requests.get(tws_url)
if r.status_code == 200:
data = BeautifulSoup(r.text, "lxml")
else:
data = "There was an error while accessing data on techshop.ws."
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_client_id(self, id):
"""Returns True if we have a client with a certain integer identifier""" |
return self.query(Client).filter(Client.id==id).count() != 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 client(self, id):
"""Returns the client object in the database given a certain id. Raises an error if that does not exist.""" |
return self.query(Client).filter(Client.id==id).one() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def protocol_names(self):
"""Returns all registered protocol names""" |
l = self.protocols()
retval = [str(k.name) for k in l]
return retval |
<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_protocol(self, name):
"""Tells if a certain protocol is available""" |
return self.query(Protocol).filter(Protocol.name==name).count() != 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 protocol(self, name):
"""Returns the protocol object in the database given a certain name. Raises an error if that does not exist.""" |
return self.query(Protocol).filter(Protocol.name==name).one() |
<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(__pkg: ModuleType) -> Tuple[Callable[[str], str], Callable[[str, str, int], str]]: """Configure ``gettext`` for given package. Args: __pkg: Package to u... |
package_locale = path.join(path.dirname(__pkg.__file__), 'locale')
gettext.install(__pkg.__name__, package_locale)
return gettext.gettext, gettext.ngettext |
<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(sub_command, quiet=False, no_edit=False, no_verify=False):
"""Run a git command Prefix that sub_command with "git " then run the command in shell If quie... |
if _working_dirs[0] != '.':
git_command = 'git -C "%s"' % _working_dirs[0]
else:
git_command = 'git'
edit = 'GIT_EDITOR=true' if no_edit else ''
verify = 'GIT_SSL_NO_VERIFY=true' if no_verify else ''
command = '%s %s %s %s' % (verify, edit, git_command, sub_command)
if not quiet... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def branches(remotes=False):
"""Return a list of all local branches in the repo If remotes is true then also include remote branches Note: the normal '*' indicat... |
stdout = branch('--list %s' % (remotes and '-a' or ''), quiet=True)
return [_.lstrip('*').strip() for _ in stdout.splitlines()] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def branches_containing(commit):
"""Return a list of branches conatining that commit""" |
lines = run('branch --contains %s' % commit).splitlines()
return [l.lstrip('* ') for l in 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 conflicted(path_to_file):
"""Whether there are any conflict markers in that file""" |
for line in open(path_to_file, 'r'):
for marker in '>="<':
if line.startswith(marker * 8):
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 config(key, value, local=True):
"""Set that config key to that value Unless local is set to False: only change local config """ |
option = local and '--local' or ''
run('config %s "%s" "%s"' % (option, key, value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clone(url, path=None, remove=True):
"""Clone a local repo from that URL to that path If path is not given, then use the git default: same as repo name If pat... |
clean = True
if path and os.path.isdir(path):
if not remove:
clean = False
else:
shutil.rmtree(path)
if clean:
stdout = run('clone %s %s' % (url, path or ''))
into = stdout.splitlines()[0].split("'")[1]
path_to_clone = os.path.realpath(into)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def needs_abort():
"""A command to abort an operation in progress For example a merge, cherry-pick or rebase If one of these operations has left the repo conflic... |
for line in status().splitlines():
if '--abort' in line:
for part in line.split('"'):
if '--abort' in part:
return part
elif 'All conflicts fixed but you are still merging' in line:
return 'git merge --abort'
elif 'You have unmerge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_branches(branch1, branch2):
"""Runs git show-branch between the 2 branches, parse result""" |
def find_column(string):
"""Find first non space line in the prefix"""
result = 0
for c in string:
if c == ' ':
result += 1
return result
def parse_show_line(string):
"""Parse a typical line from git show-branch
>>> parse_show_line(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkout(branch, quiet=False, as_path=False):
"""Check out that branch Defaults to a quiet checkout, giving no stdout if stdout it wanted, call with quiet = ... |
try:
if as_path:
branch = '-- %s' % branch
run('checkout %s %s' % (quiet and '-q' or '', branch))
return True
except GitError as e:
if 'need to resolve your current index' in e.output:
raise
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 same_diffs(commit1, commit2):
"""Whether those 2 commits have the same change Run "git range-diff" against 2 commit ranges: 1. parent of commit1 to commit1 1... |
def range_one(commit):
"""A git commit "range" to include only one commit"""
return '%s^..%s' % (commit, commit)
output = run('range-diff %s %s' % (range_one(commit1), range_one(commit2)))
lines = output.splitlines()
for i, line in enumerate(lines, 1):
if not line.startswith('%... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def renew_local_branch(branch, start_point, remote=False):
"""Make a new local branch from that start_point start_point is a git "commit-ish", e.g branch, tag, c... |
if branch in branches():
checkout(start_point)
delete(branch, force=True, remote=remote)
result = new_local_branch(branch, start_point)
if remote:
publish(branch)
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 publish(branch, full_force=False):
"""Publish that branch, i.e. push it to origin""" |
checkout(branch)
try:
push('--force --set-upstream origin', branch)
except ExistingReference:
if full_force:
push('origin --delete', branch)
push('--force --set-upstream origin', branch) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit(message, add=False, quiet=False):
"""Commit with that message and return the SHA1 of the commit If add is truish then "$ git add ." first """ |
if add:
run('add .')
try:
stdout = run('commit -m %r' % str(message), quiet=quiet)
except GitError as e:
s = str(e)
if 'nothing to commit' in s or 'no changes added to commit' in s:
raise EmptyCommit(*e.inits())
raise
return re.split('[ \]]', stdout.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 pull(rebase=True, refspec=None):
"""Pull refspec from remote repository to local If refspec is left as None, then pull current branch The '--rebase' option i... |
options = rebase and '--rebase' or ''
output = run('pull %s %s' % (options, refspec or ''))
return not re.search('up.to.date', 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 rebase(upstream, branch=None):
"""Rebase branch onto upstream If branch is empty, use current branch """ |
rebase_branch = branch and branch or current_branch()
with git_continuer(run, 'rebase --continue', no_edit=True):
stdout = run('rebase %s %s' % (upstream, rebase_branch))
return 'Applying' in stdout |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tempfile_writer(target):
'''write cache data to a temporary location. when writing is
complete, rename the file to the actual location. delete
the temporary file on any error'''
tmp = target.parent / ('_%s' % target.name)
try:
with tmp.open('wb') as fd:
yield fd
except:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def xform_key(self, key):
'''we transform cache keys by taking their sha1 hash so that
we don't need to worry about cache keys containing invalid
characters'''
newkey = hashlib.sha1(key.encode('utf-8'))
return newkey.hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def invalidate(self, key):
'''Clear an item from the cache'''
path = self.path(self.xform_key(key))
try:
LOG.debug('invalidate %s (%s)', key, path)
path.unlink()
except OSError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def invalidate_all(self):
'''Clear all items from the cache'''
LOG.debug('clearing cache')
appcache = str(self.get_app_cache())
for dirpath, dirnames, filenames in os.walk(appcache):
for name in filenames:
try:
pathlib.Path(dirpath, 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 store_iter(self, key, content):
'''stores content in the cache by iterating over
content'''
cachekey = self.xform_key(key)
path = self.path(cachekey)
with tempfile_writer(path) as fd:
for data in content:
LOG.debug('writing chunk of %d bytes for %... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def store_lines(self, key, content):
'''like store_iter, but appends a newline to each chunk of
content'''
return self.store_iter(
key,
(data + '\n'.encode('utf-8') for data in 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 load_fd(self, key, noexpire=False):
'''Look up an item in the cache and return an open file
descriptor for the object. It is the caller's responsibility
to close the file descriptor.'''
cachekey = self.xform_key(key)
path = self.path(cachekey)
try:
stat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load_lines(self, key, noexpire=None):
'''Look up up an item in the cache and return a line iterator.
The underlying file will be closed once all lines have been
consumed.'''
return line_iterator(self.load_fd(key, noexpire=noexpire)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load_iter(self, key, chunksize=None, noexpire=None):
'''Lookup an item in the cache and return an iterator
that reads chunksize bytes of data at a time. The underlying
file will be closed when all data has been read'''
return chunk_iterator(self.load_fd(key, noexpire=noexpire),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load(self, key, noexpire=None):
'''Lookup an item in the cache and return the raw content of
the file as a string.'''
with self.load_fd(key, noexpire=noexpire) as fd:
return fd.read() |
<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_bool_param(params, name, value):
""" Set a boolean parameter if applicable. :param dict params: A dict containing API call parameters. :param str name: T... |
if value is None:
return
if value is True:
params[name] = 'true'
elif value is False:
params[name] = 'false'
else:
raise ValueError("Parameter '%s' must be boolean or None, got %r." % (
name, value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_str_param(params, name, value):
""" Set a string parameter if applicable. :param dict params: A dict containing API call parameters. :param str name: The... |
if value is None:
return
if isinstance(value, str):
params[name] = value
elif isinstance(value, unicode):
params[name] = value.encode('utf-8')
else:
raise ValueError("Parameter '%s' must be a string or None, got %r." % (
name, value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_float_param(params, name, value, min=None, max=None):
""" Set a float parameter if applicable. :param dict params: A dict containing API call parameters.... |
if value is None:
return
try:
value = float(str(value))
except:
raise ValueError(
"Parameter '%s' must be numeric (or a numeric string) or None,"
" got %r." % (name, value))
if min is not None and value < min:
raise ValueError(
"Param... |
<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_int_param(params, name, value, min=None, max=None):
""" Set a int parameter if applicable. :param dict params: A dict containing API call parameters. :pa... |
if value is None:
return
try:
value = int(str(value))
except:
raise ValueError(
"Parameter '%s' must be an integer (or a string representation of"
" an integer) or None, got %r." % (name, value))
if min is not None and value < min:
raise ValueErr... |
<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_list_param(params, name, value, min_len=None, max_len=None):
""" Set a list parameter if applicable. :param dict params: A dict containing API call param... |
if value is None:
return
if type(value) is dict:
raise ValueError(
"Parameter '%s' cannot be a dict." % name)
try:
value = list(value)
except:
raise ValueError(
"Parameter '%s' must be a list (or a type that can be turned into"
"a li... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def statuses_user_timeline(self, user_id=None, screen_name=None, since_id=None, count=None, max_id=None, trim_user=None, exclude_replies=None, contributor_details... |
params = {}
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
set_str_param(params, 'since_id', since_id)
set_int_param(params, 'count', count)
set_str_param(params, 'max_id', max_id)
set_bool_param(params, 'trim_user', 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 statuses_home_timeline(self, count=None, since_id=None, max_id=None, trim_user=None, exclude_replies=None, contributor_details=None, include_entities=None):
... |
params = {}
set_int_param(params, 'count', count)
set_str_param(params, 'since_id', since_id)
set_str_param(params, 'max_id', max_id)
set_bool_param(params, 'trim_user', trim_user)
set_bool_param(params, 'exclude_replies', exclude_replies)
set_bool_param(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 statuses_retweets(self, id, count=None, trim_user=None):
""" Returns a list of the most recent retweets of the Tweet specified by the id parameter. https://d... |
params = {'id': id}
set_int_param(params, 'count', count)
set_bool_param(params, 'trim_user', trim_user)
return self._get_api('statuses/retweets.json', 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 statuses_show(self, id, trim_user=None, include_my_retweet=None, include_entities=None):
""" Returns a single Tweet, specified by the id parameter. https://d... |
params = {'id': id}
set_bool_param(params, 'trim_user', trim_user)
set_bool_param(params, 'include_my_retweet', include_my_retweet)
set_bool_param(params, 'include_entities', include_entities)
return self._get_api('statuses/show.json', 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 statuses_destroy(self, id, trim_user=None):
""" Destroys the status specified by the ID parameter. https://dev.twitter.com/docs/api/1.1/post/statuses/destroy... |
params = {'id': id}
set_bool_param(params, 'trim_user', trim_user)
return self._post_api('statuses/destroy.json', 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 statuses_update(self, status, in_reply_to_status_id=None, lat=None, long=None, place_id=None, display_coordinates=None, trim_user=None, media_ids=None):
""" ... |
params = {}
set_str_param(params, 'status', status)
set_str_param(params, 'in_reply_to_status_id', in_reply_to_status_id)
set_float_param(params, 'lat', lat, min=-90, max=90)
set_float_param(params, 'long', long, min=-180, max=180)
set_str_param(params, 'place_id', place... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def statuses_retweet(self, id, trim_user=None):
""" Retweets the status specified by the ID parameter. https://dev.twitter.com/docs/api/1.1/post/statuses/retweet... |
params = {'id': id}
set_bool_param(params, 'trim_user', trim_user)
return self._post_api('statuses/retweet.json', 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 media_upload(self, media, additional_owners=None):
""" Uploads an image to Twitter for later embedding in tweets. https://dev.twitter.com/rest/reference/post... |
params = {}
set_list_param(
params, 'additional_owners', additional_owners, max_len=100)
return self._upload_media('media/upload.json', media, 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 stream_filter(self, delegate, follow=None, track=None, locations=None, stall_warnings=None):
""" Streams public messages filtered by various parameters. http... |
params = {}
if follow is not None:
params['follow'] = ','.join(follow)
if track is not None:
params['track'] = ','.join(track)
if locations is not None:
raise NotImplementedError(
"The `locations` parameter is not yet supported.")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def userstream_user(self, delegate, stall_warnings=None, with_='followings', replies=None):
""" Streams messages for a single user. https://dev.twitter.com/docs/... |
params = {'stringify_friend_ids': 'true'}
set_bool_param(params, 'stall_warnings', stall_warnings)
set_str_param(params, 'with', with_)
set_str_param(params, 'replies', replies)
svc = TwitterStreamService(
lambda: self._get_userstream('user.json', 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 direct_messages(self, since_id=None, max_id=None, count=None, include_entities=None, skip_status=None):
""" Gets the 20 most recent direct messages received ... |
params = {}
set_str_param(params, 'since_id', since_id)
set_str_param(params, 'max_id', max_id)
set_int_param(params, 'count', count)
set_bool_param(params, 'include_entities', include_entities)
set_bool_param(params, 'skip_status', skip_status)
return self._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 direct_messages_sent(self, since_id=None, max_id=None, count=None, include_entities=None, page=None):
""" Gets the 20 most recent direct messages sent by the... |
params = {}
set_str_param(params, 'since_id', since_id)
set_str_param(params, 'max_id', max_id)
set_int_param(params, 'count', count)
set_int_param(params, 'page', page)
set_bool_param(params, 'include_entities', include_entities)
return self._get_api('direct_mes... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def direct_messages_show(self, id):
""" Gets the direct message with the given id. https://dev.twitter.com/docs/api/1.1/get/direct_messages/show :param str id: (... |
params = {}
set_str_param(params, 'id', id)
d = self._get_api('direct_messages/show.json', params)
d.addCallback(lambda dms: dms[0])
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 direct_messages_destroy(self, id, include_entities=None):
""" Destroys the direct message with the given id. https://dev.twitter.com/docs/api/1.1/post/direct... |
params = {}
set_str_param(params, 'id', id)
set_bool_param(params, 'include_entities', include_entities)
return self._post_api('direct_messages/destroy.json', 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 direct_messages_new(self, text, user_id=None, screen_name=None):
""" Sends a new direct message to the given user from the authenticating user. https://dev.t... |
params = {}
set_str_param(params, 'text', text)
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
return self._post_api('direct_messages/new.json', 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 friendships_create(self, user_id=None, screen_name=None, follow=None):
""" Allows the authenticating users to follow the specified user. https://dev.twitter.... |
params = {}
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
set_bool_param(params, 'follow', follow)
return self._post_api('friendships/create.json', 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 friendships_destroy(self, user_id=None, screen_name=None):
""" Allows the authenticating user to unfollow the specified user. https://dev.twitter.com/docs/ap... |
params = {}
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
return self._post_api('friendships/destroy.json', 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 api_call(endpoint, args, payload):
""" Generic function to call the RO API """ |
headers = {'content-type': 'application/json; ; charset=utf-8'}
url = 'https://{}/{}'.format(args['--server'], endpoint)
attempt = 0
resp = None
while True:
try:
attempt += 1
resp = requests.post(
url, data=json.dumps(payload), headers=headers,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def benchmark(store, n=10000):
""" Increments an integer count n times. """ |
x = UpdatableItem(store=store, count=0)
for _ in xrange(n):
x.count += 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 progressbar(stream, prefix='Loading: ', width=0.5, **options):
""" Generator filter to print a progress bar. """ |
size = len(stream)
if not size:
return stream
if 'width' not in options:
if width <= 1:
width = round(shutil.get_terminal_size()[0] * width)
options['width'] = width
with ProgressBar(max=size, prefix=prefix, **options) as b:
b.set(0)
for i, x in enume... |
<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_week_dates(year, week, as_timestamp=False):
""" Get the dates or timestamp of a week in a year. param year: The year. param week: The week. param as_time... |
year = int(year)
week = int(week)
start_date = date(year, 1, 1)
if start_date.weekday() > 3:
start_date = start_date + timedelta(7 - start_date.weekday())
else:
start_date = start_date - timedelta(start_date.weekday())
dlt = timedelta(days=(week-1)*7)
start = start_date + dl... |
<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_year_week(timestamp):
"""Get the year and week for a given timestamp.""" |
time_ = datetime.fromtimestamp(timestamp)
year = time_.isocalendar()[0]
week = time_.isocalendar()[1]
return year, week |
<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_last_weeks(number_of_weeks):
"""Get the last weeks.""" |
time_now = datetime.now()
year = time_now.isocalendar()[0]
week = time_now.isocalendar()[1]
weeks = []
for i in range(0, number_of_weeks):
start = get_week_dates(year, week - i, as_timestamp=True)[0]
n_year, n_week = get_year_week(start)
weeks.append((n_year, n_week))
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 gevent_wait_callback(conn, timeout=None):
"""A wait callback useful to allow gevent to work with Psycopg.""" |
while 1:
state = conn.poll()
if state == extensions.POLL_OK:
break
elif state == extensions.POLL_READ:
wait_read(conn.fileno(), timeout=timeout)
elif state == extensions.POLL_WRITE:
wait_write(conn.fileno(), timeout=timeout)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conf(self):
"""Generate the Sphinx `conf.py` configuration file Returns: (str):
the contents of the `conf.py` file. """ |
return self.env.get_template('conf.py.j2').render(
metadata=self.metadata,
package=self.package) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makefile(self):
"""Generate the documentation Makefile. Returns: (str):
the contents of the `Makefile`. """ |
return self.env.get_template('Makefile.j2').render(
metadata=self.metadata,
package=self.package) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare_trees(dir1, dir2):
"""Parse two directories and return lists of unique files""" |
paths1 = DirPaths(dir1).walk()
paths2 = DirPaths(dir2).walk()
return unique_venn(paths1, paths2) |
<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):
'''Validates a data dict against this schema.
Args:
data (dict): The data to be validated.
Raises:
ValidationError: If the data is invalid.
'''
try:
self._validator.validate(data)
except jsonschema.Validation... |
<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_version(request, response):
"""Set version and revision to response """ |
settings = request.registry.settings
resolver = DottedNameResolver()
# get version config
version_header = settings.get(
'api.version_header',
'X-Version',
)
version_header_value = settings.get('api.version_header_value')
if callable(version_header_value):
version_h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.