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. This must be a numpy.ndarray with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2 dimensions each. Each correspond to the data for one of the input classes, every row corresponds to one example of the data set, every column, one different feature. Returns: Machine: A trained multiclass machine. """
_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-versus-all strategy machines = [] for k in range(len(X)): NC_range = list(range(0,k)) + list(range(k+1,len(X))) machines.append(_trainer.train(add_bias(numpy.vstack(X[NC_range])), add_bias(X[k]))) return MultiClassMachine(machines)
<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 dot-delimited str of keys (see Note 1) default - value if index fails required - require every index to work (see Note 2) as_list - return result as list (see Note 3) Notes: 1. Each key is used to index a dict, replacing the dict with the matching value. This process is repeated until an index fails, or the keys are exhausted. If keys is a string, it is split by '.' and treated as a list of keys. 2. If the required flag is False, a failure to match a key causes the default value to be used. If the required flag is True, every key must match, otherwise a TypeError or KeyError is raised. 3. If as_list is True, a non-list match will be wrapped in a list, unless match is None, which will be replaced with an empty list. """
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 = default break if as_list: return [] if d is None else [d] if not isinstance(d, list) else d return 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_obj = [] for i in obj: n_obj.append(recur(i)) return n_obj if isinstance(obj, list) else tuple(obj) elif isinstance(obj, dict): n_obj = {} for k,v in obj.items(): n_obj[k] = recur(v) return n_obj return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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(seconds = seconds) > now: web.notmodified() else: web.lastmodified(now) web.header('Cache-Control', 'max-age='+str(seconds)) yield f(*args) return wrapped_f return wrap
<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 returned list ['fred', 'here'] """
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 filler makes no difference True If there are not a multiple of count items, then any extras are discarded [(0, 1, 2), (7, 8, 9)] Specifying a filler expands the "lost" group [(0, 1, 2), (7, 8, 9), (6, 0, 0)] """
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,was,here' """
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 where the `zip_file_obj` was unpacked wrapped in \ :class:`.PathAndHash` structure. Raises: ValueError: If there is too many files in .zip archive. \ See :attr:`._max_zipfiles` for details. AssertionError: If the `zip_file_obj` is not file-like object. """
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) try: self._unpack_zip(zip_file_obj, full_path) except Exception: shutil.rmtree(full_path) raise return PathAndHash(path=full_path, hash=file_hash)
<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 in headers) + "\n" result += '-' * col_width * len(headers) + "\n" for row in data: result += "".join(word.ljust(col_width) for word in row) + "\n" 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 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 headers: col_counter = 0 for word in headers: try: col_widths[col_counter] = max(len(word), col_widths[col_counter]) except IndexError: col_widths.append(len(word)) col_counter += 1 # Add padding col_widths = [width + padding for width in col_widths] total_width = sum(col_widths) if headers: col_counter = 0 for word in headers: result += "".join(word.ljust(col_widths[col_counter])) col_counter += 1 result += "\n" result += '-' * total_width + "\n" for row in data: col_counter = 0 for word in row: result += "".join(word.ljust(col_widths[col_counter])) col_counter += 1 result += "\n" 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 progress_bar(items_total, items_progress, columns=40, base_char='.', progress_char='#', percentage=False, prefix='', postfix=''): """ Print a progress bar of width `columns` """
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 = float(items_progress) / float(items_total) * 100 # Round the percentage to two decimals postfix = ' ' + str(round(progress_percentage, 2)) + '% ' + postfix progress += postfix return progress
<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: #print item label = datetimeutil.tuple_to_string(item[0:-1]) if filter_none and label == 'None-None': continue try: data[label]['y'] = item[-1] except KeyError: data[label] = {'label': label, 'x': 0, 'y': item[-1]} # Keys are not sorted return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 to the right """
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 sorted(data): #result.append([item, str(data[item]['x']) + '|' + str(data[item]['y'])]) bins_x = int((float(data[item]['x']) / float(max_value)) * bins_total) + 1 bins_y = int((float(data[item]['y']) / float(max_value)) * bins_total) + 1 print(bins_x) print(bins_y) #result.append([item, str(data[item]['x']), str(data[item]['y'])]) result.append([item, '*' * bins_x, '*' * bins_y]) result = to_smart_columns(result, headers=headers) 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 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( 'Missing required {} config: {}'.format(_settings_key, missing)) # Check for unknown settings unknown = user_settings_keys - _available_settings_keys if unknown: raise AuthzConfigurationError( 'Unknown {} config params: {}'.format(_settings_key, unknown)) # Merge defaults with provided settings defaults = _available_settings_keys - user_settings_keys user_settings.update({key: _available_settings[key] for key in defaults}) _rectify(user_settings) return types.MappingProxyType(user_settings)
<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 SelenolWebSocketClosedException() from ex
<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': ['request', 'result'], 'request_id': request_id, 'content': { 'content': result, }, } except SelenolException as e: logging.exception(e) return { 'reason': ['request', 'exception'], 'request_id': request_id, 'content': { 'message': str(e), }, } except Exception as e: logging.exception(e) return { 'reason': ['request', 'exception'], 'request_id': request_id, 'content': { 'message': 'Not a Selenol exception', }, }
<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 involved session. :param trigger: Circumstance that will trigger the event. :param event: Reason of the message that will be created. :param message: Content of the message that will be created. """
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 location. """
# 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) for d in dists ] if dist_infos == [(dist.project_name, dist.version)]: return dists.pop() if dist_infos == [(dist.project_name.lower(), dist.version)]: return dists.pop()
<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 hasattr(self, 'get_queryset'): return self.get_queryset().model else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_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_fields = self.request.POST.get('selected_fields', None) if request_fields and ','.join(current_fields) != request_fields: # TODO validate fields current_fields = request_fields.split(',') self.request.user.attributes.set_attribute(field_attribute, current_fields) elif request_fields: current_fields = request_fields.split(',') if not current_fields: config = self.get_model_config() current_fields = config.list_default_fields if config.list_default_fields else ['created_at', 'id'] self.current_fields = current_fields return current_fields
<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, 'page_size': self.get_page_size(), 'num_pages': paginator.num_pages, 'sort': self.get_sort(), 'current_fields': self.get_current_fields(), 'fields': self.get_all_fields(), 'items': 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_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]['renderer'](item, field) for field in self.get_current_fields() ] }) return 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 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: row[field_name] = '' if hasattr(item, field['field']): row[field_name] = getattr(item, field['field']) else: row[field_name] = '' # TODO Maybe render field ans strip html? yield row
<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()): csvwriter.writerow([value for index, value in item.items()]) stream_file.seek(0) data = stream_file.read() stream_file.seek(0) stream_file.truncate() yield data response = StreamingHttpResponse(stream(), content_type="text/csv") response["Content-Disposition"] = "attachment; filename={}.csv".format(self.get_model_config().model_name.lower()) 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_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 = tabs.get_tab(model_alias, object, tab_code) return item.get_layout(object).render(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 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('app'), 'model': self.kwargs.get('model'), }) 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(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', }) return self.render_te_response(self.display_dialog(*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 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', }) return self.render_te_response(self.handle_dialog(*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_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')) except Exception: raise Exception("Could not load {}".format(self.model.__name__.lower())) setattr(self, self.model.__name__.lower(), self.object) return 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 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.has_perm(self.permission)
<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_tag = False return { 'title': self.title.format( model_name=self.get_model_config().model_name, object=str(self.object) if self.object else '', ), 'content': self.render_to_string(self.template, { 'form': form, 'success_message': success_message, }), 'submit_label': self.submit_label, 'success': bool(success_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 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(), object=str(obj), ) return self.display_dialog(*args, form_instance=form, success_message=success_message, **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_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 if no commands are defined. """
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 django.core, and in each installed application -- if a commands package exists, all commands in that package are registered. Core commands are always included. If a settings module has been specified, user-defined commands will also be included. The dictionary is in the format {command_name: app_name}. Key-value pairs from this dictionary can then be used in calls to load_command_class(app_name, command_name) If a specific version of a command must be loaded (e.g., with the startapp command), the instantiated module can be placed in the dictionary in place of the application name. The dictionary is cached on the first call and reused on subsequent calls. """
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) for name in find_commands(path))) return commands
<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 suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used to get information about the cli input. Please refer to the BASH man-page for more information about this variables. Subcommand options are saved as pairs. A pair consists of the long option string (e.g. '--exclude') and a boolean value indicating if the option requires arguments. When printing to stdout, an equal sign is appended to options which require arguments. Note: If debugging this function, it is recommended to write the debug output in a separate file. Otherwise the debug output will be treated and formatted as potential completion suggestions. """
# 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: curr = '' subcommands = list(get_commands()) + ['help'] options = [('--help', None)] # subcommand if cword == 1: print(' '.join(sorted(filter(lambda x: x.startswith(curr), subcommands)))) # subcommand options # special case: the 'help' subcommand has no options elif cwords[0] in subcommands and cwords[0] != 'help': subcommand_cls = self.fetch_command(cwords[0]) # special case: 'runfcgi' stores additional options as # 'key=value' pairs if cwords[0] == 'runfcgi': from django.core.servers.fastcgi import FASTCGI_OPTIONS options += [(k, 1) for k in FASTCGI_OPTIONS] # special case: add the names of installed apps to options elif cwords[0] in ('dumpdata', 'sql', 'sqlall', 'sqlclear', 'sqlcustom', 'sqlindexes', 'sqlsequencereset', 'test'): try: app_configs = apps.get_app_configs() # Get the last part of the dotted path as the app name. options += [(app_config.label, 0) for app_config in app_configs] except ImportError: # Fail silently if DJANGO_SETTINGS_MODULE isn't set. The # user will find out once they execute the command. pass parser = subcommand_cls.create_parser('', cwords[0]) if subcommand_cls.use_argparse: options += [(sorted(s_opt.option_strings)[0], s_opt.nargs != 0) for s_opt in parser._actions if s_opt.option_strings] else: options += [(s_opt.get_opt_string(), s_opt.nargs) for s_opt in parser.option_list] # filter out previously specified options from available options prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]] options = [opt for opt in options if opt[0] not in prev_opts] # filter options by current input options = sorted((k, v) for k, v in options if k.startswith(curr)) for option in options: opt_label = option[0] # append '=' to options which require args if option[1]: opt_label += '=' print(opt_label) sys.exit(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 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 bytes used instead of 32, as a buffer for any slight # lack of entropy in urandom # Double-sha256 used instead of single hash, for entropy # reasons as well. # I know, it's nit-picking, but better safe than sorry. if int(key,16) > 1 and int(key,16) < N: break return 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 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 do it in one function. This function will return a tuple of the data and the leftover. For example, let's say you are parsing a transaction from beginning to end, and you know the next byte is a varint byte. Here's an example: fd5d010048304502200187af928e9d155c4b1ac9c1c9118153239aba76774f77 5d7c1f9c3e106ff33c0221008822b0f658edec22274d0b6ae9de10ebf2da06b1 bbdaaba4e50eb078f39e3d78014730440220795f0f4f5941a77ae032ecb9e337 53788d7eb5cb0c78d805575d6b00a1d9bfed02203e1f4ad9332d1416ae01e270 38e945bc9db59c732728a383a6f1ed2fb99da7a4014cc952410491bba2510912 a5bd37da1fb5b1673010e43d2c6d812c514e91bfa9f2eb129e1c183329db55bd 868e209aac2fbc02cb33d98fe74bf23f0c235d6126b1d8334f864104865c4029 3a680cb9c020e7b1e106d8c1916d3cef99aa431a56d253e69256dac09ef122b1 a986818a7cb624532f062c1d1f8722084861c5c3291ccffef4ec687441048d24 55d2403e08708fc1f556002f1b6cd83f992d085097f9974ab08a28838f07896f bab08f39495e15fa6fad6edbfb1e754e35fa1c7844c41f322a1863d4621353ae ffffffff0140420f00000000001976a914ae56b4db13554d321c402db3961187 aed1bbed5b88ac00000000 If the above tx fragment is input as a single long string with no white-space, this function will return the tuple: ('004830...53ae', 'ffffffff...00000000') See _doctester.py for that example in action. ''' data = strlify(data) numbytes = numvarintbytes(data[:2]) varint = data[:2*numbytes] data = data[2*numbytes:] tostrip = fromvarint(varint) * 2 return data[:tostrip], data[tostrip:]
<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:(2*i + 2)],16) >= 128 tempbin = str(bin(int(reversedbytes[2*i:(2*i + 2)],16))) \ .lstrip("0b").replace("b","").replace("L","") \ .replace("'","").replace('"',"") \ .zfill(8) binstr += tempbin[1:] return int(binstr,2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 the addition. """
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 then overriden unless append is False. """
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.attributes = carddict["attributes"] if isinstance(self.attributes, text_type): self.attributes = eval(self.attributes) self.info = carddict["info"] if isinstance(self.info, text_type): self.info = eval(self.info) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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, default None): UUID of the book. prefix (str, default settings.TEMP_DIR): Where the package will be stored. Default :attr:`settings.TEMP_DIR`. Returns: str: Path to the root directory. """
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 root of the package generated using :attr:`settings.TEMP_DIR` and :func:`_get_package_name`. `orig_dir` is path to the directory, where the data files are stored. `metadata_dir` is path to the directory with MODS metadata. Args: book_id (str, default None): UUID of the book. prefix (str, default settings.TEMP_DIR): Where the package will be stored. Default :attr:`settings.TEMP_DIR`. Warning: If the `root_dir` exists, it is REMOVED! Returns: list of str: root_dir, orig_dir, metadata_dir """
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) return root_dir, original_dir, 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 it. Args: aleph_record (str): XML containing full aleph record. book_id (str): UUID of the book. ebook_fn (str): Original filename of the ebook. data (str/bytes): Ebook's content. url (str): URL of the publication used when the URL can't be found in `aleph_record`. urn_nbn (str, default None): URN:NBN. Returns: str: Name of the package's directory in ``/tmp``. """
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_filenames = [] records = marcxml2mods(marc_xml=aleph_record, uuid=book_id, url=url) for cnt, mods_record in enumerate(records): fn = os.path.join( meta_dir, fn_composers.volume_fn(cnt) ) with open(fn, "w") as f: f.write(mods_record) metadata_filenames.append(fn) # collect md5 sums md5_fn = os.path.join(root_dir, fn_composers.checksum_fn(book_id)) checksums = checksum_generator.generate_hashfile(root_dir) with open(md5_fn, "w") as f: f.write(checksums) # create info file info_fn = os.path.join(root_dir, fn_composers.info_fn(book_id)) with open(info_fn, "w") as f: f.write( info_composer.compose_info( root_dir=root_dir, files=[original_fn] + metadata_filenames, hash_fn=md5_fn, aleph_record=aleph_record, urn_nbn=urn_nbn, ) ) return root_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 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(client_id=self.client_id, client_secret=self.client_secret) else: self.sc = Client(access_token=self.accesstoken, client_id=self.client_id, client_secret=self.client_secret) return self.sc
<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])) return False elif t == 'access_token': self.username = tokenobj['username'] self.refresh_token = tokenobj['refresh_token'] return tokenobj[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 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 issued :param people: People to add :type people: list[paps.people.People] :rtype: None :raises Exception: On error (for now just an exception) """
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 update :type people: list[paps.people.People] :rtype: None :raises Exception: On error (for now just an exception) """
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', self._namespace_str)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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\s(.*)\s\snetmask\s(.*)\s\sbroadcast\s(.*)' for line in stdout: if line.startswith('inet '): tmp = re.search(pattern, line).groups() (inf.inet, inf.netmask, inf.broadcast) = tmp stdout.remove(line) break for line in stdout: if line.startswith('ether'): inf.ether = line[6:23] break return stdcode, '', inf.make_dict() def format_centos_6_5(inf): pattern = r'HWaddr\s(.*)' inf.ether = re.search(pattern, stdout[0]).groups()[0] stdout.pop(0) pattern = r'addr:(.*)\s\sBcast:(.*)\s\sMask:(.*)' for line in stdout: if line.startswith('inet '): tmp = re.search(pattern, line).groups() (inf.inet, inf.broadcast, inf.netmask) = tmp stdout.remove(line) break inf.state = 'DOWN' for line in stdout: if 'RUNNING' in line: state = line[:2] state = 'UP' if not cmp(state, 'UP') else 'DOWN' inf.state = state break return stdcode, '', inf.make_dict() linux_dist = platform.linux_distribution()[1][:3] if linux_dist in supported_dists: try: cmd = ['ifconfig', interface] stdcode, stdout = execute(cmd) inf = resource.Interface(interface) if not cmp(linux_dist, '6.5'): return format_centos_6_5(inf) elif not cmp(linux_dist, '7.0'): return format_centos_7_0(inf) except Exception as e: message = stdout.pop(0) return stdcode, message, None # Unsupported OS distribute message = 'Unsupported OS distribute %s, only support for CentOS %s.' message = message % (linux_dist, str(supported_dists)) return 1, message, 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 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 supplied. """
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 of ``docker-compose up``. ''' services = list(services) if not len(services): raise ValueError('empty iterable passed to up(): {0}'.format(services)) return _call('docker-compose up --no-color -d ' + ' '.join(services), shell = 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 _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 ``subprocess.Popen``. Return Value(s) --------------- The integer status of command. ''' child = subprocess.Popen(command, stdout = subprocess.PIPE, stderr = subprocess.PIPE, *args, **kwargs) def log(): '''Send processes stdout and stderr to logger.''' for fh in select.select(( child.stdout, child.stderr, ), (), (), 0)[0]: line = fh.readline()[:-1] if len(line): getattr(logger, { child.stdout: 'debug', child.stderr: 'error', }[fh])('%s: %s', command, line) while child.poll() is None: log() log() return child.wait()
<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 its configstore. """
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 needed if tstamp > state._tstamp: state.update_conf() state._tstamp = tstamp # Not too critical time.sleep(10)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _redis_watcher(state): """Listen to redis channel for a configuration update notifications. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """
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 msg in sub.listen(): # Skip non-messages if not msg['type'] == 'message': continue tstamp = float(msg['data']) # Compare timestamps and update config if needed if tstamp > state._tstamp: state.update_conf() state._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 _file_notifier(state): """Notify of configuration update through file. Arguments: state (_WaffleState): Object that contains reference to app and its configstore. """
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 configstore. """
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 boundary configuration """
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(): self.markers = numpy.zeros((markers.shape[0], 2), dtype=int) # Check for plink's "off" mode mask = markers[:, 2].astype(int) >= 0 # Turn them all 'on' self.snp_mask[:,0] = ~mask self.snp_mask[:,1] = ~mask snp_count = numpy.sum(self.snp_mask[:, 0] == 0) self.markers[0:snp_count, 0] = markers[:, 0].astype(int)[mask] self.markers[0:snp_count, 1] = markers[:, 2].astype(int)[mask] self.rsids = markers[:, 1][mask] self.markers = self.markers[0:snp_count] else: idx = 0 self.markers = [] self.rsids = [] for locus in markers: if DataParser.boundary.TestBoundary(int(locus[0]), int(locus[2]), locus[1]): self.markers.append([locus[0], locus[2]]) self.rsids.append(locus[1]) self.snp_mask[idx] = 0 idx += 1 self.markers = numpy.array(self.markers, dtype=numpy.int) self.rsids = numpy.array(self.rsids) # We don't follow these rules here DataParser.boundary.beyond_upper_bound = False self.locus_count = len(self.markers)
<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` * Subsititue blanks ('') for any None values destined for `null=False` fields Returns a list of unsaved Model objects rather than a queryset ''' model = model or values_queryset.model app = app or DEFAULT_APP new_list = [] for record in values_queryset: new_record = {} for k, v in record.iteritems(): field_name = find_field_name(k, model=model, app=app) field_class = model._meta.get_field(field_name) # if isinstance(field_class, (djmodels.fields.DateTimeField, djmodels.fields.DateField)): # new_record[field_name] = unix_timestamp(v) # try: if isinstance(field_class, (djmodels.fields.CharField, djmodels.fields.TextField)) or isinstance(v, basestring): if v is None: v = '' else: v = unicode(v).strip() if isinstance(field_class, djmodels.fields.CharField): if len(v) > getattr(field_class, 'max_length', 0): if verbosity > 0: print k, v, len(v), '>', field_class.max_length print 'string = %s' % repr(v) # truncate strings that are too long for the database field v = v[:getattr(field_class, 'max_length', 0)] new_record[field_name] = v # except: # pass if (v is None or new_record[field_name] is None) and not getattr(field_class, 'null'): new_record[field_name] = '' if verbosity > 1: print new_record new_list += [new_record] return new_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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')) ((0, u'a'), (1, u'b'), (2, u'c'), (3, u'd')) (('hello', u'hello'),) True """
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 arg in args): return tuple((k, unicode(k)) for k in args)
<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 translation dictionary `CHOICES_<FIELD_NAME>` attribute for the given `model_name`. In addition, translate `None` into 'Null', or whatever string is indicated by `none_value`. ''' if app and isinstance(app, basestring): app = get_app(app) if not db_values: return try: db_values = dict(db_values) except: raise NotImplemented("This function can only handle objects that can be converted to a dict, not lists or querysets returned by django `.values().aggregate()`.") if not field_name in db_values: return db_values if human_readable: for i, db_value in enumerate(db_values[field_name]): if db_value in (None, 'None') or app in (None, 'None'): db_values[field_name][i] = none_value continue if isinstance(db_value, basestring): normalized_code = str(db_value).strip().upper() # the app is actually the models.py module, NOT the app_name package # so don't look in app.models, you'll only find django.db.models there (app_name.models.models) choices = getattr(app, 'CHOICES_%s' % field_name.upper(), []) normalized_name = None if choices: normalized_name = str(choices.get(normalized_code, missing_value)).strip() elif normalized_code: normalized_name = 'DB Code: "%s"' % normalized_code db_values[field_name][i] = normalized_name or blank_value else: raise NotImplemented("This function can only convert database choices to human-readable strings.") return db_values
<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 app name string, even if mispelled (uses fuzzywuzzy to find the best match) To get a list of all the apps use `get_app(None)` or `get_app([]) or get_app(())` To get a single random app use `get_app('')` True True True True isinstance(get_app(), ModuleType) False isinstance(get_app(), list) True """
# 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 default app(s) else: if get_app.default: return get_app(get_app.default) else: return djmodels.get_apps()[-1] elif isinstance(app, ModuleType): return app elif isinstance(app, basestring): if app.strip().endswith('.models'): return get_app(app[:-len('.models')]) elif '.' in app: return get_app('.'.join(app.split('.')[1:])) # django.db.models only looks at the module name in the INSTALLED_APPS list! try: if verbosity > 1: print 'Attempting django.db.models.get_app(%r)' % app return djmodels.get_app(app) except ImproperlyConfigured: if verbosity > 0: print 'WARNING: unable to find app = %r' % app if verbosity > 2: print 'Trying a fuzzy match on app = %r' % app app_names = [app_class.__package__ for app_class in djmodels.get_apps() if app_class and app_class.__package__] fuzzy_app_name = fuzzy.extractOne(str(app), app_names)[0] if verbosity > 0: print 'WARNING: Best fuzzy match for app name %r is %s' % (app, fuzzy_app_name) return djmodels.get_app(fuzzy_app_name.split('.')[-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_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[0]) else: return None raise NotImplementedError("Unknown default model name. Don't know where to look for field %s" % '.'.join(field)) field = model._meta.get_field(field[-1]) return 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, tuple)): for i, title_prefix in enumerate(title_prefix): if isinstance(title_prefix, basestring): if title_prefix.lower().endswith('sales'): title_prefix = title_prefix[:-5].strip('_') title_prefix += [title_prefix] model_list += ['WikiItem'] else: model_list += [DEFAULT_MODEL] filter_dicts += [{'model__startswith': title_prefix}] elif isinstance(title_prefix, dict): filter_dicts = [title_prefix] elif isinstance(title_prefix, (list, tuple)): filter_dicts = util.listify(title_prefix) model = get_model(model, app) querysets = [] for filter_dict, model in zip(filter_dicts, model_list): filter_dict = filter_dict or {} querysets += [model.objects.filter(**filter_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 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 field names without consulting a synonyms list Returns: list: A list model field names (strings) sorted from most likely to least likely. [] If no similar field names could be found in the indicated model [None] If none found and and `pad_with_none` set Examples: ['date', 'model', 'net_sales'] """
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] >= score_cutoff: matched_fields += [match[0]] elif pad_with_none: matched_fields += [None] return matched_fields
<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 path, like 'project.app.model' Returns: Django Model-based class """
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(module, 'models'), model_name) except AttributeError: model = get_model(model_name, app_name, fuzziness=fuzziness) return model
<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 matching to find a similarly named field Returns: A single model field name (string) Examples: 'end_date_time' 'date_time' 'date_time' """
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) # print match if match and match[1] >= score_cutoff: if not best_match or match[1] > (root_preference * best_ratio): best_match, best_ratio = match return best_match
<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 models in an app called "miner": """
# 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 settings.INSTALLED_APPS) for app in apps: # print 'getting %r, from app %r' % (model_name, app) model = get_model(model=model_name, app=app, fuzziness=fuzziness) if model: return model 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 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 values by the specified number of samples. FIXME: sort has no effect when sequences provided in x, y instead of field names ([0.1, 0.2, 0.3, 0.4], [0, 1, 2, 3]) ([0.1, 0.2, 0.3, 0.4], [0, 1, 2, 3]) """
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 and len(y) == len(x): if sort: xy = sorted(zip(x,y), reverse=bool(int(sort) < 0)) x, y = [col1 for col1, col2 in xy], [col2 for col1, col2 in xy] return x, lagged_seq(y, lag=lag, pad=pad, truncate=truncate) if x and len(x) and 2 == len(x) <= len(x[0]): #print 'X:', x x, y = x[0], lagged_seq(x[1], lag=lag, pad=pad, truncate=truncate) if truncate: print truncate, lag if lag >= 0: x = x[lag:] else: x = x[:lag] #print x, y return x, y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def django_object_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), ignore_related=True, strip=True, ignore_errors=True, verbosity=0): """Construct Django model instance from values provided in a python dict or Mapping Args: row (list or dict): Data (values of any type) to be assigned to fields in the Django object. If `row` is a list, then the column names (header row) can be provided in `field_names`. If `row` is a list and no field_names are provided, then `field_names` will be taken from the Django model class field names, in the order they appear within the class definition. model (django.db.models.Model): The model class to be constructed with data from `row` field_names (list or tuple of str): The field names to place the row values in. Defaults to the keys of the dict of `row` (if `row` is a `dict`) or the names of the fields in the Django model being constructed. ignore_fields (list or tuple of str): The field names to ignore if place the row values in. Returns: Model instance: Django model instance constructed with values from `row` in fields from `field_names` or `model`'s fields """
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 try: obj = model(**field_dict) return obj, errors except: print_exc() raise ValueError('Unable to coerce the dict = %r into a %r object' % (field_dict, model))
<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 i + 1