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 path_exists_or_creatable_portable(pathname: str) -> bool: """OS-portable check for whether current path exists or is creatable. This function is guaranteed to... |
try:
# To prevent "os" module calls from raising undesirable exceptions on
# invalid pathnames, is_pathname_valid() is explicitly called first.
return is_pathname_valid(pathname) and (
os.path.exists(pathname) or is_path_sibling_creatable(pathname))
# Report failure on non-f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Q(name):
"""Gets a variable from the current sketch. Processing has a number of methods and variables with the same name, 'mousePressed' for example. This al... |
retval = PApplet.getDeclaredField(name).get(Sketch.get_instance())
if isinstance(retval, (long, int)):
return float(retval)
else:
return retval |
<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_source(link):
""" Return source of the `link` whether it is filename or url. Args: link (str):
Filename or URL. Returns: str: Content. Raises: UserWarn... |
if link.startswith("http://") or link.startswith("https://"):
down = httpkie.Downloader()
return down.download(link)
if os.path.exists(link):
with open(link) as f:
return f.read()
raise UserWarning("html: '%s' is neither URL or data!" % link) |
<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_config_item(item, dirname):
""" Process one item from the configuration file, which contains multiple items saved as dictionary. This function reads... |
item = copy.deepcopy(item)
html = item.get("html", None)
if not html:
raise UserWarning("Can't find HTML source for item:\n%s" % str(item))
# process HTML link
link = html if "://" in html else os.path.join(dirname, html)
del item["html"]
# replace $name with the actual name of 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 read_config(file_name):
""" Read YAML file with configuration and pointers to example data. Args: file_name (str):
Name of the file, where the configuration... |
dirname = os.path.dirname(
os.path.abspath(file_name)
)
dirname = os.path.relpath(dirname)
# create utf-8 strings, not unicode
def custom_str_constructor(loader, node):
return loader.construct_scalar(node).encode('utf-8')
yaml.add_constructor(u'tag:yaml.org,2002:str', custom_st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hash(value, arg):
""" Returns a hex-digest of the passed in value for the hash algorithm given. """ |
arg = str(arg).lower()
if sys.version_info >= (3,0):
value = value.encode("utf-8")
if not arg in get_available_hashes():
raise TemplateSyntaxError("The %s hash algorithm does not exist. Supported algorithms are: %" % (arg, get_available_hashes()))
try:
f = getattr(hashlib, arg)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def paginator(context, adjacent_pages=2):
"""
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displa... |
current_page = context.get('page')
paginator = context.get('paginator')
if not paginator:
return
pages = paginator.num_pages
current_range = range(current_page - adjacent_pages, current_page + adjacent_pages + 1)
page_numbers = [n for n in current_range if n > 0 and n <... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_headers_link(headers):
"""Returns the parsed header links of the response, if any.""" |
header = CaseInsensitiveDict(headers).get('link')
l = {}
if header:
links = parse_link(header)
for link in links:
key = link.get('rel') or link.get('url')
l[key] = link
return 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 run(self, cmd, timeout=None, key=None):
""" Run a command on the phablet device using ssh :param cmd: a list of strings to execute as a command :param timeou... |
if not isinstance(cmd, list):
raise TypeError("cmd needs to be a list")
if not all(isinstance(item, str) for item in cmd):
raise TypeError("cmd needs to be a list of strings")
self.connect(timeout, key)
return self._run_ssh(cmd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, timeout=None, key=None):
""" Perform one-time setup procedure. :param timeout: a timeout (in seconds) for device discovery :param key: a path t... |
if self.port is not None:
return
self._wait_for_device(timeout)
self._setup_port_forwarding()
self._purge_known_hosts_entry()
self._copy_ssh_key(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 FromType(name, otype):
""" ValueOption subclasses factory, creates a convenient option to store data from a given Type. attribute precedence : * ``|attrs| > ... |
if otype.attrs is not None and len(otype.attrs):
raise NotImplementedError("for otype, options can't have attributs")
#return VectorField(ftype)
elif otype.uniq:
return SetOption(name, otype)
elif otype.multi:
#XXX: dbl check needed?
#... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upsert_object_property(self, identifier, properties, ignore_constraints=False):
"""Manipulate an object's property set. Inserts or updates properties in give... |
# Retrieve the object with the gievn identifier. This is a (sub-)class
# of ObjectHandle
obj = self.get_object(identifier)
if not obj is None:
# Modify property set of retrieved object handle. Raise exception if
# and of the upserts is not valid.
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 delete_object(self, identifier, erase=False):
"""Delete the entry with given identifier in the database. Returns the handle for the deleted object or None if... |
# Get object to ensure that it exists.
db_object = self.get_object(identifier)
# Set active flag to False if object exists.
if db_object is None:
return None
# Check whether the read-only property is set to true
if PROPERTY_READONLY in db_object.properties:
... |
<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_object(self, identifier, include_inactive=False):
"""Retrieve object with given identifier from the database. Parameters identifier : string Unique objec... |
# Find all objects with given identifier. The result size is expected
# to be zero or one
query = {'_id': identifier}
if not include_inactive:
query['active'] = True
cursor = self.collection.find(query)
if cursor.count() > 0:
return self.from_dict... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert_object(self, db_object):
"""Create new entry in the database. Parameters db_object : (Sub-class of)ObjectHandle """ |
# Create object using the to_dict() method.
obj = self.to_dict(db_object)
obj['active'] = True
self.collection.insert_one(obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_objects(self, query=None, limit=-1, offset=-1):
"""List of all objects in the database. Optinal parameter limit and offset for pagination. A dictionary ... |
result = []
# Build the document query
doc = {'active' : True}
if not query is None:
for key in query:
doc[key] = query[key]
# Iterate over all objects in the MongoDB collection and add them to
# the result
coll = self.collection.find(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self, db_obj):
"""Create a Json-like dictionary for objects managed by this object store. Parameters db_obj : (Sub-class of)ObjectHandle Returns ----... |
# Base Json serialization for database objects
return {
'_id' : db_obj.identifier,
'timestamp' : str(db_obj.timestamp.isoformat()),
'properties' : db_obj.properties} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile_msg_payload(self, invite):
""" Determine recipient, message content, return it as a dict that can be Posted to the message sender """ |
self.l.info("Compiling the outbound message payload")
update_invite = False
# Determine the recipient address
if "to_addr" in invite.invite:
to_addr = invite.invite["to_addr"]
else:
update_invite = True
to_addr = get_identity_address(invite.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 send_message(self, payload):
""" Create a post request to the message sender """ |
self.l.info("Creating outbound message request")
result = ms_client.create_outbound(payload)
self.l.info("Created outbound message request")
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 run(self, invite_id, **kwargs):
""" Sends a message about service rating to invitee """ |
self.l = self.get_logger(**kwargs)
self.l.info("Looking up the invite")
invite = Invite.objects.get(id=invite_id)
msg_payload = self.compile_msg_payload(invite)
result = self.send_message(msg_payload)
self.l.info("Creating task to update invite after send")
post_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self, key):
""" Stop a concurrent operation. This gets the concurrency limiter for the given key (creating it if necessary) and stops a concurrent opera... |
self._get_limiter(key).stop()
self._cleanup_limiter(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 fields_for(context, form, template="includes/form_fields.html"):
""" Renders fields for a form with an optional template choice. """ |
context["form_for_fields"] = form
return get_template(template).render(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 sort_by(items, attr):
""" General sort filter - sorts by either attribute or key. """ |
def key_func(item):
try:
return getattr(item, attr)
except AttributeError:
try:
return item[attr]
except TypeError:
getattr(item, attr) # Reraise AttributeError
return sorted(items, key=key_func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gravatar_url(email, size=32):
""" Return the full URL for a Gravatar given an email hash. """ |
bits = (md5(email.lower().encode("utf-8")).hexdigest(), size)
return "//www.gravatar.com/avatar/%s?s=%s&d=identicon&r=PG" % bits |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def metablock(parsed):
""" Remove HTML tags, entities and superfluous characters from meta blocks. """ |
parsed = " ".join(parsed.replace("\n", "").split()).replace(" ,", ",")
return escape(strip_tags(decode_entities(parsed))) |
<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_for(context, current_page, page_var="page", exclude_vars=""):
""" Include the pagination template and data for persisting querystring in paginatio... |
querystring = context["request"].GET.copy()
exclude_vars = [v for v in exclude_vars.split(",") if v] + [page_var]
for exclude_var in exclude_vars:
if exclude_var in querystring:
del querystring[exclude_var]
querystring = querystring.urlencode()
return {
"current_page": c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_form(context, search_model_names=None):
""" Includes the search form with a list of models to use as choices for filtering the search by. Models shoul... |
template_vars = {
"request": context["request"],
}
if not search_model_names or not settings.SEARCH_MODEL_CHOICES:
search_model_names = []
elif search_model_names == "all":
search_model_names = list(settings.SEARCH_MODEL_CHOICES)
else:
search_model_names = search_mod... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def richtext_filters(content):
""" Takes a value edited via the WYSIWYG editor, and passes it through each of the functions specified by the RICHTEXT_FILTERS set... |
for filter_name in settings.RICHTEXT_FILTERS:
filter_func = import_dotted_path(filter_name)
content = filter_func(content)
return content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def editable(parsed, context, token):
""" Add the required HTML to the parsed content for in-line editing, such as the icon and edit form if the object is deemed... |
def parse_field(field):
field = field.split(".")
obj = context.get(field.pop(0), None)
attr = field.pop()
while field:
obj = getattr(obj, field.pop(0))
if callable(obj):
# Allows {% editable page.get_content_model.content %}
ob... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def try_url(url_name):
""" Mimics Django's ``url`` template tag but fails silently. Used for url names in admin templates as these won't resolve when admin tests... |
from warnings import warn
warn("try_url is deprecated, use the url tag with the 'as' arg instead.")
try:
url = reverse(url_name)
except NoReverseMatch:
return ""
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def admin_dropdown_menu(context):
""" Renders the app list for the admin dropdown menu navigation. """ |
template_vars = context.flatten()
user = context["request"].user
if user.is_staff:
template_vars["dropdown_menu_app_list"] = admin_app_list(
context["request"])
if user.is_superuser:
sites = Site.objects.all()
else:
try:
sites = 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 dashboard_column(context, token):
""" Takes an index for retrieving the sequence of template tags from ``yacms.conf.DASHBOARD_TAGS`` to render into the admin... |
column_index = int(token.split_contents()[1])
output = []
for tag in settings.DASHBOARD_TAGS[column_index]:
t = Template("{%% load %s %%}{%% %s %%}" % tuple(tag.split(".")))
output.append(t.render(context))
return "".join(output) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raise_error(self, message='', errors=None, field_name=None):
"""Raises a ValidationError. """ |
field_name = field_name if field_name else self.field_name
raise ValidationError(message, errors=errors, field_name=field_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(self, value):
"""Make sure that value is of the right type """ |
if not isinstance(value, self.nested_klass):
self.raise_error('NestedClass is of the wrong type: {0} vs expected {1}'
.format(value.__class__.__name__, self.nested_klass.__name__))
super(NestedDocumentField, self).validate(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 validate(self, value):
"""Make sure that the inspected value is of type `list` or `tuple` """ |
if not isinstance(value, (list, tuple)) or isinstance(value, str_types):
self.raise_error('Only lists and tuples may be used in the ListField vs provided {0}'
.format(type(value).__name__))
super(ListField, self).validate(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 validate(self, value):
"""Make sure that the inspected value is of type `dict` """ |
if not isinstance(value, dict):
self.raise_error('Only Python dict may be used in the DictField vs provided {0}'
.format(type(value).__name__))
super(DictField, self).validate(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 install_cache(expire_after=12 * 3600, cache_post=False):
""" Patches the requests library with requests_cache. """ |
allowable_methods = ['GET']
if cache_post:
allowable_methods.append('POST')
requests_cache.install_cache(
expire_after=expire_after,
allowable_methods=allowable_methods) |
<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_url(url, back_off=True, **kwargs):
""" Get the content of a URL and return a file-like object. back_off=True provides retry """ |
if back_off:
return _download_with_backoff(url, as_file=True, **kwargs)
else:
return _download_without_backoff(url, as_file=True, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _download_without_backoff(url, as_file=True, method='GET', **kwargs):
""" Get the content of a URL and return a file-like object. """ |
# Make requests consistently hashable for caching.
# 'headers' is handled by requests itself.
# 'cookies' and 'proxies' contributes to headers.
# 'files' and 'json' contribute to data.
for k in ['data', 'params']:
if k in kwargs and isinstance(kwargs[k], dict):
kwargs[k] = Order... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_url_in_cache(*args, **kwargs):
""" Return True if request has been cached or False otherwise. """ |
# Only include allowed arguments for a PreparedRequest.
allowed_args = inspect.getargspec(
requests.models.PreparedRequest.prepare).args
# self is in there as .prepare() is a method.
allowed_args.remove('self')
kwargs_cleaned = {}
for key, value in dict(kwargs).items():
if 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 block_idxmat_sets(idxmat, b):
"""Reshapes idxmat into the idx vectors for the training set and validation set Parameters: idxmat : ndarray Matrix with N shuf... |
import numpy as np
idx_train = idxmat[:, [c for c in range(idxmat.shape[1]) if c is not b]]
idx_train = idx_train.reshape((np.prod(idx_train.shape),))
return idx_train, idxmat[:, b] |
<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_logging(parser, log_format=LOG_FORMAT, log_level=LOG_LEVEL, color=True):
"""Configures the `argparse.ArgumentParser` with arguments to configure logging.... |
parser.set_defaults(log_level=log_level)
parser.add_argument('-v', dest='log_level', action=_LogLevelAddAction, const=1, help='use more verbose logging (stackable)')
parser.add_argument('-q', dest='log_level', action=_LogLevelAddAction, const=-1, help='use less verbose logging (stackable)')
root_logge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assertHeader(self, name, value=None, *args, **kwargs):
""" Returns `True` if ``name`` was in the headers and, if ``value`` is True, whether or not the values... |
return name in self.raw_headers and (
True if value is None else self.raw_headers[name] == 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 ConfigureLazyWorkers(self):
""" Lazy workers are instances that are running and reachable but failed to register with the cldb to join the mapr cluster. This... |
lazy_worker_instances = self.__GetMissingWorkers()
if not lazy_worker_instances:
return
reachable_states = self.__AreInstancesReachable(lazy_worker_instances)
reachable_instances = [t[0] for t in zip(lazy_worker_instances,
reachable_states) if t[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 __StartMaster(self):
""" Starts a master node, configures it, and starts services. """ |
num_masters = len(self.cluster.get_instances_in_role("master", "running"))
assert(num_masters < 1)
logging.info( "waiting for masters to start")
if self.config.master_on_spot_instances:
self.__LaunchSpotMasterInstances()
else:
self.__LaunchOnDemandMasterInstances()
tim... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __AddWorkers(self, num_to_add):
""" Adds workers evenly across all enabled zones.""" |
# Check preconditions
assert(self.__IsWebUiReady())
zone_to_ips = self.__GetZoneToWorkerIpsTable()
zone_old_new = []
for zone, ips in zone_to_ips.iteritems():
num_nodes_in_zone = len(ips)
num_nodes_to_add = 0
zone_old_new.append((zone, num_nodes_in_zone, num_n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __IpsToServerIds(self):
""" Get list of mapping of ip address into a server id""" |
master_instance = self.__GetMasterInstance()
assert(master_instance)
retval, response = self.__RunMaprCli('node list -columns id')
ip_to_id = {}
for line_num, line in enumerate(response.split('\n')):
tokens = line.split()
if len(tokens) == 3 and tokens[0] != 'id':
instan... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contents(self):
""" This method downloads the contents of the file represented by a `GettFile` object's metadata. Input: * None Output: * A byte stream **NOT... |
response = GettRequest().get("/files/%s/%s/blob" % (self.sharename, self.fileid))
return response.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 thumbnail(self):
""" This method returns a thumbnail representation of the file if the data is a supported graphics format. Input: * None Output: * A byte st... |
response = GettRequest().get("/files/%s/%s/blob/thumb" % (self.sharename, self.fileid))
return response.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 send_data(self, **kwargs):
""" This method transmits data to the Gett service. Input: * ``put_url`` A PUT url to use when transmitting the data (required) * ... |
put_url = None
if 'put_url' in kwargs:
put_url = kwargs['put_url']
else:
put_url = self.put_upload_url
if 'data' not in kwargs:
raise AttributeError("'data' parameter is required")
if not put_url:
raise AttributeError("'put_url' ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def __signal(self, sig, verbose=None):
'''
Helper class preventing code duplication..
:param sig:
Signal to use (e.g. "HUP", "ALRM")
:param verbose:
Overwrite :func:`photon.Photon.m`'s `verbose`
:returns:
|kill_return| with specified `pid`
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def linreg_mle(y, X, algorithm='Nelder-Mead', debug=False):
"""MLE for Linear Regression Model Parameters: y : ndarray target variable with N observations X : nd... |
import numpy as np
import scipy.stats as sstat
import scipy.optimize as sopt
def objective_nll_linreg(theta, y, X):
yhat = np.dot(X, theta[:-1]) # =X*beta
return -1.0 * sstat.norm.logpdf(y, loc=yhat, scale=theta[-1]).sum()
# check eligible algorithm
if algorithm not in ('Neld... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fill(self, paths):
""" Initialise the tree. paths is a list of strings where each string is the relative path to some file. """ |
for path in paths:
tree = self.tree
parts = tuple(path.split('/'))
dir_parts = parts[:-1]
built = ()
for part in dir_parts:
self.cache[built] = tree
built += (part, )
parent = tree
tree =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, prefix, name):
""" Remove a path from the tree prefix is a tuple of the parts in the dirpath name is a string representing the name of the file ... |
tree = self.cache.get(prefix, empty)
if tree is empty:
return False
if name not in tree.files:
return False
tree.files.remove(name)
self.remove_folder(tree, list(prefix))
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_folder(self, tree, prefix):
""" Used to remove any empty folders If this folder is empty then it is removed. If the parent is empty as a result, then ... |
while True:
child = tree
tree = tree.parent
if not child.folders and not child.files:
del self.cache[tuple(prefix)]
if tree:
del tree.folders[prefix.pop()]
if not tree or tree.folders or tree.files:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_manage(user, semester=None, pool=None, any_pool=False):
""" Whether a user is allowed to manage a workshift semester. This includes the current workshift... |
if semester and user in semester.workshift_managers.all():
return True
if Manager and Manager.objects.filter(
incumbent__user=user, workshift_manager=True,
).count() > 0:
return True
if pool and pool.managers.filter(incumbent__user=user).count() > 0:
return True
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_year_season(day=None):
""" Returns a guess of the year and season of the current semester. """ |
if day is None:
day = date.today()
year = day.year
if day.month > 3 and day.month <= 7:
season = Semester.SUMMER
elif day.month > 7 and day.month <= 10:
season = Semester.FALL
else:
season = Semester.SPRING
if day.month > 10:
year += 1
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 get_semester_start_end(year, season):
""" Returns a guess of the start and end dates for given semester. """ |
if season == Semester.SPRING:
start_month, start_day = 1, 20
end_month, end_day = 5, 17
elif season == Semester.SUMMER:
start_month, start_day = 5, 25
end_month, end_day = 8, 16
else:
start_month, start_day = 8, 24
end_month, end_day = 12, 20
return date... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randomly_assign_instances(semester, pool, profiles=None, instances=None):
""" Randomly assigns workshift instances to profiles. Returns ------- list of works... |
if profiles is None:
profiles = WorkshiftProfile.objects.filter(semester=semester)
if instances is None:
instances = WorkshiftInstance.objects.filter(
Q(info__pool=pool) |
Q(weekly_workshift__pool=pool),
workshifter__isnull=True,
closed=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 clear_all_assignments(semester=None, pool=None, shifts=None):
""" Clears all regular workshift assignments. Parameters semester : workshift.models.Semester, ... |
if semester is None:
try:
semester = Semester.objects.get(current=True)
except (Semester.DoesNotExist, Semester.MultipleObjectsReturned):
return []
if pool is None:
pool = WorkshiftPool.objects.get(
semester=semester,
is_primary=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_standings(semester=None, pool_hours=None, moment=None):
""" This function acts to update a list of PoolHours objects to adjust their current standing ... |
if semester is None:
try:
semester = Semester.objects.get(current=True)
except (Semester.DoesNotExist, Semester.MultipleObjectsReturned):
return []
if moment is None:
moment = localtime(now())
if pool_hours is None:
pool_hours = PoolHours.objects.fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset_standings(semester=None, pool_hours=None):
""" Utility function to recalculate workshift standings. This function is meant to only be called from the m... |
if semester is None:
try:
semester = Semester.objects.get(current=True)
except (Semester.DoesNotExist, Semester.MultipleObjectsReturned):
return
if pool_hours is None:
pool_hours = PoolHours.objects.filter(pool__semester=semester)
for hours in pool_hours:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_assigned_hours(semester=None, profiles=None):
""" Utility function to recalculate the assigned workshift hours. This function is meant to only be c... |
if semester is None:
try:
semester = Semester.objects.get(current=True)
except (Semester.DoesNotExist, Semester.MultipleObjectsReturned):
return
if profiles is None:
profiles = WorkshiftProfile.objects.filter(semester=semester)
for profile in profiles:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset_instance_assignments(semester=None, shifts=None):
""" Utility function to reset instance assignments. This function is meant to only be called from the... |
if semester is None:
try:
semester = Semester.objects.get(current=True)
except (Semester.DoesNotExist, Semester.MultipleObjectsReturned):
return
if shifts is None:
shifts = RegularWorkshift.objects.filter(
pool__semester=semester,
)
for 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 pid_exists(pid):
""" Determines if a system process identifer exists in process table. """ |
try:
os.kill(pid, 0)
except OSError as exc:
return exc.errno == errno.EPERM
else:
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def daemonize(pid_file, working_dir, func):
""" Turns the current process into a daemon. `pid_file` File path to use as pid lock file for daemon. `working_dir` W... |
def _fork():
""" Fork a child process.
Returns ``False`` if fork failed; otherwise,
we are inside the new child process.
"""
try:
pid = os.fork()
if pid > 0:
os._exit(0) # exit parent
return True
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 shell_focusd(data_dir):
""" Shells a new instance of a focusd daemon process. `data_dir` Home directory for focusd data. Returns boolean. * Raises ``ValueErr... |
command = 'focusd {0}'.format(data_dir)
# see what event hook plugins are registered
plugins = registration.get_registered(event_hooks=True)
if not plugins: # none registered, bail
raise errors.NoPluginsRegistered
# do any of the plugins need root access?
# if so, wrap command with... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def focusd(task):
""" Forks the current process as a daemon to run a task. `task` ``Task`` instance for the task to run. """ |
# determine if command server should be started
if registration.get_registered(event_hooks=True, root_access=True):
# root event plugins available
start_cmd_srv = (os.getuid() == 0) # must be root
else:
start_cmd_srv = False
# daemonize our current process
_run = 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 _reg_sighandlers(self):
""" Registers signal handlers to this class. """ |
# SIGCHLD, so we shutdown when any of the child processes exit
_handler = lambda signo, frame: self.shutdown()
signal.signal(signal.SIGCHLD, _handler)
signal.signal(signal.SIGTERM, _handler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _drop_privs(self):
""" Reduces effective privileges for this process to that of the task owner. The umask and environment variables are also modified to recr... |
uid = self._task.owner
# get pwd database info for task owner
try:
pwd_info = pwd.getpwuid(uid)
except OSError:
pwd_info = None
# set secondary group ids for user, must come first
if pwd_info:
try:
gids = [g.gr_gid ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shutdown(self):
""" Shuts down the daemon process. """ |
if not self._exited:
self._exited = True
# signal task runner to terminate via SIGTERM
if self._task_runner.is_alive():
self._task_runner.terminate()
# if command server is running, then block until
# task runner completes 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 run(self, start_command_srv):
""" Setup daemon process, start child forks, and sleep until events are signalled. `start_command_srv` Set to ``True`` if comma... |
if start_command_srv:
# note, this must be established *before* the task runner is forked
# so the task runner can communicate with the command server.
# fork the command server
self._command_server.start()
# drop root privileges; command server wi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def running(self):
""" Determines if daemon is active. Returns boolean. """ |
# check if task is active and pid file exists
return (not self._exited and os.path.isfile(self._pidfile)
and self._task.active) |
<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_sigterm(self):
""" Registers SIGTERM signal handler. """ |
_handler = lambda signo, frame: self.shutdown()
signal.signal(signal.SIGTERM, _handler) |
<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):
""" Main process loop. """ |
self._prepare()
while self.running:
if self._run() is False:
break
time.sleep(self._sleep_period)
self.shutdown() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setup_root_plugins(self):
""" Injects a `run_root` method into the registered root event plugins. """ |
def run_root(_self, command):
""" Executes a shell command as root.
`command`
Shell command string.
Returns boolean.
"""
try:
# get lock, so this plugin has exclusive access to command pipe
... |
<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_events(self, shutdown=False):
""" Runs event hooks for registered event plugins. `shutdown` Set to ``True`` to run task_end events; otherwise, run task_... |
# run task_start events, if not ran already
if not self._ran_taskstart:
self._ran_taskstart = True
registration.run_event_hooks('task_start', self._task)
# run events
event = 'task_end' if shutdown else 'task_run'
registration.run_event_hooks(event, sel... |
<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_commands(self):
""" Processes commands received and executes them accordingly. Returns ``True`` if successful, ``False`` if connection closed or ser... |
try:
# poll for data, so we don't block forever
if self._cmd_pipe.poll(1): # 1 sec timeout
payload = self._cmd_pipe.recv_bytes()
if payload:
# segment payload
parts = payload.split('\x80', 2)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_settings(cls, settings):
"""Read Mongodb Source configuration from the provided settings""" |
if not 'mongodb' in settings or not 'collection' in settings or \
settings['mongodb'] == '' or settings['collection'] == '':
raise Exception(
"Erroneous mongodb settings, "
"needs a collection and mongodb setting",
settings)
c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_key(cli, familly, discriminant=None):
"""This function is used to compute a unique key from all connection parametters.""" |
hash_key = hashlib.sha256()
hash_key.update(familly)
hash_key.update(cli.host)
hash_key.update(cli.user)
hash_key.update(cli.password)
if discriminant:
if isinstance(discriminant, list):
for i in discriminant:
if i is not None and i is not 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 override_familly(self, args):
"""Look in the current wrapped object to find a cache configuration to override the current default configuration.""" |
resourceapi = args[0]
cache_cfg = resourceapi.cache
if cache_cfg.has_key('familly'):
self.familly = cache_cfg['familly']
if cache_cfg.has_key('whole_familly'):
self.whole_familly = cache_cfg['whole_familly']
if self.familly is None:
raise Exce... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def friendly_type_name(raw_type: typing.Type) -> str: """ Returns a user-friendly type name :return: user friendly type as string """ |
try:
return _TRANSLATE_TYPE[raw_type]
except KeyError:
LOGGER.error('unmanaged value type: %s', raw_type)
return str(raw_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loads(content):
"""Loads variable definitions from a string.""" |
lines = _group_lines(line for line in content.split('\n'))
lines = [
(i, _parse_envfile_line(line))
for i, line in lines if line.strip()
]
errors = []
# Reject files with duplicate variables (no sane default).
duplicates = _find_duplicates(((i, line[0]) for i, line in 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(self):
""" Loads the configuration and returns it as a dictionary """ |
with open(self.filename, 'r') as f:
self.config = ujson.load(f)
return self.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 set(self, option, value):
""" Sets an option to a value. """ |
if self.config is None:
self.config = {}
self.config[option] = 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 delete(self, option):
""" Deletes an option if exists """ |
if self.config is not None:
if option in self.config:
del self.config[option] |
<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):
""" Saves the configuration """ |
with open(self.filename, 'w') as f:
ujson.dump(self.config, f, indent=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 timestamp(stamp, tolerance=150):
"""Validate timestamp specified by request. See `validate.request` for additional info. Args: stamp: str. Time request was m... |
try:
tolerance = datetime.timedelta(0, tolerance)
timestamp_low = dateutil.parser.parse(stamp)
timestamp_high = timestamp_low + tolerance
now = datetime.datetime.now(timestamp_low.tzinfo)
except ValueError:
return False
return now >= timestamp_low and now <= timesta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signature_cert_chain_url(url):
"""Validate URL specified by SignatureCertChainUrl. See `validate.request` for additional info. Args: url: str. SignatureCertC... |
r = urlparse(url)
if not r.scheme.lower() == 'https':
warnings.warn('Certificate URL scheme is invalid.')
return False
if not r.hostname.lower() == 's3.amazonaws.com':
warnings.warn('Certificate URL hostname is invalid.')
return False
if not os.path.normpath(r.path).star... |
<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(url):
"""Retrieve and parse PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: url: str. SignatureCertChainUrl h... |
try:
pem_data = urlopen(url).read()
except (ValueError, HTTPError):
warnings.warn('Certificate URL is invalid.')
return False
if sys.version >= '3':
try:
pem_data = pem_data.decode()
except(UnicodeDecodeError):
warnings.warn('Certificate enco... |
<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_pem_data(pem_data):
"""Parse PEM-encoded X.509 certificate chain. Args: pem_data: str. PEM file retrieved from SignatureCertChainUrl. Returns: list or... |
sep = '-----BEGIN CERTIFICATE-----'
cert_chain = [six.b(sep + s) for s in pem_data.split(sep)[1:]]
certs = []
load_cert = x509.load_pem_x509_certificate
for cert in cert_chain:
try:
certs.append(load_cert(cert, default_backend()))
except ValueError:
warnings.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cert_chain(certs):
"""Validate PEM-encoded X.509 certificate chain. See `validate.request` for additional info. Args: certs: list. The certificate chain as a... |
if len(certs) < 2:
warnings.warn('Certificate chain contains < 3 certificates.')
return False
cert = certs[0]
today = datetime.datetime.today()
if not today > cert.not_valid_before:
warnings.warn('Certificate Not Before date is invalid.')
return False
if not today <... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signature(cert, sig, body):
"""Validate data request signature. See `validate.request` for additional info. Args: cert: cryptography.hazmat.backends.openssl.... |
body = six.b(body)
sig = base64.decodestring(sig)
padder = padding.PKCS1v15()
public_key = cert.public_key()
try:
public_key.verify(sig, body, padder, hashes.SHA1())
return True
except InvalidSignature:
warnings.warn('Signature verification failed.')
return Fals... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def application_id(self, app_id):
"""Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Ar... |
if self.app_id != app_id:
warnings.warn('Application ID is invalid.')
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sender(self, body, stamp, url, sig):
"""Validate request is from Alexa. Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5. Checking the Sig... |
if not timestamp(stamp):
return False
if self.url != url:
if not signature_cert_chain_url(url):
return False
certs = retrieve(url)
if not certs:
return False
if not cert_chain(certs):
return F... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, app_id=None, body=None, stamp=None, url=None, sig=None):
"""Validate application ID and request is from Alexa.""" |
if self.app_id:
if not self.application_id(app_id):
return False
if (url or sig):
if not (body and stamp and url and sig):
raise ValueError('Unable to validate sender, check arguments.')
else:
if not self.sender(body, ... |
<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_tables_from_files(db_connection):
""" Looks in the current working directory for all required tables. """ |
_log.info('Loading tables from disk to DB.')
sde_dir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'sde')
for sde_file_name in os.listdir(sde_dir_path):
_log.info('Loading the following table: {}'.format(sde_file_name))
sde_file_path = os.path.join(sde_dir_path, sde_f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_connection(connection_details=None):
""" Creates a connection to the MySQL DB. """ |
if connection_details is None:
connection_details = get_default_connection_details()
return MySQLdb.connect(
connection_details['host'],
connection_details['user'],
connection_details['password'],
connection_details['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_default_connection_details():
""" Gets the connection details based on environment vars or Thanatos default settings. :return: Returns a dictionary of co... |
return {
'host': os.environ.get('MYSQL_HOST', '127.0.0.1'),
'user': os.environ.get('MYSQL_USER', 'vagrant'),
'password': os.environ.get('MYSQL_PASSWORD', 'vagrant'),
'database': os.environ.get('MYSQL_DB', 'thanatos'),
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unwrap_or(self, default: U) -> Union[T, U]: """ Returns the contained value or ``default``. Args: default: The default value. Returns: The contained value if ... |
return self.unwrap_or_else(lambda: default) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.