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 distribution_version(name): """try to get the version of the named distribution, returs None on failure"""
from pkg_resources import get_distribution, DistributionNotFound try: dist = get_distribution(name) except DistributionNotFound: pass else: return dist.version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initpkg(pkgname, exportdefs, attr=None, eager=False): """ initialize given package from the export definitions. """
attr = attr or {} oldmod = sys.modules.get(pkgname) d = {} f = getattr(oldmod, '__file__', None) if f: f = _py_abspath(f) d['__file__'] = f if hasattr(oldmod, '__version__'): d['__version__'] = oldmod.__version__ if hasattr(oldmod, '__loader__'): d['__loader__'] = oldmod.__loader__ if hasattr(oldmod, '__path__'): d['__path__'] = [_py_abspath(p) for p in oldmod.__path__] if hasattr(oldmod, '__package__'): d['__package__'] = oldmod.__package__ if '__doc__' not in exportdefs and getattr(oldmod, '__doc__', None): d['__doc__'] = oldmod.__doc__ d.update(attr) if hasattr(oldmod, "__dict__"): oldmod.__dict__.update(d) mod = ApiModule(pkgname, exportdefs, implprefix=pkgname, attr=d) sys.modules[pkgname] = mod # eagerload in bypthon to avoid their monkeypatching breaking packages if 'bpython' in sys.modules or eager: for module in list(sys.modules.values()): if isinstance(module, ApiModule): module.__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 importobj(modpath, attrname): """imports a module, then resolves the attrname on it"""
module = __import__(modpath, None, None, ['__doc__']) if not attrname: return module retval = module names = attrname.split(".") for x in names: retval = getattr(retval, x) return retval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __makeattr(self, name): """lazily compute value for name or raise AttributeError if unknown."""
# print "makeattr", self.__name__, name target = None if '__onfirstaccess__' in self.__map__: target = self.__map__.pop('__onfirstaccess__') importobj(*target)() try: modpath, attrname = self.__map__[name] except KeyError: if target is not None and name != '__onfirstaccess__': # retry, onfirstaccess might have set attrs return getattr(self, name) raise AttributeError(name) else: result = importobj(modpath, attrname) setattr(self, name, result) try: del self.__map__[name] except KeyError: pass # in a recursive-import situation a double-del can happen 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 _request(self, http_method, relative_url='', **kwargs): """Does actual HTTP request using requests library."""
# It could be possible to call api.resource.get('/index') # but it would be non-intuitive that the path would resolve # to root of domain relative_url = self._remove_leading_slash(relative_url) # Add default kwargs with possible custom kwargs returned by # before_request new_kwargs = self.default_kwargs().copy() custom_kwargs = self.before_request( http_method, relative_url, kwargs.copy() ) new_kwargs.update(custom_kwargs) response = requests.request( http_method, self._join_url(relative_url), **new_kwargs ) return self.after_request(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 _new_url(self, relative_url): """Create new Url which points to new url."""
return Url( urljoin(self._base_url, relative_url), **self._default_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 roles(self): """gets user groups"""
result = AuthGroup.objects(creator=self.client).only('role') return json.loads(result.to_json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_permissions(self, role): """gets permissions of role"""
target_role = AuthGroup.objects(role=role, creator=self.client).first() if not target_role: return '[]' targets = AuthPermission.objects(groups=target_role, creator=self.client).only('name') return json.loads(targets.to_json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_role(self, role): """Returns a role object """
role = AuthGroup.objects(role=role, creator=self.client).first() return role
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def del_role(self, role): """ deletes a group """
target = AuthGroup.objects(role=role, creator=self.client).first() if target: target.delete() return True else: 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 add_membership(self, user, role): """ make user a member of a group """
targetGroup = AuthGroup.objects(role=role, creator=self.client).first() if not targetGroup: return False target = AuthMembership.objects(user=user, creator=self.client).first() if not target: target = AuthMembership(user=user, creator=self.client) if not role in [i.role for i in target.groups]: target.groups.append(targetGroup) target.save() 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 del_membership(self, user, role): """ dismember user from a group """
if not self.has_membership(user, role): return True targetRecord = AuthMembership.objects(creator=self.client, user=user).first() if not targetRecord: return True for group in targetRecord.groups: if group.role==role: targetRecord.groups.remove(group) targetRecord.save() 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 has_membership(self, user, role): """ checks if user is member of a group"""
targetRecord = AuthMembership.objects(creator=self.client, user=user).first() if targetRecord: return role in [i.role for i in targetRecord.groups] 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 add_permission(self, role, name): """ authorize a group for something """
if self.has_permission(role, name): return True targetGroup = AuthGroup.objects(role=role, creator=self.client).first() if not targetGroup: return False # Create or update permission = AuthPermission.objects(name=name).update( add_to_set__groups=[targetGroup], creator=self.client, upsert=True ) 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 del_permission(self, role, name): """ revoke authorization of a group """
if not self.has_permission(role, name): return True targetGroup = AuthGroup.objects(role=role, creator=self.client).first() target = AuthPermission.objects(groups=targetGroup, name=name, creator=self.client).first() if not target: return True target.delete() 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 user_has_permission(self, user, name): """ verify user has permission """
targetRecord = AuthMembership.objects(creator=self.client, user=user).first() if not targetRecord: return False for group in targetRecord.groups: if self.has_permission(group.role, name): 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 handler(event): """Signal decorator to allow use of callback functions as class decorators."""
def decorator(fn): def apply(cls): event.connect(fn, sender=cls) return cls fn.apply = apply return fn return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stringify(req, resp): """ dumps all valid jsons This is the latest after hook """
if isinstance(resp.body, dict): try: resp.body = json.dumps(resp.body) except(nameError): resp.status = falcon.HTTP_500
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def instantiate(self, scope, args, interp): """Create a ParamList instance for actual interpretation :args: TODO :returns: A ParamList object """
param_instances = [] BYREF = "byref" # TODO are default values for function parameters allowed in 010? for param_name, param_cls in self._params: # we don't instantiate a copy of byref params if getattr(param_cls, "byref", False): param_instances.append(BYREF) else: field = param_cls() field._pfp__name = param_name param_instances.append(field) if len(args) != len(param_instances): raise errors.InvalidArguments( self._coords, [x.__class__.__name__ for x in args], [x.__class__.__name__ for x in param_instances] ) # TODO type checking on provided types for x in six.moves.range(len(args)): param = param_instances[x] # arrays are simply passed through into the function. We shouldn't # have to worry about frozenness/unfrozenness at this point if param is BYREF or isinstance(param, pfp.fields.Array): param = args[x] param_instances[x] = param scope.add_local(self._params[x][0], param) else: param._pfp__set_value(args[x]) scope.add_local(param._pfp__name, param) param._pfp__interp = interp return ParamList(param_instances)
<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_library(lookup=True, key='exp_id'): ''' return the raw library, without parsing''' library = None response = requests.get(EXPFACTORY_LIBRARY) if response.status_code == 200: library = response.json() if lookup is True: return make_lookup(library,key=key) return library
<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(self): ''' obtain database and filesystem preferences from defaults, and compare with selection in container. ''' self.selection = EXPFACTORY_EXPERIMENTS self.ordered = len(EXPFACTORY_EXPERIMENTS) > 0 self.data_base = EXPFACTORY_DATA self.study_id = EXPFACTORY_SUBID self.base = EXPFACTORY_BASE self.randomize = EXPFACTORY_RANDOMIZE self.headless = EXPFACTORY_HEADLESS # Generate variables, if they exist self.vars = generate_runtime_vars() or None available = get_experiments("%s" % self.base) self.experiments = get_selection(available, self.selection) self.logger.debug(self.experiments) self.lookup = make_lookup(self.experiments) final = "\n".join(list(self.lookup.keys())) bot.log("Headless mode: %s" % self.headless) bot.log("User has selected: %s" % self.selection) bot.log("Experiments Available: %s" %"\n".join(available)) bot.log("Randomize: %s" % self.randomize) bot.log("Final Set \n%s" % final)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def finish_experiment(self, session, exp_id): '''remove an experiment from the list after completion. ''' self.logger.debug('Finishing %s' %exp_id) experiments = session.get('experiments', []) experiments = [x for x in experiments if x != exp_id] session['experiments'] = experiments return experiments
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def copy_directory(src, dest, force=False): ''' Copy an entire directory recursively ''' if os.path.exists(dest) and force is True: shutil.rmtree(dest) try: shutil.copytree(src, dest) except OSError as e: # If the error was caused because the source wasn't a directory if e.errno == errno.ENOTDIR: shutil.copy(src, dest) else: bot.error('Directory not copied. Error: %s' % e) sys.exit(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def clone(url, tmpdir=None): '''clone a repository from Github''' if tmpdir is None: tmpdir = tempfile.mkdtemp() name = os.path.basename(url).replace('.git', '') dest = '%s/%s' %(tmpdir,name) return_code = os.system('git clone %s %s' %(url,dest)) if return_code == 0: return dest bot.error('Error cloning repo.') sys.exit(return_code)
<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_template(name, base=None): '''read in and return a template file ''' # If the file doesn't exist, assume relative to base template_file = name if not os.path.exists(template_file): if base is None: base = get_templatedir() template_file = "%s/%s" %(base, name) # Then try again, if it still doesn't exist, bad name if os.path.exists(template_file): with open(template_file,"r") as filey: template = "".join(filey.readlines()) return template bot.error("%s does not exist." %template_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sub_template(template,template_tag,substitution): '''make a substitution for a template_tag in a template ''' template = template.replace(template_tag,substitution) return template
<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_post_fields(request): '''parse through a request, and return fields from post in a dictionary ''' fields = dict() for field,value in request.form.items(): fields[field] = value return fields
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse( data = None, template = None, data_file = None, template_file = None, interp = None, debug = False, predefines = True, int3 = True, keep_successful = False, printf = True, ): """Parse the data stream using the supplied template. The data stream WILL NOT be automatically closed. :data: Input data, can be either a string or a file-like object (StringIO, file, etc) :template: template contents (str) :data_file: PATH to the data to be used as the input stream :template_file: template file path :interp: the interpretor to be used (a default one will be created if ``None``) :debug: if debug information should be printed while interpreting the template (false) :predefines: if built-in type information should be inserted (true) :int3: if debugger breaks are allowed while interpreting the template (true) :keep_successful: return any succesfully parsed data instead of raising an error. If an error occurred and ``keep_successful`` is True, then ``_pfp__error`` will be contain the exception object :printf: if ``False``, all calls to ``Printf`` (:any:`pfp.native.compat_interface.Printf`) will be noops. (default=``True``) :returns: pfp DOM """
if data is None and data_file is None: raise Exception("No input data was specified") if data is not None and data_file is not None: raise Exception("Only one input data may be specified") if isinstance(data, six.string_types): data = six.StringIO(data) if data_file is not None: data = open(os.path.expanduser(data_file), "rb") if template is None and template_file is None: raise Exception("No template specified!") if template is not None and template_file is not None: raise Exception("Only one template may be specified!") orig_filename = "string" if template_file is not None: orig_filename = template_file try: with open(os.path.expanduser(template_file), "r") as f: template = f.read() except Exception as e: raise Exception("Could not open template file '{}'".format(template_file)) # the user may specify their own instance of PfpInterp to be # used if interp is None: interp = pfp.interp.PfpInterp( debug = debug, parser = PARSER, int3 = int3, ) # so we can consume single bits at a time data = BitwrappedStream(data) dom = interp.parse( data, template, predefines = predefines, orig_filename = orig_filename, keep_successful = keep_successful, printf = printf, ) # close the data stream if a data_file was specified if data_file is not None: data.close() return dom
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FindFirst(params, ctxt, scope, stream, coord, interp): """ This function is identical to the FindAll function except that the return value is the position of the first occurrence of the target found. A negative number is returned if the value could not be found. """
global FIND_MATCHES_ITER FIND_MATCHES_ITER = _find_helper(params, ctxt, scope, stream, coord, interp) try: first = six.next(FIND_MATCHES_ITER) return first.start() + FIND_MATCHES_START_OFFSET except StopIteration as e: return -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 FindNext(params, ctxt, scope, stream, coord): """ This function returns the position of the next occurrence of the target value specified with the FindFirst function. If dir is 1, the find direction is down. If dir is 0, the find direction is up. The return value is the address of the found data, or -1 if the target is not found. """
if FIND_MATCHES_ITER is None: raise errors.InvalidState() direction = 1 if len(params) > 0: direction = PYVAL(params[0]) if direction != 1: # TODO maybe instead of storing the iterator in FIND_MATCHES_ITER, # we should go ahead and find _all the matches in the file and store them # in a list, keeping track of the idx of the current match. # # This would be highly inefficient on large files though. raise NotImplementedError("Reverse searching is not yet implemented") try: next_match = six.next(FIND_MATCHES_ITER) return next_match.start() + FIND_MATCHES_START_OFFSET except StopIteration as e: return -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 list_users(self): '''list users, each associated with a filesystem folder ''' folders = glob('%s/*' %(self.database)) folders.sort() return [self.print_user(x) for x in folders]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def generate_user(self, subid=None): '''generate a new user on the filesystem, still session based so we create a new identifier. This function is called from the users new entrypoint, and it assumes we want a user generated with a token. since we don't have a database proper, we write the folder name to the filesystem ''' # Only generate token if subid being created if subid is None: token = str(uuid.uuid4()) subid = self.generate_subid(token=token) if os.path.exists(self.data_base): # /scif/data data_base = "%s/%s" %(self.data_base, subid) # expfactory/00001 if not os.path.exists(data_base): mkdir_p(data_base) return data_base
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def restart_user(self, subid): '''restart user will remove any "finished" or "revoked" extensions from the user folder to restart the session. This command always comes from the client users function, so we know subid does not start with the study identifer first ''' if os.path.exists(self.data_base): # /scif/data/<study_id> data_base = "%s/%s" %(self.data_base, subid) for ext in ['revoked','finished']: folder = "%s_%s" % (data_base, ext) if os.path.exists(folder): os.rename(folder, data_base) self.logger.info('Restarting %s, folder is %s.' % (subid, data_base)) self.logger.warning('%s does not have revoked or finished folder, no changes necessary.' % (subid)) return data_base self.logger.warning('%s does not exist, cannot restart. %s' % (self.database, subid))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def refresh_token(self, subid): '''refresh or generate a new token for a user. If the user is finished, this will also make the folder available again for using.''' if os.path.exists(self.data_base): # /scif/data data_base = "%s/%s" %(self.data_base, subid) if os.path.exists(data_base): refreshed = "%s/%s" %(self.database, str(uuid.uuid4())) os.rename(data_base, refreshed) return refreshed self.logger.warning('%s does not exist, cannot rename %s' % (data_base, subid)) else: self.logger.warning('%s does not exist, cannot rename %s' % (self.database, subid))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def native(name, ret, interp=None, send_interp=False): """Used as a decorator to add the decorated function to the pfp interpreter so that it can be used from within scripts. :param str name: The name of the function as it will be exposed in template scripts. :param pfp.fields.Field ret: The return type of the function (a class) :param pfp.interp.PfpInterp interp: The specific interpreter to add the function to :param bool send_interp: If the current interpreter should be passed to the function. Examples: The example below defines a ``Sum`` function that will return the sum of all parameters passed to the function: :: from pfp.fields import PYVAL @native(name="Sum", ret=pfp.fields.Int64) def sum_numbers(params, ctxt, scope, stream, coord): res = 0 for param in params: res += PYVAL(param) return res The code below is the code for the :any:`Int3 <pfp.native.dbg.int3>` function. Notice that it requires that the interpreter be sent as a parameter: :: @native(name="Int3", ret=pfp.fields.Void, send_interp=True) def int3(params, ctxt, scope, stream, coord, interp): if interp._no_debug: return if interp._int3: interp.debugger = PfpDbg(interp) interp.debugger.cmdloop() """
def native_decorator(func): @functools.wraps(func) def native_wrapper(*args, **kwargs): return func(*args, **kwargs) pfp.interp.PfpInterp.add_native(name, func, ret, interp=interp, send_interp=send_interp) return native_wrapper return native_decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_next(self, args): """Step over the next statement """
self._do_print_from_last_cmd = True self._interp.step_over() 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 do_step(self, args): """Step INTO the next statement """
self._do_print_from_last_cmd = True self._interp.step_into() 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 do_continue(self, args): """Continue the interpreter """
self._do_print_from_last_cmd = True self._interp.cont() 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 do_eval(self, args): """Eval the user-supplied statement. Note that you can do anything with this command that you can do in a template. The resulting value of your statement will be displayed. """
try: res = self._interp.eval(args) if res is not None: if hasattr(res, "_pfp__show"): print(res._pfp__show()) else: print(repr(res)) except errors.UnresolvedID as e: print("ERROR: " + e.message) except Exception as e: raise print("ERROR: " + e.message) 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 do_quit(self, args): """The quit command """
self._interp.set_break(self._interp.BREAK_NONE) 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 validate(self, url): ''' takes in a Github repository for validation of preview and runtime (and possibly tests passing? ''' # Preview must provide the live URL of the repository if not url.startswith('http') or not 'github' in url: bot.error('Test of preview must be given a Github repostitory.') return False if not self._validate_preview(url): 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 mask_dict_password(dictionary, secret='***'): """Replace passwords with a secret in a dictionary."""
d = dictionary.copy() for k in d: if 'password' in k: d[k] = secret return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def save(): '''save is a view to save data. We might want to adjust this to allow for updating saved data, but given single file is just one post for now ''' if request.method == 'POST': exp_id = session.get('exp_id') app.logger.debug('Saving data for %s' %exp_id) fields = get_post_fields(request) result_file = app.save_data(session=session, content=fields, exp_id=exp_id) experiments = app.finish_experiment(session, exp_id) app.logger.info('Finished %s, %s remaining.' % (exp_id, len(experiments))) # Note, this doesn't seem to be enough to trigger ajax success return json.dumps({'success':True}), 200, {'ContentType':'application/json'} return json.dumps({'success':False}), 403, {'ContentType':'application/json'}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def main(args,parser,subparser=None): '''this is the main entrypoint for a container based web server, with most of the variables coming from the environment. See the Dockerfile template for how this function is executed. ''' # First priority to args.base base = args.base if base is None: base = os.environ.get('EXPFACTORY_BASE') # Does the base folder exist? if base is None: bot.error("You must set a base of experiments with --base" % base) sys.exit(1) if not os.path.exists(base): bot.error("Base folder %s does not exist." % base) sys.exit(1) # Export environment variables for the client experiments = args.experiments if experiments is None: experiments = " ".join(glob("%s/*" % base)) os.environ['EXPFACTORY_EXPERIMENTS'] = experiments # If defined and file exists, set runtime variables if args.vars is not None: if os.path.exists(args.vars): os.environ['EXPFACTORY_RUNTIME_VARS'] = args.vars os.environ['EXPFACTORY_RUNTIME_DELIM'] = args.delim else: bot.warning('Variables file %s not found.' %args.vars) subid = os.environ.get('EXPFACTORY_STUDY_ID') if args.subid is not None: subid = args.subid os.environ['EXPFACTORY_SUBID'] = subid os.environ['EXPFACTORY_RANDOM'] = str(args.disable_randomize) os.environ['EXPFACTORY_BASE'] = base from expfactory.server import start start(port=5000)
<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_data(self,session, exp_id, content): '''save data will obtain the current subid from the session, and save it depending on the database type.''' from expfactory.database.models import ( Participant, Result ) subid = session.get('subid') bot.info('Saving data for subid %s' % subid) # We only attempt save if there is a subject id, set at start if subid is not None: p = Participant.query.filter(Participant.id == subid).first() # better query here # Preference is to save data under 'data', otherwise do all of it if "data" in content: content = content['data'] if isinstance(content,dict): content = json.dumps(content) result = Result(data=content, exp_id=exp_id, participant_id=p.id) # check if changes from str/int self.session.add(result) p.results.append(result) self.session.commit() bot.info("Participant: %s" %p) bot.info("Result: %s" %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 read_bits(self, stream, num_bits, padded, left_right, endian): """Return ``num_bits`` bits, taking into account endianness and left-right bit directions """
if self._cls_bits is None and padded: raw_bits = stream.read_bits(self.cls.width*8) self._cls_bits = self._endian_transform(raw_bits, endian) if self._cls_bits is not None: if num_bits > len(self._cls_bits): raise errors.PfpError("BitfieldRW reached invalid state") if left_right: res = self._cls_bits[:num_bits] self._cls_bits = self._cls_bits[num_bits:] else: res = self._cls_bits[-num_bits:] self._cls_bits = self._cls_bits[:-num_bits] return res else: return stream.read_bits(num_bits)
<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_bits(self, stream, raw_bits, padded, left_right, endian): """Write the bits. Once the size of the written bits is equal to the number of the reserved bits, flush it to the stream """
if padded: if left_right: self._write_bits += raw_bits else: self._write_bits = raw_bits + self._write_bits if len(self._write_bits) == self.reserved_bits: bits = self._endian_transform(self._write_bits, endian) # if it's padded, and all of the bits in the field weren't used, # we need to flush out the unused bits # TODO should we save the value of the unused bits so the data that # is written out matches exactly what was read? if self.reserved_bits < self.cls.width * 8: filler = [0] * ((self.cls.width * 8) - self.reserved_bits) if left_right: bits += filler else: bits = filler + bits stream.write_bits(bits) self._write_bits = [] else: # if an unpadded field ended up using the same BitfieldRW and # as a previous padded field, there will be unwritten bits left in # self._write_bits. These need to be flushed out as well if len(self._write_bits) > 0: stream.write_bits(self._write_bits) self._write_bits = [] stream.write_bits(raw_bits)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pfp__process_metadata(self): """Process the metadata once the entire struct has been declared. """
if self._pfp__metadata_processor is None: return metadata_info = self._pfp__metadata_processor() if isinstance(metadata_info, list): for metadata in metadata_info: if metadata["type"] == "watch": self._pfp__set_watch( metadata["watch_fields"], metadata["update_func"], *metadata["func_call_info"] ) elif metadata["type"] == "packed": del metadata["type"] self._pfp__set_packer(**metadata) if self._pfp__can_unpack(): self._pfp__unpack_data(self.raw_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 _pfp__watch(self, watcher): """Add the watcher to the list of fields that are watching this field """
if self._pfp__parent is not None and isinstance(self._pfp__parent, Union): self._pfp__parent._pfp__watch(watcher) else: self._pfp__watchers.append(watcher)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pfp__set_watch(self, watch_fields, update_func, *func_call_info): """Subscribe to update events on each field in ``watch_fields``, using ``update_func`` to update self's value when ``watch_field`` changes"""
self._pfp__watch_fields = watch_fields for watch_field in watch_fields: watch_field._pfp__watch(self) self._pfp__update_func = update_func self._pfp__update_func_call_info = func_call_info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pfp__pack_data(self): """Pack the nested field """
if self._pfp__pack_type is None: return tmp_stream = six.BytesIO() self._._pfp__build(bitwrap.BitwrappedStream(tmp_stream)) raw_data = tmp_stream.getvalue() unpack_func = self._pfp__packer unpack_args = [] if self._pfp__packer is not None: unpack_func = self._pfp__packer unpack_args = [true(), raw_data] elif self._pfp__pack is not None: unpack_func = self._pfp__pack unpack_args = [raw_data] # does not need to be converted to a char array if not isinstance(unpack_func, functions.NativeFunction): io_stream = bitwrap.BitwrappedStream(six.BytesIO(raw_data)) unpack_args[-1] = Array(len(raw_data), Char, io_stream) res = unpack_func.call(unpack_args, *self._pfp__pack_func_call_info, no_cast=True) if isinstance(res, Array): res = res._pfp__build() io_stream = six.BytesIO(res) tmp_stream = bitwrap.BitwrappedStream(io_stream) self._pfp__no_unpack = True self._pfp__parse(tmp_stream) self._pfp__no_unpack = 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 _pfp__unpack_data(self, raw_data): """Means that the field has already been parsed normally, and that it now needs to be unpacked. :raw_data: A string of the data that the field consumed while parsing """
if self._pfp__pack_type is None: return if self._pfp__no_unpack: return unpack_func = self._pfp__packer unpack_args = [] if self._pfp__packer is not None: unpack_func = self._pfp__packer unpack_args = [false(), raw_data] elif self._pfp__unpack is not None: unpack_func = self._pfp__unpack unpack_args = [raw_data] # does not need to be converted to a char array if not isinstance(unpack_func, functions.NativeFunction): io_stream = bitwrap.BitwrappedStream(six.BytesIO(raw_data)) unpack_args[-1] = Array(len(raw_data), Char, io_stream) res = unpack_func.call(unpack_args, *self._pfp__pack_func_call_info, no_cast=True) if isinstance(res, Array): res = res._pfp__build() io_stream = six.BytesIO(res) tmp_stream = bitwrap.BitwrappedStream(io_stream) tmp_stream.padded = self._pfp__interp.get_bitfield_padded() self._ = self._pfp__parsed_packed = self._pfp__pack_type(tmp_stream) self._._pfp__watch(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 _pfp__handle_updated(self, watched_field): """Handle the watched field that was updated """
self._pfp__no_notify = True # nested data has been changed, so rebuild the # nested data to update the field # TODO a global setting to determine this behavior? # could slow things down a bit for large nested structures # notice the use of _is_ here - 'is' != '=='. '==' uses # the __eq__ operator, while is compares id(object) results if watched_field is self._: self._pfp__pack_data() elif self._pfp__update_func is not None: self._pfp__update_func.call( [self] + self._pfp__watch_fields, *self._pfp__update_func_call_info ) self._pfp__no_notify = 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 _pfp__restore_snapshot(self, recurse=True): """Restore the snapshotted value without triggering any events """
super(Struct, self)._pfp__restore_snapshot(recurse=recurse) if recurse: for child in self._pfp__children: child._pfp__restore_snapshot(recurse=recurse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pfp__set_value(self, value): """Initialize the struct. Value should be an array of fields, one each for each struct member. :value: An array of fields to initialize the struct with :returns: None """
if self._pfp__frozen: raise errors.UnmodifiableConst() if len(value) != len(self._pfp__children): raise errors.PfpError("struct initialization has wrong number of members") for x in six.moves.range(len(self._pfp__children)): self._pfp__children[x]._pfp__set_value(value[x])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pfp__add_child(self, name, child, stream=None, overwrite=False): """Add a child to the Struct field. If multiple consecutive fields are added with the same name, an implicit array will be created to store all fields of that name. :param str name: The name of the child :param pfp.fields.Field child: The field to add :param bool overwrite: Overwrite existing fields (False) :param pfp.bitwrap.BitwrappedStream stream: unused, but her for compatability with Union._pfp__add_child :returns: The resulting field added """
if not overwrite and self._pfp__is_non_consecutive_duplicate(name, child): return self._pfp__handle_non_consecutive_duplicate(name, child) elif not overwrite and name in self._pfp__children_map: return self._pfp__handle_implicit_array(name, child) else: child._pfp__parent = self self._pfp__children.append(child) child._pfp__name = name self._pfp__children_map[name] = child return child
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pfp__handle_implicit_array(self, name, child): """Handle inserting implicit array elements """
existing_child = self._pfp__children_map[name] if isinstance(existing_child, Array): # I don't think we should check this # #if existing_child.field_cls != child.__class__: # raise errors.PfpError("implicit arrays must be sequential!") existing_child.append(child) return existing_child else: cls = child._pfp__class if hasattr(child, "_pfp__class") else child.__class__ ary = Array(0, cls) # since the array starts with the first item ary._pfp__offset = existing_child._pfp__offset ary._pfp__parent = self ary._pfp__name = name ary.implicit = True ary.append(existing_child) ary.append(child) exist_idx = -1 for idx,child in enumerate(self._pfp__children): if child is existing_child: exist_idx = idx break self._pfp__children[exist_idx] = ary self._pfp__children_map[name] = ary return ary
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pfp__show(self, level=0, include_offset=False): """Show the contents of the struct """
res = [] res.append("{}{} {{".format( "{:04x} ".format(self._pfp__offset) if include_offset else "", self._pfp__show_name )) for child in self._pfp__children: res.append("{}{}{:10s} = {}".format( " "*(level+1), "{:04x} ".format(child._pfp__offset) if include_offset else "", child._pfp__name, child._pfp__show(level+1, include_offset) )) res.append("{}}}".format(" "*level)) return "\n".join(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 _pfp__add_child(self, name, child, stream=None): """Add a child to the Union field :name: The name of the child :child: A :class:`.Field` instance :returns: The resulting field """
res = super(Union, self)._pfp__add_child(name, child) self._pfp__buff.seek(0, 0) child._pfp__build(stream=self._pfp__buff) size = len(self._pfp__buff.getvalue()) self._pfp__buff.seek(0, 0) if stream is not None: curr_pos = stream.tell() stream.seek(curr_pos-size, 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 _pfp__notify_update(self, child=None): """Handle a child with an updated value """
if getattr(self, "_pfp__union_update_other_children", True): self._pfp__union_update_other_children = False new_data = child._pfp__build() new_stream = bitwrap.BitwrappedStream(six.BytesIO(new_data)) for other_child in self._pfp__children: if other_child is child: continue if isinstance(other_child, Array) and other_child.is_stringable(): other_child._pfp__set_value(new_data) else: other_child._pfp__parse(new_stream) new_stream.seek(0) self._pfp__no_update_other_children = True super(Union, self)._pfp__notify_update(child=child)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pfp__build(self, stream=None, save_offset=False): """Build the union and write the result into the stream. :stream: None :returns: None """
max_size = -1 if stream is None: core_stream = six.BytesIO() new_stream = bitwrap.BitwrappedStream(core_stream) else: new_stream = stream for child in self._pfp__children: curr_pos = new_stream.tell() child._pfp__build(new_stream, save_offset) size = new_stream.tell() - curr_pos new_stream.seek(-size, 1) if size > max_size: max_size = size new_stream.seek(max_size, 1) if stream is None: return core_stream.getvalue() else: return max_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 _pfp__parse(self, stream, save_offset=False): """Parse the IO stream for this numeric field :stream: An IO stream that can be read from :returns: The number of bytes parsed """
if save_offset: self._pfp__offset = stream.tell() if self.bitsize is None: raw_data = stream.read(self.width) data = utils.binary(raw_data) else: bits = self.bitfield_rw.read_bits(stream, self.bitsize, self.bitfield_padded, self.bitfield_left_right, self.endian) width_diff = self.width - (len(bits)//8) - 1 bits_diff = 8 - (len(bits) % 8) padding = [0] * (width_diff * 8 + bits_diff) bits = padding + bits data = bitwrap.bits_to_bytes(bits) if self.endian == LITTLE_ENDIAN: # reverse the data data = data[::-1] if len(data) < self.width: raise errors.PrematureEOF() self._pfp__data = data self._pfp__value = struct.unpack( "{}{}".format(self.endian, self.format), data )[0] return self.width
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dom_class(self, obj1, obj2): """Return the dominating numeric class between the two :obj1: TODO :obj2: TODO :returns: TODO """
if isinstance(obj1, Double) or isinstance(obj2, Double): return Double if isinstance(obj1, Float) or isinstance(obj2, Float): return Float
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pfp__parse(self, stream, save_offset=False): """Parse the IO stream for this enum :stream: An IO stream that can be read from :returns: The number of bytes parsed """
res = super(Enum, self)._pfp__parse(stream, save_offset) if self._pfp__value in self.enum_vals: self.enum_name = self.enum_vals[self._pfp__value] else: self.enum_name = "?? UNK_ENUM ??" 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 _pfp__set_value(self, new_val): """Set the value of the String, taking into account escaping and such as well """
if not isinstance(new_val, Field): new_val = utils.binary(utils.string_escape(new_val)) super(String, self)._pfp__set_value(new_val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pfp__parse(self, stream, save_offset=False): """Read from the stream until the string is null-terminated :stream: The input stream :returns: None """
if save_offset: self._pfp__offset = stream.tell() res = utils.binary("") while True: byte = utils.binary(stream.read(self.read_size)) if len(byte) < self.read_size: raise errors.PrematureEOF() # note that the null terminator must be added back when # built again! if byte == self.terminator: break res += byte self._pfp__value = 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 _pfp__build(self, stream=None, save_offset=False): """Build the String field :stream: TODO :returns: TODO """
if stream is not None and save_offset: self._pfp__offset = stream.tell() data = self._pfp__value + utils.binary("\x00") if stream is None: return data else: stream.write(data) return len(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 Printf(params, ctxt, scope, stream, coord, interp): """Prints format string to stdout :params: TODO :returns: TODO """
if len(params) == 1: if interp._printf: sys.stdout.write(PYSTR(params[0])) return len(PYSTR(params[0])) parts = [] for part in params[1:]: if isinstance(part, pfp.fields.Array) or isinstance(part, pfp.fields.String): parts.append(PYSTR(part)) else: parts.append(PYVAL(part)) to_print = PYSTR(params[0]) % tuple(parts) res = len(to_print) if interp._printf: sys.stdout.write(to_print) sys.stdout.flush() 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 get_strategy(name_or_cls): """Return the strategy identified by its name. If ``name_or_class`` is a class, it will be simply returned. """
if isinstance(name_or_cls, six.string_types): if name_or_cls not in STRATS: raise MutationError("strat is not defined") return STRATS[name_or_cls]() return name_or_cls()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mutate(self, field): """Mutate the given field, modifying it directly. This is not intended to preserve the value of the field. :field: The pfp.fields.Field instance that will receive the new value """
new_val = self.next_val(field) field._pfp__set_value(new_val) return field
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def generate_subid(self, token=None, return_user=False): '''generate a new user in the database, still session based so we create a new identifier. ''' from expfactory.database.models import Participant if not token: p = Participant() else: p = Participant(token=token) self.session.add(p) self.session.commit() if return_user is True: return p return p.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 print_user(self, user): '''print a relational database user ''' status = "active" token = user.token if token in ['finished', 'revoked']: status = token if token is None: token = '' subid = "%s\t%s[%s]" %(user.id, token, status) print(subid) return subid
<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_users(self, user=None): '''list users, each having a model in the database. A headless experiment will use protected tokens, and interactive will be based on auto- incremented ids. ''' from expfactory.database.models import Participant participants = Participant.query.all() users = [] for user in participants: users.append(self.print_user(user)) return users
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def generate_user(self): '''generate a new user in the database, still session based so we create a new identifier. This function is called from the users new entrypoint, and it assumes we want a user generated with a token. ''' token = str(uuid.uuid4()) return self.generate_subid(token=token, return_user=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 finish_user(self, subid): '''finish user will remove a user's token, making the user entry not accesible if running in headless model''' p = self.revoke_token(subid) p.token = "finished" self.session.commit() return p
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def restart_user(self, subid): '''restart a user, which means revoking and issuing a new token.''' p = self.revoke_token(subid) p = self.refresh_token(subid) return p
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def revoke_token(self, subid): '''revoke a token by removing it. Is done at finish, and also available as a command line option''' from expfactory.database.models import Participant p = Participant.query.filter(Participant.id == subid).first() if p is not None: p.token = 'revoked' self.session.commit() return p
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def refresh_token(self, subid): '''refresh or generate a new token for a user''' from expfactory.database.models import Participant p = Participant.query.filter(Participant.id == subid).first() if p is not None: p.token = str(uuid.uuid4()) self.session.commit() return p
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrap_type_instantiation(self, type_cls): """Wrap the creation of the type so that we can provide a null-stream to initialize it"""
def wrapper(*args, **kwargs): # use args for struct arguments?? return type_cls(stream=self._null_stream) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def level(self): """Return the current scope level """
res = len(self._scope_stack) if self._parent is not None: res += self._parent.level() 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 add_local(self, field_name, field): """Add a local variable in the current scope :field_name: The field's name :field: The field :returns: None """
self._dlog("adding local '{}'".format(field_name)) field._pfp__name = field_name # TODO do we allow clobbering of locals??? self._curr_scope["vars"][field_name] = field
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_type_struct_or_union(self, name, interp, node): """Store the node with the name. When it is instantiated, the node itself will be handled. :name: name of the typedefd struct/union :node: the union/struct node :interp: the 010 interpreter """
self.add_type_class(name, StructUnionDef(name, interp, 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 add_type(self, new_name, orig_names): """Record the typedefd name for orig_names. Resolve orig_names to their core names and save those. :new_name: TODO :orig_names: TODO :returns: TODO """
self._dlog("adding a type '{}'".format(new_name)) # TODO do we allow clobbering of types??? res = copy.copy(orig_names) resolved_names = self._resolve_name(res[-1]) if resolved_names is not None: res.pop() res += resolved_names self._curr_scope["types"][new_name] = 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 get_id(self, name, recurse=True): """Get the first id matching ``name``. Will either be a local or a var. :name: TODO :returns: TODO """
self._dlog("getting id '{}'".format(name)) var = self._search("vars", name, recurse) return var
<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_native(cls, name, func, ret, interp=None, send_interp=False): """Add the native python function ``func`` into the pfp interpreter with the name ``name`` and return value ``ret`` so that it can be called from within a template script. .. note:: The :any:`@native <pfp.native.native>` decorator exists to simplify this. All native functions must have the signature ``def func(params, ctxt, scope, stream, coord [,interp])``, optionally allowing an interpreter param if ``send_interp`` is ``True``. Example: The example below defines a function ``Sum`` using the ``add_native`` method. :: import pfp.fields from pfp.fields import PYVAL def native_sum(params, ctxt, scope, stream, coord): return PYVAL(params[0]) + PYVAL(params[1]) pfp.interp.PfpInterp.add_native("Sum", native_sum, pfp.fields.Int64) :param basestring name: The name the function will be exposed as in the interpreter. :param function func: The native python function that will be referenced. :param type(pfp.fields.Field) ret: The field class that the return value should be cast to. :param pfp.interp.PfpInterp interp: The specific pfp interpreter the function should be defined in. :param bool send_interp: If true, the current pfp interpreter will be added as an argument to the function. """
if interp is None: natives = cls._natives else: # the instance's natives natives = interp._natives natives[name] = functions.NativeFunction( name, func, ret, send_interp )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def define_natives(cls): """Define the native functions for PFP """
if len(cls._natives) > 0: return glob_pattern = os.path.join(os.path.dirname(__file__), "native", "*.py") for filename in glob.glob(glob_pattern): basename = os.path.basename(filename).replace(".py", "") if basename == "__init__": continue try: mod_base = __import__("pfp.native", globals(), locals(), fromlist=[basename]) except Exception as e: sys.stderr.write("cannot import native module {} at '{}'".format(basename, filename)) raise e continue mod = getattr(mod_base, basename) setattr(mod, "PYVAL", fields.get_value) setattr(mod, "PYSTR", fields.get_str)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dlog(self, msg, indent_increase=0): """log the message to the log"""
self._log.debug("interp", msg, indent_increase, filename=self._orig_filename, coord=self._coord)
<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_break(self, break_type): """Set if the interpreter should break. :returns: TODO """
self._break_type = break_type self._break_level = self._scope.level()
<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_curr_lines(self): """Return the current line number in the template, as well as the surrounding source lines """
start = max(0, self._coord.line - 5) end = min(len(self._template_lines), self._coord.line + 4) lines = [(x, self._template_lines[x]) for x in six.moves.range(start, end, 1)] return self._coord.line, lines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_node(self, node, scope=None, ctxt=None, stream=None): """Recursively handle nodes in the 010 AST :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """
if scope is None: if self._scope is None: self._scope = scope = self._create_scope() else: scope = self._scope if ctxt is None and self._ctxt is not None: ctxt = self._ctxt else: self._ctxt = ctxt if type(node) is tuple: node = node[1] # TODO probably a better way to do this... # this occurs with if-statements that have a single statement # instead of a compound statement (no curly braces) elif type(node) is list and len(list(filter(lambda x: isinstance(x, AST.Node), node))) == len(node): node = AST.Compound( block_items=node, coord=node[0].coord ) return self._handle_node(node, scope, ctxt, stream) # need to check this so that debugger-eval'd statements # don't mess with the current state if not self._no_debug: self._coord = node.coord self._dlog("handling node type {}, line {}".format(node.__class__.__name__, node.coord.line if node.coord is not None else "?")) self._log.inc() breakable = self._node_is_breakable(node) if breakable and not self._no_debug and self._break_type != self.BREAK_NONE: # always break if self._break_type == self.BREAK_INTO: self._break_level = self._scope.level() self.debugger.cmdloop() # level <= _break_level elif self._break_type == self.BREAK_OVER: if self._scope.level() <= self._break_level: self._break_level = self._scope.level() self.debugger.cmdloop() else: pass if node.__class__ not in self._node_switch: raise errors.UnsupportedASTNode(node.coord, node.__class__.__name__) res = self._node_switch[node.__class__](node, scope, ctxt, stream) self._log.dec() 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 _handle_cast(self, node, scope, ctxt, stream): """Handle cast nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """
self._dlog("handling cast") to_type = self._handle_node(node.to_type, scope, ctxt, stream) val_to_cast = self._handle_node(node.expr, scope, ctxt, stream) res = to_type() res._pfp__set_value(val_to_cast) 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 _get_node_name(self, node): """Get the name of the node - check for node.name and node.type.declname. Not sure why the second one occurs exactly - it happens with declaring a new struct field with parameters"""
res = getattr(node, "name", None) if res is None: return res if isinstance(res, AST.TypeDecl): return res.declname 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 _handle_metadata(self, node, scope, ctxt, stream): """Handle metadata for the node """
self._dlog("handling node metadata {}".format(node.metadata.keyvals)) keyvals = node.metadata.keyvals metadata_info = [] if "watch" in node.metadata.keyvals or "update" in keyvals: metadata_info.append( self._handle_watch_metadata(node, scope, ctxt, stream) ) if "packtype" in node.metadata.keyvals or "packer" in keyvals: metadata_info.append( self._handle_packed_metadata(node, scope, ctxt, stream) ) return metadata_info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_watch_metadata(self, node, scope, ctxt, stream): """Handle watch vars for fields """
keyvals = node.metadata.keyvals if "watch" not in keyvals: raise errors.PfpError("Packed fields require a packer function set") if "update" not in keyvals: raise errors.PfpError("Packed fields require a packer function set") watch_field_name = keyvals["watch"] update_func_name = keyvals["update"] watch_fields = list(map(lambda x: self.eval(x.strip()), watch_field_name.split(";"))) update_func = scope.get_id(update_func_name) return { "type": "watch", "watch_fields": watch_fields, "update_func": update_func, "func_call_info": (ctxt, scope, stream, self, self._coord) }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_packed_metadata(self, node, scope, ctxt, stream): """Handle packed metadata """
keyvals = node.metadata.keyvals if "packer" not in keyvals and ("pack" not in keyvals or "unpack" not in keyvals): raise errors.PfpError("Packed fields require a packer function to be set or pack and unpack functions to be set") if "packtype" not in keyvals: raise errors.PfpError("Packed fields require a packtype to be set") args_ = {} if "packer" in keyvals: packer_func_name = keyvals["packer"] packer_func = scope.get_id(packer_func_name) args_["packer"] = packer_func elif "pack" in keyvals and "unpack" in keyvals: pack_func = scope.get_id(keyvals["pack"]) unpack_func = scope.get_id(keyvals["unpack"]) args_["pack"] = pack_func args_["unpack"] = unpack_func packtype_cls_name = keyvals["packtype"] packtype_cls = scope.get_type(packtype_cls_name) args_["pack_type"] = packtype_cls args_["type"] = "packed" args_["func_call_info"] = (ctxt, scope, stream, self, self._coord) return 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 _str_to_int(self, string): """Check for the hex """
string = string.lower() if string.endswith("l"): string = string[:-1] if string.lower().startswith("0x"): # should always match match = re.match(r'0[xX]([a-fA-F0-9]+)', string) return int(match.group(1), 0x10) else: return int(string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_parentof(self, node, scope, ctxt, stream): """Handle the parentof unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """
# if someone does something like parentof(this).blah, # we'll end up with a StructRef instead of an ID ref # for node.expr, but we'll also end up with a structref # if the user does parentof(a.b.c)... # # TODO how to differentiate between the two?? # # the proper way would be to do (parentof(a.b.c)).a or # (parentof a.b.c).a field = self._handle_node(node.expr, scope, ctxt, stream) parent = field._pfp__parent return parent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_exists(self, node, scope, ctxt, stream): """Handle the exists unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """
res = fields.Int() try: self._handle_node(node.expr, scope, ctxt, stream) res._pfp__set_value(1) except AttributeError: res._pfp__set_value(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 _handle_function_exists(self, node, scope, ctxt, stream): """Handle the function_exists unary operator :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """
res = fields.Int() try: func = self._handle_node(node.expr, scope, ctxt, stream) if isinstance(func, functions.BaseFunction): res._pfp__set_value(1) else: res._pfp__set_value(0) except errors.UnresolvedID: res._pfp__set_value(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 _handle_assignment(self, node, scope, ctxt, stream): """Handle assignment nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """
def add_op(x,y): x += y def sub_op(x,y): x -= y def div_op(x,y): x /= y def mod_op(x,y): x %= y def mul_op(x,y): x *= y def xor_op(x,y): x ^= y def and_op(x,y): x &= y def or_op(x,y): x |= y def lshift_op(x,y): x <<= y def rshift_op(x,y): x >>= y def assign_op(x,y): x._pfp__set_value(y) switch = { "+=" : add_op, "-=" : sub_op, "/=" : div_op, "%=" : mod_op, "*=" : mul_op, "^=" : xor_op, "&=" : and_op, "|=" : or_op, "<<=" : lshift_op, ">>=" : rshift_op, "=" : assign_op } self._dlog("handling assignment") field = self._handle_node(node.lvalue, scope, ctxt, stream) self._dlog("field = {}".format(field)) value = self._handle_node(node.rvalue, scope, ctxt, stream) if node.op is None: self._dlog("value = {}".format(value)) field._pfp__set_value(value) else: self._dlog("value {}= {}".format(node.op, value)) if node.op not in switch: raise errors.UnsupportedAssignmentOperator(node.coord, node.op) switch[node.op](field, value)