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 train(self, X):
""" Trains multiple logistic regression classifiers to handle the multiclass problem posed by ``X`` X (numpy.ndarray):
The input data matrix... |
_trainer = bob.learn.linear.CGLogRegTrainer(**{'lambda':self.regularizer})
if len(X) == 2: #trains and returns a single logistic regression classifer
return _trainer.train(add_bias(X[0]), add_bias(X[1]))
else: #trains and returns a multi-class logistic regression classifier
# use one-versu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nested_get(d, keys, default=None, required=False, as_list=False):
""" Multi-level dict get helper Parameters: d - dict instance keys - iterable of keys or do... |
if isinstance(keys, str):
keys = keys.split('.')
for key in keys:
try:
d = d[key]
except KeyError:
if required:
raise
d = default
break
except TypeError:
if required:
raise
d ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def recur(obj, type_func_tuple_list=()):
'''recuring dealing an object'''
for obj_type, func in type_func_tuple_list:
if type(obj) == type(obj_type):
return func(obj)
# by default, we wolud recurring list, tuple and dict
if isinstance(obj, list) or isinstance(obj, tuple):
n_o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def browser_cache(seconds):
"""Decorator for browser cache. Only for webpy @browser_cache( seconds ) before GET/POST function. """ |
import web
def wrap(f):
def wrapped_f(*args):
last_time_str = web.ctx.env.get('HTTP_IF_MODIFIED_SINCE', '')
last_time = web.net.parsehttpdate(last_time_str)
now = datetime.datetime.now()
if last_time and\
last_time + datetime.timedelta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join(items, separator=None):
"""Join the items into a string using the separator Converts items to strings if needed '1,2,3' """ |
if not items:
return ''
if separator is None:
separator = _default_separator()
return separator.join([str(item) for item in 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 split(string, separator_regexp=None, maxsplit=0):
"""Split a string to a list ['fred', ' was', ' here'] """ |
if not string:
return []
if separator_regexp is None:
separator_regexp = _default_separator()
if not separator_regexp:
return string.split()
return re.split(separator_regexp, string, maxsplit) |
<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_and_strip(string, separator_regexp=None, maxsplit=0):
"""Split a string into items and trim any excess spaces from the items ['fred', 'was', 'here'] ""... |
if not string:
return ['']
if separator_regexp is None:
separator_regexp = _default_separator()
if not separator_regexp:
return string.split()
return [item.strip()
for item in re.split(separator_regexp, string, maxsplit)] |
<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_and_strip_without(string, exclude, separator_regexp=None):
"""Split a string into items, and trim any excess spaces Any items in exclude are not in the... |
result = split_and_strip(string, separator_regexp)
if not exclude:
return result
return [x for x in result if x not in 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_by_count(items, count, filler=None):
"""Split the items into tuples of count items each [(0, 1), (2, 3)] If there are a mutiple of count items then fil... |
if filler is not None:
items = items[:]
while len(items) % count:
items.append(filler)
iterator = iter(items)
iterators = [iterator] * count
return list(zip(*iterators)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rejoin(string, separator_regexp=None, spaced=False):
"""Split a string and then rejoin it Spaces are interspersed between items only if spaced is True 'fred,... |
strings = split_and_strip(string)
if separator_regexp is None:
separator_regexp = _default_separator()
joiner = spaced and '%s ' % separator_regexp or separator_regexp
return joiner.join(strings) |
<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_archive_as_dir(self, zip_file_obj):
""" Add archive to the storage and unpack it. Args: zip_file_obj (file):
Opened file-like object. Returns: obj: Path... |
BalancedDiscStorage._check_interface(zip_file_obj)
file_hash = self._get_hash(zip_file_obj)
dir_path = self._create_dir_path(file_hash)
full_path = os.path.join(dir_path, file_hash)
if os.path.exists(full_path):
shutil.rmtree(full_path)
os.mkdir(full_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 to_even_columns(data, headers=None):
""" Nicely format the 2-dimensional list into evenly spaced columns """ |
result = ''
col_width = max(len(word) for row in data for word in row) + 2 # padding
if headers:
header_width = max(len(word) for row in headers for word in row) + 2
if header_width > col_width:
col_width = header_width
result += "".join(word.ljust(col_width) for word ... |
<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_smart_columns(data, headers=None, padding=2):
""" Nicely format the 2-dimensional list into columns """ |
result = ''
col_widths = []
for row in data:
col_counter = 0
for word in row:
try:
col_widths[col_counter] = max(len(word), col_widths[col_counter])
except IndexError:
col_widths.append(len(word))
col_counter += 1
if h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def progress_bar(items_total, items_progress, columns=40, base_char='.', progress_char='#', percentage=False, prefix='', postfix=''):
""" Print a progress bar of... |
bins_total = int(float(items_total) / columns) + 1
bins_progress = int((float(items_progress) / float(items_total)) * bins_total) + 1
progress = prefix
progress += progress_char * bins_progress
progress += base_char * (bins_total - bins_progress)
if percentage:
progress_percentage = flo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_x_y(collection_x, collection_y, filter_none=False):
""" Merge two lists, creating a dictionary with key `label` and a set x and y """ |
data = {}
for item in collection_x:
#print item[0:-1]
#print item[-1]
label = datetimeutil.tuple_to_string(item[0:-1])
if filter_none and label == 'None-None':
continue
data[label] = {'label': label, 'x': item[-1], 'y': 0}
for item in collection_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 x_vs_y(collection_x, collection_y, title_x=None, title_y=None, width=43, filter_none=False):
""" Print a histogram with bins for x to the left and bins of y ... |
data = merge_x_y(collection_x, collection_y, filter_none)
max_value = get_max_x_y(data)
bins_total = int(float(max_value) / width) + 1
if title_x is not None and title_y is not None:
headers = [title_x, title_y]
else:
headers = None
result = []
# Sort keys
for item 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 settings():
""" Fetch the middleware settings. :return dict: settings """ |
# Get the user-provided settings
user_settings = dict(getattr(django_settings, _settings_key, {}))
user_settings_keys = set(user_settings.keys())
# Check for required but missing settings
missing = _required_settings_keys - user_settings_keys
if missing:
raise AuthzConfigurationError(
... |
<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):
"""Run the service in infinitive loop processing requests.""" |
try:
while True:
message = self.connection.recv()
result = self.on_message(message)
if result:
self.connection.send(result)
except SelenolWebSocketClosedException as ex:
self.on_closed(0, '')
raise S... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_message(self, message):
"""Message from the backend has been received. :param message: Message string received. """ |
work_unit = SelenolMessage(message)
request_id = work_unit.request_id
if message['reason'] == ['selenol', 'request']:
try:
result = self.on_request(work_unit)
if result is not None:
return {
'reason': ['req... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def event(self, request_id, trigger, event, message):
"""Create an event in the backend to be triggered given a circumstance. :param request_id: Request ID of a ... |
self.connection.send({
'reason': ['request', 'event'],
'request_id': request_id,
'content': {
'trigger': trigger,
'message': {
'reason': event,
'content': message,
},
},
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, event, message):
"""Send a message to the backend. :param reason: Reason of the message. :param message: Message content. """ |
self.connection.send({
'reason': ['request', 'send'],
'content': {
'reason': event,
'request_id': self.request_counter,
'content': message,
},
})
self.request_counter = self.request_counter + 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 _get_matching_dist_in_location(dist, location):
""" Check if `locations` contain only the one intended dist. Return the dist with metadata in the new locatio... |
# Getting the dist from the environment causes the
# distribution meta data to be read. Cloning isn't
# good enough.
import pkg_resources
env = pkg_resources.Environment([location])
dists = [ d for project_name in env for d in env[project_name] ]
dist_infos = [ (d.project_name, d.version) ... |
<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_model_class(self):
"""Get model class""" |
if getattr(self, 'model', None):
return self.model
elif getattr(self, 'object', None):
return self.object.__class__
elif 'app' in self.kwargs and 'model' in self.kwargs:
return apps.get_model(self.kwargs.get('app'), self.kwargs.get('model'))
elif hasa... |
<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_model_config(self):
"""Get Trionyx model config""" |
if not hasattr(self, '__config'):
setattr(self, '__config', models_config.get_config(self.get_model_class()))
return getattr(self, '__config', 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 dispatch(self, request, *args, **kwargs):
"""Validate if user can use view""" |
if False: # TODO do permission check based on Model
raise PermissionDenied
return super().dispatch(request, *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 get_session_value(self, name, default=None):
"""Get value from session""" |
session_name = 'list_{}_{}_{}'.format(self.kwargs.get('app'), self.kwargs.get('model'), name)
return self.request.session.get(session_name, default) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_value(self, name, value):
"""Save value to session""" |
session_name = 'list_{}_{}_{}'.format(self.kwargs.get('app'), self.kwargs.get('model'), name)
self.request.session[session_name] = value
setattr(self, name, 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 get_title(self):
"""Get page title""" |
if self.title:
return self.title
return self.get_model_class()._meta.verbose_name_plural |
<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(self, paginator):
"""Get current page or page in session""" |
page = int(self.get_and_save_value('page', 1))
if page < 1:
return self.save_value('page', 1)
if page > paginator.num_pages:
return self.save_value('page', paginator.num_pages)
return page |
<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_search(self):
"""Get current search or search from session, reset page if search is changed""" |
old_search = self.get_session_value('search', '')
search = self.get_and_save_value('search', '')
if old_search != search:
self.page = 1
self.get_session_value('page', self.page)
return search |
<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_all_fields(self):
"""Get all aviable fields""" |
return {
name: {
'name': name,
'label': field['label'],
}
for name, field in self.get_model_config().get_list_fields().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 get_current_fields(self):
"""Get current list to be used""" |
if hasattr(self, 'current_fields') and self.current_fields:
return self.current_fields
field_attribute = 'list_{}_{}_fields'.format(self.kwargs.get('app'), self.kwargs.get('model'))
current_fields = self.request.user.attributes.get_attribute(field_attribute, [])
request_fie... |
<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_queryset(self):
"""Get search query set""" |
queryset = self.get_model_class().objects.get_queryset()
if self.get_model_config().list_select_related:
queryset = queryset.select_related(*self.get_model_config().list_select_related)
return watson.filter(queryset, self.get_search(), ranking=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 handle_request(self, request, *args, **kwargs):
"""Give back list items + config""" |
paginator = self.get_paginator()
# Call search first, it will reset page if search is changed
search = self.get_search()
page = self.get_page(paginator)
items = self.get_items(paginator, page)
return {
'search': search,
'page': page,
'... |
<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_items(self, paginator, current_page):
"""Get list items for current page""" |
fields = self.get_model_config().get_list_fields()
page = paginator.page(current_page)
items = []
for item in page:
items.append({
'id': item.id,
'url': item.get_absolute_url(),
'row_data': [
fields[field]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def items(self):
"""Get all list items""" |
query = self.get_queryset()
fields = self.get_model_config().get_list_fields()
for item in query.iterator():
row = OrderedDict()
for field_name in self.get_current_fields():
field = fields.get(field_name)
if not field_name:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def csv_response(self):
"""Get csv response""" |
def stream():
"""Create data stream generator"""
stream_file = io.StringIO()
csvwriter = csv.writer(stream_file, delimiter=',', quotechar='"')
csvwriter.writerow(self.get_current_fields())
for index, item in enumerate(self.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 get_delete_url(self):
"""Get model object delete url""" |
return reverse('trionyx:model-delete', kwargs={
'app': self.get_app_label(),
'model': self.get_model_name(),
'pk': self.object.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 get_edit_url(self):
"""Get model object edit url""" |
return reverse('trionyx:model-edit', kwargs={
'app': self.get_app_label(),
'model': self.get_model_name(),
'pk': self.object.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 get_model_alias(self):
"""Get model alias""" |
if self.model_alias:
return self.model_alias
return '{}.{}'.format(self.get_app_label(), self.get_model_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 handle_request(self, request, app, model, pk):
"""Render and return tab""" |
ModelClass = self.get_model_class()
object = ModelClass.objects.get(id=pk)
tab_code = request.GET.get('tab')
model_alias = request.GET.get('model_alias')
model_alias = model_alias if model_alias else '{}.{}'.format(app, model)
# TODO permission check
item = ta... |
<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_form(self, form_class=None):
"""Get form for model""" |
form = super().get_form(form_class)
if not getattr(form, 'helper', None):
form.helper = FormHelper()
form.helper.form_tag = False
else:
form.helper.form_tag = False
return form |
<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_cancel_url(self):
"""Get cancel url""" |
if self.cancel_url:
return self.cancel_url
ModelClass = self.get_model_class()
return reverse('trionyx:model-list', kwargs={
'app': ModelClass._meta.app_label,
'model': ModelClass._meta.model_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 form_valid(self, form):
"""Add success message""" |
response = super().form_valid(form)
messages.success(self.request, "Successfully created ({})".format(self.object))
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 get_success_url(self):
"""Get success url""" |
messages.success(self.request, "Successfully deleted ({})".format(self.object))
if self.success_url:
return reverse(self.success_url)
if 'app' in self.kwargs and 'model' in self.kwargs:
return reverse('trionyx:model-list', kwargs={
'app': self.kwargs.get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, request, *args, **kwargs):
"""Handle get request""" |
try:
kwargs = self.load_object(kwargs)
except Exception as e:
return self.render_te_response({
'title': str(e),
})
if not self.has_permission(request):
return self.render_te_response({
'title': 'No access',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, request, *args, **kwargs):
"""Handle post request""" |
try:
kwargs = self.load_object(kwargs)
except Exception as e:
return self.render_te_response({
'title': str(e),
})
if not self.has_permission(request):
return self.render_te_response({
'title': 'No access',
... |
<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_object(self, kwargs):
"""Load object and model config and remove pk from kwargs""" |
self.object = None
self.config = None
self.model = self.get_model_class()
kwargs.pop('app', None)
kwargs.pop('model', None)
if self.model and kwargs.get('pk', False):
try:
self.object = self.model.objects.get(pk=kwargs.pop('pk'))
... |
<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_permission(self, request):
"""Check if user has permission""" |
if not self.object and not self.permission:
return True
if not self.permission:
return request.user.has_perm('{}_{}'.format(
self.model_permission,
self.object.__class__.__name__.lower()), self.object
)
return request.user.ha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_to_string(self, template_file, context):
"""Render given template to string and add object to context""" |
context = context if context else {}
if self.object:
context['object'] = self.object
context[self.object.__class__.__name__.lower()] = self.object
return render_to_string(template_file, context, self.request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_te_response(self, data):
"""Render data to JsonResponse""" |
if 'submit_label' in data and 'url' not in data:
data['url'] = self.request.get_full_path()
return JsonResponse(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 display_dialog(self, *args, **kwargs):
"""Display form and success message when set""" |
form = kwargs.pop('form_instance', None)
success_message = kwargs.pop('success_message', None)
if not form:
form = self.get_form_class()(initial=kwargs, instance=self.object)
if not hasattr(form, "helper"):
form.helper = FormHelper()
form.helper.form_ta... |
<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_dialog(self, *args, **kwargs):
"""Handle form and save and set success message on valid form""" |
form = self.get_form_class()(self.request.POST, initial=kwargs, instance=self.object)
success_message = None
if form.is_valid():
obj = form.save()
success_message = self.success_message.format(
model_name=self.get_model_config().model_name.capitalize(),
... |
<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_term_size():
'''Gets the size of your terminal. May not work everywhere. YMMV.'''
rows, columns = os.popen('stty size', 'r').read().split()
return int(rows), int(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 find_commands(management_dir):
""" Given a path to a management directory, returns a list of all the command names that are available. Returns an empty list ... |
command_dir = os.path.join(management_dir, 'commands')
try:
return [f[:-3] for f in os.listdir(command_dir)
if not f.startswith('_') and f.endswith('.py')]
except OSError:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_commands():
""" Returns a dictionary mapping command names to their callback applications. This works by looking for a management.commands package in dja... |
commands = dict((name, 'pug.crawlnmine') for name in find_commands(__path__[0]))
if not settings.configured:
return commands
for app_config in reversed(list(apps.get_app_configs())):
path = os.path.join(app_config.path, 'management')
commands.update(dict((name, app_config.name) fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autocomplete(self):
""" Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion... |
# Don't complete if user hasn't sourced bash_completion file.
if 'DJANGO_AUTO_COMPLETE' not in os.environ:
return
cwords = os.environ['COMP_WORDS'].split()[1:]
cword = int(os.environ['COMP_CWORD'])
try:
curr = cwords[cword - 1]
except IndexError... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def genkeyhex():
'''
Generate new random Bitcoin private key, using os.urandom and
double-sha256. Hex format.
'''
while True:
key = hash256(
hexlify(os.urandom(40) + str(datetime.datetime.now())
.encode("utf-8")))
# 40 byt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def genkey(outcompressed=True,prefix='80'):
'''
Generate new random Bitcoin private key, using os.urandom and
double-sha256.
'''
key = prefix + genkeyhex()
if outcompressed:
key = key + '01'
return b58e(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 getandstrip_varintdata(data):
'''
Takes a hex string that begins with varint data, and has extra at
the end, and gets the varint integer, strips the varint bytes, and
returns the integer and the remaining data. So rather than having
to manually read the varint prefix, count, and strip, you can ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def LEB128toint(LEBinput):
'''
Convert unsigned LEB128 hex to integer
'''
reversedbytes = hexreverse(LEBinput)
binstr = ""
for i in range(len(LEBinput) // 2):
if i == 0:
assert int(reversedbytes[2*i:(2*i + 2)],16) < 128
else:
assert int(reversedbytes[2*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 add_attribute(self, attribute):
""" Add the given attribute to this Card. Returns the length of attributes after addition. """ |
self.attributes.append(attribute)
return len(self.attributes) |
<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_ability(self, phase, ability):
"""Add the given ability to this Card under the given phase. Returns the length of the abilities for the given phase after... |
if phase not in self.abilities:
self.abilities[phase] = []
self.abilities[phase].append(ability)
return len(self.abilities[phase]) |
<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_info(self, key, value, append=True):
""" Set any special info you wish to the given key. Each info is stored in a list and will be appended to rather the... |
if append:
if key not in self.info:
self.info[key] = []
self.info[key].append(value)
else:
self.info[key] = 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 save(self):
""" Converts the Card as is into a dictionary capable of reconstructing the card with ``Card.load`` or serialized to a string for storage. """ |
return dict(code=self.code, name=self.name, abilities=self.abilities,
attributes=self.attributes, info=self.info) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, carddict):
""" Takes a carddict as produced by ``Card.save`` and sets this card instances information to the previously saved cards information. "... |
self.code = carddict["code"]
if isinstance(self.code, text_type):
self.code = eval(self.code)
self.name = carddict["name"]
self.abilities = carddict["abilities"]
if isinstance(self.abilities, text_type):
self.abilities = eval(self.abilities)
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 ep(self, exc: Exception) -> bool: """Return False if the exception had not been handled gracefully""" |
if not isinstance(exc, ConnectionAbortedError):
return False
if len(exc.args) != 2:
return False
origin, reason = exc.args
logging.getLogger(__name__).warning('Exited')
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_package_name(prefix=settings.TEMP_DIR, book_id=None):
""" Return package path. Use uuid to generate package's directory name. Args: book_id (str, defaul... |
if book_id is None:
book_id = str(uuid.uuid4())
return os.path.join(prefix, book_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 _create_package_hierarchy(prefix=settings.TEMP_DIR, book_id=None):
""" Create hierarchy of directories, at it is required in specification. `root_dir` is roo... |
root_dir = _get_package_name(book_id=book_id, prefix=prefix)
if os.path.exists(root_dir):
shutil.rmtree(root_dir)
os.mkdir(root_dir)
original_dir = os.path.join(root_dir, "original")
metadata_dir = os.path.join(root_dir, "metadata")
os.mkdir(original_dir)
os.mkdir(metadata_dir)
... |
<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_ltp_package(aleph_record, book_id, ebook_fn, data, url, urn_nbn=None):
""" Create LTP package as it is specified in specification v1.0 as I understand... |
root_dir, orig_dir, meta_dir = _create_package_hierarchy(book_id=book_id)
# create original file
original_fn = os.path.join(
orig_dir,
fn_composers.original_fn(book_id, ebook_fn)
)
with open(original_fn, "wb") as f:
f.write(data)
# create metadata files
metadata_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 steemconnect(self, accesstoken=None):
''' Initializes the SteemConnect Client
class
'''
if self.sc is not None:
return self.sc
if accesstoken is not None:
self.accesstoken = accesstoken
if self.accesstoken is None:
self.sc = Client(... |
<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, code=None):
''' Uses a SteemConnect refresh token
to retreive an access token
'''
tokenobj = self.steemconnect().get_access_token(code)
for t in tokenobj:
if t == 'error':
self.msg.error_message(str(tokenobj[t]))
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 vote(self, voter, author, permlink, voteweight):
''' Uses a SteemConnect accses token
to vote.
'''
vote = Vote(voter, author, permlink, voteweight)
result = self.steemconnect().broadcast(
[vote.to_operation_structure()])
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 on_person_new(self, people):
""" Add new people All people supported need to be added simultaneously, since on every call a unjoin() followed by a join() is ... |
try:
self.on_person_leave([])
except:
# Already caught and logged
pass
try:
self.sensor_client.join(people)
except:
self.exception("Failed to join audience")
raise Exception("Joining audience failed") |
<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_person_update(self, people):
""" People have changed Should always include all people (all that were added via on_person_new) :param people: People to upd... |
try:
self.sensor_client.person_update(people)
except:
self.exception("Failed to update people")
raise Exception("Updating people failed") |
<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_namespace(self):
'''Remove all keys from the namespace
'''
conn = redis.Redis(connection_pool=self.pool)
keys = conn.keys("%s*" % self._namespace_str)
for i in xrange(0, len(keys), 10000):
conn.delete(*keys[i:i+10000])
logger.debug('tearing down %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 get_interface(interface):
"""Support Centos standard physical interface, such as eth0. """ |
# Supported CentOS Version
supported_dists = ['7.0', '6.5']
def format_centos_7_0(inf):
pattern = r'<([A-Z]+)'
state = re.search(pattern, stdout[0]).groups()[0]
state = 'UP' if not cmp(state, 'UP') else 'DOWN'
inf.state = state
stdout.pop(0)
pattern = r'inet... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_to_str(d):
""" Recursively convert all values in a dictionary to strings This is required because setup() does not like unicode in the values it is s... |
d2 = {}
for k, v in d.items():
k = str(k)
if type(v) in [list, tuple]:
d2[k] = [str(a) for a in v]
elif type(v) is dict:
d2[k] = convert_to_str(v)
else:
d2[k] = str(v)
return d2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def up(services: Iterable[str] = ()) -> int:
'''Start the specified docker-compose services.
Parameters
----------
:``services``: a list of docker-compose service names to start (must be
defined in docker-compose.yml)
Return Value(s)
---------------
The integer 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 _call(command: str, *args, **kwargs) -> int:
'''Wrapper around ``subprocess.Popen`` that sends command output to logger.
.. seealso::
``subprocess.Popen``_
Parameters
----------
:``command``: string form of the command to execute
All other parameters are passed directly to ``subp... |
<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_watcher(state):
"""Watch for file changes and reload config when needed. Arguments: state (_WaffleState):
Object that contains reference to app and it... |
conf = state.app.config
file_path = conf.get('WAFFLE_WATCHER_FILE', '/tmp/waffleconf.txt')
if not os.path.isfile(file_path):
# Create watch file
open(file_path, 'a').close()
while True:
tstamp = os.path.getmtime(file_path)
# Compare timestamps and update config if ne... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _redis_watcher(state):
"""Listen to redis channel for a configuration update notifications. Arguments: state (_WaffleState):
Object that contains reference ... |
conf = state.app.config
r = redis.client.StrictRedis(
host=conf.get('WAFFLE_REDIS_HOST', 'localhost'),
port=conf.get('WAFFLE_REDIS_PORT', 6379))
sub = r.pubsub(ignore_subscribe_messages=True)
sub.subscribe(conf.get('WAFFLE_REDIS_CHANNEL', 'waffleconf'))
while True:
for ms... |
<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_notifier(state):
"""Notify of configuration update through file. Arguments: state (_WaffleState):
Object that contains reference to app and its config... |
tstamp = time.time()
state._tstamp = tstamp
conf = state.app.config
file_path = conf.get('WAFFLE_WATCHER_FILE', '/tmp/waffleconf.txt')
if not os.path.isfile(file_path):
# Create watch file
open(file_path, 'a').close()
# Update timestamp
os.utime(file_path, (tstamp, tstamp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _redis_notifier(state):
"""Notify of configuration update through redis. Arguments: state (_WaffleState):
Object that contains reference to app and its conf... |
tstamp = time.time()
state._tstamp = tstamp
conf = state.app.config
# Notify timestamp
r = redis.client.StrictRedis()
r.publish(conf.get('WAFFLE_REDIS_CHANNEL', 'waffleconf'), tstamp) |
<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_dir(cls, directory_name):
"""Create a directory in the system""" |
if not os.path.exists(directory_name):
os.makedirs(directory_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 load_mapfile(self, map3=False):
"""Load the marker data :param map3: When true, ignore the gen. distance column Builds up the marker list according to the bo... |
cols = [0, 1, 3]
if map3:
cols = [0, 1, 2]
markers = numpy.loadtxt(self.mapfile, dtype=str, usecols=cols)
self.snp_mask = numpy.ones(markers.shape[0]*2,
dtype=numpy.int8).reshape(-1, 2)
if DataParser.boundary.NoExclusions():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def normalize_values_queryset(values_queryset, model=None, app=None, verbosity=1):
'''Shoehorn the values from one database table into another
* Remove padding (leading/trailing spaces) from `CharField` and `TextField` values
* Truncate all `CharField`s to the max_length of the destination `model`
* Su... |
<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_choices(*args):
"""Convert a 1-D sequence into a 2-D sequence of tuples for use in a Django field choices attribute ((0, u'0'), (1, u'1'), (2, u'2')) ((... |
if not args:
return tuple()
if isinstance(args[0], (list, tuple)):
return make_choices(*tuple(args[0]))
elif isinstance(args[0], collections.Mapping):
return tuple((k, unicode(v)) for (k, v) in args[0].iteritems())
elif all(isinstance(arg, (int, float, Decimal, basestring)) for ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def normalize_choices(db_values, field_name, app=DEFAULT_APP, model_name='', human_readable=True, none_value='Null',
blank_value='Unknown', missing_value='Unknown DB Code'):
'''Output the human-readable strings associated with the list of database values for a model field.
Uses the trans... |
<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_app(app=None, verbosity=0):
"""Uses django.db.djmodels.get_app and fuzzywuzzy to get the models module for a django app Retrieve an app module from an ap... |
# print 'get_app(', app
if not app:
# for an empty list, tuple or None, just get all apps
if isinstance(app, (type(None), list, tuple)):
return [app_class.__package__ for app_class in djmodels.get_apps() if app_class and app_class.__package__]
# for a blank string, get the d... |
<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_field(field):
"""Return a field object based on a dot-delimited app.model.field name""" |
if isinstance(field, djmodels.fields.Field):
return field
elif isinstance(field, basestring):
field = field.split('.')
if len(field) == 3:
model = get_model(app=field[0], model=field[1])
elif len(field) == 2:
model = get_model(app=DEFAULT_APP, model=field... |
<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_primary_key(model):
"""Get the name of the field in a model that has primary_key=True""" |
model = get_model(model)
return (field.name for field in model._meta.fields if field.primary_key).next() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def querysets_from_title_prefix(title_prefix=None, model=DEFAULT_MODEL, app=DEFAULT_APP):
"""Return a list of Querysets from a list of model numbers""" |
if title_prefix is None:
title_prefix = [None]
filter_dicts = []
model_list = []
if isinstance(title_prefix, basestring):
title_prefix = title_prefix.split(',')
elif not isinstance(title_prefix, dict):
title_prefix = title_prefix
if isinstance(title_prefix, (list, tupl... |
<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_field_names(fields, model=DEFAULT_MODEL, app=DEFAULT_APP, score_cutoff=50, pad_with_none=False):
"""Use fuzzy string matching to find similar model fiel... |
fields = util.listify(fields)
model = get_model(model, app)
available_field_names = model._meta.get_all_field_names()
matched_fields = []
for field_name in fields:
match = fuzzy.extractOne(str(field_name), available_field_names)
if match and match[1] is not None and match[1] >= scor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def model_from_path(model_path, fuzziness=False):
"""Find the model class for a given model path like 'project.app.model' Args: path (str):
dot-delimited model ... |
app_name = '.'.join(model_path.split('.')[:-1])
model_name = model_path.split('.')[-1]
if not app_name:
return None
module = importlib.import_module(app_name)
try:
model = getattr(module, model_name)
except AttributeError:
try:
model = getattr(getattr(modul... |
<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_synonymous_field(field, model=DEFAULT_MODEL, app=DEFAULT_APP, score_cutoff=50, root_preference=1.02):
"""Use a dictionary of synonyms and fuzzy string m... |
fields = util.listify(field) + list(synonyms(field))
model = get_model(model, app)
available_field_names = model._meta.get_all_field_names()
best_match, best_ratio = None, None
for i, field_name in enumerate(fields):
match = fuzzy.extractOne(str(field_name), available_field_names)
#... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_model(model_name, apps=settings.INSTALLED_APPS, fuzziness=0):
"""Find model_name among indicated Django apps and return Model class Examples: To find mo... |
# if it looks like a file system path rather than django project.app.model path the return it as a string
if '/' in model_name:
return model_name
if not apps and isinstance(model_name, basestring) and '.' in model_name:
apps = [model_name.split('.')[0]]
apps = util.listify(apps or setti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lagged_in_date(x=None, y=None, filter_dict=None, model='WikiItem', app=DEFAULT_APP, sort=True, limit=30000, lag=1, pad=0, truncate=True):
""" Lag the y value... |
lag = int(lag or 0)
#print 'X, Y:', x, y
if isinstance(x, basestring) and isinstance(y, basestring):
x, y = sequence_from_filter_spec([find_synonymous_field(x), find_synonymous_field(y)], filter_dict, model=model,
app=app, sort=sort, limit=limit)
if y 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 django_object_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), ignore_related=True, strip=True, ignore_errors=True, verbosity=0):
"""Constr... |
field_dict, errors = field_dict_from_row(row, model, field_names=field_names, ignore_fields=ignore_fields, strip=strip,
ignore_errors=ignore_errors, ignore_related=ignore_related, verbosity=verbosity)
if verbosity >= 3:
print 'field_dict = %r' % field_dict
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def count_lines(fname, mode='rU'):
'''Count the number of lines in a file
Only faster way would be to utilize multiple processor cores to perform parallel reads.
http://stackoverflow.com/q/845058/623735
'''
with open(fname, mode) as f:
for i, l in enumerate(f):
pass
return ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.