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 sync_and_deploy_gateway(collector):
"""Do a sync followed by deploying the gateway""" |
configuration = collector.configuration
aws_syncr = configuration['aws_syncr']
find_gateway(aws_syncr, configuration)
artifact = aws_syncr.artifact
aws_syncr.artifact = ""
sync(collector)
aws_syncr.artifact = artifact
deploy_gateway(collector) |
<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_result(self, f=sys.stdout, verbose=False):
"""Print result to f :param f: stream to print output :param verbose: print all data or only the most import... |
var_count = len(self.betas)/2
if verbose:
results = [str(x) for x in [
self.chr,
self.pos,
self.rsid,
self.ph_label,
self.non_miss,
self.maj_allele,
self.min_allele,
... |
<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_synonym(self, input_word):
""" Generate Synonym using a WordNet synset. """ |
results = []
results.append(input_word)
synset = wordnet.synsets(input_word)
for i in synset:
index = 0
syn = i.name.split('.')
if syn[index]!= input_word:
name = syn[0]
results.append(PataLib().strip_underscor... |
<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_canonical(version, loosedev=False):
# type: (str, bool) -> bool """ Return whether or not the version string is canonical according to Pep 440 """ |
if loosedev:
return loose440re.match(version) is not None
return pep440re.match(version) is not 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 decode(data):
""" Handles decoding of the JSON `data`. Args: data (str):
Data which will be decoded. Returns: dict: Dictionary with decoded data. """ |
decoded = None
try:
decoded = json.loads(data)
except Exception, e:
raise MetaParsingException("Can't parse your JSON data: %s" % e.message)
decoded = validator.check_structure(decoded)
return decoded |
<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(host='0.0.0.0', port=1338):
""" Initialize PyMLGame. This creates a controller thread that listens for game controllers and events. :param host: Bind to... |
CONTROLLER.host = host
CONTROLLER.port = port
CONTROLLER.setDaemon(True) # because it's a deamon it will exit together with the main thread
CONTROLLER.start() |
<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_events(maximum=10):
""" Get all events since the last time you asked for them. You can define a maximum which is 10 by default. :param maximum: Maximum n... |
events = []
for ev in range(0, maximum):
try:
if CONTROLLER.queue.empty():
break
else:
events.append(CONTROLLER.queue.get_nowait())
except NameError:
print('PyMLGame is not initialized correctly. Use pymlgame.init() first.')
... |
<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_entry(entry):
"""Consolidate some entry attributes and rename a few others. Consolidate address attributes into a single field and replace some field n... |
newEntry = {}
if 'Address1' in entry:
address = str(entry['Address1'])
if entry['Address2'] != '':
address = address + ' ' + str(entry['Address2'])
newEntry['address'] = address
del entry['Address1']
del entry['Address2']
for key in entry.keys():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_expenditure_entry(database, entry):
"""Update a record of a expenditure report in the provided database. @param db: The MongoDB database to operate on... |
entry = clean_entry(entry)
database.expenditures.update(
{'recordID': entry['recordID']},
{'$set': entry},
upsert=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 update_loan_entry(database, entry):
"""Update a record of a loan report in the provided database. @param db: The MongoDB database to operate on. The loans co... |
entry = clean_entry(entry)
database.loans.update(
{'recordID': entry['recordID']},
{'$set': entry},
upsert=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 insert_contribution_entries(database, entries):
"""Insert a set of records of a contribution report in the provided database. Insert a set of new records int... |
entries = map(clean_entry, entries)
database.contributions.insert(entries, continue_on_error=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 insert_expenditure_entries(database, entries):
"""Insert a set of records of a expenditure report in the provided database. Insert a set of new records into ... |
entries = map(clean_entry, entries)
database.expenditures.insert(entries, continue_on_error=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 insert_loan_entries(database, entries):
"""Insert a set of records of a loan report in the provided database. Insert a set of new records into the provided d... |
entries = map(clean_entry, entries)
database.loans.insert(entries, continue_on_error=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 pagination_links(paginator_page, show_pages, url_params=None,
first_page_label=None, last_page_label=None,
page_url=''):
'''Django template tag to display pagination links for a paginated
list of items.
Expects the following variables:
* the current :class... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modify_classes():
""" Auto-discover INSTALLED_APPS class_modifiers.py modules and fail silently when not present. This forces an import on them to modify any... |
import copy
from django.conf import settings
from django.contrib.admin.sites import site
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to impor... |
<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(self, text):
'''Wraps the text object to width, breaking at whitespaces. Runs of
whitespace characters are preserved, provided they do not fall at a
line boundary. The implementation is based on that of textwrap from the
standard library, but we can cope with StringWithFormattin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chainable(fn):
""" Make function a chainable validator The returned function is a chainable validator factory which takes the next function in the chain and ... |
@functools.wraps(fn)
def wrapper(nxt=lambda x: x):
if hasattr(nxt, '__call__'):
return lambda x: nxt(fn(x))
# Value has been passsed directly, so we don't chain
return fn(nxt)
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 make_chain(fns):
""" Take a list of chainable validators and return a chained validator The functions should be decorated with ``chainable`` decorator. Any e... |
chain = lambda x: x
for fn in reversed(fns):
chain = fn(chain)
def validator(v):
try:
return chain(v)
except ReturnEarly:
return v
return validator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, locator, factory):
""" Registers a component using a factory method. :param locator: a locator to identify component to be created. :param fac... |
if locator == None:
raise Exception("Locator cannot be null")
if factory == None:
raise Exception("Factory cannot be null")
self._registrations.append(Registration(locator, factory)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, locator):
""" Creates a component identified by given locator. :param locator: a locator to identify component to be created. :return: the creat... |
for registration in self._registrations:
this_locator = registration.locator
if this_locator == locator:
try:
return registration.factory(locator)
except Exception as ex:
if isinstance(ex, CreateException):
... |
<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(self, catalog=None, dependencies=None, allow_overwrite=False):
'''
Convenience method to update this Di instance with the specified contents.
:param catalog: ICatalog supporting class or mapping
:type catalog: ICatalog or collections.Mapping
:param dependencies: Mappi... |
<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_missing_deps(self, obj):
'''
Returns missing dependencies for provider key.
Missing meaning no instance can be provided at this time.
:param key: Provider key
:type key: object
:return: Missing dependencies
:rtype: list
'''
deps = self.get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def iresolve(self, *keys):
'''
Iterates over resolved instances for given provider keys.
:param keys: Provider keys
:type keys: tuple
:return: Iterator of resolved instances
:rtype: generator
'''
for key in keys:
missing = self.get_missing_dep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def resolve(self, *keys):
'''
Returns resolved instances for given provider keys.
If only one positional argument is given, only one is returned.
:param keys: Provider keys
:type keys: tuple
:return: Resolved instance(s); if only one key given, otherwise list of them.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def resolve_deps(self, obj):
'''
Returns list of resolved dependencies for given obj.
:param obj: Object to lookup dependencies for
:type obj: object
:return: Resolved dependencies
:rtype: list
'''
deps = self.get_deps(obj)
return list(self.iresol... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def register_factory(self, key, factory=_sentinel, scope=NoneScope, allow_overwrite=False):
'''
Creates and registers a provider using the given key, factory, and scope.
Can also be used as a decorator.
:param key: Provider key
:type key: object
:param factory: Factory ... |
<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_instance(self, key, instance, default_scope=GlobalScope):
'''
Sets instance under specified provider key. If a provider for specified key does not exist, one is created
without a factory using the given scope.
:param key: Provider key
:type key: object
:param ins... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def depends_on(self, *keys):
'''
Decorator that marks the wrapped as depending on specified provider keys.
:param keys: Provider keys to mark as dependencies for wrapped
:type keys: tuple
:return: decorator
:rtype: decorator
'''
def decorator(wrapped):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def inject_classproperty(self, key, name=None, replace_on_access=False):
'''
Decorator that injects the specified key as a classproperty.
If replace_on_access is True, then it replaces itself with the instance on first lookup.
:param key: Provider key
:type key: object
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getTarget(iid):
'''
A static method which returns a Target object identified by
iid. Returns None if a Target object was not found
'''
db = getDataCommunicator()
verbose('Loading target with id {}'.format(iid))
data = db.getTarget(iid)
if dat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def delete(self):
'''
Deletes link from vault and removes database information
'''
if not self._id:
verbose('This target does not have an id')
return False
# Removes link from vault directory
verbose('Removing link from vault 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 secure(self):
'''
Creates a hard link to the target file in the vault directory
and saves information about the target file in the database
'''
verbose('Saving information about target into conman database')
self._id = self.db.insertTarget(self.name, self.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 deploy(self):
'''
Creates a link at the original path of this target
'''
if not os.path.exists(self.path):
makedirs(self.path)
link(self.vault_path, self.real_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 parse_cstring(stream, offset):
""" parse_cstring will parse a null-terminated string in a bytestream. The string will be decoded with UTF-8 decoder, of cours... |
stream.seek(offset)
string = ""
while True:
char = struct.unpack('c', stream.read(1))[0]
if char == b'\x00':
return string
else:
string += char.decode() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unite_dataset(dataset, basecolumn, fn=None):
""" Unite dataset via fn Parameters dataset : list A list of data basecolumn : int A number of column which will... |
# create default unite_fn
if fn is None:
fn = default_unite_function
# classify dataset via unite_fn
united_dataset = OrderedDict()
for data in dataset:
unite_name = fn(data)
if unite_name not in united_dataset:
united_dataset[unite_name] = []
united_data... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _create_folder(self):
''' a helper method for creating a temporary audio clip folder '''
# import dependencies
import os
from labpack.platforms.localhost import localhostClient
from labpack.records.id import labID
# create folder in user app data
record_i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _transcribe_files(self, file_list, file_mimetype):
''' a helper method for multi-processing file transcription '''
# import dependencies
import queue
from threading import Thread
# define multithreading function
def _recognize_file(file_path, file_mimetype, queue)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def lazy_enumerate(self, **kwargs):
'''Enumerate without evaluating any sets.
'''
kwargs['lazy'] = True
for item in self.enumerate(**kwargs):
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 group_selection(request):
"""Allow user to select a TenantGroup if they have more than one.""" |
groups = get_user_groups(request.user)
count = len(groups)
if count == 1:
# Redirect to the detail page for this group
return redirect(groups[0])
context = {
'groups': groups,
'count': count,
}
return render(request, 'multitenancy/group-landing.html', context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def group_dashboard(request, group_slug):
"""Dashboard for managing a TenantGroup.""" |
groups = get_user_groups(request.user)
group = get_object_or_404(groups, slug=group_slug)
tenants = get_user_tenants(request.user, group)
can_edit_group = request.user.has_perm('multitenancy.change_tenantgroup', group)
count = len(tenants)
if count == 1:
# Redirect to the detail page fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tenant_dashboard(request, group_slug, tenant_slug):
"""Dashboard for managing a tenant.""" |
groups = get_user_groups(request.user)
group = get_object_or_404(groups, slug=group_slug)
tenants = get_user_tenants(request.user, group)
tenant = get_object_or_404(tenants, slug=tenant_slug)
can_edit_tenant = request.user.has_perm('multitenancy.change_tenant', tenant)
context = {
'grou... |
<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_connections(self, connections):
""" Reads connections from configuration parameters. Each section represents an individual Connectionparams :param conne... |
del self._items[:]
for key in connections.get_key_names():
item = DiscoveryItem()
item.key = key
value = connections.get_as_nullable_string(key)
item.connection = ConnectionParams.from_string(value)
self._items.append(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 register(self, correlation_id, key, connection):
""" Registers connection parameters into the discovery service. :param correlation_id: (optional) transactio... |
item = DiscoveryItem()
item.key = key
item.connection = connection
self._items.append(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 resolve_one(self, correlation_id, key):
""" Resolves a single connection parameters by its key. :param correlation_id: (optional) transaction id to trace exe... |
connection = None
for item in self._items:
if item.key == key and item.connection != None:
connection = item.connection
break
return connection |
<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_chunks(string, num_chars):
"""Yield num_chars-character chunks from string.""" |
for start in range(0, len(string), num_chars):
yield string[start:start+num_chars] |
<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_package_config(reload_=False):
"""Loads the package configurations from the global `acorn.cfg` file. """ |
global _packages
from acorn.config import settings
packset = settings("acorn", reload_)
if packset.has_section("acorn.packages"):
for package, value in packset.items("acorn.packages"):
_packages[package] = value.strip() == "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 load_decorate(package):
"""Imports and decorates the package with the specified name. """ |
# We import the decoration logic from acorn and then overwrite the sys.module
# for this package with the decorated, original pandas package.
from acorn.logging.decoration import set_decorating, decorating
#Before we do any imports, we need to set that we are decorating so that
#everything wor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_file(self, path, dryrun):
""" Remove files and return filename. """ |
# if dryrun just return file path
if dryrun:
return path
# remove and return file
if self.__force or raw_input("Remove file '%s'? [y/N]" % path).lower() == "y":
os.remove(path)
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_module(self, fullname, path=None):
""" Find the appropriate loader for module ``name`` :param fullname: ``__name__`` of the module to import :type fulln... |
# path points to the top-level package path if any
# and we can only import sub-modules/-packages
if path is None:
return
if fullname.startswith(self.module_prefix):
return self
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Evaluate the command line arguments, performing the appropriate actions so the application can be started. """ |
# The list command prevents any other processing of args
if self._args.list:
self._print_installed_apps(self._args.controller)
sys.exit(0)
# If app is not specified at this point, raise an error
if not self._args.application:
sys.stderr.write('\nerro... |
<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_cli_args(self):
"""Add the cli arguments to the argument parser.""" |
# Optional cli arguments
self._arg_parser.add_argument('-l', '--list',
action='store_true',
help='List installed sprockets apps')
self._arg_parser.add_argument('-s', '--syslog',
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 _configure_logging(application, verbosity=0, syslog=False):
"""Configure logging for the application, setting the appropriate verbosity and adding syslog if ... |
# Create a new copy of the logging config that will be modified
config = dict(LOGGING)
# Increase the logging verbosity
if verbosity == 1:
config['loggers']['sprockets']['level'] = logging.INFO
elif verbosity == 2:
config['loggers']['sprockets']['level']... |
<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_application_module(self, controller, application):
"""Return the module for an application. If it's a entry-point registered application name, return th... |
for pkg in self._get_applications(controller):
if pkg.name == application:
return pkg.module_name
return application |
<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_controllers(self):
"""Iterate through the installed controller entry points and import the module and assign the handle to the CLI._controllers dict. :r... |
controllers = dict()
for pkg in pkg_resources.iter_entry_points(group=self.CONTROLLERS):
LOGGER.debug('Loading %s controller', pkg.name)
controllers[pkg.name] = importlib.import_module(pkg.module_name)
return controllers |
<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_controller_help(self, controller):
"""Return the value of the HELP attribute for a controller that should describe the functionality of the controller. ... |
if hasattr(self._controllers[controller], 'HELP'):
return self._controllers[controller].HELP
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 _print_installed_apps(self, controller):
"""Print out a list of installed sprockets applications :param str controller: The name of the controller to get app... |
print('\nInstalled Sprockets %s Apps\n' % controller.upper())
print("{0:<25} {1:>25}".format('Name', 'Module'))
print(string.ljust('', 51, '-'))
for app in self._get_applications(controller):
print('{0:<25} {1:>25}'.format(app.name, '(%s)' % app.module_name))
print('... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rslv(self, interface: str, name: str=None) -> Tuple[str, int, Optional[str]]: """Return the IP address, port and optionally host IP for one of this Nodes in... |
if name is None:
name = self.name
key = '{}-{}'.format(name, interface)
host = None
if 'host' in self.interfaces[key]:
host = self.interfaces[key]['host']
return self.interfaces[key]['ip'], self.interfaces[key]['port'], host |
<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(self, target: str, trigger: str, parameters: Dict[str, Any]={}):
"""Calls the specified Trigger of another Area with the optionally given parameter... |
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def benchmark(f, n_repeats=3, warmup=True, name=""):
""" Run the given function f repeatedly, return the average elapsed time. """ |
if warmup:
f()
total_time = 0
for i in range(n_repeats):
iter_name = "%s (iter #%d)" % (name, i + 1,)
with Timer(iter_name) as t:
f()
total_time += t.elapsed
return total_time / n_repeats |
<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_to_dict(item):
'''Examine an item of any type and return a true dictionary.
If the item is already a dictionary, then the item is returned as-is. Easy.
Otherwise, it attempts to interpret it. So far, this routine can handle:
* a class, function, or anything with a .__dict__ entry
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def do_op(field, op, value):
''' used for comparisons '''
if op==NOOP:
return True
if field==None:
if value==None:
return True
else:
return False
if value==None:
return False
if op==LESS:
return (field < value)
if op==LESSorEQUAL:
... |
<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_value(row, field_name):
'''
Returns the value found in the field_name attribute of the row dictionary.
'''
result = None
dict_row = convert_to_dict(row)
if detect_list(field_name):
temp = row
for field in field_name:
dict_temp = convert_to_dict(temp)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def select(table, index_track, field_name, op, value, includeMissing):
'''Modifies the table and index_track lists based on the comparison.
'''
result = []
result_index = []
counter = 0
for row in table:
if detect_fields(field_name, convert_to_dict(row)):
final_value = get_va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def capture(package, prefix, modules=[], level=logging.DEBUG):
""" Capture log messages for the given modules and archive them to a ``LogFile`` resource. """ |
handler = LogFileHandler(package, prefix)
formatter = logging.Formatter(FORMAT)
handler.setFormatter(formatter)
modules = set(modules + ['loadkit'])
for logger in modules:
if not hasattr(logger, 'addHandler'):
logger = logging.getLogger(logger)
logger.setLevel(level=lev... |
<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(package, prefix, offset=0, limit=1000):
""" Load lines from the log file with pagination support. """ |
logs = package.all(LogFile, unicode(prefix))
logs = sorted(logs, key=lambda l: l.name, reverse=True)
seen = 0
record = None
tmp = tempfile.NamedTemporaryFile(suffix='.log')
for log in logs:
shutil.copyfileobj(log.fh(), tmp)
tmp.seek(0)
for line in reversed(list(tmp)):
... |
<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():
""" Clean data created by this script """ |
for queue in MyQueue.collection().instances():
queue.delete()
for job in MyJob.collection().instances():
job.delete()
for person in Person.collection().instances():
person.delete() |
<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, queue):
""" Create the fullname, and store a a message serving as result in the job """ |
# add some random time to simulate a long job
time.sleep(random.random())
# compute the fullname
obj = self.get_object()
obj.fullname.hset('%s %s' % tuple(obj.hmget('firstname', 'lastname')))
# this will the "result" of the job
result = 'Created fullname for Pe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def job_success(self, job, queue, job_result):
""" Update the queue's dates and number of jobs managed, and save into the job the result received by the callback... |
# display what was done
obj = job.get_object()
message = '[%s|%s] %s [%s]' % (queue.name.hget(),
obj.pk.get(),
job_result,
threading.current_thread().name)
self.log(mess... |
<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_listing(cls, request) -> [(200, 'Ok', ResourceListingModel)]:
'''Return the list of all available resources on the system.
Resources are filtered according to the permission system, so querying
this resource as different users may bare different results.'''
apis = [api.get_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _extract_models(cls, apis):
'''An helper function to extract all used models from the apis.'''
# TODO: This would probably be much better if the info would be
# extracted from the classes, rather than from the swagger
# representation...
models = set()
for api in apis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def api_declaration(
cls, request,
api_path: (Ptypes.path,
String('The path for the info on the resource.'))) -> [
(200, 'Ok', ApiDeclarationModel),
(404, 'Not a valid resource.')]:
'''Return the complete specification of a single API.
... |
<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_route_info(self, request):
"""Return information about the current URL.""" |
resolve_match = resolve(request.path)
app_name = resolve_match.app_name # The application namespace for the URL pattern that matches the URL.
namespace = resolve_match.namespace # The instance namespace for the URL pattern that matches the URL.
url_name = resolve_match.url_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 validate_account(self):
"""Make sure we are able to connect to the right account""" |
self._validating = True
with self.catch_invalid_credentials():
log.info("Finding a role to check the account id")
a_role = list(self.iam.resource.roles.limit(1))
if not a_role:
raise AwsSyncrError("Couldn't find an iam role, can't validate the account... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def do_GET(self):
'''The GET command.
'''
if self.path.lower().endswith("?wsdl"):
service_path = self.path[:-5]
service = self.server.getNode(service_path)
if hasattr(service, "_wsdl"):
wsdl = service._wsdl
# update the soap:location 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 get_notebook_names(self, path=''):
"""List all notebook names in the notebook dir and path.""" |
path = path.strip('/')
spec = {'path': path,
'type': 'notebook'}
fields = {'name': 1}
notebooks = list(self._connect_collection(self.notebook_collection).find(spec,fields))
names = [n['name'] for n in notebooks]
return names |
<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_notebook(self, model=None, path=''):
"""Create a new notebook and return its model with no content.""" |
path = path.strip('/')
if model is None:
model = {}
if 'content' not in model:
metadata = current.new_metadata(name=u'')
model['content'] = current.new_notebook(metadata=metadata)
if 'name' not in model:
model['name'] = self.increment_file... |
<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_type(stype):
''' Get the python type for a given string describtion for a type.
@param stype: The string representing the type to return
@return: The python type if available
'''
stype = stype.lower()
if stype == 'str':
return str
if stype == 'unicode':
if 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 _format_message(value, line_length, indent="", first_indent=None):
''' Return a string with newlines so that the given string fits into this
line length. At the start of the line the indent is added. This can
be used for commenting the message out within a file or to indent your
text.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def init_default_config(self, path):
''' Initialize the config object and load the default configuration.
The path to the config file must be provided. The name of the
application is read from the config file.
The config file stores the description and the default values 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 get_description(self, section, key):
''' Get the description of a config key. If it does not exist an
Exception will be thrown.
@param section: the section where the key is stored.
@param key: the key to get the description for.
@return: A tuple with thre... |
<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_default(self):
''' Load the default config files.
First the global config file then the user config file.
'''
appdir = AppDirs(self.application_name, self.application_author,
version=self.application_version)
file_name = os.path.join(appdir.site_data_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load(self, filename):
''' Load the given config file.
@param filename: the filename including the path to load.
'''
if not os.path.exists(filename):
#print 'Could not load config file [%s]' % (filename)
raise AppConfigValueException('Could not load 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 get(self, section, key):
''' Get the value of a key in the given section. It will automatically
translate the paramter type if the parameter has a type specified
with the description.
@param section: the section where the key can be found.
@param key: the 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 set(self, section, key, value):
''' Set the value for a key in the given section. It will check the
type of the value if it is available. If the value is not from
the given type it will be transformed to the type.
An exception will be thrown if there is a problem with the... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def save(self, filename=None, verbose=False):
''' Save the config to the given file or to given default location.
@param filename: the file to write the config
@param verbose: If set to true the config file will have all values
and all descriptions
'''
... |
<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_config(self, filedesc, verbose=False):
''' Write the current config to the given filedescriptor which has must
be opened for writing.
Only the config values different from the default value are written
If the verbose switch is turned on the config file generated w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self, data):
""" Call json.dumps & let it rip """ |
super(Serializer, self).serialize(data)
self.resp.body = json.dumps(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def surround_previous_word(input_str):
'''
Surround last word in string with parentheses. If last non-whitespace character
is delimiter, do nothing
'''
start = None
end = None
for i, char in enumerate(reversed(input_str)):
if start is None:
if char in '{}()[]<>?|':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _limit_call_handler(self):
""" Ensure we don't exceed the N requests a minute limit by leveraging a thread lock """ |
# acquire a lock on our threading.Lock() object
with self.limit_lock:
# if we have no configured limit, exit. the lock releases based on scope
if self.limit_per_min <= 0:
return
now = time.time()
# self.limits is a list of query times + ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def roughpage(request, url):
""" Public interface to the rough page view. """ |
if settings.APPEND_SLASH and not url.endswith('/'):
# redirect to the url which have end slash
return redirect(url + '/', permanent=True)
# get base filename from url
filename = url_to_filename(url)
# try to find the template_filename with backends
template_filenames = get_backend()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_roughpage(request, t):
""" Internal interface to the rough page view. """ |
import django
if django.VERSION >= (1, 8):
c = {}
response = HttpResponse(t.render(c, request))
else:
c = RequestContext(request)
response = HttpResponse(t.render(c))
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_form_media_type(media_type):
""" Return True if the media type is a valid form media type. """ |
base_media_type, params = parse_header(media_type.encode(HTTP_HEADER_ENCODING))
return (base_media_type == 'application/x-www-form-urlencoded' or
base_media_type == 'multipart/form-data') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clone_request(request, method):
""" Internal helper method to clone a request, replacing with a different HTTP method. Used for checking permissions against ... |
ret = Request(request=request._request,
parsers=request.parsers,
authenticators=request.authenticators,
negotiator=request.negotiator,
parser_context=request.parser_context)
ret._data = request._data
ret._files = request._files
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user(self, value):
""" Sets the user on the current request. This is necessary to maintain compatibility with django.contrib.auth where the user property is ... |
self._user = value
self._request.user = 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 auth(self, value):
""" Sets any non-user authentication information associated with the request, such as an authentication token. """ |
self._auth = value
self._request.auth = 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 _load_data_and_files(self):
""" Parses the request content into `self.data`. """ |
if not _hasattr(self, '_data'):
self._data, self._files = self._parse()
if self._files:
self._full_data = self._data.copy()
self._full_data.update(self._files)
else:
self._full_data = self._data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_stream(self):
""" Return the content body of the request, as a stream. """ |
meta = self._request.META
try:
content_length = int(
meta.get('CONTENT_LENGTH', meta.get('HTTP_CONTENT_LENGTH', 0))
)
except (ValueError, TypeError):
content_length = 0
if content_length == 0:
self._stream = None
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 generate_antonym(self, input_word):
""" Generate an antonym using a Synset and its lemmas. """ |
results = []
synset = wordnet.synsets(input_word)
for i in synset:
if i.pos in ['n','v']:
for j in i.lemmas:
if j.antonyms():
name = j.antonyms()[0].name
results.append(PataLib().strip_underscore(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(self, name, default=None):
""" Returns an extension instance with a given name. In case there are few extensions with a given name, the first one will be... |
try:
value = self[name]
except KeyError:
value = default
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort(line):
""" change point position if x1,y0 < x0,y0 """ |
x0, y0, x1, y1 = line
# if (x0**2+y0**2)**0.5 < (x1**2+y1**2)**0.5:
# return (x1,y1,x0,y0)
# return line
#
# if x1 < x0:
# return (x1,y1,x0,y0)
# return line
turn = False
if abs(x1 - x0) > abs(y1 - y0):
if x1 < x0:
turn = Tru... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.