Instruction:
Can you generate a brief explanation for the following Python 3 code
def _terms(self):
        res = []
        for sign, terms in self.terms.items():
            for ID, lon in terms.items():
                res.append(self.T(ID, sign))
        return res

Response: Returns a list with the objects as terms.


Instruction:
How would you implement a function in Python 3 that
returns a sorted list with all the primary directions. Arcs and significators are returned.

Response:
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)


Instruction:
Write a Python 3 script for
returning the directions within the arcmin and arcmax arcs.

Response:
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


Instruction:
Create a Python 3 function for
returning all directions to a significator.

Response:
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


Instruction:
Can you generate the documentation for the following Python 3 function
def byPromissor(self, ID):
        res = []
        for direction in self.table:
            if ID in direction[1]:
                res.append(direction)
        return res

Response: Returns all directions to a promissor.


Instruction:
Create a Python 3 function for
returning a deep copy of this chart.

Response:
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


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get(self, ID):
        if ID.startswith('House'):
            return self.getHouse(ID)
        elif ID in const.LIST_ANGLES:
            return self.getAngle(ID)
        else:
            return self.getObject(ID)

Response:
Returns an object house or angle
        from the chart.


Instruction:
Make a summary of the following Python 3 code
def getFixedStars(self):
        IDs = const.LIST_FIXED_STARS
        return ephem.getFixedStarList(IDs, self.date)

Response: Returns a list with all fixed stars.


Instruction:
Can you generate the documentation for the following Python 3 function
def isHouse1Asc(self):
        house1 = self.getHouse(const.HOUSE1)
        asc = self.getAngle(const.ASC)
        dist = angle.closestdistance(house1.lon, asc.lon)
        return abs(dist) < 0.0003

Response: Returns true if House1 is the same as Asc.


Instruction:
Implement a Python 3 function for
returning true if House10 is the same as the MC.

Response:
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


Instruction:
Implement a Python 3 function for
returning true if this chart is diurnal.

Response:
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)


Instruction:
How would you explain what the following Python 3 function does
def getMoonPhase(self):
        sun = self.getObject(const.SUN)
        moon = self.getObject(const.MOON)
        dist = angle.distance(sun.lon, moon.lon)
        if dist < 90:
            return const.MOON_FIRST_QUARTER
        elif dist < 180:
            return const.MOON_SECOND_QUARTER
        elif dist < 270:
            return const.MOON_THIRD_QUARTER
        else:
            return const.MOON_LAST_QUARTER

Response: Returns the phase of the moon.


Instruction:
Here you have a function in Python 3, explain what it does
def solarReturn(self, 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)

Response:
Returns this chart s solar return for a
        given year.


Instruction:
How would you code a function in Python 3 to
return the longitude of an object.

Response:
def objLon(ID, chart):
    """ Returns the longitude of an object. """
    if ID.startswith('$R'):
        # Return Ruler
        ID = ID[2:]
        obj = chart.get(ID)
        rulerID = essential.ruler(obj.sign)
        ruler = chart.getObject(rulerID)
        return ruler.lon
    elif ID.startswith('Pars'):
        # Return an arabic part
        return partLon(ID, chart)
    else:
        # Return an object
        obj = chart.get(ID)
        return obj.lon


Instruction:
Write a Python 3 function that can
return the longitude of an arabic part.

Response:
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


Instruction:
Make a summary of the following Python 3 code
def getPart(ID, chart):
    obj = GenericObject()
    obj.id = ID
    obj.type = const.OBJ_ARABIC_PART
    obj.relocate(partLon(ID, chart))
    return obj

Response: Returns an Arabic Part.


Instruction:
Can you implement a function in Python 3 that
returns an object from the Ephemeris.

Response:
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]
    }


Instruction:
Can you tell what is the following Python 3 function doing
def sweObjectLon(obj, jd):
    sweObj = SWE_OBJECTS[obj]
    sweList = swisseph.calc_ut(jd, sweObj)
    return sweList[0]

Response: Returns the longitude of an object in the given JD.


Instruction:
Can you create a Python 3 function that
returns the julian date of the next transit of the object.

Response:
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]


Instruction:
Write a Python 3 script for
returning a list of lists of houses and angles.

Response:
def sweHouses(jd, lat, lon, hsys):
    """ Returns lists of houses and angles. """
    hsys = SWE_HOUSESYS[hsys]
    hlist, ascmc = swisseph.houses(jd, lat, lon, hsys)
    # Add first house to the end of 'hlist' so that we
    # can compute house sizes with an iterator
    hlist += (hlist[0],)
    houses = [
        {
            'id': const.LIST_HOUSES[i],
            'lon': hlist[i],
            'size': angle.distance(hlist[i], hlist[i+1])
        } for i in range(12)
    ]
    angles = [
        {'id': const.ASC, 'lon': ascmc[0]},
        {'id': const.MC, 'lon': ascmc[1]},
        {'id': const.DESC, 'lon': angle.norm(ascmc[0] + 180)},
        {'id': const.IC, 'lon': angle.norm(ascmc[1] + 180)}
    ]
    return (houses, angles)


Instruction:
Write a Python 3 script to
return lists with house and angle longitudes.

Response:
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)


Instruction:
Write a Python 3 script to
return a fixed star from the Ephemeris.

Response:
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]
    }


Instruction:
Implement a function in Python 3 to
return the jd details of the previous or next global solar eclipse.

Response:
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],
    }


Instruction:
Make a summary of the following Python 3 code
def lunarEclipseGlobal(jd, backward):

    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],
    }

Response: Returns the jd details of the previous or next global lunar eclipse.


Instruction:
Create a Python 3 function to
convert date to Julian Day Number.

Response:
def dateJDN(year, month, day, calendar):
    """ Converts date to Julian Day Number. """
    a = (14 - month) // 12
    y = year + 4800 - a
    m = month + 12*a - 3
    if calendar == GREGORIAN:
        return day + (153*m + 2)//5 + 365*y + y//4 - y//100 + y//400 - 32045
    else:
        return day + (153*m + 2)//5 + 365*y + y//4 - 32083


Instruction:
How would you implement a function in Python 3 that
converts Julian Day Number to Gregorian date.

Response:
def jdnDate(jdn):
    """ Converts Julian Day Number to Gregorian date. """
    a = jdn + 32044
    b = (4*a + 3) // 146097
    c = a - (146097*b) // 4
    d = (4*c + 3) // 1461
    e = c - (1461*d) // 4
    m = (5*e + 2) // 153
    day = e + 1 - (153*m + 2) // 5
    month = m + 3 - 12*(m//10)
    year = 100*b + d - 4800 + m//10
    return [year, month, day]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def toList(self):
        date = self.date()
        sign = '+' if date[0] >= 0 else '-'
        date[0] = abs(date[0])
        return list(sign) + date

Response: Returns date as signed list.


Instruction:
Write a Python 3 script for
returning a string representation of the current time entry.

Response:
def toString(self):
        """ Returns date as string. """
        slist = self.toList()
        sign = '' if slist[0] == '+' else '-'
        string = '/'.join(['%02d' % v for v in slist[1:]])
        return sign + string


Instruction:
Explain what the following Python 3 code does
def getUTC(self, utcoffset):
        newTime = (self.value - utcoffset.value) % 24
        return Time(newTime)

Response:
Returns a new Time object set to UTC given
        an offset Time object.


Instruction:
Implement a function in Python 3 to
return time as list [ hh mm ss ]

Response:
def time(self):
        """ Returns time as list [hh,mm,ss]. """
        slist = self.toList()
        if slist[0] == '-':
            slist[1] *= -1
            # We must do a trick if we want to
            # make negative zeros explicit
            if slist[1] == -0:
                slist[1] = -0.0
        return slist[1:]


Instruction:
Implement a function in Python 3 to
return time as signed list.

Response:
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


Instruction:
Create a Python 3 function to
return time as string.

Response:
def toString(self):
        """ Returns time as string. """
        slist = self.toList()
        string = angle.slistStr(slist)
        return string if slist[0] == '-' else string[1:]


Instruction:
How would you code a function in Python 3 to
build a Datetime object given a jd and utc offset.

Response:
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)


Instruction:
How would you code a function in Python 3 to
return this Datetime localized for UTC.

Response:
def getUTC(self):
        """ Returns this Datetime localized for UTC. """
        timeUTC = self.time.getUTC(self.utcoffset)
        dateUTC = Date(round(self.jd))
        return Datetime(dateUTC, timeUTC)


Instruction:
How would you implement a function in Python 3 that
returns an object for a specific date and location.

Response:
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


Instruction:
Explain what the following Python 3 code does
def getHouses(jd, lat, lon, hsys):
    houses, angles = swe.sweHouses(jd, lat, lon, hsys)
    for house in houses:
        _signInfo(house)
    for angle in angles:
        _signInfo(angle)
    return (houses, angles)

Response: Returns a list of lists of houses and angles.


