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 load_corpus(self, path, config):
'''Load a dialogue corpus; eventually, support pickles and potentially other formats'''
# use the default dataset if no path is provided
# TODO -- change this to use a pre-saved dataset
if path == '':
path = self.default_path_to_corpus
self.data = Corpus(path=path, config=self.data_config) |
<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_dataset_prepare_args(self, parser):
'''Only invoked conditionally if subcommand is 'prepare' '''
parser.add_argument('-f', '--configuration', dest='config', default=DEFAULT_USER_CONFIG_PATH,
help='the path to the configuration file to use -- ./config.yaml by default')
parser.add_argument('-c', '--corpus-name', help='the name of the corpus to process')
parser.add_argument('-n', '--dataset-name', help='the name to assign the newly processed dataset') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def executeBatch(cursor, sql, regex=r"(?mx) ([^';]* (?:'[^']*'[^';]*)*)", comment_regex=r"(?mx) (?:^\s*$)|(?:--.*$)"):
""" Takes a SQL file and executes it as many separate statements. TODO: replace regexes with something easier to grok and extend. """ |
# First, strip comments
sql = "\n".join([x.strip().replace("%", "%%") for x in re.split(comment_regex, sql) if x.strip()])
# Stored procedures don't work with the above regex because many of them are
# made up multiple sql statements each delimited with a single ;
# where the regexes assume each statement delimited by a ; is a complete
# statement to send to mysql and execute.
#
# Here i'm simply checking for the delimiter statements (which seem to be
# mysql-only) and then using them as markers to start accumulating statements.
# So the first delimiter is the signal to start accumulating
# and the second delimiter is the signal to combine them into
# single sql compound statement and send it to mysql.
in_proc = False
statements = []
for st in re.split(regex, sql)[1:][::2]:
if st.strip().lower().startswith("delimiter"):
in_proc = not in_proc
if statements and not in_proc:
procedure = ";".join(statements)
statements = []
cursor.execute(procedure)
# skip the delimiter line
continue
if in_proc:
statements.append(st)
else:
cursor.execute(st) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def howToMigrate(self, fromVersion, toVersion=None):
"""Given a starting version and an ending version returns filenames of all the migrations in that range, exclusive. e.g.: [fromVersion, toVersion) """ |
# slice notation [start:end:step]
# by adding a step of 1 we make a slice from 0:0 be empty
# rather than containing the whole list.
if toVersion is not None:
return self.migrations[fromVersion:toVersion:1]
else:
return self.migrations[fromVersion::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 runSql(self, migrationName, version):
""" Given a migration name and version lookup the sql file and run it. """ |
sys.stdout.write("Running migration %s to version %s: ..."%(migrationName, version))
sqlPath = os.path.join(self.migrationDirectory, migrationName)
sql = open(sqlPath, "r").read()
try:
if self.session.is_active:
print "session is active"
self.session.commit()
self.session.begin()
executeBatch(self.session, sql)
self.session.add(models.Migration(version, migrationName))
except:
print "\n"
self.session.rollback()
raise
else:
self.session.commit()
sys.stdout.write("\r")
sys.stdout.flush()
sys.stdout.write("Running migration %s to version %s: SUCCESS!\n"%(migrationName, version)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_event(self, event):
"""Writes an ``Event`` object to Splunk. :param event: An ``Event`` object. """ |
if not self.header_written:
self._out.write("<stream>")
self.header_written = True
event.write_to(self._out) |
<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(self, severity, message):
"""Logs messages about the state of this modular input to Splunk. These messages will show up in Splunk's internal logs. :param severity: ``string``, severity of message, see severities defined as class constants. :param message: ``string``, message to log. """ |
self._err.write("%s %s\n" % (severity, message))
self._err.flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def TxKazooClient(reactor, pool, client):
"""Create a client for txkazoo. :param twisted.internet.interfaces.IReactorThreads reactor: The reactor used to interact with the thread pool. :param ThreadPool pool: The thread pool to which blocking calls will be deferred. :param kazoo.client.KazooClient client: The blocking Kazoo client, whose blocking methods will be deferred to the thread pool. :return: An object with a similar interface to the Kazoo client, but returning deferreds for all blocking methods. The actual method calls will be executed in the thread pool. """ |
make_thimble = partial(Thimble, reactor, pool)
wrapper = _RunCallbacksInReactorThreadWrapper(reactor, client)
client_thimble = make_thimble(wrapper, _blocking_client_methods)
def _Lock(path, identifier=None):
"""Return a wrapped :class:`kazoo.recipe.lock.Lock` for this client."""
lock = client.Lock(path, identifier)
return Thimble(reactor, pool, lock, _blocking_lock_methods)
client_thimble.Lock = _Lock
client_thimble.SetPartitioner = partial(_SetPartitionerWrapper,
reactor, pool, client)
# Expose these so e.g. recipes can access them from the kzclient
client.reactor = reactor
client.pool = pool
client.kazoo_client = client
return client_thimble |
<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_listener(self, listener):
"""Add the given listener to the wrapped client. The listener will be wrapped, so that it will be called in the reactor thread. This way, it can safely use Twisted APIs. """ |
internal_listener = partial(self._call_in_reactor_thread, listener)
self._internal_listeners[listener] = internal_listener
return self._client.add_listener(internal_listener) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_listener(self, listener):
"""Remove the given listener from the wrapped client. :param listener: A listener previously passed to :meth:`add_listener`. """ |
internal_listener = self._internal_listeners.pop(listener)
return self._client.remove_listener(internal_listener) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wrapped_method_with_watch_fn(self, f, *args, **kwargs):
"""A wrapped method with a watch function. When this method is called, it will call the underlying method with the same arguments, *except* that if the ``watch`` argument isn't :data:`None`, it will be replaced with a wrapper around that watch function, so that the watch function will be called in the reactor thread. This means that the watch function can safely use Twisted APIs. """ |
bound_args = signature(f).bind(*args, **kwargs)
orig_watch = bound_args.arguments.get("watch")
if orig_watch is not None:
wrapped_watch = partial(self._call_in_reactor_thread, orig_watch)
wrapped_watch = wraps(orig_watch)(wrapped_watch)
bound_args.arguments["watch"] = wrapped_watch
return f(**bound_args.arguments) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _call_in_reactor_thread(self, f, *args, **kwargs):
"""Call the given function with args in the reactor thread.""" |
self._reactor.callFromThread(f, *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 converse(self):
'''The 'converse' subcommand'''
# Initialize the converse subcommand's argparser
parser = argparse.ArgumentParser(description='Initiate a conversation with a trained dialogue model')
self.init_converse_args(parser)
# Parse the args we got
args = parser.parse_args(sys.argv[2:])
args.config = ConfigurationLoader(args.config).load().conversation_config
print(CLI_DIVIDER + '\n')
Conversant(**vars(args)).run() |
<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_converse_args(self, parser):
'''Only invoked conditionally if subcommand is 'converse' '''
parser.add_argument('-f', '--configuration', dest='config', default=DEFAULT_USER_CONFIG_PATH,
help='the path to the configuration file to use -- ./config.yaml by default')
parser.add_argument('-m', '--model', dest='model_name', help='the name of the (pretrained) dialogue model to use') |
<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_next_timestep(self, ts=None):
"""copy next frame into timestep""" |
if self.ts.frame >= self.n_frames-1:
raise IOError(errno.EIO, 'trying to go over trajectory limit')
if ts is None:
ts = self.ts
ts.frame += 1
self.zdock_inst._set_pose_num(ts.frame+1)
ts._pos = self.zdock_inst.static_mobile_copy_uni.trajectory.ts._pos
return ts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def viterbi_alignment(es, fs, t, a):
'''
return
dictionary
e in es -> f in fs
'''
max_a = collections.defaultdict(float)
l_e = len(es)
l_f = len(fs)
for (j, e) in enumerate(es, 1):
current_max = (0, -1)
for (i, f) in enumerate(fs, 1):
val = t[(e, f)] * a[(i, j, l_e, l_f)]
# select the first one among the maximum candidates
if current_max[1] < val:
current_max = (i, val)
max_a[j] = current_max[0]
return max_a |
<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_marker_token(self, type_):
"""Make a token that has no content""" |
tok = Token(type_,
'',
self.line,
self.line_num,
self.start,
self.start)
return tok |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_nullable_map(value):
""" Converts JSON string into map object or returns null when conversion is not possible. :param value: the JSON string to convert. :return: Map object value or null when conversion is not supported. """ |
if value == None:
return None
# Parse JSON
try:
value = json.loads(value)
return RecursiveMapConverter.to_nullable_map(value)
except:
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 to_map_with_default(value, default_value):
""" Converts JSON string into map object or returns default value when conversion is not possible. :param value: the JSON string to convert. :param default_value: the default value. :return: Map object value or default when conversion is not supported. """ |
result = JsonConverter.to_nullable_map(value)
return result if result != None else default_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 generate_project(self):
""" Generate the whole project. Returns True if at least one file has been generated, False otherwise.""" |
# checks needed properties
if not self.name or not self.destdir or \
not os.path.isdir(self.destdir):
raise ValueError("Empty or invalid property values: run with 'help' command")
_log("Generating project '%s'" % self.name)
_log("Destination directory is: '%s'" % self.destdir)
top = os.path.join(self.destdir, self.name)
src = os.path.join(top, self.src_name)
resources = os.path.join(top, self.res_name)
utils = os.path.join(src, "utils")
if self.complex:
models = os.path.join(src, "models")
ctrls = os.path.join(src, "ctrls")
views = os.path.join(src, "views")
else: models = ctrls = views = src
res = self.__generate_tree(top, src, resources, models, ctrls, views, utils)
res = self.__generate_classes(models, ctrls, views) or res
res = self.__mksrc(os.path.join(utils, "globals.py"), templates.glob) or res
if self.complex: self.templ.update({'model_import' : "from models.application import ApplModel",
'ctrl_import' : "from ctrls.application import ApplCtrl",
'view_import' : "from views.application import ApplView"})
else: self.templ.update({'model_import' : "from ApplModel import ApplModel",
'ctrl_import' : "from ApplCtrl import ApplCtrl",
'view_import' : "from ApplView import ApplView"})
res = self.__mksrc(os.path.join(top, "%s.py" % self.name), templates.main) or res
# builder file
if self.builder:
res = self.__generate_builder(resources) or res
if self.dist_gtkmvc3: res = self.__copy_framework(os.path.join(resources, "external")) or res
if not res: _log("No actions were taken")
else: _log("Done")
return res |
<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_tree(self, top, src, resources, models, ctrls, views, utils):
"""Creates directories and packages""" |
res = self.__mkdir(top)
for fn in (src, models, ctrls, views, utils): res = self.__mkpkg(fn) or res
res = self.__mkdir(resources) or res
res = self.__mkdir(os.path.join(resources, "ui", "builder")) or res
res = self.__mkdir(os.path.join(resources, "ui", "styles")) or res
res = self.__mkdir(os.path.join(resources, "external")) or res
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scp_put(self, src, dst):
"""Copy src file from local system to dst on remote system.""" |
cmd = [ 'scp',
'-B',
'-oStrictHostKeyChecking=no',
'-oUserKnownHostsFile=/dev/null',
'-oLogLevel=ERROR']
if self._key is not None:
cmd.extend(['-i', self._key])
cmd.append(src)
remote = ''
if self._user is not None:
remote += self._user + '@'
remote += self._ip + ':' + dst
cmd.append(remote)
try:
# Actually ignore output on success, but capture stderr on failure
subprocess.check_output(cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as ex:
raise RuntimeError('scp returned exit status %d:\n%s'
% (ex.returncode, ex.output.strip())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_group_by_id(self, group_id: str) -> typing.Optional['Group']: """ Gets a group by id Args: group_id: group id Returns: Group """ |
VALID_POSITIVE_INT.validate(group_id, 'get_group_by_id', exc=ValueError)
for group in self.groups:
if group.group_id == group_id:
return group
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_clients_groups(self) -> typing.Iterator['Group']: """ Gets all clients groups Returns: generator of Groups """ |
for group in self.groups:
if group.group_is_client_group:
yield group |
<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_group_by_name(self, group_name: str) -> typing.Optional['Group']: """ Gets a group from its name Args: group_name: Returns: Group """ |
VALID_STR.validate(group_name, 'get_group_by_name')
for group in self.groups:
if group.group_name == group_name:
return group
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_unit_by_name(self, unit_name: str) -> typing.Optional['BaseUnit']: """ Gets a unit from its name Args: unit_name: unit name Returns: """ |
VALID_STR.validate(unit_name, 'get_unit_by_name')
for unit in self.units:
if unit.unit_name == unit_name:
return unit
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_unit_by_id(self, unit_id: str) -> typing.Optional['BaseUnit']: """ Gets a unit from its ID Args: unit_id: unit id Returns: Unit """ |
VALID_POSITIVE_INT.validate(unit_id, 'get_unit_by_id')
for unit in self.units:
if unit.unit_id == unit_id:
return unit
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 units(self) -> typing.Iterator['BaseUnit']: """ Iterates over all units Returns: generator of Unit """ |
for group in self.groups:
for unit in group.units:
yield unit |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups(self) -> typing.Iterator['Group']: """ Iterates over all groups Returns: generator of Group """ |
for country in self.countries:
for group in country.groups:
yield group |
<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_country_by_name(self, country_name) -> 'Country': """ Gets a country in this coalition by its name Args: country_name: country name Returns: Country """ |
VALID_STR.validate(country_name, 'get_country_by_name', exc=ValueError)
if country_name not in self._countries_by_name.keys():
for country in self.countries:
if country.country_name == country_name:
return country
raise ValueError(country_name)
else:
return self._countries_by_name[country_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 get_country_by_id(self, country_id) -> 'Country': """ Gets a country in this coalition by its ID Args: country_id: country Id Returns: Country """ |
VALID_POSITIVE_INT.validate(country_id, 'get_country_by_id', exc=ValueError)
if country_id not in self._countries_by_id.keys():
for country in self.countries:
if country.country_id == country_id:
return country
raise ValueError(country_id)
else:
return self._countries_by_id[country_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 bundle_dir():
"""Handle resource management within an executable file.""" |
if frozen():
directory = sys._MEIPASS
else:
directory = os.path.dirname(os.path.abspath(stack()[1][1]))
if os.path.exists(directory):
return directory |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_path(relative):
"""Adjust path for executable use in executable file""" |
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, relative)
return os.path.join(relative) |
<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_string(value):
""" Parses colon-separated list of descriptor fields and returns them as a Descriptor. :param value: colon-separated descriptor fields to initialize Descriptor. :return: a newly created Descriptor. """ |
if value == None or len(value) == 0:
return None
tokens = value.split(":")
if len(tokens) != 5:
raise ConfigException(
None, "BAD_DESCRIPTOR", "Descriptor " + str(value) + " is in wrong format"
).with_details("descriptor", value)
return Descriptor(tokens[0].strip(), tokens[1].strip(), tokens[2].strip(), tokens[3].strip(), tokens[4].strip()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self):
""" Fetch a random weighted choice """ |
choice = weighted_choice(self._responses)
# If the choice is a tuple, join the elements into a single mapped string
if isinstance(choice, tuple):
return ''.join(map(str, choice)).strip()
# Otherwise, return the choice itself as a string
return str(choice) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(obj, name, path=None, ext="dat", overwrite=True, silent=False):
""" Dumps the object to disk with given name and extension. Optionally the path can be specified as well. (But nothing stops you from adding path to the name. """ |
if path and os.path.isfile(path):
raise ValueException("Specified path is a file.")
filename = __get_filename(path, name, ext)
if not overwrite and os.path.exists(filename):
if not silent:
raise ValueException("Specified output filename already exists.")
return
with open(filename, "wb") as f:
pickle.dump(obj, 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 load(name, path=None, ext="dat", silent=False):
""" Loads an object from file with given name and extension. Optionally the path can be specified as well. """ |
filename = __get_filename(path, name, ext)
if not os.path.exists(filename):
if not silent:
raise ValueException("Specified input filename doesn't exist.")
return None
with open(filename, "rb") as f:
return pickle.load(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 standard_input():
"""Generator that yields lines from standard input.""" |
with click.get_text_stream("stdin") as stdin:
while stdin.readable():
line = stdin.readline()
if line:
yield line.strip().encode("utf-8") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(out_fmt, input, output):
"""Converts text.""" |
_input = StringIO()
for l in input:
try:
_input.write(str(l))
except TypeError:
_input.write(bytes(l, 'utf-8'))
_input = seria.load(_input)
_out = (_input.dump(out_fmt))
output.write(_out) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def value(self):
''' Data decoded with the specified charset '''
pos = self.file.tell()
self.file.seek(0)
val = self.file.read()
self.file.seek(pos)
return val.decode(self.charset) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _violinplot(dataset, positions=None, vert=True, widths=0.5,
showmeans=False, showextrema=True, showmedians=False,
points=100, bw_method=None, ax=None):
'''Local version of the matplotlib violinplot.'''
if ax is None:
ax = plt.gca()
if positions is None:
positions = np.arange(1, len(dataset)+1)
amp = widths / 2.0
result = dict(bodies=[], means=[], mins=[], maxes=[], bars=[], medians=[])
for pos, d in zip(positions, dataset):
result['bodies'].append(_violin(d, pos, amp, ax=ax))
x0 = pos - amp/2.
x1 = pos + amp/2.
d_min, d_max = np.min(d), np.max(d)
result['bars'].append(ax.vlines(pos, d_min, d_max))
if showmedians:
m1 = np.median(d)
result['medians'].append(ax.plot([x0,x1], [m1,m1], 'k-'))
if showmeans:
m1 = np.mean(d)
result['means'].append(ax.plot([x0,x1], [m1,m1], 'k-'))
if showextrema:
result['mins'].append(ax.plot([x0,x1], [d_min,d_min], 'k-'))
result['maxes'].append(ax.plot([x0,x1], [d_max,d_max], 'k-'))
ax.set_xticks(positions)
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 dir(suffix='', prefix='tmp', dir=None, force=True):
"""Create a temporary directory. A contextmanager that creates and returns a temporary directory, cleaning it up on exit. The force option specifies whether or not the directory is removed recursively. If set to `False` (the default is `True`), only an empty temporary directory will be removed. This is helpful to create temporary directories for things like mountpoints; otherwise a failing unmount would result in all files on the mounted volume to be deleted. :param suffix: Passed on to :func:`tempfile.mkdtemp`. :param prefix: Passed on to :func:`tempfile.mkdtemp`. :param dir: Passed on to :func:`tempfile.mkdtemp`. :param force: If true, recursively removes directory, otherwise just removes if empty. If directory isn't empty and `force` is `False`, :class:`OSError` is raised. :return: Path to the newly created temporary directory. """ |
name = tempfile.mkdtemp(suffix, prefix, dir)
try:
yield name
finally:
try:
if force:
shutil.rmtree(name)
else:
os.rmdir(name)
except OSError as e:
if e.errno != 2: # not found
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 file(mode='w+b', suffix='', prefix='tmp', dir=None, ignore_missing=False):
"""Create a temporary file. A contextmanager that creates and returns a named temporary file and removes it on exit. Differs from temporary file functions in :mod:`tempfile` by not deleting the file once it is closed, making it safe to write and close the file and then processing it with an external program. If the temporary file is moved elsewhere later on, `ignore_missing` should be set to `True`. :param mode: Passed on to :func:`tempfile.NamedTemporaryFile`. :param suffix: Passed on to :func:`tempfile.NamedTemporaryFile`. :param prefix: Passed on to :func:`tempfile.NamedTemporaryFile`. :param dir: Passed on to :func:`tempfile.NamedTemporaryFile`. :param ignore_missing: If set to `True`, no exception will be raised if the temporary file has been deleted when trying to clean it up. :return: A file object with a `.name`. """ |
# note: bufsize is not supported in Python3, try to prevent problems
# stemming from incorrect api usage
if isinstance(suffix, int):
raise ValueError('Passed an integer as suffix. Did you want to '
'specify the deprecated parameter `bufsize`?')
fp = tempfile.NamedTemporaryFile(mode=mode,
suffix=suffix,
prefix=prefix,
dir=dir,
delete=False)
try:
yield fp
finally:
try:
os.unlink(fp.name)
except OSError as e:
# if the file does not exist anymore, ignore
if e.errno != ENOENT or ignore_missing is False:
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 unix_socket(sock=None, socket_name='tmp.socket', close=True):
"""Create temporary unix socket. Creates and binds a temporary unix socket that will be closed and removed on exit. :param sock: If not `None`, will not created a new unix socket, but bind the passed in one instead. :param socket_name: The name for the socket file (will be placed in a temporary directory). Do not pass in an absolute path! :param close: If `False`, does not close the socket before removing the temporary directory. :return: A tuple of `(socket, addr)`, where `addr` is the location of the bound socket on the filesystem. """ |
sock = sock or socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
with dir() as dtmp:
addr = os.path.join(dtmp, socket_name)
sock.bind(addr)
try:
yield sock, addr
finally:
if close:
sock.close() |
<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_config(self, path):
'''Load a configuration file; eventually, support dicts, .yaml, .csv, etc.'''
# if no path was provided, resort to defaults
if path == None:
print("Path to config was null; using defaults.")
return
if not os.path.exists(path):
print("[No user config file found at default location; using defaults.]\n")
return
user_config = None
# read in the user's configuration file (for now, we hope it's yaml)
with open(path) as f:
user_config = f.read()
# load the user's configuration file into a Config object
extension = os.path.splitext(path)
if extension == 'yaml':
user_config = yaml.load(user_config)
else:
raise Error('Configuration file type "{}" not supported'.format(extension))
# copy the user's preferences into the default configurations
self.merge_config(user_config)
# build the udpated configuration
self.configuration = Configuration(self.data_config, self.model_config, self.conversation_config) |
<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_config(self, user_config):
'''
Take a dictionary of user preferences and use them to update the default
data, model, and conversation configurations.
'''
# provisioanlly update the default configurations with the user preferences
temp_data_config = copy.deepcopy(self.data_config).update(user_config)
temp_model_config = copy.deepcopy(self.model_config).update(user_config)
temp_conversation_config = copy.deepcopy(self.conversation_config).update(user_config)
# if the new configurations validate, apply them
if validate_data_config(temp_data_config):
self.data_config = temp_data_config
if validate_model_config(temp_model_config):
self.model_config = temp_model_config
if validate_conversation_config(temp_conversation_config):
self.conversation_config = temp_conversation_config |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def which(program):
""" A python implementation of which. https://stackoverflow.com/a/2969007 """ |
path_ext = [""]
ext_list = None
if sys.platform == "win32":
ext_list = [ext.lower() for ext in os.environ["PATHEXT"].split(";")]
def is_exe(fpath):
exe = os.path.isfile(fpath) and os.access(fpath, os.X_OK)
# search for executable under windows
if not exe:
if ext_list:
for ext in ext_list:
exe_path = f"{fpath}{ext}"
if os.path.isfile(exe_path) and os.access(exe_path, os.X_OK):
path_ext[0] = ext
return True
return False
return exe
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return f"{program}{path_ext[0]}"
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return f"{exe_file}{path_ext[0]}"
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 migrate(module=None):
""" Entrypoint to migrate the schema. For the moment only create tables. """ |
if not module:
#Parsing
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--service', type=str, help='Migrate the module', required=True,
dest='module')
args = parser.parse_args()
module = args.module
#1. Load settings
farine.settings.load()
#2. Load the module
models = farine.discovery.import_models(module)
#3. Get the connection
db = farine.connectors.sql.setup(getattr(farine.settings, module))
#4. Create tables
for model in models:
model._meta.database = db
model.create_table(fail_silently=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 execute(options):
"""execute the tool with given options.""" |
# Load the key in PKCS 12 format that you downloaded from the Google APIs
# Console when you created your Service account.
package_name = options['<package>']
source_directory = options['<output_dir>']
if options['upload'] is True:
upstream = True
else:
upstream = False
sub_tasks = {'images': options['--images'], 'listings': options['--listings'], 'inapp': options['--inapp']}
if sub_tasks == {'images': False, 'listings': False, 'inapp': False}:
sub_tasks = {'images': True, 'listings': True, 'inapp': True}
credentials = create_credentials(credentials_file=options['--credentials'],
service_email=options['--service-email'],
service_key=options['--key'])
command = SyncCommand(
package_name, source_directory, upstream, credentials, **sub_tasks)
command.execute() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_credentials(credentials_file=None, service_email=None, service_key=None, scope='https://www.googleapis.com/auth/androidpublisher'):
""" Create Google credentials object. If given credentials_file is None, try to retrieve file path from environment or look up file in homefolder. """ |
credentials = None
if service_email is None and service_key is None:
print(credentials_file)
if credentials_file is None:
# try load file from env
key = 'PLAY_DELIVER_CREDENTIALS'
if key in os.environ:
credentials_file = os.environ[key]
if credentials_file is None:
# try to find the file in home
path = os.path.expanduser('~/.playdeliver/credentials.json')
if os.path.exists(path):
credentials_file = path
if credentials_file is not None:
credentials = client.GoogleCredentials.from_stream(
credentials_file)
credentials = credentials.create_scoped(scope)
else:
sys.exit("no credentials")
else:
credentials = client.SignedJwtAssertionCredentials(
service_email, _load_key(service_key), scope=scope)
return 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 good_classmethod_decorator(decorator):
"""This decorator makes class method decorators behave well wrt to decorated class method names, doc, etc.""" |
def new_decorator(cls, f):
g = decorator(cls, f)
g.__name__ = f.__name__
g.__doc__ = f.__doc__
g.__dict__.update(f.__dict__)
return g
new_decorator.__name__ = decorator.__name__
new_decorator.__doc__ = decorator.__doc__
new_decorator.__dict__.update(decorator.__dict__)
return new_decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_descriptor_le(self, lineedit, tf):
"""Update the given line edit to show the descriptor that is stored in the index :param lineedit: the line edit to update with the descriptor :type lineedit: QLineEdit :param tf: the selected taskfileinfo :type tf: :class:`TaskFileInfo` | None :returns: None :rtype: None :raises: None """ |
if tf:
descriptor = tf.descriptor
lineedit.setText(descriptor)
else:
lineedit.setText("") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _save_tfi(self, tfi, asset=False):
"""Save currently open scene with the information in the given taskfile info :param tfi: taskfile info :type tfi: :class:`TaskFileInfo` :returns: None :rtype: None :raises: None """ |
jbfile = JB_File(tfi)
self.create_dir(jbfile)
tf, note = self.create_db_entry(tfi)
try:
js = JukeboxSignals.get()
if asset:
js.before_save_asset.emit(jbfile, tf)
self.save_asset(jbfile, tf)
js.after_save_asset.emit(jbfile, tf)
else:
js.before_save_shot.emit(jbfile, tf)
self.save_shot(jbfile, tf)
js.after_save_shot.emit(jbfile, tf)
except:
tf.delete()
note.delete()
self.statusbar.showMessage('Saving failed!')
log.exception("Saving failed!")
return
self.browser.update_model(tfi) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_dir(self, jbfile):
"""Create a dir for the given dirfile and display an error message, if it fails. :param jbfile: the jb file to make the directory for :type jbfile: class:`JB_File` :returns: None :rtype: None :raises: None """ |
try:
jbfile.create_directory()
except os.error:
self.statusbar.showMessage('Could not create path: %s' % jbfile.get_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 check_selection_for_save(self, task, releasetype, descriptor):
"""Emit warnings if the descriptor is None or the current file is of a different task. :param task: the selected task :type task: :class:`djadapter.models.Task` :param releasetype: the releasetype to save (probably work) :type releasetype: str :param descriptor: the descriptor :type descriptor: str :returns: True if check was successfull. :rtype: bool :raises: None """ |
if not descriptor:
self.statusbar.showMessage("Please provide a descriptor!")
return False
try:
jukedj.validators.alphanum_vld(descriptor)
except ValidationError:
self.statusbar.showMessage("Descriptor contains characters other than alphanumerical ones.")
return False
cur = self.get_current_file()
if cur and task != cur.task:
self.statusbar.showMessage("Task is different. Not supported atm!")
return False
elif cur and releasetype != cur.releasetype:
self.statusbar.showMessage("Releasetype is different. Not supported atm!")
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 create_db_entry(self, tfi):
"""Create a db entry for the given task file info :param tfi: the info for a TaskFile entry in the db :type tfi: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: the created taskfile and note :rtype: tuple :raises: ValidationError """ |
if tfi.task.department.assetflag:
comment = self.asset_comment_pte.toPlainText()
else:
comment = self.shot_comment_pte.toPlainText()
return tfi.create_db_entry(comment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def closeEvent(self, event):
"""Send last file signal on close event :param event: The close event :type event: :returns: None :rtype: None :raises: None """ |
lf = self.browser.get_current_selection()
if lf:
self.last_file.emit(lf)
return super(GenesisWin, self).close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(client, source_dir):
"""Upload listing files in source_dir. folder herachy.""" |
print('')
print('upload store listings')
print('---------------------')
listings_folder = os.path.join(source_dir, 'listings')
langfolders = filter(os.path.isdir, list_dir_abspath(listings_folder))
for language_dir in langfolders:
language = os.path.basename(language_dir)
with open(os.path.join(language_dir, 'listing.json')) as listings_file:
listing = json.load(listings_file)
listing_response = client.update(
'listings', language=language, body=listing)
print(' Listing for language %s was updated.' %
listing_response['language']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(client, target_dir):
"""Download listing files from play and saves them into folder herachy.""" |
print('')
print('download store listings')
print('---------------------')
listings = client.list('listings')
for listing in listings:
path = os.path.join(target_dir, 'listings', listing['language'])
mkdir_p(path)
with open(os.path.join(path, 'listing.json'), 'w') as outfile:
print("save listing for {0}".format(listing['language']))
json.dump(
listing, outfile, sort_keys=True,
indent=4, separators=(',', ': ')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def filter(self, **kwargs):
'''Assumes all the dict's items are hashable.
'''
# So we don't return anything more than once.
yielded = set()
dunder = '__'
filter_items = set()
for k, v in kwargs.items():
if dunder in k:
k, op = k.split(dunder)
try:
handler = getattr(self, 'handle__%s' % op)
except AttributeError:
msg = '%s has no %r method to handle operator %r.'
raise NonExistentHandler(msg % (self, handler, op))
for dicty in self:
if handler(k, v, dicty):
dicty_id = id(dicty)
if dicty_id not in yielded:
yield dicty
yielded.add(dicty_id)
else:
filter_items.add((k, v))
for dicty in self:
dicty_items = set(dicty.items())
if filter_items.issubset(dicty_items):
yield dicty |
<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_ssh_keys_to_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False):
""" Copy the SSH keys to the given hosts. :param hosts: the list of `Host` objects to copy the SSH keys to. :param known_hosts: the `known_hosts` file to store the SSH public keys. :param dry: perform a dry run. :raise msshcopyid.errors.CopySSHKeysError: """ |
exceptions = [] # list of `CopySSHKeyError`
for host in hosts:
logger.info('[%s] Copy the SSH public key [%s]...', host.hostname, self.sshcopyid.pub_key)
if not dry:
try:
self.copy_ssh_keys_to_host(host, known_hosts=known_hosts)
except (paramiko.ssh_exception.SSHException, socket.error) as ex:
logger.error(format_error(format_exception(ex)))
logger.debug(traceback.format_exc())
exceptions.append(CopySSHKeyError(host=host, exception=ex))
if exceptions:
raise CopySSHKeysError(exceptions=exceptions) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_fn(self, what, *args, **kwargs):
""" Lazy call init_adapter then call the function """ |
logger.debug('f_{0}:{1}{2}({3})'.format(
self.call_stack_level,
' ' * 4 * self.call_stack_level,
what,
arguments_as_string(args, kwargs)))
port, fn_name = self._what(what)
if port not in self['_initialized_ports']:
self._call_fn(port, 'init_adapter')
self['_initialized_ports'].append(port)
return self._call_fn(port, fn_name, *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 unpack_zipfile(filename):
"""Unpack a zipfile, using the names in the zip.""" |
with open(filename, "rb") as fzip:
z = zipfile.ZipFile(fzip)
for name in z.namelist():
print((" extracting {}".format(name)))
ensure_dirs(name)
z.extract(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 prog_iter(bounded_iterable, delta=0.01, line_size=50):
'''Wraps the provided sequence with an iterator that tracks its progress
on the console.
>>> for i in prog_iter(xrange(100)): pass
..................................................
..................................................
(0.000331163406372 s)
More specifically, the behavior is as follows:
- Produces a progress bar on stdout, at ``delta`` increments, where
``delta`` is a percentage (represented as a float from 0.0 to 1.0)
- Newline every line_size dots (defaults to 50)
- Displays the time the loop took, as in toc() (without interfering with toc)
- A prog_iter nested in another prog_iter will not produce any of these
side effects. That is, only one progress bar will ever be printing at a time.
'''
# TODO: Technically, this should have a __len__.
global _prog_iterin_loop
if not _prog_iterin_loop:
startTime = _time.time()
_prog_iterin_loop = True
length = float(len(bounded_iterable))
_sys.stdout.write(".")
dots = 1
next = delta
for i, item in enumerate(bounded_iterable):
if (i + 1) / length >= next:
next += delta
dots += 1
_sys.stdout.write(".")
if dots % line_size == 0:
_sys.stdout.write("\n")
_sys.stdout.flush()
yield item
print((" (" + str(_time.time() - startTime) + " s)"))
_prog_iterin_loop = False
else:
for item in bounded_iterable:
yield item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def include(gset, elem, value=True):
"""Do whatever it takes to make ``elem in gset`` true. ['Lucy'] set(['Sky']) {'Diamonds': True} Works for sets (using ``add``), lists (using ``append``) and dicts (using ``__setitem__``). ``value`` if ``gset`` is a dict, does ``gset[elem] = value``. Returns ``elem``, or raises an Error if none of these operations are supported. """ |
add = getattr(gset, 'add', None) # sets
if add is None: add = getattr(gset, 'append', None) # lists
if add is not None: add(elem)
else: # dicts
if not hasattr(gset, '__setitem__'):
raise Error("gset is not a supported container.")
gset[elem] = value
return elem |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_all(gset, elem):
"""Removes every occurrence of ``elem`` from ``gset``. Returns the number of times ``elem`` was removed. """ |
n = 0
while True:
try:
remove_once(gset, elem)
n = n + 1
except RemoveError:
return n |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten(iterable, check=is_iterable):
"""Produces a recursively flattened version of ``iterable`` ``check`` Recurses only if check(value) is true. """ |
for value in iterable:
if check(value):
for flat in flatten(value, check):
yield flat
else:
yield 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 xflatten(iterable, transform, check=is_iterable):
"""Apply a transform to iterable before flattening at each level.""" |
for value in transform(iterable):
if check(value):
for flat in xflatten(value, transform, check):
yield flat
else:
yield 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 flatten_once(iterable, check=is_iterable):
"""Flattens only the first level.""" |
for value in iterable:
if check(value):
for item in value:
yield item
else:
yield 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 join(iterable, sep):
"""Like str.join, but yields an iterable.""" |
i = 0
for i, item in enumerate(iterable):
if i == 0:
yield item
else:
yield sep
yield item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop_at(iterable, idx):
"""Stops iterating before yielding the specified idx.""" |
for i, item in enumerate(iterable):
if i == idx: return
yield item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all_pairs(seq1, seq2=None):
"""Yields all pairs drawn from ``seq1`` and ``seq2``. If ``seq2`` is ``None``, ``seq2 = seq1``. ((0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7)) """ |
if seq2 is None: seq2 = seq1
for item1 in seq1:
for item2 in seq2:
yield (item1, item2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def padded_to_same_length(seq1, seq2, item=0):
"""Return a pair of sequences of the same length by padding the shorter sequence with ``item``. The padded sequence is a tuple. The unpadded sequence is returned as-is. """ |
len1, len2 = len(seq1), len(seq2)
if len1 == len2:
return (seq1, seq2)
elif len1 < len2:
return (cons.ed(seq1, yield_n(len2-len1, item)), seq2)
else:
return (seq1, cons.ed(seq2, yield_n(len1-len2, item))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_int_like(value):
"""Returns whether the value can be used as a standard integer. True False False False """ |
try:
if isinstance(value, int): return True
return int(value) == value and str(value).isdigit()
except:
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 is_float_like(value):
"""Returns whether the value acts like a standard float. True True False False """ |
try:
if isinstance(value, float): return True
return float(value) == value and not str(value).isdigit()
except:
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 make_symmetric(dict):
"""Makes the given dictionary symmetric. Values are assumed to be unique.""" |
for key, value in list(dict.items()):
dict[value] = key
return dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fn_kwargs(callable):
"""Returns a dict with the kwargs from the provided function. Example """ |
fn = get_fn(callable)
(args, _, _, defaults) = _inspect.getargspec(fn)
if defaults is None: return { }
return dict(list(zip(reversed(args), reversed(defaults)))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fn_available_argcount(callable):
"""Returns the number of explicit non-keyword arguments that the callable can be called with. Bound methods are called with an implicit first argument, so this takes that into account. Excludes *args and **kwargs declarations. """ |
fn = get_fn_or_method(callable)
if _inspect.isfunction(fn):
return fn.__code__.co_argcount
else: # method
if fn.__self__ is None:
return fn.__func__.__code__.co_argcount
else:
return fn.__func__.__code__.co_argcount - 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 fn_minimum_argcount(callable):
"""Returns the minimum number of arguments that must be provided for the call to succeed.""" |
fn = get_fn(callable)
available_argcount = fn_available_argcount(callable)
try:
return available_argcount - len(fn.__defaults__)
except TypeError:
return available_argcount |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fn_signature(callable, argument_transform=(lambda name: name), default_transform=(lambda name, value: "%s=%s" % (name, repr(value))), vararg_transform=(lambda name: "*" + name), kwargs_transform=(lambda name: "**" + name)):
"""Returns the signature of the provided callable as a tuple of strings.""" |
signature = []
fn = get_fn(callable)
avail_ac = fn_available_argcount(fn)
kwargs = fn_kwargs(fn)
argnames = fn_argnames(fn)
for name in stop_at(argnames, avail_ac):
if name in kwargs:
signature.append(default_transform(name, kwargs[name]))
else:
signature.append(argument_transform(name))
if fn_has_args(fn):
if fn_has_kwargs(fn):
signature.append(vararg_transform(argnames[-2]))
signature.append(kwargs_transform(argnames[-1]))
else:
signature.append(vararg_transform(argnames[-1]))
elif fn_has_kwargs(fn):
signature.append(kwargs_transform(argnames[-1]))
return signature |
<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(d):
"""Creates a proper decorator. If the default for the first (function) argument is None, creates a See examples below. """ |
defaults = d.__defaults__
if defaults and defaults[0] is None:
# Can be applied as @decorator or @decorator(kwargs) because
# first argument is None
def decorate(fn=None, **kwargs):
if fn is None:
return _functools.partial(decorate, **kwargs)
else:
decorated = d(fn, **kwargs)
_functools.update_wrapper(decorated, fn)
return decorated
else:
# Can only be applied as @decorator
def decorate(fn):
decorated = d(fn)
_functools.update_wrapper(decorated, fn)
return decorated
_functools.update_wrapper(decorate, d)
return decorate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def memoize(fn=None):
"""Caches the result of the provided function.""" |
cache = { }
arg_hash_fn = fn_arg_hash_function(fn)
def decorated(*args, **kwargs):
try:
hash_ = arg_hash_fn(*args, **kwargs)
except TypeError:
return fn(*args, **kwargs)
try:
return cache[hash_]
except KeyError:
return_val = fn(*args, **kwargs)
cache[hash_] = return_val
return return_val
_functools.update_wrapper(decorated, fn)
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 safe_setattr(obj, name, value):
"""Attempt to setattr but catch AttributeErrors.""" |
try:
setattr(obj, name, value)
return True
except AttributeError:
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 method_call_if_def(obj, attr_name, m_name, default, *args, **kwargs):
"""Calls the provided method if it is defined. Returns default if not defined. """ |
try:
attr = getattr(obj, attr_name)
except AttributeError:
return default
else:
return getattr(attr, m_name)(*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 call_on_if_def(obj, attr_name, callable, default, *args, **kwargs):
"""Calls the provided callable on the provided attribute of ``obj`` if it is defined. If not, returns default. """ |
try:
attr = getattr(obj, attr_name)
except AttributeError:
return default
else:
return callable(attr, *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 is_senior_subclass(obj, cls, testcls):
"""Determines whether the cls is the senior subclass of basecls for obj. The most senior subclass is the first class in the mro which is a subclass of testcls. Use for inheritance schemes where a method should only be called once by the most senior subclass. Don't use if it is optional to call the base method! In that case, the most reasonable way to do it is to ensure the method is idempotent and deal with the hopefully small inefficiency of calling it multiple times. Doing a hasattr check in these implementations should be relatively efficient. In particular, __init__ for mixins tends to act like this. """ |
for base in obj.__class__.mro():
if base is cls:
return True
else:
if issubclass(base, testcls):
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 string_escape(string, delimiter='"'):
"""Turns special characters into escape sequences in the provided string. Supports both byte strings and unicode strings properly. Any other values will produce None. Example: "a line\\t" u"\\u9999" None """ |
if isinstance(string, str):
escaped = string.encode("string-escape")
elif isinstance(string, str):
escaped = str(string.encode("unicode-escape"))
else:
raise Error("Unexpected string type.")
return delimiter + escape_quotes(escaped, delimiter) + delimiter |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def re_line_and_indentation(base_indentation, modifiers=(True, True)):
"""Returns a re matching newline + base_indentation. modifiers is a tuple, (include_first, include_final). If include_first, matches indentation at the beginning of the string. If include_final, matches indentation at the end of the string. Cached. """ |
cache = re_line_and_indentation.cache[modifiers]
compiled = cache.get(base_indentation, None)
if compiled is None:
[prefix, suffix] = re_line_and_indentation.tuple[modifiers]
compiled = cache[modifiers] = \
_re.compile(prefix + base_indentation + suffix)
return compiled |
<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_base_indentation(code, include_start=False):
"""Heuristically extracts the base indentation from the provided code. Finds the smallest indentation following a newline not at the end of the string. """ |
new_line_indentation = re_new_line_indentation[include_start].finditer(code)
new_line_indentation = tuple(m.groups(0)[0] for m in new_line_indentation)
if new_line_indentation:
return min(new_line_indentation, key=len)
else:
return "" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fix_indentation(code, base_indentation=None, correct_indentation="", modifiers=(True, True)):
"""Replaces base_indentation at beginning of lines with correct_indentation. If base_indentation is None, tries to find it using get_base_indentation. modifiers are passed to re_line_and_indentation. See there for doc. """ |
if base_indentation is None:
base_indentation = get_base_indentation(code, modifiers[0])
return re_line_and_indentation(base_indentation, modifiers).sub(
"\n" + correct_indentation, 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 name(self):
"""The unique name of this object, relative to the parent.""" |
basename = self.basename
if basename is None:
return None
parent = self.Naming_parent
if parent is None:
return basename
else:
return parent.generate_unique_name(basename) |
<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_unique_name(self, basename):
"""Generates a unique name for a child given a base name.""" |
counts = self.__counts
try:
count = counts[basename]
counts[basename] += 1
except KeyError:
count = 0
counts[basename] = 1
prefix = self.Naming_prefix
if count == 0:
name = prefix + basename
else:
name = prefix + basename + "_" + str(count)
if prefix != "" or count != 0:
try:
count = counts[name]
return self.generate_unique_name(name)
except KeyError:
# wasn't already used so return it
counts[name] = 1
return 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 add_to_parent(self):
"""Adds this node to the parent's ``children`` collection if it exists.""" |
parent = self.parent
if parent is not None:
try:
children = parent.children
except AttributeError: pass
else:
include(children, self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_from_parent(self):
"""Removes this node from the parent's ``children`` collection if it exists.""" |
parent = self.parent
if parent is not None:
try:
children = parent.children
except AttributeError: pass
else:
remove_upto_once(children, self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_up(self, include_self=True):
"""Iterates up the tree to the root.""" |
if include_self: yield self
parent = self.parent
while parent is not None:
yield parent
try:
parent = parent.parent
except AttributeError:
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getrec(self, name, include_self=True, *default):
"""Look up an attribute in the path to the root.""" |
for node in self.iter_up(include_self):
try:
return getattr(node, name)
except AttributeError: pass
if default:
return default[0]
else:
raise AttributeError(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 trigger_hook(self, name, *args, **kwargs):
"""Recursively call a method named ``name`` with the provided args and keyword args if defined.""" |
method = getattr(self, name, None)
if is_callable(method):
method(*args, **kwargs)
try:
children = self.children
except AttributeError:
return
else:
if children is not None:
for child in children:
method = getattr(child, 'trigger_hook', None)
if is_callable(method):
method(name, *args, **kwargs)
else:
method = getattr(child, name, None)
if is_callable(method):
method(*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 _spawn_thread(self, target):
""" Create a thread """ |
t = Thread(target=target)
t.daemon = True
t.start()
return t |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join(self):
""" Wait for all current tasks to be finished """ |
self._jobs.join()
try:
return self._results, self._errors
finally:
self._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 call(exe, *argv):
""" Run a command, returning its output, or None if it fails. """ |
exes = which(exe)
if not exes:
returnValue(None)
stdout, stderr, value = yield getProcessOutputAndValue(
exes[0], argv, env=os.environ.copy()
)
if value:
returnValue(None)
returnValue(stdout.decode('utf-8').rstrip('\n')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.