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 __get_hosts(self, pattern): """ finds hosts that postively match a particular pattern. Does not take into account negative matches. """
(name, enumeration_details) = self._enumeration_info(pattern) hpat = self._hosts_in_unenumerated_pattern(name) hpat = sorted(hpat, key=lambda x: x.name) return set(self._apply_ranges(pattern, hpat))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _hosts_in_unenumerated_pattern(self, pattern): """ Get all host names matching the pattern """
hosts = {} # ignore any negative checks here, this is handled elsewhere pattern = pattern.replace("!","").replace("&", "") groups = self.get_groups() for group in groups: for host in group.get_hosts(): if pattern == 'all' or self._match(group.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 restrict_to(self, restriction): """ Restrict list operations to the hosts given in restriction. This is used to exclude failed hosts in main playbook code, d...
if type(restriction) != list: restriction = [ restriction ] self._restriction = restriction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def also_restrict_to(self, restriction): """ Works like restict_to but offers an additional restriction. Playbooks use this to implement serial behavior. """
if type(restriction) != list: restriction = [ restriction ] self._also_restriction = restriction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_file(self): """ did inventory come from a file? """
if not isinstance(self.host_list, basestring): return False return os.path.exists(self.host_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 register(tag, end_tag=None): """ Decorator for registering shortcode functions. """
def register_function(function): tagmap[tag] = {'func': function, 'endtag': end_tag} if end_tag: tagmap['endtags'].append(end_tag) return function return register_function
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_time_param(t): """Check whether a string sent in matches the ISO8601 format. If a Datetime object is passed instead, it will be converted into an ISO86...
if type(t) is str: if not ISO.match(t): raise ValueError('Date string "%s" does not match ISO8601 format' % (t)) return t else: return t.isoformat()
<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_iso_stamp(t, tz=None): """Convert a string in ISO8601 form into a Datetime object. This is mainly used for converting timestamps sent from the TempoD...
if t is None: return None dt = dateutil.parser.parse(t) if tz is not None: timezone = pytz.timezone(tz) if dt.tzinfo is None: dt = timezone.localize(dt) return dt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_weekday(weekday): """Returns the name of the weekday after the given weekday name."""
ix = WEEKDAYS.index(weekday) if ix == len(WEEKDAYS)-1: return WEEKDAYS[0] return WEEKDAYS[ix+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 prev_weekday(weekday): """Returns the name of the weekday before the given weekday name."""
ix = WEEKDAYS.index(weekday) if ix == 0: return WEEKDAYS[len(WEEKDAYS)-1] return WEEKDAYS[ix-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 workdays(first_day=None): """Returns a list of workday names. Arguments --------- first_day : str, default None The first day of the five-day work week. If n...
if first_day is None: first_day = 'Monday' ix = _lower_weekdays().index(first_day.lower()) return _double_weekdays()[ix:ix+5]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def weekdays(first_day=None): """Returns a list of weekday names. Arguments --------- first_day : str, default None The first day of the week. If not given, 'Mon...
if first_day is None: first_day = 'Monday' ix = _lower_weekdays().index(first_day.lower()) return _double_weekdays()[ix:ix+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 buyQuestItems(self): """ Attempts to buy all quest items, returns result Returns bool - True if successful, otherwise False """
for item in self.items: us = UserShopFront(self.usr, item.owner, item.id, str(item.price)) us.loadInventory() if not item.name in us.inventory: return False if not us.inventory[item.name].buy(): 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 submitQuest(self): """ Submits the active quest, returns result Returns bool - True if successful, otherwise False """
form = pg.form(action="kitchen2.phtml") pg = form.submit() if "Woohoo" in pg.content: try: self.prize = pg.find(text = "The Chef waves his hands, and you may collect your prize...").parent.parent.find_all("b")[-1].text except 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 youtube(no_controls, no_autoplay, store, store_name, youtube_url): """Convert a Youtube URL so that works correctly with Helium. This command is used for con...
old_url_colour = 'blue' new_url_colour = 'green' echo('Format --> {0}: {1}'.format( style('Original URL/Stored Title', fg=old_url_colour), style('New URL', fg=new_url_colour) )) for url in youtube_url: new_url = convert_youtube_url(url, no_controls, no_autoplay) if 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 list(): """Use this function to display all of the stored URLs. This command is used for displaying all of the URLs and their names from the stored list. """
for name, url in get_all_data().items(): echo('{}: {}'.format( style(name, fg='blue'), style(url, fg='green') ))
<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_class_by_path(class_path: str, is_module: Optional[bool] = False) -> type: """ Get class by its name within a package structure. :param class_path: E.g. b...
if is_module: try: backend_module = importlib.import_module(class_path) except ImportError: logger.warning("Can't import backend with name `%s`", class_path) raise else: return backend_module module_name, class_name = class_path.rsplit('...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: """Get list of submodules for some package by its path. E.g ``pkg.subpackage``"""
pkg = importlib.import_module(package_path) subs = ( ModuleDescription( name=modname, path="{}.{}".format(package_path, modname), is_package=ispkg ) for importer, modname, ispkg in pkgutil.iter_modules(pkg.__path__) ) result = tuple(subs) return resu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: """ Makes tuple to use in Django's Fields ``choices`` attribute. Enum members names will be titles for the choices. :param source: Enum to process. :return: Tuple...
result = tuple((s.value, s.name.title()) for s in source) 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 is_contradictory(self, other): """ Returns True if the two DictCells are unmergeable. """
if not isinstance(other, DictCell): raise Exception("Incomparable") for key, val in self: if key in other.__dict__['p'] \ and val.is_contradictory(other.__dict__['p'][key]): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """ This method converts the DictCell into a python `dict`. This is useful for JSON serialization. """
output = {} for key, value in self.__dict__['p'].iteritems(): if value is None or isinstance(value, SIMPLE_TYPES): output[key] = value elif hasattr(value, 'to_dot'): output[key] = value.to_dot() elif hasattr(value, 'to_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 to_latex(self): """ Returns a LaTeX representation of an attribute-value matrix """
latex = r"[{} " for attribute, value in self: if attribute in ['speaker_model', 'is_in_commonground']: continue value_l = value.to_latex() if value_l == "": continue latex += "{attribute:<15} & {value:<20} \\\\ \n".format(attribute=attribute, value=valu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def business_days(start, stop): """ Return business days between two inclusive dates - ignoring public holidays. Note that start must be less than stop or else 0...
dates=rrule.rruleset() # Get dates between start/stop (which are inclusive) dates.rrule(rrule.rrule(rrule.DAILY, dtstart=start, until=stop)) # Exclude Sat/Sun dates.exrule(rrule.rrule(rrule.DAILY, byweekday=(rrule.SA, rrule.SU), dtstart=start)) return dates.count()
<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_anniversary_periods(start, finish, anniversary=1): """ Return a list of anniversaries periods between start and finish. """
import sys current = start periods = [] while current <= finish: (period_start, period_finish) = date_period(DATE_FREQUENCY_MONTHLY, anniversary, current) current = period_start + relativedelta(months=+1) period_start = period_start if period_start > start else start per...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def previous_quarter(d): """ Retrieve the previous quarter for dt """
from django_toolkit.datetime_util import quarter as datetime_quarter return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_field_changed(instance, old_instance, field_name, update_fields=None): """ Examines update_fields and an attribute of an instance to determine if that...
if update_fields is not None and field_name not in update_fields: return False return getattr(instance, field_name) != getattr(old_instance, field_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def play(self): """Play the match. This match simulator iterates through two lists of random numbers 25 times, one for each team, comparing the numbers and award...
score1 = 0 score2 = 0 for __ in range(25): num1 = random.randint(0, 100) num2 = random.randint(0, 100) if num1 > num2: score1 += 1 elif num2 > num1: score2 += 1 if score1 > score2: self.winner = ...
<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_logger(name, formatter=None, handler=None, level=None): """ Returns a new logger for the specified name. """
logger = logging.getLogger(name) #: remove existing handlers logger.handlers = [] #: use a standard out handler if handler is None: handler = logging.StreamHandler(sys.stdout) #: set the formatter when a formatter is given if formatter is not None: handler.setFormatter(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 splitstatus(a,statusfn): 'split sequence into subsequences based on binary condition statusfn. a is a list, returns list of lists' groups=[]; mode=None for elt,status in zip(a,map(statusfn,a)): assert isinstance(status,bool) if status!=mode: mode=status; group=[mode]; groups.append(group) gr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ungroupslice(groups,gslice): 'this is a helper for contigsub.' 'coordinate transform: takes a match from seqingroups() and transforms to ungrouped coordinates' eltsbefore=0 for i in range(gslice[0]): eltsbefore+=len(groups[i])-1 x=eltsbefore+gslice[1]; return [x-1,x+gslice[2]-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 translate_diff(origtext,deltas): 'take diff run on separated words and convert the deltas to character offsets' lens=[0]+cumsum(map(len,splitpreserve(origtext))) # [0] at the head for like 'length before' return [Delta(lens[a],lens[b],''.join(replace)) for a,b,replace in deltas]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def word_diff(a,b): 'do diff on words but return character offsets' return translate_diff(a,rediff(splitpreserve(a),splitpreserve(b)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def checkdiff(a,b,sp=True): 'take diff of a to b, apply to a, return the applied diff so external code can check it against b' if sp: a=splitpreserve(a); b=splitpreserve(b) res=applydiff(a,rediff(a,b)) if sp: res=''.join(res) return res
<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(cls, source, *, transform_args=None): """Create an instance of the class from the source. By default cls.transform_args is used, but can be overridden...
if transform_args is None: transform_args = cls.transform_args return cls(get_obj(source, *transform_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 map(cls, sources, *, transform_args=None): """Generates instances from the sources using either cls.transform_args or transform_args argument if present. """
for idx, source in enumerate(sources): try: yield cls.create(source, transform_args=transform_args) except Exception as ex: raise Exception("An error occurred with item {0}".format(idx)) 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 save(self, *args, **kwargs): """ Set the current site ID, and ``is_public`` based on the setting ``COMMENTS_DEFAULT_APPROVED``. """
if not self.id: self.is_public = settings.COMMENTS_DEFAULT_APPROVED self.site_id = current_site_id() super(ThreadedComment, self).save(*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 save(self, *args, **kwargs): """ Validate that the rating falls between the min and max values. """
valid = map(str, settings.RATINGS_RANGE) if str(self.value) not in valid: raise ValueError("Invalid rating. %s is not in %s" % (self.value, ", ".join(valid))) super(Rating, self).save(*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 add_mutex_switch(parser, dest, arguments=set(), default=None, single_arg=False, required=False): """Adds mutually exclusive switch arguments. Args: arguments...
if default is not None: assert default in arguments if isinstance(arguments, set): arguments = {k: None for k in arguments} if not single_arg: mg = parser.add_mutually_exclusive_group(required=required) for name, help_text in arguments.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 _save_action(extra_context=None): ''' Save list of revisions revisions for active Conda environment. .. versionchanged:: 0.18 Compress action revision files using ``bz2`` to save disk space. Parameters ---------- extra_context : dict, optional Extra content to store in stor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def available_packages(*args, **kwargs): ''' Query available plugin packages based on specified Conda channels. Parameters ---------- *args Extra arguments to pass to Conda ``search`` command. Returns ------- dict .. versionchanged:: 0.24 All Conda packages ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def install(plugin_name, *args, **kwargs): ''' Install plugin packages based on specified Conda channels. .. versionchanged:: 0.19.1 Do not save rollback info on dry-run. .. versionchanged:: 0.24 Remove channels argument. Use Conda channels as configured in Conda environment. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def uninstall(plugin_name, *args): ''' Uninstall plugin packages. Plugin packages must have a directory with the same name as the package in the following directory: <conda prefix>/share/microdrop/plugins/available/ Parameters ---------- plugin_name : str or list Plugin pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def import_plugin(package_name, include_available=False): ''' Import MicroDrop plugin. Parameters ---------- package_name : str Name of MicroDrop plugin Conda package. include_available : bool, optional If ``True``, import from all available plugins (not just **enabled** ...
<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_related(self, filename=None, content=None, mimetype=None): """ Attaches a file with the given filename and content. The filename can be omitted and th...
if isinstance(filename, MIMEBase): assert content == mimetype == None self.related_attachments.append(filename) else: assert content is not None self.related_attachments.append((filename, content, mimetype))
<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_related_file(self, path, mimetype=None): """Attaches a file from the filesystem."""
filename = os.path.basename(path) content = open(path, 'rb').read() self.attach_related(filename, content, mimetype)
<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_dat_file(self): """ Create and write empty data file in the data directory """
output = "## {}\n".format(self.name) try: kwargs_items = self.kwargs.iteritems() except AttributeError: kwargs_items = self.kwargs.items() for key, val in kwargs_items: if val is "l": output += "#l {}=\n".format(str(key)) e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_data_to_internal(self, data=None): """parse to internal """
if data is None: f = open(self.location_dat, "rb") data = { "PMCA SPECTRUM": {}, "DATA": [], "DP5 CONFIGURATION": {}, "DPP STATUS": {} } delimiter = { "PMCA SPECTRUM": " - ", ...
<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_data_to_internal(self, data=None): """Use numpy loadtxt """
if data is None: kwargs = self.kwargs data = np.loadtxt( open(self.location_dat, "rb"), **kwargs ) if self.filetype is "pickle": pickle.dump(data, open(self.location_internal, "wb")) elif self.filetype is "hickle": impo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ctx_provider(self, func): """ Decorator for adding a context provider. :: @jade.ctx_provider def my_context(): """
func = to_coroutine(func) self.providers.append(func) return func
<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, func): """ Register function to templates. """
if callable(func): self.functions[func.__name__] = func return func
<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(self, path, **context): """ Render a template with context. """
funcs = self.functions ctx = dict(self.functions, jdebug=lambda: dict( (k, v) for k, v in ctx.items() if k not in funcs and k != 'jdebug')) for provider in self.providers: _ctx = yield from provider() ctx.update(_ctx) ctx.update(context) templ...
<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_template(self, path): """ Load and compile a template. """
if not path.startswith('/'): for folder in self.options['template_folders']: fullpath = op.join(folder, path) if op.exists(fullpath): path = fullpath break else: raise JadeException('Template doesnt ...
<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_size(self, data_size): """ Set the data slice size. """
if len(str(data_size)) > self.first: raise ValueError( 'Send size is too large for message size-field width!') self.data_size = data_size
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _is_related(parent_entry, child_entry): '''This function checks if a child entry is related to the parent entry. This is done by comparing the reference and sequence numbers.''' if parent_entry.header.mft_record == child_entry.header.base_record_ref and \ parent_entry.header.seq_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 load_mp(cls, file_pointer, _mft_config=None): '''The initialization process takes a file like object "file_pointer" and loads it in the internal structures. "use_cores" can be definied if multiple cores are to be used. The "size" argument is the size of the MFT entries. If not provid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def finddives2(depths, min_dive_thresh=10): '''Find dives in depth data below a minimum dive threshold Args ---- depths: ndarray Datalogger depth measurements min_dive_thresh: float Minimum depth threshold for which to classify a dive Returns ------- dives: ndarray ...
<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_des_asc2(depths, dive_mask, pitch, cutoff, fs, order=5): '''Get boolean masks of descents and ascents in the depth data Args ---- dive_mask: ndarray Boolean mask array over depth data. Cells with `True` are dives and cells with `False` are not. pitch: ndarray Pitch a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rm_incomplete_des_asc(des_mask, asc_mask): '''Remove descents-ascents that have no corresponding ascent-descent Args ---- des_mask: ndarray Boolean mask of descents in the depth data asc_mask: ndarray Boolean mask of ascents in the depth data Returns ------- des_mas...
<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_bottom(depths, des_mask, asc_mask): '''Get boolean mask of regions in depths the animal is at the bottom Args ---- des_mask: ndarray Boolean mask of descents in the depth data asc_mask: ndarray Boolean mask of ascents in the depth data Returns ------- BOTTOM: nd...
<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_phase(n_samples, des_mask, asc_mask): '''Get the directional phase sign for each sample in depths Args ---- n_samples: int Length of output phase array des_mask: numpy.ndarray, shape (n,) Boolean mask of values where animal is descending asc_mask: numpy.ndarray, shape(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 tempfilename(**kwargs): """ Reserve a temporary file for future use. This is useful if you want to get a temporary file name, write to it in the future and e...
kwargs.update(delete=False) try: f = NamedTemporaryFile(**kwargs) f.close() yield f.name except Exception: if os.path.exists(f.name): # Ensure we clean up after ourself os.unlink(f.name) raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makedirs(p): """ A makedirs that avoids a race conditions for multiple processes attempting to create the same directory. """
try: os.makedirs(p, settings.FILE_UPLOAD_PERMISSIONS) except OSError: # Perhaps someone beat us to the punch? if not os.path.isdir(p): # Nope, must be something else... raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def control_high_limit(self) -> Optional[Union[int, float]]: """ Control high limit setting for a special sensor. For LS-10/LS-20 base units only. """
return self._get_field_value(SpecialDevice.PROP_CONTROL_HIGH_LIMIT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def control_low_limit(self) -> Optional[Union[int, float]]: """ Control low limit setting for a special sensor. For LS-10/LS-20 base units only. """
return self._get_field_value(SpecialDevice.PROP_CONTROL_LOW_LIMIT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current_reading(self) -> Optional[Union[int, float]]: """Current reading for a special sensor."""
return self._get_field_value(SpecialDevice.PROP_CURRENT_READING)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def high_limit(self) -> Optional[Union[int, float]]: """ High limit setting for a special sensor. For LS-10/LS-20 base units this is the alarm high limit. For LS-...
return self._get_field_value(SpecialDevice.PROP_HIGH_LIMIT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def low_limit(self) -> Optional[Union[int, float]]: """ Low limit setting for a special sensor. For LS-10/LS-20 base units this is the alarm low limit. For LS-30 ...
return self._get_field_value(SpecialDevice.PROP_LOW_LIMIT)
<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, device_id: int) -> Optional[Device]: """Get device using the specified ID, or None if not found."""
return self._devices.get(device_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 make_ttv_yaml(corpora, path_to_ttv_file, ttv_ratio=DEFAULT_TTV_RATIO, deterministic=False): """ Create a test, train, validation from the corpora given and s...
dataset = get_dataset(corpora) data_sets = make_ttv(dataset, ttv_ratio=ttv_ratio, deterministic=deterministic) def get_for_ttv(key): return ( data_sets['test'][key], data_sets['train'][key], data_sets['validation'][key] ) test, train, validation = g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_user_config(vcs): """Load the user config Args: vcs (easyci.vcs.base.Vcs) - the vcs object for the current project Returns: dict - the config Raises: Co...
config_path = os.path.join(vcs.path, 'eci.yaml') if not os.path.exists(config_path): raise ConfigNotFoundError with open(config_path, 'r') as f: try: config = yaml.safe_load(f) except yaml.YAMLError: raise ConfigFormatError if not isinstance(config, 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 expose_request(func): """ A decorator that adds an expose_request flag to the underlying callable. @raise TypeError: C{func} must be callable. """
if not python.callable(func): raise TypeError("func must be callable") if isinstance(func, types.UnboundMethodType): setattr(func.im_func, '_pyamf_expose_request', True) else: setattr(func, '_pyamf_expose_request', True) return func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addService(self, service, name=None, description=None, authenticator=None, expose_request=None, preprocessor=None): """ Adds a service to the gateway. @param...
if isinstance(service, (int, long, float, basestring)): raise TypeError("Service cannot be a scalar value") allowed_types = (types.ModuleType, types.FunctionType, types.DictType, types.MethodType, types.InstanceType, types.ObjectType) if not python.callable(service) an...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeService(self, service): """ Removes a service from the gateway. @param service: Either the name or t of the service to remove from the gateway, or . @t...
for name, wrapper in self.services.iteritems(): if service in (name, wrapper.service): del self.services[name] return raise NameError("Service %r not found" % (service,))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getServiceRequest(self, request, target): """ Returns a service based on the message. @raise UnknownServiceError: Unknown service. @param request: The AMF re...
try: return self._request_class( request.envelope, self.services[target], None) except KeyError: pass try: sp = target.split('.') name, meth = '.'.join(sp[:-1]), sp[-1] return self._request_class( requ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getProcessor(self, request): """ Returns request processor. @param request: The AMF message. @type request: L{Request<remoting.Request>} """
if request.target == 'null' or not request.target: from pyamf.remoting import amf3 return amf3.RequestProcessor(self) else: from pyamf.remoting import amf0 return amf0.RequestProcessor(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 mustExposeRequest(self, service_request): """ Decides whether the underlying http request should be exposed as the first argument to the method call. This is...
expose_request = service_request.service.mustExposeRequest(service_request) if expose_request is None: if self.expose_request is None: return False return self.expose_request return expose_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 callServiceRequest(self, service_request, *args, **kwargs): """ Executes the service_request call """
if self.mustExposeRequest(service_request): http_request = kwargs.get('http_request', None) args = (http_request,) + args return service_request(*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 node_input(): """ Get a valid node id from the user. Return -1 if invalid """
try: node = int(raw_input("Node id: ")) except ValueError: node = INVALID_NODE print 'invalid node id: %s' % node return node
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def existing_node_input(): """ Get an existing node id by name or id. Return -1 if invalid """
input_from_user = raw_input("Existing node name or id: ") node_id = INVALID_NODE if not input_from_user: return node_id # int or str? try: parsed_input = int(input_from_user) except ValueError: parsed_input = input_from_user if isinstance(parsed_input, int): ...
<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_value_for_node(node_id): """ Wrap render_node for usage in operate scripts. Returns without template rendered. """
value = None result = [] try: result = db.execute(text(fetch_query_string('select_node_from_id.sql')), node_id=node_id).fetchall() except DatabaseError as err: current_app.logger.error("DatabaseError: %s", err) if result: kw = dict(zip(result[0].keys(), result[0].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 purge_collection(keys): "Recursive purge of nodes with name and id" for key in keys: m = re.match(r'(.*) \((\d+)\)', key) name = m.group(1) node_id = m.group(2) value = render_value_for_node(node_id) print 'remove node with name:{0} and id:{1}'.format(name, node_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 mode_new_collection(): """ Create a new collection of items with common attributes. """
print globals()['mode_new_collection'].__doc__ collection_name = raw_input("Collection name: ") item_attr_list = [] collection_node_id = None if collection_name: collection_node_id = insert_node(name=collection_name, value=None) insert_query(name='select_link_node_from_node.sql', 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 mode_database_functions(): "Select a function to perform from chill.database" print globals()['mode_database_functions'].__doc__ selection = True database_functions = [ 'init_db', 'insert_node', 'insert_node_node', 'delete_node', 'select_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 operate_menu(): "Select between these operations on the database" selection = True while selection: print globals()['operate_menu'].__doc__ selection = select([ 'chill.database functions', 'execute sql file', 'render_node', 'New collectio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def thread_local_property(name): '''Creates a thread local ``property``.''' name = '_thread_local_' + name def fget(self): try: return getattr(self, name).value except AttributeError: return None def fset(self, value): getattr(self, name).value = 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 kvlclient(self): '''Return a thread local ``kvlayer`` client.''' if self._kvlclient is None: self._kvlclient = kvlayer.client() return self._kvlclient
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def divide(self, data_source_factory): """Divides the task according to the number of workers."""
data_length = data_source_factory.length() data_interval_length = data_length / self.workers_number() + 1 current_index = 0 self.responses = [] while current_index < data_length: self.responses.append(0) offset = current_index limit = min((da...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map(self, data_source_factory, timeout=0, on_timeout="local_mode"): """Sends tasks to workers and awaits the responses. When all the responses are received, ...
def local_launch(): print "Local launch" return self.reduce_fn( self.map_fn(data_source_factory.build_data_source()) ) if self.local_mode: return local_launch() for index, factory in enumerate(self.divide(data_sou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _orderedCleanDict(attrsObj): """ -> dict with false-values removed Also evaluates attr-instances for false-ness by looking at the values of their properties ...
def _filt(k, v): if attr.has(v): return not not any(attr.astuple(v)) return not not v return attr.asdict(attrsObj, dict_factory=OrderedDict, recurse=False, filter=_filt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def representCleanOpenAPIOperation(dumper, data): """ Unpack nonstandard attributes while representing an OpenAPIOperation """
dct = _orderedCleanDict(data) if '_extended' in dct: for k, ext in list(data._extended.items()): dct[k] = ext del dct['_extended'] return dumper.yaml_representers[type(dct)](dumper, dct)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def representCleanOpenAPIParameter(dumper, data): """ Rename python reserved keyword fields before representing an OpenAPIParameter """
dct = _orderedCleanDict(data) # We are using "in_" as a key for the "in" parameter, since in is a Python keyword. # To represent it correctly, we then have to swap "in_" for "in". # So we do an item-by-item copy of the dct so we don't change the order when # making this swap. d2 = OrderedDict()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def representCleanOpenAPIObjects(dumper, data): """ Produce a representation of an OpenAPI object, removing empty attributes """
dct = _orderedCleanDict(data) return dumper.yaml_representers[type(dct)](dumper, dct)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mediaTypeHelper(mediaType): """ Return a function that creates a Responses object; """
def _innerHelper(data=None): """ Create a Responses object that contains a MediaType entry of the specified mediaType Convenience function for the most common cases where you need an instance of Responses """ ret = OpenAPIResponses() if data is None: dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ensure_config_file_exists(): """ Makes sure the config file exists. :raises: :class:`epab.core.new_config.exc.ConfigFileNotFoundError` """
config_file = Path(ELIBConfig.config_file_path).absolute() if not config_file.exists(): raise ConfigFileNotFoundError(ELIBConfig.config_file_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _relevant_checkers(self, path): """ Get set of checkers for the given path. TODO: currently this is based off the file extension. We would like to honor magi...
_, ext = os.path.splitext(path) ext = ext.lstrip('.') return checkers.checkers.get(ext, [])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _list_checkers(self): """ Print information about checkers and their external tools. Currently only works properly on systems with the `which` tool available...
classes = set() for checker_group in checkers.checkers.itervalues(): for checker in checker_group: classes.add(checker) max_width = 0 for clazz in classes: max_width = max(max_width, len(clazz.tool), len(clazz.__name__)) for clazz in sor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _should_ignore(self, path): """ Return True iff path should be ignored. """
for ignore in self.options.ignores: if fnmatch.fnmatch(path, ignore): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def legacy_notes_view(request): """ View to see legacy notes. """
notes = TeacherNote.objects.all() note_count = notes.count() paginator = Paginator(notes, 100) page = request.GET.get('page') try: notes = paginator.page(page) except PageNotAnInteger: notes = paginator.page(1) except EmptyPage: notes = paginator.page(paginator.num_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def legacy_events_view(request): """ View to see legacy events. """
events = TeacherEvent.objects.all() event_count = events.count() paginator = Paginator(events, 100) page = request.GET.get('page') try: events = paginator.page(page) except PageNotAnInteger: events = paginator.page(1) except EmptyPage: events = paginator.page(pagina...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def legacy_requests_view(request, rtype): """ View to see legacy requests of rtype request type, which should be either 'food' or 'maintenance'. """
if not rtype in ['food', 'maintenance']: raise Http404 requests_dict = [] # [(req, [req_responses]), (req2, [req2_responses]), ...] requests = TeacherRequest.objects.filter(request_type=rtype) request_count = requests.count() paginator = Paginator(requests, 50) page = request.GET.get('...