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 to_haab(jd): '''Determine Mayan Haab "month" and day from Julian day''' # Number of days since the start of the long count lcount = trunc(jd) + 0.5 - EPOCH # Long Count begins 348 days after the start of the cycle day = (lcount + 348) % 365 count = day % 20 month = trunc(day / 20) ...
<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_tzolkin(jd): '''Determine Mayan Tzolkin "month" and day from Julian day''' lcount = trunc(jd) + 0.5 - EPOCH day = amod(lcount + 4, 13) name = amod(lcount + 20, 20) return int(day), TZOLKIN_NAMES[int(name) - 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 longcount_generator(baktun, katun, tun, uinal, kin): '''Generate long counts, starting with input''' j = to_jd(baktun, katun, tun, uinal, kin) while True: yield from_jd(j) j = j + 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 next_haab(month, jd): '''For a given haab month and a julian day count, find the next start of that month on or after the JDC''' if jd < EPOCH: raise IndexError("Input day is before Mayan epoch.") hday, hmonth = to_haab(jd) if hmonth == month: days = 1 - hday else: cou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def next_tzolkin(tzolkin, jd): '''For a given tzolk'in day, and a julian day count, find the next occurrance of that tzolk'in after the date''' if jd < EPOCH: raise IndexError("Input day is before Mayan epoch.") count1 = _tzolkin_count(*to_tzolkin(jd)) count2 = _tzolkin_count(*tzolkin) add...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def next_tzolkin_haab(tzolkin, haab, jd): '''For a given haab-tzolk'in combination, and a Julian day count, find the next occurrance of the combination after the date''' # get H & T of input jd, and their place in the 18,980 day cycle haabcount = _haab_count(*to_haab(jd)) haab_desired_count = _haab_coun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def haab_monthcalendar(baktun=None, katun=None, tun=None, uinal=None, kin=None, jdc=None): '''For a given long count, return a calender of the current haab month, divided into tzolkin "weeks"''' if not jdc: jdc = to_jd(baktun, katun, tun, uinal, kin) haab_number, haab_month = to_haab(jdc) first...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _update_data(self, data={}): '''Update the data in this object.''' # Store the changes to prevent this update from affecting it pending_changes = self._changes or {} try: del self._changes except: pass # Map custom fields into our custom fiel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _remap_tag_to_tag_id(cls, tag, new_data): '''Remaps a given changed field from tag to tag_id.''' try: value = new_data[tag] except: # If tag wasn't changed, just return return tag_id = tag + '_id' try: # Remap the ID change to ...
<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_item_manager(self, key, item_class, **paths): ''' Add an item manager to this object. ''' updated_paths = {} for path_type, path_value in paths.iteritems(): updated_paths[path_type] = path_value.format(**self.__dict__) manager = Redmine_Items_Manager...
<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(self): '''Refresh this item from data on the server. Will save any unsaved data first.''' if not self._item_path: raise AttributeError('refresh is not available for %s' % self._type) if not self.id: raise RedmineError('%s did not come from the Redmine...
<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_changes(self): '''Get all changed values.''' result = dict( (f['id'], f.get('value','')) for f in self._data if f.get('changed', False) ) self._clear_changes 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 new(self, **dict): '''Create a new item with the provided dict information. Returns the new item.''' if not self._item_new_path: raise AttributeError('new is not available for %s' % self._item_name) # Remap various tag to tag_id for tag in self._object._remap_to_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 get(self, id, **options): '''Get a single item with the given ID''' if not self._item_path: raise AttributeError('get is not available for %s' % self._item_name) target = self._item_path % id json_data = self._redmine.get(target, **options) data = self._redmine.un...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update(self, id, **dict): '''Update a given item with the passed data.''' if not self._item_path: raise AttributeError('update is not available for %s' % self._item_name) target = (self._update_path or self._item_path) % id payload = json.dumps({self._item_type: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 delete(self, id): '''Delete a single item with the given ID''' if not self._item_path: raise AttributeError('delete is not available for %s' % self._item_name) target = self._item_path % id self._redmine.delete(target) 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 query(self, **options): '''Return an iterator for the given items.''' if not self._query_path: raise AttributeError('query is not available for %s' % self._item_name) last_item = 0 offset = 0 current_item = None limit = options.get('limit', 25) opt...
<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_authentication(self, username, password): '''Create the authentication object with the given credentials.''' ## BUG WORKAROUND if self.version < 1.1: # Version 1.0 had a bug when using the key parameter. # Later versions have the opposite bug (a key in the use...
<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_raw(self, page, parms=None, payload=None, HTTPrequest=None, payload_type='application/json' ): '''Opens a page from the server with optional XML. Returns a response file-like object''' if not parms: parms={} # if we're using a key, but it's not going in the header, add it ...
<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, page, parms=None, payload=None, HTTPrequest=None ): '''Opens a page from the server with optional content. Returns the string response.''' response = self.open_raw( page, parms, payload, HTTPrequest ) return response.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 post(self, page, payload, parms=None ): '''Posts a string payload to the server - used to make new Redmine items. Returns an JSON string or error.''' if self.readonlytest: print 'Redmine read only test: Pretending to create: ' + page return payload else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def put(self, page, payload, parms=None ): '''Puts an XML object on the server - used to update Redmine items. Returns nothing useful.''' if self.readonlytest: print 'Redmine read only test: Pretending to update: ' + page else: return self.open( page, parms, payload, HTT...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete(self, page ): '''Deletes a given object on the server - used to remove items from Redmine. Use carefully!''' if self.readonlytest: print 'Redmine read only test: Pretending to delete: ' + page else: return self.open( page, HTTPrequest=self.DELETE_Request )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def unwrap_json(self, type, json_data): '''Decodes a json string, and unwraps any 'type' it finds within.''' # Parse the data try: data = json.loads(json_data) except ValueError: # If parsing failed, then raise the string which likely contains an error message ins...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def find_all_item_classes(self): '''Finds and stores a reference to all Redmine_Item subclasses for later use.''' # This is a circular import, but performed after the class is defined and an object is instatiated. # We do this in order to get references to any objects definitions in the redmine....
<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_cache(self, type, data, obj=None): '''Returns the updated cached version of the given dict''' try: id = data['id'] except: # Not an identifiable item #print 'don\'t know this item %r:%r' % (type, data) return data # If obj was pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def substract(self, pt): """Return a Point instance as the displacement of two points."""
if isinstance(pt, Point): return Point(pt.x - self.x, pt.y - self.y, pt.z - self.z) else: raise TypeError
<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_list(cls, l): """Return a Point instance from a given list"""
if len(l) == 3: x, y, z = map(float, l) return cls(x, y, z) elif len(l) == 2: x, y = map(float, l) return cls(x, y) else: raise AttributeError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multiply(self, number): """Return a Vector as the product of the vector and a real number."""
return self.from_list([x * number for x in self.to_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 magnitude(self): """Return magnitude of the vector."""
return math.sqrt( reduce(lambda x, y: x + y, [x ** 2 for x in self.to_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 sum(self, vector): """Return a Vector instance as the vector sum of two vectors."""
return self.from_list( [x + vector.vector[i] for i, x in self.to_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 dot(self, vector, theta=None): """Return the dot product of two vectors. If theta is given then the dot product is computed as v1*v1 = |v1||v2|cos(theta). Ar...
if theta is not None: return (self.magnitude() * vector.magnitude() * math.degrees(math.cos(theta))) return (reduce(lambda x, y: x + y, [x * vector.vector[i] for i, x in self.to_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 cross(self, vector): """Return a Vector instance as the cross product of two vectors"""
return Vector((self.y * vector.z - self.z * vector.y), (self.z * vector.x - self.x * vector.z), (self.x * vector.y - self.y * vector.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 unit(self): """Return a Vector instance of the unit vector"""
return Vector( (self.x / self.magnitude()), (self.y / self.magnitude()), (self.z / self.magnitude()) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def angle(self, vector): """Return the angle between two vectors in degrees."""
return math.degrees( math.acos( self.dot(vector) / (self.magnitude() * vector.magnitude()) ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def non_parallel(self, vector): """Return True if vectors are non-parallel. Non-parallel vectors are vectors which are neither parallel nor perpendicular to each...
if (self.is_parallel(vector) is not True and self.is_perpendicular(vector) is not True): 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 rotate(self, angle, axis=(0, 0, 1)): """Returns the rotated vector. Assumes angle is in radians"""
if not all(isinstance(a, int) for a in axis): raise ValueError x, y, z = self.x, self.y, self.z # Z axis rotation if(axis[2]): x = (self.x * math.cos(angle) - self.y * math.sin(angle)) y = (self.x * math.sin(angle) + self.y * math.cos(angle)) ...
<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_points(cls, point1, point2): """Return a Vector instance from two given points."""
if isinstance(point1, Point) and isinstance(point2, Point): displacement = point1.substract(point2) return cls(displacement.x, displacement.y, displacement.z) raise TypeError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def spherical(cls, mag, theta, phi=0): '''Returns a Vector instance from spherical coordinates''' return cls( mag * math.sin(phi) * math.cos(theta), # X mag * math.sin(phi) * math.sin(theta), # Y mag * math.cos(phi) # Z )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def cylindrical(cls, mag, theta, z=0): '''Returns a Vector instance from cylindircal coordinates''' return cls( mag * math.cos(theta), # X mag * math.sin(theta), # Y z # Z )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def amod(a, b): '''Modulus function which returns numerator if modulus is zero''' modded = int(a % b) return b if modded is 0 else modded
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def search_weekday(weekday, jd, direction, offset): '''Determine the Julian date for the next or previous weekday''' return weekday_before(weekday, jd + (direction * offset))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def irafglob(inlist, atfile=None): """ Returns a list of filenames based on the type of IRAF input. Handles lists, wild-card characters, and at-files. For specia...
# Sanity check if inlist is None or len(inlist) == 0: return [] # Determine which form of input was provided: if isinstance(inlist, list): # python list flist = [] for f in inlist: flist += irafglob(f) elif ',' in inlist: # comma-separated 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 pack(self): """Return binary format of packet. The returned string is the binary format of the packet with stuffing and framing applied. It is ready to be se...
# Possible structs for packet ID. # try: structs_ = get_structs_for_fields([self.fields[0]]) except (TypeError): # TypeError, if self.fields[0] is a wrong argument to `chr()`. raise PackError(self) # Possible structs for packet ID + subcode...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpack(cls, rawpacket): """Instantiate `Packet` from binary string. :param rawpacket: TSIP pkt in binary format. :type rawpacket: String. byte stuffing rever...
structs_ = get_structs_for_rawpacket(rawpacket) for struct_ in structs_: try: return cls(*struct_.unpack(rawpacket)) except struct.error: raise # Try next one. pass # Packet ID 0xff is a pseudo-packet rep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ch_handler(offset=0, length=-1, **kw): """ Handle standard PRIMARY clipboard access. Note that offset and length are passed as strings. This differs from CLI...
global _lastSel offset = int(offset) length = int(length) if length < 0: length = len(_lastSel) return _lastSel[offset:offset+length]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(text, cbname): """ Put the given string into the given clipboard. """
global _lastSel _checkTkInit() if cbname == 'CLIPBOARD': _theRoot.clipboard_clear() if text: # for clipboard_append, kwds can be -displayof, -format, or -type _theRoot.clipboard_append(text) return if cbname == 'PRIMARY': _lastSel = text _...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(cbname): """ Get the contents of the given clipboard. """
_checkTkInit() if cbname == 'PRIMARY': try: return _theRoot.selection_get(selection='PRIMARY') except: return None if cbname == 'CLIPBOARD': try: return _theRoot.selection_get(selection='CLIPBOARD') except: return None rais...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, measurementId): """ Initiates a new measurement. Accepts a json payload with the following attributes; * duration: in seconds * startTime OR delay:...
json = request.get_json() try: start = self._calculateStartTime(json) except ValueError: return 'invalid date format in request', 400 duration = json['duration'] if 'duration' in json else 10 if start is None: # should never happen but just in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def printCols(strlist,cols=5,width=80): """Print elements of list in cols columns"""
# This may exist somewhere in the Python standard libraries? # Should probably rewrite this, it is pretty crude. nlines = (len(strlist)+cols-1)//cols line = nlines*[""] for i in range(len(strlist)): c, r = divmod(i,nlines) nwid = c*width//cols - len(line[r]) if nwid>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 stripQuotes(value): """Strip single or double quotes off string; remove embedded quote pairs"""
if value[:1] == '"': value = value[1:] if value[-1:] == '"': value = value[:-1] # replace "" with " value = re.sub(_re_doubleq2, '"', value) elif value[:1] == "'": value = value[1:] if value[-1:] == "'": value = value[:-1] # repla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rglob(root, pattern): """ Same thing as glob.glob, but recursively checks subdirs. """
# Thanks to Alex Martelli for basics on Stack Overflow retlist = [] if None not in (pattern, root): for base, dirs, files in os.walk(root): goodfiles = fnmatch.filter(files, pattern) retlist.extend(os.path.join(base, f) for f in goodfiles) return retlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translateName(s, dot=0): """Convert CL parameter or variable name to Python-acceptable name Translate embedded dollar signs to 'DOLLAR' Add 'PY' prefix to co...
s = s.replace('$', 'DOLLAR') sparts = s.split('.') for i in range(len(sparts)): if sparts[i] == "" or sparts[i][0] in string.digits or \ keyword.iskeyword(sparts[i]): sparts[i] = 'PY' + sparts[i] if dot: return 'DOT'.join(sparts) else: return '.'.join(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_tk_default_root(withdraw=True): """ In case the _default_root value is required, you may safely call this ahead of time to ensure that it has been initi...
if not capable.OF_GRAPHICS: raise RuntimeError("Cannot run this command without graphics") if not TKNTR._default_root: # TKNTR imported above junk = TKNTR.Tk() # tkinter._default_root is now populated (== junk) retval = TKNTR._default_root if withdraw and retval: retval.wi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tkreadline(file=None): """Read a line from file while running Tk mainloop. If the file is not line-buffered then the Tk mainloop will stop running after one ...
if file is None: file = sys.stdin if not hasattr(file, "readline"): raise TypeError("file must be a filehandle with a readline method") # Call tkread now... # BUT, if we get in here for something not GUI-related (e.g. terminal- # focused code in a sometimes-GUI app) then skip tkre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def launchBrowser(url, brow_bin='mozilla', subj=None): """ Given a URL, try to pop it up in a browser on most platforms. brow_bin is only used on OS's where ther...
if not subj: subj = url # Tries to use webbrowser module on most OSes, unless a system command # is needed. (E.g. win, linux, sun, etc) if sys.platform not in ('os2warp, iphone'): # try webbrowser w/ everything? import webbrowser if not webbrowser.open(url): print("Error ...
<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(self, file, nbytes): """Read nbytes characters from file while running Tk mainloop"""
if not capable.OF_GRAPHICS: raise RuntimeError("Cannot run this command without graphics") if isinstance(file, int): fd = file else: # Otherwise, assume we have Python file object try: fd = file.fileno() except: ...
<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(self, fd, mask): """Read waiting data and terminate Tk mainloop if done"""
try: # if EOF was encountered on a tty, avoid reading again because # it actually requests more data if select.select([fd],[],[],0)[0]: snew = os.read(fd, self.nbytes) # returns bytes in PY3K if PY3K: snew = snew.decode('ascii','replace') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def legal_date(year, month, day): '''Checks if a given date is a legal positivist date''' try: assert year >= 1 assert 0 < month <= 14 assert 0 < day <= 28 if month == 14: if isleap(year + YEAR_EPOCH - 1): assert day <= 2 else: ...
<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): '''Convert a Positivist date to Julian day count.''' legal_date(year, month, day) gyear = year + YEAR_EPOCH - 1 return ( gregorian.EPOCH - 1 + (365 * (gyear - 1)) + floor((gyear - 1) / 4) + (-floor((gyear - 1) / 100)) + floor((gyear - 1) / 400) + (mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_jd(jd): '''Convert a Julian day count to Positivist date.''' try: assert jd >= EPOCH except AssertionError: raise ValueError('Invalid Julian day') depoch = floor(jd - 0.5) + 0.5 - gregorian.EPOCH quadricent = floor(depoch / gregorian.INTERCALATION_CYCLE_DAYS) dqc = dep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dayname(year, month, day): ''' Give the name of the month and day for a given date. Returns: tuple month_name, day_name ''' legal_date(year, month, day) yearday = (month - 1) * 28 + day if isleap(year + YEAR_EPOCH - 1): dname = data.day_names_leap[yearday - 1] else...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _evictStaleDevices(self): """ A housekeeping function which runs in a worker thread and which evicts devices that haven't sent an update for a while. """
while self.running: expiredDeviceIds = [key for key, value in self.devices.items() if value.hasExpired()] for key in expiredDeviceIds: logger.warning("Device timeout, removing " + key) del self.devices[key] time.sleep(1) # TODO sen...
<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_parse(name_list): """Parse a comma-separated list of values, or a filename (starting with @) containing a list value on each line. """
if name_list and name_list[0] == '@': value = name_list[1:] if not os.path.exists(value): log.warning('The file %s does not exist' % value) return try: return [v.strip() for v in open(value, 'r').readlines()] except IOError as e: log....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _mmInit(self): """Create the minimum match dictionary of keys"""
# cache references to speed up loop a bit mmkeys = {} mmkeysGet = mmkeys.setdefault minkeylength = self.minkeylength for key in self.data.keys(): # add abbreviations as short as minkeylength # always add at least one entry (even for key="") le...
<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, key, keylist): """Hook to resolve ambiguities in selected keys"""
raise AmbiguousKeyError("Ambiguous key "+ repr(key) + ", could be any of " + str(sorted(keylist)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key, failobj=None, exact=0): """Raises exception if key is ambiguous"""
if not exact: key = self.getfullkey(key,new=1) return self.data.get(key,failobj)
<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(self, key, exact=0): """Raises an exception if key is ambiguous"""
if not exact: key = self.getfullkey(key,new=1) return key in self.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 getall(self, key, failobj=None): """Returns a list of all the matching values for key, containing a single entry for unambiguous matches and multiple entries...
if self.mmkeys is None: self._mmInit() k = self.mmkeys.get(key) if not k: return failobj return list(map(self.data.get, k))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key, failobj=None, exact=0): """Returns failobj if key is not found or is ambiguous"""
if not exact: try: key = self.getfullkey(key) except KeyError: return failobj return self.data.get(key,failobj)
<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(self, key, exact=0): """Returns false if key is not found or is ambiguous"""
if not exact: try: key = self.getfullkey(key) return 1 except KeyError: return 0 else: return key in self.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 parFactory(fields, strict=0): """parameter factory function fields is a list of the comma-separated fields (as in the .par file). Each entry is a string or N...
if len(fields) < 3 or None in fields[0:3]: raise SyntaxError("At least 3 fields must be given") type = fields[1] if type in _string_types: return IrafParS(fields,strict) elif type == 'R': return StrictParR(fields,1) elif type in _real_types: return IrafParR(fields,s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setCmdline(self,value=1): """Set cmdline flag"""
# set through dictionary to avoid extra calls to __setattr__ if value: self.__dict__['flags'] = self.flags | _cmdlineFlag else: self.__dict__['flags'] = self.flags & ~_cmdlineFlag
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setChanged(self,value=1): """Set changed flag"""
# set through dictionary to avoid another call to __setattr__ if value: self.__dict__['flags'] = self.flags | _changedFlag else: self.__dict__['flags'] = self.flags & ~_changedFlag
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isLearned(self, mode=None): """Return true if this parameter is learned Hidden parameters are not learned; automatic parameters inherit behavior from package...
if "l" in self.mode: return 1 if "h" in self.mode: return 0 if "a" in self.mode: if mode is None: mode = 'ql' # that is, iraf.cl.mode if "h" in mode and "l" not in mode: return 0 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 getWithPrompt(self): """Interactively prompt for parameter value"""
if self.prompt: pstring = self.prompt.split("\n")[0].strip() else: pstring = self.name if self.choice: schoice = list(map(self.toString, self.choice)) pstring = pstring + " (" + "|".join(schoice) + ")" elif self.min not in [None, INDEF] or...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkOneValue(self,v,strict=0): """Checks a single value to see if it is in range or choice list Allows indirection strings starting with ")". Assumes v has ...
if v in [None, INDEF] or (isinstance(v,str) and v[:1] == ")"): return v elif v == "": # most parameters treat null string as omitted value return None elif self.choice is not None and v not in self.choiceDict: schoice = list(map(self.toString, sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pretty(self,verbose=0): """Return pretty list description of parameter"""
# split prompt lines and add blanks in later lines to align them plines = self.prompt.split('\n') for i in range(len(plines)-1): plines[i+1] = 32*' ' + plines[i+1] plines = '\n'.join(plines) namelen = min(len(self.name), 12) pvalue = self.get(prompt=0,lpar=1) alw...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setChoice(self,s,strict=0): """Set choice parameter from string s"""
clist = _getChoice(s,strict) self.choice = list(map(self._coerceValue, clist)) self._setChoiceDict()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setChoiceDict(self): """Create dictionary for choice list"""
# value is name of choice parameter (same as key) self.choiceDict = {} for c in self.choice: self.choiceDict[c] = c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _optionalPrompt(self, mode): """Interactively prompt for parameter if necessary Prompt for value if (1) mode is hidden but value is undefined or bad, or (2) ...
if (self.mode == "h") or (self.mode == "a" and mode == "h"): # hidden parameter if not self.isLegal(): self.getWithPrompt() elif self.mode == "u": # "u" is a special mode used for local variables in CL scripts # They should never prompt un...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getPFilename(self,native,prompt): """Get p_filename field for this parameter Same as get for non-list params """
return self.get(native=native,prompt=prompt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getField(self, field, native=0, prompt=1): """Get a parameter field value"""
try: # expand field name using minimum match field = _getFieldDict[field] except KeyError as e: # re-raise the exception with a bit more info raise SyntaxError("Cannot get field " + field + " for parameter " + self.name + "\n" + str(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 _setField(self, value, field, check=1): """Set a parameter field value"""
try: # expand field name using minimum match field = _setFieldDict[field] except KeyError as e: raise SyntaxError("Cannot set field " + field + " for parameter " + self.name + "\n" + str(e)) if field == "p_prompt": self.prompt ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sumindex(self, index=None): """Convert tuple index to 1-D index into value"""
try: ndim = len(index) except TypeError: # turn index into a 1-tuple index = (index,) ndim = 1 if len(self.shape) != ndim: raise ValueError("Index to %d-dimensional array %s has too %s dimensions" % (len(self.shape), se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _coerceValue(self,value,strict=0): """Coerce parameter to appropriate type Should accept None or null string. Must be an array. """
try: if isinstance(value,str): # allow single blank-separated string as input value = value.split() if len(value) != len(self.value): raise IndexError v = len(self.value)*[0] for i in range(len(v)): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setChoiceDict(self): """Create min-match dictionary for choice list"""
# value is full name of choice parameter self.choiceDict = minmatch.MinMatchDict() for c in self.choice: self.choiceDict.add(c, c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def legal_date(year, month, day): '''Check if this is a legal date in the Gregorian calendar''' if month == 2: daysinmonth = 29 if isleap(year) else 28 else: daysinmonth = 30 if month in HAVE_30_DAYS else 31 if not (0 < day <= daysinmonth): raise ValueError("Month {} doesn't hav...
<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_jd2(year, month, day): '''Gregorian to Julian Day Count for years between 1801-2099''' # http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html legal_date(year, month, day) if month <= 2: year = year - 1 month = month + 12 a = floor(year / 100) b = floor(a / 4) c = ...
<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): "Retrieve the Julian date equivalent for this date" return day + (month - 1) * 30 + (year - 1) * 365 + floor(year / 4) + 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(jdc): "Create a new date from a Julian date." cdc = floor(jdc) + 0.5 - EPOCH year = floor((cdc - floor((cdc + 366) / 1461)) / 365) + 1 yday = jdc - to_jd(year, 1, 1) month = floor(yday / 30) + 1 day = yday - (month - 1) * 30 + 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 print_archive(self,format=True): """ Prints out archived WCS keywords."""
if len(list(self.orig_wcs.keys())) > 0: block = 'Original WCS keywords for ' + self.rootname+ '\n' block += ' backed up on '+repr(self.orig_wcs['WCSCDATE'])+'\n' if not format: for key in self.wcstrans.keys(): block += key.upper() + " ...
<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_orient(self): """ Return the computed orientation based on CD matrix. """
self.orient = RADTODEG(N.arctan2(self.cd12,self.cd22))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateWCS(self, pixel_scale=None, orient=None,refpos=None,refval=None,size=None): """ Create a new CD Matrix from the absolute pixel scale and reference imag...
# Set up parameters necessary for updating WCS # Check to see if new value is provided, # If not, fall back on old value as the default _updateCD = no if orient is not None and orient != self.orient: pa = DEGTORAD(orient) self.orient = orient ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xy2rd(self,pos): """ This method would apply the WCS keywords to a position to generate a new sky position. The algorithm comes directly from 'imgtools.xy2rd...
if self.ctype1.find('TAN') < 0 or self.ctype2.find('TAN') < 0: print('XY2RD only supported for TAN projections.') raise TypeError if isinstance(pos,N.ndarray): # If we are working with an array of positions, # point to just X and Y values pos...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotateCD(self,orient): """ Rotates WCS CD matrix to new orientation given by 'orient' """
# Determine where member CRVAL position falls in ref frame # Find out whether this needs to be rotated to align with # reference frame. _delta = self.get_orient() - orient if _delta == 0.: return # Start by building the rotation matrix... _rot = fil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self,fitsname=None,wcs=None,archive=True,overwrite=False,quiet=True): """ Write out the values of the WCS keywords to the specified image. If it is a G...
## Start by making sure all derived values are in sync with CD matrix self.update() image = self.rootname _fitsname = fitsname if image.find('.fits') < 0 and _fitsname is not None: # A non-FITS image was provided, and openImage made a copy # Update attr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(self): """ Reset the active WCS keywords to values stored in the backup keywords. """
# If there are no backup keys, do nothing... if len(list(self.backup.keys())) == 0: return for key in self.backup.keys(): if key != 'WCSCDATE': self.__dict__[self.wcstrans[key]] = self.orig_wcs[self.backup[key]] self.update()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def archive(self,prepend=None,overwrite=no,quiet=yes): """ Create backup copies of the WCS keywords with the given prepended string. If backup keywords are alrea...
# Verify that existing backup values are not overwritten accidentally. if len(list(self.backup.keys())) > 0 and overwrite == no: if not quiet: print('WARNING: Backup WCS keywords already exist! No backup made.') print(' The values can only be overridd...
<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_archive(self,header,prepend=None): """ Extract a copy of WCS keywords from an open file header, if they have already been created and remember the prefi...
# Start by looking for the any backup WCS keywords to # determine whether archived values are present and to set # the prefix used. _prefix = None _archive = False if header is not None: for kw in header.items(): if kw[0][1:] in self.wcstrans....