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 add_if_changed(self, resource):
"""Add resource if change is not None else ChangeTypeError.""" |
if (resource.change is not None):
self.resources.append(resource)
else:
raise ChangeTypeError(resource.change) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, resource):
"""Add a resource change or an iterable collection of them. Allows multiple resource_change objects for the same resource (ie. URI) and ... |
if isinstance(resource, collections.Iterable):
for r in resource:
self.add_if_changed(r)
else:
self.add_if_changed(resource) |
<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_changed_resources(self, resources, change=None):
"""Add items from a ResourceContainer resources. If change is specified then the attribute is set in the... |
for resource in resources:
rc = Resource(resource=resource, change=change)
self.add(rc) |
<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, lines):
""" Match and store Fenced Code Blocks in the HtmlStash. """ |
text = "\n".join(lines)
while 1:
m = FENCED_BLOCK_RE.search(text)
if not m:
break
lang = m.group('lang')
linenums = bool(m.group('linenums'))
html = highlight_syntax(m.group('code'), lang, linenums=linenums)
placeho... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize_hashes(self):
"""Create new hashlib objects for each hash we are going to calculate.""" |
if ('md5' in self.hashes):
self.md5_calc = hashlib.md5()
if ('sha-1' in self.hashes):
self.sha1_calc = hashlib.sha1()
if ('sha-256' in self.hashes):
self.sha256_calc = hashlib.sha256() |
<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_for_file(self, file, block_size=2**14):
"""Compute hash digests for a file. Calculate the hashes based on one read through the file. Optional block_s... |
self.initialize_hashes()
f = open(file, 'rb')
while True:
data = f.read(block_size)
if not data:
break
if (self.md5_calc is not None):
self.md5_calc.update(data)
if (self.sha1_calc is not None):
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 pre_save(self, model_instance, add):
"""Remove dashes, spaces, and convert isbn to uppercase before saving when clean_isbn is enabled""" |
value = getattr(model_instance, self.attname)
if self.clean_isbn and value not in EMPTY_VALUES:
cleaned_isbn = value.replace(' ', '').replace('-', '').upper()
setattr(model_instance, self.attname, cleaned_isbn)
return super(ISBNField, self).pre_save(model_instance, add) |
<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, dt):
""" Updates game engine each tick """ |
# if not playing dont update model
if self.win_status != 'undecided':
return
# Step known time for agents
if self.force_fps > 0:
dt = 1 / self.force_fps
# update target
self.player.update_rotation(dt, self.buttons)
# Get planned update
... |
<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_visited(self):
""" Updates exploration map visited status """ |
assert isinstance(self.player.cshape.center, eu.Vector2)
pos = self.player.cshape.center
# Helper function
def set_visited(layer, cell):
if cell and not cell.properties.get('visited') and cell.tile and cell.tile.id > 0:
cell.properties['visited'] = 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_sensors(self):
""" Check path for each sensor and record wall proximity """ |
assert isinstance(self.player.cshape.center, eu.Vector2)
pos = self.player.cshape.center
a = math.radians(self.player.rotation)
for sensor in self.player.sensors:
sensor.sensed_type = 'wall'
rad = a + sensor.angle
dis = min(self.distance_to_tile(pos,... |
<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_state(self):
""" Create state from sensors and battery """ |
# Include battery level in state
battery = self.player.stats['battery']/100
# Create observation from sensor proximities
# TODO: Have state persist, then update columns by `sensed_type`
# Multi-channel; detecting `items`
if len(self.mode['items']) > 0:
obser... |
<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_rotation(self, dt, buttons):
""" Updates rotation and impulse direction """ |
assert isinstance(buttons, dict)
ma = buttons['right'] - buttons['left']
if ma != 0:
self.stats['battery'] -= self.battery_use['angular']
self.rotation += ma * dt * self.angular_velocity
# Redirect velocity in new direction
a = math.radians(self.rotatio... |
<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(*paths):
'''read and return txt content of file'''
with open(os.path.join(os.path.dirname(__file__), *paths)) as fp:
return fp.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile_excludes(self):
"""Compile a set of regexps for files to be exlcuded from scans.""" |
self.compiled_exclude_files = []
for pattern in self.exclude_files:
try:
self.compiled_exclude_files.append(re.compile(pattern))
except re.error as e:
raise ValueError(
"Bad python regex in exclude '%s': %s" % (pattern, str(e))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exclude_file(self, file):
"""True if file should be exclude based on name pattern.""" |
for pattern in self.compiled_exclude_files:
if (pattern.match(file)):
return(True)
return(False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_disk(self, resource_list=None, paths=None):
"""Create or extend resource_list with resources from disk scan. Assumes very simple disk path to URL mappin... |
num = 0
# Either use resource_list passed in or make a new one
if (resource_list is None):
resource_list = ResourceList()
# Compile exclude pattern matches
self.compile_excludes()
# Work out start paths from map if not explicitly specified
if (paths 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 from_disk_add_path(self, path=None, resource_list=None):
"""Add to resource_list with resources from disk scan starting at path.""" |
# sanity
if (path is None or resource_list is None or self.mapper is None):
raise ValueError("Must specify path, resource_list and mapper")
# is path a directory or a file? for each file: create Resource object,
# add, increment counter
if (sys.version_info < (3, 0))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_file(self, resource_list=None, dir=None, file=None):
"""Add a single file to resource_list. Follows object settings of set_path, set_hashes and set_lengt... |
try:
if self.exclude_file(file):
self.logger.debug("Excluding file %s" % (file))
return
# get abs filename and also URL
if (dir is not None):
file = os.path.join(dir, file)
if (not os.path.isfile(file) or not (
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def has_file_extension(filepath, ext_required):
'''Assert that a filepath has the required file extension
:param filepath: string filepath presumably containing a file extension
:param ext_required: the expected file extension
examples: ".pdf", ".html", ".tex"
'''
ext = os.path.splitext(fil... |
<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_binary(system_binary_str):
'''Assert that a string represents a system binary
Return true if a string represents a system binary
Raise TypeError if the system_binary_str is not a string
Raise ValueError if the system_binary_str is not a system binary
:param system_binary_str: STR string rep... |
<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_is_type(ls, t):
'''Assert that a list contains only elements of type t
Return True if list contains elements of type t
Raise TypeError if t is not a class
Raise TypeError if ls is not a list
Raise TypeError if ls contains non-t elements
:param ls: LIST
:param t: python 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 require_api_auth(allow_anonymous=False):
"""Decorator to require API authentication using OAuth token. :param allow_anonymous: Allow access without OAuth tok... |
def wrapper(f):
"""Wrap function with oauth require decorator."""
f_oauth_required = oauth2.require_oauth()(f)
@wraps(f)
def decorated(*args, **kwargs):
"""Require OAuth 2.0 Authentication."""
if not hasattr(current_user, 'login_via_oauth2'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_oauth_scopes(*scopes):
r"""Decorator to require a list of OAuth scopes. Decorator must be preceded by a ``require_api_auth()`` decorator. Note, API k... |
required_scopes = set(scopes)
def wrapper(f):
@wraps(f)
def decorated(*args, **kwargs):
# Variable requests.oauth is only defined for oauth requests (see
# require_api_auth() above).
if hasattr(request, 'oauth') and request.oauth is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def indx_table(node_dict, tbl_mode=False):
"""Print Table for dict=formatted list conditionally include numbers.""" |
nt = PrettyTable()
nt.header = False
nt.padding_width = 2
nt.border = False
clr_num = C_TI + "NUM"
clr_name = C_TI + "NAME"
clr_state = "STATE" + C_NORM
t_lu = {True: [clr_num, "NAME", "REGION", "CLOUD",
"SIZE", "PUBLIC IP", clr_state],
False: [clr_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 run(host=DEFAULT_HOST, port=DEFAULT_PORT, path='.'):
"""Run the development server """ |
path = abspath(path)
c = Clay(path)
c.run(host=host, port=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 build(pattern=None, path='.'):
"""Generates a static copy of the sources """ |
path = abspath(path)
c = Clay(path)
c.build(pattern) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frequency_to_probability(frequency_map, decorator=lambda f: f):
"""Transform a ``frequency_map`` into a map of probability using the sum of all frequencies a... |
total = sum(frequency_map.values())
return {k: decorator(v / total) for k, v in frequency_map.items()} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index_of_coincidence(*texts):
"""Calculate the index of coincidence for one or more ``texts``. The results are averaged over multiple texts to return the del... |
if not texts:
raise ValueError("texts must not be empty")
return statistics.mean(_calculate_index_of_coincidence(frequency_analyze(text), len(text)) for text in texts) |
<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_index_of_coincidence(frequency_map, length):
"""A measure of how similar frequency_map is to the uniform distribution. Or the probability that two... |
if length <= 1:
return 0
# We cannot error here as length can legitimiately be 1.
# Imagine a ciphertext of length 3 and a key of length 2.
# Spliting this text up and calculating the index of coincidence results in ['AC', 'B']
# IOC of B will be calcuated for the 2nd column... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chi_squared(source_frequency, target_frequency):
"""Calculate the Chi Squared statistic by comparing ``source_frequency`` with ``target_frequency``. Example:... |
# Ignore any symbols from source that are not in target.
# TODO: raise Error if source_len is 0?
target_prob = frequency_to_probability(target_frequency)
source_len = sum(v for k, v in source_frequency.items() if k in target_frequency)
result = 0
for symbol, prob in target_prob.items():
... |
<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_chi_squared(source_freq, target_prob, source_len):
"""A measure of the observed frequency of the symbol versus the expected frequency. If the valu... |
expected = source_len * target_prob
return (source_freq - expected)**2 / expected |
<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_ngram(name):
"""Dynamically import the python module with the ngram defined as a dictionary. Since bigger ngrams are large files its wasteful to always... |
module = importlib.import_module('lantern.analysis.english_ngrams.{}'.format(name))
return getattr(module, 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 score(text, *score_functions):
"""Score ``text`` using ``score_functions``. Examples: Args: text (str):
The text to score *score_functions (variable length ... |
if not score_functions:
raise ValueError("score_functions must not be empty")
return statistics.mean(func(text) for func in score_functions) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def PatternMatch(regex):
"""Compute the score of a text by determing if a pattern matches. Example: 0 -1 Args: regex (str):
regular expression string to use as ... |
pattern = re.compile(regex)
return lambda text: -1 if pattern.search(text) is None else 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _request(self, url, params={}):
"""Makes a request using the currently open session. :param url: A url fragment to use in the creation of the master url """ |
r = self._session.get(url=url, params=params, headers=DEFAULT_ORIGIN)
return r |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emit(self, event, *args, **kwargs):
"""Send out an event and call it's associated functions :param event: Name of the event to trigger """ |
for func in self._registered_events[event].values():
func(*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 remove_all_listeners(self, event=None):
"""Remove all functions for all events, or one event if one is specifed. :param event: Optional event you wish to rem... |
if event is not None:
self._registered_events[event] = OrderedDict()
else:
self._registered_events = defaultdict(OrderedDict) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def version(self):
"""Spotify version information""" |
url: str = get_url("/service/version.json")
params = {"service": "remote"}
r = self._request(url=url, params=params)
return r.json() |
<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_current_status(self):
"""Returns the current state of the local spotify client""" |
url = get_url("/remote/status.json")
params = {"oauth": self._oauth_token, "csrf": self._csrf_token}
r = self._request(url=url, params=params)
return r.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pause(self, pause=True):
"""Pauses the spotify player :param pause: boolean value to choose the pause/play state """ |
url: str = get_url("/remote/pause.json")
params = {
"oauth": self._oauth_token,
"csrf": self._csrf_token,
"pause": "true" if pause else "false",
}
self._request(url=url, params=params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticate(self):
""" Authenticate with the api """ |
resp = self.session.get(self.api_url, auth=self.auth)
resp = self._process_response(resp)
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_screenshots(self):
""" Take a config file as input and generate screenshots """ |
headers = {'content-type': 'application/json', 'Accept': 'application/json'}
resp = requests.post(self.api_url, data=json.dumps(self.config), \
headers=headers, auth=self.auth)
resp = self._process_response(resp)
return resp.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def screenshots_done(self, jobid):
""" Return true if the screenshots job is done """ |
resp = self.session.get(os.path.join(self.api_url, '{0}.json'.format(jobid)))
resp = self._process_response(resp)
return True if resp.json()['state'] == 'done' else 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 create_items(self):
""" Create collidable items """ |
if not self.mode['items'] or len(self.mode['items']) == 0: return
# FIXME: Check if already contains
self.collman.add(self.player)
for k in self.mode['items']:
item = self.mode['items'][k]
#{'terminal': False, 'num': 50, 'scale': 1.0, 'reward': 2.0}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_item(self, radius, item_type):
""" Add a single item in random open position """ |
assert isinstance(radius, int) or isinstance(radius, float)
assert isinstance(item_type, str)
separation_scale = 1.1
min_separation = separation_scale * radius
# Removable item
item = Collidable(0, 0, radius, item_type, self.pics[item_type], True)
cntTrys = 0
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_collisions(self):
""" Test player for collisions with items """ |
if not self.mode['items'] or len(self.mode['items']) == 0: return
# update collman
# FIXME: Why update each frame?
self.collman.clear()
for z, node in self.children:
if hasattr(node, 'cshape') and type(node.cshape) == cm.CircleShape:
self.collman.add... |
<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_view(self, view_class, *args, **kwargs):
"""Register an admin view on this admin instance. :param view_class: The view class name passed to the view... |
protected_view_class = self.view_class_factory(view_class)
if 'endpoint' not in kwargs:
kwargs['endpoint'] = view_class(*args, **kwargs).endpoint
self.admin.add_view(protected_view_class(*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 load_entry_point_group(self, entry_point_group):
"""Load administration interface from entry point group. :param str entry_point_group: Name of the entry poi... |
for ep in pkg_resources.iter_entry_points(group=entry_point_group):
admin_ep = dict(ep.load())
keys = tuple(
k in admin_ep for k in ('model', 'modelview', 'view_class'))
if keys == (False, False, True):
self.register_view(
... |
<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(url):
"""Ranomdly generates a url for use in requests. Generates a hostname with the port and the provided suffix url provided :param url: A url frag... |
sub = "{0}.spotilocal.com".format("".join(choices(ascii_lowercase, k=10)))
return "http://{0}:{1}{2}".format(sub, DEFAULT_PORT, 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 get_oauth_token():
"""Retrieve a simple OAuth Token for use with the local http client.""" |
url = "{0}/token".format(DEFAULT_ORIGIN["Origin"])
r = s.get(url=url)
return r.json()["t"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_csrf_token():
"""Retrieve a simple csrf token for to prevent cross site request forgery.""" |
url = get_url("/simplecsrf/token.json")
r = s.get(url=url, headers=DEFAULT_ORIGIN)
return r.json()["token"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def protected_adminview_factory(base_class):
"""Factory for creating protected admin view classes. The factory will ensure that the admin view will check if a us... |
class ProtectedAdminView(base_class):
"""Admin view class protected by authentication."""
def _handle_view(self, name, **kwargs):
"""Override Talisman CSP header configuration for admin views.
Flask-Admin extension is not CSP compliant (see:
https://github.com/... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def client_getter():
"""Decorator to retrieve Client object and check user permission.""" |
def wrapper(f):
@wraps(f)
def decorated(*args, **kwargs):
if 'client_id' not in kwargs:
abort(500)
client = Client.query.filter_by(
client_id=kwargs.pop('client_id'),
user_id=current_user.get_id(),
).first()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token_getter(is_personal=True, is_internal=False):
"""Decorator to retrieve Token object and check user permission. :param is_personal: Search for a personal... |
def wrapper(f):
@wraps(f)
def decorated(*args, **kwargs):
if 'token_id' not in kwargs:
abort(500)
token = Token.query.filter_by(
id=kwargs.pop('token_id'),
user_id=current_user.get_id(),
is_personal=is_personal... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index():
"""List user tokens.""" |
clients = Client.query.filter_by(
user_id=current_user.get_id(),
is_internal=False,
).all()
tokens = Token.query.options(db.joinedload('client')).filter(
Token.user_id == current_user.get_id(),
Token.is_personal == True, # noqa
Token.is_internal == False,
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 client_new():
"""Create new client.""" |
form = ClientForm(request.form)
if form.validate_on_submit():
c = Client(user_id=current_user.get_id())
c.gen_salt()
form.populate_obj(c)
db.session.add(c)
db.session.commit()
return redirect(url_for('.client_view', client_id=c.client_id))
return render_tem... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def client_view(client):
"""Show client's detail.""" |
if request.method == 'POST' and 'delete' in request.form:
db.session.delete(client)
db.session.commit()
return redirect(url_for('.index'))
form = ClientForm(request.form, obj=client)
if form.validate_on_submit():
form.populate_obj(client)
db.session.commit()
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def client_reset(client):
"""Reset client's secret.""" |
if request.form.get('reset') == 'yes':
client.reset_client_secret()
db.session.commit()
return redirect(url_for('.client_view', client_id=client.client_id)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token_new():
"""Create new token.""" |
form = TokenForm(request.form)
form.scopes.choices = current_oauth2server.scope_choices()
if form.validate_on_submit():
t = Token.create_personal(
form.data['name'], current_user.get_id(), scopes=form.scopes.data
)
db.session.commit()
session['show_personal_acce... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token_view(token):
"""Show token details.""" |
if request.method == "POST" and 'delete' in request.form:
db.session.delete(token)
db.session.commit()
return redirect(url_for('.index'))
show_token = session.pop('show_personal_access_token', False)
form = TokenForm(request.form, name=token.client.name, scopes=token.scopes)
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 token_revoke(token):
"""Revoke Authorized Application token.""" |
db.session.delete(token)
db.session.commit()
return redirect(url_for('.index')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token_permission_view(token):
"""Show permission garanted to authorized application token.""" |
scopes = [current_oauth2server.scopes[x] for x in token.scopes]
return render_template(
"invenio_oauth2server/settings/token_permission_view.html",
token=token,
scopes=scopes,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extendMarkdown(self, md, md_globals):
"""Modifies inline patterns.""" |
md.inlinePatterns.add('del', SimpleTagPattern(DEL_RE, 'del'), '<not_strong')
md.inlinePatterns.add('ins', SimpleTagPattern(INS_RE, 'ins'), '<not_strong')
md.inlinePatterns.add('mark', SimpleTagPattern(MARK_RE, 'mark'), '<not_strong') |
<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_state(self, site, timestamp=None):
"""Write status dict to client status file. FIXME - should have some file lock to avoid race """ |
parser = ConfigParser()
parser.read(self.status_file)
status_section = 'incremental'
if (not parser.has_section(status_section)):
parser.add_section(status_section)
if (timestamp is None):
parser.remove_option(
status_section,
... |
<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_state(self, site):
"""Read client status file and return dict.""" |
parser = ConfigParser()
status_section = 'incremental'
parser.read(self.status_file)
timestamp = None
try:
timestamp = float(
parser.get(
status_section,
self.config_site_to_name(site)))
except NoSection... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def escape_latex_str_if_str(value):
'''Escape a latex string'''
if not isinstance(value, str):
return value
for regex, replace_text in REGEX_ESCAPE_CHARS:
value = re.sub(regex, replace_text, value)
value = re.sub(REGEX_BACKSLASH, r'\\\\', value)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resources_as_xml(self, resources, sitemapindex=False, fh=None):
"""Write or return XML for a set of resources in sitemap format. Arguments: - resources - eit... |
# element names depending on sitemapindex or not
root_element = ('sitemapindex' if (sitemapindex) else 'urlset')
item_element = ('sitemap' if (sitemapindex) else 'url')
# namespaces and other settings
namespaces = {'xmlns': SITEMAP_NS, 'xmlns:rs': RS_NS}
root = Element(r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_xml(self, fh=None, etree=None, resources=None, capability=None, sitemapindex=None):
"""Parse XML Sitemap and add to resources object. Reads from fh or ... |
if (resources is None):
resources = ResourceContainer()
if (fh is not None):
etree = parse(fh)
elif (etree is None):
raise ValueError("Neither fh or etree set")
# check root element: urlset (for sitemap), sitemapindex or bad
root_tag = etree.g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_etree_element(self, resource, element_name='url'):
"""Return xml.etree.ElementTree.Element representing the resource. Returns and element for the sp... |
e = Element(element_name)
sub = Element('loc')
sub.text = resource.uri
e.append(sub)
if (resource.timestamp is not None):
# Create appriate element for timestamp
sub = Element('lastmod')
sub.text = str(resource.lastmod) # W3C Datetime in UTC
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_as_xml(self, resource):
"""Return string for the resource as part of an XML sitemap. Returns a string with the XML snippet representing the resource... |
e = self.resource_etree_element(resource)
if (sys.version_info >= (3, 0)):
# python3.x
return(tostring(e, encoding='unicode', method='xml'))
elif (sys.version_info >= (2, 7)):
s = tostring(e, encoding='UTF-8', method='xml')
else:
# must no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_from_etree(self, etree, resource_class):
"""Construct a Resource from an etree. Parameters: etree - the etree to parse resource_class - class of Res... |
loc_elements = etree.findall('{' + SITEMAP_NS + "}loc")
if (len(loc_elements) > 1):
raise SitemapParseError(
"Multiple <loc> elements while parsing <url> in sitemap")
elif (len(loc_elements) == 0):
raise SitemapParseError(
"Missing <loc> e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_element_with_atts_to_etree(self, etree, name, atts):
"""Add element with name and atts to etree iff there are any atts. Parameters: etree - an etree obje... |
xml_atts = {}
for att in atts.keys():
val = atts[att]
if (val is not None):
xml_atts[self._xml_att_name(att)] = str(val)
if (len(xml_atts) > 0):
e = Element(name, xml_atts)
if (self.pretty_xml):
e.tail = "\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 dst_to_src(self, dst_file):
"""Map destination path to source URI.""" |
for map in self.mappings:
src_uri = map.dst_to_src(dst_file)
if (src_uri is not None):
return(src_uri)
# Must have failed if loop exited
raise MapperError(
"Unable to translate destination path (%s) "
"into a source URI." % (dst_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 src_to_dst(self, src_uri):
"""Map source URI to destination path.""" |
for map in self.mappings:
dst_path = map.src_to_dst(src_uri)
if (dst_path is not None):
return(dst_path)
# Must have failed if loop exited
raise MapperError(
"Unable to translate source URI (%s) into "
"a destination path." % (src_... |
<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_from_uri(self, uri):
"""Make a safe path name from uri. In the case that uri is already a local path then the same path is returned. """ |
(scheme, netloc, path, params, query, frag) = urlparse(uri)
if (netloc == ''):
return(uri)
path = '/'.join([netloc, path])
path = re.sub('[^\w\-\.]', '_', path)
path = re.sub('__+', '_', path)
path = re.sub('[_\.]+$', '', path)
path = re.sub('^[_\.]+'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strip_trailing_slashes(self, path):
"""Return input path minus any trailing slashes.""" |
m = re.match(r"(.*)/+$", path)
if (m is None):
return(path)
return(m.group(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 dst_to_src(self, dst_file):
"""Return the src URI from the dst filepath. This does not rely on the destination filepath actually existing on the local filesy... |
m = re.match(self.dst_path + "/(.*)$", dst_file)
if (m is None):
return(None)
rel_path = m.group(1)
return(self.src_uri + '/' + rel_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def src_to_dst(self, src_uri):
"""Return the dst filepath from the src URI. Returns None on failure, destination path on success. """ |
m = re.match(self.src_uri + "/(.*)$", src_uri)
if (m is None):
return(None)
rel_path = m.group(1)
return(self.dst_path + '/' + rel_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unsafe(self):
"""True if the mapping is unsafe for an update. Applies only to local source. Returns True if the paths for source and destination are the same... |
(scheme, netloc, path, params, query, frag) = urlparse(self.src_uri)
if (scheme != ''):
return(False)
s = os.path.normpath(self.src_uri)
d = os.path.normpath(self.dst_path)
lcp = os.path.commonprefix([s, d])
return(s == lcp or d == lcp) |
<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(text, exclude):
"""Remove ``exclude`` symbols from ``text``. Example: 'exampletext' Args: text (str):
The text to modify exclude (iterable):
The sym... |
exclude = ''.join(str(symbol) for symbol in exclude)
return text.translate(str.maketrans('', '', exclude)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_columns(text, n_columns):
"""Split ``text`` into ``n_columns`` many columns. Example: ['eape', 'xml'] Args: text (str):
The text to split n_columns (i... |
if n_columns <= 0 or n_columns > len(text):
raise ValueError("n_columns must be within the bounds of 1 and text length")
return [text[i::n_columns] for i in range(n_columns)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def combine_columns(columns):
"""Combine ``columns`` into a single string. Example: 'example' Args: columns (iterable):
ordered columns to combine Returns: Stri... |
columns_zipped = itertools.zip_longest(*columns)
return ''.join(x for zipped in columns_zipped for x in zipped if 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 iterate_ngrams(text, n):
"""Generator to yield ngrams in ``text``. Example: exam xamp ampl mple Args: text (str):
text to iterate over n (int):
size of win... |
if n <= 0:
raise ValueError("n must be a positive integer")
return [text[i: i + n] for i in range(len(text) - n + 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 group(text, size):
"""Group ``text`` into blocks of ``size``. Example: ['te', 'st'] Args: text (str):
text to separate size (int):
size of groups to split ... |
if size <= 0:
raise ValueError("n must be a positive integer")
return [text[i:i + size] for i in range(0, len(text), size)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _evaluate_rhs(cls, funcs, nodes, problem):
""" Compute the value of the right-hand side of the system of ODEs. Parameters basis_funcs : list(function) nodes ... |
evald_funcs = cls._evaluate_functions(funcs, nodes)
evald_rhs = problem.rhs(nodes, *evald_funcs, **problem.params)
return evald_rhs |
<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_residuals(self, coefs_array, basis_kwargs, boundary_points, nodes, problem):
""" Return collocation residuals. Parameters coefs_array : numpy.ndarra... |
coefs_list = self._array_to_list(coefs_array, problem.number_odes)
derivs, funcs = self._construct_approximation(basis_kwargs, coefs_list)
resids = self._assess_approximation(boundary_points, derivs, funcs,
nodes, problem)
return resids |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _construct_approximation(self, basis_kwargs, coefs_list):
""" Construct a collection of derivatives and functions that approximate the solution to the bounda... |
derivs = self._construct_derivatives(coefs_list, **basis_kwargs)
funcs = self._construct_functions(coefs_list, **basis_kwargs)
return derivs, funcs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _construct_derivatives(self, coefs, **kwargs):
"""Return a list of derivatives given a list of coefficients.""" |
return [self.basis_functions.derivatives_factory(coef, **kwargs) for coef in coefs] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _construct_functions(self, coefs, **kwargs):
"""Return a list of functions given a list of coefficients.""" |
return [self.basis_functions.functions_factory(coef, **kwargs) for coef in coefs] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _solution_factory(self, basis_kwargs, coefs_array, nodes, problem, result):
""" Construct a representation of the solution to the boundary value problem. Par... |
soln_coefs = self._array_to_list(coefs_array, problem.number_odes)
soln_derivs = self._construct_derivatives(soln_coefs, **basis_kwargs)
soln_funcs = self._construct_functions(soln_coefs, **basis_kwargs)
soln_residual_func = self._interior_residuals_factory(soln_derivs,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve(self, basis_kwargs, boundary_points, coefs_array, nodes, problem, **solver_options):
""" Solve a boundary value problem using the collocation method. P... |
result = optimize.root(self._compute_residuals,
x0=coefs_array,
args=(basis_kwargs, boundary_points, nodes, problem),
**solver_options)
solution = self._solution_factory(basis_kwargs, result.x, nodes,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datetime_to_str(dt='now', no_fractions=False):
"""The Last-Modified data in ISO8601 syntax, Z notation. The lastmod is stored as unix timestamp which is alre... |
if (dt is None):
return None
elif (dt == 'now'):
dt = time.time()
if (no_fractions):
dt = int(dt)
else:
dt += 0.0000001 # improve rounding to microseconds
return datetime.utcfromtimestamp(dt).isoformat() + 'Z' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_to_datetime(s, context='datetime'):
"""Set timestamp from an W3C Datetime Last-Modified value. The sitemaps.org specification says that <lastmod> values ... |
t = None
if (s is None):
return(t)
if (s == ''):
raise ValueError('Attempt to set empty %s' % (context))
# Make a date into a full datetime
m = re.match(r"\d\d\d\d(\-\d\d(\-\d\d)?)?$", s)
if (m is not None):
if (m.group(1) is None):
s += '-01-01'
elif... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def need_geocoding(self):
""" Returns True if any of the required address components is missing """ |
need_geocoding = False
for attribute, component in self.required_address_components.items():
if not getattr(self, attribute):
need_geocoding = True
break # skip extra loops
return need_geocoding |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def geocode(self, commit=False, force=False):
""" Do a backend geocoding if needed """ |
if self.need_geocoding() or force:
result = get_cached(getattr(self, self.geocoded_by), provider='google')
if result.status == 'OK':
for attribute, components in self.required_address_components.items():
for component in components:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def link(self, rel):
"""Look for link with specified rel, return else None.""" |
for link in self.ln:
if ('rel' in link and
link['rel'] == rel):
return(link)
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 link_href(self, rel):
"""Look for link with specified rel, return href from it or None.""" |
link = self.link(rel)
if (link is not None):
link = link['href']
return(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 default_capability(self):
"""Set capability name in md. Every ResourceSync document should have the top-level capability attributes. """ |
if ('capability' not in self.md and self.capability_name is not None):
self.md['capability'] = self.capability_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 add(self, resource):
"""Add a resource or an iterable collection of resources to this container. Must be implemented in derived class. """ |
if isinstance(resource, collections.Iterable):
for r in resource:
self.resources.append(r)
else:
self.resources.append(resource) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prune_before(self, timestamp):
"""Remove all resources with timestamp earlier than that given. Returns the number of entries removed. Will raise an excpetion... |
n = 0
pruned = []
for r in self.resources:
if (r.timestamp is None):
raise Exception("Entry %s has no timestamp" % (r.uri))
elif (r.timestamp >= timestamp):
pruned.append(r)
else:
n += 1
self.resources =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.