Instruction:
Create a Python 3 function for
returning a fixed star.

Response:
def getFixedStar(ID, jd):
    """ Returns a fixed star. """
    star = swe.sweFixedStar(ID, jd)
    _signInfo(star)
    return star


Instruction:
Write a Python 3 function for
returning the JD of the next sunrise.

Response:
def nextSunrise(jd, lat, lon):
    """ Returns the JD of the next sunrise. """
    return swe.sweNextTransit(const.SUN, jd, lat, lon, 'RISE')


Instruction:
Implement a Python 3 function for
returning the JD of the next sunset

Response:
def nextSunset(jd, lat, lon):
    """ Returns the JD of the next sunset. """
    return swe.sweNextTransit(const.SUN, jd, lat, lon, 'SET')


Instruction:
Can you implement a function in Python 3 that
adds the sign id and longitude to an object.

Response:
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
    })


Instruction:
Explain what the following Python 3 code does
def pfLon(jd, lat, lon):
    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)

Response: Returns the ecliptic longitude of Pars Fortuna.


Instruction:
Can you write a function in Python 3 where it
returns true if the sun is above the horizon of a given date and location.

Response:
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)


Instruction:
Write a Python 3 script to
find the latest new or full moon and returns the julian date of that event.

Response:
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


Instruction:
How would you implement a function in Python 3 that
finds the julian date before or after jd when the sun is at longitude lon.

Response:
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


Instruction:
Can you generate a brief explanation for the following Python 3 code
def nextStationJD(ID, jd):
    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

Response: Finds the aproximate julian date of the next station of a planet. Returns None if no next station is found.


Instruction:
Can you tell what is the following Python 3 function doing
def clean_caches(path):

    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)

Response: Removes all python cache files recursively on a path.


Instruction:
Make a summary of the following Python 3 code
def clean_py_files(path):

    for dirname, subdirlist, filelist in os.walk(path):

        for f in filelist:
            if f.endswith('py'):
                os.remove(os.path.join(dirname, f))

Response: Removes all. py files in the path.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def toFloat(value):
    if isinstance(value, str):
        # Find lat/lon char in string and insert angle sign
        value = value.upper()
        for char in ['N', 'S', 'E', 'W']:
            if char in value:
                value = SIGN[char] + value.replace(char, ':')
                break
    return angle.toFloat(value)

Response:
Converts angle representation to float.
    Accepts strings such as 12W30 : 00.


Instruction:
Create a Python 3 function for
converting a float to a string.

Response:
def toString(value, mode):
    """ Converts angle float to string.
    Mode refers to LAT/LON.

    """
    string = angle.toString(value)
    sign = string[0]
    separator = CHAR[mode][sign]
    string = string.replace(':', separator, 1)
    return string[1:]


Instruction:
Can you create a Python 3 function that
returns lat / lon as strings.

Response:
def strings(self):
        """ Return lat/lon as strings. """
        return [
            toString(self.lat, LAT),
            toString(self.lon, LON)
        ]


Instruction:
How would you code a function in Python 3 to
return a list with the orb and angular distances from obj1 to obj2 considering a list of possible aspects.

Response:
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
    ]


Instruction:
Can you tell what is the following Python 3 function doing
def _aspectDict(obj1, obj2, aspList):
    # Ignore aspects from same and Syzygy
    if obj1 == obj2 or obj1.id == const.SYZYGY:
        return None

    orbs = _orbList(obj1, obj2, aspList)
    for aspDict in orbs:
        asp = aspDict['type']
        orb = aspDict['orb']

        # Check if aspect is within orb
        if asp in const.MAJOR_ASPECTS:
            # Ignore major aspects out of orb
            if obj1.orb() < orb and obj2.orb() < orb:
                continue
        else:
            # Ignore minor aspects out of max orb
            if MAX_MINOR_ASP_ORB < orb:
                continue

        # Only conjunctions for Pars Fortuna and Nodes
        if obj1.id in [const.PARS_FORTUNA,
                       const.NORTH_NODE,
                       const.SOUTH_NODE] and \
                asp != const.CONJUNCTION:
            continue

        # We have a valid aspect within orb
        return aspDict

    return None

Response:
Returns the properties of the aspect of
    obj1 to obj2 considering a list of possible aspects.


Instruction:
Can you implement a function in Python 3 that
returns the properties of an aspect between obj1 and obj2 given by aspDict.

Response:
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


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _getActivePassive(obj1, obj2):
    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
        }

Response: Returns which is the active and the passive objects.


Instruction:
Implement a function in Python 3 to
return the aspect type between objects considering a list of possible aspect types.

Response:
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


Instruction:
Make a summary of the following Python 3 code
def hasAspect(obj1, obj2, aspList):
    aspType = aspectType(obj1, obj2, aspList)
    return aspType != const.NO_ASPECT

Response:
Returns True if there is an aspect between objects
    considering a list of possible aspect types.


Instruction:
Write a Python 3 function for
returning True if obj1 aspects obj2 within its orb considering a list of possible aspect types.

Response:
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


Instruction:
Given the following Python 3 function, write the documentation
def getAspect(obj1, obj2, aspList):
    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)

Response: Returns an Aspect object for the aspect between two objects considering a list of possible aspect types.


Instruction:
Can you write a function in Python 3 where it
returns the movement of this aspect.

Response:
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


Instruction:
Make a summary of the following Python 3 code
def getRole(self, ID):
        if self.active.id == ID:
            return {
                'role': 'active',
                'inOrb': self.active.inOrb,
                'movement': self.active.movement
            }
        elif self.passive.id == ID:
            return {
                'role': 'passive',
                'inOrb': self.passive.inOrb,
                'movement': self.passive.movement
            }
        return None

Response: Returns the role of an object in this aspect.


Instruction:
Write a Python 3 function for
setting the default faces for the given variant

Response:
def setFaces(variant):
    """
    Sets the default faces variant

    """
    global FACES
    if variant == CHALDEAN_FACES:
        FACES = tables.CHALDEAN_FACES
    else:
        FACES = tables.TRIPLICITY_FACES


Instruction:
Here you have a function in Python 3, explain what it does
def setTerms(variant):
    global TERMS
    if variant == EGYPTIAN_TERMS:
        TERMS = tables.EGYPTIAN_TERMS
    elif variant == TETRABIBLOS_TERMS:
        TERMS = tables.TETRABIBLOS_TERMS
    elif variant == LILLY_TERMS:
        TERMS = tables.LILLY_TERMS

Response:
Sets the default terms of the Dignities
    table.


Instruction:
Write a Python 3 function for
returning the term for a sign and longitude.

Response:
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


Instruction:
Create a Python 3 function to
return the face for a sign and longitude.

Response:
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]


Instruction:
Given the following Python 3 function, write the documentation
def getInfo(sign, lon):
    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)
    }

Response:
Returns the complete essential dignities
    for a sign and longitude.


Instruction:
Create a Python 3 function for
returning True if an object is peregrine on a sign and longitude.

Response:
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


Instruction:
Implement a Python 3 function for
returning the score of an object on a sign and longitude.

Response:
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])


Instruction:
Implement a function in Python 3 to
return the almutem for a given sign and longitude.

Response:
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]


Instruction:
How would you implement a function in Python 3 that
returns the dignities belonging to this object.

Response:
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


Instruction:
Given the following Python 3 function, write the documentation
def isPeregrine(self):
        return isPeregrine(self.obj.id,
                           self.obj.sign,
                           self.obj.signlon)

Response: Returns if this object is peregrine.


Instruction:
Write a Python 3 function that can
return the solar return of a Chart after a specific date.

Response:
def nextSolarReturn(chart, date):
    """ Returns the solar return of a Chart
    after a specific date.

    """
    sun = chart.getObject(const.SUN)
    srDate = ephem.nextSolarReturn(date, sun.lon)
    return _computeChart(chart, srDate)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def hourTable(date, pos):

    lastSunrise = ephem.lastSunrise(date, pos)
    middleSunset = ephem.nextSunset(lastSunrise, pos)
    nextSunrise = ephem.nextSunrise(date, pos)
    table = []

    # Create diurnal hour sequence
    length = (middleSunset.jd - lastSunrise.jd) / 12.0
    for i in range(12):
        start = lastSunrise.jd + i * length
        end = start + length
        ruler = nthRuler(i, lastSunrise.date.dayofweek())
        table.append([start, end, ruler])

    # Create nocturnal hour sequence
    length = (nextSunrise.jd - middleSunset.jd) / 12.0
    for i in range(12):
        start = middleSunset.jd + i * length
        end = start + length
        ruler = nthRuler(i + 12, lastSunrise.date.dayofweek())
        table.append([start, end, ruler])

    return table

Response:
Creates the planetary hour table for a date
    and position.


Instruction:
Can you generate the documentation for the following Python 3 function
def getHourTable(date, pos):
    table = hourTable(date, pos)
    return HourTable(table, date)

Response: Returns an HourTable object for the given date and position.


