text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_site_config(name):
"""Load and return site configuration as a dict.""" |
return _load_config_json(
os.path.join(
CONFIG_PATH,
CONFIG_SITES_PATH,
name + CONFIG_EXT
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_charsets(self):
""" Overridden function for Phylip dataset as the content is different and goes into a separate file. """ |
count_start = 1
out = ''
for gene_code, lengths in self.data.gene_codes_and_lengths.items():
count_end = lengths[0] + count_start - 1
formatted_line = self.format_charset_line(gene_code, count_start, count_end)
converted_line = formatted_line.replace(' cha... |
<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_date(cls, date):
""" Returns a Month instance from the given datetime.date or datetime.datetime object """ |
try:
date = date.date()
except AttributeError:
pass
return cls(date.year, date.month) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def rebuild(self, **kwargs):
'''Repopulate the node-tracking data structures. Shouldn't
really ever be needed.
'''
self.nodes = []
self.node_types = []
self.id_dict = {}
self.type_dict = {}
self.add_node(self.root) |
<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_search_kwarg_types(self, kwargs):
'''Checks that every element of kwargs is a valid type in this tree.'''
for key in kwargs:
if key not in self.node_types:
raise TypeError("Invalid search type: {}".format(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 average(x):
""" Return a numpy array of column average. It does not affect if the array is one dimension Parameters x : ndarray A numpy array instance Return... |
if x.ndim > 1 and len(x[0]) > 1:
return np.average(x, axis=1)
return x |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mean(x):
""" Return a numpy array of column mean. It does not affect if the array is one dimension Parameters x : ndarray A numpy array instance Returns ----... |
if x.ndim > 1 and len(x[0]) > 1:
return np.mean(x, axis=1)
return x |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def median(x):
""" Return a numpy array of column median. It does not affect if the array is one dimension Parameters x : ndarray A numpy array instance Returns ... |
if x.ndim > 1 and len(x[0]) > 1:
return np.median(x, axis=1)
return x |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def variance(x):
""" Return a numpy array of column variance Parameters x : ndarray A numpy array instance Returns ------- ndarray A 1 x n numpy array instance o... |
if x.ndim > 1 and len(x[0]) > 1:
return np.var(x, axis=1)
return np.var(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def standard_deviation(x):
""" Return a numpy array of column standard deviation Parameters x : ndarray A numpy array instance Returns ------- ndarray A 1 x n nu... |
if x.ndim > 1 and len(x[0]) > 1:
return np.std(x, axis=1)
return np.std(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def confidential_interval(x, alpha=0.98):
""" Return a numpy array of column confidential interval Parameters x : ndarray A numpy array instance alpha : float Al... |
from scipy.stats import t
if x.ndim == 1:
df = len(x) - 1
# calculate positive critical value of student's T distribution
cv = t.interval(alpha, df)
# calculate sample standard distribution
std = np.std(x)
else:
# calculate degree of freedom
df = len(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simple_moving_matrix(x, n=10):
""" Create simple moving matrix. Parameters x : ndarray A numpy array n : integer The number of sample points used to make ave... |
if x.ndim > 1 and len(x[0]) > 1:
x = np.average(x, axis=1)
h = n / 2
o = 0 if h * 2 == n else 1
xx = []
for i in range(h, len(x) - h):
xx.append(x[i-h:i+h+o])
return np.array(xx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simple_moving_average(x, n=10):
""" Calculate simple moving average Parameters x : ndarray A numpy array n : integer The number of sample points used to make... |
if x.ndim > 1 and len(x[0]) > 1:
x = np.average(x, axis=1)
a = np.ones(n) / float(n)
return np.convolve(x, a, 'valid') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_available_port():
"""Find an available port. Simple trick: open a socket to localhost, see what port was allocated. Could fail in highly concurrent setu... |
s = socket.socket()
s.bind(('localhost', 0))
_address, port = s.getsockname()
s.close()
return port |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_file(self, needle, candidates):
"""Find the first directory containing a given candidate file.""" |
for candidate in candidates:
fullpath = os.path.join(candidate, needle)
if os.path.isfile(fullpath):
return fullpath
raise PathError("Unable to locate file %s; tried %s" % (needle, candidates)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _poll_slapd(self, timeout=DEFAULT_STARTUP_DELAY):
"""Poll slapd port until available.""" |
begin = time.time()
time.sleep(0.5)
while time.time() < begin + timeout:
if self._process.poll() is not None:
raise RuntimeError("LDAP server has exited before starting listen.")
s = socket.socket()
try:
s.connect(('localhost... |
<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_users(self):
''' a method to list all the user ids of all users in the bucket '''
# construct url
url = self.bucket_url + '/_user/'
# send request and unwrap response
response = requests.get(url)
response = response.json()
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create(self, doc_details):
'''
a method to create a new document in the collection
:param doc_details: dictionary with document details and user id value
:return: dictionary with document details and _id and _rev values
'''
# https://developer.couchbase... |
<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):
'''
a method to remove the entire bucket from the database
:return: string with confirmation message
'''
# https://developer.couchbase.com/documentation/mobile/1.5/references/sync-gateway/admin-rest-api/index.html#/database/delete__db__
title =... |
<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_chart(self):
"""Write color palette to Altair Chart. """ |
encoding, properties = {}, {}
if self.orientation == "horizontal":
# Set the axis
encoding["x"] = alt.X(
"hex",
axis=None,
scale=alt.Scale(zero=False, padding=0)
)
# Set the rectangle size.
pro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _repr_mimebundle_(self, *args, **kwargs):
"""Return a MIME bundle for display in Jupyter frontends.""" |
chart = self.to_chart()
dct = chart.to_dict()
return alt.renderers.get()(dct) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _enter_newline(self):
""" Remove the trailing spaces in the current line, and then mark that the leading spaces of the next line need to be removed. .. seeal... |
last_text_idx = self._last_text_idx
if last_text_idx >= 0:
buf = self._buffer
buf[last_text_idx] = buf[last_text_idx].rstrip()
self._remove_begining_ws = 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 handle_comment(self, comment):
""" Remove comment except IE conditional comment. .. seealso:: `About conditional comments <http://msdn.microsoft.com/en-us/li... |
match = _COND_COMMENT_PATTERN.match(comment)
if match is not None:
cond = match.group(1)
content = match.group(2)
self._buffer.append(_COND_COMMENT_START_FORMAT % cond)
self._push_status()
self.feed(content)
self._pop_status()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_data(self, data):
""" Any space immediately following another collapsible space will be collapsed. .. seealso:: `CSS Text Module Level 3 - The White S... |
tag_stack = self._tag_stack
if tag_stack and tag_stack[-1] in _RM_WS_ELEMENTS:
# just ignore the content of this element
assert data.strip() == ''
return
if self._preserve == 0:
if self._remove_begining_ws:
data = data.lstrip()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def twilio_SMS(self, from_, to, body):
""" Send an SMS message from your `twilio`_ account. .. _twilio: https://www.twilio.com/ Login will be performed using sto... |
logging.debug('Texting from Twilio')
client = TwilioRestClient(self._credentials['TWILIO_ACCOUNT_SID'], self._credentials['TWILIO_AUTH_TOKEN'])
response = client.messages.create(
to=to,
from_=from_,
body=body,
)
logging.debug('Response fr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def special_get_field(self, value, args, kwargs, format_spec=None):
"""Also take the spec into account""" |
if value in self.chain:
raise BadOptionFormat("Recursive option", chain=self.chain + [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 _get_page_from_path(self, path):
""" Fetches the FeinCMS Page object that the path points to. Override this to deal with different types of object from Page.... |
from feincms.module.page.models import Page
try:
return Page.objects.best_match_for_path(path)
except Page.DoesNotExist:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_resource_access_state(self, request):
""" Returns the FeinCMS resource's access_state, following any INHERITed values. Will return None if the resource ... |
feincms_page = self._get_page_from_path(request.path_info.lstrip('/'))
if not feincms_page:
return None
# Chase inherited values up the tree of inheritance.
INHERIT = AccessState.STATE_INHERIT
while feincms_page.access_state == INHERIT and feincms_page.parent:
... |
<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_resource_protected(self, request, **kwargs):
""" Determines if a resource should be protected. Returns true if and only if the resource's access_state mat... |
access_state = self._get_resource_access_state(request)
protected_states = self.get_protected_states()
return access_state in protected_states |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare_two_documents(kls, doc1, doc2):
"""Compare two documents by converting them into json objects and back to strings and compare""" |
first = doc1
if isinstance(doc1, string_types):
try:
first = json.loads(doc1)
except (ValueError, TypeError) as error:
log.warning("Failed to convert doc into a json object\terror=%s", error)
yield error.args[0]
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def facter_info():
"""Returns data from facter. """ |
with suppress(FileNotFoundError): # facter may not be installed
proc = subprocess.Popen(['facter', '--yaml'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
if not proc.returncode:
... |
<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_color(index):
"""Dips the brush in paint. Arguments: index - an integer between 0 and 7, inclusive. Tells the bot which color you want. """ |
if index in range(0, 8):
# Send the turtle to the top-left corner of the window to imitate the position of the WCB's brush.
state['turtle'].goto(-WCB_WIDTH / 2, -WCB_HEIGHT / 2)
_make_cnc_request("tool.color./" + str(index))
# This is the order of the colors in the palette in our ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_to(x, y):
"""Moves the brush to a particular position. Arguments: x - a number between -250 and 250. y - a number between -180 and 180. """ |
_make_cnc_request("coord/{0}/{1}".format(x, y))
state['turtle'].goto(x, 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 turn_left(relative_angle):
"""Turns the brush's "turtle" to the left. Arguments: relative_angle - a number like 10. A bigger number makes the turtle turn far... |
assert int(relative_angle) == relative_angle, "turn_left() only accepts integers, but you gave it " + str(relative_angle)
_make_cnc_request("move.left./" + str(relative_angle))
state['turtle'].left(relative_angle) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def turn_right(relative_angle):
"""Turns the brush's "turtle" to the right. Arguments: relative_angle - a number like 10. A bigger number makes the turtle turn f... |
assert int(relative_angle) == relative_angle, "turn_right() only accepts integers, but you gave it " + str(relative_angle)
_make_cnc_request("move.right./" + str(relative_angle))
state['turtle'].right(relative_angle) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe(o):
"""Describes the object using developer-specified attributes specific to each main object type. Returns: dict: keys are specific attributes tail... |
#First, we need to determine the fqdn, so that we can lookup the format for
#this object in the config file for the package.
from inspect import getmodule
from acorn.logging.decoration import _fqdn
fqdn = _fqdn(o, False)
if fqdn is None:
#This should not have happened; if the FQDN could... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _obj_getattr(obj, fqdn, start=1):
"""Returns the attribute specified by the fqdn list from obj. """ |
node = obj
for chain in fqdn.split('.')[start:]:
if hasattr(node, chain):
node = getattr(node, chain)
else:
node = None
break
return node |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _package_transform(package, fqdn, start=1, *args, **kwargs):
"""Applies the specified package transform with `fqdn` to the package. Args: package: imported p... |
#Our only difficulty here is that package names can be chained. We ignore
#the first item since that was already checked for us by the calling
#method.
node = _obj_getattr(package, fqdn, start)
#By the time this loop is finished, we should have a function to apply if
#the developer setting... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _instance_transform(fqdn, o, *args, **kwargs):
"""Applies an instance method with name `fqdn` to `o`. Args: fqdn (str):
fully-qualified domain name of the o... |
return _package_transform(o, fqdn, start=0, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json_describe(o, fqdn, descriptor=None):
"""Describes the specified object using the directives in the JSON `descriptor`, if available. Args: o: object to de... |
if descriptor is None or not isinstance(descriptor, dict):
return {"fqdn": fqdn}
else:
result = {"fqdn": fqdn}
for attr, desc in descriptor.items():
if attr == "instance":
#For instance methods, we repeatedly call instance methods on
#`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 get_database_name(self):
""" extract database from connection string """ |
uri_dict = uri_parser.parse_uri(self.host)
database = uri_dict.get('database', None)
if not database:
raise "database name is missing"
return 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 find(self, start, end, limit=50, *args, **kwargs):
""" find by creation date, using start and end dates as range """ |
# check if spec has been specified, build on top of it
fc = kwargs.get('spec', dict())
# filter _id on start and end dates
fc['_id'] = {'$gte': ObjectId.from_datetime(start),
'$lte': ObjectId.from_datetime(end)}
if not self.collection:
collecti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_exc(exc):
""" Given a database exception determine how to fail Attempt to lookup a known error & abort on a meaningful error. Otherwise issue a generi... |
err = ERRORS_TABLE.get(exc.pgcode)
if err:
abort(exceptions.InvalidQueryParams(**{
'detail': err,
'parameter': 'filter',
}))
abort(exceptions.DatabaseUnavailable) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dirty_vals(model):
""" Get the models dirty values in a friendly SQL format This will be a string of comma separated field names in a format for psycopg to s... |
vals = []
for field in model.dirty_fields:
vals.append('%({0})s'.format(field))
vals = ', '.join(vals)
return vals or 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 field_cols(model):
""" Get the models columns in a friendly SQL format This will be a string of comma separated field names prefixed by the models resource t... |
to_many = model.to_many
cols = [f for f in model.all_fields if f not in to_many]
cols = ', '.join(cols)
return cols or 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 sorts_query(sortables):
""" Turn the Sortables into a SQL ORDER BY query """ |
stmts = []
for sortable in sortables:
if sortable.desc:
stmts.append('{} DESC'.format(sortable.field))
else:
stmts.append('{} ASC'.format(sortable.field))
return ' ORDER BY {}'.format(', '.join(stmts)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, model):
""" Given a model object instance create it """ |
signals.pre_create.send(model.__class__, model=model)
signals.pre_save.send(model.__class__, model=model)
param = self.to_pg(model)
query = """
INSERT INTO {table} ({dirty_cols})
VALUES ({dirty_vals})
RETURNING {cols};
""... |
<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, model):
""" Given a model object instance delete it """ |
signals.pre_delete.send(model.__class__, model=model)
param = {'rid_value': self.to_pg(model)[model.rid_field]}
query = """
DELETE FROM {table}
WHERE {rid_field} = %(rid_value)s
RETURNING {cols};
"""
query = query.format... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self, query, param=None):
""" Perform a SQL based query This will abort on a failure to communicate with the database. :query: string query :params: pa... |
with self.conn.cursor() as curs:
print 'XXX QUERY', curs.mogrify(query, param)
try:
curs.execute(query, param)
except BaseException as exc:
msg = 'query: {}, param: {}, exc: {}'.format(query, param, exc)
if hasattr(exc, 'pgco... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, rtype, **kwargs):
""" Search for the model by assorted criteria Quite a bit needs to happen for a search processing! The breakdown is we need to... |
model = rtype_to_model(rtype)
param = {}
pages = self.pages_query(kwargs.get('pages'))
sorts = self.sorts_query(kwargs.get(
'sorts', [Sortable(goldman.config.SORT)]
))
query = """
SELECT {cols}, count(*) OVER() as _count
FROM... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, model):
""" Given a model object instance update it """ |
signals.pre_update.send(model.__class__, model=model)
signals.pre_save.send(model.__class__, model=model)
param = self.to_pg(model)
param['rid_value'] = param[model.rid_field]
query = """
UPDATE {table}
SET ({dirty_cols}) = ({dirty_vals})
... |
<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_path(environ):
""" Get the path """ |
from wsgiref import util
request_uri = environ.get('REQUEST_URI', environ.get('RAW_URI', ''))
if request_uri == '':
uri = util.request_uri(environ)
host = environ.get('HTTP_HOST', '')
scheme = util.guess_scheme(environ)
prefix = "{scheme}://{host}".format(scheme=scheme, host... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_purge(environ, start_response):
""" Handle a PURGE request. """ |
from utils import is_valid_security, get_cached_files
from settings import DEBUG
server = environ['SERVER_NAME']
try:
request_uri = get_path(environ)
path_and_query = request_uri.lstrip("/")
query_string = environ.get('QUERY_STRING', '')
if is_valid_security('PURGE', que... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_instance(page_to_crawl):
"""Return an instance of CrawlModel.""" |
global _instances
if isinstance(page_to_crawl, basestring):
uri = page_to_crawl
page_to_crawl = crawlpage.get_instance(uri)
elif isinstance(page_to_crawl, crawlpage.CrawlPage):
uri = page_to_crawl.uri
else:
raise TypeError(
"get_instance() expects a parker.Cr... |
<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_exists(original_file):
""" Validate the original file is in the S3 bucket """ |
s3 = boto3.resource('s3')
bucket_name, object_key = _parse_s3_file(original_file)
bucket = s3.Bucket(bucket_name)
bucket_iterator = bucket.objects.filter(Prefix=object_key)
bucket_list = [x for x in bucket_iterator]
logger.debug("Bucket List: {0}".format(", ".join([x.key for x in bucket_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 put_file(buffer, modified_file):
""" write the buffer to modified_file. modified_file should be in the format 's3://bucketname/path/to/file.txt' """ |
import mimetypes
import boto3
file_type, _ = mimetypes.guess_type(modified_file)
s3 = boto3.resource('s3')
bucket_name, object_key = _parse_s3_file(modified_file)
extra_args = {
'ACL': 'public-read',
'ContentType': file_type
}
bucket = s3.Bucket(bucket_name)
logger.... |
<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_data_files(*include_dirs):
'called from setup.py in skeleton projects'
data_files = []
for include_dir in include_dirs:
for root, directories, filenames in os.walk(include_dir):
include_files = []
for filename in filenames:
# do not bring along certain... |
<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_html_dict(dictionary, prefix=''):
""" Used to support dictionary values in HTML forms. { 'profile.username': 'example', 'profile.email': 'example@examp... |
ret = MultiValueDict()
regex = re.compile(r'^%s\.(.+)$' % re.escape(prefix))
for field, value in dictionary.items():
match = regex.match(field)
if not match:
continue
key = match.groups()[0]
ret[key] = value
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def meta(self):
"""Data for loading later""" |
mount_points = []
for overlay in self.overlays:
mount_points.append(overlay.mount_point)
return [self.end_dir, self.start_dir, mount_points] |
<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_level_fmt(self, level):
"""Get format for log level.""" |
key = None
if level == logging.DEBUG:
key = 'debug'
elif level == logging.INFO:
key = 'info'
elif level == logging.WARNING:
key = 'warning'
elif level == logging.ERROR:
key = 'error'
elif level == logging.CRITICAL:
... |
<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, record):
"""Format log record.""" |
format_orig = self._fmt
self._fmt = self.get_level_fmt(record.levelno)
record.prefix = self.prefix
record.plugin_id = self.plugin_id
result = logging.Formatter.format(self, record)
self._fmt = format_orig
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 start_simple_server():
"A simple mail server that sends a simple response"
args = _get_args()
addr = ('', args.port)
DebuggingServer(addr, None)
asyncore.loop() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_post(self, req, resp):
""" Validate the token revocation request for spec compliance The spec also dictates the JSON based error response on failure & is ... |
token = req.get_param('token')
token_type_hint = req.get_param('token_type_hint')
# errors or not, disable client caching along the way
# per the spec
resp.disable_caching()
if not token:
resp.status = falcon.HTTP_400
resp.serialize({
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emulate_seek(fd, offset, chunk=CHUNK):
""" Emulates a seek on an object that does not support it The seek is emulated by reading and discarding bytes until s... |
while chunk and offset > CHUNK:
fd.read(chunk)
offset -= chunk
fd.read(offset) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def force_seek(fd, offset, chunk=CHUNK):
""" Force adjustment of read cursort to specified offset This function takes a file descriptor ``fd`` and tries to seek ... |
try:
fd.seek(offset)
except (AttributeError, io.UnsupportedOperation):
# This file handle probably has no seek()
emulate_seek(fd, offset, chunk) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def range_iter(fd, offset, length, chunk=CHUNK):
""" Iterator generator that iterates over chunks in specified range This generator is meant to be used when retu... |
force_seek(fd, offset, chunk)
while length > 0:
ret = fd.read(chunk)
if not ret:
return
length -= chunk
yield ret
fd.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, size=None):
""" Read a specified number of bytes from the file descriptor This method emulates the normal file descriptor's ``read()`` method and ... |
if not self.fd:
raise ValueError('I/O on closed file')
if not size:
size = self.remaining
size = min([self.remaining, size])
if not size:
return ''
data = self.fd.read(size)
self.remaining -= size
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def placeholdit( width, height, background_color="cccccc", text_color="969696", text=None, random_background_color=False ):
""" Creates a placeholder image using... |
url = get_placeholdit_url(
width,
height,
background_color=background_color,
text_color=text_color,
text=text,
)
return format_html('<img src="{}"/>', 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 pangram(language='en'):
""" Prints a pangram in the specified language. A pangram is a phrase that includes every letter of an alphabet. Default is English. ... |
try:
pangram = get_pangram(language)
except KeyError:
raise template.TemplateSyntaxError(
"Could not find a pangram for %r abbreviation" % language
)
return get_pangram_html(pangram) |
<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_result(self):
""" get the result """ |
info = {}
self.options2attr = {
'email': self._email,
'telephone': self._telephone,
'QQ' : self._QQ,
'wechat': self._wechat,
'url': self._url,
'emoji': self._emoji,
'tex': self._tex,
'blur': self._blur,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract(self, m):
""" extract info specified in option """ |
self._clear()
self.m = m
# self._preprocess()
if self.option != []:
self._url_filter()
self._email_filter()
if 'tex' in self.option:
self._tex_filter()
# if 'email' in self.option:
# self._email_filter()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _filter(self):
""" delete the punctuation """ |
pattern = u"[\s+\.\!\-\/_,$%^*(+\"\']+|[+——!】【,。??:、:~@#¥%……&*“”()]+"
self.m = re.sub(pattern, "", self.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 set_log_level(self, log_level):
'''Configures class log level
Arguments:
log_level (:obj:`str`): log level ('NOTSET','DEBUG','INFO' 'WARNING',
'ERROR', 'CRITICAL')
'''
if log_level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
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 set_log_format(self, log_type, log_format):
'''Configures log format
Arguments:
log_type (:obj:`str`): log type (error, debug or stream)
log_format (:obj:`str`): log format (ex:"Log: %(message)s | Log level:%(levelname)s |
Date:%(asctime)s',datefmt='%m/%d/%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 add_document(self, question, answer):
"""Add question answer set to DB. :param question: A question to an answer :type question: :class:`str` :param answer: ... |
question = question.strip()
answer = answer.strip()
session = self.Session()
if session.query(Document) \
.filter_by(text=question, answer=answer).count():
logger.info('Already here: {0} -> {1}'.format(question, answer))
return
logger.in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_best_answer(self, query):
"""Get best answer to a question. :param query: A question to get an answer :type query: :class:`str` :returns: An answer to a ... |
query = to_unicode(query)
session = self.Session()
grams = self._get_grams(session, query)
if not grams:
raise NoAnswerError('Can not found answer')
documents = set([doc for gram in grams for doc in gram.documents])
self._recalc_idfs(session, grams)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recreate_grams(self):
"""Re-create grams for database. In normal situations, you never need to call this method. But after migrate DB, this method is useful.... |
session = self.Session()
for document in session.query(Document).all():
logger.info(document.text)
grams = self._get_grams(session, document.text, make=True)
document.grams = list(grams)
broken_links = session.query(Gram) \
.filter(~Gram.docume... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _recalc_idfs(self, session, grams=None):
"""Re-calculate idfs for database. calculating idfs for gram is taking long time. So I made it calculates idfs for s... |
if not grams:
grams = session.query(Gram)
for gram in grams:
orig_idf = gram.idf
gram.idf = self._get_idf(session, gram)
logger.debug('Recalculating {} {} -> {}'.format(
gram.gram, orig_idf, gram.idf)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def throw(self, type, value=None, traceback=None):
# pylint: disable=redefined-builtin """Raise an exception in this element""" |
return self.__wrapped__.throw(type, value, traceback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enumeratelet(iterable=None, start=0):
r""" Enumerate chunks of data from an iterable or a chain :param iterable: object supporting iteration, or an index :ty... |
# shortcut directly to chain enumeration
if iterable is None:
return _enumeratelet(start=start)
try:
iterator = iter(iterable)
except TypeError:
if start != 0:
raise # first arg is not iterable but start is explicitly set
return _enumeratelet(start=iterable)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filterlet(function=bool, iterable=None):
""" Filter chunks of data from an iterable or a chain :param function: callable selecting valid elements :type funct... |
if iterable is None:
return _filterlet(function=function)
else:
return iterlet(elem for elem in iterable if function(elem)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def printlet(flatten=False, **kwargs):
""" Print chunks of data from a chain :param flatten: whether to flatten data chunks :param kwargs: keyword arguments as f... |
chunk = yield
if flatten:
while True:
print(*chunk, **kwargs)
chunk = yield chunk
else:
while True:
print(chunk, **kwargs)
chunk = yield chunk |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_one(self, aws_syncr, amazon, function):
"""Make sure this function exists and has only attributes we want it to have""" |
function_info = amazon.lambdas.function_info(function.name, function.location)
if not function_info:
amazon.lambdas.create_function(function.name, function.description, function.location, function.runtime, function.role, function.handler, function.timeout, function.memory_size, function.cod... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def update(self, *args, **kwargs):
'''Preserves order if given an assoc list.
'''
arg = dict_arg(*args, **kwargs)
if isinstance(arg, list):
for key, val in arg:
self[key] = val
else:
super(AssocDict, self).update(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 _get_url_path(list_name):
""" Live Dao requires RESTCLIENTS_MAILMAN_KEY in the settings.py """ |
access_key = getattr(settings,
"RESTCLIENTS_MAILMAN_KEY",
"__mock_key__")
return URL.format(key=access_key, uwnetid=list_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 operations(*operations):
'''Decorator for marking Resource methods as HTTP operations.
This decorator does a number of different things:
- It transfer onto itself docstring and annotations from the decorated
method, so as to be "transparent" with regards to introspection.
- It tra... |
<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_signature(cls, function):
'''Parses the signature of a method and its annotations to swagger.
Return a dictionary {arg_name: info}.
'''
annotations = function.__annotations__.copy()
del annotations['return']
result = []
for param_name, (param_type, para... |
<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_swagger_fragment(cls):
'''Return the swagger-formatted fragment for the Resource Listing.'''
if cls.__swagger_fragment:
return cls.__swagger_fragment
cls.__swagger_fragment = {
'path': cls.endpoint_path.replace('<', '{').replace('>', '}'),
'description... |
<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_resource_operations(cls):
'''Return the swagger-formatted method descriptions'''
operations = []
for http, callback in cls.implemented_methods.items():
# Parse docstring
summary, notes = utils.parse_docstring(callback)
# Parse return annotations
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def callbacks(cls):
'''Return all the methods that are actually a request callback.'''
if cls.__callbacks is not None:
return cls.__callbacks
cls.__callbacks = []
for mname in dir(cls):
# Avoid recursion by excluding all methods of this prototype class
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def implemented_methods(cls):
'''Return a mapping of implemented HTTP methods vs. their callbacks.'''
if cls.__implemented_methods:
return cls.__implemented_methods
cls.__implemented_methods = {}
for method in cls.callbacks:
for op in getattr(method, 'swagger_ops'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit2dArrayToFn(arr, fn, mask=None, down_scale_factor=None, output_shape=None, guess=None, outgrid=None):
"""Fit a 2d array to a 2d function USE ONLY MASKED V... |
if mask is None:
#assert outgrid is not None
mask = np.ones(shape=arr.shape, dtype=bool)
if down_scale_factor is None:
if mask.sum() > 1000:
down_scale_factor = 0.3
else:
down_scale_factor = 1
if down_scale_factor != 1:
# SCALE TO DECREASE A... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_auth_scheme(self, req):
""" Check if the request has auth & the proper scheme Remember NOT to include the error related info in the WWW-Authenticat... |
if not req.auth:
raise AuthRequired(**{
'detail': 'You must first login to access the requested '
'resource(s). Please retry your request using '
'OAuth 2.0 Bearer Token Authentication as '
'documented in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_token(self, req):
""" Get the token from the Authorization header If the header is actually malformed where Bearer Auth was indicated by the request the... |
self._validate_auth_scheme(req)
try:
return naked(req.auth.split(' ')[1])
except IndexError:
desc = 'You are using the Bearer Authentication scheme as ' \
'required to login but your Authorization header is ' \
'completely missing ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
"""Starts the delayed execution""" |
if self._timer:
self._timer.cancel()
self._timer = Timer(self._timeout, self._fire)
self._timer.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tmpfile(root=TEMPS_DIR, prefix=TEMPS_PREFIX, suffix=TEMPS_SUFFIX):
'''
For use in a with statement, this function returns a context manager that
yields a path directly under root guaranteed to be unique by using the uuid
module. This path is not created. However if the path is an existing file
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def tmppath(root=TEMPS_DIR, prefix=TEMPS_PREFIX, suffix=TEMPS_SUFFIX):
'''
Returns a path directly under root that is guaranteed to be unique by
using the uuid module.
'''
return os.path.join(root, prefix + uuid.uuid4().hex + suffix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getComplexFileData(self, fileInfo, data):
"""Function to initialize the slightly more complicated data for file info""" |
result = fileInfo[fileInfo.find(data + "</td>") + len(data + "</td>"):]
result = result[:result.find("</td>")]
result = result[result.rfind(">") + 1:]
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 getFileDescription(self, fileInfo):
"""Function to get the description of a file.""" |
data = 'Description'
result = fileInfo[fileInfo.find(data + "</td>") + len(data + "</td>"):]
result.lstrip()
result = result[:result.find("</td>")]
result = result[result.rfind("<"):]
if "<td" in result:
result = result[result.find(">") + 1:]
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 two_numbers(
cls, request,
operation: (Ptypes.path,
String('One of the 4 arithmetic operations.',
enum=['add', 'sub', 'mul', 'div'])),
first: (Ptypes.path,
Float('The first operand.')),
second... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.