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 get_profile_form():
""" Returns the profile form defined by ``settings.ACCOUNTS_PROFILE_FORM_CLASS``. """ |
from yacms.conf import settings
try:
return import_dotted_path(settings.ACCOUNTS_PROFILE_FORM_CLASS)
except ImportError:
raise ImproperlyConfigured("Value for ACCOUNTS_PROFILE_FORM_CLASS "
"could not be imported: %s" %
se... |
<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_profile_user_fieldname(profile_model=None, user_model=None):
""" Returns the name of the first field on the profile model that points to the ``auth.User`... |
Profile = profile_model or get_profile_model()
User = user_model or get_user_model()
for field in Profile._meta.fields:
if field.rel and field.rel.to == User:
return field.name
raise ImproperlyConfigured("Value for ACCOUNTS_PROFILE_MODEL does not "
"co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gameValue(self):
"""identify the correpsonding internal SC2 game value for self.type's value""" |
allowed = type(self).ALLOWED_TYPES
try:
if isinstance(allowed, dict): # if ALLOWED_TYPES is not a dict, there is no-internal game value mapping defined
return allowed.get(self.type.name)
except: pass # None .type values are okay -- such result in a None gameValue() r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def direct2dDistance(self, point):
"""consider the distance between two mapPoints, ignoring all terrain, pathing issues""" |
if not isinstance(point, MapPoint): return 0.0
return ((self.x-point.x)**2 + (self.y-point.y)**2)**(0.5) # simple distance formula |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def midPoint(self, point):
"""identify the midpoint between two mapPoints""" |
x = (self.x + point.x)/2.0
y = (self.y + point.y)/2.0
z = (self.z + point.z)/2.0
return MapPoint(x,y,z) |
<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_conf(to_hash, other_hash, path=[]):
"merges other_hash into to_hash"
for key in other_hash:
if (key in to_hash and isinstance(to_hash[key], dict)
and isinstance(other_hash[key], dict)):
merge_conf(to_hash[key], other_hash[key], path + [str(key)])
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_inputs(self):
""" Check for the existence of input files """ |
self.inputs = self.expand_filenames(self.inputs)
result = False
if len(self.inputs) == 0 or self.files_exist(self.inputs):
result = True
else:
print("Not executing task. Input file(s) do not exist.")
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 check_outputs(self):
""" Check for the existence of output files """ |
self.outputs = self.expand_filenames(self.outputs)
result = False
if self.files_exist(self.outputs):
if self.dependencies_are_newer(self.outputs, self.inputs):
result = True
print("Dependencies are newer than outputs.")
print("Running ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand_filenames(self, filenames):
""" Expand a list of filenames using environment variables, followed by expansion of shell-style wildcards. """ |
results = []
for filename in filenames:
result = filename
if "$" in filename:
template = Template(filename)
result = template.substitute(**self.environment)
logging.debug(
"Expanding {} to {}.".format(filename, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def files_exist(self, filenames):
""" Check if all files in a given list exist. """ |
return all([os.path.exists(os.path.abspath(filename)) and os.path.isfile(os.path.abspath(filename))
for filename in filenames]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dependencies_are_newer(self, files, dependencies):
""" For two lists of files, check if any file in the second list is newer than any file of the first. """ |
dependency_mtimes = [
os.path.getmtime(filename) for filename in dependencies]
file_mtimes = [os.path.getmtime(filename) for filename in files]
result = False
for file_mtime in file_mtimes:
for dependency_mtime in dependency_mtimes:
if dependency_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mktemp_file(self):
""" Create a temporary file in the '.faz' directory for the code to feed to the interpreter. """ |
if not(os.path.exists(self.__dirname)):
logging.debug("Creating directory {}".format(self.__dirname))
os.mkdir(self.__dirname)
elif not(os.path.isdir(self.__dirname)):
raise TempDirIsFileException(
"There is a file called %s in this 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 _get_max_page(dom):
""" Try to guess how much pages are in book listing. Args: dom (obj):
HTMLElement container of the page with book list. Returns: int: Nu... |
div = dom.find("div", {"class": "razeniKnihListovani"})
if not div:
return 1
# isolate only page numbers from links
links = div[0].find("a")
max_page = filter(
lambda x: "href" in x.params and "pageindex=" in x.params["href"],
links
)
max_page = map(
lambda... |
<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_book_links(dom):
""" Parse links to the details about publications from page with book list. Args: dom (obj):
HTMLElement container of the page with ... |
links = []
picker = lambda x: x.params.get("class", "").startswith("boxProKnihy")
for el in dom.find(None, fn=picker):
book_ref = el.find("a")
if not book_ref or "href" not in book_ref[0].params:
continue
links.append(book_ref[0].params["href"])
return links |
<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_book_links(links):
""" Go thru `links` to categories and return list to all publications in all given categories. Args: links (list):
List of strings (a... |
book_links = []
for link in links:
data = DOWNER.download(link + "1")
dom = dhtmlparser.parseString(data)
book_links.extend(_parse_book_links(dom))
max_page = _get_max_page(dom)
if max_page == 1:
continue
for i in range(max_page - 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 _parse_authors(authors):
""" Parse informations about authors of the book. Args: dom (obj):
HTMLElement containing slice of the page with details. Returns: ... |
link = authors.find("a")
link = link[0].params.get("href") if link else None
author_list = _strip_content(authors)
if "(" in author_list:
author_list = author_list.split("(")[0]
if not author_list.strip():
return []
return map(
lambda author: Author(author.strip(), l... |
<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_book(link):
""" Download and parse available informations about book from the publishers webpages. Args: link (str):
URL of the book at the publish... |
# download and parse book info
data = DOWNER.download(link)
dom = dhtmlparser.parseString(
utils.handle_encodnig(data)
)
dhtmlparser.makeDoubleLinked(dom)
# some books are without price in expected elements, this will try to get
# it from elsewhere
price = None
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(text) -> Optional['Response']: """Parse response into an instance of the appropriate child class.""" |
# Trim the start and end markers, and ensure only lowercase is used
if text.startswith(MARKER_START) and text.endswith(MARKER_END):
text = text[1:len(text)-1].lower()
# No-op; can just ignore these
if not text:
return None
if text.startswith(CMD_DATETI... |
<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_closed(self) -> Optional[bool]: """For Magnet Sensor; True if Closed, False if Open.""" |
if self._device_type is not None and self._device_type == DeviceType.DoorMagnet:
return bool(self._current_status & 0x01)
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 rssi_bars(self) -> int: """Received Signal Strength Indication, from 0 to 4 bars.""" |
rssi_db = self.rssi_db
if rssi_db < 45:
return 0
elif rssi_db < 60:
return 1
elif rssi_db < 75:
return 2
elif rssi_db < 90:
return 3
return 4 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zone(self) -> Optional[str]: """Zone the device is assigned to.""" |
if self._device_category == DC_BASEUNIT:
return None
return '{:02x}-{:02x}'.format(self._group_number, self._unit_number) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def workspace_state_changed(ob, event):
""" when a workspace is made 'open', we need to give all intranet users the 'Guest' role equally, when the workspace is n... |
workspace = event.object
roles = ['Guest', ]
if event.new_state.id == 'open':
api.group.grant_roles(
groupname=INTRANET_USERS_GROUP_ID,
obj=workspace,
roles=roles,
)
workspace.reindexObjectSecurity()
elif event.old_state.id == 'open':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def workspace_added(ob, event):
""" when a workspace is created, we add the creator to the admin group. We then setup our placeful workflow """ |
# Whoever creates the workspace should be added as an Admin
creator = ob.Creator()
IWorkspace(ob).add_to_team(
user=creator,
groups=set(['Admins']),
)
# Configure our placeful workflow
cmfpw = 'CMFPlacefulWorkflow'
ob.manage_addProduct[cmfpw].manage_addWorkflowPolicyConfig(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def participation_policy_changed(ob, event):
""" Move all the existing users to a new group """ |
workspace = IWorkspace(ob)
old_group_name = workspace.group_for_policy(event.old_policy)
old_group = api.group.get(old_group_name)
for member in old_group.getAllGroupMembers():
groups = workspace.get(member.getId()).groups
groups -= set([event.old_policy.title()])
groups.add(eve... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def invitation_accepted(event):
""" When an invitation is accepted, add the user to the team """ |
request = getRequest()
storage = get_storage()
if event.token_id not in storage:
return
ws_uid, username = storage[event.token_id]
storage[event.token_id]
acl_users = api.portal.get_tool('acl_users')
acl_users.updateCredentials(
request,
request.response,
us... |
<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_deleted_from_site_event(event):
""" Remove deleted user from all the workspaces where he is a member """ |
userid = event.principal
catalog = api.portal.get_tool('portal_catalog')
query = {'object_provides': WORKSPACE_INTERFACE}
query['workspace_members'] = userid
workspaces = [
IWorkspace(b._unrestrictedGetObject())
for b in catalog.unrestrictedSearchResults(query)
]
for 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 data_context_name(fn):
""" Return the `fn` in absolute path in `template_data` directory. """ |
return os.path.join(os.path.dirname(__file__), "template_data", fn) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_context(fn, mode="r"):
""" Return content fo the `fn` from the `template_data` directory. """ |
with open(data_context_name(fn), mode) as f:
return f.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tmp_context(fn, mode="r"):
""" Return content fo the `fn` from the temporary directory. """ |
with open(tmp_context_name(fn), mode) as f:
return f.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup_environment():
""" Shutdown the ZEO server process running in another thread and cleanup the temporary directory. """ |
SERV.terminate()
shutil.rmtree(TMP_PATH)
if os.path.exists(TMP_PATH):
os.rmdir(TMP_PATH)
global TMP_PATH
TMP_PATH = 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 stringify(obj):
""" Return the string representation of an object. :param obj: object to get the representation of :returns: unicode string representation of... |
out = obj
if isinstance(obj, uuid.UUID):
out = str(obj)
elif hasattr(obj, 'strftime'):
out = obj.strftime('%Y-%m-%dT%H:%M:%S.%f%z')
elif isinstance(obj, memoryview):
out = obj.tobytes()
elif isinstance(obj, bytearray):
out = bytes(obj)
elif sys.version_info[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 normalize_collection(coll):
""" Normalize all elements in a collection. :param coll: the collection to normalize. This is required to implement one of the fo... |
#
# The recursive version of this algorithm is something like:
#
# if isinstance(coll, dict):
# return dict((stringify(k), normalize_collection(v))
# for k, v in coll.items())
# if isinstance(obj, (list, tuple)):
# return [normalize_collection(ite... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def available(self):
""" Returns a set of the available versions. :returns: A set of integers giving the available versions. """ |
# Short-circuit
if not self._schema:
return set()
# Build up the set of available versions
avail = set(self._schema.__vers_downgraders__.keys())
avail.add(self._schema.__version__)
return avail |
<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_args_to_dict(values_specs):
"""It is used to analyze the extra command options to command. Besides known options and arguments, our commands also suppo... |
# values_specs for example: '-- --tag x y --key1 type=int value1'
# -- is a pseudo argument
values_specs_copy = values_specs[:]
if values_specs_copy and values_specs_copy[0] == '--':
del values_specs_copy[0]
# converted ArgumentParser arguments for each of the options
_options = {}
... |
<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_args(qCmd, parsed_args, _extra_values, value_specs):
"""Merge arguments from _extra_values into parsed_args. If an argument value are provided in both... |
temp_values = _extra_values.copy()
for key, value in six.iteritems(temp_values):
if hasattr(parsed_args, key):
arg_value = getattr(parsed_args, key)
if arg_value is not None and value is not None:
if isinstance(arg_value, list):
if value and 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 update_dict(obj, dict, attributes):
"""Update dict with fields from obj.attributes. :param obj: the object updated into dict :param dict: the result dictiona... |
for attribute in attributes:
if hasattr(obj, attribute) and getattr(obj, attribute) is not None:
dict[attribute] = getattr(obj, attribute) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retrieve_list(self, parsed_args):
"""Retrieve a list of resources from Neutron server.""" |
neutron_client = self.get_client()
_extra_values = parse_args_to_dict(self.values_specs)
_merge_args(self, parsed_args, _extra_values,
self.values_specs)
search_opts = self.args2search_opts(parsed_args)
search_opts.update(_extra_values)
if self.pagina... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lock_key(group_id, item_id, group_width=8):
"""Creates a lock ID where the lower bits are the group ID and the upper bits are the item ID. This allows the us... |
if group_id >= (1 << group_width):
raise Exception("Group ID is too big")
if item_id >= (1 << (63 - group_width)) - 1:
raise Exception("Item ID is too big")
return (item_id << group_width) | group_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 release_lock(dax, key, lock_mode=LockMode.wait):
"""Manually release a pg advisory lock. :dax: a DataAccess instance :key: either a big int or a 2-tuple of i... |
lock_fxn = _lock_fxn("unlock", lock_mode, False)
return dax.get_scalar(
dax.callproc(lock_fxn, key if isinstance(key, (list, tuple)) else [key])[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 advisory_lock(dax, key, lock_mode=LockMode.wait, xact=False):
"""A context manager for obtaining a lock, executing code, and then releasing the lock. A boole... |
if lock_mode == LockMode.wait:
obtain_lock(dax, key, lock_mode, xact)
else:
got_lock = obtain_lock(dax, key, lock_mode, xact)
if not got_lock:
if lock_mode == LockMode.error:
raise Exception("Unable to obtain advisory lock {}".format(key))
else:
# lock_mode is skip
y... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _lock_fxn(direction, lock_mode, xact):
"""Builds a pg advisory lock function name based on various options. :direction: one of "lock" or "unlock" :lock_mode:... |
if direction == "unlock" or lock_mode == LockMode.wait:
try_mode = ""
else:
try_mode = "_try"
if direction == "lock" and xact:
xact_mode = "_xact"
else:
xact_mode = ""
return "pg{}_advisory{}_{}".format(try_mode, xact_mode, direction) |
<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_hash(fName, readSize, dire=pDir()):
""" creates the required hash """ |
if not fileExists(fName, dire):
return -1
readSize = readSize * 1024 # bytes to be read
fName = os.path.join(dire, fName) # name coupled with path
with open(fName, 'rb') as f:
size = os.path.getsize(fName)
if size < readSize * 2:
return -1
data = f.read(readS... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_file(fName, time, dire=pDir()):
""" download the required subtitle """ |
# hash
gen_hash = get_hash(fName, 64, dire)
if gen_hash == -1:
return -1
# making request
user_agent = {'User-agent': 'SubDB/1.0 (sub/0.1; http://github.com/leosartaj/sub)'}
param = {'action': 'download', 'hash': gen_hash, 'language': 'en'} # Specification for the request
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_downloaded(dwn, fName, verbose=False):
""" print for downloaded file """ |
if verbose:
if dwn == 200:
fName, fExt = os.path.splitext(fName)
print 'Downloaded ' + fName + '.srt'
return True
elif dwn != -1:
print 'Tried downloading got ' + str(dwn) + ' for ' + fName
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 download(name, options):
""" download a file or all files in a directory """ |
dire = os.path.dirname(name) # returns the directory name
fName = os.path.basename(name) # returns the filename
fNameOnly, fExt = os.path.splitext(fName)
dwn = 0
if fileExists(fName, dire) and not fileExists((fNameOnly + '.srt'), dire): # skip if already downloaded
if file_downloaded(down... |
<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_dateobject_to_string(x):
"""Convert a Pandas Timestamp object or datetime object to 'YYYY-MM-DD' string Parameters x : str, list, tuple, numpy.ndarray,... |
import numpy as np
import pandas as pd
def proc_elem(e):
try:
return e.strftime("%Y-%m-%d")
except Exception as e:
print(e)
return None
def proc_list(x):
return [proc_elem(e) for e in x]
def proc_ndarray(x):
tmp = proc_list(list... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def AND(*args, **kwargs):
""" ALL args must not raise an exception when called incrementally. If an exception is specified, raise it, otherwise raise the callabl... |
for arg in args:
try:
arg()
except CertifierError as e:
exc = kwargs.get('exc', None)
if exc is not None:
raise exc(e)
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def NAND(*args, **kwargs):
""" ALL args must raise an exception when called overall. Raise the specified exception on failure OR the first exception. :params ite... |
errors = []
for arg in args:
try:
arg()
except CertifierError as e:
errors.append(e)
if (len(errors) != len(args)) and len(args) > 1:
exc = kwargs.get(
'exc',
CertifierValueError('Expecting no certified values'),
)
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def XOR(a, b, exc=CertifierValueError('Expected at least one certified value')):
""" Only one arg must not raise a Certifier exception when called overall. Raise... |
errors = []
for certifier in [a, b]:
try:
certifier()
except CertifierError as e:
errors.append(e)
if len(errors) != 1:
if exc is not None:
raise exc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, verbose, config):
""" IPS Vagrant Management Utility """ |
assert isinstance(ctx, Context)
# Set up the logger
verbose = verbose if (verbose <= 3) else 3
log_levels = {1: logging.WARN, 2: logging.INFO, 3: logging.DEBUG}
log_level = log_levels[verbose]
ctx.log = logging.getLogger('ipsv')
ctx.log.setLevel(log_level)
# Console logger
console... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def db(self):
""" Get a loaded database session """ |
if self.database is NotImplemented:
self.database = Session
return self.database |
<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_login(self, use_session=True):
""" Get an active login session @param use_session: Use a saved session file if available @type use_session: bool """ |
# Should we try and return an existing login session?
if use_session and self._login.check():
self.cookiejar = self._login.cookiejar
return self.cookiejar
# Prompt the user for their login credentials
username = click.prompt('IPS Username')
password = cl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_commands(self, ctx):
""" List CLI commands @type ctx: Context @rtype: list """ |
commands_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'commands')
command_list = [name for __, name, ispkg in pkgutil.iter_modules([commands_path]) if ispkg]
command_list.sort()
return command_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_command(self, ctx, name):
""" Get a bound command method @type ctx: Context @param name: Command name @type name: str @rtype: object """ |
try:
mod = importlib.import_module('ips_vagrant.commands.{name}'.format(name=name))
return mod.cli
except (ImportError, AttributeError):
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging.""" |
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", 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 _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument.""" |
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(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 _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required.""" |
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename)) |
<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_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name.""" |
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename) |
<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_prospector_on(filenames, tools, disabled_linters, show_lint_files, ignore_codes=None):
"""Run prospector on filename, using the specified tools. This fu... |
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't li... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _run_prospector(filename, stamp_file_name, disabled_linters, show_lint_files):
"""Run prospector.""" |
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be... |
<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_pyroma(setup_file, show_lint_files):
"""Run pyroma.""" |
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ 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 _run_polysquare_style_linter(matched_filenames, cache_dir, show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames.""" |
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = M... |
<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_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames.""" |
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = err... |
<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_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames.""" |
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stde... |
<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_cache_dir(candidate):
"""Get the current cache directory.""" |
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_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 _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions.""" |
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _file_lines(self, filename):
"""Get lines for filename, caching opened files.""" |
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline. The suppression format is suppress(CODE1,CODE2,CODE3) etc.... |
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_md_files(self):
"""Get all markdown files.""" |
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)]) |
<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_files_to_lint(self, external_directories):
"""Get files to lint.""" |
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize_options(self):
# suppress(unused-function) """Set all options to their initial values.""" |
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 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 normalize_pattern(pattern):
"""Converts backslashes in path patterns to forward slashes. Doesn't normalize regular expressions - they may contain escapes. ""... |
if not (pattern.startswith('RE:') or pattern.startswith('!RE:')):
pattern = _slashes.sub('/', pattern)
if len(pattern) > 1:
pattern = pattern.rstrip('/')
return pattern |
<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(self, pat, fun):
r"""Add a pattern and replacement. The pattern must not contain capturing groups. The replacement might be either a string template in w... |
self._pat = None
self._pats.append(pat)
self._funs.append(fun) |
<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_replacer(self, replacer):
r"""Add all patterns from another replacer. All patterns and replacements from replacer are appended to the ones already define... |
self._pat = None
self._pats.extend(replacer._pats)
self._funs.extend(replacer._funs) |
<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_pattern_valid(pattern):
"""Returns True if pattern is valid. :param pattern: Normalized pattern. is_pattern_valid() assumes pattern to be normalized. see:... |
result = True
translator = Globster.pattern_info[Globster.identify(pattern)]["translator"]
tpattern = '(%s)' % translator(pattern)
try:
re_obj = lazy_regex.lazy_compile(tpattern, re.UNICODE)
re_obj.search("") # force compile
except Exception as 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 put(self, device_id: int) -> Device: """ Updates the Device Resource with the name. """ |
device = self._get_or_abort(device_id)
self.update(device)
session.commit()
session.add(device)
return device |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xross_listener(http_method=None, **xross_attrs):
"""Instructs xross to handle AJAX calls right from the moment it is called. This should be placed in a view ... |
handler = currentframe().f_back.f_locals['request']._xross_handler
handler.set_attrs(**xross_attrs)
if http_method is not None:
handler.http_method = http_method
handler.dispatch() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xross_view(*op_functions):
"""This decorator should be used to decorate application views that require xross functionality. :param list op_functions: operati... |
operations_dict = construct_operations_dict(*op_functions)
def get_request(src):
return src if isinstance(src, HttpRequest) else None
def dec_wrapper(func):
def func_wrapper(*fargs, **fkwargs):
request_idx = getattr(func, '_req_idx', None)
if request_idx is 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 intercept(actions: dict={}):
""" Decorates a function and handles any exceptions that may rise. Args: actions: A dictionary ``<exception type>: <action>``. A... |
for action in actions.values():
if type(action) is not returns and type(action) is not raises:
raise InterceptorError('Actions must be declared as `returns` or `raises`')
def decorated(f):
def wrapped(*args, **kargs):
try:
return f(*args, **kargs)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extend(self, *bindings):
""" Append the given bindings to this keymap. Arguments: *bindings (Binding):
Bindings to be added. Returns: Keymap: self """ |
self._bindings.extend(self._preprocess(bindings))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def when(self, key):
""" Specify context, i.e. condition that must be met. Arguments: key (str):
Name of the context whose value you want to query. Returns: Con... |
ctx = Context(key, self)
self.context.append(ctx)
return ctx |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _split_source_page(self, path):
"""Split the source file texts by triple-dashed lines. shit code """ |
with codecs.open(path, "rb", "utf-8") as fd:
textlist = fd.readlines()
metadata_notation = "---\n"
if textlist[0] != metadata_notation:
logging.error(
"{} first line must be triple-dashed!".format(path)
)
sys.exit(1)
meta... |
<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_feed_data(self, file_paths):
""" get data to display in feed file """ |
rv = {}
for i in file_paths:
# TODO(crow): only support first category
_ = i.split('/')
category = _[-2]
name = _[-1].split('.')[0]
page_config, md = self._get_config_and_content(i)
parsed_md = tools.parse_markdown(md, self.site_co... |
<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_feed(self, feed_data):
""" render feed file with data """ |
atom_feed = self._render_html('atom.xml', feed_data)
feed_path = os.path.join(os.getcwd(), 'public', 'atom.xml')
with codecs.open(feed_path, 'wb', 'utf-8') as f:
f.write(atom_feed) |
<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_tz(val):
"""Normalizes all valid ISO8601 time zone variants to the one python will parse. :val: a timestamp string without a timezone, or with a t... |
match = _TZ_RE.match(val)
if match:
ts, tz = match.groups()
if len(tz) == 5:
# If the length of the tz is 5 then it is of the form (+|-)dddd, which is exactly what python
# wants, so just return it.
return ts + tz
if len(tz) == 6:
# If the length of the tz is 6 then it is of 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 node(self, nodeid):
"""Creates a new node with the specified name, with `MockSocket` instances as incoming and outgoing sockets. Returns the implementation o... |
_assert_valid_nodeid(nodeid)
# addr = 'tcp://' + nodeid
# insock = MockInSocket(addEndpoints=lambda endpoints: self.bind(addr, insock, endpoints))
# outsock = lambda: MockOutSocket(addr, self)
return Node(hub=Hub(nodeid=nodeid)) |
<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_label(self):
""" Create label for x and y axis, title and suptitle """ |
outputdict = self.outputdict
xlabel_options = self.kwargs.get("xlabel_options", {})
self.subplot.set_xlabel(
self.kwargs.get("xlabel", "").format(**outputdict),
**xlabel_options)
ylabel_options = self.kwargs.get("ylabel_options", {})
self.subplot.set_ylab... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extant_item(arg, arg_type):
"""Determine if parser argument is an existing file or directory. This technique comes from http://stackoverflow.com/a/11541450/9... |
if arg_type == "file":
if not os.path.isfile(arg):
raise argparse.ArgumentError(
None,
"The file {arg} does not exist.".format(arg=arg))
else:
# File exists so return the filename
return arg
elif arg_type == "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 parse_config_input_output(args=sys.argv):
"""Parse the args using the config_file, input_dir, output_dir pattern Args: args: sys.argv Returns: The populated ... |
parser = argparse.ArgumentParser(
description='Process the input files using the given config')
parser.add_argument(
'config_file',
help='Configuration file.',
metavar='FILE', type=extant_file)
parser.add_argument(
'input_dir',
help='Directory containing 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 parse_config(args=sys.argv):
"""Parse the args using the config_file pattern Args: args: sys.argv Returns: The populated namespace object from parser.parse_a... |
parser = argparse.ArgumentParser(
description='Read in the config file')
parser.add_argument(
'config_file',
help='Configuration file.',
metavar='FILE', type=extant_file)
return parser.parse_args(args[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 cache(self, CachableItem):
"""Updates cache area with latest information """ |
_cachedItem = self.get(CachableItem)
if not _cachedItem:
_dirtyCachedItem = self.mapper.get(CachableItem)
logger.debug("new cachable item added to sql cache area {id: %s, type: %s}", str(_dirtyCachedItem.getId()), str(_dirtyCachedItem.__class__))
cached_item = self.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 format_json(item, **kwargs):
""" formats a datatype object to a json value """ |
try:
json.dumps(item.value)
return item.value
except TypeError:
if 'time' in item.class_type.lower() \
or 'date' in item.class_type.lower():
return item.value.isoformat()
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_sparql(item, dt_format='turtle', **kwargs):
""" Formats a datatype value to a SPARQL representation args: item: the datatype object dt_format: the ret... |
try:
rtn_val = json.dumps(item.value)
rtn_val = item.value
except:
if 'time' in item.class_type.lower() \
or 'date' in item.class_type.lower():
rtn_val = item.value.isoformat()
else:
rtn_val = str(item.value)
if hasattr(item, "datatype... |
<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(self, method="sparql", dt_format="turtle"):
""" Rormats the value in various formats args: method: ['sparql', 'json', 'pyuri'] dt_format: ['turtle','... |
try:
return __FORMAT_OPTIONS__[method](self, dt_format=dt_format)
except KeyError:
raise NotImplementedError("'{}' is not a valid format method"
"".format(method)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bind(self, prefix, namespace, *args, **kwargs):
""" Extends the function to add an attribute to the class for each added namespace to allow for use of dot no... |
# RdfNamespace(prefix, namespace, **kwargs)
setattr(self, prefix, RdfNamespace(prefix, namespace, **kwargs))
if kwargs.pop('calc', True):
self.__make_dicts__ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def prefix(self, format="sparql"):
''' Generates a string of the rdf namespaces listed used in the
framework
format: "sparql" or "turtle"
'''
lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3]))
lg.setLevel(self.log_level)
_return_str = ""... |
<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, filepath, file_encoding=None):
""" Reads the the beginning of a turtle file and sets the prefix's used in that file and sets the prefix attribute ... |
with open(filepath, encoding=file_encoding) as inf:
for line in inf:
current_line = str(line).strip()
if current_line.startswith("@prefix"):
self._add_ttl_ns(current_line.replace("\n",""))
elif len(current_line) > 10:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dict_load(self, ns_dict):
""" Reads a dictionary of namespaces and binds them to the manager Args: ns_dict: dictionary with the key as the prefix and the val... |
for prefix, uri in ns_dict.items():
self.bind(prefix, uri, override=False, calc=False)
self.__make_dicts__ |
<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_ttl_ns(self, line):
""" takes one prefix line from the turtle file and binds the namespace to the class Args: line: the turtle prefix line string """ |
lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3]))
lg.setLevel(self.log_level)
lg.debug("line:\n%s", line)
line = str(line).strip()
# if the line is not a prefix line exit
if line is None or line == 'none' or line == '' \
or not line.lowe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def del_ns(self, namespace):
""" will remove a namespace ref from the manager. either Arg is optional. args: namespace: prefix, string or Namespace() to remove "... |
# remove the item from the namespace dict
namespace = str(namespace)
attr_name = None
if hasattr(self, namespace):
delattr(self, namespace) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.