Instruction:
Given the following Python 3 function, write the documentation
def index(self, date):
        for (i, (start, end, ruler)) in enumerate(self.table):
            if start <= date.jd <= end:
                return i
        return None

Response: Returns the index of a date in the table.


Instruction:
Given the following Python 3 function, write the documentation
def indexInfo(self, index):
        entry = self.table[index]
        info = {
            # Default is diurnal
            'mode': 'Day',
            'ruler': self.dayRuler(),
            'dayRuler': self.dayRuler(),
            'nightRuler': self.nightRuler(),
            'hourRuler': entry[2],
            'hourNumber': index + 1,
            'tableIndex': index,
            'start': Datetime.fromJD(entry[0], self.date.utcoffset),
            'end': Datetime.fromJD(entry[1], self.date.utcoffset)
        }
        if index >= 12:
            # Set information as nocturnal
            info.update({
                'mode': 'Night',
                'ruler': info['nightRuler'],
                'hourNumber': index + 1 - 12
            })
        return info

Response:
Returns information about a specific
 planetary time.


Instruction:
Implement a Python 3 function for
computing a profection chart for a given date.

Response:
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


Instruction:
How would you implement a function in Python 3 that
merges two list of objects removing repetitions.

Response:
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_)


Instruction:
Implement a Python 3 function for
computing the behavior of the current object.

Response:
def compute(chart):
    """ Computes the behavior. """

    factors = []

    # Planets in House1 or Conjunct Asc
    house1 = chart.getHouse(const.HOUSE1)
    planetsHouse1 = chart.objects.getObjectsInHouse(house1)
    asc = chart.getAngle(const.ASC)
    planetsConjAsc = chart.objects.getObjectsAspecting(asc, [0])

    _set = _merge(planetsHouse1, planetsConjAsc)
    factors.append(['Planets in House1 or Conj Asc', _set])

    # Planets conjunct Moon or Mercury
    moon = chart.get(const.MOON)
    mercury = chart.get(const.MERCURY)
    planetsConjMoon = chart.objects.getObjectsAspecting(moon, [0])
    planetsConjMercury = chart.objects.getObjectsAspecting(mercury, [0])

    _set = _merge(planetsConjMoon, planetsConjMercury)
    factors.append(['Planets Conj Moon or Mercury', _set])

    # Asc ruler if aspected by disposer
    ascRulerID = essential.ruler(asc.sign)
    ascRuler = chart.getObject(ascRulerID)
    disposerID = essential.ruler(ascRuler.sign)
    disposer = chart.getObject(disposerID)

    _set = []
    if aspects.isAspecting(disposer, ascRuler, const.MAJOR_ASPECTS):
        _set = [ascRuler.id]
    factors.append(['Asc Ruler if aspected by its disposer', _set]);

    # Planets aspecting Moon or Mercury
    aspMoon = chart.objects.getObjectsAspecting(moon, [60,90,120,180])
    aspMercury = chart.objects.getObjectsAspecting(mercury, [60,90,120,180])

    _set = _merge(aspMoon, aspMercury)
    factors.append(['Planets Asp Moon or Mercury', _set])

    return factors


Instruction:
Explain what the following Python 3 code does
def termLons(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

Response:
Returns a list with the absolute longitude
    of all terms.


Instruction:
How would you implement a function in Python 3 that
computes the Almutem table.

Response:
def compute(chart):
    """ Computes the Almutem table. """
    almutems = {}

    # Hylegic points
    hylegic = [
        chart.getObject(const.SUN),
        chart.getObject(const.MOON),
        chart.getAngle(const.ASC),
        chart.getObject(const.PARS_FORTUNA),
        chart.getObject(const.SYZYGY)
    ]
    for hyleg in hylegic:
        row = newRow()
        digInfo = essential.getInfo(hyleg.sign, hyleg.signlon)

        # Add the scores of each planet where hyleg has dignities
        for dignity in DIGNITY_LIST:
            objID = digInfo[dignity]
            if objID:
                score = essential.SCORES[dignity]
                row[objID]['string'] += '+%s' % score
                row[objID]['score'] += score

        almutems[hyleg.id] = row

    # House positions
    row = newRow()
    for objID in OBJECT_LIST:
        obj = chart.getObject(objID)
        house = chart.houses.getObjectHouse(obj)
        score = HOUSE_SCORES[house.id]
        row[objID]['string'] = '+%s' % score
        row[objID]['score'] = score
    almutems['Houses'] = row

    # Planetary time
    row = newRow()
    table = planetarytime.getHourTable(chart.date, chart.pos)
    ruler = table.currRuler()
    hourRuler = table.hourRuler()
    row[ruler] = {
        'string': '+7',
        'score': 7
    }
    row[hourRuler] = {
        'string': '+6',
        'score': 6
    }
    almutems['Rulers'] = row;

    # Compute scores
    scores = newRow()
    for _property, _list in almutems.items():
        for objID, values in _list.items():
            scores[objID]['string'] += values['string']
            scores[objID]['score'] += values['score']
    almutems['Score'] = scores

    return almutems


Instruction:
Create a Python 3 function for
getting the details for one or more resources by ID.

Response:
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()]


Instruction:
Given the following Python 3 function, write the documentation
def post(self, resource):
        response = self.api.execute(
            "POST", self.endpoint, json=(resource.as_dict()))

        if not response.ok:
            raise Error.parse(response.json())

        return self._cls.parse(response.json())

Response: Creates a new instance of the resource.


Instruction:
Implement a function in Python 3 to
edit an existing resource instance

Response:
def put(self, resource):
        """ Edits an existing resource

        Args:
            resource - gophish.models.Model - The resource instance
        """

        endpoint = self.endpoint

        if resource.id:
            endpoint = self._build_url(endpoint, resource.id)

        response = self.api.execute("PUT", endpoint, json=resource.as_dict())

        if not response.ok:
            raise Error.parse(response.json())

        return self._cls.parse(response.json())


Instruction:
Given the following Python 3 function, write the documentation
def delete(self, resource_id):

        endpoint = '{}/{}'.format(self.endpoint, resource_id)

        response = self.api.execute("DELETE", endpoint)

        if not response.ok:
            raise Error.parse(response.json())

        return self._cls.parse(response.json())

Response: Deletes an existing resource in the cluster.


Instruction:
Explain what the following Python 3 code does
def as_dict(self):
        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

Response: Returns a dict representation of the resource.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def execute(self, method, path, **kwargs):

        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

Response: Executes a request to a given endpoint returning the response


Instruction:
How would you explain what the following Python 3 function does
def complete(self, campaign_id):

        return super(API, self).get(
            resource_id=campaign_id, resource_action='complete')

Response: Complete an existing campaign


Instruction:
Given the following Python 3 function, write the documentation
def summary(self, campaign_id=None):
        resource_cls = CampaignSummary
        single_resource = False

        if not campaign_id:
            resource_cls = CampaignSummaries
            single_resource = True

        return super(API, self).get(
            resource_id=campaign_id,
            resource_action='summary',
            resource_cls=resource_cls,
            single_resource=single_resource)

Response: Returns the summary of the current user s infrastructure.


Instruction:
How would you explain what the following Python 3 function does
def results(self, campaign_id):
        return super(API, self).get(
            resource_id=campaign_id,
            resource_action='results',
            resource_cls=CampaignResults)

Response: Returns just the results for a given campaign


Instruction:
Can you tell what is the following Python 3 function doing
def set_path(self, file_path):
        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

Response: Set the path of the database.


Instruction:
How would you explain what the following Python 3 function does
def delete(self, key):
        obj = self._get_content()
        obj.pop(key, None)

        self.write_data(self.path, obj)

Response: Removes the specified key from the database.


Instruction:
How would you explain what the following Python 3 function does
def data(self, **kwargs):

        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()

Response: Get the content of the entry in the database.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def filter(self, filter_arguments):
        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

Response: Returns a list of objects based on a dictionary of filter parameters.


Instruction:
Create a Python 3 function for
dropping the database by deleting the JSON file.

Response:
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 = {}


Instruction:
Make a summary of the following Python 3 code
def read_data(file_path):

    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

Response: Reads a file and returns a json encoded representation of the file.


Instruction:
Explain what the following Python 3 code does
def write_data(path, obj):
    with open_file_for_writing(path) as db:
        db.write(encode(obj))

    return obj

Response: Writes a dictionary to a file and returns the updated file content.


Instruction:
Write a Python 3 script for
checking to see if a file exists or is empty.

Response:
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


