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 isalive(path):
""" Returns True if the file with the given name contains a process id that is still alive. Returns False otherwise. :type path: str :param path: The name of the pidfile. :rtype: bool :return: Whether the process is alive. """ |
# try to read the pid from the pidfile
pid = read(path)
if pid is None:
return False
# Check if a process with the given pid exists.
try:
os.kill(pid, 0) # Signal 0 does not kill, but check.
except OSError as xxx_todo_changeme1:
(code, text) = xxx_todo_changeme1.args
if code == errno.ESRCH: # No such process.
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kill(path):
""" Kills the process, if it still exists. :type path: str :param path: The name of the pidfile. """ |
# try to read the pid from the pidfile
pid = read(path)
if pid is None:
return
# Try to kill the process.
logging.info("Killing PID %s", pid)
try:
os.kill(pid, 9)
except OSError as xxx_todo_changeme2:
# re-raise if the error wasn't "No such process"
(code, text) = xxx_todo_changeme2.args
# re-raise if the error wasn't "No such process"
if code != errno.ESRCH:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(path):
""" Writes the current process id to the given pidfile. :type path: str :param path: The name of the pidfile. """ |
pid = os.getpid()
logging.info("Writing PID %s to '%s'", pid, path)
try:
pidfile = open(path, 'wb')
# get a non-blocking exclusive lock
fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
# clear out the file
pidfile.seek(0)
pidfile.truncate(0)
# write the pid
pidfile.write(str(pid))
finally:
try:
pidfile.close()
except:
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 set_username_prompt(self, regex=None):
""" Defines a pattern that is used to monitor the response of the connected host for a username prompt. :type regex: RegEx :param regex: The pattern that, when matched, causes an error. """ |
if regex is None:
self.manual_user_re = regex
else:
self.manual_user_re = to_regexs(regex) |
<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_password_prompt(self, regex=None):
""" Defines a pattern that is used to monitor the response of the connected host for a password prompt. :type regex: RegEx :param regex: The pattern that, when matched, causes an error. """ |
if regex is None:
self.manual_password_re = regex
else:
self.manual_password_re = to_regexs(regex) |
<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_login_error_prompt(self, error=None):
""" Defines a pattern that is used to monitor the response of the connected host during the authentication procedure. If the pattern matches an error is raised. :type error: RegEx :param error: The pattern that, when matched, causes an error. """ |
if error is None:
self.manual_login_error_re = error
else:
self.manual_login_error_re = to_regexs(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 connect(self, hostname=None, port=None):
""" Opens the connection to the remote host or IP address. :type hostname: string :param hostname: The remote host or IP address. :type port: int :param port: The remote TCP port number. """ |
if hostname is not None:
self.host = hostname
conn = self._connect_hook(self.host, port)
self.os_guesser.protocol_info(self.get_remote_version())
self.auto_driver = driver_map[self.guess_os()]
if self.get_banner():
self.os_guesser.data_received(self.get_banner(), False)
return conn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def protocol_authenticate(self, account=None):
""" Low-level API to perform protocol-level authentication on protocols that support it. .. HINT:: In most cases, you want to use the login() method instead, as it automatically chooses the best login method for each protocol. :type account: Account :param account: An account object, like login(). """ |
with self._get_account(account) as account:
user = account.get_name()
password = account.get_password()
key = account.get_key()
if key is None:
self._dbg(1, "Attempting to authenticate %s." % user)
self._protocol_authenticate(user, password)
else:
self._dbg(1, "Authenticate %s with key." % user)
self._protocol_authenticate_by_key(user, key)
self.proto_authenticated = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def app_authenticate(self, account=None, flush=True, bailout=False):
""" Attempt to perform application-level authentication. Application level authentication is needed on devices where the username and password are requested from the user after the connection was already accepted by the remote device. The difference between app-level authentication and protocol-level authentication is that in the latter case, the prompting is handled by the client, whereas app-level authentication is handled by the remote device. App-level authentication comes in a large variety of forms, and while this method tries hard to support them all, there is no guarantee that it will always work. We attempt to smartly recognize the user and password prompts; for a list of supported operating systems please check the Exscript.protocols.drivers module. Returns upon finding the first command line prompt. Depending on whether the flush argument is True, it also removes the prompt from the incoming buffer. :type account: Account :param account: An account object, like login(). :type flush: bool :param flush: Whether to flush the last prompt from the buffer. :type bailout: bool :param bailout: Whether to wait for a prompt after sending the password. """ |
with self._get_account(account) as account:
user = account.get_name()
password = account.get_password()
self._dbg(1, "Attempting to app-authenticate %s." % user)
self._app_authenticate(account, password, flush, bailout)
self.app_authenticated = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_monitor(self, pattern, callback, limit=80):
""" Calls the given function whenever the given pattern matches the incoming data. .. HINT:: If you want to catch all incoming data regardless of a pattern, use the Protocol.data_received_event event instead. Arguments passed to the callback are the protocol instance, the index of the match, and the match object of the regular expression. :type pattern: str|re.RegexObject|list(str|re.RegexObject) :param pattern: One or more regular expressions. :type callback: callable :param callback: The function that is called. :type limit: int :param limit: The maximum size of the tail of the buffer that is searched, in number of bytes. """ |
self.buffer.add_monitor(pattern, partial(callback, self), limit) |
<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_connection(func):
""" A decorator that unpacks the host and connection from the job argument and passes them as separate arguments to the wrapped function. """ |
def _wrapped(job, *args, **kwargs):
job_id = id(job)
to_parent = job.data['pipe']
host = job.data['host']
# Create a protocol adapter.
mkaccount = partial(_account_factory, to_parent, host)
pargs = {'account_factory': mkaccount,
'stdout': job.data['stdout']}
pargs.update(host.get_options())
conn = prepare(host, **pargs)
# Connect and run the function.
log_options = get_label(func, 'log_to')
if log_options is not None:
# Enable logging.
proxy = LoggerProxy(to_parent, log_options['logger_id'])
log_cb = partial(proxy.log, job_id)
proxy.add_log(job_id, job.name, job.failures + 1)
conn.data_received_event.listen(log_cb)
try:
conn.connect(host.get_address(), host.get_tcp_port())
result = func(job, host, conn, *args, **kwargs)
conn.close(force=True)
except:
proxy.log_aborted(job_id, serializeable_sys_exc_info())
raise
else:
proxy.log_succeeded(job_id)
finally:
conn.data_received_event.disconnect(log_cb)
else:
conn.connect(host.get_address(), host.get_tcp_port())
result = func(job, host, conn, *args, **kwargs)
conn.close(force=True)
return result
return _wrapped |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join(self):
""" Waits until all jobs are completed. """ |
self._dbg(2, 'Waiting for the queue to finish.')
self.workqueue.wait_until_done()
for child in list(self.pipe_handlers.values()):
child.join()
self._del_status_bar()
self._print_status_bar()
gc.collect() |
<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(self, force=False):
""" Stop executing any further jobs. If the force argument is True, the function does not wait until any queued jobs are completed but stops immediately. After emptying the queue it is restarted, so you may still call run() after using this method. :type force: bool :param force: Whether to wait until all jobs were processed. """ |
if not force:
self.join()
self._dbg(2, 'Shutting down queue...')
self.workqueue.shutdown(True)
self._dbg(2, 'Queue shut down.')
self._del_status_bar() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
""" Remove all accounts, hosts, etc. """ |
self._dbg(2, 'Resetting queue...')
self.account_manager.reset()
self.workqueue.shutdown(True)
self.completed = 0
self.total = 0
self.failed = 0
self.status_bar_length = 0
self._dbg(2, 'Queue reset.')
self._del_status_bar() |
<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(scope, source, index):
""" Returns a copy of the list item with the given index. It is an error if an item with teh given index does not exist. :type source: string :param source: A list of strings. :type index: string :param index: A list of strings. :rtype: string :return: The cleaned up list of strings. """ |
try:
index = int(index[0])
except IndexError:
raise ValueError('index variable is required')
except ValueError:
raise ValueError('index is not an integer')
try:
return [source[index]]
except IndexError:
raise ValueError('no such item in the 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 execute(scope, command):
""" Executes the given command locally. :type command: string :param command: A shell command. """ |
process = Popen(command[0],
shell=True,
stdin=PIPE,
stdout=PIPE,
stderr=STDOUT,
close_fds=True)
scope.define(__response__=process.stdout.read())
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, key, value, confidence=100):
""" Defines the given value with the given confidence, unless the same value is already defined with a higher confidence level. """ |
if value is None:
return
if key in self.info:
old_confidence, old_value = self.info.get(key)
if old_confidence >= confidence:
return
self.info[key] = (confidence, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, key, confidence=0):
""" Returns the info with the given key, if it has at least the given confidence. Returns None otherwise. """ |
if key not in self.info:
return None
conf, value = self.info.get(key)
if conf >= confidence:
return value
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 bind(function, *args, **kwargs):
""" Wraps the given function such that when it is called, the given arguments are passed in addition to the connection argument. :type function: function :param function: The function that's ought to be wrapped. :type args: list :param args: Passed on to the called function. :type kwargs: dict :param kwargs: Passed on to the called function. :rtype: function :return: The wrapped function. """ |
def decorated(*inner_args, **inner_kwargs):
kwargs.update(inner_kwargs)
return function(*(inner_args + args), **kwargs)
copy_labels(function, decorated)
return decorated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def problem_glob(extension='.py'):
"""Returns ProblemFile objects for all valid problem files""" |
filenames = glob.glob('*[0-9][0-9][0-9]*{}'.format(extension))
return [ProblemFile(file) for file in filenames] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def human_time(timespan, precision=3):
"""Formats the timespan in a human readable format""" |
if timespan >= 60.0:
# Format time greater than one minute in a human-readable format
# Idea from http://snipplr.com/view/5713/
def _format_long_time(time):
suffixes = ('d', 'h', 'm', 's')
lengths = (24*60*60, 60*60, 60, 1)
for suffix, length in zip(suffixes, lengths):
value = int(time / length)
if value > 0:
time %= length
yield '%i%s' % (value, suffix)
if time < 1:
break
return ' '.join(_format_long_time(timespan))
else:
units = ['s', 'ms', 'us', 'ns']
# Attempt to replace 'us' with 'µs' if UTF-8 encoding has been set
if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding == 'UTF-8':
try:
units[2] = b'\xc2\xb5s'.decode('utf-8')
except UnicodeEncodeError:
pass
scale = [1.0, 1e3, 1e6, 1e9]
if timespan > 0.0:
# Determine scale of timespan (s = 0, ms = 1, µs = 2, ns = 3)
order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
else:
order = 3
return '%.*g %s' % (precision, timespan * scale[order], units[order]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_time(start, end):
"""Returns string with relevant time information formatted properly""" |
try:
cpu_usr = end[0] - start[0]
cpu_sys = end[1] - start[1]
except TypeError:
# `clock()[1] == None` so subtraction results in a TypeError
return 'Time elapsed: {}'.format(human_time(cpu_usr))
else:
times = (human_time(x) for x in (cpu_usr, cpu_sys, cpu_usr + cpu_sys))
return 'Time elapsed: user: {}, sys: {}, total: {}'.format(*times) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filename(self, prefix='', suffix='', extension='.py'):
"""Returns filename padded with leading zeros""" |
return BASE_NAME.format(prefix, self.num, suffix, extension) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def glob(self):
"""Returns a sorted glob of files belonging to a given problem""" |
file_glob = glob.glob(BASE_NAME.format('*', self.num, '*', '.*'))
# Sort globbed files by tuple (filename, extension)
return sorted(file_glob, key=lambda f: os.path.splitext(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 copy_resources(self):
"""Copies the relevant resources to a resources subdirectory""" |
if not os.path.isdir('resources'):
os.mkdir('resources')
resource_dir = os.path.join(os.getcwd(), 'resources', '')
copied_resources = []
for resource in self.resources:
src = os.path.join(EULER_DATA, 'resources', resource)
if os.path.isfile(src):
shutil.copy(src, resource_dir)
copied_resources.append(resource)
if copied_resources:
copied = ', '.join(copied_resources)
path = os.path.relpath(resource_dir, os.pardir)
msg = "Copied {} to {}.".format(copied, path)
click.secho(msg, fg='green') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solution(self):
"""Returns the answer to a given problem""" |
num = self.num
solution_file = os.path.join(EULER_DATA, 'solutions.txt')
solution_line = linecache.getline(solution_file, num)
try:
answer = solution_line.split('. ')[1].strip()
except IndexError:
answer = None
if answer:
return answer
else:
msg = 'Answer for problem %i not found in solutions.txt.' % num
click.secho(msg, fg='red')
click.echo('If you have an answer, consider submitting a pull '
'request to EulerPy on GitHub.')
sys.exit(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 text(self):
"""Parses problems.txt and returns problem text""" |
def _problem_iter(problem_num):
problem_file = os.path.join(EULER_DATA, 'problems.txt')
with open(problem_file) as f:
is_problem = False
last_line = ''
for line in f:
if line.strip() == 'Problem %i' % problem_num:
is_problem = True
if is_problem:
if line == last_line == '\n':
break
else:
yield line[:-1]
last_line = line
problem_lines = [line for line in _problem_iter(self.num)]
if problem_lines:
# First three lines are the problem number, the divider line,
# and a newline, so don't include them in the returned string.
# Also, strip the final newline.
return '\n'.join(problem_lines[3:-1])
else:
msg = 'Problem %i not found in problems.txt.' % self.num
click.secho(msg, fg='red')
click.echo('If this problem exists on Project Euler, consider '
'submitting a pull request to EulerPy on GitHub.')
sys.exit(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 cheat(num):
"""View the answer to a problem.""" |
# Define solution before echoing in case solution does not exist
solution = click.style(Problem(num).solution, bold=True)
click.confirm("View answer to problem %i?" % num, abort=True)
click.echo("The answer to problem {} is {}.".format(num, solution)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate(num, prompt_default=True):
"""Generates Python file for a problem.""" |
p = Problem(num)
problem_text = p.text
msg = "Generate file for problem %i?" % num
click.confirm(msg, default=prompt_default, abort=True)
# Allow skipped problem files to be recreated
if p.glob:
filename = str(p.file)
msg = '"{}" already exists. Overwrite?'.format(filename)
click.confirm(click.style(msg, fg='red'), abort=True)
else:
# Try to keep prefix consistent with existing files
previous_file = Problem(num - 1).file
prefix = previous_file.prefix if previous_file else ''
filename = p.filename(prefix=prefix)
header = 'Project Euler Problem %i' % num
divider = '=' * len(header)
text = '\n'.join([header, divider, '', problem_text])
content = '\n'.join(['"""', text, '"""'])
with open(filename, 'w') as f:
f.write(content + '\n\n\n')
click.secho('Successfully created "{}".'.format(filename), fg='green')
# Copy over problem resources if required
if p.resources:
p.copy_resources() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preview(num):
"""Prints the text of a problem.""" |
# Define problem_text before echoing in case problem does not exist
problem_text = Problem(num).text
click.secho("Project Euler Problem %i" % num, bold=True)
click.echo(problem_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 skip(num):
"""Generates Python file for the next problem.""" |
click.echo("Current problem is problem %i." % num)
generate(num + 1, prompt_default=False)
Problem(num).file.change_suffix('-skipped') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify(num, filename=None, exit=True):
"""Verifies the solution to a problem.""" |
p = Problem(num)
filename = filename or p.filename()
if not os.path.isfile(filename):
# Attempt to verify the first problem file matched by glob
if p.glob:
filename = str(p.file)
else:
click.secho('No file found for problem %i.' % p.num, fg='red')
sys.exit(1)
solution = p.solution
click.echo('Checking "{}" against solution: '.format(filename), nl=False)
cmd = (sys.executable or 'python', filename)
start = clock()
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
stdout = proc.communicate()[0]
end = clock()
time_info = format_time(start, end)
# Return value of anything other than 0 indicates an error
if proc.poll() != 0:
click.secho('Error calling "{}".'.format(filename), fg='red')
click.secho(time_info, fg='cyan')
# Return None if option is not --verify-all, otherwise exit
return sys.exit(1) if exit else None
# Decode output if returned as bytes (Python 3)
if isinstance(stdout, bytes):
output = stdout.decode('ascii')
# Split output lines into array; make empty output more readable
output_lines = output.splitlines() if output else ['[no output]']
# If output is multi-lined, print the first line of the output on a
# separate line from the "checking against solution" message, and
# skip the solution check (multi-line solution won't be correct)
if len(output_lines) > 1:
is_correct = False
click.echo() # force output to start on next line
click.secho('\n'.join(output_lines), bold=True, fg='red')
else:
is_correct = output_lines[0] == solution
fg_colour = 'green' if is_correct else 'red'
click.secho(output_lines[0], bold=True, fg=fg_colour)
click.secho(time_info, fg='cyan')
# Remove any suffix from the filename if its solution is correct
if is_correct:
p.file.change_suffix('')
# Exit here if answer was incorrect, otherwise return is_correct value
return sys.exit(1) if exit and not is_correct else is_correct |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_all(num):
""" Verifies all problem files in the current directory and prints an overview of the status of each problem. """ |
# Define various problem statuses
keys = ('correct', 'incorrect', 'error', 'skipped', 'missing')
symbols = ('C', 'I', 'E', 'S', '.')
colours = ('green', 'red', 'yellow', 'cyan', 'white')
status = OrderedDict(
(key, click.style(symbol, fg=colour, bold=True))
for key, symbol, colour in zip(keys, symbols, colours)
)
overview = {}
# Search through problem files using glob module
files = problem_glob()
# No Project Euler files in the current directory
if not files:
click.echo("No Project Euler files found in the current directory.")
sys.exit(1)
for file in files:
# Catch KeyboardInterrupt during verification to allow the user to
# skip the verification of a specific problem if it takes too long
try:
is_correct = verify(file.num, filename=str(file), exit=False)
except KeyboardInterrupt:
overview[file.num] = status['skipped']
else:
if is_correct is None: # error was returned by problem file
overview[file.num] = status['error']
elif is_correct:
overview[file.num] = status['correct']
elif not is_correct:
overview[file.num] = status['incorrect']
# Attempt to add "skipped" suffix to the filename if the
# problem file is not the current problem. This is useful
# when the --verify-all is used in a directory containing
# files generated pre-v1.1 (before files with suffixes)
if file.num != num:
file.change_suffix('-skipped')
# Separate each verification with a newline
click.echo()
# Print overview of the status of each problem
legend = ', '.join('{} = {}'.format(v, k) for k, v in status.items())
click.echo('-' * 63)
click.echo(legend + '\n')
# Rows needed for overview is based on the current problem number
num_of_rows = (num + 19) // 20
for row in range(1, num_of_rows + 1):
low, high = (row * 20) - 19, (row * 20)
click.echo("Problems {:03d}-{:03d}: ".format(low, high), nl=False)
for problem in range(low, high + 1):
# Add missing status to problems with no corresponding file
status = overview[problem] if problem in overview else '.'
# Separate problem indicators into groups of 5
spacer = ' ' if (problem % 5 == 0) else ' '
# Start a new line at the end of each row
click.secho(status + spacer, nl=(problem % 20 == 0))
click.echo() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def euler_options(fn):
"""Decorator to link CLI options with their appropriate functions""" |
euler_functions = cheat, generate, preview, skip, verify, verify_all
# Reverse functions to print help page options in alphabetical order
for option in reversed(euler_functions):
name, docstring = option.__name__, option.__doc__
kwargs = {'flag_value': option, 'help': docstring}
# Apply flag(s) depending on whether or not name is a single word
flag = '--%s' % name.replace('_', '-')
flags = [flag] if '_' in name else [flag, '-%s' % name[0]]
fn = click.option('option', *flags, **kwargs)(fn)
return fn |
<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(option, problem):
"""Python-based Project Euler command line tool.""" |
# No problem given (or given option ignores the problem argument)
if problem == 0 or option in {skip, verify_all}:
# Determine the highest problem number in the current directory
files = problem_glob()
problem = max(file.num for file in files) if files else 0
# No Project Euler files in current directory (no glob results)
if problem == 0:
# Generate the first problem file if option is appropriate
if option not in {cheat, preview, verify_all}:
msg = "No Project Euler files found in the current directory."
click.echo(msg)
option = generate
# Set problem number to 1
problem = 1
# --preview and no problem; preview the next problem
elif option is preview:
problem += 1
# No option and no problem; generate next file if answer is
# correct (verify() will exit if the solution is incorrect)
if option is None:
verify(problem)
problem += 1
option = generate
# Problem given but no option; decide between generate and verify
elif option is None:
option = verify if Problem(problem).glob else generate
# Execute function based on option
option(problem)
sys.exit(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 start(self, *args, **kwargs):
""" Start the server thread if it wasn't created with autostart = True. """ |
if args:
LOG.debug("args: %s" % str(args))
if kwargs:
LOG.debug("kwargs: %s" % str(kwargs))
try:
self._server.start()
self._server.proxyInit()
return True
except Exception as err:
LOG.critical("Failed to start server")
LOG.debug(str(err))
self._server.stop()
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 stop(self, *args, **kwargs):
""" Stop the server thread. """ |
if args:
LOG.debug("args: %s" % str(args))
if kwargs:
LOG.debug("kwargs: %s" % str(kwargs))
try:
self._server.stop()
self._server = None
# Device-storage clear
self.devices.clear()
self.devices_all.clear()
self.devices_raw.clear()
self.devices_raw_dict.clear()
return True
except Exception as err:
LOG.critical("Failed to stop server")
LOG.debug(str(err))
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 getMetadata(self, remote, address, key):
"""Get metadata of device""" |
if self._server is not None:
# pylint: disable=E1121
return self._server.getAllMetadata(remote, address, 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 get_hs_color(self):
""" Return the color of the light as HSV color without the "value" component for the brightness. Returns (hue, saturation) tuple with values in range of 0-1, representing the H and S component of the HSV color system. """ |
# Get the color from homematic. In general this is just the hue parameter.
hm_color = self.getCachedOrUpdatedValue("COLOR", channel=self._color_channel)
if hm_color >= 200:
# 200 is a special case (white), so we have a saturation of 0.
# Larger values are undefined. For the sake of robustness we return "white" anyway.
return 0, 0
# For all other colors we assume saturation of 1
return hm_color/200, 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 set_hs_color(self, hue: float, saturation: float):
""" Set a fixed color and also turn off effects in order to see the color. :param hue: Hue component (range 0-1) :param saturation: Saturation component (range 0-1). Yields white for values near 0, other values are interpreted as 100% saturation. The input values are the components of an HSV color without the value/brightness component. Example colors: * Green: set_hs_color(120/360, 1) * Blue: set_hs_color(240/360, 1) * Yellow: set_hs_color(60/360, 1) * White: set_hs_color(0, 0) """ |
self.turn_off_effect()
if saturation < 0.1: # Special case (white)
hm_color = 200
else:
hm_color = int(round(max(min(hue, 1), 0) * 199))
self.setValue(key="COLOR", channel=self._color_channel, value=hm_color) |
<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_effect(self) -> str: """Return the current color change program of the light.""" |
effect_value = self.getCachedOrUpdatedValue("PROGRAM", channel=self._effect_channel)
try:
return self._light_effect_list[effect_value]
except IndexError:
LOG.error("Unexpected color effect returned by CCU")
return "Unknown" |
<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_effect(self, effect_name: str):
"""Sets the color change program of the light.""" |
try:
effect_index = self._light_effect_list.index(effect_name)
except ValueError:
LOG.error("Trying to set unknown light effect")
return False
return self.setValue(key="PROGRAM", channel=self._effect_channel, value=effect_index) |
<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_http_credentials(username=None, password=None):
"""Build auth part for api_url.""" |
credentials = ''
if username is None:
return credentials
if username is not None:
if ':' in username:
return credentials
credentials += username
if credentials and password is not None:
credentials += ":%s" % password
return "%s@" % credentials |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_api_url(host=REMOTES['default']['ip'], port=REMOTES['default']['port'], path=REMOTES['default']['path'], username=None, password=None, ssl=False):
"""Build API URL from components.""" |
credentials = make_http_credentials(username, password)
scheme = 'http'
if not path:
path = ''
if path and not path.startswith('/'):
path = "/%s" % path
if ssl:
scheme += 's'
return "%s://%s%s:%i%s" % (scheme, credentials, host, port, 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 createDeviceObjects(self, interface_id):
"""Transform the raw device descriptions into instances of devicetypes.generic.HMDevice or availabe subclass.""" |
global WORKING
WORKING = True
remote = interface_id.split('-')[-1]
LOG.debug(
"RPCFunctions.createDeviceObjects: iterating interface_id = %s" % (remote, ))
# First create parent object
for dev in self._devices_raw[remote]:
if not dev['PARENT']:
if dev['ADDRESS'] not in self.devices_all[remote]:
try:
if dev['TYPE'] in devicetypes.SUPPORTED:
deviceObject = devicetypes.SUPPORTED[dev['TYPE']](
dev, self._proxies[interface_id], self.resolveparamsets)
LOG.debug("RPCFunctions.createDeviceObjects: created %s as SUPPORTED device for %s" % (
dev['ADDRESS'], dev['TYPE']))
else:
deviceObject = devicetypes.UNSUPPORTED(
dev, self._proxies[interface_id], self.resolveparamsets)
LOG.debug("RPCFunctions.createDeviceObjects: created %s as UNSUPPORTED device for %s" % (
dev['ADDRESS'], dev['TYPE']))
LOG.debug(
"RPCFunctions.createDeviceObjects: adding to self.devices_all")
self.devices_all[remote][dev['ADDRESS']] = deviceObject
LOG.debug(
"RPCFunctions.createDeviceObjects: adding to self.devices")
self.devices[remote][dev['ADDRESS']] = deviceObject
except Exception as err:
LOG.critical(
"RPCFunctions.createDeviceObjects: Parent: %s", str(err))
# Then create all children for parent
for dev in self._devices_raw[remote]:
if dev['PARENT']:
try:
if dev['ADDRESS'] not in self.devices_all[remote]:
deviceObject = HMChannel(
dev, self._proxies[interface_id], self.resolveparamsets)
self.devices_all[remote][dev['ADDRESS']] = deviceObject
self.devices[remote][dev['PARENT']].CHANNELS[
dev['INDEX']] = deviceObject
except Exception as err:
LOG.critical(
"RPCFunctions.createDeviceObjects: Child: %s", str(err))
if self.devices_all[remote] and self.remotes[remote].get('resolvenames', False):
self.addDeviceNames(remote)
WORKING = False
if self.systemcallback:
self.systemcallback('createDeviceObjects')
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def event(self, interface_id, address, value_key, value):
"""If a device emits some sort event, we will handle it here.""" |
LOG.debug("RPCFunctions.event: interface_id = %s, address = %s, value_key = %s, value = %s" % (
interface_id, address, value_key.upper(), str(value)))
self.devices_all[interface_id.split(
'-')[-1]][address].event(interface_id, value_key.upper(), value)
if self.eventcallback:
self.eventcallback(interface_id=interface_id, address=address,
value_key=value_key.upper(), value=value)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __request(self, *args, **kwargs):
""" Call method on server side """ |
with self.lock:
parent = xmlrpc.client.ServerProxy
# pylint: disable=E1101
return parent._ServerProxy__request(self, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parseCCUSysVar(self, data):
"""Helper to parse type of system variables of CCU""" |
if data['type'] == 'LOGIC':
return data['name'], data['value'] == 'true'
elif data['type'] == 'NUMBER':
return data['name'], float(data['value'])
elif data['type'] == 'LIST':
return data['name'], int(data['value'])
else:
return data['name'], data['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 jsonRpcLogin(self, remote):
"""Login to CCU and return session""" |
session = False
try:
params = {"username": self.remotes[remote][
'username'], "password": self.remotes[remote]['password']}
response = self._rpcfunctions.jsonRpcPost(
self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPORT), "Session.login", params)
if response['error'] is None and response['result']:
session = response['result']
if not session:
LOG.warning(
"ServerThread.jsonRpcLogin: Unable to open session.")
except Exception as err:
LOG.debug(
"ServerThread.jsonRpcLogin: Exception while logging in via JSON-RPC: %s" % str(err))
return session |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jsonRpcLogout(self, remote, session):
"""Logout of CCU""" |
logout = False
try:
params = {"_session_id_": session}
response = self._rpcfunctions.jsonRpcPost(
self.remotes[remote]['ip'], self.remotes[remote].get('jsonport', DEFAULT_JSONPORT), "Session.logout", params)
if response['error'] is None and response['result']:
logout = response['result']
except Exception as err:
LOG.debug(
"ServerThread.jsonRpcLogout: Exception while logging in via JSON-RPC: %s" % str(err))
return logout |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def homegearCheckInit(self, remote):
"""Check if proxy is still initialized""" |
rdict = self.remotes.get(remote)
if not rdict:
return False
if rdict.get('type') != BACKEND_HOMEGEAR:
return False
try:
interface_id = "%s-%s" % (self._interface_id, remote)
return self.proxies[interface_id].clientServerInitialized(interface_id)
except Exception as err:
LOG.debug(
"ServerThread.homegearCheckInit: Exception: %s" % str(err))
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_ontime(self, ontime):
"""Set duration th switch stays on when toggled. """ |
try:
ontime = float(ontime)
except Exception as err:
LOG.debug("SwitchPowermeter.set_ontime: Exception %s" % (err,))
return False
self.actionNodeData("ON_TIME", ontime) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def event(self, interface_id, key, value):
""" Handle the event received by server. """ |
LOG.info(
"HMGeneric.event: address=%s, interface_id=%s, key=%s, value=%s"
% (self._ADDRESS, interface_id, key, value))
self._VALUES[key] = value # Cache the value
for callback in self._eventcallbacks:
LOG.debug("HMGeneric.event: Using callback %s " % str(callback))
callback(self._ADDRESS, interface_id, 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 getParamsetDescription(self, paramset):
""" Descriptions for paramsets are available to determine what can be don with the device. """ |
try:
self._PARAMSET_DESCRIPTIONS[paramset] = self._proxy.getParamsetDescription(self._ADDRESS, paramset)
except Exception as err:
LOG.error("HMGeneric.getParamsetDescription: Exception: " + str(err))
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 updateParamset(self, paramset):
""" Devices should not update their own paramsets. They rely on the state of the server. Hence we pull the specified paramset. """ |
try:
if paramset:
if self._proxy:
returnset = self._proxy.getParamset(self._ADDRESS, paramset)
if returnset:
self._paramsets[paramset] = returnset
if self.PARAMSETS:
if self.PARAMSETS.get(PARAMSET_VALUES):
self._VALUES[PARAM_UNREACH] = self.PARAMSETS.get(PARAMSET_VALUES).get(PARAM_UNREACH)
return True
return False
except Exception as err:
LOG.debug("HMGeneric.updateParamset: Exception: %s, %s, %s" % (str(err), str(self._ADDRESS), str(paramset)))
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 updateParamsets(self):
""" Devices should update their own paramsets. They rely on the state of the server. Hence we pull all paramsets. """ |
try:
for ps in self._PARAMSETS:
self.updateParamset(ps)
return True
except Exception as err:
LOG.error("HMGeneric.updateParamsets: Exception: " + str(err))
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 putParamset(self, paramset, data={}):
""" Some devices act upon changes to paramsets. A "putted" paramset must not contain all keys available in the specified paramset, just the ones which are writable and should be changed. """ |
try:
if paramset in self._PARAMSETS and data:
self._proxy.putParamset(self._ADDRESS, paramset, data)
# We update all paramsets to at least have a temporarily accurate state for the device.
# This might not be true for tasks that take long to complete (lifting a rollershutter completely etc.).
# For this the server-process has to call the updateParamsets-method when it receives events for the device.
self.updateParamsets()
return True
else:
return False
except Exception as err:
LOG.error("HMGeneric.putParamset: Exception: " + str(err))
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 getCachedOrUpdatedValue(self, key):
""" Gets the device's value with the given key. If the key is not found in the cache, the value is queried from the host. """ |
try:
return self._VALUES[key]
except KeyError:
return self.getValue(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 getCachedOrUpdatedValue(self, key, channel=None):
""" Gets the channel's value with the given key. If the key is not found in the cache, the value is queried from the host. If 'channel' is given, the respective channel's value is returned. """ |
if channel:
return self._hmchannels[channel].getCachedOrUpdatedValue(key)
try:
return self._VALUES[key]
except KeyError:
value = self._VALUES[key] = self.getValue(key)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def UNREACH(self):
""" Returns true if the device or any children is not reachable """ |
if self._VALUES.get(PARAM_UNREACH, False):
return True
else:
for device in self._hmchannels.values():
if device.UNREACH:
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 getAttributeData(self, name, channel=None):
""" Returns a attribut """ |
return self._getNodeData(name, self._ATTRIBUTENODE, channel) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getBinaryData(self, name, channel=None):
""" Returns a binary node """ |
return self._getNodeData(name, self._BINARYNODE, channel) |
<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_temperature(self, target_temperature):
""" Set the target temperature. """ |
try:
target_temperature = float(target_temperature)
except Exception as err:
LOG.debug("Thermostat.set_temperature: Exception %s" % (err,))
return False
self.writeNodeData("SET_TEMPERATURE", target_temperature) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Shut down our XML-RPC server.""" |
LOG.info("Shutting down server")
self.server.shutdown()
LOG.debug("ServerThread.stop: Stopping ServerThread")
self.server.server_close()
LOG.info("Server stopped") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def heirarchical_help(shovel, prefix):
'''Given a shovel of tasks, display a heirarchical list of the tasks'''
result = []
tuples = heirarchical_helper(shovel, prefix)
if not tuples:
return ''
# We need to figure out the longest fullname length
longest = max(len(name + ' ' * level) for name, _, level in tuples)
fmt = '%%%is => %%-50s' % longest
for name, docstring, level in tuples:
if docstring == None:
result.append(' ' * level + name + '/')
else:
docstring = re.sub(r'\s+', ' ', docstring).strip()
if len(docstring) > 50:
docstring = docstring[:47] + '...'
result.append(fmt % (name, docstring))
return '\n'.join(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 shovel_help(shovel, *names):
'''Return a string about help with the tasks, or lists tasks available'''
# If names are provided, and the name refers to a group of tasks, print out
# the tasks and a brief docstring. Otherwise, just enumerate all the tasks
# available
if not len(names):
return heirarchical_help(shovel, '')
else:
for name in names:
task = shovel[name]
if isinstance(task, Shovel):
return heirarchical_help(task, name)
else:
return task.help() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load(cls, path, base=None):
'''Either load a path and return a shovel object or return None'''
obj = cls()
obj.read(path, base)
return 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 extend(self, tasks):
'''Add tasks to this particular shovel'''
self._tasks.extend(tasks)
for task in tasks:
# We'll now go through all of our tasks and group them into
# sub-shovels
current = self.map
modules = task.fullname.split('.')
for module in modules[:-1]:
if not isinstance(current[module], Shovel):
logger.warn('Overriding task %s with a module' %
current[module].file)
shovel = Shovel()
shovel.overrides = current[module]
current[module] = shovel
current = current[module].map
# Now we'll put the task in this particular sub-shovel
name = modules[-1]
if name in current:
logger.warn('Overriding %s with %s' % (
'.'.join(modules), task.file))
task.overrides = current[name]
current[name] = 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(self, path, base=None):
'''Import some tasks'''
if base == None:
base = os.getcwd()
absolute = os.path.abspath(path)
if os.path.isfile(absolute):
# Load that particular file
logger.info('Loading %s' % absolute)
self.extend(Task.load(path, base))
elif os.path.isdir(absolute):
# Walk this directory looking for tasks
tasks = []
for root, _, files in os.walk(absolute):
files = [f for f in files if f.endswith('.py')]
for child in files:
absolute = os.path.join(root, child)
logger.info('Loading %s' % absolute)
tasks.extend(Task.load(absolute, base))
self.extend(tasks) |
<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):
'''Return all valid keys'''
keys = []
for key, value in self.map.items():
if isinstance(value, Shovel):
keys.extend([key + '.' + k for k in value.keys()])
else:
keys.append(key)
return sorted(keys) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def items(self):
'''Return a list of tuples of all the keys and tasks'''
pairs = []
for key, value in self.map.items():
if isinstance(value, Shovel):
pairs.extend([(key + '.' + k, v) for k, v in value.items()])
else:
pairs.append((key, value))
return sorted(pairs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tasks(self, name):
'''Get all the tasks that match a name'''
found = self[name]
if isinstance(found, Shovel):
return [v for _, v in found.items()]
return [found] |
<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(cls, obj):
'''Given a callable object, return a new callable object'''
try:
cls._cache.append(Task(obj))
except Exception:
logger.exception('Unable to make task for %s' % repr(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 load(cls, path, base=None):
'''Return a list of the tasks stored in a file'''
base = base or os.getcwd()
absolute = os.path.abspath(path)
parent = os.path.dirname(absolute)
name, _, _ = os.path.basename(absolute).rpartition('.py')
fobj, path, description = imp.find_module(name, [parent])
try:
imp.load_module(name, fobj, path, description)
finally:
if fobj:
fobj.close()
# Manipulate the full names of the tasks to be relative to the provided
# base
relative, _, _ = os.path.relpath(path, base).rpartition('.py')
for task in cls._cache:
parts = relative.split(os.path.sep)
parts.append(task.name)
# If it's either in shovel.py, or folder/__init__.py, then we
# should consider it as being at one level above that file
parts = [part.strip('.') for part in parts if part not in
('shovel', '.shovel', '__init__', '.', '..', '')]
task.fullname = '.'.join(parts)
logger.debug('Found task %s in %s' % (task.fullname, task.module))
return cls.clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def capture(self, *args, **kwargs):
'''Run a task and return a dictionary with stderr, stdout and the
return value. Also, the traceback from the exception if there was
one'''
import traceback
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
stdout, stderr = sys.stdout, sys.stderr
sys.stdout = out = StringIO()
sys.stderr = err = StringIO()
result = {
'exception': None,
'stderr': None,
'stdout': None,
'return': None
}
try:
result['return'] = self.__call__(*args, **kwargs)
except Exception:
result['exception'] = traceback.format_exc()
sys.stdout, sys.stderr = stdout, stderr
result['stderr'] = err.getvalue()
result['stdout'] = out.getvalue()
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 dry(self, *args, **kwargs):
'''Perform a dry-run of the task'''
return 'Would have executed:\n%s%s' % (
self.name, Args(self.spec).explain(*args, **kwargs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def help(self):
'''Return the help string of the task'''
# This returns a help string for a given task of the form:
#
# ==================================================
# <name>
# ============================== (If supplied)
# <docstring>
# ============================== (If overrides other tasks)
# Overrides <other task file>
# ==============================
# From <file> on <line>
# ==============================
# <name>(Argspec)
result = [
'=' * 50,
self.name
]
# And the doc, if it exists
if self.doc:
result.extend([
'=' * 30,
self.doc
])
override = self.overrides
while override:
if isinstance(override, Shovel):
result.append('Overrides module')
else:
result.append('Overrides %s' % override.file)
override = override.overrides
# Print where we read this function in from
result.extend([
'=' * 30,
'From %s on line %i' % (self.file, self.line),
'=' * 30,
'%s%s' % (self.name, str(Args(self.spec)))
])
return os.linesep.join(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 explain(self, *args, **kwargs):
'''Return a string that describes how these args are interpreted'''
args = self.get(*args, **kwargs)
results = ['%s = %s' % (name, value) for name, value in args.required]
results.extend(['%s = %s (overridden)' % (
name, value) for name, value in args.overridden])
results.extend(['%s = %s (default)' % (
name, value) for name, value in args.defaulted])
if self._varargs:
results.append('%s = %s' % (self._varargs, args.varargs))
if self._kwargs:
results.append('%s = %s' % (self._kwargs, args.kwargs))
return '\n\t'.join(results) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get(self, *args, **kwargs):
'''Evaluate this argspec with the provided arguments'''
# We'll go through all of our required args and make sure they're
# present
required = [arg for arg in self._args if arg not in kwargs]
if len(args) < len(required):
raise TypeError('Missing arguments %s' % required[len(args):])
required = list(zip(required, args))
args = args[len(required):]
# Now we'll look through our defaults, if there are any
defaulted = [(name, default) for name, default in self._defaults
if name not in kwargs]
overridden = list(zip([d[0] for d in defaulted], args))
args = args[len(overridden):]
defaulted = defaulted[len(overridden):]
# And anything left over is in varargs
if args and not self._varargs:
raise TypeError('Too many arguments provided')
return ArgTuple(required, overridden, defaulted, args, kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sumnum(*args):
'''Computes the sum of the provided numbers'''
print('%s = %f' % (' + '.join(args), sum(float(arg) for arg in 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 attributes(name, **kwargs):
'''Prints a name, and all keyword attributes'''
print('%s has attributes:' % name)
for key, value in kwargs.items():
print('\t%s => %s' % (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 render(self, name, value, attrs=None, multi=False, renderer=None):
""" Django <= 1.10 variant. """ |
DJANGO_111_OR_UP = (VERSION[0] == 1 and VERSION[1] >= 11) or (
VERSION[0] >= 2
)
if DJANGO_111_OR_UP:
return super(DynamicRawIDWidget, self).render(
name, value, attrs, renderer=renderer
)
if attrs is None:
attrs = {}
related_url = reverse(
'admin:{0}_{1}_changelist'.format(
self.rel.to._meta.app_label,
self.rel.to._meta.object_name.lower(),
),
current_app=self.admin_site.name,
)
params = self.url_parameters()
if params:
url = u'?' + u'&'.join(
[u'{0}={1}'.format(k, v) for k, v in params.items()]
)
else:
url = u''
if "class" not in attrs:
attrs[
'class'
] = (
'vForeignKeyRawIdAdminField'
) # The JavaScript looks for this hook.
app_name = self.rel.to._meta.app_label.strip()
model_name = self.rel.to._meta.object_name.lower().strip()
hidden_input = super(widgets.ForeignKeyRawIdWidget, self).render(
name, value, attrs
)
extra_context = {
'hidden_input': hidden_input,
'name': name,
'app_name': app_name,
'model_name': model_name,
'related_url': related_url,
'url': url,
}
return render_to_string(
'dynamic_raw_id/admin/widgets/dynamic_raw_id_field.html',
extra_context,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_context(self, name, value, attrs):
""" Django >= 1.11 variant. """ |
context = super(DynamicRawIDWidget, self).get_context(
name, value, attrs
)
model = self.rel.model if VERSION[0] == 2 else self.rel.to
related_url = reverse(
'admin:{0}_{1}_changelist'.format(
model._meta.app_label, model._meta.object_name.lower()
),
current_app=self.admin_site.name,
)
params = self.url_parameters()
if params:
url = u'?' + u'&'.join(
[u'{0}={1}'.format(k, v) for k, v in params.items()]
)
else:
url = u''
if "class" not in attrs:
attrs[
'class'
] = (
'vForeignKeyRawIdAdminField'
) # The JavaScript looks for this hook.
app_name = model._meta.app_label.strip()
model_name = model._meta.object_name.lower().strip()
context.update(
{
'name': name,
'app_name': app_name,
'model_name': model_name,
'related_url': related_url,
'url': url,
}
)
return context |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_form(self, request, rel, admin_site):
"""Return filter form.""" |
return DynamicRawIDFilterForm(
admin_site=admin_site,
rel=rel,
field_name=self.field_path,
data=self.used_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 queryset(self, request, queryset):
"""Filter queryset using params from the form.""" |
if self.form.is_valid():
# get no null params
filter_params = dict(
filter(lambda x: bool(x[1]), self.form.cleaned_data.items())
)
return queryset.filter(**filter_params)
return queryset |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def decorator(cls, candidate, *exp_args, **exp_kwargs):
'''
Decorate a control function in order to conduct an experiment when called.
:param callable candidate: your candidate function
:param iterable exp_args: positional arguments passed to :class:`Experiment`
:param dict exp_kwargs: keyword arguments passed to :class:`Experiment`
Usage::
candidate_func = lambda: True
@Experiment.decorator(candidate_func)
def control_func():
return True
'''
def wrapper(control):
@wraps(control)
def inner(*args, **kwargs):
experiment = cls(*exp_args, **exp_kwargs)
experiment.control(control, args=args, kwargs=kwargs)
experiment.candidate(candidate, args=args, kwargs=kwargs)
return experiment.conduct()
return inner
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def candidate(self, cand_func, args=None, kwargs=None, name='Candidate', context=None):
'''
Adds a candidate function to an experiment. Can be used multiple times for
multiple candidates.
:param callable cand_func: your control function
:param iterable args: positional arguments to pass to your function
:param dict kwargs: keyword arguments to pass to your function
:param string name: a name for your observation
:param dict context: observation-specific context
'''
self._candidates.append({
'func': cand_func,
'args': args or [],
'kwargs': kwargs or {},
'name': name,
'context': context or {},
}) |
<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(data):
'''
bytes -> str
'''
if riemann.network.CASHADDR_PREFIX is None:
raise ValueError('Network {} does not support cashaddresses.'
.format(riemann.get_current_network_name()))
data = convertbits(data, 8, 5)
checksum = calculate_checksum(riemann.network.CASHADDR_PREFIX, data)
payload = b32encode(data + checksum)
form = '{prefix}:{payload}'
return form.format(
prefix=riemann.network.CASHADDR_PREFIX,
payload=payload) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def decode(data):
'''
str -> bytes
'''
if riemann.network.CASHADDR_PREFIX is None:
raise ValueError('Network {} does not support cashaddresses.'
.format(riemann.get_current_network_name()))
if data.find(riemann.network.CASHADDR_PREFIX) != 0:
raise ValueError('Malformed cashaddr. Cannot locate prefix: {}'
.format(riemann.netowrk.CASHADDR_PREFIX))
# the data is everything after the colon
prefix, data = data.split(':')
decoded = b32decode(data)
if not verify_checksum(prefix, decoded):
raise ValueError('Bad cash address checksum')
converted = convertbits(decoded, 5, 8)
return bytes(converted[:-6]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def copy(self, outpoint=None, stack_script=None,
redeem_script=None, sequence=None):
'''
TxIn -> TxIn
'''
return TxIn(
outpoint=outpoint if outpoint is not None else self.outpoint,
stack_script=(stack_script if stack_script is not None
else self.stack_script),
redeem_script=(redeem_script if redeem_script is not None
else self.redeem_script),
sequence=sequence if sequence is not None else self.sequence) |
<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_bytes(TxIn, byte_string):
'''
byte_string -> TxIn
parses a TxIn from a byte-like object
'''
outpoint = Outpoint.from_bytes(byte_string[:36])
script_sig_len = VarInt.from_bytes(byte_string[36:45])
script_start = 36 + len(script_sig_len)
script_end = script_start + script_sig_len.number
script_sig = byte_string[script_start:script_end]
sequence = byte_string[script_end:script_end + 4]
if script_sig == b'':
stack_script = b''
redeem_script = b''
else:
stack_script, redeem_script = TxIn._parse_script_sig(script_sig)
return TxIn(
outpoint=outpoint,
stack_script=stack_script,
redeem_script=redeem_script,
sequence=sequence) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def no_witness(self):
'''
Tx -> bytes
'''
tx = bytes()
tx += self.version
tx += VarInt(len(self.tx_ins)).to_bytes()
for tx_in in self.tx_ins:
tx += tx_in.to_bytes()
tx += VarInt(len(self.tx_outs)).to_bytes()
for tx_out in self.tx_outs:
tx += tx_out.to_bytes()
tx += self.lock_time
return bytes(tx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _hash_sequence(self, sighash_type, anyone_can_pay):
'''BIP143 hashSequence implementation
Args:
sighash_type (int): SIGHASH_SINGLE or SIGHASH_ALL
anyone_can_pay (bool): true if ANYONECANPAY should be set
Returns:
(bytes): the hashSequence, a 32 byte hash
'''
if anyone_can_pay or sighash_type == shared.SIGHASH_SINGLE:
# If any of ANYONECANPAY, SINGLE sighash type is set,
# hashSequence is a uint256 of 0x0000......0000.
return b'\x00' * 32
else:
# hashSequence is the double SHA256 of nSequence of all inputs;
sequences = ByteData()
for tx_in in self.tx_ins:
sequences += tx_in.sequence
return utils.hash256(sequences.to_bytes()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _adjusted_script_code(self, script):
'''
Checks if the script code pased in to the sighash function is already
length-prepended
This will break if there's a redeem script that's just a pushdata
That won't happen in practice
Args:
script (bytes): the spend script
Returns:
(bytes): the length-prepended script (if necessary)
'''
script_code = ByteData()
if script[0] == len(script) - 1:
return script
script_code += VarInt(len(script))
script_code += script
return script_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 _hash_outputs(self, index, sighash_type):
'''BIP143 hashOutputs implementation
Args:
index (int): index of input being signed
sighash_type (int): SIGHASH_SINGLE or SIGHASH_ALL
Returns:
(bytes): the hashOutputs, a 32 byte hash
'''
if sighash_type == shared.SIGHASH_ALL:
# If the sighash type is ALL,
# hashOutputs is the double SHA256 of all output amounts
# paired up with their scriptPubKey;
outputs = ByteData()
for tx_out in self.tx_outs:
outputs += tx_out.to_bytes()
return utils.hash256(outputs.to_bytes())
elif (sighash_type == shared.SIGHASH_SINGLE
and index < len(self.tx_outs)):
# if sighash type is SINGLE
# and the input index is smaller than the number of outputs,
# hashOutputs is the double SHA256 of the output at the same index
return utils.hash256(self.tx_outs[index].to_bytes())
else:
# Otherwise, hashOutputs is a uint256 of 0x0000......0000
raise NotImplementedError(
'I refuse to implement the SIGHASH_SINGLE bug.') |
<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(serialized_script):
'''
bytearray -> str
'''
deserialized = []
i = 0
while i < len(serialized_script):
current_byte = serialized_script[i]
if current_byte == 0xab:
raise NotImplementedError('OP_CODESEPARATOR is a bad idea.')
if current_byte <= 75 and current_byte != 0:
deserialized.append(
serialized_script[i + 1: i + 1 + current_byte].hex())
i += 1 + current_byte
if i > len(serialized_script):
raise IndexError(
'Push {} caused out of bounds exception.'
.format(current_byte))
elif current_byte == 76:
# next hex blob length
blob_len = serialized_script[i + 1]
deserialized.append(
serialized_script[i + 2: i + 2 + blob_len].hex())
i += 2 + blob_len
elif current_byte == 77:
# next hex blob length
blob_len = utils.le2i(serialized_script[i + 1: i + 3])
deserialized.append(
serialized_script[i + 3: i + 3 + blob_len].hex())
i += 3 + blob_len
elif current_byte == 78:
raise NotImplementedError('OP_PUSHDATA4 is a bad idea.')
else:
if current_byte in riemann.network.INT_TO_CODE_OVERWRITE:
deserialized.append(
riemann.network.INT_TO_CODE_OVERWRITE[current_byte])
elif current_byte in INT_TO_CODE:
deserialized.append(INT_TO_CODE[current_byte])
else:
raise ValueError(
'Unsupported opcode. '
'Got 0x%x' % serialized_script[i])
i += 1
return ' '.join(deserialized) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _hsig_input(self, index):
'''
inputs for the hsig hash
'''
hsig_input = z.ZcashByteData()
hsig_input += self.tx_joinsplits[index].random_seed
hsig_input += self.tx_joinsplits[index].nullifiers
hsig_input += self.joinsplit_pubkey
return hsig_input.to_bytes() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _primary_input(self, index):
'''
Primary input for the zkproof
'''
primary_input = z.ZcashByteData()
primary_input += self.tx_joinsplits[index].anchor
primary_input += self.tx_joinsplits[index].nullifiers
primary_input += self.tx_joinsplits[index].commitments
primary_input += self.tx_joinsplits[index].vpub_old
primary_input += self.tx_joinsplits[index].vpub_new
primary_input += self.hsigs[index]
primary_input += self.tx_joinsplits[index].vmacs
return primary_input.to_bytes() |
<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_bytes(SproutTx, byte_string):
'''
byte-like -> SproutTx
'''
version = byte_string[0:4]
tx_ins = []
tx_ins_num = shared.VarInt.from_bytes(byte_string[4:])
current = 4 + len(tx_ins_num)
for _ in range(tx_ins_num.number):
tx_in = TxIn.from_bytes(byte_string[current:])
current += len(tx_in)
tx_ins.append(tx_in)
tx_outs = []
tx_outs_num = shared.VarInt.from_bytes(byte_string[current:])
current += len(tx_outs_num)
for _ in range(tx_outs_num.number):
tx_out = TxOut.from_bytes(byte_string[current:])
current += len(tx_out)
tx_outs.append(tx_out)
lock_time = byte_string[current:current + 4]
current += 4
tx_joinsplits = None
joinsplit_pubkey = None
joinsplit_sig = None
if utils.le2i(version) == 2: # If we expect joinsplits
tx_joinsplits = []
tx_joinsplits_num = shared.VarInt.from_bytes(byte_string[current:])
current += len(tx_joinsplits_num)
for _ in range(tx_joinsplits_num.number):
joinsplit = z.SproutJoinsplit.from_bytes(byte_string[current:])
current += len(joinsplit)
tx_joinsplits.append(joinsplit)
joinsplit_pubkey = byte_string[current:current + 32]
current += 32
joinsplit_sig = byte_string[current:current + 64]
return SproutTx(
version=version,
tx_ins=tx_ins,
tx_outs=tx_outs,
lock_time=lock_time,
tx_joinsplits=tx_joinsplits,
joinsplit_pubkey=joinsplit_pubkey,
joinsplit_sig=joinsplit_sig) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def copy(self, version=None, tx_ins=None, tx_outs=None, lock_time=None,
tx_joinsplits=None, joinsplit_pubkey=None, joinsplit_sig=None):
'''
SproutTx, ... -> Tx
Makes a copy. Allows over-writing specific pieces.
'''
return SproutTx(
version=version if version is not None else self.version,
tx_ins=tx_ins if tx_ins is not None else self.tx_ins,
tx_outs=tx_outs if tx_outs is not None else self.tx_outs,
lock_time=(lock_time if lock_time is not None
else self.lock_time),
tx_joinsplits=(tx_joinsplits if tx_joinsplits is not None
else self.tx_joinsplits),
joinsplit_pubkey=(joinsplit_pubkey if joinsplit_pubkey is not None
else self.joinsplit_pubkey),
joinsplit_sig=(joinsplit_sig if joinsplit_sig is not None
else self.joinsplit_sig)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.