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 activate(self, prefix=None, backend=None): """ A decorator used to activate the mocker. :param prefix: :param backend: An instance of a storage backend. """
if isinstance(prefix, compat.string_types): self.prefix = prefix if isinstance(backend, RmoqStorageBackend): self.backend = backend def activate(func): if isinstance(func, type): return self._decorate_class(func) def wrapper(*ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_call(self, req, resource): """This is were all callbacks are made and the req is processed."""
if resource == "ports": if req.method.upper() in ('PUT', 'POST'): # Pass the request back to be processed by other filters # and Neutron first resp = req.get_response(self.app) if resp.status_code not in (200, 204): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keep_on_one_line(): """ Keep all the output generated within a with-block on one line. Whenever a new line would be printed, instead reset the cursor to the ...
class CondensedStream: def __init__(self): self.sys_stdout = sys.stdout def write(self, string): with swap_streams(self.sys_stdout): string = string.replace('\n', ' ') string = truncate_to_fit_terminal(string) if string.stri...
<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_color(string, name, style='normal', when='auto'): """ Write the given colored string to standard out. """
write(color(string, name, style, when))
<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_color(string, name, style='normal', when='auto'): """ Replace the existing line with the given colored string. """
clear() write_color(string, name, style, when)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def progress_color(current, total, name, style='normal', when='auto'): """ Display a simple, colored progress report. """
update_color('[%d/%d] ' % (current, total), name, style, when)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def color(string, name, style='normal', when='auto'): """ Change the color of the given string. """
if name not in colors: from .text import oxford_comma raise ValueError("unknown color '{}'.\nknown colors are: {}".format( name, oxford_comma(["'{}'".format(x) for x in sorted(colors)]))) if style not in styles: from .text import oxford_comma raise ValueError("unkno...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(objects): """ Retrieve remote file object """
def exists(object): if os.path.exists(TMPDIR + '/' + filename): return True else: msg = 'File object %s failed to download to %s. Exit' % (filename, TMPDIR) logger.warning(msg) stdout_message('%s: %s' % (inspect.stack()[0][3], msg)) 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 precheck(): """ Pre-run dependency check """
binaries = ['make'] for bin in binaries: if not which(bin): msg = 'Dependency fail -- Unable to locate rquired binary: ' stdout_message('%s: %s' % (msg, ACCENT + bin + RESET)) return False elif not root(): return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_semester_view(request): """ Initiates a semester"s worth of workshift, with the option to copy workshift types from the previous semester. """
page_name = "Start Semester" year, season = utils.get_year_season() start_date, end_date = utils.get_semester_start_end(year, season) semester_form = SemesterForm( data=request.POST or None, initial={ "year": year, "season": season, "start_date": sta...
<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_preferred(instance, profile): """ Check if a user has marked an instance's workshift type as preferred. """
if not instance.weekly_workshift: return False if profile and profile.ratings.filter( workshift_type=instance.weekly_workshift.workshift_type, rating=WorkshiftRating.LIKE, ).count() == 0: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def profile_view(request, semester, targetUsername, profile=None): """ Show the user their workshift history for the current semester as well as upcoming shifts....
wprofile = get_object_or_404( WorkshiftProfile, user__username=targetUsername, semester=semester ) if wprofile == profile: page_name = "My Workshift Profile" else: page_name = "{}'s Workshift Profile".format(wprofile.user.get_full_name()) past_shifts = Works...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def preferences_view(request, semester, targetUsername, profile=None): """ Show the user their preferences for the given semester. """
# TODO: Change template to show descriptions in tooltip / ajax show box? wprofile = get_object_or_404( WorkshiftProfile, user__username=targetUsername, ) full_management = utils.can_manage(request.user, semester=semester) if wprofile.user != request.user and \ not full_manag...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust_hours_view(request, semester): """ Adjust members' workshift hours requirements. """
page_name = "Adjust Hours" pools = WorkshiftPool.objects.filter(semester=semester).order_by( "-is_primary", "title", ) workshifters = WorkshiftProfile.objects.filter(semester=semester) pool_hour_forms = [] for workshifter in workshifters: forms_list = [] for pool in po...
<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_workshifter_view(request, semester): """ Add a new member workshift profile, for people who join mid-semester. """
page_name = "Add Workshifter" existing = [ i.user.pk for i in WorkshiftProfile.objects.filter(semester=semester) ] users = User.objects.exclude( Q(pk__in=existing) | Q(is_active=False) | Q(userprofile__status=UserProfile.ALUMNUS) ) add_workshifter_forms = [] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill_shifts_view(request, semester): """ Allows managers to quickly fill in the default workshifts for a few given workshift pools. """
page_name = "Fill Shifts" fill_regular_shifts_form = None fill_social_shifts_form = None fill_humor_shifts_form = None fill_bathroom_shifts_form = None fill_hi_shifts_form = None reset_all_shifts_form = None managers = Manager.objects.filter(incumbent__user=request.user) admin = u...
<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_shift_view(request, semester): """ View for the workshift manager to create new types of workshifts. """
page_name = "Add Workshift" any_management = utils.can_manage(request.user, semester, any_pool=True) if not any_management: messages.add_message( request, messages.ERROR, MESSAGES["ADMINS_ONLY"], ) return HttpResponseRedirect(semester.get_view_ur...
<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_view(request, semester, pk, profile=None): """ View the details of a particular RegularWorkshift. """
shift = get_object_or_404(RegularWorkshift, pk=pk) page_name = shift.workshift_type.title if shift.is_manager_shift: president = Manager.objects.filter( incumbent__user=request.user, president=True, ).count() > 0 can_edit = request.user.is_superuser or presi...
<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_shift_view(request, semester, pk, profile=None): """ View for a manager to edit the details of a particular RegularWorkshift. """
shift = get_object_or_404(RegularWorkshift, pk=pk) if shift.is_manager_shift: # XXX: Bad way of doing this, we should make manager_shift point to # the related Manager object directly try: manager = Manager.objects.get(title=shift.workshift_type.title) except Manage...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def instance_view(request, semester, pk, profile=None): """ View the details of a particular WorkshiftInstance. """
instance = get_object_or_404(WorkshiftInstance, pk=pk) page_name = instance.title management = utils.can_manage( request.user, semester=semester, pool=instance.pool, ) interact_forms = _get_forms( profile, instance, request, undo=management, prefix="i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_instance_view(request, semester, pk, profile=None): """ View for a manager to edit the details of a particular WorkshiftInstance. """
instance = get_object_or_404(WorkshiftInstance, pk=pk) if instance.weekly_workshift and instance.weekly_workshift.is_manager_shift: president = Manager.objects.filter( incumbent__user=request.user, president=True ).count() > 0 can_edit = request.user.is_superuse...
<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_type_view(request, semester, pk, profile=None): """ View for a manager to edit the details of a particular WorkshiftType. """
wtype = get_object_or_404(WorkshiftType, pk=pk) full_management = utils.can_manage(request.user, semester) any_management = utils.can_manage(request.user, semester, any_pool=True) if not any_management: messages.add_message( request, messages.ERROR, MESSAGES...
<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_modules(dir_path): """ Attempts to import modules in the specified directory path. `dir_path` Base directory path to attempt to import modules. """
def _import_module(module): """ Imports the specified module. """ # already loaded, skip if module in mods_loaded: return False __import__(module) mods_loaded.append(module) mods_loaded = [] # check if provided path exists if not os.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 _setup_directories(self): """ Creates data directory structure. * Raises a ``DirectorySetupFail`` exception if error occurs while creating directories. """
dirs = [self._data_dir] dirs += [os.path.join(self._data_dir, name) for name in self.DATA_SUBDIRS] for path in dirs: if not os.path.isdir(path): try: os.makedirs(path) # recursive mkdir os.chmod(path, 0755) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_task(self, load): """ Sets up the ``Task`` object and loads active file for task. `load` Set to ``True`` to load task after setup. """
if not self._task: self._task = Task(self._data_dir) if load: self._task.load()
<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_plugins(self): """ Attempts to load plugin modules according to the order of available plugin directories. """
# import base plugin modules try: __import__('focus.plugin.modules') #import focus.plugin.modules except ImportError as exc: raise errors.PluginImport(unicode(exc)) # load user defined plugin modules try: user_plugin_dir = os.pat...
<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): """ Loads in resources needed for this environment, including loading a new or existing task, establishing directory structures, and importing pl...
self._setup_directories() self._load_plugins() self._setup_task(load=True) self._loaded = 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 resize(image, width=None, height=None, crop=False, namespace="resized"): """ Returns the url of the resized image """
return resize_lazy(image=image, width=width, height=height, crop=crop, namespace=namespace, as_url=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 conditional_resize(image, ratio, width=None, height=None, upcrop=True, namespace="resized"): """ Crop the image based on a ratio If upcrop is true, crops the...
aspect = float(image.width) / float(image.height) crop = False if (aspect > ratio and upcrop) or (aspect <= ratio and not upcrop): crop = True return resize_lazy(image=image, width=width, height=height, crop=crop, namespace=namespace, as_url=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 choose(s, possibilities, threshold=.6): """ Returns the closest match to string s if exceeds threshold, else returns None """
if not possibilities: return None if s in possibilities: return s if s == '': return None startswith = [x for x in possibilities if x.lower().startswith(s.lower())] if len(startswith) == 1: return startswith[0] contained = [x for x in possibilities if s.lower() in x.lower()] if len(containe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def normalized(a, axis=-1, order=2): '''Return normalized vector for arbitrary axis Args ---- a: ndarray (n,3) Tri-axial vector data axis: int Axis index to overwhich to normalize order: int Order of nomalization to calculate Notes ----- This function was ad...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def findzc(x, thresh, t_max=None): ''' Find cues to each zero-crossing in vector x. To be accepted as a zero-crossing, the signal must pass from below -thresh to above thresh, or vice versa, in no more than t_max samples. Args ---- thresh: (float) magnitude threshold for detecting ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def butter_filter(cutoff, fs, order=5, btype='low'): '''Create a digital butter fileter with cutoff frequency in Hz Args ---- cutoff: float Cutoff frequency where filter should separate signals fs: float sampling frequency btype: str Type of filter type to create. 'low' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def butter_apply(b, a, data): '''Apply filter with filtfilt to allign filtereted data with input The filter is applied once forward and once backward to give it linear phase, using Gustafsson's method to give the same length as the original signal. Args ---- b: ndarray Numerator po...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calc_PSD_welch(x, fs, nperseg): '''Caclulate power spectral density with Welch's method Args ---- x: ndarray sample array fs: float sampling frequency (1/dt) Returns ------- f_welch: ndarray Discrete frequencies S_xx_welch: ndarray Estimated PSD ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def simple_peakfinder(x, y, delta): '''Detect local maxima and minima in a vector A point is considered a maximum peak if it has the maximal value, and was preceded (to the left) by a value lower by `delta`. Args ---- y: ndarray array of values to find local maxima and minima in de...
<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_near(lat, lon, *, n=10, session=None): """Return n results for a given latitude and longitude"""
search_params = {'npoints': n, 'clat': lat, 'clon': lon, 'Columns[]': ['Subregion', 'Notes', 'CollectionYear', 'ReservoirAge', 'ReservoirErr', 'C14age', 'C14err', 'LabID', 'Delta13C', 'nextime', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _query_near(*, session=None, **kwargs): """Query marine database with given query string values and keys"""
url_endpoint = 'http://calib.org/marine/index.html' if session is not None: resp = session.get(url_endpoint, params=kwargs) else: with requests.Session() as s: # Need to get the index page before query. Otherwise get bad query response that seems legit. s.get('http:/...
<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_content(self): """Render the panel's content."""
if not self.has_content: return "" template = self.template if isinstance(self.template, str): template = self.app.ps.jinja2.env.get_template(self.template) context = self.render_vars() content = template.render(app=self.app, request=self.request, **conte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_response(self, response): """Store response headers."""
self.response_headers = [(k, v) for k, v in sorted(response.headers.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 retry(exception_to_check, tries=5, delay=5, multiplier=2): '''Tries to call the wrapped function again, after an incremental delay :param exception_to_check: Exception(s) to check for, before retrying. :type exception_to_check: Exception :param tries: Number of time to retry before failling. :t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_average_measure(dirname, measure_func, t_steady=None): """ Calculate a measure of a model in an output directory, averaged over all times when the model ...
if t_steady is None: meas, meas_err = measure_func(get_recent_model(dirname)) return meas, meas_err else: ms = [filename_to_model(fname) for fname in get_filenames(dirname)] ms_steady = [m for m in ms if m.t > t_steady] meas_list = [measure_func(m) for m in ms_steady] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def measures(dirnames, measure_func, t_steady=None): """Calculate a measure of a set of model output directories, for a measure function which returns an associa...
measures, measure_errs = [], [] for dirname in dirnames: meas, meas_err = get_average_measure(dirname, measure_func, t_steady) measures.append(meas) measure_errs.append(meas_err) return np.array(measures), np.array(measure_errs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def params(dirnames, param_func, t_steady=None): """Calculate a parameter of a set of model output directories, for a measure function which returns an associate...
return np.array([param_func(get_recent_model(d)) for d in dirnames])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def t_measures(dirname, time_func, measure_func): """Calculate a measure over time for a single output directory, and its uncertainty. Parameters dirname: str Pa...
ts, measures, measure_errs = [], [], [] for fname in get_filenames(dirname): m = filename_to_model(fname) ts.append(time_func(m)) meas, meas_err = measure_func(m) measures.append(meas) measure_errs.append(meas_err) return np.array(ts), np.array(measures), np.array(me...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def group_by_key(dirnames, key): """Group a set of output directories according to a model parameter. Parameters dirnames: list[str] Output directories key: vari...
groups = defaultdict(lambda: []) for dirname in dirnames: m = get_recent_model(dirname) groups[m.__dict__[key]].append(dirname) return dict(groups)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pearson_correlation(self): x, y, dt = self.data X, Y = np.array(x), np.array(y) ''' Compute Pearson Correlation Coefficient. ''' # Normalise X and Y X -= X.mean(0) Y -= Y.mean(0) # Standardise X and Y X /= X.std(0) Y /= Y.std(0) # Compu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intervalTrees(reffh, scoreType=int, verbose=False): """ Build a dictionary of interval trees indexed by chrom from a BED stream or file :param reffh: This ca...
if type(reffh).__name__ == "str": fh = open(reffh) else: fh = reffh # load all the regions and split them into lists for each chrom elements = {} if verbose and fh != sys.stdin: totalLines = linesInFile(fh.name) pind = ProgressIndicator(totalToDo=totalLines, mess...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def BEDIterator(filehandle, sortedby=None, verbose=False, scoreType=int, dropAfter=None): """ Get an iterator for a BED file :param filehandle: this can be eithe...
chromsSeen = set() prev = None if type(filehandle).__name__ == "str": filehandle = open(filehandle) if verbose: try: pind = ProgressIndicator(totalToDo=os.path.getsize(filehandle.name), messagePrefix="completed", messageSuffix="of pro...
<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_forum_votes(sender, **kwargs): """ When a Vote is added, re-saves the topic or post to update vote count. Since Votes can be assigned to any conte...
vote = kwargs['instance'] if vote.content_type.app_label != "fretboard": return if vote.content_type.model == "topic": t = get_model('fretboard', 'Topic').objects.get(id=vote.object.id) t.votes = t.score() t.save(update_fields=['votes']) elif vote.content_type.mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def close(self): ''' terminate the connection ''' cache_key = self._cache_key() SSH_CONNECTION_CACHE.pop(cache_key, None) SFTP_CONNECTION_CACHE.pop(cache_key, None) if self.sftp is not None: self.sftp.close() self.ssh.close()
<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(self, line=None): """parses the line provided, if None then uses sys.argv"""
args = self.parser.parse_args(args=line) return args.func(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 vertical_layout(self, draw, slide): """ Augment slide with vertical layout info """
padding = self.padding heading = slide['heading'] width, height = draw.textsize(heading['text']) top = padding left = padding # Calculate size and location of heading heading.update(dict( width = width, height = height, top =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def horizontal_layout(self, draw, slide): """ Augment slide with horizontal layout info """
padding = self.padding heading = slide['heading'] top = padding left = padding top += heading['height'] + padding rows = slide['rows'] for row in rows: images = row.get('images', 0) items = row['items'] used_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gp_xfac(): """example using QM12 enhancement factors - uses `gpcalls` kwarg to reset xtics - numpy.loadtxt needs reshaping for input files w/ only one datapo...
# prepare data inDir, outDir = getWorkDirs() data = OrderedDict() # TODO: "really" reproduce plot using spectral data for file in os.listdir(inDir): info = os.path.splitext(file)[0].split('_') key = ' '.join(info[:2] + [':', ' - '.join([ str(float(s)/1e3) for s in info[-1][:7].split('-'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify(value, msg): """ C-style validator Keyword arguments: value -- dictionary to validate (required) msg -- the protobuf schema to validate against (requi...
return bool(value) and \ converts_to_proto(value, msg) and \ successfuly_encodes(msg) and \ special_typechecking(value, msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def converts_to_proto(value, msg, raise_err=False): """ Boolean response if a dictionary can convert into the proto's schema :param value: <dict> :param msg: <pr...
result = True try: dict_to_protobuf.dict_to_protobuf(value, msg) except TypeError as type_error: if raise_err: raise type_error result = False 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 successfuly_encodes(msg, raise_err=False): """ boolean response if a message contains correct information to serialize :param msg: <proto object> :param rais...
result = True try: msg.SerializeToString() except EncodeError as encode_error: if raise_err: raise encode_error result = False 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 strip(value, msg): """ Strips all non-essential keys from the value dictionary given the message format protobuf raises ValueError exception if value does no...
dict_to_protobuf.dict_to_protobuf(value, msg) try: msg.SerializeToString() #raise error for insufficient input except EncodeError as encode_error: raise ValueError(str(encode_error)) output = dict_to_protobuf.protobuf_to_dict(msg) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_german_number(x): """Convert a string with a German number into a Decimal Parameters x : str, list, tuple, numpy.ndarray, pandas.DataFrame A string wit...
import numpy as np import pandas as pd import re def proc_elem(e): # abort if it is not a string if not isinstance(e, str): return None # strip all char except digits, ".", "," and "-" s = re.sub('[^0-9\.\,\-]+', '', e) # abort if nothing is left ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def score(package_path): """ Runs pylint on a package and returns a score Lower score is better :param package_path: path of the package to score :return: number...
python_files = find_files(package_path, '*.py') total_counter = Counter() for python_file in python_files: output = run_pylint(python_file) counter = parse_pylint_output(output) total_counter += counter score_value = 0 for count, stat in enumerate(total_counter): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover(url, options={}): """ Retrieve the API definition from the given URL and construct a Patchboard to interface with it. """
try: resp = requests.get(url, headers=Patchboard.default_headers) except Exception as e: raise PatchboardError("Problem discovering API: {0}".format(e)) # Parse as JSON (Requests uses json.loads()) try: api_spec = resp.json() except ValueError as e: raise Patchboard...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spawn(self, context=None): """ context may be a callable or a dict. """
if context is None: context = self.default_context if isinstance(context, collections.Callable): context = context() if not isinstance(context, collections.Mapping): raise PatchboardError('Cannot determine a valid context') return Client(self, cont...
<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_version(form='short'): """ Returns the version string. Takes single argument ``form``, which should be one of the following strings: * ``short`` Returns ...
versions = {} branch = "%s.%s" % (VERSION[0], VERSION[1]) tertiary = VERSION[2] type_ = VERSION[3] type_num = VERSION[4] versions["branch"] = branch v = versions["branch"] if tertiary: versions["tertiary"] = "." + str(tertiary) v += versions["tertiary"] versions...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _download_article(self, article_number, max_retries=10): """Download a given article. :type article_number: str :param article_number: the article number to ...
log.debug('downloading article {0} from {1}'.format(article_number, self.name)) _connection = self.session.connections.get() try: i = 0 while True: if i >= max_retries: return False try: _connection...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index_article(self, msg_str, article_number, start, length): """Add article to index file. :type msg_str: str :param msg_str: the message string to index. :t...
f = cStringIO.StringIO(msg_str) message = rfc822.Message(f) f.close() # Replace header dict None values with '', and any tabs or # newlines with ' '. h = dict() for key in message.dict: if not message.dict[key]: h[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 compress_and_sort_index(self): """Sort index, add header, and compress. :rtype: bool :returns: True """
idx_fname = '{name}.{date}.mbox.csv'.format(**self.__dict__) try: reader = csv.reader(open(idx_fname), dialect='excel-tab') except IOError: return False index = [x for x in reader if x] sorted_index = sorted(index, key=itemgetter(0)) gzip_idx_fnam...
<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, data): """Save a document or list of documents"""
if not self.is_connected: raise Exception("No database selected") if not data: return False if isinstance(data, dict): doc = couchdb.Document() doc.update(data) self.db.create(doc) elif isinstance(data, couchdb.Document): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def win_register(): "need to be admin" try: with winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, "austere.HTTP") as k: # winreg.SetValue(k, None, winreg.REG_SZ, "{} austere".format(sys.argv[0])) logger.debug("\shell") with winreg.CreateKey(k, "shell") as shellkey: ...
<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_config(path=None, defaults=None): """ Loads and parses an INI style configuration file using Python's built-in ConfigParser module. If path is specified...
if defaults is None: defaults = DEFAULT_FILES config = configparser.SafeConfigParser(allow_no_value=True) if defaults: config.read(defaults) if path: with open(path) as fh: config.readfp(fh) return config
<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_value_from_schema(v): """ Load a value from a schema defined string. """
x = urllib.parse.urlparse(v) if x.scheme.lower() == 'decimal': v = Decimal(x.netloc) elif x.scheme.lower() in ['int', 'integer']: v = int(x.netloc) elif x.scheme.lower() == 'float': v = float(x.netloc) elif x.scheme.lower() in ['s', 'str', 'string']: v = str(x.netlo...
<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_value(v, parser, config, description): """ Convert a string received on the command-line into a value or None. :param str v: The value to parse. :param...
val = None if v == '': return if v is not None: try: val = load_value_from_schema(v) except Exception as e: six.raise_from( CertifierTypeError( message='{kind}'.format( description=description, ...
<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_simple_date(datestring): """Transforms a datestring into shorter date 7.9.2017 > 07.09 Expects the datestring to be format 07.09.2017. If this is not the...
simple_date = re.compile(r"\d{1,2}(\.)\d{1,2}") date = simple_date.search(datestring) if date: dates = date.group().split(".") if len(dates[0]) == 1: dates[0] = add_zero(dates[0]) if len(dates[1]) == 1: dates[1] = add_zero(dates[1]) if date_is_valid(...
<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_month(datestring): """Transforms a written month into corresponding month number. E.g. November -> 11, or May -> 05. Keyword arguments: datestring -- a s...
convert_written = re.compile(r"jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec", re.IGNORECASE) month = convert_written.search(datestring) month_number = None # If there's a match, convert the month to its corresponding number if month: month_number = strptime(month.group(), "%b").tm_mon ...
<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_day_of_month(datestring): """Transforms an ordinal number into plain number with padding zero. E.g. 3rd -> 03, or 12th -> 12 Keyword arguments: datestrin...
get_day = re.compile(r"\d{1,2}(st|nd|rd|th)?", re.IGNORECASE) day = get_day.search(datestring) the_day = None if day: if bool(re.search(r"[st|nd|rd|th]", day.group().lower())): the_day = day.group()[:-2] else: the_day = day.group() if int(the_day) < 10: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_string(self, string, *args): """Strips matching regular expressions from string Keyword arguments: string -- The given string, that will be stripped *a...
res = string for r in args: res = re.sub(r, "", res.strip(), flags=re.IGNORECASE|re.MULTILINE) return res.strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_between(self, string, start, end): """Deletes everything between regexes start and end from string"""
regex = start + r'.*?' + end + r'\s*' res = re.sub(regex, '', string, flags=re.DOTALL|re.IGNORECASE|re.MULTILINE) 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 distance_between(self, string, start, end): """Returns number of lines between start and end"""
count = 0 started = False for line in string.split("\n"): if self.scan_line(line, start) and not started: started = True if self.scan_line(line, end): return count if started: count += 1 return coun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan_line(self, line, regex): """Checks if regex is in line, returns bool"""
return bool(re.search(regex, line, flags=re.IGNORECASE))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan_message(self, message, regex): """Scans regex from msg and returns the line that matches Keyword arguments: message -- A (long) string, e.g. email body ...
for line in message.split("\n"): if bool(re.search( regex, line, flags=re.IGNORECASE|re.MULTILINE)): return line 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 format_date(self, dl_string): """Formats various date formats to dd.MM. Examples - January 15th --> 15.01. - 15.01.2017 --> 15.01. - 15th of January --> 15.0...
thedate = get_simple_date(dl_string) if thedate != "Failed" and thedate: return thedate day = get_day_of_month(dl_string) month = get_month(dl_string) return day + '.' + month + '.'
<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_user(self, user_id, custom_properties=None, headers=None, endpoint_url=None): """ Creates a new identified user if he doesn't exist. :param str user_id: ...
endpoint_url = endpoint_url or self._endpoint_url url = endpoint_url + '/users' headers = headers or self._default_headers() payload = {"user_id": user_id} if custom_properties is not None: payload["user_properties"] = custom_properties response = 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 add_event(self, user_id, event_name, event_properties=None, headers=None, endpoint_url=None): """ Send an identified event. If a user doesn't exist it will c...
endpoint_url = endpoint_url or self._endpoint_url url = endpoint_url + '/users/' + user_id + '/events' headers = headers or self._default_headers() event_properties = event_properties or {} payload = { "event_name": event_name, "custom_properties": even...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decrease_user_property(self, user_id, property_name, value=0, headers=None, endpoint_url=None): """ Decrease a user's property by a value. :param str user_id...
endpoint_url = endpoint_url or self._endpoint_url url = endpoint_url + "/users/" + user_id + "/properties/" + property_name + "/decrease/" + value.__str__() headers = headers or self._default_headers(content_type="") response = requests.post(url, headers=headers) return respo...
<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_user_properties(self, user_id, user_properties, headers=None, endpoint_url=None): """ Update a user's properties with values provided in "user_propert...
endpoint_url = endpoint_url or self._endpoint_url url = endpoint_url + '/users/' + user_id + '/properties' headers = headers or self._default_headers() payload = user_properties response = requests.put(url, headers=headers, json=payload) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def link_user_to_group(self, user_id, group_id, headers=None, endpoint_url=None): """ Links a user to a group :param str user_id: identified user's ID :param str...
endpoint_url = endpoint_url or self._endpoint_url url = endpoint_url + '/groups/' + group_id + '/link/' + user_id headers = headers or self._default_headers() response = requests.post(url, headers=headers) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_group_properties(self, group_id, group_properties, headers=None, endpoint_url=None): """ Update a group's properties with values provided in "group_pr...
endpoint_url = endpoint_url or self._endpoint_url url = endpoint_url + '/groups/' + group_id + '/properties' headers = headers or self._default_headers() payload = group_properties response = requests.put(url, headers=headers, json=payload) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timing(self, stats, value): """ Log timing information """
self.update_stats(stats, value, self.SC_TIMING)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count(self, stats, value, sample_rate=1): """ Updates one or more stats counters by arbitrary value """
self.update_stats(stats, value, self.SC_COUNT, sample_rate)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timeit(self, metric, func, *args, **kwargs): """ Times given function and log metric in ms for duration of execution. """
(res, seconds) = timeit(func, *args, **kwargs) self.timing(metric, seconds * 1000.0) 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 format(keys, value, _type, prefix=""): """ General format function. {'example.format': '2|T'} {'example.format31': '2|T', 'example.format37': '2|T'} {'prefix...
data = {} value = "{0}|{1}".format(value, _type) # TODO: Allow any iterable except strings if not isinstance(keys, (list, tuple)): keys = [keys] for key in keys: data[prefix + key] = value return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def jars(self, absolute=True): ''' List of jars in the jar path ''' jars = glob(os.path.join(self._jar_path, '*.jar')) return jars if absolute else map(lambda j: os.path.abspath(j), jars)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def download_jars_to(cls, folder): ''' Download missing jars to a specific folder ''' if not os.path.exists(folder): os.makedirs(folder) for info in JARS: jar = MavenJar(info[0], info[1], info[2]) path = os.path.join(folder, jar.filename) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attributes_from_dict(document): """Convert a Json representation of a set of attribute instances into a dictionary. Parameters document : Json object Json se...
attributes = dict() for attr in document: name = str(attr['name']) attributes[name] = Attribute( name, attr['value'] ) return attributes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attributes_to_dict(attributes): """Transform a dictionary of attribute instances into a list of Json objects, i.e., list of key-value pairs. Parameters attri...
result = [] for key in attributes: result.append({ 'name' : key, 'value' : attributes[key].value }) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(attributes, definitions): """Create a dictionary of attributes from a given list of key-value pairs. Detects duplicate definitions of the same attrib...
# Create a list of valis parameter names valid_names = {} for para in definitions: valid_names[para.identifier] = para result = {} if not attributes is None: for element in attributes: if isinstance(element, dict): # Create attribute from dictionary ...
<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(document): """Create attribute definition form Json-like object represenation. Parameters document : dict Json-like object represenation Returns --...
if 'default' in document: default = document['default'] else: default = None return AttributeDefinition( document['id'], document['name'], document['description'], AttributeType.from_dict(document['type']), defa...
<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): """Convert attribute definition into a dictionary. Returns ------- dict Json-like dictionary representation of the attribute definition """
obj = { 'id' : self.identifier, 'name' : self.name, 'description' : self.description, 'type' : self.data_type.to_dict() } if not self.default is None: obj['default'] = self.default return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_dict(document): """Create data type definition form Json-like object represenation. Parameters document : dict Json-like object represenation Returns --...
# Get the type name from the document type_name = document['name'] if type_name == ATTR_TYPE_INT: return IntType() elif type_name == ATTR_TYPE_FLOAT: return FloatType() elif type_name == ATTR_TYPE_ENUM: return EnumType(document['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 from_string(self, value): """Convert string to dictionary."""
# Remove optional {} if value.startswith('{') and value.endswith('}'): text = value[1:-1].strip() else: text = value.strip() # Result is a dictionary result = {} # Convert each pair of <int>:<float> into a key, value pair. for val in text....