Instruction:
Given the following Python 3 function, write the documentation
def _refine(node_coords, cells_nodes, edge_nodes, cells_edges):
    num_nodes = len(node_coords)
    num_new_nodes = len(edge_nodes)

    # new_nodes = numpy.empty(num_new_nodes, dtype=numpy.dtype((float, 2)))
    node_coords.resize(num_nodes + num_new_nodes, 3, refcheck=False)
    # Set starting index for new nodes.
    new_node_gid = num_nodes

    # After the refinement step, all previous edge-node associations will be
    # obsolete, so record *all* the new edges.
    num_edges = len(edge_nodes)
    num_cells = len(cells_nodes)
    assert num_cells == len(cells_edges)
    num_new_edges = 2 * num_edges + 3 * num_cells
    new_edges_nodes = numpy.empty(num_new_edges, dtype=numpy.dtype((int, 2)))

    new_edge_gid = 0

    # After the refinement step, all previous cell-node associations will be
    # obsolete, so record *all* the new cells.
    num_new_cells = 4 * num_cells
    new_cells_nodes = numpy.empty(num_new_cells, dtype=numpy.dtype((int, 3)))
    new_cells_edges = numpy.empty(num_new_cells, dtype=numpy.dtype((int, 3)))
    new_cell_gid = 0

    is_edge_divided = numpy.zeros(num_edges, dtype=bool)
    edge_midpoint_gids = numpy.empty(num_edges, dtype=int)
    edge_newedges_gids = numpy.empty(num_edges, dtype=numpy.dtype((int, 2)))

    # Loop over all elements.
    for cell_id, cell in enumerate(zip(cells_edges, cells_nodes)):
        cell_edges, cell_nodes = cell
        # Divide edges.
        local_edge_midpoint_gids = numpy.empty(3, dtype=int)
        local_edge_newedges = numpy.empty(3, dtype=numpy.dtype((int, 2)))
        local_neighbor_midpoints = [[], [], []]
        local_neighbor_newedges = [[], [], []]
        for k, edge_gid in enumerate(cell_edges):
            edgenodes_gids = edge_nodes[edge_gid]
            if is_edge_divided[edge_gid]:
                # Edge is already divided. Just keep records for the cell
                # creation.
                local_edge_midpoint_gids[k] = edge_midpoint_gids[edge_gid]
                local_edge_newedges[k] = edge_newedges_gids[edge_gid]
            else:
                # Create new node at the edge midpoint.
                node_coords[new_node_gid] = 0.5 * (
                    node_coords[edgenodes_gids[0]] + node_coords[edgenodes_gids[1]]
                )
                local_edge_midpoint_gids[k] = new_node_gid
                new_node_gid += 1
                edge_midpoint_gids[edge_gid] = local_edge_midpoint_gids[k]

                # Divide edge into two.
                new_edges_nodes[new_edge_gid] = numpy.array(
                    [edgenodes_gids[0], local_edge_midpoint_gids[k]]
                )
                new_edge_gid += 1
                new_edges_nodes[new_edge_gid] = numpy.array(
                    [local_edge_midpoint_gids[k], edgenodes_gids[1]]
                )
                new_edge_gid += 1

                local_edge_newedges[k] = [new_edge_gid - 2, new_edge_gid - 1]
                edge_newedges_gids[edge_gid] = local_edge_newedges[k]
                # Do the household.
                is_edge_divided[edge_gid] = True
            # Keep a record of the new neighbors of the old nodes.
            # Get local node IDs.
            edgenodes_lids = [
                numpy.nonzero(cell_nodes == edgenodes_gids[0])[0][0],
                numpy.nonzero(cell_nodes == edgenodes_gids[1])[0][0],
            ]
            local_neighbor_midpoints[edgenodes_lids[0]].append(
                local_edge_midpoint_gids[k]
            )
            local_neighbor_midpoints[edgenodes_lids[1]].append(
                local_edge_midpoint_gids[k]
            )
            local_neighbor_newedges[edgenodes_lids[0]].append(local_edge_newedges[k][0])
            local_neighbor_newedges[edgenodes_lids[1]].append(local_edge_newedges[k][1])

        new_edge_opposite_of_local_node = numpy.empty(3, dtype=int)
        # New edges: Connect the three midpoints.
        for k in range(3):
            new_edges_nodes[new_edge_gid] = local_neighbor_midpoints[k]
            new_edge_opposite_of_local_node[k] = new_edge_gid
            new_edge_gid += 1

        # Create new elements.
        # Center cell:
        new_cells_nodes[new_cell_gid] = local_edge_midpoint_gids
        new_cells_edges[new_cell_gid] = new_edge_opposite_of_local_node
        new_cell_gid += 1
        # The three corner elements:
        for k in range(3):
            new_cells_nodes[new_cell_gid] = numpy.array(
                [
                    cells_nodes[cell_id][k],
                    local_neighbor_midpoints[k][0],
                    local_neighbor_midpoints[k][1],
                ]
            )
            new_cells_edges[new_cell_gid] = numpy.array(
                [
                    new_edge_opposite_of_local_node[k],
                    local_neighbor_newedges[k][0],
                    local_neighbor_newedges[k][1],
                ]
            )
            new_cell_gid += 1

    return node_coords, new_cells_nodes, new_edges_nodes, new_cells_edges

Response:
Refines a mesh by inserting nodes at all edge midpoints
    and make four triangular elements where there was one.


Instruction:
How would you explain what the following Python 3 function does
def create_edges(cells_nodes):
    # Create the idx_hierarchy (nodes->edges->cells), i.e., the value of
    # `self.idx_hierarchy[0, 2, 27]` is the index of the node of cell 27, edge
    # 2, node 0. The shape of `self.idx_hierarchy` is `(2, 3, n)`, where `n` is
    # the number of cells. Make sure that the k-th edge is opposite of the k-th
    # point in the triangle.
    local_idx = numpy.array([[1, 2], [2, 0], [0, 1]]).T
    # Map idx back to the nodes. This is useful if quantities which are in
    # idx shape need to be added up into nodes (e.g., equation system rhs).
    nds = cells_nodes.T
    idx_hierarchy = nds[local_idx]

    s = idx_hierarchy.shape
    a = numpy.sort(idx_hierarchy.reshape(s[0], s[1] * s[2]).T)

    b = numpy.ascontiguousarray(a).view(
        numpy.dtype((numpy.void, a.dtype.itemsize * a.shape[1]))
    )
    _, idx, inv, cts = numpy.unique(
        b, return_index=True, return_inverse=True, return_counts=True
    )

    # No edge has more than 2 cells. This assertion fails, for example, if
    # cells are listed twice.
    assert all(cts < 3)

    edge_nodes = a[idx]
    cells_edges = inv.reshape(3, -1).T

    return edge_nodes, cells_edges

Response: Create edge - node and edge - cell relations. Adapted from voropy.


Instruction:
Given the following Python 3 function, write the documentation
def plot2d(points, cells, mesh_color="k", show_axes=False):
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection

    fig = plt.figure()
    ax = fig.gca()
    plt.axis("equal")
    if not show_axes:
        ax.set_axis_off()

    xmin = numpy.amin(points[:, 0])
    xmax = numpy.amax(points[:, 0])
    ymin = numpy.amin(points[:, 1])
    ymax = numpy.amax(points[:, 1])

    width = xmax - xmin
    xmin -= 0.1 * width
    xmax += 0.1 * width

    height = ymax - ymin
    ymin -= 0.1 * height
    ymax += 0.1 * height

    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)

    edge_nodes, _ = create_edges(cells)

    # Get edges, cut off z-component.
    e = points[edge_nodes][:, :, :2]
    line_segments = LineCollection(e, color=mesh_color)
    ax.add_collection(line_segments)
    return fig

Response: Plot a 2D mesh using matplotlib.


Instruction:
Can you create a Python 3 function that
performs a job by a member in the pool and return the result.

Response:
def put(self, job, result):
        "Perform a job by a member in the pool and return the result."
        self.job.put(job)
        r = result.get()
        return r


Instruction:
Implement a function in Python 3 to
perform a contract on a number of jobs and block until a result is retrieved for each job.

Response:
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


