text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Returns true if the object last and next movement are <END_TASK> <USER_TASK:> Description: def __sepApp(self, IDs, aspList): """ Returns true if the object last and next movement are separations and applications to objects in list IDs. It only considers aspects in aspList. This function is static since it does not test if the next application will be indeed perfected. It considers only a snapshot of the chart and not its astronomical movement. """
sep, app = self.dyn.immediateAspects(self.obj.id, aspList) if sep is None or app is None: return False else: sepCondition = sep['id'] in IDs appCondition = app['id'] in IDs return sepCondition == appCondition == True
<SYSTEM_TASK:> Returns if the object is separating and applying to <END_TASK> <USER_TASK:> Description: def isAuxilied(self): """ Returns if the object is separating and applying to a benefic considering good aspects. """
benefics = [const.VENUS, const.JUPITER] return self.__sepApp(benefics, aspList=[0, 60, 120])
<SYSTEM_TASK:> Returns if the object is separating and applying to <END_TASK> <USER_TASK:> Description: def isSurrounded(self): """ Returns if the object is separating and applying to a malefic considering bad aspects. """
malefics = [const.MARS, const.SATURN] return self.__sepApp(malefics, aspList=[0, 90, 180])
<SYSTEM_TASK:> Returns if object is conjunct north node. <END_TASK> <USER_TASK:> Description: def isConjNorthNode(self): """ Returns if object is conjunct north node. """
node = self.chart.getObject(const.NORTH_NODE) return aspects.hasAspect(self.obj, node, aspList=[0])
<SYSTEM_TASK:> Returns if object is conjunct south node. <END_TASK> <USER_TASK:> Description: def isConjSouthNode(self): """ Returns if object is conjunct south node. """
node = self.chart.getObject(const.SOUTH_NODE) return aspects.hasAspect(self.obj, node, aspList=[0])
<SYSTEM_TASK:> Returns true if the object does not have any <END_TASK> <USER_TASK:> Description: def isFeral(self): """ Returns true if the object does not have any aspects. """
planets = copy(const.LIST_SEVEN_PLANETS) planets.remove(self.obj.id) for otherID in planets: otherObj = self.chart.getObject(otherID) if aspects.hasAspect(self.obj, otherObj, const.MAJOR_ASPECTS): return False return True
<SYSTEM_TASK:> Returns the sum of the accidental dignities <END_TASK> <USER_TASK:> Description: def score(self): """ Returns the sum of the accidental dignities score. """
if not self.scoreProperties: self.scoreProperties = self.getScoreProperties() return sum(self.scoreProperties.values())
<SYSTEM_TASK:> Builds instance from dictionary of properties. <END_TASK> <USER_TASK:> Description: def fromDict(cls, _dict): """ Builds instance from dictionary of properties. """
obj = cls() obj.__dict__.update(_dict) return obj
<SYSTEM_TASK:> Returns the Equatorial Coordinates of this object. <END_TASK> <USER_TASK:> Description: def eqCoords(self, zerolat=False): """ Returns the Equatorial Coordinates of this object. Receives a boolean parameter to consider a zero latitude. """
lat = 0.0 if zerolat else self.lat return utils.eqCoords(self.lon, lat)
<SYSTEM_TASK:> Relocates this object to a new longitude. <END_TASK> <USER_TASK:> Description: def relocate(self, lon): """ Relocates this object to a new longitude. """
self.lon = angle.norm(lon) self.signlon = self.lon % 30 self.sign = const.LIST_SIGNS[int(self.lon / 30.0)]
<SYSTEM_TASK:> Returns if this object is direct, retrograde <END_TASK> <USER_TASK:> Description: def movement(self): """ Returns if this object is direct, retrograde or stationary. """
if abs(self.lonspeed) < 0.0003: return const.STATIONARY elif self.lonspeed > 0: return const.DIRECT else: return const.RETROGRADE
<SYSTEM_TASK:> Returns if a longitude belongs to this house. <END_TASK> <USER_TASK:> Description: def inHouse(self, lon): """ Returns if a longitude belongs to this house. """
dist = angle.distance(self.lon + House._OFFSET, lon) return dist < self.size
<SYSTEM_TASK:> Returns the orb of this fixed star. <END_TASK> <USER_TASK:> Description: def orb(self): """ Returns the orb of this fixed star. """
for (mag, orb) in FixedStar._ORBS: if self.mag < mag: return orb return 0.5
<SYSTEM_TASK:> Returns true if this star aspects another object. <END_TASK> <USER_TASK:> Description: def aspects(self, obj): """ Returns true if this star aspects another object. Fixed stars only aspect by conjunctions. """
dist = angle.closestdistance(self.lon, obj.lon) return abs(dist) < self.orb()
<SYSTEM_TASK:> Returns a list with all objects in a house. <END_TASK> <USER_TASK:> Description: def getObjectsInHouse(self, house): """ Returns a list with all objects in a house. """
res = [obj for obj in self if house.hasObject(obj)] return ObjectList(res)
<SYSTEM_TASK:> Returns a list of objects aspecting a point <END_TASK> <USER_TASK:> Description: def getObjectsAspecting(self, point, aspList): """ Returns a list of objects aspecting a point considering a list of possible aspects. """
res = [] for obj in self: if obj.isPlanet() and aspects.isAspecting(obj, point, aspList): res.append(obj) return ObjectList(res)
<SYSTEM_TASK:> Returns the arc of direction between a Promissor <END_TASK> <USER_TASK:> Description: def arc(pRA, pDecl, sRA, sDecl, mcRA, lat): """ Returns the arc of direction between a Promissor and Significator. It uses the generic proportional semi-arc method. """
pDArc, pNArc = utils.dnarcs(pDecl, lat) sDArc, sNArc = utils.dnarcs(sDecl, lat) # Select meridian and arcs to be used # Default is MC and Diurnal arcs mdRA = mcRA sArc = sDArc pArc = pDArc if not utils.isAboveHorizon(sRA, sDecl, mcRA, lat): # Use IC and Nocturnal arcs mdRA = angle.norm(mcRA + 180) sArc = sNArc pArc = pNArc # Promissor and Significator distance to meridian pDist = angle.closestdistance(mdRA, pRA) sDist = angle.closestdistance(mdRA, sRA) # Promissor should be after significator (in degrees) if pDist < sDist: pDist += 360 # Meridian distances proportional to respective semi-arcs sPropDist = sDist / (sArc / 2.0) pPropDist = pDist / (pArc / 2.0) # The arc is how much of the promissor's semi-arc is # needed to reach the significator return (pPropDist - sPropDist) * (pArc / 2.0)
<SYSTEM_TASK:> Returns the arc of direction between a promissor <END_TASK> <USER_TASK:> Description: def getArc(prom, sig, mc, pos, zerolat): """ Returns the arc of direction between a promissor and a significator. Arguments are also the MC, the geoposition and zerolat to assume zero ecliptical latitudes. ZeroLat true => inZodiaco, false => inMundo """
pRA, pDecl = prom.eqCoords(zerolat) sRa, sDecl = sig.eqCoords(zerolat) mcRa, mcDecl = mc.eqCoords() return arc(pRA, pDecl, sRa, sDecl, mcRa, pos.lat)
<SYSTEM_TASK:> Builds a data structure indexing the terms <END_TASK> <USER_TASK:> Description: def _buildTerms(self): """ Builds a data structure indexing the terms longitude by sign and object. """
termLons = tables.termLons(tables.EGYPTIAN_TERMS) res = {} for (ID, sign, lon) in termLons: try: res[sign][ID] = lon except KeyError: res[sign] = {} res[sign][ID] = lon return res
<SYSTEM_TASK:> Creates a generic entry for an object. <END_TASK> <USER_TASK:> Description: def G(self, ID, lat, lon): """ Creates a generic entry for an object. """
# Equatorial coordinates eqM = utils.eqCoords(lon, lat) eqZ = eqM if lat != 0: eqZ = utils.eqCoords(lon, 0) return { 'id': ID, 'lat': lat, 'lon': lon, 'ra': eqM[0], 'decl': eqM[1], 'raZ': eqZ[0], 'declZ': eqZ[1], }
<SYSTEM_TASK:> Returns the term of an object in a sign. <END_TASK> <USER_TASK:> Description: def T(self, ID, sign): """ Returns the term of an object in a sign. """
lon = self.terms[sign][ID] ID = 'T_%s_%s' % (ID, sign) return self.G(ID, 0, lon)
<SYSTEM_TASK:> Returns the dexter aspect of an object. <END_TASK> <USER_TASK:> Description: def D(self, ID, asp): """ Returns the dexter aspect of an object. """
obj = self.chart.getObject(ID).copy() obj.relocate(obj.lon - asp) ID = 'D_%s_%s' % (ID, asp) return self.G(ID, obj.lat, obj.lon)
<SYSTEM_TASK:> Returns the conjunction or opposition aspect <END_TASK> <USER_TASK:> Description: def N(self, ID, asp=0): """ Returns the conjunction or opposition aspect of an object. """
obj = self.chart.get(ID).copy() obj.relocate(obj.lon + asp) ID = 'N_%s_%s' % (ID, asp) return self.G(ID, obj.lat, obj.lon)
<SYSTEM_TASK:> Computes the in-zodiaco and in-mundo arcs <END_TASK> <USER_TASK:> Description: def _arc(self, prom, sig): """ Computes the in-zodiaco and in-mundo arcs between a promissor and a significator. """
arcm = arc(prom['ra'], prom['decl'], sig['ra'], sig['decl'], self.mcRA, self.lat) arcz = arc(prom['raZ'], prom['declZ'], sig['raZ'], sig['declZ'], self.mcRA, self.lat) return { 'arcm': arcm, 'arcz': arcz }
<SYSTEM_TASK:> Returns the arcs between a promissor and <END_TASK> <USER_TASK:> Description: def getArc(self, prom, sig): """ Returns the arcs between a promissor and a significator. Should uses the object creation functions to build the objects. """
res = self._arc(prom, sig) res.update({ 'prom': prom['id'], 'sig': sig['id'] }) return res
<SYSTEM_TASK:> Returns the IDs as objects considering the <END_TASK> <USER_TASK:> Description: def _elements(self, IDs, func, aspList): """ Returns the IDs as objects considering the aspList and the function. """
res = [] for asp in aspList: if (asp in [0, 180]): # Generate func for conjunctions and oppositions if func == self.N: res.extend([func(ID, asp) for ID in IDs]) else: res.extend([func(ID) for ID in IDs]) else: # Generate Dexter and Sinister for others res.extend([self.D(ID, asp) for ID in IDs]) res.extend([self.S(ID, asp) for ID in IDs]) return res
<SYSTEM_TASK:> Returns a list with the objects as terms. <END_TASK> <USER_TASK:> Description: def _terms(self): """ Returns a list with the objects as terms. """
res = [] for sign, terms in self.terms.items(): for ID, lon in terms.items(): res.append(self.T(ID, sign)) return res
<SYSTEM_TASK:> Returns a sorted list with all <END_TASK> <USER_TASK:> Description: def getList(self, aspList): """ Returns a sorted list with all primary directions. """
# Significators objects = self._elements(self.SIG_OBJECTS, self.N, [0]) houses = self._elements(self.SIG_HOUSES, self.N, [0]) angles = self._elements(self.SIG_ANGLES, self.N, [0]) significators = objects + houses + angles # Promissors objects = self._elements(self.SIG_OBJECTS, self.N, aspList) terms = self._terms() antiscias = self._elements(self.SIG_OBJECTS, self.A, [0]) cantiscias = self._elements(self.SIG_OBJECTS, self.C, [0]) promissors = objects + terms + antiscias + cantiscias # Compute all res = [] for prom in promissors: for sig in significators: if (prom['id'] == sig['id']): continue arcs = self._arc(prom, sig) for (x,y) in [('arcm', 'M'), ('arcz', 'Z')]: arc = arcs[x] if 0 < arc < self.MAX_ARC: res.append([ arcs[x], prom['id'], sig['id'], y, ]) return sorted(res)
<SYSTEM_TASK:> Returns the directions within the <END_TASK> <USER_TASK:> Description: def view(self, arcmin, arcmax): """ Returns the directions within the min and max arcs. """
res = [] for direction in self.table: if arcmin < direction[0] < arcmax: res.append(direction) return res
<SYSTEM_TASK:> Returns all directions to a significator. <END_TASK> <USER_TASK:> Description: def bySignificator(self, ID): """ Returns all directions to a significator. """
res = [] for direction in self.table: if ID in direction[2]: res.append(direction) return res
<SYSTEM_TASK:> Returns all directions to a promissor. <END_TASK> <USER_TASK:> Description: def byPromissor(self, ID): """ Returns all directions to a promissor. """
res = [] for direction in self.table: if ID in direction[1]: res.append(direction) return res
<SYSTEM_TASK:> Returns a deep copy of this chart. <END_TASK> <USER_TASK:> Description: def copy(self): """ Returns a deep copy of this chart. """
chart = Chart.__new__(Chart) chart.date = self.date chart.pos = self.pos chart.hsys = self.hsys chart.objects = self.objects.copy() chart.houses = self.houses.copy() chart.angles = self.angles.copy() return chart
<SYSTEM_TASK:> Returns an object, house or angle <END_TASK> <USER_TASK:> Description: def get(self, ID): """ Returns an object, house or angle from the chart. """
if ID.startswith('House'): return self.getHouse(ID) elif ID in const.LIST_ANGLES: return self.getAngle(ID) else: return self.getObject(ID)
<SYSTEM_TASK:> Returns a list with all fixed stars. <END_TASK> <USER_TASK:> Description: def getFixedStars(self): """ Returns a list with all fixed stars. """
IDs = const.LIST_FIXED_STARS return ephem.getFixedStarList(IDs, self.date)
<SYSTEM_TASK:> Returns true if House1 is the same as the Asc. <END_TASK> <USER_TASK:> Description: def isHouse1Asc(self): """ Returns true if House1 is the same as the Asc. """
house1 = self.getHouse(const.HOUSE1) asc = self.getAngle(const.ASC) dist = angle.closestdistance(house1.lon, asc.lon) return abs(dist) < 0.0003
<SYSTEM_TASK:> Returns true if House10 is the same as the MC. <END_TASK> <USER_TASK:> Description: def isHouse10MC(self): """ Returns true if House10 is the same as the MC. """
house10 = self.getHouse(const.HOUSE10) mc = self.getAngle(const.MC) dist = angle.closestdistance(house10.lon, mc.lon) return abs(dist) < 0.0003
<SYSTEM_TASK:> Returns true if this chart is diurnal. <END_TASK> <USER_TASK:> Description: def isDiurnal(self): """ Returns true if this chart is diurnal. """
sun = self.getObject(const.SUN) mc = self.getAngle(const.MC) # Get ecliptical positions and check if the # sun is above the horizon. lat = self.pos.lat sunRA, sunDecl = utils.eqCoords(sun.lon, sun.lat) mcRA, mcDecl = utils.eqCoords(mc.lon, 0) return utils.isAboveHorizon(sunRA, sunDecl, mcRA, lat)
<SYSTEM_TASK:> Returns this chart's solar return for a <END_TASK> <USER_TASK:> Description: def solarReturn(self, year): """ Returns this chart's solar return for a given year. """
sun = self.getObject(const.SUN) date = Datetime('{0}/01/01'.format(year), '00:00', self.date.utcoffset) srDate = ephem.nextSolarReturn(date, sun.lon) return Chart(srDate, self.pos, hsys=self.hsys)
<SYSTEM_TASK:> Returns the longitude of an arabic part. <END_TASK> <USER_TASK:> Description: def partLon(ID, chart): """ Returns the longitude of an arabic part. """
# Get diurnal or nocturnal formula abc = FORMULAS[ID][0] if chart.isDiurnal() else FORMULAS[ID][1] a = objLon(abc[0], chart) b = objLon(abc[1], chart) c = objLon(abc[2], chart) return c + b - a
<SYSTEM_TASK:> Returns an object from the Ephemeris. <END_TASK> <USER_TASK:> Description: def sweObject(obj, jd): """ Returns an object from the Ephemeris. """
sweObj = SWE_OBJECTS[obj] sweList = swisseph.calc_ut(jd, sweObj) return { 'id': obj, 'lon': sweList[0], 'lat': sweList[1], 'lonspeed': sweList[3], 'latspeed': sweList[4] }
<SYSTEM_TASK:> Returns the julian date of the next transit of <END_TASK> <USER_TASK:> Description: def sweNextTransit(obj, jd, lat, lon, flag): """ Returns the julian date of the next transit of an object. The flag should be 'RISE' or 'SET'. """
sweObj = SWE_OBJECTS[obj] flag = swisseph.CALC_RISE if flag == 'RISE' else swisseph.CALC_SET trans = swisseph.rise_trans(jd, sweObj, lon, lat, 0, 0, 0, flag) return trans[1][0]
<SYSTEM_TASK:> Returns lists with house and angle longitudes. <END_TASK> <USER_TASK:> Description: def sweHousesLon(jd, lat, lon, hsys): """ Returns lists with house and angle longitudes. """
hsys = SWE_HOUSESYS[hsys] hlist, ascmc = swisseph.houses(jd, lat, lon, hsys) angles = [ ascmc[0], ascmc[1], angle.norm(ascmc[0] + 180), angle.norm(ascmc[1] + 180) ] return (hlist, angles)
<SYSTEM_TASK:> Returns a fixed star from the Ephemeris. <END_TASK> <USER_TASK:> Description: def sweFixedStar(star, jd): """ Returns a fixed star from the Ephemeris. """
sweList = swisseph.fixstar_ut(star, jd) mag = swisseph.fixstar_mag(star) return { 'id': star, 'mag': mag, 'lon': sweList[0], 'lat': sweList[1] }
<SYSTEM_TASK:> Returns the jd details of previous or next global solar eclipse. <END_TASK> <USER_TASK:> Description: def solarEclipseGlobal(jd, backward): """ Returns the jd details of previous or next global solar eclipse. """
sweList = swisseph.sol_eclipse_when_glob(jd, backward=backward) return { 'maximum': sweList[1][0], 'begin': sweList[1][2], 'end': sweList[1][3], 'totality_begin': sweList[1][4], 'totality_end': sweList[1][5], 'center_line_begin': sweList[1][6], 'center_line_end': sweList[1][7], }
<SYSTEM_TASK:> Returns the jd details of previous or next global lunar eclipse. <END_TASK> <USER_TASK:> Description: def lunarEclipseGlobal(jd, backward): """ Returns the jd details of previous or next global lunar eclipse. """
sweList = swisseph.lun_eclipse_when(jd, backward=backward) return { 'maximum': sweList[1][0], 'partial_begin': sweList[1][2], 'partial_end': sweList[1][3], 'totality_begin': sweList[1][4], 'totality_end': sweList[1][5], 'penumbral_begin': sweList[1][6], 'penumbral_end': sweList[1][7], }
<SYSTEM_TASK:> Returns date as signed list. <END_TASK> <USER_TASK:> Description: def toList(self): """ Returns date as signed list. """
date = self.date() sign = '+' if date[0] >= 0 else '-' date[0] = abs(date[0]) return list(sign) + date
<SYSTEM_TASK:> Returns time as signed list. <END_TASK> <USER_TASK:> Description: def toList(self): """ Returns time as signed list. """
slist = angle.toList(self.value) # Keep hours in 0..23 slist[1] = slist[1] % 24 return slist
<SYSTEM_TASK:> Builds a Datetime object given a jd and utc offset. <END_TASK> <USER_TASK:> Description: def fromJD(jd, utcoffset): """ Builds a Datetime object given a jd and utc offset. """
if not isinstance(utcoffset, Time): utcoffset = Time(utcoffset) localJD = jd + utcoffset.value / 24.0 date = Date(round(localJD)) time = Time((localJD + 0.5 - date.jdn) * 24) return Datetime(date, time, utcoffset)
<SYSTEM_TASK:> Returns this Datetime localized for UTC. <END_TASK> <USER_TASK:> Description: def getUTC(self): """ Returns this Datetime localized for UTC. """
timeUTC = self.time.getUTC(self.utcoffset) dateUTC = Date(round(self.jd)) return Datetime(dateUTC, timeUTC)
<SYSTEM_TASK:> Returns an object for a specific date and <END_TASK> <USER_TASK:> Description: def getObject(ID, jd, lat, lon): """ Returns an object for a specific date and location. """
if ID == const.SOUTH_NODE: obj = swe.sweObject(const.NORTH_NODE, jd) obj.update({ 'id': const.SOUTH_NODE, 'lon': angle.norm(obj['lon'] + 180) }) elif ID == const.PARS_FORTUNA: pflon = tools.pfLon(jd, lat, lon) obj = { 'id': ID, 'lon': pflon, 'lat': 0, 'lonspeed': 0, 'latspeed': 0 } elif ID == const.SYZYGY: szjd = tools.syzygyJD(jd) obj = swe.sweObject(const.MOON, szjd) obj['id'] = const.SYZYGY else: obj = swe.sweObject(ID, jd) _signInfo(obj) return obj
<SYSTEM_TASK:> Appends the sign id and longitude to an object. <END_TASK> <USER_TASK:> Description: def _signInfo(obj): """ Appends the sign id and longitude to an object. """
lon = obj['lon'] obj.update({ 'sign': const.LIST_SIGNS[int(lon / 30)], 'signlon': lon % 30 })
<SYSTEM_TASK:> Returns the ecliptic longitude of Pars Fortuna. <END_TASK> <USER_TASK:> Description: def pfLon(jd, lat, lon): """ Returns the ecliptic longitude of Pars Fortuna. It considers diurnal or nocturnal conditions. """
sun = swe.sweObjectLon(const.SUN, jd) moon = swe.sweObjectLon(const.MOON, jd) asc = swe.sweHousesLon(jd, lat, lon, const.HOUSES_DEFAULT)[1][0] if isDiurnal(jd, lat, lon): return angle.norm(asc + moon - sun) else: return angle.norm(asc + sun - moon)
<SYSTEM_TASK:> Returns true if the sun is above the horizon <END_TASK> <USER_TASK:> Description: def isDiurnal(jd, lat, lon): """ Returns true if the sun is above the horizon of a given date and location. """
sun = swe.sweObject(const.SUN, jd) mc = swe.sweHousesLon(jd, lat, lon, const.HOUSES_DEFAULT)[1][1] ra, decl = utils.eqCoords(sun['lon'], sun['lat']) mcRA, _ = utils.eqCoords(mc, 0.0) return utils.isAboveHorizon(ra, decl, mcRA, lat)
<SYSTEM_TASK:> Finds the latest new or full moon and <END_TASK> <USER_TASK:> Description: def syzygyJD(jd): """ Finds the latest new or full moon and returns the julian date of that event. """
sun = swe.sweObjectLon(const.SUN, jd) moon = swe.sweObjectLon(const.MOON, jd) dist = angle.distance(sun, moon) # Offset represents the Syzygy type. # Zero is conjunction and 180 is opposition. offset = 180 if (dist >= 180) else 0 while abs(dist) > MAX_ERROR: jd = jd - dist / 13.1833 # Moon mean daily motion sun = swe.sweObjectLon(const.SUN, jd) moon = swe.sweObjectLon(const.MOON, jd) dist = angle.closestdistance(sun - offset, moon) return jd
<SYSTEM_TASK:> Finds the julian date before or after <END_TASK> <USER_TASK:> Description: def solarReturnJD(jd, lon, forward=True): """ Finds the julian date before or after 'jd' when the sun is at longitude 'lon'. It searches forward by default. """
sun = swe.sweObjectLon(const.SUN, jd) if forward: dist = angle.distance(sun, lon) else: dist = -angle.distance(lon, sun) while abs(dist) > MAX_ERROR: jd = jd + dist / 0.9833 # Sun mean motion sun = swe.sweObjectLon(const.SUN, jd) dist = angle.closestdistance(sun, lon) return jd
<SYSTEM_TASK:> Finds the aproximate julian date of the <END_TASK> <USER_TASK:> Description: def nextStationJD(ID, jd): """ Finds the aproximate julian date of the next station of a planet. """
speed = swe.sweObject(ID, jd)['lonspeed'] for i in range(2000): nextjd = jd + i / 2 nextspeed = swe.sweObject(ID, nextjd)['lonspeed'] if speed * nextspeed <= 0: return nextjd return None
<SYSTEM_TASK:> Removes all python cache files recursively on a path. <END_TASK> <USER_TASK:> Description: def clean_caches(path): """ Removes all python cache files recursively on a path. :param path: the path :return: None """
for dirname, subdirlist, filelist in os.walk(path): for f in filelist: if f.endswith('pyc'): try: os.remove(os.path.join(dirname, f)) except FileNotFoundError: pass if dirname.endswith('__pycache__'): shutil.rmtree(dirname)
<SYSTEM_TASK:> Returns a list with the orb and angular <END_TASK> <USER_TASK:> Description: def _orbList(obj1, obj2, aspList): """ Returns a list with the orb and angular distances from obj1 to obj2, considering a list of possible aspects. """
sep = angle.closestdistance(obj1.lon, obj2.lon) absSep = abs(sep) return [ { 'type': asp, 'orb': abs(absSep - asp), 'separation': sep, } for asp in aspList ]
<SYSTEM_TASK:> Returns the properties of an aspect between <END_TASK> <USER_TASK:> Description: def _aspectProperties(obj1, obj2, aspDict): """ Returns the properties of an aspect between obj1 and obj2, given by 'aspDict'. This function assumes obj1 to be the active object, i.e., the one responsible for starting the aspect. """
orb = aspDict['orb'] asp = aspDict['type'] sep = aspDict['separation'] # Properties prop1 = { 'id': obj1.id, 'inOrb': False, 'movement': const.NO_MOVEMENT } prop2 = { 'id': obj2.id, 'inOrb': False, 'movement': const.NO_MOVEMENT } prop = { 'type': asp, 'orb': orb, 'direction': -1, 'condition': -1, 'active': prop1, 'passive': prop2 } if asp == const.NO_ASPECT: return prop # Aspect within orb prop1['inOrb'] = orb <= obj1.orb() prop2['inOrb'] = orb <= obj2.orb() # Direction prop['direction'] = const.DEXTER if sep <= 0 else const.SINISTER # Sign conditions # Note: if obj1 is before obj2, orbDir will be less than zero orbDir = sep-asp if sep >= 0 else sep+asp offset = obj1.signlon + orbDir if 0 <= offset < 30: prop['condition'] = const.ASSOCIATE else: prop['condition'] = const.DISSOCIATE # Movement of the individual objects if abs(orbDir) < MAX_EXACT_ORB: prop1['movement'] = prop2['movement'] = const.EXACT else: # Active object applies to Passive if it is before # and direct, or after the Passive and Rx.. prop1['movement'] = const.SEPARATIVE if (orbDir > 0 and obj1.isDirect()) or \ (orbDir < 0 and obj1.isRetrograde()): prop1['movement'] = const.APPLICATIVE elif obj1.isStationary(): prop1['movement'] = const.STATIONARY # The Passive applies or separates from the Active # if it has a different direction.. # Note: Non-planets have zero speed prop2['movement'] = const.NO_MOVEMENT obj2speed = obj2.lonspeed if obj2.isPlanet() else 0.0 sameDir = obj1.lonspeed * obj2speed >= 0 if not sameDir: prop2['movement'] = prop1['movement'] return prop
<SYSTEM_TASK:> Returns which is the active and the passive objects. <END_TASK> <USER_TASK:> Description: def _getActivePassive(obj1, obj2): """ Returns which is the active and the passive objects. """
speed1 = abs(obj1.lonspeed) if obj1.isPlanet() else -1.0 speed2 = abs(obj2.lonspeed) if obj2.isPlanet() else -1.0 if speed1 > speed2: return { 'active': obj1, 'passive': obj2 } else: return { 'active': obj2, 'passive': obj1 }
<SYSTEM_TASK:> Returns the aspect type between objects considering <END_TASK> <USER_TASK:> Description: def aspectType(obj1, obj2, aspList): """ Returns the aspect type between objects considering a list of possible aspect types. """
ap = _getActivePassive(obj1, obj2) aspDict = _aspectDict(ap['active'], ap['passive'], aspList) return aspDict['type'] if aspDict else const.NO_ASPECT
<SYSTEM_TASK:> Returns if there is an aspect between objects <END_TASK> <USER_TASK:> Description: def hasAspect(obj1, obj2, aspList): """ Returns if there is an aspect between objects considering a list of possible aspect types. """
aspType = aspectType(obj1, obj2, aspList) return aspType != const.NO_ASPECT
<SYSTEM_TASK:> Returns if obj1 aspects obj2 within its orb, <END_TASK> <USER_TASK:> Description: def isAspecting(obj1, obj2, aspList): """ Returns if obj1 aspects obj2 within its orb, considering a list of possible aspect types. """
aspDict = _aspectDict(obj1, obj2, aspList) if aspDict: return aspDict['orb'] < obj1.orb() return False
<SYSTEM_TASK:> Returns an Aspect object for the aspect between two <END_TASK> <USER_TASK:> Description: def getAspect(obj1, obj2, aspList): """ Returns an Aspect object for the aspect between two objects considering a list of possible aspect types. """
ap = _getActivePassive(obj1, obj2) aspDict = _aspectDict(ap['active'], ap['passive'], aspList) if not aspDict: aspDict = { 'type': const.NO_ASPECT, 'orb': 0, 'separation': 0, } aspProp = _aspectProperties(ap['active'], ap['passive'], aspDict) return Aspect(aspProp)
<SYSTEM_TASK:> Returns the movement of this aspect. <END_TASK> <USER_TASK:> Description: def movement(self): """ Returns the movement of this aspect. The movement is the one of the active object, except if the active is separating but within less than 1 degree. """
mov = self.active.movement if self.orb < 1 and mov == const.SEPARATIVE: mov = const.EXACT return mov
<SYSTEM_TASK:> Returns the term for a sign and longitude. <END_TASK> <USER_TASK:> Description: def term(sign, lon): """ Returns the term for a sign and longitude. """
terms = TERMS[sign] for (ID, a, b) in terms: if (a <= lon < b): return ID return None
<SYSTEM_TASK:> Returns the face for a sign and longitude. <END_TASK> <USER_TASK:> Description: def face(sign, lon): """ Returns the face for a sign and longitude. """
faces = FACES[sign] if lon < 10: return faces[0] elif lon < 20: return faces[1] else: return faces[2]
<SYSTEM_TASK:> Returns the complete essential dignities <END_TASK> <USER_TASK:> Description: def getInfo(sign, lon): """ Returns the complete essential dignities for a sign and longitude. """
return { 'ruler': ruler(sign), 'exalt': exalt(sign), 'dayTrip': dayTrip(sign), 'nightTrip': nightTrip(sign), 'partTrip': partTrip(sign), 'term': term(sign, lon), 'face': face(sign, lon), 'exile': exile(sign), 'fall': fall(sign) }
<SYSTEM_TASK:> Returns if an object is peregrine <END_TASK> <USER_TASK:> Description: def isPeregrine(ID, sign, lon): """ Returns if an object is peregrine on a sign and longitude. """
info = getInfo(sign, lon) for dign, objID in info.items(): if dign not in ['exile', 'fall'] and ID == objID: return False return True
<SYSTEM_TASK:> Returns the score of an object on <END_TASK> <USER_TASK:> Description: def score(ID, sign, lon): """ Returns the score of an object on a sign and longitude. """
info = getInfo(sign, lon) dignities = [dign for (dign, objID) in info.items() if objID == ID] return sum([SCORES[dign] for dign in dignities])
<SYSTEM_TASK:> Returns the almutem for a given <END_TASK> <USER_TASK:> Description: def almutem(sign, lon): """ Returns the almutem for a given sign and longitude. """
planets = const.LIST_SEVEN_PLANETS res = [None, 0] for ID in planets: sc = score(ID, sign, lon) if sc > res[1]: res = [ID, sc] return res[0]
<SYSTEM_TASK:> Returns the dignities belonging to this object. <END_TASK> <USER_TASK:> Description: def getDignities(self): """ Returns the dignities belonging to this object. """
info = self.getInfo() dignities = [dign for (dign, objID) in info.items() if objID == self.obj.id] return dignities
<SYSTEM_TASK:> Returns if this object is peregrine. <END_TASK> <USER_TASK:> Description: def isPeregrine(self): """ Returns if this object is peregrine. """
return isPeregrine(self.obj.id, self.obj.sign, self.obj.signlon)
<SYSTEM_TASK:> Internal function to return a new chart for <END_TASK> <USER_TASK:> Description: def _computeChart(chart, date): """ Internal function to return a new chart for a specific date using properties from old chart. """
pos = chart.pos hsys = chart.hsys IDs = [obj.id for obj in chart.objects] return Chart(date, pos, IDs=IDs, hsys=hsys)
<SYSTEM_TASK:> Returns the index of a date in the table. <END_TASK> <USER_TASK:> Description: def index(self, date): """ Returns the index of a date in the table. """
for (i, (start, end, ruler)) in enumerate(self.table): if start <= date.jd <= end: return i return None
<SYSTEM_TASK:> Returns a profection chart for a given <END_TASK> <USER_TASK:> Description: def compute(chart, date, fixedObjects=False): """ Returns a profection chart for a given date. Receives argument 'fixedObjects' to fix chart objects in their natal locations. """
sun = chart.getObject(const.SUN) prevSr = ephem.prevSolarReturn(date, sun.lon) nextSr = ephem.nextSolarReturn(date, sun.lon) # In one year, rotate chart 30º rotation = 30 * (date.jd - prevSr.jd) / (nextSr.jd - prevSr.jd) # Include 30º for each previous year age = math.floor((date.jd - chart.date.jd) / 365.25) rotation = 30 * age + rotation # Create a copy of the chart and rotate content pChart = chart.copy() for obj in pChart.objects: if not fixedObjects: obj.relocate(obj.lon + rotation) for house in pChart.houses: house.relocate(house.lon + rotation) for angle in pChart.angles: angle.relocate(angle.lon + rotation) return pChart
<SYSTEM_TASK:> Merges two list of objects removing <END_TASK> <USER_TASK:> Description: def _merge(listA, listB): """ Merges two list of objects removing repetitions. """
listA = [x.id for x in listA] listB = [x.id for x in listB] listA.extend(listB) set_ = set(listA) return list(set_)
<SYSTEM_TASK:> Returns a list with the absolute longitude <END_TASK> <USER_TASK:> Description: def termLons(TERMS): """ Returns a list with the absolute longitude of all terms. """
res = [] for i, sign in enumerate(SIGN_LIST): termList = TERMS[sign] res.extend([ ID, sign, start + 30 * i, ] for (ID, start, end) in termList) return res
<SYSTEM_TASK:> Gets the details for one or more resources by ID <END_TASK> <USER_TASK:> Description: def get(self, resource_id=None, resource_action=None, resource_cls=None, single_resource=False): """ Gets the details for one or more resources by ID Args: cls - gophish.models.Model - The resource class resource_id - str - The endpoint (URL path) for the resource resource_action - str - An action to perform on the resource resource_cls - cls - A class to use for parsing, if different than the base resource single_resource - bool - An override to tell Gophish that even though we aren't requesting a single resource, we expect a single response object Returns: One or more instances of cls parsed from the returned JSON """
endpoint = self.endpoint if not resource_cls: resource_cls = self._cls if resource_id: endpoint = self._build_url(endpoint, resource_id) if resource_action: endpoint = self._build_url(endpoint, resource_action) response = self.api.execute("GET", endpoint) if not response.ok: raise Error.parse(response.json()) if resource_id or single_resource: return resource_cls.parse(response.json()) return [resource_cls.parse(resource) for resource in response.json()]
<SYSTEM_TASK:> Returns a dict representation of the resource <END_TASK> <USER_TASK:> Description: def as_dict(self): """ Returns a dict representation of the resource """
result = {} for key in self._valid_properties: val = getattr(self, key) if isinstance(val, datetime): val = val.isoformat() # Parse custom classes elif val and not Model._is_builtin(val): val = val.as_dict() # Parse lists of objects elif isinstance(val, list): # We only want to call as_dict in the case where the item # isn't a builtin type. for i in range(len(val)): if Model._is_builtin(val[i]): continue val[i] = val[i].as_dict() # If it's a boolean, add it regardless of the value elif isinstance(val, bool): result[key] = val # Add it if it's not None if val: result[key] = val return result
<SYSTEM_TASK:> Executes a request to a given endpoint, returning the result <END_TASK> <USER_TASK:> Description: def execute(self, method, path, **kwargs): """ Executes a request to a given endpoint, returning the result """
url = "{}{}".format(self.host, path) kwargs.update(self._client_kwargs) response = requests.request( method, url, headers={"Authorization": "Bearer {}".format(self.api_key)}, **kwargs) return response
<SYSTEM_TASK:> Returns just the results for a given campaign <END_TASK> <USER_TASK:> Description: def results(self, campaign_id): """ Returns just the results for a given campaign """
return super(API, self).get( resource_id=campaign_id, resource_action='results', resource_cls=CampaignResults)
<SYSTEM_TASK:> Set the path of the database. <END_TASK> <USER_TASK:> Description: def set_path(self, file_path): """ Set the path of the database. Create the file if it does not exist. """
if not file_path: self.read_data = self.memory_read self.write_data = self.memory_write elif not is_valid(file_path): self.write_data(file_path, {}) self.path = file_path
<SYSTEM_TASK:> Removes the specified key from the database. <END_TASK> <USER_TASK:> Description: def delete(self, key): """ Removes the specified key from the database. """
obj = self._get_content() obj.pop(key, None) self.write_data(self.path, obj)
<SYSTEM_TASK:> If a key is passed in, a corresponding value will be returned. <END_TASK> <USER_TASK:> Description: def data(self, **kwargs): """ If a key is passed in, a corresponding value will be returned. If a key-value pair is passed in then the corresponding key in the database will be set to the specified value. A dictionary can be passed in as well. If a key does not exist and a value is provided then an entry will be created in the database. """
key = kwargs.pop('key', None) value = kwargs.pop('value', None) dictionary = kwargs.pop('dictionary', None) # Fail if a key and a dictionary or a value and a dictionary are given if (key is not None and dictionary is not None) or \ (value is not None and dictionary is not None): raise ValueError # If only a key was provided return the corresponding value if key is not None and value is None: return self._get_content(key) # if a key and a value are passed in if key is not None and value is not None: self._set_content(key, value) if dictionary is not None: for key in dictionary.keys(): value = dictionary[key] self._set_content(key, value) return self._get_content()
<SYSTEM_TASK:> Takes a dictionary of filter parameters. <END_TASK> <USER_TASK:> Description: def filter(self, filter_arguments): """ Takes a dictionary of filter parameters. Return a list of objects based on a list of parameters. """
results = self._get_content() # Filter based on a dictionary of search parameters if isinstance(filter_arguments, dict): for item, content in iteritems(self._get_content()): for key, value in iteritems(filter_arguments): keys = key.split('.') value = filter_arguments[key] if not self._contains_value({item: content}, keys, value): del results[item] # Filter based on an input string that should match database key if isinstance(filter_arguments, str): if filter_arguments in results: return [{filter_arguments: results[filter_arguments]}] else: return [] return results
<SYSTEM_TASK:> Remove the database by deleting the JSON file. <END_TASK> <USER_TASK:> Description: def drop(self): """ Remove the database by deleting the JSON file. """
import os if self.path: if os.path.exists(self.path): os.remove(self.path) else: # Clear the in-memory data if there is no file path self._data = {}
<SYSTEM_TASK:> Reads a file and returns a json encoded representation of the file. <END_TASK> <USER_TASK:> Description: def read_data(file_path): """ Reads a file and returns a json encoded representation of the file. """
if not is_valid(file_path): write_data(file_path, {}) db = open_file_for_reading(file_path) content = db.read() obj = decode(content) db.close() return obj
<SYSTEM_TASK:> Writes to a file and returns the updated file content. <END_TASK> <USER_TASK:> Description: def write_data(path, obj): """ Writes to a file and returns the updated file content. """
with open_file_for_writing(path) as db: db.write(encode(obj)) return obj
<SYSTEM_TASK:> Check to see if a file exists or is empty. <END_TASK> <USER_TASK:> Description: def is_valid(file_path): """ Check to see if a file exists or is empty. """
from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(file_path) and is_file and stat(file_path).st_size > 0
<SYSTEM_TASK:> Perform a contract on a number of jobs and block until a result is <END_TASK> <USER_TASK:> Description: def contract(self, jobs, result): """ Perform a contract on a number of jobs and block until a result is retrieved for each job. """
for j in jobs: WorkerPool.put(self, j) r = [] for i in xrange(len(jobs)): r.append(result.get()) return r
<SYSTEM_TASK:> Open a web browser pointing to geojson.io with the specified content. <END_TASK> <USER_TASK:> Description: def display(contents, domain=DEFAULT_DOMAIN, force_gist=False): """ Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the content is small, this step is not needed as the data can be included in the URL Parameters ---------- content - (see make_geojson) domain - string, default http://geojson.io force_gist - bool, default False Create an anonymous gist on Github regardless of the size of the contents """
url = make_url(contents, domain, force_gist) webbrowser.open(url) return url
<SYSTEM_TASK:> Returns the URL to open given the domain and contents. <END_TASK> <USER_TASK:> Description: def make_url(contents, domain=DEFAULT_DOMAIN, force_gist=False, size_for_gist=MAX_URL_LEN): """ Returns the URL to open given the domain and contents. If the file contents are large, an anonymous gist will be created. Parameters ---------- contents * string - assumed to be GeoJSON * an object that implements __geo_interface__ A FeatureCollection will be constructed with one feature, the object. * a sequence of objects that each implement __geo_interface__ A FeatureCollection will be constructed with the objects as the features domain - string, default http://geojson.io force_gist - force gist creation regardless of file size. For more information about __geo_interface__ see: https://gist.github.com/sgillies/2217756 If the contents are large, then a gist will be created. """
contents = make_geojson(contents) if len(contents) <= size_for_gist and not force_gist: url = data_url(contents, domain) else: gist = _make_gist(contents) url = gist_url(gist.id, domain) return url
<SYSTEM_TASK:> Return a GeoJSON string from a variety of inputs. <END_TASK> <USER_TASK:> Description: def make_geojson(contents): """ Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string """
if isinstance(contents, six.string_types): return contents if hasattr(contents, '__geo_interface__'): features = [_geo_to_feature(contents)] else: try: feature_iter = iter(contents) except TypeError: raise ValueError('Unknown type for input') features = [] for i, f in enumerate(feature_iter): if not hasattr(f, '__geo_interface__'): raise ValueError('Unknown type at index {0}'.format(i)) features.append(_geo_to_feature(f)) data = {'type': 'FeatureCollection', 'features': features} return json.dumps(data)
<SYSTEM_TASK:> Create and return an anonymous gist with a single file and specified <END_TASK> <USER_TASK:> Description: def _make_gist(contents, description='', filename='data.geojson'): """ Create and return an anonymous gist with a single file and specified contents """
ghapi = github3.GitHub() files = {filename: {'content': contents}} gist = ghapi.create_gist(description, files) return gist
<SYSTEM_TASK:> Clenshaw's algorithm for evaluating <END_TASK> <USER_TASK:> Description: def clenshaw(a, alpha, beta, t): """Clenshaw's algorithm for evaluating S(t) = \\sum a_k P_k(alpha, beta)(t) where P_k(alpha, beta) is the kth orthogonal polynomial defined by the recurrence coefficients alpha, beta. See <https://en.wikipedia.org/wiki/Clenshaw_algorithm> for details. """
n = len(alpha) assert len(beta) == n assert len(a) == n + 1 try: b = numpy.empty((n + 1,) + t.shape) except AttributeError: # 'float' object has no attribute 'shape' b = numpy.empty(n + 1) # b[0] is unused, can be any value # TODO shift the array b[0] = 1.0 b[n] = a[n] b[n - 1] = a[n - 1] + (t - alpha[n - 1]) * b[n] for k in range(n - 2, 0, -1): b[k] = a[k] + (t - alpha[k]) * b[k + 1] - beta[k + 1] * b[k + 2] phi0 = 1.0 phi1 = t - alpha[0] return phi0 * a[0] + phi1 * b[1] - beta[1] * phi0 * b[2]
<SYSTEM_TASK:> Recurrence coefficients for generalized Laguerre polynomials. <END_TASK> <USER_TASK:> Description: def recurrence_coefficients(n, alpha, standardization="normal", symbolic=False): """Recurrence coefficients for generalized Laguerre polynomials. vals_k = vals_{k-1} * (t*a_k - b_k) - vals{k-2} * c_k """
S = sympy.S if symbolic else lambda x: x sqrt = sympy.sqrt if symbolic else numpy.sqrt gamma = sympy.gamma if symbolic else scipy.special.gamma if standardization == "monic": p0 = 1 a = n * [1] b = [2 * k + 1 + alpha for k in range(n)] c = [k * (k + alpha) for k in range(n)] c[0] = gamma(alpha + 1) elif standardization == "classical": p0 = 1 a = [-S(1) / (k + 1) for k in range(n)] b = [-S(2 * k + 1 + alpha) / (k + 1) for k in range(n)] c = [S(k + alpha) / (k + 1) for k in range(n)] c[0] = numpy.nan else: assert ( standardization == "normal" ), "Unknown Laguerre standardization '{}'.".format( standardization ) p0 = 1 / sqrt(gamma(alpha + 1)) a = [-1 / sqrt((k + 1) * (k + 1 + alpha)) for k in range(n)] b = [-(2 * k + 1 + alpha) / sqrt((k + 1) * (k + 1 + alpha)) for k in range(n)] c = [sqrt(k * S(k + alpha) / ((k + 1) * (k + 1 + alpha))) for k in range(n)] c[0] = numpy.nan return p0, numpy.array(a), numpy.array(b), numpy.array(c)
<SYSTEM_TASK:> Evaluates the entire tree of orthogonal polynomials for the n-cube <END_TASK> <USER_TASK:> Description: def tree(X, n, symbolic=False): """Evaluates the entire tree of orthogonal polynomials for the n-cube The computation is organized such that tree returns a list of arrays, L={0, ..., dim}, where each level corresponds to the polynomial degree L. Further, each level is organized like a discrete (dim-1)-dimensional simplex. Let's demonstrate this for 3D: L = 1: (0, 0, 0) L = 2: (1, 0, 0) (0, 1, 0) (0, 0, 1) L = 3: (2, 0, 0) (1, 1, 0) (1, 0, 1) (0, 2, 0) (0, 1, 1) (0, 0, 2) The main insight here that makes computation for n dimensions easy is that the next level is composed by: * Taking the whole previous level and adding +1 to the first entry. * Taking the last row of the previous level and adding +1 to the second entry. * Taking the last entry of the last row of the previous and adding +1 to the third entry. In the same manner this can be repeated for `dim` dimensions. """
p0, a, b, c = legendre(n + 1, "normal", symbolic=symbolic) dim = X.shape[0] p0n = p0 ** dim out = [] level = numpy.array([numpy.ones(X.shape[1:], dtype=int) * p0n]) out.append(level) # TODO use a simpler binom implementation for L in range(n): level = [] for i in range(dim - 1): m1 = int(scipy.special.binom(L + dim - i - 1, dim - i - 1)) if L > 0: m2 = int(scipy.special.binom(L + dim - i - 2, dim - i - 1)) r = 0 for k in range(L + 1): m = int(scipy.special.binom(k + dim - i - 2, dim - i - 2)) val = out[L][-m1:][r : r + m] * (a[L - k] * X[i] - b[L - k]) if L - k > 0: val -= out[L - 1][-m2:][r : r + m] * c[L - k] r += m level.append(val) # treat the last one separately val = out[L][-1] * (a[L] * X[-1] - b[L]) if L > 0: val -= out[L - 1][-1] * c[L] level.append([val]) out.append(numpy.concatenate(level)) return out
<SYSTEM_TASK:> Case-insensitive search for `key` within keys of `lookup_dict`. <END_TASK> <USER_TASK:> Description: def _iget(key, lookup_dict): """ Case-insensitive search for `key` within keys of `lookup_dict`. """
for k, v in lookup_dict.items(): if k.lower() == key.lower(): return v return None
<SYSTEM_TASK:> Write a function `f` defined in terms of spherical coordinates to a file. <END_TASK> <USER_TASK:> Description: def write(filename, f): """Write a function `f` defined in terms of spherical coordinates to a file. """
import meshio import meshzoo points, cells = meshzoo.iso_sphere(5) # get spherical coordinates from points polar = numpy.arccos(points[:, 2]) azimuthal = numpy.arctan2(points[:, 1], points[:, 0]) vals = f(polar, azimuthal) meshio.write(filename, points, {"triangle": cells}, point_data={"f": vals}) return