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 fromexcel(cls, path, sheet_name_or_num=0, headers=None): """ Constructs a new DataTable from an Excel file. Specify sheet_name_or_number to load that specifi...
reader = ExcelRW.UnicodeDictReader(path, sheet_name_or_num) return cls(reader, headers=headers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __print_table(self, row_delim, header_delim=None, header_pad=u"", pad=u""): """ row_delim default delimiter inserted between columns of every row in the tabl...
if header_delim is None: header_delim = row_delim num_cols = len(self.fields) accumulator = ((u"%s" + header_delim) * num_cols)[:-len(header_delim)] accumulator = ((header_pad + accumulator + header_pad + u"\n") % tuple(self.fields)) for dataro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, func, *fields): """ Applies the function, `func`, to every row in the DataTable. If no fields are supplied, the entire row is passed to `func`. I...
results = [] for row in self: if not fields: results.append(func(row)) else: if any(field not in self for field in fields): for field in fields: if field not in self: raise 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 col(self, col_name_or_num): """ Returns the col at index `colnum` or name `colnum`. """
if isinstance(col_name_or_num, basestring): return self[col_name_or_num] elif isinstance(col_name_or_num, (int, long)): if col_name_or_num > len(self.fields): raise IndexError("Invalid column index `%s` for DataTable" % col_name_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 distinct(self, fieldname, key=None): """ Returns the unique values seen at `fieldname`. """
return tuple(unique_everseen(self[fieldname], key=key))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mask(self, masklist): """ `masklist` is an array of Bools or equivalent. This returns a new DataTable using only the rows that were True (or equivalent) in t...
if not hasattr(masklist, '__len__'): masklist = tuple(masklist) if len(masklist) != len(self): raise Exception("Masklist length (%s) must match length " "of DataTable (%s)" % (len(masklist), len(self))) new_datatable = DataTable() 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 mutapply(self, function, fieldname): """ Applies `function` in-place to the field name specified. In other words, `mutapply` overwrites column `fieldname` it...
self[fieldname] = self.apply(function, fieldname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename(self, old_fieldname, new_fieldname): """ Renames a specific field, and preserves the underlying order. """
if old_fieldname not in self: raise Exception("DataTable does not have field `%s`" % old_fieldname) if not isinstance(new_fieldname, basestring): raise ValueError("DataTable fields must be strings, not `%s`" % type(new_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 reorder(self, fields_in_new_order): """ Pass in field names in the order you wish them to be swapped. """
if not len(fields_in_new_order) == len(self.fields): raise Exception("Fields to reorder with are not the same length " "(%s) as the original fields (%s)" % (len(fields_in_new_order), len(self.fields))) if not set(fields_in_new_order) =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample(self, num): """ Returns a new table with rows randomly sampled. We create a mask with `num` True bools, and fill it with False bools until it is the l...
if num > len(self): return self.copy() elif num < 0: raise IndexError("Cannot sample a negative number of rows " "from a DataTable") random_row_mask = ([True] * num) + ([False] * (len(self) - num)) shuffle(random_row_mask) 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 select(self, *cols): """ Returns DataTable with a subset of columns in this table """
return DataTable([cols] + zip(*[self[col] for col in cols]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort(self, fieldname, key=lambda x: x, desc=False, inplace=False): """ This matches Python's built-in sorting signature closely. By default, a new DataTable ...
try: field_index = tuple(self.fields).index(fieldname) except ValueError: raise ValueError("Sorting on a field that doesn't exist: `%s`" % fieldname) data_cols = izip(*sorted(izip(*[self.__data[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 where(self, fieldname, value, negate=False): """ Returns a new DataTable with rows only where the value at `fieldname` == `value`. """
if negate: return self.mask([elem != value for elem in self[fieldname]]) else: return self.mask([elem == value for elem in self[fieldname]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wheregreater(self, fieldname, value): """ Returns a new DataTable with rows only where the value at `fieldname` > `value`. """
return self.mask([elem > value for elem in self[fieldname]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def whereless(self, fieldname, value): """ Returns a new DataTable with rows only where the value at `fieldname` < `value`. """
return self.mask([elem < value for elem in self[fieldname]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wherenot(self, fieldname, value): """ Logical opposite of `where`. """
return self.where(fieldname, value, negate=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 wherenotin(self, fieldname, value): """ Logical opposite of `wherein`. """
return self.wherein(fieldname, value, negate=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 writexlsx(self, path, sheetname="default"): """ Writes this table to an .xlsx file at the specified path. If you'd like to specify a sheetname, you may do so...
writer = ExcelRW.UnicodeWriter(path) writer.set_active_sheet(sheetname) writer.writerow(self.fields) writer.writerows(self) writer.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pyuri_formatter(namespace, value): """ Formats a namespace and ending value into a python friendly format args: namespace: RdfNamespace or tuple in the forma...
if namespace[0]: return "%s_%s" %(namespace[0], value) else: return "pyuri_%s_%s" % (base64.b64encode(bytes(namespace[1], "utf-8")).decode(), 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 robots(self): """Return values for robots html meta key"""
r = 'noindex' if self.is_noindex else 'index' r += ',' r += 'nofollow' if self.is_nofollow else 'follow' return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_common_args(parser, is_create=True): """If is_create is True, protocol and action become mandatory arguments. CreateCommand = is_create : True UpdateCom...
parser.add_argument( '--name', help=_('Name for the firewall rule.')) parser.add_argument( '--description', help=_('Description for the firewall rule.')) parser.add_argument( '--source-ip-address', help=_('Source IP address or subnet.')) parser.add_argume...
<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_relation_by_type_list(parser, token): """Gets list of relations from object identified by a content type. Syntax:: {% get_relation_list [content_type_app...
tokens = token.contents.split() if len(tokens) not in (6, 7): raise template.TemplateSyntaxError( "%r tag requires 6 arguments" % tokens[0] ) if tokens[2] != 'for': raise template.TemplateSyntaxError( "Third argument in %r tag must be 'for'" % tokens[0] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def filter(cls, **items): ''' Returns multiple Union objects with search params ''' client = cls._new_api_client(subpath='/search') items_dict = dict((k, v) for k, v in list(items.items())) json_data = json.dumps(items_dict, sort_keys=True, indent=4) return 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(cls, id): ''' Look up one Union object ''' client = cls._new_api_client() return client.make_request(cls, 'get', url_params={'id': 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 save(self): ''' Save an instance of a Union object ''' client = self._new_api_client() params = {'id': self.id} if hasattr(self, 'id') else {} action = 'patch' if hasattr(self, 'id') else 'post' saved_model = client.make_request(self, action, url_params=param...
<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(cls, id): ''' Destroy a Union object ''' client = cls._new_api_client() return client.make_request(cls, 'delete', url_params={'id': 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 applyconfiguration(targets, conf=None, *args, **kwargs): """Apply configuration on input targets. If targets are not annotated by a Configurable, a new one i...
result = [] for target in targets: configurables = Configurable.get_annotations(target) if not configurables: configurables = [Configurable()] for configurable in configurables: configuredtargets = configurable.applyconfiguration( targets=[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 getcallparams( self, target, conf=None, args=None, kwargs=None, exec_ctx=None ): """Get target call parameters. :param list args: target call arguments. :par...
if args is None: args = [] if kwargs is None: kwargs = {} if conf is None: conf = self.conf params = conf.params try: argspec = getargspec(target) except TypeError as tex: argspec = None callar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modules(self, value): """Change required modules. Reload modules given in the value. :param list value: new modules to use."""
modules = [module.__name__ for module in self.loadmodules(value)] self._modules = [ module for module in self._modules + modules if module not in self._modules ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conf(self, value): """Change of configuration. :param value: new configuration to use. :type value: Category or Configuration """
self._conf = self._toconf(value) if self.autoconf: self.applyconfiguration()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _toconf(self, conf): """Convert input parameter to a Configuration. :param conf: configuration to convert to a Configuration object. :type conf: Configuratio...
result = conf if result is None: result = Configuration() elif isinstance(result, Category): result = configuration(result) elif isinstance(result, Parameter): result = configuration(category('', result)) elif isinstance(result, 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 paths(self, value): """Change of paths in adding it in watching list."""
if value is None: value = () elif isinstance(value, string_types): value = (value, ) self._paths = tuple(value) if self.autoconf: self.applyconfiguration()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getconf( self, conf=None, paths=None, drivers=None, logger=None, modules=None ): """Get a configuration from paths. :param conf: conf to update. Default this...
result = None self.loadmodules(modules=modules) modules = [] conf = self._toconf(conf) # start to initialize input params if conf is None: conf = self.conf.copy() else: selfconf = self.conf.copy() selfconf.update(conf) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure( self, conf=None, targets=None, logger=None, callconf=False, keepstate=None, modules=None ): """Apply input conf on targets objects. Specialization...
result = [] self.loadmodules(modules=modules) modules = [] conf = self._toconf(conf) if conf is None: conf = self.conf if targets is None: targets = self.targets if logger is None: logger = self.logger if keepsta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _configure( self, target, conf=None, logger=None, callconf=None, keepstate=None, modules=None ): """Configure this class with input conf only if auto_conf or...
result = target self.loadmodules(modules=modules) modules = [] if conf is None: conf = self.conf if logger is None: logger = self.logger if callconf is None: callconf = self.callparams if keepstate is None: ke...
<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_matches(self, text): """Return candidates matching the text."""
if self.use_main_ns: self.namespace = __main__.__dict__ if "." in text: return self.attr_matches(text) else: return self.global_matches(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict_camel_to_snake_case(camel_dict, convert_keys=True, convert_subkeys=False): """ Recursively convert camelCased keys for a camelCased dict into snake_case...
converted = {} for key, value in camel_dict.items(): if isinstance(value, dict): new_value = dict_camel_to_snake_case(value, convert_keys=convert_subkeys, convert_subkeys=True) elif isinstance(value, list): new_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 dict_snake_to_camel_case(snake_dict, convert_keys=True, convert_subkeys=False): """ Recursively convert a snake_cased dict into a camelCased dict :param snak...
converted = {} for key, value in snake_dict.items(): if isinstance(value, dict): new_value = dict_snake_to_camel_case(value, convert_keys=convert_subkeys, convert_subkeys=True) elif isinstance(value, list): new_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 dubstep(client, channel, nick, message, matches): """ Dubstep can be described as a rapid succession of wub wubs, wow wows, and yep yep yep yeps """
now = time.time() if dubstep._last and (now - dubstep._last) > WUB_TIMEOUT: dubstep._counts[channel] = 0 dubstep._last = now if dubstep._counts[channel] >= MAX_WUBS: dubstep._counts[channel] = 0 return u'STOP! MY HEAD IS VIBRATING' else: dubstep._counts[channel] +=...
<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_tree(profile, sha, recursive=True): """Fetch a tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell t...
resource = "/trees/" + sha if recursive: resource += "?recursive=1" data = api.get_request(profile, resource) return prepare(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 create_tree(profile, tree): """Create a new tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this mod...
resource = "/trees" payload = {"tree": tree} data = api.post_request(profile, resource, payload) return prepare(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 validate(self): """Ensure that all fields' values are valid and that non-nullable fields are present. """
for field_name, field_obj in self._fields.items(): value = field_obj.__get__(self, self.__class__) if value is None and field_obj.null is False: raise ValidationError('Non-nullable field {0} is set to None'.format(field_name)) elif value is None and field_ob...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_json(self): """Converts given document to JSON dict. """
json_data = dict() for field_name, field_obj in self._fields.items(): if isinstance(field_obj, NestedDocumentField): nested_document = field_obj.__get__(self, self.__class__) value = None if nested_document is None else nested_document.to_json() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_json(cls, json_data): """ Converts json data to a new document instance"""
new_instance = cls() for field_name, field_obj in cls._get_fields().items(): if isinstance(field_obj, NestedDocumentField): if field_name in json_data: nested_field = field_obj.__get__(new_instance, new_instance.__class__) if not neste...
<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, conn, tmp, module_name, module_args, inject): ''' handler for template operations ''' if not self.runner.is_playbook: raise errors.AnsibleError("in current versions of ansible, templates are only usable in playbooks") # load up options options = utils.parse_k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decompose_dateint(dateint): """Decomposes the given dateint into its year, month and day components. Arguments --------- dateint : int An integer object deci...
year = int(dateint / 10000) leftover = dateint - year * 10000 month = int(leftover / 100) day = leftover - month * 100 return year, month, day
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dateint_to_datetime(dateint): """Converts the given dateint to a datetime object, in local timezone. Arguments --------- dateint : int An integer object deci...
if len(str(dateint)) != 8: raise ValueError( 'Dateints must have exactly 8 digits; the first four representing ' 'the year, the next two the months, and the last two the days.') year, month, day = decompose_dateint(dateint) return datetime(year=year, month=month, day=day)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dateint_to_weekday(dateint, first_day='Monday'): """Returns the weekday of the given dateint. Arguments --------- dateint : int An integer object decipting a...
weekday_ix = dateint_to_datetime(dateint).weekday() return (weekday_ix - WEEKDAYS.index(first_day)) % 7
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_dateint(dateint, day_shift): """Shifts the given dateint by the given amount of days. Arguments --------- dateint : int An integer object decipting a s...
dtime = dateint_to_datetime(dateint) delta = timedelta(days=abs(day_shift)) if day_shift > 0: dtime = dtime + delta else: dtime = dtime - delta return datetime_to_dateint(dtime)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dateint_range(first_dateint, last_dateint): """Returns all dateints in the given dateint range. Arguments --------- first_dateint : int An integer object dec...
first_datetime = dateint_to_datetime(first_dateint) last_datetime = dateint_to_datetime(last_dateint) delta = last_datetime - first_datetime delta_in_hours = math.ceil(delta.total_seconds() / 3600) delta_in_days = math.ceil(delta_in_hours / 24) + 1 dateint_set = set() for delta_i in range(0...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dateint_week_by_dateint(dateint, first_day='Monday'): """Return a dateint range of the week the given dateint belongs to. Arguments --------- dateint : int A...
weekday_ix = dateint_to_weekday(dateint, first_day) first_day_dateint = shift_dateint(dateint, -weekday_ix) last_day_dateint = shift_dateint(first_day_dateint, 6) return dateint_range(first_day_dateint, last_day_dateint)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dateint_difference(dateint1, dateint2): """Return the difference between two dateints in days. Arguments --------- dateint1 : int An integer object decipting...
dt1 = dateint_to_datetime(dateint1) dt2 = dateint_to_datetime(dateint2) delta = dt1 - dt2 return abs(delta.days)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copyFile(src, dest): """Copies a source file to a destination whose path may not yet exist. Keyword arguments: src -- Source path to a file (string) dest -- ...
#Src Exists? try: if os.path.isfile(src): dpath, dfile = os.path.split(dest) if not os.path.isdir(dpath): os.makedirs(dpath) if not os.path.exists(dest): touch(dest) try: shutil.copy2(src, dest) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _terminal_notifier(title, message): """ Shows user notification message via `terminal-notifier` command. `title` Notification title. `message` Notification m...
try: paths = common.extract_app_paths(['terminal-notifier']) except ValueError: pass common.shell_process([paths[0], '-title', title, '-message', 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 _growlnotify(title, message): """ Shows growl notification message via `growlnotify` command. `title` Notification title. `message` Notification message. """
try: paths = common.extract_app_paths(['growlnotify']) except ValueError: return common.shell_process([paths[0], '-t', title, '-m', 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 _dbus_notify(title, message): """ Shows system notification message via dbus. `title` Notification title. `message` Notification message. """
try: # fetch main account manager interface bus = dbus.SessionBus() obj = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications') if obj: iface = dbus.Interface(obj, 'org.freedesktop.Notifications') if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _notify(self, task, message): """ Shows system notification message according to system requirements. `message` Status message. """
if self.notify_func: message = common.to_utf8(message.strip()) title = common.to_utf8(u'Focus ({0})'.format(task.name)) self.notify_func(title, 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 parse_option(self, option, block_name, message): """ Parse show, end_show, and timer_show options. """
if option == 'show': option = 'start_' + option key = option.split('_', 1)[0] self.messages[key] = 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 format_value(value): """ Convert a list into a comma separated string, for displaying select multiple values in emails. """
if isinstance(value, list): value = ", ".join([v.strip() for v in 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 form_processor(request, page): """ Display a built form and handle submission. """
form = FormForForm(page.form, RequestContext(request), request.POST or None, request.FILES or None) if form.is_valid(): url = page.get_absolute_url() + "?sent=1" if is_spam(request, form, url): return redirect(url) attachments = [] for f in 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 visible(self): """ Only shown on the sharing view """
context_state = api.content.get_view(context=self.context, request=self.request, name="plone_context_state") url = context_state.current_base_url() return url.endswith('@@sharing')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def active_participant_policy(self): """ Get the title of the current participation policy """
key = self.context.participant_policy policy = PARTICIPANT_POLICY.get(key) return policy['title']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_integrity_multilevel(d1, d2): """ still under development """
keys = [x for x in d2] for key in keys: d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_keys modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[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 read_local_config(cfg): """ Parses local config file for override values Args: :local_file (str): filename of local config file Returns: dict object of valu...
try: if os.path.exists(cfg): config = import_file_object(cfg) return config else: logger.warning( '%s: local config file (%s) not found, cannot be read' % (inspect.stack()[0][3], str(cfg))) except IOError as e: logger.w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formfield_for_dbfield(self, db_field, **kwargs): """ Adds the "Send to Twitter" checkbox after the "status" field, provided by any ``Displayable`` models. Th...
formfield = super(TweetableAdminMixin, self).formfield_for_dbfield(db_field, **kwargs) if Api and db_field.name == "status" and get_auth_settings(): def wrapper(render): def wrapped(*args, **kwargs): rendered = render(*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 command(cmd): """Execute command and raise an exception upon an error. True Traceback (most recent call last): SdistCreationError """
status, out = commands.getstatusoutput(cmd) if status is not 0: logger.error("Something went wrong:") logger.error(out) raise SdistCreationError() return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenize_number(val, line): """Parse val correctly into int or float."""
try: num = int(val) typ = TokenType.int except ValueError: num = float(val) typ = TokenType.float return {'type': typ, 'value': num, 'line': line}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadHistory(self): """ Loads the shop sale history Raises parseException """
pg = self.usr.getPage("http://www.neopets.com/market.phtml?type=sales")\ try: rows = pg.find("b", text = "Date").parent.parent.parent.find_all("tr") # First and last row do not contain entries rows.pop(0) rows.pop(-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 edit_entry(self, id_, **kwargs): """ Edits a time entry by ID. Takes the same data as `create_entry`, but requires an ID to work. It also takes a `force` par...
data = self._wrap_dict("time_entry", kwargs) return self.patch("/time_entries/{}.json".format(id_), 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 start_tracker(self, id_, **kwargs): """ Starts a tracker for the time entry identified by `id_`. """
data = None if kwargs: data = self._wrap_dict("tracker", self._wrap_dict("tracking_time_entry", kwargs)) return self.patch("/tracker/{}.json".format(id_), data=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 edit_customer(self, id_, **kwargs): """ Edits a customer by ID. All fields available at creation can be updated as well. If you want to update hourly rates r...
data = self._wrap_dict("customer", kwargs) return self.patch("/customers/{}.json".format(id_), data=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 edit_project(self, id_, **kwargs): """ Edits a project by ID. All fields available at creation can be updated as well. If you want to update hourly rates ret...
data = self._wrap_dict("project", kwargs) return self.patch("/projects/{}.json".format(id_), data=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 edit_service(self, id_, **kwargs): """ Edits a service by ID. All fields available at creation can be updated as well. If you want to update hourly rates ret...
data = self._wrap_dict("service", kwargs) return self.patch("/services/{}.json".format(id_), data=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 get_committed_signatures(vcs): """Get the list of committed signatures Args: vcs (easyci.vcs.base.Vcs) Returns: list(basestring) - list of signatures """
committed_path = _get_committed_history_path(vcs) known_signatures = [] if os.path.exists(committed_path): with open(committed_path, 'r') as f: known_signatures = f.read().split() return known_signatures
<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_staged_signatures(vcs): """Get the list of staged signatures Args: vcs (easyci.vcs.base.Vcs) Returns: list(basestring) - list of signatures """
staged_path = _get_staged_history_path(vcs) known_signatures = [] if os.path.exists(staged_path): with open(staged_path, 'r') as f: known_signatures = f.read().split() return known_signatures
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit_signature(vcs, user_config, signature): """Add `signature` to the list of committed signatures The signature must already be staged Args: vcs (easyci....
if signature not in get_staged_signatures(vcs): raise NotStagedError evidence_path = _get_committed_history_path(vcs) committed_signatures = get_committed_signatures(vcs) if signature in committed_signatures: raise AlreadyCommittedError committed_signatures.append(signature) 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 stage_signature(vcs, signature): """Add `signature` to the list of staged signatures Args: vcs (easyci.vcs.base.Vcs) signature (basestring) Raises: AlreadySt...
evidence_path = _get_staged_history_path(vcs) staged = get_staged_signatures(vcs) if signature in staged: raise AlreadyStagedError staged.append(signature) string = '\n'.join(staged) with open(evidence_path, 'w') as f: f.write(string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unstage_signature(vcs, signature): """Remove `signature` from the list of staged signatures Args: vcs (easyci.vcs.base.Vcs) signature (basestring) Raises: No...
evidence_path = _get_staged_history_path(vcs) staged = get_staged_signatures(vcs) if signature not in staged: raise NotStagedError staged.remove(signature) string = '\n'.join(staged) with open(evidence_path, 'w') as f: f.write(string)
<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_decrpyted_path(encrypted_path, surfix=default_surfix): """ Find the original path of encrypted file or dir. Example: - file: ``${home}/test-encrypted.txt...
surfix_reversed = surfix[::-1] p = Path(encrypted_path).absolute() fname = p.fname fname_reversed = fname[::-1] new_fname = fname_reversed.replace(surfix_reversed, "", 1)[::-1] decrypted_p = p.change(new_fname=new_fname) return decrypted_p.abspath
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(src, dst, converter, overwrite=False, stream=True, chunksize=1024**2, **kwargs): """ A file stream transform IO utility function. :param src: origi...
if not overwrite: # pragma: no cover if Path(dst).exists(): raise EnvironmentError("'%s' already exists!" % dst) with open(src, "rb") as f_input: with open(dst, "wb") as f_output: if stream: # fix chunksize to a reasonable range if chunk...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, tweet): """Add a tweet to the end of the list."""
c = self.connection.cursor() last_tweet = c.execute("SELECT tweet from tweetlist where label='last_tweet'").next()[0] c.execute("INSERT INTO tweets(message, previous_tweet, next_tweet) VALUES (?,?,NULL)", (tweet, last_tweet)) tweet_id = c.lastrowid # Set the current tweet as...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop(self): """Return first tweet in the list."""
c = self.connection.cursor() first_tweet_id = c.execute("SELECT tweet from tweetlist where label='first_tweet'").next()[0] if first_tweet_id is None: # No tweets are in the list, so return None return None tweet = c.execute("SELECT id, message, previous_tweet,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def peek(self): """Peeks at the first of the list without removing it."""
c = self.connection.cursor() first_tweet_id = c.execute("SELECT tweet from tweetlist where label='first_tweet'").next()[0] if first_tweet_id is None: # No tweets are in the list, so return None return None tweet = c.execute("SELECT message from tweets WHERE 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 delete(self, tweet_id): """Deletes a tweet from the list with the given id"""
c = self.connection.cursor() try: tweet = c.execute("SELECT id, message, previous_tweet, next_tweet from tweets WHERE id=?", (tweet_id,)).next() except StopIteration: raise ValueError("No tweets were found with that ID") # Update linked list references ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def usetz_now(): """Determine current time depending on USE_TZ setting. Affects Django 1.4 and above only. if `USE_TZ = True`, then returns current time accordin...
USE_TZ = getattr(settings, 'USE_TZ', False) if USE_TZ and DJANGO_VERSION >= '1.4': return now() else: return datetime.utcnow()
<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_delta(self, now, then): """ Internal helper which will return a ``datetime.timedelta`` representing the time between ``now`` and ``then``. Assumes ``now...
if now.__class__ is not then.__class__: now = datetime.date(now.year, now.month, now.day) then = datetime.date(then.year, then.month, then.day) if now < then: raise ValueError("Cannot determine moderation rules because date field is set to a value in the future") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """ Hook up the moderation methods to pre- and post-save signals from the comment models. """
signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=comments.get_model()) signals.comment_was_posted.connect(self.post_save_moderation, sender=comments.get_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 register(self, model_or_iterable, moderation_class): """ Register a model or a list of models for comment moderation, using a particular moderation class. Ra...
if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model in self._registry: raise AlreadyModerated( "The model '%s' is already being moderated" % model._meta.verbose_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 unregister(self, model_or_iterable): """ Remove a model or a list of models from the list of models whose comments will be moderated. Raise ``NotModerated`` ...
if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model not in self._registry: raise NotModerated("The model '%s' is not currently being moderated" % model._meta.module_name) del se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pre_save_moderation(self, sender, comment, request, **kwargs): """ Apply any necessary pre-save moderation steps to new comments. """
model = comment.content_type.model_class() if model not in self._registry: return content_object = comment.content_object moderation_class = self._registry[model] # Comment will be disallowed outright (HTTP 403 response) if not moderation_class.allow(comment...
<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_save_moderation(self, sender, comment, request, **kwargs): """ Apply any necessary post-save moderation steps to new comments. """
model = comment.content_type.model_class() if model not in self._registry: return self._registry[model].email(comment, comment.content_object, 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 main(args): """ main entry point for the FDR script. :param args: the arguments for this script, as a list of string. Should already have had things like the...
# get options and arguments ui = getUI(args) if ui.optionIsSet("test"): # just run unit tests unittest.main(argv=[sys.argv[0]]) elif ui.optionIsSet("help"): # just show help ui.usage() else: verbose = (ui.optionIsSet("verbose") is True) or DEFAULT_VERBOSITY # header? header = ui...
<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, in_fh, header=False, delimit=None, verbose=False): """ Load this data_table from a stream or file. Blank lines in the file are skipped. Any existi...
self.clear() if verbose: sys.stderr.write("getting input...\n") # figure out whether we need to open a file or not in_strm = in_fh if isinstance(in_strm, basestring): in_strm = open(in_strm) for line in in_strm: line = line.strip() if line == "": continue ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, strm, delim, verbose=False): """ Write this data frame to a stream or file. :param strm: stream to write to; can also be a string, in which case ...
if verbose: sys.stderr.write("outputing...\n") # figure out whether we need to open a file or not out_strm = strm if isinstance(out_strm, basestring): out_strm = open(out_strm) if self.header is not None: out_strm.write(delim.join(self.header)) max_col_len = len(max(self.fra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach_core_filters(cls): """ Attach core filters to filterset """
opts = cls._meta base_filters = cls.base_filters.copy() cls.base_filters.clear() for name, filter_ in six.iteritems(base_filters): if isinstance(filter_, AutoFilters): field = filterset.get_model_field(opts.model, filter_.name) filter_exclusio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def only_for(theme, redirect_to='/', raise_error=None): """ Decorator for restrict access to views according by list of themes. Params: * ``theme`` - string or l...
def check_theme(*args, **kwargs): if isinstance(theme, six.string_types): themes = (theme,) else: themes = theme if settings.CURRENT_THEME is None: return True result = settings.CURRENT_THEME in themes if not result and raise_error is n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_dict(self, document): """Create experiment object from JSON document retrieved from database. Parameters document : JSON Json document in database Retur...
identifier = str(document['_id']) active = document['active'] timestamp = datetime.datetime.strptime(document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f') properties = document['properties'] subject_id = document['subject'] image_group_id = document['images'] fmri_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 list_objects(self, query=None, limit=-1, offset=-1): """List of all experiments in the database. Overrides the super class method to allow the returned objec...
# Call super class method to get the object listing result = super(DefaultExperimentManager, self).list_objects( query=query, limit=limit, offset=offset ) # Run aggregate count on predictions if collection was given if not self.coll_prediction...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_fmri_data(self, identifier, fmri_data_id): """Associate the fMRI object with the identified experiment. Parameters identifier : string Unique experime...
# Get experiment to ensure that it exists experiment = self.get_object(identifier) if experiment is None: return None # Update fmri_data property and replace existing object with updated one experiment.fmri_data_id = fmri_data_id self.replace_object(experimen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config(): """ Load system configuration @rtype: ConfigParser """
cfg = ConfigParser() cfg.read(os.path.join(os.path.dirname(os.path.realpath(ips_vagrant.__file__)), 'config/ipsv.conf')) return cfg