Instruction:
Make a summary of the following Python 3 code
def cube(
    xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, zmin=0.0, zmax=1.0, nx=11, ny=11, nz=11
):
    """Canonical tetrahedrization of the cube.
    Input:
    Edge lenghts of the cube
    Number of nodes along the edges.
    """
    # Generate suitable ranges for parametrization
    x_range = numpy.linspace(xmin, xmax, nx)
    y_range = numpy.linspace(ymin, ymax, ny)
    z_range = numpy.linspace(zmin, zmax, nz)

    # Create the vertices.
    x, y, z = numpy.meshgrid(x_range, y_range, z_range, indexing="ij")
    # Alternative with slightly different order:
    # ```
    # nodes = numpy.stack([x, y, z]).T.reshape(-1, 3)
    # ```
    nodes = numpy.array([x, y, z]).T.reshape(-1, 3)

    # Create the elements (cells).
    # There is 1 way to split a cube into 5 tetrahedra,
    # and 12 ways to split it into 6 tetrahedra.
    # See
    # <http://www.baumanneduard.ch/Splitting%20a%20cube%20in%20tetrahedras2.htm>
    # Also interesting: <http://en.wikipedia.org/wiki/Marching_tetrahedrons>.

    a0 = numpy.add.outer(numpy.array(range(nx - 1)), nx * numpy.array(range(ny - 1)))
    a = numpy.add.outer(a0, nx * ny * numpy.array(range(nz - 1)))

    # The general scheme here is:
    #  * Initialize everything with `a`, equivalent to
    #    [i + nx * j + nx*ny * k].
    #  * Add the "even" elements.
    #  * Switch the element styles for every other element to make sure the
    #    edges match at the faces of the cubes.
    # The last step requires adapting the original pattern at
    #     [1::2, 0::2, 0::2, :]
    #     [0::2, 1::2, 0::2, :]
    #     [0::2, 0::2, 1::2, :]
    #     [1::2, 1::2, 1::2, :]
    #

    # Tetrahedron 0:
    # [
    # i   + nx*j     + nx*ny * k,
    # i   + nx*(j+1) + nx*ny * k,
    # i+1 + nx*j     + nx*ny * k,
    # i   + nx*j     + nx*ny * (k+1)
    # ]
    # TODO get
    # ```
    # elems0 = numpy.stack([a, a + nx, a + 1, a + nx*ny]).T
    # ```
    # back.
    elems0 = numpy.concatenate(
        [a[..., None], a[..., None] + nx, a[..., None] + 1, a[..., None] + nx * ny],
        axis=3,
    )

    # Every other element cube:
    # [
    # i+1 + nx * j     + nx*ny * k,
    # i+1 + nx * (j+1) + nx*ny * k,
    # i   + nx * j     + nx*ny * k,
    # i+1 + nx * j     + nx*ny * (k+1)
    # ]
    elems0[1::2, 0::2, 0::2, 0] += 1
    elems0[0::2, 1::2, 0::2, 0] += 1
    elems0[0::2, 0::2, 1::2, 0] += 1
    elems0[1::2, 1::2, 1::2, 0] += 1

    elems0[1::2, 0::2, 0::2, 1] += 1
    elems0[0::2, 1::2, 0::2, 1] += 1
    elems0[0::2, 0::2, 1::2, 1] += 1
    elems0[1::2, 1::2, 1::2, 1] += 1

    elems0[1::2, 0::2, 0::2, 2] -= 1
    elems0[0::2, 1::2, 0::2, 2] -= 1
    elems0[0::2, 0::2, 1::2, 2] -= 1
    elems0[1::2, 1::2, 1::2, 2] -= 1

    elems0[1::2, 0::2, 0::2, 3] += 1
    elems0[0::2, 1::2, 0::2, 3] += 1
    elems0[0::2, 0::2, 1::2, 3] += 1
    elems0[1::2, 1::2, 1::2, 3] += 1

    # Tetrahedron 1:
    # [
    # i   + nx*(j+1) + nx*ny * k,
    # i+1 + nx*(j+1) + nx*ny * k,
    # i+1 + nx*j     + nx*ny * k,
    # i+1 + nx*(j+1) + nx*ny * (k+1)
    # ]
    # elems1 = numpy.stack([a + nx, a + 1 + nx, a + 1, a + 1 + nx + nx*ny]).T
    elems1 = numpy.concatenate(
        [
            a[..., None] + nx,
            a[..., None] + 1 + nx,
            a[..., None] + 1,
            a[..., None] + 1 + nx + nx * ny,
        ],
        axis=3,
    )

    # Every other element cube:
    # [
    # i+1 + nx * (j+1) + nx*ny * k,
    # i   + nx * (j+1) + nx*ny * k,
    # i   + nx * j     + nx*ny * k,
    # i   + nx * (j+1) + nx*ny * (k+1)
    # ]
    elems1[1::2, 0::2, 0::2, 0] += 1
    elems1[0::2, 1::2, 0::2, 0] += 1
    elems1[0::2, 0::2, 1::2, 0] += 1
    elems1[1::2, 1::2, 1::2, 0] += 1

    elems1[1::2, 0::2, 0::2, 1] -= 1
    elems1[0::2, 1::2, 0::2, 1] -= 1
    elems1[0::2, 0::2, 1::2, 1] -= 1
    elems1[1::2, 1::2, 1::2, 1] -= 1

    elems1[1::2, 0::2, 0::2, 2] -= 1
    elems1[0::2, 1::2, 0::2, 2] -= 1
    elems1[0::2, 0::2, 1::2, 2] -= 1
    elems1[1::2, 1::2, 1::2, 2] -= 1

    elems1[1::2, 0::2, 0::2, 3] -= 1
    elems1[0::2, 1::2, 0::2, 3] -= 1
    elems1[0::2, 0::2, 1::2, 3] -= 1
    elems1[1::2, 1::2, 1::2, 3] -= 1

    # Tetrahedron 2:
    # [
    # i   + nx*(j+1) + nx*ny * k,
    # i+1 + nx*j     + nx*ny * k,
    # i   + nx*j     + nx*ny * (k+1),
    # i+1 + nx*(j+1) + nx*ny * (k+1)
    # ]
    # elems2 = numpy.stack([a + nx, a + 1, a + nx*ny, a + 1 + nx + nx*ny]).T
    elems2 = numpy.concatenate(
        [
            a[..., None] + nx,
            a[..., None] + 1,
            a[..., None] + nx * ny,
            a[..., None] + 1 + nx + nx * ny,
        ],
        axis=3,
    )

    # Every other element cube:
    # [
    # i+1 + nx * (j+1) + nx*ny * k,
    # i   + nx * j     + nx*ny * k,
    # i+1 + nx * j     + nx*ny * (k+1),
    # i   + nx * (j+1) + nx*ny * (k+1)
    # ]
    elems2[1::2, 0::2, 0::2, 0] += 1
    elems2[0::2, 1::2, 0::2, 0] += 1
    elems2[0::2, 0::2, 1::2, 0] += 1
    elems2[1::2, 1::2, 1::2, 0] += 1

    elems2[1::2, 0::2, 0::2, 1] -= 1
    elems2[0::2, 1::2, 0::2, 1] -= 1
    elems2[0::2, 0::2, 1::2, 1] -= 1
    elems2[1::2, 1::2, 1::2, 1] -= 1

    elems2[1::2, 0::2, 0::2, 2] += 1
    elems2[0::2, 1::2, 0::2, 2] += 1
    elems2[0::2, 0::2, 1::2, 2] += 1
    elems2[1::2, 1::2, 1::2, 2] += 1

    elems2[1::2, 0::2, 0::2, 3] -= 1
    elems2[0::2, 1::2, 0::2, 3] -= 1
    elems2[0::2, 0::2, 1::2, 3] -= 1
    elems2[1::2, 1::2, 1::2, 3] -= 1

    # Tetrahedron 3:
    # [
    # i   + nx * (j+1) + nx*ny * k,
    # i   + nx * j     + nx*ny * (k+1),
    # i   + nx * (j+1) + nx*ny * (k+1),
    # i+1 + nx * (j+1) + nx*ny * (k+1)
    # ]
    # elems3 = numpy.stack([
    #     a + nx,
    #     a + nx*ny,
    #     a + nx + nx*ny,
    #     a + 1 + nx + nx*ny
    #     ]).T
    elems3 = numpy.concatenate(
        [
            a[..., None] + nx,
            a[..., None] + nx * ny,
            a[..., None] + nx + nx * ny,
            a[..., None] + 1 + nx + nx * ny,
        ],
        axis=3,
    )

    # Every other element cube:
    # [
    # i+1 + nx * (j+1) + nx*ny * k,
    # i+1 + nx * j     + nx*ny * (k+1),
    # i+1 + nx * (j+1) + nx*ny * (k+1),
    # i   + nx * (j+1) + nx*ny * (k+1)
    # ]
    elems3[1::2, 0::2, 0::2, 0] += 1
    elems3[0::2, 1::2, 0::2, 0] += 1
    elems3[0::2, 0::2, 1::2, 0] += 1
    elems3[1::2, 1::2, 1::2, 0] += 1

    elems3[1::2, 0::2, 0::2, 1] += 1
    elems3[0::2, 1::2, 0::2, 1] += 1
    elems3[0::2, 0::2, 1::2, 1] += 1
    elems3[1::2, 1::2, 1::2, 1] += 1

    elems3[1::2, 0::2, 0::2, 2] += 1
    elems3[0::2, 1::2, 0::2, 2] += 1
    elems3[0::2, 0::2, 1::2, 2] += 1
    elems3[1::2, 1::2, 1::2, 2] += 1

    elems3[1::2, 0::2, 0::2, 3] -= 1
    elems3[0::2, 1::2, 0::2, 3] -= 1
    elems3[0::2, 0::2, 1::2, 3] -= 1
    elems3[1::2, 1::2, 1::2, 3] -= 1

    # Tetrahedron 4:
    # [
    # i+1 + nx * j     + nx*ny * k,
    # i   + nx * j     + nx*ny * (k+1),
    # i+1 + nx * (j+1) + nx*ny * (k+1),
    # i+1 + nx * j     + nx*ny * (k+1)
    # ]
    # elems4 = numpy.stack([
    #     a + 1,
    #     a + nx*ny,
    #     a + 1 + nx + nx*ny,
    #     a + 1 + nx*ny
    #     ]).T
    elems4 = numpy.concatenate(
        [
            a[..., None] + 1,
            a[..., None] + nx * ny,
            a[..., None] + 1 + nx + nx * ny,
            a[..., None] + 1 + nx * ny,
        ],
        axis=3,
    )

    # Every other element cube:
    # [
    # i   + nx * j     + nx*ny * k,
    # i+1 + nx * j     + nx*ny * (k+1),
    # i   + nx * (j+1) + nx*ny * (k+1),
    # i   + nx * j     + nx*ny * (k+1)
    # ]
    elems4[1::2, 0::2, 0::2, 0] -= 1
    elems4[0::2, 1::2, 0::2, 0] -= 1
    elems4[0::2, 0::2, 1::2, 0] -= 1
    elems4[1::2, 1::2, 1::2, 0] -= 1

    elems4[1::2, 0::2, 0::2, 1] += 1
    elems4[0::2, 1::2, 0::2, 1] += 1
    elems4[0::2, 0::2, 1::2, 1] += 1
    elems4[1::2, 1::2, 1::2, 1] += 1

    elems4[1::2, 0::2, 0::2, 2] -= 1
    elems4[0::2, 1::2, 0::2, 2] -= 1
    elems4[0::2, 0::2, 1::2, 2] -= 1
    elems4[1::2, 1::2, 1::2, 2] -= 1

    elems4[1::2, 0::2, 0::2, 3] -= 1
    elems4[0::2, 1::2, 0::2, 3] -= 1
    elems4[0::2, 0::2, 1::2, 3] -= 1
    elems4[1::2, 1::2, 1::2, 3] -= 1

    elems = numpy.vstack(
        [
            elems0.reshape(-1, 4),
            elems1.reshape(-1, 4),
            elems2.reshape(-1, 4),
            elems3.reshape(-1, 4),
            elems4.reshape(-1, 4),
        ]
    )

    return nodes, elems

