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 add(self, sid, token): """ Add new sensor to the database Parameters sid : str SensorId token : str """
try: self.dbcur.execute(SQL_SENSOR_INS, (sid, token)) except sqlite3.IntegrityError: # sensor entry exists pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, sid): """ Remove sensor from the database Parameters sid : str SensorID """
self.dbcur.execute(SQL_SENSOR_DEL, (sid,)) self.dbcur.execute(SQL_TMPO_DEL, (sid,))
<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(self, *sids): """ List all tmpo-blocks in the database Parameters sids : list of str SensorID's for which to list blocks Optional, leave empty to get them all Returns ------- list[list[tuple]] """
if sids == (): sids = [sid for (sid,) in self.dbcur.execute(SQL_SENSOR_ALL)] slist = [] for sid in sids: tlist = [] for tmpo in self.dbcur.execute(SQL_TMPO_ALL, (sid,)): tlist.append(tmpo) sid, rid, lvl, bid, ext, ctd, blk = tmpo self._dprintf(DBG_TMPO_WRITE, ctd, sid, rid, lvl, bid, len(blk)) slist.append(tlist) return slist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def series(self, sid, recycle_id=None, head=None, tail=None, datetime=True): """ Create data Series Parameters sid : str recycle_id : optional head : int | pandas.Timestamp, optional Start of the interval default earliest available tail : int | pandas.Timestamp, optional End of the interval default max epoch datetime : bool convert index to datetime default True Returns ------- pandas.Series """
if head is None: head = 0 else: head = self._2epochs(head) if tail is None: tail = EPOCHS_MAX else: tail = self._2epochs(tail) if recycle_id is None: self.dbcur.execute(SQL_TMPO_RID_MAX, (sid,)) recycle_id = self.dbcur.fetchone()[0] tlist = self.list(sid)[0] srlist = [] for _sid, rid, lvl, bid, ext, ctd, blk in tlist: if (recycle_id == rid and head < self._blocktail(lvl, bid) and tail >= bid): srlist.append(self._blk2series(ext, blk, head, tail)) if len(srlist) > 0: ts = pd.concat(srlist) ts.name = sid if datetime is True: ts.index = pd.to_datetime(ts.index, unit="s", utc=True) return ts else: return pd.Series([], name=sid)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataframe(self, sids, head=0, tail=EPOCHS_MAX, datetime=True): """ Create data frame Parameters sids : list[str] head : int | pandas.Timestamp, optional Start of the interval default earliest available tail : int | pandas.Timestamp, optional End of the interval default max epoch datetime : bool convert index to datetime default True Returns ------- pandas.DataFrame """
if head is None: head = 0 else: head = self._2epochs(head) if tail is None: tail = EPOCHS_MAX else: tail = self._2epochs(tail) series = [self.series(sid, head=head, tail=tail, datetime=False) for sid in sids] df = pd.concat(series, axis=1) if datetime is True: df.index = pd.to_datetime(df.index, unit="s", utc=True) return df
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def first_timestamp(self, sid, epoch=False): """ Get the first available timestamp for a sensor Parameters sid : str SensorID epoch : bool default False If True return as epoch If False return as pd.Timestamp Returns ------- pd.Timestamp | int """
first_block = self.dbcur.execute(SQL_TMPO_FIRST, (sid,)).fetchone() if first_block is None: return None timestamp = first_block[2] if not epoch: timestamp = pd.Timestamp.utcfromtimestamp(timestamp) timestamp = timestamp.tz_localize('UTC') return timestamp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def last_timestamp(self, sid, epoch=False): """ Get the theoretical last timestamp for a sensor Parameters sid : str SensorID epoch : bool default False If True return as epoch If False return as pd.Timestamp Returns ------- pd.Timestamp | int """
timestamp, value = self.last_datapoint(sid, epoch) return timestamp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addKwdArgsToSig(sigStr, kwArgsDict): """ Alter the passed function signature string to add the given kewords """
retval = sigStr if len(kwArgsDict) > 0: retval = retval.strip(' ,)') # open up the r.h.s. for more args for k in kwArgsDict: if retval[-1] != '(': retval += ", " retval += str(k)+"="+str(kwArgsDict[k]) retval += ')' retval = retval 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 _gauss_funct(p, fjac=None, x=None, y=None, err=None, weights=None): """ Defines the gaussian function to be used as the model. """
if p[2] != 0.0: Z = (x - p[1]) / p[2] model = p[0] * np.e ** (-Z ** 2 / 2.0) else: model = np.zeros(np.size(x)) status = 0 if weights is not None: if err is not None: print("Warning: Ignoring errors and using weights.\n") return [status, (y - model) * weights] elif err is not None: return [status, (y - model) / err] else: return [status, y - model]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gfit1d(y, x=None, err=None, weights=None, par=None, parinfo=None, maxiter=200, quiet=0): """ Return the gaussian fit as an object. Parameters y: 1D Numpy array The data to be fitted x: 1D Numpy array (optional) The x values of the y array. x and y must have the same shape. err: 1D Numpy array (optional) 1D array with measurement errors, must be the same shape as y weights: 1D Numpy array (optiional) 1D array with weights, must be the same shape as y par: List (optional) Starting values for the parameters to be fitted parinfo: Dictionary of lists (optional) provides additional information for the parameters. For a detailed description see nmpfit.py. Parinfo can be used to limit parameters or keep some of them fixed. maxiter: number Maximum number of iterations to perform Default: 200 quiet: number if set to 1, nmpfit does not print to the screen Default: 0 Examples -------- [10. 15. 1.41421356] """
y = y.astype(np.float) if weights is not None: weights = weights.astype(np.float) if err is not None: err = err.astype(np.float) if x is None and len(y.shape) == 1: x = np.arange(len(y)).astype(np.float) if x.shape != y.shape: print("input arrays X and Y must be of equal shape.\n") return fa = {'x': x, 'y': y, 'err': err, 'weights': weights} if par is not None: p = par else: ysigma = y.std() ind = np.nonzero(y > ysigma)[0] if len(ind) != 0: xind = int(ind.mean()) p2 = x[xind] p1 = y[xind] p3 = 1.0 else: ymax = y.max() ymin = y.min() ymean= y.mean() if (ymax - ymean) > (abs(ymin - ymean)): p1 = ymax else: p1 = ymin ind = (np.nonzero(y == p1))[0] p2 = x.mean() p3 = 1. p = [p1, p2, p3] m = nmpfit.mpfit(_gauss_funct, p,parinfo = parinfo, functkw=fa, maxiter=maxiter, quiet=quiet) if (m.status <= 0): print('error message = ', m.errmsg) return m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, *args, **kwargs): """filter lets django managers use `objects.filter` on a hashable object."""
obj = kwargs.pop(self.object_property_name, None) if obj is not None: kwargs['object_hash'] = self.model._compute_hash(obj) return super().filter(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_model_params(self, defaults, **kwargs): """this method allows django managers use `objects.get_or_create` and `objects.update_or_create` on a hashable object. """
obj = kwargs.pop(self.object_property_name, None) if obj is not None: kwargs['object_hash'] = self.model._compute_hash(obj) lookup, params = super()._extract_model_params(defaults, **kwargs) if obj is not None: params[self.object_property_name] = obj del params['object_hash'] return lookup, params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def persist(self): """a private method that persists an estimator object to the filesystem"""
if self.object_hash: data = dill.dumps(self.object_property) f = ContentFile(data) self.object_file.save(self.object_hash, f, save=False) f.close() self._persisted = True return self._persisted
<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): """a private method that loads an estimator object from the filesystem"""
if self.is_file_persisted: self.object_file.open() temp = dill.loads(self.object_file.read()) self.set_object(temp) self.object_file.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 create_from_file(cls, filename): """Return an Estimator object given the path of the file, relative to the MEDIA_ROOT"""
obj = cls() obj.object_file = filename obj.load() 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 getAppDir(): """ Return our application dir. Create it if it doesn't exist. """
# Be sure the resource dir exists theDir = os.path.expanduser('~/.')+APP_NAME.lower() if not os.path.exists(theDir): try: os.mkdir(theDir) except OSError: print('Could not create "'+theDir+'" to save GUI settings.') theDir = "./"+APP_NAME.lower() return theDir
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getEmbeddedKeyVal(cfgFileName, kwdName, dflt=None): """ Read a config file and pull out the value of a given keyword. """
# Assume this is a ConfigObj file. Use that s/w to quickly read it and # put it in dict format. Assume kwd is at top level (not in a section). # The input may also be a .cfgspc file. # # Only use ConfigObj here as a tool to generate a dict from a file - do # not use the returned object as a ConfigObj per se. As such, we can call # with "simple" format, ie. no cfgspc, no val'n, and "list_values"=False. try: junkObj = configobj.ConfigObj(cfgFileName, list_values=False) except: if kwdName == TASK_NAME_KEY: raise KeyError('Can not parse as a parameter config file: '+ \ '\n\t'+os.path.realpath(cfgFileName)) else: raise KeyError('Unfound key "'+kwdName+'" while parsing: '+ \ '\n\t'+os.path.realpath(cfgFileName)) if kwdName in junkObj: retval = junkObj[kwdName] del junkObj return retval # Not found if dflt is not None: del junkObj return dflt else: if kwdName == TASK_NAME_KEY: raise KeyError('Can not parse as a parameter config file: '+ \ '\n\t'+os.path.realpath(cfgFileName)) else: raise KeyError('Unfound key "'+kwdName+'" while parsing: '+ \ '\n\t'+os.path.realpath(cfgFileName))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCfgFilesInDirForTask(aDir, aTask, recurse=False): """ This is a specialized function which is meant only to keep the same code from needlessly being much repeated throughout this application. This must be kept as fast and as light as possible. This checks a given directory for .cfg files matching a given task. If recurse is True, it will check subdirectories. If aTask is None, it returns all files and ignores aTask. """
if recurse: flist = irafutils.rglob(aDir, '*.cfg') else: flist = glob.glob(aDir+os.sep+'*.cfg') if aTask: retval = [] for f in flist: try: if aTask == getEmbeddedKeyVal(f, TASK_NAME_KEY, ''): retval.append(f) except Exception as e: print('Warning: '+str(e)) return retval else: return flist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getUsrCfgFilesForPyPkg(pkgName): """ See if the user has one of their own local .cfg files for this task, such as might be created automatically during the save of a read-only package, and return their names. """
# Get the python package and it's .cfg file thePkg, theFile = findCfgFileForPkg(pkgName, '.cfg') # See if the user has any of their own local .cfg files for this task tname = getEmbeddedKeyVal(theFile, TASK_NAME_KEY) flist = getCfgFilesInDirForTask(getAppDir(), tname) return flist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkSetReadOnly(fname, raiseOnErr = False): """ See if we have write-privileges to this file. If we do, and we are not supposed to, then fix that case. """
if os.access(fname, os.W_OK): # We can write to this but it is supposed to be read-only. Fix it. # Take away usr-write, leave group and other alone, though it # may be simpler to just force/set it to: r--r--r-- or r-------- irafutils.setWritePrivs(fname, False, ignoreErrors= not raiseOnErr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isHiddenName(astr): """ Return True if this string name denotes a hidden par or section """
if astr is not None and len(astr) > 2 and astr.startswith('_') and \ astr.endswith('_'): 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 syncParamList(self, firstTime, preserve_order=True): """ Set or reset the internal param list from the dict's contents. """
# See the note in setParam about this design. # Get latest par values from dict. Make sure we do not # change the id of the __paramList pointer here. new_list = self._getParamsFromConfigDict(self, initialPass=firstTime) # dumpCfgspcTo=sys.stdout) # Have to add this odd last one for the sake of the GUI (still?) if self._forUseWithEpar: new_list.append(basicpar.IrafParS(['$nargs','s','h','N'])) if len(self.__paramList) > 0 and preserve_order: # Here we have the most up-to-date data from the actual data # model, the ConfigObj dict, and we need to use it to fill in # our param list. BUT, we need to preserve the order our list # has had up until now (by unique parameter name). namesInOrder = [p.fullName() for p in self.__paramList] assert len(namesInOrder) == len(new_list), \ 'Mismatch in num pars, had: '+str(len(namesInOrder))+ \ ', now we have: '+str(len(new_list))+', '+ \ str([p.fullName() for p in new_list]) self.__paramList[:] = [] # clear list, keep same pointer # create a flat dict view of new_list, for ease of use in next step new_list_dict = {} # can do in one step in v2.7 for par in new_list: new_list_dict[par.fullName()] = par # populate for fn in namesInOrder: self.__paramList.append(new_list_dict[fn]) else: # Here we just take the data in whatever order it came. self.__paramList[:] = new_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getDefaultParList(self): """ Return a par list just like ours, but with all default values. """
# The code below (create a new set-to-dflts obj) is correct, but it # adds a tenth of a second to startup. Clicking "Defaults" in the # GUI does not call this. But this can be used to set the order seen. # But first check for rare case of no cfg file name if self.filename is None: # this is a .cfgspc-only kind of object so far self.filename = self.getDefaultSaveFilename(stub=True) return copy.deepcopy(self.__paramList) tmpObj = ConfigObjPars(self.filename, associatedPkg=self.__assocPkg, setAllToDefaults=True, strict=False) return tmpObj.getParList()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, *args, **kw): """ This may be overridden by a subclass. """
if self._runFunc is not None: # remove the two args sent by EditParDialog which we do not use if 'mode' in kw: kw.pop('mode') if '_save' in kw: kw.pop('_save') return self._runFunc(self, *args, **kw) else: raise taskpars.NoExecError('No way to run task "'+self.__taskName+\ '". You must either override the "run" method in your '+ \ 'ConfigObjPars subclass, or you must supply a "run" '+ \ 'function in your package.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def triggerLogicToStr(self): """ Print all the trigger logic to a string and return it. """
try: import json except ImportError: return "Cannot dump triggers/dependencies/executes (need json)" retval = "TRIGGERS:\n"+json.dumps(self._allTriggers, indent=3) retval += "\nDEPENDENCIES:\n"+json.dumps(self._allDepdcs, indent=3) retval += "\nTO EXECUTE:\n"+json.dumps(self._allExecutes, indent=3) retval += "\n" 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 _findAssociatedConfigSpecFile(self, cfgFileName): """ Given a config file, find its associated config-spec file, and return the full pathname of the file. """
# Handle simplest 2 cases first: co-located or local .cfgspc file retval = "."+os.sep+self.__taskName+".cfgspc" if os.path.isfile(retval): return retval retval = os.path.dirname(cfgFileName)+os.sep+self.__taskName+".cfgspc" if os.path.isfile(retval): return retval # Also try the resource dir retval = self.getDefaultSaveFilename()+'spc' # .cfgspc if os.path.isfile(retval): return retval # Now try and see if there is a matching .cfgspc file in/under an # associated package, if one is defined. if self.__assocPkg is not None: x, theFile = findCfgFileForPkg(None, '.cfgspc', pkgObj = self.__assocPkg, taskName = self.__taskName) return theFile # Finally try to import the task name and see if there is a .cfgspc # file in that directory x, theFile = findCfgFileForPkg(self.__taskName, '.cfgspc', taskName = self.__taskName) if os.path.exists(theFile): return theFile # unfound raise NoCfgFileError('Unfound config-spec file for task: "'+ \ self.__taskName+'"')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPosArgs(self): """ Return a list, in order, of any parameters marked with "pos=N" in the .cfgspc file. """
if len(self._posArgs) < 1: return [] # The first item in the tuple is the index, so we now sort by it self._posArgs.sort() # Build a return list retval = [] for idx, scope, name in self._posArgs: theDict, val = findScopedPar(self, scope, name) retval.append(val) 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 dottedQuadToNum(ip): """ Convert decimal dotted quad string to long integer 1 16777218 16908291 16909060 4294967295 Traceback (most recent call last): ValueError: Not a good dotted-quad IP: 255.255.255.256 """
# import here to avoid it when ip_addr values are not used import socket, struct try: return struct.unpack('!L', socket.inet_aton(ip.strip()))[0] except socket.error: raise ValueError('Not a good dotted-quad IP: %s' % ip) 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 numToDottedQuad(num): """ Convert long int to dotted quad string Traceback (most recent call last): ValueError: Not a good numeric IP: -1 '0.0.0.1' '1.0.0.2' '1.2.0.3' '1.2.3.4' '255.255.255.255' Traceback (most recent call last): ValueError: Not a good numeric IP: 4294967296 """
# import here to avoid it when ip_addr values are not used import socket, struct # no need to intercept here, 4294967295 is fine if num > 4294967295 or num < 0: raise ValueError('Not a good numeric IP: %s' % num) try: return socket.inet_ntoa( struct.pack('!L', long(num))) except (socket.error, struct.error, OverflowError): raise ValueError('Not a good numeric IP: %s' % num)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_num_param(names, values, to_float=False): """ Return numbers from inputs or raise VdtParamError. Lets ``None`` pass through. Pass in keyword argument ``to_float=True`` to use float for the conversion rather than int. [0, 1] [0.0, 1.0] Traceback (most recent call last): VdtParamError: passed an incorrect value "a" for parameter "a". """
fun = to_float and float or int out_params = [] for (name, val) in zip(names, values): if val is None: out_params.append(val) elif isinstance(val, number_or_string_types): try: out_params.append(fun(val)) except ValueError: raise VdtParamError(name, val) else: raise VdtParamError(name, val) return out_params
<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_boolean(value): """ Check if the value represents a boolean. 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 Traceback (most recent call last): VdtTypeError: the value "" is of the wrong type. Traceback (most recent call last): VdtTypeError: the value "up" is of the wrong type. """
if isinstance(value, string_types): try: return bool_dict[value.lower()] except KeyError: raise VdtTypeError(value) # we do an equality test rather than an identity test # this ensures Python 2.2 compatibilty # and allows 0 and 1 to represent True and False if value == False: return False elif value == True: return True else: raise VdtTypeError(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_ip_addr(value): """ Check that the supplied value is an Internet Protocol address, v.4, represented by a dotted-quad string, i.e. '1.2.3.4'. '1' '1.2' '1.2.3' '1.2.3.4' '0.0.0.0' '255.255.255.255' Traceback (most recent call last): VdtValueError: the value "255.255.255.256" is unacceptable. Traceback (most recent call last): VdtValueError: the value "1.2.3.4.5" is unacceptable. Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. """
if not isinstance(value, string_types): raise VdtTypeError(value) value = value.strip() try: dottedQuadToNum(value) except ValueError: raise VdtValueError(value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_list(value, min=None, max=None): """ Check that the value is a list of values. You can optionally specify the minimum and maximum number of members. It does no check on list members. [] [] [1, 2] [1, 2] Traceback (most recent call last): VdtValueTooShortError: the value "(1, 2)" is too short. Traceback (most recent call last): VdtValueTooLongError: the value "(1, 2, 3, 4, 5, 6)" is too long. [1, 2, 3, 4] Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. Traceback (most recent call last): VdtTypeError: the value "12" is of the wrong type. """
(min_len, max_len) = _is_num_param(('min', 'max'), (min, max)) if isinstance(value, string_types): raise VdtTypeError(value) try: num_members = len(value) except TypeError: raise VdtTypeError(value) if min_len is not None and num_members < min_len: raise VdtValueTooShortError(value) if max_len is not None and num_members > max_len: raise VdtValueTooLongError(value) return list(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_int_list(value, min=None, max=None): """ Check that the value is a list of integers. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is an integer. [] [] [1, 2] [1, 2] Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. """
return [is_integer(mem) for mem in is_list(value, min, max)]
<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_bool_list(value, min=None, max=None): """ Check that the value is a list of booleans. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is a boolean. [] [] 1 1 Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. """
return [is_boolean(mem) for mem in is_list(value, min, max)]
<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_float_list(value, min=None, max=None): """ Check that the value is a list of floats. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is a float. [] [] [1.0, 2.0] [1.0, 2.0] Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. """
return [is_float(mem) for mem in is_list(value, min, max)]
<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_string_list(value, min=None, max=None): """ Check that the value is a list of strings. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is a string. [] [] ['a', 'b'] Traceback (most recent call last): VdtTypeError: the value "1" is of the wrong type. Traceback (most recent call last): VdtTypeError: the value "hello" is of the wrong type. """
if isinstance(value, string_types): raise VdtTypeError(value) return [is_string(mem) for mem in is_list(value, min, max)]
<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_ip_addr_list(value, min=None, max=None): """ Check that the value is a list of IP addresses. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is an IP address. [] [] ['1.2.3.4', '5.6.7.8'] Traceback (most recent call last): VdtValueError: the value "a" is unacceptable. """
return [is_ip_addr(mem) for mem in is_list(value, min, max)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def force_list(value, min=None, max=None): """ Check that a value is a list, coercing strings into a list with one member. Useful where users forget the trailing comma that turns a single value into a list. You can optionally specify the minimum and maximum number of members. A minumum of greater than one will fail if the user only supplies a string. [] [] ['hello'] """
if not isinstance(value, (list, tuple)): value = [value] return is_list(value, min, max)
<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_mixed_list(value, *args): """ Check that the value is a list. Allow specifying the type of each member. Work on lists of specific lengths. You specify each member as a positional argument specifying type Each type should be one of the following strings : 'integer', 'float', 'ip_addr', 'string', 'boolean' So you can specify a list of two strings, followed by two integers as : mixed_list('string', 'string', 'integer', 'integer') The length of the list must match the number of positional arguments you supply. 1 1 Traceback (most recent call last): VdtTypeError: the value "b" is of the wrong type. Traceback (most recent call last): VdtValueTooShortError: the value "(1, 2.0, '1.2.3.4', 'a')" is too short. Traceback (most recent call last): VdtValueTooLongError: the value "(1, 2.0, '1.2.3.4', 'a', 1, 'b')" is too long. Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. This test requires an elaborate setup, because of a change in error string output from the interpreter between Python 2.2 and 2.3 . 1 """
try: length = len(value) except TypeError: raise VdtTypeError(value) if length < len(args): raise VdtValueTooShortError(value) elif length > len(args): raise VdtValueTooLongError(value) try: return [fun_dict[arg](val) for arg, val in zip(args, value)] except KeyError as e: raise(VdtParamError('mixed_list', e))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_option(value, *options): """ This check matches the value to any of a set of options. 'yoda' Traceback (most recent call last): VdtValueError: the value "jed" is unacceptable. Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. """
if not isinstance(value, string_types): raise VdtTypeError(value) if not value in options: raise VdtValueError(value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unquote(self, val): """Unquote a value if necessary."""
if (len(val) >= 2) and (val[0] in ("'", '"')) and (val[0] == val[-1]): val = val[1:-1] return 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 match_header(cls, header): """A constant value HDU will only be recognized as such if the header contains a valid PIXVALUE and NAXIS == 0. """
pixvalue = header.get('PIXVALUE') naxis = header.get('NAXIS', 0) return (super(_ConstantValueImageBaseHDU, cls).match_header(header) and (isinstance(pixvalue, float) or _is_int(pixvalue)) and naxis == 0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_constant_value_data(self, data): """Verify that the HDU's data is a constant value array."""
arrayval = data.flat[0] if np.all(data == arrayval): return arrayval return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dumps(columns): ''' Serialize ``columns`` to a JSON formatted ``bytes`` object. ''' fp = BytesIO() dump(columns, fp) fp.seek(0) return fp.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def readall(cls, member, size): ''' Parse variable metadata for a XPORT file member. ''' fp = member.library.fp LINE = member.library.LINE n = cls.header_match(fp.read(LINE)) namestrs = [fp.read(size) for i in range(n)] # Each namestr field is 140 bytes long, but the fields are # streamed together and broken in 80-byte pieces. If the last # byte of the last namestr field does not fall in the last byte # of the 80-byte record, the record is padded with ASCII blanks # to 80 bytes. remainder = n * size % LINE if remainder: padding = 80 - remainder fp.read(padding) info = [cls.unpack(s) for s in namestrs] for d in info: d['format'] = Format(**d['format']) d['iformat'] = InputFormat(**d['iformat']) return [Variable(**d) for d in 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 to_jd(year, month, day): '''Determine Julian day count from Islamic date''' return (day + ceil(29.5 * (month - 1)) + (year - 1) * 354 + trunc((3 + (11 * year)) / 30) + EPOCH) - 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 from_jd(jd): '''Calculate Islamic date from Julian day''' jd = trunc(jd) + 0.5 year = trunc(((30 * (jd - EPOCH)) + 10646) / 10631) month = min(12, ceil((jd - (29 + to_jd(year, 1, 1))) / 29.5) + 1) day = int(jd - to_jd(year, month, 1)) + 1 return (year, month, day)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def freshenFocus(self): """ Did something which requires a new look. Move scrollbar up. This often needs to be delayed a bit however, to let other events in the queue through first. """
self.top.update_idletasks() self.top.after(10, self.setViewAtTop)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mwl(self, event): """Mouse Wheel - under tkinter we seem to need Tk v8.5+ for this """
if event.num == 4: # up on Linux self.top.f.canvas.yview_scroll(-1*self._tmwm, 'units') elif event.num == 5: # down on Linux self.top.f.canvas.yview_scroll(1*self._tmwm, 'units') else: # assume event.delta has the direction, but reversed sign self.top.f.canvas.yview_scroll(-(event.delta)*self._tmwm, 'units')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def focusNext(self, event): """Set focus to next item in sequence"""
try: event.widget.tk_focusNext().focus_set() except TypeError: # see tkinter equivalent code for tk_focusNext to see # commented original version name = event.widget.tk.call('tk_focusNext', event.widget._w) event.widget._nametowidget(str(name)).focus_set()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def focusPrev(self, event): """Set focus to previous item in sequence"""
try: event.widget.tk_focusPrev().focus_set() except TypeError: # see tkinter equivalent code for tk_focusPrev to see # commented original version name = event.widget.tk.call('tk_focusPrev', event.widget._w) event.widget._nametowidget(str(name)).focus_set()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doScroll(self, event): """Scroll the panel down to ensure widget with focus to be visible Tracks the last widget that doScroll was called for and ignores repeated calls. That handles the case where the focus moves not between parameter entries but to someplace outside the hierarchy. In that case the scrolling is not expected. Returns false if the scroll is ignored, else true. """
canvas = self.top.f.canvas widgetWithFocus = event.widget if widgetWithFocus is self.lastFocusWidget: return FALSE self.lastFocusWidget = widgetWithFocus if widgetWithFocus is None: return TRUE # determine distance of widget from top & bottom edges of canvas y1 = widgetWithFocus.winfo_rooty() y2 = y1 + widgetWithFocus.winfo_height() cy1 = canvas.winfo_rooty() cy2 = cy1 + canvas.winfo_height() yinc = self.yscrollincrement if y1<cy1: # this will continue to work when integer division goes away sdist = int((y1-cy1-yinc+1.)/yinc) canvas.yview_scroll(sdist, "units") elif cy2<y2: sdist = int((y2-cy2+yinc-1.)/yinc) canvas.yview_scroll(sdist, "units") 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 _handleParListMismatch(self, probStr, extra=False): """ Handle the situation where two par lists do not match. This is meant to allow subclasses to override. Note that this only handles "missing" pars and "extra" pars, not wrong-type pars. """
errmsg = 'ERROR: mismatch between default and current par lists ' + \ 'for task "'+self.taskName+'"' if probStr: errmsg += '\n\t'+probStr errmsg += '\n(try: "unlearn '+self.taskName+'")' print(errmsg) 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 _setupDefaultParamList(self): """ This creates self.defaultParamList. It also does some checks on the paramList, sets its order if needed, and deletes any extra or unknown pars if found. We assume the order of self.defaultParamList is the correct order. """
# Obtain the default parameter list self.defaultParamList = self._taskParsObj.getDefaultParList() theParamList = self._taskParsObj.getParList() # Lengths are probably equal but this isn't necessarily an error # here, so we check for differences below. if len(self.defaultParamList) != len(theParamList): # whoa, lengths don't match (could be some missing or some extra) pmsg = 'Current list not same length as default list' if not self._handleParListMismatch(pmsg): return False # convert current par values to a dict of { par-fullname:par-object } # for use below ourpardict = {} for par in theParamList: ourpardict[par.fullName()] = par # Sort our paramList according to the order of the defaultParamList # and repopulate the list according to that order. Create sortednames. sortednames = [p.fullName() for p in self.defaultParamList] # Rebuild par list sorted into correct order. Also find/flag any # missing pars or any extra/unknown pars. This automatically deletes # "extras" by not adding them to the sorted list in the first place. migrated = [] newList = [] for fullName in sortednames: if fullName in ourpardict: newList.append(ourpardict[fullName]) migrated.append(fullName) # make sure all get moved over else: # this is a missing par - insert the default version theDfltVer = \ [p for p in self.defaultParamList if p.fullName()==fullName] newList.append(copy.deepcopy(theDfltVer[0])) # Update! Next line writes to the self._taskParsObj.getParList() obj theParamList[:] = newList # fill with newList, keep same mem pointer # See if any got left out extras = [fn for fn in ourpardict if not fn in migrated] for fullName in extras: # this is an extra/unknown par - let subclass handle it if not self._handleParListMismatch('Unexpected par: "'+\ fullName+'"', extra=True): return False print('Ignoring unexpected par: "'+p+'"') # return value indicates that all is well to continue 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 saveAs(self, event=None): """ Save the parameter settings to a user-specified file. Any changes here must be coordinated with the corresponding tpar save_as function. """
self.debug('Clicked Save as...') # On Linux Pers..Dlg causes the cwd to change, so get a copy of current curdir = os.getcwd() # The user wishes to save to a different name writeProtChoice = self._writeProtectOnSaveAs if capable.OF_TKFD_IN_EPAR: # Prompt using native looking dialog fname = asksaveasfilename(parent=self.top, title='Save Parameter File As', defaultextension=self._defSaveAsExt, initialdir=os.path.dirname(self._getSaveAsFilter())) else: # Prompt. (could use tkinter's FileDialog, but this one is prettier) # initWProtState is only used in the 1st call of a session from . import filedlg fd = filedlg.PersistSaveFileDialog(self.top, "Save Parameter File As", self._getSaveAsFilter(), initWProtState=writeProtChoice) if fd.Show() != 1: fd.DialogCleanup() os.chdir(curdir) # in case file dlg moved us return fname = fd.GetFileName() writeProtChoice = fd.GetWriteProtectChoice() fd.DialogCleanup() if not fname: return # canceled # First check the child parameters, aborting save if # invalid entries were encountered if self.checkSetSaveChildren(): os.chdir(curdir) # in case file dlg moved us return # Run any subclass-specific steps right before the save self._saveAsPreSave_Hook(fname) # Verify all the entries (without save), keeping track of the invalid # entries which have been reset to their original input values self.badEntriesList = self.checkSetSaveEntries(doSave=False) # If there were invalid entries, prepare the message dialog if self.badEntriesList: ansOKCANCEL = self.processBadEntries(self.badEntriesList, self.taskName) if not ansOKCANCEL: os.chdir(curdir) # in case file dlg moved us return # If there were no invalid entries or the user says OK, finally # save to their stated file. Since we have already processed the # bad entries, there should be none returned. mstr = "TASKMETA: task="+self.taskName+" package="+self.pkgName if self.checkSetSaveEntries(doSave=True, filename=fname, comment=mstr, set_ro=writeProtChoice, overwriteRO=True): os.chdir(curdir) # in case file dlg moved us raise Exception("Unexpected bad entries for: "+self.taskName) # Run any subclass-specific steps right after the save self._saveAsPostSave_Hook(fname) os.chdir(curdir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def htmlHelp(self, helpString=None, title=None, istask=False, tag=None): """ Pop up the help in a browser window. By default, this tries to show the help for the current task. With the option arguments, it can be used to show any help string. """
# Check the help string. If it turns out to be a URL, launch that, # if not, dump it to a quick and dirty tmp html file to make it # presentable, and pass that file name as the URL. if not helpString: helpString = self.getHelpString(self.pkgName+'.'+self.taskName) if not title: title = self.taskName lwr = helpString.lower() if lwr.startswith("http:") or lwr.startswith("https:") or \ lwr.startswith("file:"): url = helpString if tag and url.find('#') < 0: url += '#'+tag # print('LAUNCHING: '+url) # DBG irafutils.launchBrowser(url, subj=title) else: # Write it to a temp HTML file to display (fd, fname) = tempfile.mkstemp(suffix='.html', prefix='editpar_') os.close(fd) f = open(fname, 'w') if istask and self._knowTaskHelpIsHtml: f.write(helpString) else: f.write('<html><head><title>'+title+'</title></head>\n') f.write('<body><h3>'+title+'</h3>\n') f.write('<pre>\n'+helpString+'\n</pre></body></html>') f.close() irafutils.launchBrowser("file://"+fname, subj=title)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getValue(self, name, scope=None, native=False): """ Return current par value from the GUI. This does not do any validation, and it it not necessarily the same value saved in the model, which is always behind the GUI setting, in time. This is NOT to be used to get all the values - it would not be efficient. """
# Get model data, the list of pars theParamList = self._taskParsObj.getParList() # NOTE: If par scope is given, it will be used, otherwise it is # assumed to be unneeded and the first name-match is returned. fullName = basicpar.makeFullName(scope, name) # Loop over the parameters to find the requested par for i in range(self.numParams): par = theParamList[i] # IrafPar or subclass entry = self.entryNo[i] # EparOption or subclass if par.fullName() == fullName or \ (scope is None and par.name == name): if native: return entry.convertToNative(entry.choice.get()) else: return entry.choice.get() # We didn't find the requested par raise RuntimeError('Could not find par: "'+fullName+'"')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pushMessages(self): """ Internal callback used to make sure the msg list keeps moving. """
# This continues to get itself called until no msgs are left in list. self.showStatus('') if len(self._statusMsgsToShow) > 0: self.top.after(200, self._pushMessages)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def teal(theTask, parent=None, loadOnly=False, returnAs="dict", canExecute=True, strict=False, errorsToTerm=False, autoClose=True, defaults=False): # overrides=None): """ Start the GUI session, or simply load a task's ConfigObj. """
if loadOnly: # this forces returnAs="dict" obj = None try: obj = cfgpars.getObjectFromTaskArg(theTask, strict, defaults) # obj.strictUpdate(overrides) # ! would need to re-verify after this ! except Exception as re: # catches RuntimeError and KeyError and ... # Since we are loadOnly, don't pop up the GUI for this if strict: raise else: print(re.message.replace('\n\n','\n')) return obj else: assert returnAs in ("dict", "status", None), \ "Invalid value for returnAs arg: "+str(returnAs) dlg = None try: # if setting to all defaults, go ahead and load it here, pre-GUI if defaults: theTask = cfgpars.getObjectFromTaskArg(theTask, strict, True) # now create/run the dialog dlg = ConfigObjEparDialog(theTask, parent=parent, autoClose=autoClose, strict=strict, canExecute=canExecute) # overrides=overrides) except cfgpars.NoCfgFileError as ncf: log_last_error() if errorsToTerm: print(str(ncf).replace('\n\n','\n')) else: popUpErr(parent=parent,message=str(ncf),title="Unfound Task") except Exception as re: # catches RuntimeError and KeyError and ... log_last_error() if errorsToTerm: print(re.message.replace('\n\n','\n')) else: popUpErr(parent=parent, message=re.message, title="Bad Parameters") # Return, depending on the mode in which we are operating if returnAs is None: return if returnAs == "dict": if dlg is None or dlg.canceled(): return None else: return dlg.getTaskParsObj() # else, returnAs == "status" if dlg is None or dlg.canceled(): return -1 if dlg.executed(): return 1 return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(theTask, canExecute=True, strict=True, defaults=False): """ Shortcut to load TEAL .cfg files for non-GUI access where loadOnly=True. """
return teal(theTask, parent=None, loadOnly=True, returnAs="dict", canExecute=canExecute, strict=strict, errorsToTerm=True, defaults=defaults)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cfgGetBool(theObj, name, dflt): """ Get a stringified val from a ConfigObj obj and return it as bool """
strval = theObj.get(name, None) if strval is None: return dflt return strval.lower().strip() == '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 _overrideMasterSettings(self): """ Override so that we can run in a different mode. """
# config-obj dict of defaults cod = self._getGuiSettings() # our own GUI setup self._appName = APP_NAME self._appHelpString = tealHelpString self._useSimpleAutoClose = self._do_usac self._showExtraHelpButton = False self._saveAndCloseOnExec = cfgGetBool(cod, 'saveAndCloseOnExec', True) self._showHelpInBrowser = cfgGetBool(cod, 'showHelpInBrowser', False) self._writeProtectOnSaveAs = cfgGetBool(cod, 'writeProtectOnSaveAsOpt', True) self._flagNonDefaultVals = cfgGetBool(cod, 'flagNonDefaultVals', None) self._optFile = APP_NAME.lower()+".optionDB" # our own colors # prmdrss teal: #00ffaa, pure cyan (teal) #00ffff (darker) #008080 # "#aaaaee" is a darker but good blue, but "#bbbbff" pops ltblu = "#ccccff" # light blue drktl = "#008888" # darkish teal self._frmeColor = cod.get('frameColor', drktl) self._taskColor = cod.get('taskBoxColor', ltblu) self._bboxColor = cod.get('buttonBoxColor', ltblu) self._entsColor = cod.get('entriesColor', ltblu) self._flagColor = cod.get('flaggedColor', 'brown') # double check _canExecute, but only if it is still set to the default if self._canExecute and self._taskParsObj: # default _canExecute=True self._canExecute = self._taskParsObj.canExecute() self._showExecuteButton = self._canExecute # check on the help string - just to see if it is HTML # (could use HTMLParser here if need be, be quick and simple tho) hhh = self.getHelpString(self.pkgName+'.'+self.taskName) if hhh: hhh = hhh.lower() if hhh.find('<html') >= 0 or hhh.find('</html>') > 0: self._knowTaskHelpIsHtml = True elif hhh.startswith('http:') or hhh.startswith('https:'): self._knowTaskHelpIsHtml = True elif hhh.startswith('file:') and \ (hhh.endswith('.htm') or hhh.endswith('.html')): self._knowTaskHelpIsHtml = 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 _doActualSave(self, fname, comment, set_ro=False, overwriteRO=False): """ Override this so we can handle case of file not writable, as well as to make our _lastSavedState copy. """
self.debug('Saving, file name given: '+str(fname)+', set_ro: '+\ str(set_ro)+', overwriteRO: '+str(overwriteRO)) cantWrite = False inInstArea = False if fname in (None, ''): fname = self._taskParsObj.getFilename() # now do some final checks then save try: if _isInstalled(fname): # check: may be installed but not read-only inInstArea = cantWrite = True else: # in case of save-as, allow overwrite of read-only file if overwriteRO and os.path.exists(fname): setWritePrivs(fname, True, True) # try make writable # do the save rv=self._taskParsObj.saveParList(filename=fname,comment=comment) except IOError: cantWrite = True # User does not have privs to write to this file. Get name of local # choice and try to use that. if cantWrite: fname = self._taskParsObj.getDefaultSaveFilename() # Tell them the context is changing, and where we are saving msg = 'Read-only config file for task "' if inInstArea: msg = 'Installed config file for task "' msg += self._taskParsObj.getName()+'" is not to be overwritten.'+\ ' Values will be saved to: \n\n\t"'+fname+'".' showwarning(message=msg, title="Will not overwrite!") # Try saving to their local copy rv=self._taskParsObj.saveParList(filename=fname, comment=comment) # Treat like a save-as (update title for ALL save ops) self._saveAsPostSave_Hook(fname) # Limit write privs if requested (only if not in the rc dir) if set_ro and os.path.dirname(os.path.abspath(fname)) != \ os.path.abspath(self._rcDir): cfgpars.checkSetReadOnly(fname) # Before returning, make a copy so we know what was last saved. # The dict() method returns a deep-copy dict of the keyvals. self._lastSavedState = self._taskParsObj.dict() return rv
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _defineEditedCallbackObjectFor(self, parScope, parName): """ Override to allow us to use an edited callback. """
# We know that the _taskParsObj is a ConfigObjPars triggerStrs = self._taskParsObj.getTriggerStrings(parScope, parName) # Some items will have a trigger, but likely most won't if triggerStrs and len(triggerStrs) > 0: return self else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateTitle(self, atitle): """ Override so we can append read-only status. """
if atitle and os.path.exists(atitle): if _isInstalled(atitle): atitle += ' [installed]' elif not os.access(atitle, os.W_OK): atitle += ' [read only]' super(ConfigObjEparDialog, self).updateTitle(atitle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edited(self, scope, name, lastSavedVal, newVal, action): """ This is the callback function invoked when an item is edited. This is only called for those items which were previously specified to use this mechanism. We do not turn this on for all items because the performance might be prohibitive. This kicks off any previously registered triggers. """
# Get name(s) of any triggers that this par triggers triggerNamesTup = self._taskParsObj.getTriggerStrings(scope, name) assert triggerNamesTup is not None and len(triggerNamesTup) > 0, \ 'Empty trigger name for: "'+name+'", consult the .cfgspc file.' # Loop through all trigger names - each one is a trigger to kick off - # in the order that they appear in the tuple we got. Most cases will # probably only have a single trigger in the tuple. for triggerName in triggerNamesTup: # First handle the known/canned trigger names # print (scope, name, newVal, action, triggerName) # DBG: debug line # _section_switch_ if triggerName == '_section_switch_': # Try to uniformly handle all possible par types here, not # just boolean (e.g. str, int, float, etc.) # Also, see logic in _BooleanMixin._coerceOneValue() state = newVal not in self.FALSEVALS self._toggleSectionActiveState(scope, state, (name,)) continue # _2_section_switch_ (see notes above in _section_switch_) if triggerName == '_2_section_switch_': state = newVal not in self.FALSEVALS # toggle most of 1st section (as usual) and ALL of next section self._toggleSectionActiveState(scope, state, (name,)) # get first par of next section (fpons) - is a tuple fpons = self.findNextSection(scope, name) nextSectScope = fpons[0] if nextSectScope: self._toggleSectionActiveState(nextSectScope, state, None) continue # Now handle rules with embedded code (eg. triggerName=='_rule1_') if '_RULES_' in self._taskParsObj and \ triggerName in self._taskParsObj['_RULES_'].configspec: # Get codeStr to execute it, but before we do so, check 'when' - # make sure this is an action that is allowed to cause a trigger ruleSig = self._taskParsObj['_RULES_'].configspec[triggerName] chkArgsDict = vtor_checks.sigStrToKwArgsDict(ruleSig) codeStr = chkArgsDict.get('code') # or None if didn't specify when2run = chkArgsDict.get('when') # or None if didn't specify greenlight = False # do we have a green light to eval the rule? if when2run is None: greenlight = True # means run rule for any possible action else: # 'when' was set to something so we need to check action # check value of action (poor man's enum) assert action in editpar.GROUP_ACTIONS, \ "Unknown action: "+str(action)+', expected one of: '+ \ str(editpar.GROUP_ACTIONS) # check value of 'when' (allow them to use comma-sep'd str) # (readers be aware that values must be those possible for # 'action', and 'always' is also allowed) whenlist = when2run.split(',') # warn for invalid values for w in whenlist: if not w in editpar.GROUP_ACTIONS and w != 'always': print('WARNING: skipping bad value for when kwd: "'+\ w+'" in trigger/rule: '+triggerName) # finally, do the correlation greenlight = 'always' in whenlist or action in whenlist # SECURITY NOTE: because this part executes arbitrary code, that # code string must always be found only in the configspec file, # which is intended to only ever be root-installed w/ the pkg. if codeStr: if not greenlight: continue # not an error, just skip this one self.showStatus("Evaluating "+triggerName+' ...') #dont keep self.top.update_idletasks() #allow msg to draw prior to exec # execute it and retrieve the outcome try: outval = execEmbCode(scope, name, newVal, self, codeStr) except Exception as ex: outval = 'ERROR in '+triggerName+': '+str(ex) print(outval) msg = outval+':\n'+('-'*99)+'\n'+traceback.format_exc() msg += 'CODE: '+codeStr+'\n'+'-'*99+'\n' self.debug(msg) self.showStatus(outval, keep=1) # Leave this debug line in until it annoys someone msg = 'Value of "'+name+'" triggered "'+triggerName+'"' stroutval = str(outval) if len(stroutval) < 30: msg += ' --> "'+stroutval+'"' self.showStatus(msg, keep=0) # Now that we have triggerName evaluated to outval, we need # to look through all the parameters and see if there are # any items to be affected by triggerName (e.g. '_rule1_') self._applyTriggerValue(triggerName, outval) continue # If we get here, we have an unknown/unusable trigger raise RuntimeError('Unknown trigger for: "'+name+'", named: "'+ \ str(triggerName)+'". Please consult the .cfgspc 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 _setTaskParsObj(self, theTask): """ Overridden version for ConfigObj. theTask can be either a .cfg file name or a ConfigObjPars object. """
# Create the ConfigObjPars obj self._taskParsObj = cfgpars.getObjectFromTaskArg(theTask, self._strict, False) # Tell it that we can be used for catching debug lines self._taskParsObj.setDebugLogger(self) # Immediately make a copy of it's un-tampered internal dict. # The dict() method returns a deep-copy dict of the keyvals. self._lastSavedState = self._taskParsObj.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 _getSaveAsFilter(self): """ Return a string to be used as the filter arg to the save file dialog during Save-As. """
# figure the dir to use, start with the one from the file absRcDir = os.path.abspath(self._rcDir) thedir = os.path.abspath(os.path.dirname(self._taskParsObj.filename)) # skip if not writeable, or if is _rcDir if thedir == absRcDir or not os.access(thedir, os.W_OK): thedir = os.path.abspath(os.path.curdir) # create save-as filter string filt = thedir+'/*.cfg' envVarName = APP_NAME.upper()+'_CFG' if envVarName in os.environ: upx = os.environ[envVarName] if len(upx) > 0: filt = upx+"/*.cfg" # done return filt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getOpenChoices(self): """ Go through all possible sites to find applicable .cfg files. Return as an iterable. """
tsk = self._taskParsObj.getName() taskFiles = set() dirsSoFar = [] # this helps speed this up (skip unneeded globs) # last dir aDir = os.path.dirname(self._taskParsObj.filename) if len(aDir) < 1: aDir = os.curdir dirsSoFar.append(aDir) taskFiles.update(cfgpars.getCfgFilesInDirForTask(aDir, tsk)) # current dir aDir = os.getcwd() if aDir not in dirsSoFar: dirsSoFar.append(aDir) taskFiles.update(cfgpars.getCfgFilesInDirForTask(aDir, tsk)) # task's python pkg dir (if tsk == python pkg name) try: x, pkgf = cfgpars.findCfgFileForPkg(tsk, '.cfg', taskName=tsk, pkgObj=self._taskParsObj.getAssocPkg()) taskFiles.update( (pkgf,) ) except cfgpars.NoCfgFileError: pass # no big deal - maybe there is no python package # user's own resourceDir aDir = self._rcDir if aDir not in dirsSoFar: dirsSoFar.append(aDir) taskFiles.update(cfgpars.getCfgFilesInDirForTask(aDir, tsk)) # extra loc - see if they used the app's env. var aDir = dirsSoFar[0] # flag to skip this if no env var found envVarName = APP_NAME.upper()+'_CFG' if envVarName in os.environ: aDir = os.environ[envVarName] if aDir not in dirsSoFar: dirsSoFar.append(aDir) taskFiles.update(cfgpars.getCfgFilesInDirForTask(aDir, tsk)) # At the very end, add an option which we will later interpret to mean # to open the file dialog. taskFiles = list(taskFiles) # so as to keep next item at end of seq taskFiles.sort() taskFiles.append("Other ...") return taskFiles
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pfopen(self, event=None): """ Load the parameter settings from a user-specified file. """
# Get the selected file name fname = self._openMenuChoice.get() # Also allow them to simply find any file - do not check _task_name_... # (could use tkinter's FileDialog, but this one is prettier) if fname[-3:] == '...': if capable.OF_TKFD_IN_EPAR: fname = askopenfilename(title="Load Config File", parent=self.top) else: from . import filedlg fd = filedlg.PersistLoadFileDialog(self.top, "Load Config File", self._getSaveAsFilter()) if fd.Show() != 1: fd.DialogCleanup() return fname = fd.GetFileName() fd.DialogCleanup() if not fname: return # canceled self.debug('Loading from: '+fname) # load it into a tmp object (use associatedPkg if we have one) try: tmpObj = cfgpars.ConfigObjPars(fname, associatedPkg=\ self._taskParsObj.getAssocPkg(), strict=self._strict) except Exception as ex: showerror(message=ex.message, title='Error in '+os.path.basename(fname)) self.debug('Error in '+os.path.basename(fname)) self.debug(traceback.format_exc()) return # check it to make sure it is a match if not self._taskParsObj.isSameTaskAs(tmpObj): msg = 'The current task is "'+self._taskParsObj.getName()+ \ '", but the selected file is for task "'+ \ str(tmpObj.getName())+'". This file was not loaded.' showerror(message=msg, title="Error in "+os.path.basename(fname)) self.debug(msg) self.debug(traceback.format_exc()) return # Set the GUI entries to these values (let the user Save after) newParList = tmpObj.getParList() try: self.setAllEntriesFromParList(newParList, updateModel=True) # go ahead and updateModel, even though it will take longer, # we need it updated for the copy of the dict we make below except editpar.UnfoundParamError as pe: showwarning(message=str(pe), title="Error in "+os.path.basename(fname)) # trip any triggers self.checkAllTriggers('fopen') # This new fname is our current context self.updateTitle(fname) self._taskParsObj.filename = fname # !! maybe try setCurrentContext() ? self.freshenFocus() self.showStatus("Loaded values from: "+fname, keep=2) # Since we are in a new context (and have made no changes yet), make # a copy so we know what the last state was. # The dict() method returns a deep-copy dict of the keyvals. self._lastSavedState = self._taskParsObj.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 _handleParListMismatch(self, probStr, extra=False): """ Override to include ConfigObj filename and specific errors. Note that this only handles "missing" pars and "extra" pars, not wrong-type pars. So it isn't that big of a deal. """
# keep down the duplicate errors if extra: return True # the base class is already stating it will be ignored # find the actual errors, and then add that to the generic message errmsg = 'Warning: ' if self._strict: errmsg = 'ERROR: ' errmsg = errmsg+'mismatch between default and current par lists ' + \ 'for task "'+self.taskName+'".' if probStr: errmsg += '\n\t'+probStr errmsg += '\nTry editing/deleting: "' + \ self._taskParsObj.filename+'" (or, if in PyRAF: "unlearn ' + \ self.taskName+'").' print(errmsg) 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 _setToDefaults(self): """ Load the default parameter settings into the GUI. """
# Create an empty object, where every item is set to it's default value try: tmpObj = cfgpars.ConfigObjPars(self._taskParsObj.filename, associatedPkg=\ self._taskParsObj.getAssocPkg(), setAllToDefaults=self.taskName, strict=False) except Exception as ex: msg = "Error Determining Defaults" showerror(message=msg+'\n\n'+ex.message, title="Error Determining Defaults") return # Set the GUI entries to these values (let the user Save after) tmpObj.filename = self._taskParsObj.filename = '' # name it later newParList = tmpObj.getParList() try: self.setAllEntriesFromParList(newParList) # needn't updateModel yet self.checkAllTriggers('defaults') self.updateTitle('') self.showStatus("Loaded default "+self.taskName+" values via: "+ \ os.path.basename(tmpObj._original_configspec), keep=1) except editpar.UnfoundParamError as pe: showerror(message=str(pe), title="Error Setting to Default 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 getDict(self): """ Retrieve the current parameter settings from the GUI."""
# We are going to have to return the dict so let's # first make sure all of our models are up to date with the values in # the GUI right now. badList = self.checkSetSaveEntries(doSave=False) if badList: self.processBadEntries(badList, self.taskName, canCancel=False) return self._taskParsObj.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 loadDict(self, theDict): """ Load the parameter settings from a given dict into the GUI. """
# We are going to have to merge this info into ourselves so let's # first make sure all of our models are up to date with the values in # the GUI right now. badList = self.checkSetSaveEntries(doSave=False) if badList: if not self.processBadEntries(badList, self.taskName): return # now, self._taskParsObj is up-to-date # So now we update _taskParsObj with the input dict cfgpars.mergeConfigObj(self._taskParsObj, theDict) # now sync the _taskParsObj dict with its par list model # '\n'.join([str(jj) for jj in self._taskParsObj.getParList()]) self._taskParsObj.syncParamList(False) # Set the GUI entries to these values (let the user Save after) try: self.setAllEntriesFromParList(self._taskParsObj.getParList(), updateModel=True) self.checkAllTriggers('fopen') self.freshenFocus() self.showStatus('Loaded '+str(len(theDict))+ \ ' user par values for: '+self.taskName, keep=1) except Exception as ex: showerror(message=ex.message, title="Error Setting to Loaded 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 _applyTriggerValue(self, triggerName, outval): """ Here we look through the entire .cfgspc to see if any parameters are affected by this trigger. For those that are, we apply the action to the GUI widget. The action is specified by depType. """
# First find which items are dependent upon this trigger (cached) # e.g. { scope1.name1 : dep'cy-type, scope2.name2 : dep'cy-type, ... } depParsDict = self._taskParsObj.getParsWhoDependOn(triggerName) if not depParsDict: return if 0: print("Dependent parameters:\n"+str(depParsDict)+"\n") # Get model data, the list of pars theParamList = self._taskParsObj.getParList() # Then go through the dependent pars and apply the trigger to them settingMsg = '' for absName in depParsDict: used = False # For each dep par, loop to find the widget for that scope.name for i in range(self.numParams): scopedName = theParamList[i].scope+'.'+theParamList[i].name # diff from makeFullName!! if absName == scopedName: # a match was found depType = depParsDict[absName] if depType == 'active_if': self.entryNo[i].setActiveState(outval) elif depType == 'inactive_if': self.entryNo[i].setActiveState(not outval) elif depType == 'is_set_by': self.entryNo[i].forceValue(outval, noteEdited=True) # WARNING! noteEdited=True may start recursion! if len(settingMsg) > 0: settingMsg += ", " settingMsg += '"'+theParamList[i].name+'" to "'+\ outval+'"' elif depType in ('set_yes_if', 'set_no_if'): if bool(outval): newval = 'yes' if depType == 'set_no_if': newval = 'no' self.entryNo[i].forceValue(newval, noteEdited=True) # WARNING! noteEdited=True may start recursion! if len(settingMsg) > 0: settingMsg += ", " settingMsg += '"'+theParamList[i].name+'" to "'+\ newval+'"' else: if len(settingMsg) > 0: settingMsg += ", " settingMsg += '"'+theParamList[i].name+\ '" (no change)' elif depType == 'is_disabled_by': # this one is only used with boolean types on = self.entryNo[i].convertToNative(outval) if on: # do not activate whole section or change # any values, only activate this one self.entryNo[i].setActiveState(True) else: # for off, set the bool par AND grey WHOLE section self.entryNo[i].forceValue(outval, noteEdited=True) self.entryNo[i].setActiveState(False) # we'd need this if the par had no _section_switch_ # self._toggleSectionActiveState( # theParamList[i].scope, False, None) if len(settingMsg) > 0: settingMsg += ", " settingMsg += '"'+theParamList[i].name+'" to "'+\ outval+'"' else: raise RuntimeError('Unknown dependency: "'+depType+ \ '" for par: "'+scopedName+'"') used = True break # Or maybe it is a whole section if absName.endswith('._section_'): scope = absName[:-10] depType = depParsDict[absName] if depType == 'active_if': self._toggleSectionActiveState(scope, outval, None) elif depType == 'inactive_if': self._toggleSectionActiveState(scope, not outval, None) used = True # Help to debug the .cfgspc rules if not used: raise RuntimeError('UNUSED "'+triggerName+'" dependency: '+ \ str({absName:depParsDict[absName]})) if len(settingMsg) > 0: # why ?! self.freshenFocus() self.showStatus('Automatically set '+settingMsg, keep=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 readShiftFile(self, filename): """ Reads a shift file from disk and populates a dictionary. """
order = [] fshift = open(filename,'r') flines = fshift.readlines() fshift.close() common = [f.strip('#').strip() for f in flines if f.startswith('#')] c=[line.split(': ') for line in common] # Remove any line comments in the shift file - lines starting with '#' # but not part of the common block. for l in c: if l[0] not in ['frame', 'refimage', 'form', 'units']: c.remove(l) for line in c: line[1]=line[1].strip() self.update(c) files = [f.strip().split(' ',1) for f in flines if not (f.startswith('#') or f.strip() == '')] for f in files: order.append(f[0]) self['order'] = order for f in files: # Check to see if filename provided is a full filename that corresponds # to a file on the path. If not, try to convert given rootname into # a valid filename based on available files. This may or may not # define the correct filename, which is why it prints out what it is # doing, so that the user can verify and edit the shiftfile if needed. #NOTE: # Supporting the specification of only rootnames in the shiftfile with this # filename expansion is NOT to be documented, but provided solely as # an undocumented, dangerous and not fully supported helper function for # some backwards compatibility. if not os.path.exists(f[0]): f[0] = fu.buildRootname(f[0]) print('Defining filename in shiftfile as: ', f[0]) f[1] = f[1].split() try: f[1] = [float(s) for s in f[1]] except: msg = 'Cannot read in ', s, ' from shiftfile ', filename, ' as a float number' raise ValueError(msg) msg = "At least 2 and at most 4 shift values should be provided in a shiftfile" if len(f[1]) < 2: raise ValueError(msg) elif len(f[1]) == 3: f[1].append(1.0) elif len(f[1]) == 2: f[1].extend([0.0, 1.0]) elif len(f[1]) > 4: raise ValueError(msg) fdict = dict(files) self.update(fdict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeShiftFile(self, filename="shifts.txt"): """ Writes a shift file object to a file on disk using the convention for shift file format. """
lines = ['# frame: ', self['frame'], '\n', '# refimage: ', self['refimage'], '\n', '# form: ', self['form'], '\n', '# units: ', self['units'], '\n'] for o in self['order']: ss = " " for shift in self[o]: ss += str(shift) + " " line = str(o) + ss + "\n" lines.append(line) fshifts= open(filename, 'w') fshifts.writelines(lines) fshifts.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 weave_instance(instance, aspect, methods=NORMAL_METHODS, lazy=False, bag=BrokenBag, **options): """ Low-level weaver for instances. .. warning:: You should not use this directly. :returns: An :obj:`aspectlib.Rollback` object. """
if bag.has(instance): return Nothing entanglement = Rollback() method_matches = make_method_matcher(methods) logdebug("weave_instance (module=%r, aspect=%s, methods=%s, lazy=%s, **options=%s)", instance, aspect, methods, lazy, options) def fixup(func): return func.__get__(instance, type(instance)) fixed_aspect = aspect + [fixup] if isinstance(aspect, (list, tuple)) else [aspect, fixup] for attr in dir(instance): func = getattr(instance, attr) if method_matches(attr): if ismethod(func): if hasattr(func, '__func__'): realfunc = func.__func__ else: realfunc = func.im_func entanglement.merge( patch_module(instance, attr, _checked_apply(fixed_aspect, realfunc, module=None), **options) ) return entanglement
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def weave_module(module, aspect, methods=NORMAL_METHODS, lazy=False, bag=BrokenBag, **options): """ Low-level weaver for "whole module weaving". .. warning:: You should not use this directly. :returns: An :obj:`aspectlib.Rollback` object. """
if bag.has(module): return Nothing entanglement = Rollback() method_matches = make_method_matcher(methods) logdebug("weave_module (module=%r, aspect=%s, methods=%s, lazy=%s, **options=%s)", module, aspect, methods, lazy, options) for attr in dir(module): func = getattr(module, attr) if method_matches(attr): if isroutine(func): entanglement.merge(patch_module_function(module, func, aspect, force_name=attr, **options)) elif isclass(func): entanglement.merge( weave_class(func, aspect, owner=module, name=attr, methods=methods, lazy=lazy, bag=bag, **options), # it's not consistent with the other ways of weaving a class (it's never weaved as a routine). # therefore it's disabled until it's considered useful. # #patch_module_function(module, getattr(module, attr), aspect, force_name=attr, **options), ) return entanglement
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_module(module, name, replacement, original=UNSPECIFIED, aliases=True, location=None, **_bogus_options): """ Low-level attribute patcher. :param module module: Object to patch. :param str name: Attribute to patch :param replacement: The replacement value. :param original: The original value (in case the object beeing patched uses descriptors or is plain weird). :param bool aliases: If ``True`` patch all the attributes that have the same original value. :returns: An :obj:`aspectlib.Rollback` object. """
rollback = Rollback() seen = False original = getattr(module, name) if original is UNSPECIFIED else original location = module.__name__ if hasattr(module, '__name__') else type(module).__module__ target = module.__name__ if hasattr(module, '__name__') else type(module).__name__ try: replacement.__module__ = location except (TypeError, AttributeError): pass for alias in dir(module): logdebug("alias:%s (%s)", alias, name) if hasattr(module, alias): obj = getattr(module, alias) logdebug("- %s:%s (%s)", obj, original, obj is original) if obj is original: if aliases or alias == name: logdebug("= saving %s on %s.%s ...", replacement, target, alias) setattr(module, alias, replacement) rollback.merge(lambda alias=alias: setattr(module, alias, original)) if alias == name: seen = True elif alias == name: if ismethod(obj): logdebug("= saving %s on %s.%s ...", replacement, target, alias) setattr(module, alias, replacement) rollback.merge(lambda alias=alias: setattr(module, alias, original)) seen = True else: raise AssertionError("%s.%s = %s is not %s." % (module, alias, obj, original)) if not seen: warnings.warn('Setting %s.%s to %s. There was no previous definition, probably patching the wrong module.' % ( target, name, replacement )) logdebug("= saving %s on %s.%s ...", replacement, target, name) setattr(module, name, replacement) rollback.merge(lambda: setattr(module, name, original)) return rollback
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_module_function(module, target, aspect, force_name=None, bag=BrokenBag, **options): """ Low-level patcher for one function from a specified module. .. warning:: You should not use this directly. :returns: An :obj:`aspectlib.Rollback` object. """
logdebug("patch_module_function (module=%s, target=%s, aspect=%s, force_name=%s, **options=%s", module, target, aspect, force_name, options) name = force_name or target.__name__ return patch_module(module, name, _checked_apply(aspect, target, module=module), original=target, **options)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unstuff(packet): """ Remove byte stuffing from a TSIP packet. :param packet: TSIP packet with byte stuffing. The packet must already have been stripped or `ValueError` will be raised. :type packet: Binary string. :return: Packet without byte stuffing. """
if is_framed(packet): raise ValueError('packet contains leading DLE and trailing DLE/ETX') else: return packet.replace(CHR_DLE + CHR_DLE, CHR_DLE)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self): """ Opens the file for subsequent access. """
if self.handle is None: self.handle = fits.open(self.fname, mode='readonly') if self.extn: if len(self.extn) == 1: hdu = self.handle[self.extn[0]] else: hdu = self.handle[self.extn[0],self.extn[1]] else: hdu = self.handle[0] if isinstance(hdu,fits.hdu.compressed.CompImageHDU): self.compress = True return hdu
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reloadCompletedMeasurements(self): """ Reloads the completed measurements from the backing store. """
from pathlib import Path reloaded = [self.load(x.resolve()) for x in Path(self.dataDir).glob('*/*/*') if x.is_dir()] logger.info('Reloaded ' + str(len(reloaded)) + ' completed measurements') self.completeMeasurements = [x for x in reloaded if x is not None and x.status == MeasurementStatus.COMPLETE] self.failedMeasurements = [x for x in reloaded if x is not None and x.status == MeasurementStatus.FAILED]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_exptime(filelist): """ Removes files with EXPTIME==0 from filelist. """
toclose = False removed_files = [] for f in filelist: if isinstance(f, str): f = fits.open(f) toclose = True try: exptime = f[0].header['EXPTIME'] except KeyError: removed_files.append(f) print("Warning: There are files without keyword EXPTIME") continue if exptime <= 0: removed_files.append(f) print("Warning: There are files with zero exposure time: keyword EXPTIME = 0.0") if removed_files != []: print("Warning: Removing the following files from input list") for f in removed_files: print('\t',f.filename() or "") return removed_files
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert2fits(sci_ivm): """ Checks if a file is in WAIVER of GEIS format and converts it to MEF """
removed_files = [] translated_names = [] newivmlist = [] for file in sci_ivm: #find out what the input is # if science file is not found on disk, add it to removed_files for removal try: imgfits,imgtype = fileutil.isFits(file[0]) except IOError: print("Warning: File %s could not be found" %file[0]) print("Warning: Removing file %s from input list" %file[0]) removed_files.append(file[0]) continue # Check for existence of waiver FITS input, and quit if found. # Or should we print a warning and continue but not use that file if imgfits and imgtype == 'waiver': newfilename = waiver2mef(file[0], convert_dq=True) if newfilename is None: print("Removing file %s from input list - could not convert WAIVER format to MEF\n" %file[0]) removed_files.append(file[0]) else: removed_files.append(file[0]) translated_names.append(newfilename) newivmlist.append(file[1]) # If a GEIS image is provided as input, create a new MEF file with # a name generated using 'buildFITSName()' # Convert the corresponding data quality file if present if not imgfits: newfilename = geis2mef(file[0], convert_dq=True) if newfilename is None: print("Removing file %s from input list - could not convert GEIS format to MEF\n" %file[0]) removed_files.append(file[0]) else: removed_files.append(file[0]) translated_names.append(newfilename) newivmlist.append(file[1]) return removed_files, translated_names, newivmlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def journals(self): """ Retrieve journals attribute for this very Issue """
try: target = self._item_path json_data = self._redmine.get(target % str(self.id), parms={'include': 'journals'}) data = self._redmine.unwrap_json(None, json_data) journals = [Journal(redmine=self._redmine, data=journal, type='issue_journal') for journal in data['issue']['journals']] return journals except Exception: 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 save(self, notes=None): '''Save all changes back to Redmine with optional notes.''' # Capture the notes if given if notes: self._changes['notes'] = notes # Call the base-class save function super(Issue, self).save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_status(self, new_status, notes=None): '''Save all changes and set to the given new_status''' self.status_id = new_status try: self.status['id'] = self.status_id # We don't have the id to name mapping, so blank the name self.status['name'] = None except: pass self.save(notes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def resolve(self, notes=None): '''Save all changes and resolve this issue''' self.set_status(self._redmine.ISSUE_STATUS_ID_RESOLVED, notes=notes)
<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, notes=None): '''Save all changes and close this issue''' self.set_status(self._redmine.ISSUE_STATUS_ID_CLOSED, notes=notes)
<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(self, page_name, **dict): ''' Create a new item with the provided dict information at the given page_name. Returns the new item. As of version 2.2 of Redmine, this doesn't seem to function. ''' self._item_new_path = '/projects/%s/wiki/%s.json' % \ (self._project.identifier, page_name) # Call the base class new method return super(Redmine_Wiki_Pages_Manager, self).new(**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 _set_version(self, version): ''' Set up this object based on the capabilities of the known versions of Redmine ''' # Store the version we are evaluating self.version = version or None # To evaluate the version capabilities, # assume the best-case if no version is provided. version_check = version or 9999.0 if version_check < 1.0: raise RedmineError('This library will only work with ' 'Redmine version 1.0 and higher.') ## SECURITY AUGMENTATION # All versions support the key in the request # (http://server/stuff.json?key=blah) # But versions 1.1 and higher can put the key in a header field # for better security. # If no version was provided (0.0) then assume we should # set the key with the request. self.key_in_header = version >= 1.1 # it puts the key in the header or # it gets the hose, but not for 1.0. self.impersonation_supported = version_check >= 2.2 self.has_project_memberships = version_check >= 1.4 self.has_project_versions = version_check >= 1.3 self.has_wiki_pages = version_check >= 2.2 ## ITEM MANAGERS # Step through all the item managers by version # and instatiate and item manager for that item. for manager_version in self._item_managers_by_version: if version_check >= manager_version: managers = self._item_managers_by_version[manager_version] for attribute_name, item in managers.iteritems(): setattr(self, attribute_name, Redmine_Items_Manager(self, item))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpret_bits_value(val): """ Converts input bits value from string to a single integer value or None. If a comma- or '+'-separated set of values are provided, they are summed. .. note:: In order to flip the bits of the final result (after summation), for input of `str` type, prepend '~' to the input string. '~' must be prepended to the *entire string* and not to each bit flag! Parameters val : int, str, None An integer bit mask or flag, `None`, or a comma- or '+'-separated string list of integer bit values. If `val` is a `str` and if it is prepended with '~', then the output bit mask will have its bits flipped (compared to simple sum of input val). Returns ------- bitmask : int or None Returns and integer bit mask formed from the input bit value or `None` if input `val` parameter is `None` or an empty string. If input string value was prepended with '~', then returned value will have its bits flipped (inverse mask). """
if isinstance(val, int) or val is None: return val else: val = str(val).strip() if val.startswith('~'): flip_bits = True val = val[1:].lstrip() else: flip_bits = False if val.startswith('('): if val.endswith(')'): val = val[1:-1].strip() else: raise ValueError('Unbalanced parantheses or incorrect syntax.') if ',' in val: valspl = val.split(',') bitmask = 0 for v in valspl: bitmask += int(v) elif '+' in val: valspl = val.split('+') bitmask = 0 for v in valspl: bitmask += int(v) elif val.upper() in ['', 'NONE', 'INDEF']: return None else: bitmask = int(val) if flip_bits: bitmask = ~bitmask return bitmask
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output_influx(data): """Print data using influxDB format."""
for contract in data: # Pop yesterdays data yesterday_data = data[contract]['yesterday_hourly_consumption'] del data[contract]['yesterday_hourly_consumption'] # Print general data out = "pyhydroquebec,contract=" + contract + " " for index, key in enumerate(data[contract]): if index != 0: out = out + "," if key in ("annual_date_start", "annual_date_end"): out += key + "=\"" + str(data[contract][key]) + "\"" else: out += key + "=" + str(data[contract][key]) out += " " + str(int(datetime.datetime.now(HQ_TIMEZONE).timestamp() * 1000000000)) print(out) # Print yesterday values yesterday = datetime.datetime.now(HQ_TIMEZONE) - datetime.timedelta(days=1) yesterday = yesterday.replace(minute=0, hour=0, second=0, microsecond=0) for hour in yesterday_data: msg = "pyhydroquebec,contract={} {} {}" data = ",".join(["{}={}".format(key, value) for key, value in hour.items() if key != 'hour']) datatime = datetime.datetime.strptime(hour['hour'], '%H:%M:%S') yesterday = yesterday.replace(hour=datatime.hour) yesterday_str = str(int(yesterday.timestamp() * 1000000000)) print(msg.format(contract, data, yesterday_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 to_jd(year, month, day): '''Determine Julian day from Bahai date''' gy = year - 1 + EPOCH_GREGORIAN_YEAR if month != 20: m = 0 else: if isleap(gy + 1): m = -14 else: m = -15 return gregorian.to_jd(gy, 3, 20) + (19 * (month - 1)) + m + day
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_jd(jd): '''Calculate Bahai date from Julian day''' jd = trunc(jd) + 0.5 g = gregorian.from_jd(jd) gy = g[0] bstarty = EPOCH_GREGORIAN_YEAR if jd <= gregorian.to_jd(gy, 3, 20): x = 1 else: x = 0 # verify this next line... bys = gy - (bstarty + (((gregorian.to_jd(gy, 1, 1) <= jd) and x))) year = bys + 1 days = jd - to_jd(year, 1, 1) bld = to_jd(year, 20, 1) if jd >= bld: month = 20 else: month = trunc(days / 19) + 1 day = int((jd + 1) - to_jd(year, month, 1)) return year, month, day
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def to_jd(baktun, katun, tun, uinal, kin): '''Determine Julian day from Mayan long count''' return EPOCH + (baktun * 144000) + (katun * 7200) + (tun * 360) + (uinal * 20) + kin
<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_jd(jd): '''Calculate Mayan long count from Julian day''' d = jd - EPOCH baktun = trunc(d / 144000) d = (d % 144000) katun = trunc(d / 7200) d = (d % 7200) tun = trunc(d / 360) d = (d % 360) uinal = trunc(d / 20) kin = int((d % 20)) return (baktun, katun, tun, uinal, kin)