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 _setup_sentry_client(context):
"""Produce and configure the sentry client.""" |
# get_secret will be deprecated soon
dsn = os.environ.get("SENTRY_DSN")
try:
client = raven.Client(dsn, sample_rate=SENTRY_SAMPLE_RATE)
client.user_context(_sentry_context_dict(context))
return client
except:
rlogger.error("Raven client error", exc_info=True)
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_processing_error(err, errstream, client):
"""Handle ProcessingError exceptions.""" |
errors = sorted(err.events, key=operator.attrgetter("index"))
failed = [e.event for e in errors]
silent = all(isinstance(e.error, OutOfOrderError) for e in errors)
if errstream:
_deliver_errored_events(errstream, failed)
must_raise = False
else:
must_raise = True
for _,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _deliver_errored_events(errstream, recs):
"""Deliver errors to error stream.""" |
rlogger.info("Going to handle %s failed events", len(recs))
rlogger.info(
"First failed event: %s", json.dumps(recs[0], indent=4))
kinesis_stream = errstream.get("kinesis_stream")
randomkey = str(uuid.uuid4())
if kinesis_stream:
send_to_kinesis_stream(
recs,
... |
<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_records(event):
"""Get records from an AWS Lambda trigger event.""" |
try:
recs, _ = unpack_kinesis_event(event, deserializer=None)
except KeyError:
# If not a Kinesis event, just unpack the records
recs = event["Records"]
return recs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _search(self, query, fields=None, limit=50000, sampling=None):
""" Perform the search and return raw rows :type query object :type fields list[str] or None :... |
body = {
"query": {
"bool": {
"must": [
query
]
}
}
}
# @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html
if 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 get_rows(self, match, fields=None, limit=10, sampling=None):
""" Returns raw rows that matches given query :arg match: query to be run against Kibana log mes... |
query = {
"match": match,
}
return self._search(query, fields, limit, sampling) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_by_string(self, query, fields=None, limit=10, sampling=None):
""" Returns raw rows that matches the given query string :arg query: query string to be r... |
query = {
"query_string": {
"query": query,
}
}
return self._search(query, fields, limit, sampling) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count(self, query):
""" Returns number of matching entries :type query str :rtype: int """ |
body = {
"query": {
"bool": {
"must": [{
"query_string": {
"query": query,
}
}]
}
}
}
body['query']['bool']['must'].append... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_by_sql(self, sql):
""" Returns entries matching given SQL query :type sql str :rtype: list[dict] """ |
# https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-rest.html
# https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-syntax-select.html
body = {'query': sql}
resp = self._es.transport.perform_request('POST', '/_xpack/sql', params={'format': 'json'}, bod... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract(self, pos, width):
"""Extracts a subword with a given width, starting from a given bit position. """ |
pos = operator.index(pos)
width = operator.index(width)
if width < 0:
raise ValueError('width must not be negative')
if pos < 0:
raise ValueError('extracting out of range')
return BinWord(width, self >> pos, trunc=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 blast_to_cigar(query_seq, match_seq, subject_seq, cigar_age='new'):
"""converts BLAST alignment into a old or new CIGAR line Args: query_seq (str):
Aligned ... |
if not len(query_seq) == len(match_seq) \
or not len(query_seq) == len(subject_seq) \
or not len(subject_seq) == len(match_seq):
raise ValueError('query_seq, match_seq, and subject_seq not same '
'lengths.')
# Translate XML alignment to CIGAR character... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clean_isbn(isbn):
""" Remove all non-digit and non "x" characters from given string. Args: isbn (str):
isbn string, which will be cleaned. Returns: list: a... |
if isinstance(isbn, basestring):
isbn = list(isbn.lower())
# filter digits and "x"
isbn = filter(lambda x: x.isdigit() or x == "x", isbn)
# convert ISBN to numbers
return map(lambda x: 10 if x == "x" else int(x), isbn) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _isbn_cleaner(fn):
""" Decorator for calling other functions from this module. Purpose of this decorator is to clean the ISBN string from garbage and return ... |
@wraps(fn)
def wrapper(isbn):
return fn(_clean_isbn(isbn))
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 application(handler, adapter_cls=WerkzeugAdapter):
"""Converts an anillo function based handler in a wsgi compiliant application function. :param adapter_cls... |
adapter = adapter_cls()
def wrapper(environ, start_response):
request = adapter.to_request(environ)
response = handler(request)
response_func = adapter.from_response(response)
return response_func(environ, start_response)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_async(func):
"""Wraps an asynchronous function into a synchronous function.""" |
@functools.wraps(func)
def wrapped(*args, **kwargs):
fut = asyncio.ensure_future(func(*args, **kwargs))
cur = greenlet.getcurrent()
def callback(fut):
try:
cur.switch(fut.result())
except BaseException as e:
cur.throw(e)
fu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_sync(func):
"""Wraps a synchronous function into an asynchronous function.""" |
@functools.wraps(func)
def wrapped(*args, **kwargs):
fut = asyncio.Future()
def green():
try:
fut.set_result(func(*args, **kwargs))
except BaseException as e:
fut.set_exception(e)
greenlet.greenlet(green).switch()
return fu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Run(self):
""" Wait for clients to connect and service them :returns: None """ |
while True:
try:
events = self.poller.poll()
except KeyboardInterrupt:
self.context.destroy()
sys.exit()
self.Handle_Events(events) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Handle_Receive(self, msg):
""" Handle a received message. :param msg: the received message :type msg: str :returns: The message to reply with :rtype: str """ |
msg = self.Check_Message(msg)
msg_type = msg['type']
f_name = "Handle_{0}".format(msg_type)
try:
f = getattr(self, f_name)
except AttributeError:
f = self.Handle_ERROR(msg)
reply = f(msg)
return reply |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Handle_Search(self, msg):
""" Handle a search. :param msg: the received search :type msg: dict :returns: The message to reply with :rtype: str """ |
search_term = msg['object']['searchTerm']
results = self.db.searchForItem(search_term)
reply = {"status": "OK",
"type": "search",
"object": {
"received search": msg['object']['searchTerm'],
"results": resu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Handle_Note(self, msg):
""" Handle a new note. :param msg: the received note :type msg: dict :returns: The message to reply with :rtype: str """ |
note_text = msg['object']['note']
note_tags = msg['object']['tags']
if 'ID' in msg['object']:
note_id = msg['object']['ID']
self.db.addItem("note", {"note": note_text,
"tags": note_tags},
note_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 after_match(self, func, full_fallback=False):
"""Returns an iterator for all the elements after the first match. If `full_fallback` is `True`, it will return... |
iterator = iter(self)
for item in iterator:
if func(item):
return iterator
if full_fallback:
iterator = iter(self)
return iterator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(correlation_id, components):
""" Clears state of multiple components. To be cleaned state components must implement [[ICleanable]] interface. If they d... |
if components == None:
return
for component in components:
Cleaner.clear_one(correlation_id, component) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_datetime(value):
"""Parses a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output u... |
match = datetime_re.match(value)
if match:
kw = match.groupdict()
if kw['microsecond']:
kw['microsecond'] = kw['microsecond'].ljust(6, '0')
tzinfo = kw.pop('tzinfo')
if tzinfo == 'Z':
tzinfo = utc
elif tzinfo is not None:
offset_mins =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(self):
""" Check if the daemon is currently running. Requires procfs, so it will only work on POSIX compliant OS'. """ |
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
return False
try:
return os.path.exists("/proc/{0}".format(pid))
except OSError:
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 func(self, name: str):
"""return the first func defined named name""" |
for f in self.body:
if (hasattr(f, '_ctype')
and isinstance(f._ctype, FuncType)
and f._name == name):
return 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 type(self, name: str):
"""return the first complete definition of type 'name'""" |
for f in self.body:
if (hasattr(f, '_ctype')
and f._ctype._storage == Storages.TYPEDEF
and f._name == name):
return 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 declallfuncs(self):
"""generator on all declaration of function""" |
for f in self.body:
if (hasattr(f, '_ctype')
and isinstance(f._ctype, FuncType)):
yield 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 declallvars(self):
"""generator on all declaration of variable""" |
for f in self.body:
if (hasattr(f, '_ctype')
and not isinstance(f._ctype, FuncType)):
yield 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 declalltypes(self):
"""generator on all declaration of type""" |
for f in self.body:
if (hasattr(f, '_ctype')
and f._ctype._storage == Storages.TYPEDEF):
yield 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 show_popup(self, *args, **kwargs):
"""Show a popup with a textedit :returns: None :rtype: None :raises: None """ |
self.mw = JB_MainWindow(parent=self, flags=QtCore.Qt.Dialog)
self.mw.setWindowTitle(self.popuptitle)
self.mw.setWindowModality(QtCore.Qt.ApplicationModal)
w = QtGui.QWidget()
self.mw.setCentralWidget(w)
vbox = QtGui.QVBoxLayout(w)
pte = QtGui.QPlainTextEdit()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mount(directory, lower_dir, upper_dir, mount_table=None):
"""Creates a mount""" |
return OverlayFS.mount(directory, lower_dir, upper_dir,
mount_table=mount_table) |
<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_teams(self, teams):
"""Expects an iterable of team IDs""" |
return [LeaderboardInstance(x) for x in self._leaderboard if x['faction']['id'] in teams] |
<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_users(self, users):
"""Expects an interable of User IDs ints""" |
return [LeaderboardInstance(x) for x in self._leaderboard if x['user_id'] in users] |
<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_trainers(self, trainers):
"""Expects an interable of Trainer IDs ints""" |
return [LeaderboardInstance(x) for x in self._leaderboard if x['id'] in trainers] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_path(path, filetype=FILE):
"""Takes a path and a filetype, verifies existence and type, and returns absolute path. """ |
if not path:
raise ValueError('"{0}" is not a valid path.'.format(path))
if not os.path.exists(path):
raise ValueError('"{0}" does not exist.'.format(path))
if filetype == FILE and not os.path.isfile(path):
raise ValueError('"{0}" is not a file.'.format(path))
elif filetype == D... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def err(*output, **kwargs):
"""Writes output to stderr. :arg wrap: If you set ``wrap=False``, then ``err`` won't textwrap the output. """ |
output = 'Error: ' + ' '.join([str(o) for o in output])
if kwargs.get('wrap') is not False:
output = '\n'.join(wrap(output, kwargs.get('indent', '')))
elif kwargs.get('indent'):
indent = kwargs['indent']
output = indent + ('\n' + indent).join(output.splitlines())
sys.stderr.writ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def out(*output, **kwargs):
"""Writes output to stdout. :arg wrap: If you set ``wrap=False``, then ``out`` won't textwrap the output. """ |
output = ' '.join([str(o) for o in output])
if kwargs.get('wrap') is not False:
output = '\n'.join(wrap(output, kwargs.get('indent', '')))
elif kwargs.get('indent'):
indent = kwargs['indent']
output = indent + ('\n' + indent).join(output.splitlines())
sys.stdout.write(output + '... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_rrule(rrule):
"""Converts icalendar rrule to dateutil rrule.""" |
args = {}
# TODO: rrule['freq'] is a list, but I'm unclear as to why.
freq = FREQ_MAP[rrule['freq'][0]]
keys = ['wkst', 'until', 'bysetpos', 'interval',
'bymonth', 'bymonthday', 'byyearday', 'byweekno',
'byhour', 'byminute', 'bysecond']
def tweak(rrule, key):
valu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_ics(icsfile):
"""Takes an icsfilename, parses it, and returns Events.""" |
events = []
cal = Calendar.from_ical(open(icsfile, 'rb').read())
for component in cal.walk('vevent'):
dtstart = component['dtstart'].dt
rrule = component['rrule']
freq, args = convert_rrule(rrule)
args['dtstart'] = dtstart
rrule = dateutil.rrule.rrule(freq, **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 route(cls, path):
"""A decorator to indicate that a method should be a routable HTTP endpoint. .. code-block:: python from compactor.process import Process c... |
if not path.startswith('/'):
raise ValueError('Routes must start with "/"')
def wrap(fn):
setattr(fn, cls.ROUTE_ATTRIBUTE, path)
return fn
return wrap |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install(cls, mbox):
"""A decorator to indicate a remotely callable method on a process. .. code-block:: python from compactor.process import Process class Pi... |
def wrap(fn):
setattr(fn, cls.INSTALL_ATTRIBUTE, mbox)
return fn
return wrap |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pid(self):
"""The pid of this process. :raises: Will raise a ``Process.UnboundProcess`` exception if the process is not bound to a context. """ |
self._assert_bound()
return PID(self._context.ip, self._context.port, self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def link(self, to):
"""Link to another process. The ``link`` operation is not guaranteed to succeed. If it does, when the other process terminates, the ``exited`... |
self._assert_bound()
self._context.link(self.pid, to) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install(cls, message_type):
"""A decorator to indicate a remotely callable method on a process using protocol buffers. .. code-block:: python from compactor.... |
def wrap(fn):
@functools.wraps(fn)
def wrapped_fn(self, from_pid, message_str):
message = message_type()
message.MergeFromString(message_str)
return fn(self, from_pid, message)
return Process.install(message_type.DESCRIPTOR.full_name)(wrapped_fn)
return wrap |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def actions(acts, done):
'''
Prepare actions pipeline.
:param tuple acts: called functions
:param function done: get result from actions
:returns function: function that starts executio
'''
def _intermediate(acc, action):
result = action(acc['state'])
values = concatv(acc['... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lift(fn=None, state_fn=None):
""" The lift decorator function will be used to abstract away the management of the state object used as the intermediate repre... |
if fn is None:
return partial(lift, state_fn=state_fn)
@wraps(fn)
def _lift(*args, **kwargs):
def _run(state):
ans = fn(*cons(state, args), **kwargs)
s = state_fn(state) if state_fn is not None else ans
return {'answer': ans, 'state': s}
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 _set_speed(self, motor, speed):
""" Change the speed of a motor on the controller. :param motor: The motor to change. :type motor: ``int`` :param speed: Spee... |
self._validate_motor(motor)
en, in1, in2 = self._motors[motor-1]
if speed == 0:
en.pwm_stop()
in1.set(False)
in2.set(False)
elif speed > 0:
en.pwm_start(abs(speed))
in1.set(True)
in2.set(False)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_all_params_are_keyword(method):
""" Raises CooperativeError if method any parameter that is not a named keyword parameter """ |
args, varargs, keywords, defaults = inspect.getargspec(method)
# Always have self, thus the -1
if len(args or []) - 1 != len(defaults or []):
raise CooperativeError, "Init has positional parameters " + \
str(args[1:])
if varargs:
raise CooperativeError, "Init has variadi... |
<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_keyword_extractor(method):
""" Removes all keyword parameters required by 'method' from dictionary 'keys' and returns them in a separate dictionary. """ |
args, _1, _2, defs = inspect.getargspec(method)
key_args = args[-len(defs or []):]
def extractor(keys):
new = {}
for a in key_args:
if a in keys:
new[a] = keys[a]
del keys[a]
return new
return extractor |
<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_config(self, ):
"""Return the user config for this plugin You have to provide a configspec, put the configspec file in the same folder as your plugin. Na... |
# get the module of the plugin class
mod = sys.modules[self.__module__]
# get the file from where it was imported
modfile = mod.__file__
# get the module directory
specdir = os.path.dirname(modfile)
# get the classname
cname = self.__class__.__name__
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_plugins(self, path):
"""Return a list with all plugins found in path :param path: the directory with plugins :type path: str :returns: list of JB_Plugin... |
ext = os.extsep+'py'
files = []
for (dirpath, dirnames, filenames) in os.walk(path):
files.extend([os.path.join(dirpath, x) for x in filenames if x.endswith(ext)])
plugins = []
for f in files:
try:
mod = self.__import_file(f)
e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gather_plugins(self):
"""Return all plugins that are found in the plugin paths Looks in the envvar ``JUKEBOX_PLUGIN_PATH``. :returns: :rtype: :raises: """ |
plugins = []
cfg = get_core_config()
pathenv = cfg['jukebox']['pluginpaths']
pathenv = os.pathsep.join((pathenv, os.environ.get("JUKEBOX_PLUGIN_PATH", "")))
paths = pathenv.split(os.pathsep)
# first find built-ins then the ones in the config, then the one from the enviro... |
<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_plugins(self, ):
"""Loads all found plugins :returns: None :rtype: None :raises: None """ |
for p in self.__plugins.values():
try:
self.load_plugin(p)
except errors.PluginInitError:
log.exception('Initializing the plugin: %s failed.' % p) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_plugin(self, p):
"""Load the specified plugin :param p: The plugin to load :type p: Subclass of JB_Plugin :returns: None :rtype: None :raises: errors.Pl... |
if p.is_loaded():
return
# load required plugins first
reqnames = p.required
reqplugins = []
for name in reqnames:
try:
reqplugins.append(self.__plugins[name])
except KeyError as e:
log.error("Required Plugin %s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unload_plugins(self, ):
""" Unloads all loaded plugins :returns: None :rtype: None :raises: None """ |
for p in self.__plugins.values():
if p.is_loaded():
try:
p._unload()
log.info('Uninitialized the plugin: %s' % p)
except errors.PluginUninitError:
log.error('Uninitialization of the plugin: %s failed.' % p) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __import_file(self, f):
"""Import the specified file and return the imported module :param f: the file to import :type f: str :returns: The imported module :... |
directory, module_name = os.path.split(f)
module_name = os.path.splitext(module_name)[0]
path = list(sys.path)
sys.path.insert(0, directory)
module = __import__(module_name)
return module |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _exception_handler(self, e):
"""This exception handler catches should only be invoked when we need to quit the workflow prematurely. It takes in an `ApiExcep... |
if isinstance(e.message, dict):
return self._prep_response(
e.message['msg'], status=e.message['status'])
if e.message.find('Validation') == 0:
return self._prep_response(self.validation.errors, status=400)
elif e.message.find('No record') == 0:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_instance(self, **kwargs):
"""Loads the record specified by the `obj_id` path in the url and stores it in g._resource_instance""" |
current_app.logger.info("Getting instance")
current_app.logger.debug("kwargs: {}".format(kwargs))
current_app.logger.info(
"Loading instance: {}".format(kwargs['obj_id']))
rec = self.db_query.get_instance(self.db_collection, kwargs['obj_id'])
g._resource_instance = ... |
<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_record_data(self, changes, orig_record=None):
"""This method merges PATCH requests with the db record to ensure no data is lost. In addition, it is als... |
current_app.logger.info("Merging request data with db record")
current_app.logger.debug("orig_record: {}".format(orig_record))
current_app.logger.debug("Changes".format(changes))
final_record = changes
if request.method == 'PATCH':
final_record = dict(orig_record)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def repr_return(func):
""" This is a decorator to give the return value a pretty print repr """ |
def repr_return_decorator(*args, **kwargs):
ret = func(*args, **kwargs)
if isinstance(ret, basestring):
return ret
if type(ret) in repr_map:
return repr_map[type(ret)](ret)
print('=' * 80 + '\n' +
' FAILED TO GET REPR RETURN for type (' +
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def repr_setup(self, name=None, col_names=None, col_types=None):
""" This wasn't safe to pass into init because of the inheritance """ |
self._name = name or self._name
self._col_types = col_types or self._col_types |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_string(obj, name=None, nonempty=False):
""" Raise an exception if the obj is not of type str or unicode. If name is provided it is used in the except... |
require_instance(obj, string_types, name, "string")
if nonempty and not obj:
raise ValueError(
(("%s: " % name) if name else "") +
"string must be nonempty.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_instance(obj, types=None, name=None, type_name=None, truncate_at=80):
""" Raise an exception if obj is not an instance of one of the specified types.... |
if not isinstance(obj, types):
obj_string = str(obj)
if len(obj_string) > truncate_at:
obj_string = obj_string[:truncate_at - 3] + "..."
if type_name is None:
try:
type_name = "one of " + ", ".join(str(t) for t in types)
except TypeError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_iterable_of(objs, types, name=None, type_name=None, truncate_at=80):
""" Raise an exception if objs is not an iterable with each element an instance ... |
# Fast pass for common case where all types are correct.
# This avoids the more expensive loop below. A typical speedup from this
# optimization is 6.6 sec -> 1.7 sec, for testing a list of size 10,000,000.
try:
if all(isinstance(obj, types) for obj in objs):
return
except TypeE... |
<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_property(obj, name, value):
""" Recursively sets value of object and its subobjects property specified by its name. The object can be a user defined obje... |
if obj == None or name == None:
return
names = name.split(".")
if names == None or len(names) == 0:
return
RecursiveObjectWriter._perform_set_property(obj, names, 0, 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 copy_properties(dest, src):
""" Copies content of one object to another object by recursively reading all properties from source object and then recursively ... |
if dest == None or src == None:
return
values = RecursiveObjectReader.get_properties(src)
RecursiveObjectWriter.set_properties(dest, values) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def time_range_cutter_at_time(local,time_range,time_cut=(0,0,0)):
""" Given a range, return a list of DateTimes that match the time_cut between start and end. :p... |
( start, end ) = time_range.get(local)
index = start.replace(
hour=time_cut[0],
minute=time_cut[1],
second=time_cut[2]
)
cuts = []
index += datetime.timedelta(days=1)
while index < end:
cuts.append(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hours(self,local=False):
""" Returns the number of hours of difference """ |
delta = self.delta(local)
return delta.total_seconds()/3600 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chunks(self,local,cutter_callback=None,*cutter_callback_args,**cutter_callback_kwargs):
""" Takes a time range and returns sub timeranges based upon the cuts... |
# First we get all the slices we want to take out of this time range.
if not cutter_callback:
cutter_callback = time_range_cutter_at_time
time_cuts = cutter_callback(local,self,*cutter_callback_args,**cutter_callback_kwargs)
# Now we need to make the time range objects for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str(self,local):
""" Return the string representation of the time range :param local: if False [default] use UTC datetime. If True use localtz """ |
s = self.start_time.str(local) \
+ u" to " \
+ self.end_time.str(local)
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def daily_hours(self,local=False):
""" This returns a number from 0 to 24 that describes the number of hours passed in a day. This is very useful for hr.attendan... |
data = self.get(local)
daily_hours = (data.hour +
data.minute / 60.0 +
data.second / 3600.0)
return round(daily_hours,2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str(self,local=False,ifempty=None):
""" Returns the string representation of the datetime """ |
ts = self.get(local)
if not ts: return ifempty
return ts.strftime('%Y-%m-%d %H:%M:%S') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gc_velocity_update(particle, social, state):
""" Guaranteed convergence velocity update. Args: particle: cipy.algorithms.pso.Particle: Particle to update the... |
gbest = state.swarm[gbest_idx(state.swarm)].position
if not np.array_equal(gbest, particle.position):
return std_velocity(particle, social, state)
rho = state.params['rho']
inertia = state.params['inertia']
v_max = state.params['v_max']
size = particle.position.size
r2 = state.rng... |
<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_fitness(objective_function, particle):
""" Calculates and updates the fitness and best_fitness of a particle. Fitness is calculated using the 'problem... |
fitness = objective_function(particle.position)
best_fitness = particle.best_fitness
cmp = comparator(fitness)
if best_fitness is None or cmp(fitness, best_fitness):
best_position = particle.position
return particle._replace(fitness=fitness,
best_fitness... |
<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_particle(position_update, velocity_update, state, nbest_topology, idx_particle):
""" Update function for a particle. Calculates and updates the veloci... |
(idx, particle) = idx_particle
nbest = state.swarm[nbest_topology[idx]].best_position
velocity = velocity_update(particle, nbest, state)
position = position_update(particle.position, velocity)
return particle._replace(position=position, velocity=velocity) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gbest_idx(swarm):
""" gbest Neighbourhood topology function. Args: swarm: list: The list of particles. Returns: int: The index of the gbest particle. """ |
best = 0
cmp = comparator(swarm[best].best_fitness)
for (idx, particle) in enumerate(swarm):
if cmp(particle.best_fitness, swarm[best].best_fitness):
best = idx
return best |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lbest_idx(state, idx):
""" lbest Neighbourhood topology function. Neighbourhood size is determined by state.params['n_s']. Args: state: cipy.algorithms.pso.S... |
swarm = state.swarm
n_s = state.params['n_s']
cmp = comparator(swarm[0].best_fitness)
indices = __lbest_indices__(len(swarm), n_s, idx)
best = None
for i in indices:
if best is None or cmp(swarm[i].best_fitness, swarm[best].best_fitness):
best = i
return best |
<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(swarm):
""" Determines the global best particle in the swarm. Args: swarm: iterable: an iterable that yields all particles in the swarm. Returns: ci... |
best = swarm[0]
cmp = comparator(best.best_fitness)
for particle in swarm:
if cmp(particle.best_fitness, best.best_fitness):
best = particle
return best |
<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_currency_view(self, select=False):
"""returns the newly added view""" |
v = CurrencyView()
self.remove_currency_view()
self['hbox_top'].pack_end(v.get_top_widget())
v.light_name(select)
return v |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def associate_by_user_id(backend, details, response, user=None, *args, **kwargs):
""" Associate current auth with a user with the same Google user_id in the DB. ... |
if user:
return None
user_id = response.get('id')
if user_id:
# Try to associate accounts registered with the same Google user_id.
for provider in ('google-appengine-oauth', 'google-appengine-oauth2'):
social = backend.strategy.storage.user.get_social_auth(provider, 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 memoize_methodcalls(func, pickle=False, dumps=pickle.dumps):
'''Cache the results of the function for each input it gets called with.
'''
cache = func._memoize_cache = {}
@functools.wraps(func)
def memoizer(self, *args, **kwargs):
if pickle:
key = dumps((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 get_section(self, section):
""" Gets parameters from specific section stored in this ConfigMap. The section name is removed from parameter keys. :param secti... |
result = ConfigParams()
prefix = section + "."
for (key, value) in self.items():
# Prevents exception on the next line
if len(key) < len(prefix):
continue
# Perform case sensitive match
key_prefix = key[: len(... |
<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_section(self, section, section_params):
""" Adds parameters into this ConfigParams under specified section. Keys for the new parameters are appended with... |
if section == None:
raise Exception("Section name cannot be null")
section = "" if self._is_shadow_name(section) else section
if section_params == None or len(section_params) == 0:
return
for (key, value) in section_params.items():
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 override(self, config_params):
""" Overrides parameters with new values from specified ConfigParams and returns a new ConfigParams object. :param config_para... |
map = StringValueMap.from_maps(self, config_params)
return ConfigParams(map) |
<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_defaults(self, default_config_params):
""" Set default values from specified ConfigParams and returns a new ConfigParams object. :param default_config_pa... |
map = StringValueMap.from_maps(default_config_params, self)
return ConfigParams(map) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(obj):
"""Serialize the given object into JSON. Args: obj: the object to be serialized. Returns: (str):
JSON representation of the given object. ""... |
LOGGER.debug('serialize(%s)', obj)
if isinstance(obj, datetime.date):
return simplejson.dumps(obj, default=encoders.as_date)
elif hasattr(obj, '__dict__'):
return simplejson.dumps(obj, default=encoders.as_object)
return simplejson.dumps(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 deserialize(json, cls=None):
"""Deserialize a JSON string into a Python object. Args: json (str):
the JSON string. cls (:py:class:`object`):
if the ``json`... |
LOGGER.debug('deserialize(%s)', json)
out = simplejson.loads(json)
if isinstance(out, dict) and cls is not None:
return cls(**out)
return 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 main(stack_name, template, mustache_variables):
'Update or create stack' template_data = _parse_template(template, mustache_variables) params = { 'StackName'... | )
exit(1)
except botocore.exceptions.ClientError as ex:
error_message = ex.response['Error']['Message']
if error_message == 'No updates are to be performed.':
print("No changes")
else:
raise
else:
print(json.dumps(
cf.describe_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_extended_help():
""" Prints an extended help message. """ |
# initiate TextWrapper class, which will handle all of the string formatting
w = textwrap.TextWrapper()
w.expand_tabs = False
w.width=110
w.initial_indent = ' '
w.subsequent_indent = ' '
print('')
print(textwrap.fill("<split> Complete parameter list:", initial_indent=''))
p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_float(self, input_string):
""" Return float type user input """ |
if input_string == '--training_fraction':
# was the flag set?
try:
index = self.args.index(input_string) + 1
except ValueError:
# it wasn't, it's optional, so return the appropriate default
return None
# the flag... |
<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_password(from_stdin_only=False):
""" Get a password either from STDIN or by prompting the user. :return: the password. """ |
if not sys.stdin.isatty():
password = sys.stdin.readline().strip()
elif not from_stdin_only:
password = getpass.getpass('Enter the password: ')
else:
password = None
return password |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_signals(self, target):
""" This is deprecated. Pass your controller to connect signals the old way. """ |
if self.connected:
raise RuntimeError("GtkBuilder can only connect signals once")
self.builder.connect_signals(target)
self.connected = 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_order_keyword_list(keywords):
""" Takes a given keyword list and returns a ready-to-go list of possible ordering values. Example: ['foo'] returns [('f... |
result = []
for keyword in keywords:
result.append((keyword, ''))
result.append(('-%s' % keyword, ''))
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 loads(s: str, **kwargs) -> JsonObj: """ Convert a json_str into a JsonObj :param s: a str instance containing a JSON document :param kwargs: arguments see: js... |
if isinstance(s, (bytes, bytearray)):
s = s.decode(json.detect_encoding(s), 'surrogatepass')
return json.loads(s, object_hook=lambda pairs: JsonObj(**pairs), **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 load(source, **kwargs) -> JsonObj: """ Deserialize a JSON source. :param source: a URI, File name or a .read()-supporting file-like object containing a JSON d... |
if isinstance(source, str):
if '://' in source:
req = Request(source)
req.add_header("Accept", "application/json, text/json;q=0.9")
with urlopen(req) as response:
jsons = response.read()
else:
with open(source) as f:
js... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_json(obj: JsonObj, indent: Optional[str]=' ', **kwargs) -> str: """ Convert obj to json string representation. :param obj: pseudo 'self' :param indent: ind... |
return obj._as_json_dumps(indent, **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 get(obj: JsonObj, item: str, default: JsonObjTypes=None) -> JsonObjTypes: """ Dictionary get routine """ |
return obj._get(item, default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setdefault(obj: JsonObj, k: str, value: Union[Dict, JsonTypes]) -> JsonObjTypes: """ Dictionary setdefault reoutine """ |
return obj._setdefault(k, 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 _default(self, obj):
""" return a serialized version of obj or raise a TypeError :param obj: :return: Serialized version of obj """ |
return obj.__dict__ if isinstance(obj, JsonObj) else json.JSONDecoder().decode(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 _as_json(self, **kwargs) -> str: """ Convert a JsonObj into straight json text :param kwargs: json.dumps arguments :return: JSON formatted str """ |
return json.dumps(self, default=self._default, **kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.