Response: Canonical tetrahedrization of the cube.


Instruction:
How would you code a function in Python 3 to
add another worker to the pool.

Response:
def grow(self):
        "Add another worker to the pool."
        t = self.worker_factory(self)
        t.start()
        self._size += 1


Instruction:
Can you generate the documentation for the following Python 3 function
def shrink(self):
        "Get rid of one worker from the pool. Raises IndexError if empty."
        if self._size <= 0:
            raise IndexError("pool is already empty")
        self._size -= 1
        self.put(SuicideJob())

Response: Get rid of one worker from the pool. Raises IndexError if empty.


Instruction:
Write a Python 3 script for
performing a map operation distributed among the workers. Will " "block until done.

Response:
def map(self, fn, *seq):
        "Perform a map operation distributed among the workers. Will "
        "block until done."
        results = Queue()
        args = zip(*seq)
        for seq in args:
            j = SimpleJob(results, fn, seq)
            self.put(j)

        # Aggregate results
        r = []
        for i in range(len(list(args))):
            r.append(results.get())

        return r


Instruction:
How would you implement a function in Python 3 that
returns a Möbius strip as a simplistic triangular mesh.

Response:
def moebius(
    num_twists=1,  # How many twists are there in the 'paper'?
    nl=60,  # Number of nodes along the length of the strip
    nw=11,  # Number of nodes along the width of the strip (>= 2)
    mode="classical",
):
    """Creates a simplistic triangular mesh on a slightly Möbius strip. The
    Möbius strip here deviates slightly from the ordinary geometry in that it
    is constructed in such a way that the two halves can be exchanged as to
    allow better comparison with the pseudo-Möbius geometry.

    The mode is either `'classical'` or `'smooth'`. The first is the classical
    Möbius band parametrization, the latter a smoothed variant matching
    `'pseudo'`.
    """
    # The width of the strip
    width = 1.0
    scale = 10.0

    # radius of the strip when flattened out
    r = 1.0

    # seam displacement
    alpha0 = 0.0  # pi / 2

    # How flat the strip will be.
    # Positive values result in left-turning Möbius strips, negative in
    # right-turning ones.
    # Also influences the width of the strip.
    flatness = 1.0

    # Generate suitable ranges for parametrization
    u_range = numpy.linspace(0.0, 2 * numpy.pi, num=nl, endpoint=False)
    v_range = numpy.linspace(-0.5 * width, 0.5 * width, num=nw)

    # Create the vertices. This is based on the parameterization
    # of the Möbius strip as given in
    # <http://en.wikipedia.org/wiki/M%C3%B6bius_strip#Geometry_and_topology>
    sin_u = numpy.sin(u_range)
    cos_u = numpy.cos(u_range)
    alpha = num_twists * 0.5 * u_range + alpha0
    sin_alpha = numpy.sin(alpha)
    cos_alpha = numpy.cos(alpha)

    if mode == "classical":
        a = cos_alpha
        b = sin_alpha
        reverse_seam = num_twists % 2 == 1
    elif mode == "smooth":
        # The fundamental difference with the ordinary Möbius band here are the
        # squares.
        # It is also possible to to abs() the respective sines and cosines, but
        # this results in a non-smooth manifold.
        a = numpy.copysign(cos_alpha ** 2, cos_alpha)
        b = numpy.copysign(sin_alpha ** 2, sin_alpha)
        reverse_seam = num_twists % 2 == 1
    else:
        assert mode == "pseudo"
        a = cos_alpha ** 2
        b = sin_alpha ** 2
        reverse_seam = False

    nodes = (
        scale
        * numpy.array(
            [
                numpy.outer(a * cos_u, v_range) + r * cos_u[:, numpy.newaxis],
                numpy.outer(a * sin_u, v_range) + r * sin_u[:, numpy.newaxis],
                numpy.outer(b, v_range) * flatness,
            ]
        )
        .reshape(3, -1)
        .T
    )

    elems = _create_elements(nl, nw, reverse_seam)
    return nodes, elems


Instruction:
Make a summary of the following Python 3 code
def run(self):
        "Get jobs from the queue and perform them as they arrive."
        while 1:
            # Sleep until there is a job to perform.
            job = self.jobs.get()

            # Yawn. Time to get some work done.
            try:
                job.run()
                self.jobs.task_done()
            except TerminationNotice:
                self.jobs.task_done()
                break

Response: Get jobs from the queue and perform them as they arrive.


Instruction:
Write a Python 3 script for
displaying a single object in a web browser pointing to geojson. io with the specified content.

Response:
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


Instruction:
Write a Python 3 function that can
embed geojson. io in an iframe in Jupyter notebook.

Response:
def embed(contents='', width='100%', height=512, *args, **kwargs):
    """
    Embed geojson.io in an iframe in Jupyter/IPython notebook.

    Parameters
    ----------
    contents - see make_url()
    width - string, default '100%' - width of the iframe
    height - string / int, default 512 - height of the iframe
    kwargs - additional arguments are passed to `make_url()`

    """
    from IPython.display import HTML

    url = make_url(contents, *args, **kwargs)
    html = '<iframe src={url} width={width} height={height}></iframe>'.format(
        url=url, width=width, height=height)
    return HTML(html)


Instruction:
Given the following Python 3 function, write the documentation
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

Response: Returns the URL to open given the domain and contents.


Instruction:
Write a Python 3 function that can
return a GeoJSON string from a variety of inputs.

Response:
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)


Instruction:
Implement a function in Python 3 to
return the URL for embedding the GeoJSON data in the URL hash

Response:
def data_url(contents, domain=DEFAULT_DOMAIN):
    """
    Return the URL for embedding the GeoJSON data in the URL hash

    Parameters
    ----------
    contents - string of GeoJSON
    domain - string, default http://geojson.io

    """
    url = (domain + '#data=data:application/json,' +
           urllib.parse.quote(contents))
    return url


Instruction:
Here you have a function in Python 3, explain what it does
def _make_gist(contents, description='', filename='data.geojson'):
    ghapi = github3.GitHub()
    files = {filename: {'content': contents}}
    gist = ghapi.create_gist(description, files)

    return gist

Response: Create and return an anonymous gist with a single file and specified contents


Instruction:
Can you generate the documentation for the following Python 3 function
def clenshaw(a, alpha, beta, t):
    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]

Response:
Clenshaw s algorithm for evaluating the kth orthogonal polynomial defined by the
    recurrence coefficients alpha and beta.


Instruction:
Here you have a function in Python 3, explain what it does
def tree(X, n, alpha=0, symbolic=False):
    args = recurrence_coefficients(n, alpha=alpha, symbolic=symbolic)
    return line_tree(X, *args)

Response:
Recurrence coefficients for generalized Laguerre polynomials. Set
    alpha=0 (default) to get classical Laguerre.


Instruction:
How would you code a function in Python 3 to
return the recurrence coefficients for generalized Laguerre polynomials.

Response:
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)


Instruction:
Can you generate the documentation for the following Python 3 function
def jacobi(n, alpha, beta, standardization, symbolic=False):
    gamma = sympy.gamma if symbolic else lambda x: scipy.special.gamma(float(x))

    def rational(x, y):
        # <https://github.com/sympy/sympy/pull/13670>
        return (
            sympy.Rational(x, y)
            if all([isinstance(val, int) for val in [x, y]])
            else x / y
        )

    frac = rational if symbolic else lambda x, y: x / y
    sqrt = sympy.sqrt if symbolic else numpy.sqrt

    int_1 = (
        2 ** (alpha + beta + 1)
        * gamma(alpha + 1)
        * gamma(beta + 1)
        / gamma(alpha + beta + 2)
    )

    if standardization == "monic":
        p0 = 1

        a = numpy.ones(n, dtype=int)

        # work around bug <https://github.com/sympy/sympy/issues/13618>
        if isinstance(alpha, numpy.int64):
            alpha = int(alpha)
        if isinstance(beta, numpy.int64):
            beta = int(beta)

        b = [
            frac(beta - alpha, alpha + beta + 2)
            if N == 0
            else frac(
                beta ** 2 - alpha ** 2,
                (2 * N + alpha + beta) * (2 * N + alpha + beta + 2),
            )
            for N in range(n)
        ]

        # c[0] is not used in the actual recurrence, but is often defined
        # as the integral of the weight function of the domain, i.e.,
        # ```
        # int_{-1}^{+1} (1-x)^a * (1+x)^b dx =
        #     2^(a+b+1) * Gamma(a+1) * Gamma(b+1) / Gamma(a+b+2).
        # ```
        # Note also that we have the treat the case N==1 separately to avoid
        # division by 0 for alpha=beta=-1/2.
        c = [
            int_1
            if N == 0
            else frac(
                4 * (1 + alpha) * (1 + beta),
                (2 + alpha + beta) ** 2 * (3 + alpha + beta),
            )
            if N == 1
            else frac(
                4 * (N + alpha) * (N + beta) * N * (N + alpha + beta),
                (2 * N + alpha + beta) ** 2
                * (2 * N + alpha + beta + 1)
                * (2 * N + alpha + beta - 1),
            )
            for N in range(n)
        ]

    elif standardization == "p(1)=(n+alpha over n)" or (
        alpha == 0 and standardization == "p(1)=1"
    ):
        p0 = 1

        # work around bug <https://github.com/sympy/sympy/issues/13618>
        if isinstance(alpha, numpy.int64):
            alpha = int(alpha)
        if isinstance(beta, numpy.int64):
            beta = int(beta)

        # Treat N==0 separately to avoid division by 0 for alpha=beta=-1/2.
        a = [
            frac(alpha + beta + 2, 2)
            if N == 0
            else frac(
                (2 * N + alpha + beta + 1) * (2 * N + alpha + beta + 2),
                2 * (N + 1) * (N + alpha + beta + 1),
            )
            for N in range(n)
        ]

        b = [
            frac(beta - alpha, 2)
            if N == 0
            else frac(
                (beta ** 2 - alpha ** 2) * (2 * N + alpha + beta + 1),
                2 * (N + 1) * (N + alpha + beta + 1) * (2 * N + alpha + beta),
            )
            for N in range(n)
        ]

        c = [
            int_1
            if N == 0
            else frac(
                (N + alpha) * (N + beta) * (2 * N + alpha + beta + 2),
                (N + 1) * (N + alpha + beta + 1) * (2 * N + alpha + beta),
            )
            for N in range(n)
        ]

    else:
        assert standardization == "normal", "Unknown standardization '{}'.".format(
            standardization
        )

        p0 = sqrt(1 / int_1)

        # Treat N==0 separately to avoid division by 0 for alpha=beta=-1/2.
        a = [
            frac(alpha + beta + 2, 2)
            * sqrt(frac(alpha + beta + 3, (alpha + 1) * (beta + 1)))
            if N == 0
            else frac(2 * N + alpha + beta + 2, 2)
            * sqrt(
                frac(
                    (2 * N + alpha + beta + 1) * (2 * N + alpha + beta + 3),
                    (N + 1) * (N + alpha + 1) * (N + beta + 1) * (N + alpha + beta + 1),
                )
            )
            for N in range(n)
        ]

        b = [
            (
                frac(beta - alpha, 2)
                if N == 0
                else frac(beta ** 2 - alpha ** 2, 2 * (2 * N + alpha + beta))
            )
            * sqrt(
                frac(
                    (2 * N + alpha + beta + 3) * (2 * N + alpha + beta + 1),
                    (N + 1) * (N + alpha + 1) * (N + beta + 1) * (N + alpha + beta + 1),
                )
            )
            for N in range(n)
        ]

        c = [
            int_1
            if N == 0
            else frac(4 + alpha + beta, 2 + alpha + beta)
            * sqrt(
                frac(
                    (1 + alpha) * (1 + beta) * (5 + alpha + beta),
                    2 * (2 + alpha) * (2 + beta) * (2 + alpha + beta),
                )
            )
            if N == 1
            else frac(2 * N + alpha + beta + 2, 2 * N + alpha + beta)
            * sqrt(
                frac(
                    N
                    * (N + alpha)
                    * (N + beta)
                    * (N + alpha + beta)
                    * (2 * N + alpha + beta + 3),
                    (N + 1)
                    * (N + alpha + 1)
                    * (N + beta + 1)
                    * (N + alpha + beta + 1)
                    * (2 * N + alpha + beta - 1),
                )
            )
            for N in range(n)
        ]

    return p0, numpy.array(a), numpy.array(b), numpy.array(c)

Response: Generate the recurrence coefficients a_k b_k c_k for the Jacobi polynomials which are orthogonal on [ 1 - 1 ).


Instruction:
Can you generate the documentation for the following Python 3 function
def plot(f, lcar=1.0e-1):
    import matplotlib
    import matplotlib.pyplot as plt
    import pygmsh

    geom = pygmsh.built_in.Geometry()
    geom.add_circle([0.0, 0.0, 0.0], 1.0, lcar, num_sections=4, compound=True)
    points, cells, _, _, _ = pygmsh.generate_mesh(geom, verbose=True)

    x = points[:, 0]
    y = points[:, 1]
    triang = matplotlib.tri.Triangulation(x, y, cells["triangle"])

    plt.tripcolor(triang, f(points.T), shading="flat")
    plt.colorbar()

    # Choose a diverging colormap such that the zeros are clearly
    # distinguishable.
    plt.set_cmap("coolwarm")
    # Make sure the color map limits are symmetric around 0.
    clim = plt.gci().get_clim()
    mx = max(abs(clim[0]), abs(clim[1]))
    plt.clim(-mx, mx)

    # circle outline
    circle = plt.Circle((0, 0), 1.0, edgecolor="k", fill=False)
    plt.gca().add_artist(circle)

    plt.gca().set_aspect("equal")
    plt.axis("off")
    return

Response: Plot function over a disk.


Instruction:
Write a Python 3 function that can
evaluate the entire tree of orthogonal polynomials for the n - cube X.

Response:
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


Instruction:
How would you explain what the following Python 3 function does
def line_evaluate(t, p0, a, b, c):
    vals1 = numpy.zeros_like(t, dtype=int)
    # The order is important here; see
    # <https://github.com/sympy/sympy/issues/13637>.
    vals2 = numpy.ones_like(t) * p0

    for a_k, b_k, c_k in zip(a, b, c):
        vals0, vals1 = vals1, vals2
        vals2 = vals1 * (t * a_k - b_k) - vals0 * c_k
    return vals2

Response:
Evaluate the orthogonal polynomial defined by its recurrence coefficients
    a b and c at the point s.


Instruction:
Make a summary of the following Python 3 code
def plot(corners, f, n=100):
    import matplotlib.tri
    import matplotlib.pyplot as plt

    # discretization points
    def partition(boxes, balls):
        # <https://stackoverflow.com/a/36748940/353337>
        def rec(boxes, balls, parent=tuple()):
            if boxes > 1:
                for i in range(balls + 1):
                    for x in rec(boxes - 1, i, parent + (balls - i,)):
                        yield x
            else:
                yield parent + (balls,)

        return list(rec(boxes, balls))

    bary = numpy.array(partition(3, n)).T / n
    X = numpy.sum([numpy.outer(bary[k], corners[:, k]) for k in range(3)], axis=0).T

    # plot the points
    # plt.plot(X[0], X[1], 'xk')

    x = numpy.array(X[0])
    y = numpy.array(X[1])
    z = numpy.array(f(bary), dtype=float)

    triang = matplotlib.tri.Triangulation(x, y)
    plt.tripcolor(triang, z, shading="flat")
    plt.colorbar()

    # Choose a diverging colormap such that the zeros are clearly
    # distinguishable.
    plt.set_cmap("coolwarm")
    # Make sure the color map limits are symmetric around 0.
    clim = plt.gci().get_clim()
    mx = max(abs(clim[0]), abs(clim[1]))
    plt.clim(-mx, mx)

    # triangle outlines
    X = numpy.column_stack([corners, corners[:, 0]])
    plt.plot(X[0], X[1], "-k")

    plt.gca().set_aspect("equal")
    plt.axis("off")
    return

Response: Plot function over a triangle.


Instruction:
Here you have a function in Python 3, explain what it does
def _iget(key, lookup_dict):
    for k, v in lookup_dict.items():
        if k.lower() == key.lower():
            return v
    return None

Response: Case - insensitive search for key within keys of lookup_dict.


Instruction:
Here you have a function in Python 3, explain what it does
def getlang_by_name(name):
    direct_match = _iget(name, _LANGUAGE_NAME_LOOKUP)
    if direct_match:
        return direct_match
    else:
        simple_name = name.split(',')[0]                 # take part before comma
        simple_name = simple_name.split('(')[0].strip()  # and before any bracket
        return _LANGUAGE_NAME_LOOKUP.get(simple_name, None)

Response: Try to lookup a Language object by name e. g. English in internal language list.


Instruction:
Explain what the following Python 3 code does
def getlang_by_native_name(native_name):
    direct_match = _iget(native_name, _LANGUAGE_NATIVE_NAME_LOOKUP)
    if direct_match:
        return direct_match
    else:
        simple_native_name = native_name.split(',')[0]                 # take part before comma
        simple_native_name = simple_native_name.split('(')[0].strip()  # and before any bracket
        return _LANGUAGE_NATIVE_NAME_LOOKUP.get(simple_native_name, None)

Response: Try to lookup a Language object by native name e. g. English in internal language list.


Instruction:
Explain what the following Python 3 code does
def getlang_by_alpha2(code):
    # Handle special cases for language codes returned by YouTube API
    if code == 'iw':   # handle old Hebrew code 'iw' and return modern code 'he'
        return getlang('he')
    elif 'zh-Hans' in code:
        return getlang('zh-CN')   # use code `zh-CN` for all simplified Chinese
    elif 'zh-Hant' in code or re.match('zh(.*)?-HK', code):
        return getlang('zh-TW')   # use code `zh-TW` for all traditional Chinese

    # extract prefix only if specified with subcode: e.g. zh-Hans --> zh
    first_part = code.split('-')[0]

    # See if pycountry can find this language
    try:
        pyc_lang = pycountry.languages.get(alpha_2=first_part)
        if pyc_lang:
            if hasattr(pyc_lang, 'inverted_name'):
                lang_name = pyc_lang.inverted_name
            else:
                lang_name = pyc_lang.name
            return getlang_by_name(lang_name)
        else:
            return None
    except KeyError:
        return None

Response: Returns a Language object for the language code code.


Instruction:
Given the following Python 3 function, write the documentation
def write(filename, f):
    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

Response: Write a function f defined in terms of spherical coordinates to a file.


Instruction:
Can you write a function in Python 3 where it
evaluates all spherical harmonics of degree at most n at angles polar and azimuthal.

Response:
def tree_sph(polar, azimuthal, n, standardization, symbolic=False):
    """Evaluate all spherical harmonics of degree at most `n` at angles `polar`,
    `azimuthal`.
    """
    cos = numpy.vectorize(sympy.cos) if symbolic else numpy.cos

    # Conventions from
    # <https://en.wikipedia.org/wiki/Spherical_harmonics#Orthogonality_and_normalization>.
    config = {
        "acoustic": ("complex spherical", False),
        "quantum mechanic": ("complex spherical", True),
        "geodetic": ("complex spherical 1", False),
        "schmidt": ("schmidt", False),
    }

    standard, cs_phase = config[standardization]

    return tree_alp(
        cos(polar),
        n,
        phi=azimuthal,
        standardization=standard,
        with_condon_shortley_phase=cs_phase,
        symbolic=symbolic,
    )


Instruction:
Can you generate the documentation for the following Python 3 function
def tree_alp(
    x, n, standardization, phi=None, with_condon_shortley_phase=True, symbolic=False
):
    """Evaluates the entire tree of associated Legendre polynomials up to depth
    n.
    There are many recurrence relations that can be used to construct the
    associated Legendre polynomials. However, only few are numerically stable.
    Many implementations (including this one) use the classical Legendre
    recurrence relation with increasing L.

    Useful references are

    Taweetham Limpanuparb, Josh Milthorpe,
    Associated Legendre Polynomials and Spherical Harmonics Computation for
    Chemistry Applications,
    Proceedings of The 40th Congress on Science and Technology of Thailand;
    2014 Dec 2-4, Khon Kaen, Thailand. P. 233-241.
    <https://arxiv.org/abs/1410.1748>

    and

    Schneider et al.,
    A new Fortran 90 program to compute regular and irregular associated
    Legendre functions,
    Computer Physics Communications,
    Volume 181, Issue 12, December 2010, Pages 2091-2097,
    <https://doi.org/10.1016/j.cpc.2010.08.038>.

    The return value is a list of arrays, where `out[k]` hosts the `2*k+1`
    values of the `k`th level of the tree

                              (0, 0)
                    (-1, 1)   (0, 1)   (1, 1)
          (-2, 2)   (-1, 2)   (0, 2)   (1, 2)   (2, 2)
            ...       ...       ...     ...       ...
    """
    # assert numpy.all(numpy.abs(x) <= 1.0)

    d = {
        "natural": (_Natural, [x, symbolic]),
        "spherical": (_Spherical, [x, symbolic]),
        "complex spherical": (_ComplexSpherical, [x, phi, symbolic, False]),
        "complex spherical 1": (_ComplexSpherical, [x, phi, symbolic, True]),
        "normal": (_Normal, [x, symbolic]),
        "schmidt": (_Schmidt, [x, phi, symbolic]),
    }
    fun, args = d[standardization]
    c = fun(*args)

    if with_condon_shortley_phase:

        def z1_factor_CSP(L):
            return -1 * c.z1_factor(L)

    else:
        z1_factor_CSP = c.z1_factor

    # Here comes the actual loop.
    e = numpy.ones_like(x, dtype=int)
    out = [[e * c.p0]]
    for L in range(1, n + 1):
        out.append(
            numpy.concatenate(
                [
                    [out[L - 1][0] * c.z0_factor(L)],
                    out[L - 1] * numpy.multiply.outer(c.C0(L), x),
                    [out[L - 1][-1] * z1_factor_CSP(L)],
                ]
            )
        )

        if L > 1:
            out[-1][2:-2] -= numpy.multiply.outer(c.C1(L), e) * out[L - 2]

    return out

Response: Evaluates the entire tree of associated Legendre polynomials up to depth n.


Instruction:
Can you tell what is the following Python 3 function doing
def tree(X, n, symbolic=False):
    frac = sympy.Rational if symbolic else lambda x, y: x / y
    sqrt = sympy.sqrt if symbolic else numpy.sqrt
    pi = sympy.pi if symbolic else numpy.pi

    mu = frac(1, 2)

    p0 = 1 / sqrt(pi)

    def alpha(n):
        return numpy.array(
            [
                2
                * sqrt(
                    frac(
                        (n + mu + frac(1, 2)) * (n + mu - frac(1, 2)),
                        (n - k) * (n + k + 2 * mu),
                    )
                )
                for k in range(n)
            ]
        )

    def beta(n):
        return 2 * sqrt(
            frac((n + mu - 1) * (n + mu + frac(1, 2)), (n + 2 * mu - 1) * n)
        )

    def gamma(n):
        return numpy.array(
            [
                sqrt(
                    frac(
                        (n - 1 - k) * (n + mu + frac(1, 2)) * (n + k + 2 * mu - 1),
                        (n - k) * (n + mu - frac(3, 2)) * (n + k + 2 * mu),
                    )
                )
                for k in range(n - 1)
            ]
        )

    def delta(n):
        return sqrt(
            frac(
                (n - 1)
                * (n + 2 * mu - 2)
                * (n + mu - frac(1, 2))
                * (n + mu + frac(1, 2)),
                n * (n + 2 * mu - 1) * (n + mu - 1) * (n + mu - 2),
            )
        )

    out = [numpy.array([0 * X[0] + p0])]

    one_min_x2 = 1 - X[0] ** 2

    for L in range(1, n + 1):
        out.append(
            numpy.concatenate(
                [
                    out[L - 1] * numpy.multiply.outer(alpha(L), X[0]),
                    [out[L - 1][L - 1] * beta(L) * X[1]],
                ]
            )
        )

        if L > 1:
            out[-1][: L - 1] -= (out[L - 2].T * gamma(L)).T
            out[-1][-1] -= out[L - 2][L - 2] * delta(L) * one_min_x2

    return out

Response: Evaluates the entire tree of orthogonal polynomials on the unit disk.