repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
flatangle/flatlib | flatlib/chart.py | Chart.isDiurnal | 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) | python | 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) | [
"def",
"isDiurnal",
"(",
"self",
")",
":",
"sun",
"=",
"self",
".",
"getObject",
"(",
"const",
".",
"SUN",
")",
"mc",
"=",
"self",
".",
"getAngle",
"(",
"const",
".",
"MC",
")",
"# Get ecliptical positions and check if the",
"# sun is above the horizon.",
"lat... | Returns true if this chart is diurnal. | [
"Returns",
"true",
"if",
"this",
"chart",
"is",
"diurnal",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/chart.py#L130-L140 | train |
flatangle/flatlib | flatlib/chart.py | Chart.getMoonPhase | def getMoonPhase(self):
""" Returns the phase of the moon. """
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 | python | def getMoonPhase(self):
""" Returns the phase of the moon. """
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 | [
"def",
"getMoonPhase",
"(",
"self",
")",
":",
"sun",
"=",
"self",
".",
"getObject",
"(",
"const",
".",
"SUN",
")",
"moon",
"=",
"self",
".",
"getObject",
"(",
"const",
".",
"MOON",
")",
"dist",
"=",
"angle",
".",
"distance",
"(",
"sun",
".",
"lon",... | Returns the phase of the moon. | [
"Returns",
"the",
"phase",
"of",
"the",
"moon",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/chart.py#L142-L154 | train |
flatangle/flatlib | flatlib/chart.py | Chart.solarReturn | def solarReturn(self, year):
""" Returns this chart's solar return for a
given year.
"""
sun = self.getObject(const.SUN)
date = Datetime('{0}/01/01'.format(year),
'00:00',
self.date.utcoffset)
srDate = ephem.nextSolarReturn(date, sun.lon)
return Chart(srDate, self.pos, hsys=self.hsys) | python | def solarReturn(self, year):
""" Returns this chart's solar return for a
given year.
"""
sun = self.getObject(const.SUN)
date = Datetime('{0}/01/01'.format(year),
'00:00',
self.date.utcoffset)
srDate = ephem.nextSolarReturn(date, sun.lon)
return Chart(srDate, self.pos, hsys=self.hsys) | [
"def",
"solarReturn",
"(",
"self",
",",
"year",
")",
":",
"sun",
"=",
"self",
".",
"getObject",
"(",
"const",
".",
"SUN",
")",
"date",
"=",
"Datetime",
"(",
"'{0}/01/01'",
".",
"format",
"(",
"year",
")",
",",
"'00:00'",
",",
"self",
".",
"date",
"... | Returns this chart's solar return for a
given year. | [
"Returns",
"this",
"chart",
"s",
"solar",
"return",
"for",
"a",
"given",
"year",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/chart.py#L159-L169 | train |
flatangle/flatlib | flatlib/tools/arabicparts.py | objLon | 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 | python | 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 | [
"def",
"objLon",
"(",
"ID",
",",
"chart",
")",
":",
"if",
"ID",
".",
"startswith",
"(",
"'$R'",
")",
":",
"# Return Ruler",
"ID",
"=",
"ID",
"[",
"2",
":",
"]",
"obj",
"=",
"chart",
".",
"get",
"(",
"ID",
")",
"rulerID",
"=",
"essential",
".",
... | Returns the longitude of an object. | [
"Returns",
"the",
"longitude",
"of",
"an",
"object",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/tools/arabicparts.py#L151-L166 | train |
flatangle/flatlib | flatlib/tools/arabicparts.py | partLon | 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 | python | 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 | [
"def",
"partLon",
"(",
"ID",
",",
"chart",
")",
":",
"# Get diurnal or nocturnal formula",
"abc",
"=",
"FORMULAS",
"[",
"ID",
"]",
"[",
"0",
"]",
"if",
"chart",
".",
"isDiurnal",
"(",
")",
"else",
"FORMULAS",
"[",
"ID",
"]",
"[",
"1",
"]",
"a",
"=",
... | Returns the longitude of an arabic part. | [
"Returns",
"the",
"longitude",
"of",
"an",
"arabic",
"part",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/tools/arabicparts.py#L168-L175 | train |
flatangle/flatlib | flatlib/tools/arabicparts.py | getPart | def getPart(ID, chart):
""" Returns an Arabic Part. """
obj = GenericObject()
obj.id = ID
obj.type = const.OBJ_ARABIC_PART
obj.relocate(partLon(ID, chart))
return obj | python | def getPart(ID, chart):
""" Returns an Arabic Part. """
obj = GenericObject()
obj.id = ID
obj.type = const.OBJ_ARABIC_PART
obj.relocate(partLon(ID, chart))
return obj | [
"def",
"getPart",
"(",
"ID",
",",
"chart",
")",
":",
"obj",
"=",
"GenericObject",
"(",
")",
"obj",
".",
"id",
"=",
"ID",
"obj",
".",
"type",
"=",
"const",
".",
"OBJ_ARABIC_PART",
"obj",
".",
"relocate",
"(",
"partLon",
"(",
"ID",
",",
"chart",
")",... | Returns an Arabic Part. | [
"Returns",
"an",
"Arabic",
"Part",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/tools/arabicparts.py#L177-L183 | train |
flatangle/flatlib | flatlib/ephem/swe.py | sweObject | 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]
} | python | 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]
} | [
"def",
"sweObject",
"(",
"obj",
",",
"jd",
")",
":",
"sweObj",
"=",
"SWE_OBJECTS",
"[",
"obj",
"]",
"sweList",
"=",
"swisseph",
".",
"calc_ut",
"(",
"jd",
",",
"sweObj",
")",
"return",
"{",
"'id'",
":",
"obj",
",",
"'lon'",
":",
"sweList",
"[",
"0"... | Returns an object from the Ephemeris. | [
"Returns",
"an",
"object",
"from",
"the",
"Ephemeris",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/swe.py#L63-L73 | train |
flatangle/flatlib | flatlib/ephem/swe.py | sweObjectLon | def sweObjectLon(obj, jd):
""" Returns the longitude of an object. """
sweObj = SWE_OBJECTS[obj]
sweList = swisseph.calc_ut(jd, sweObj)
return sweList[0] | python | def sweObjectLon(obj, jd):
""" Returns the longitude of an object. """
sweObj = SWE_OBJECTS[obj]
sweList = swisseph.calc_ut(jd, sweObj)
return sweList[0] | [
"def",
"sweObjectLon",
"(",
"obj",
",",
"jd",
")",
":",
"sweObj",
"=",
"SWE_OBJECTS",
"[",
"obj",
"]",
"sweList",
"=",
"swisseph",
".",
"calc_ut",
"(",
"jd",
",",
"sweObj",
")",
"return",
"sweList",
"[",
"0",
"]"
] | Returns the longitude of an object. | [
"Returns",
"the",
"longitude",
"of",
"an",
"object",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/swe.py#L75-L79 | train |
flatangle/flatlib | flatlib/ephem/swe.py | sweNextTransit | 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] | python | 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] | [
"def",
"sweNextTransit",
"(",
"obj",
",",
"jd",
",",
"lat",
",",
"lon",
",",
"flag",
")",
":",
"sweObj",
"=",
"SWE_OBJECTS",
"[",
"obj",
"]",
"flag",
"=",
"swisseph",
".",
"CALC_RISE",
"if",
"flag",
"==",
"'RISE'",
"else",
"swisseph",
".",
"CALC_SET",
... | Returns the julian date of the next transit of
an object. The flag should be 'RISE' or 'SET'. | [
"Returns",
"the",
"julian",
"date",
"of",
"the",
"next",
"transit",
"of",
"an",
"object",
".",
"The",
"flag",
"should",
"be",
"RISE",
"or",
"SET",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/swe.py#L81-L89 | train |
flatangle/flatlib | flatlib/ephem/swe.py | sweHouses | 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) | python | 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) | [
"def",
"sweHouses",
"(",
"jd",
",",
"lat",
",",
"lon",
",",
"hsys",
")",
":",
"hsys",
"=",
"SWE_HOUSESYS",
"[",
"hsys",
"]",
"hlist",
",",
"ascmc",
"=",
"swisseph",
".",
"houses",
"(",
"jd",
",",
"lat",
",",
"lon",
",",
"hsys",
")",
"# Add first ho... | Returns lists of houses and angles. | [
"Returns",
"lists",
"of",
"houses",
"and",
"angles",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/swe.py#L94-L114 | train |
flatangle/flatlib | flatlib/ephem/swe.py | sweHousesLon | 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) | python | 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) | [
"def",
"sweHousesLon",
"(",
"jd",
",",
"lat",
",",
"lon",
",",
"hsys",
")",
":",
"hsys",
"=",
"SWE_HOUSESYS",
"[",
"hsys",
"]",
"hlist",
",",
"ascmc",
"=",
"swisseph",
".",
"houses",
"(",
"jd",
",",
"lat",
",",
"lon",
",",
"hsys",
")",
"angles",
... | Returns lists with house and angle longitudes. | [
"Returns",
"lists",
"with",
"house",
"and",
"angle",
"longitudes",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/swe.py#L116-L126 | train |
flatangle/flatlib | flatlib/ephem/swe.py | sweFixedStar | 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]
} | python | 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]
} | [
"def",
"sweFixedStar",
"(",
"star",
",",
"jd",
")",
":",
"sweList",
"=",
"swisseph",
".",
"fixstar_ut",
"(",
"star",
",",
"jd",
")",
"mag",
"=",
"swisseph",
".",
"fixstar_mag",
"(",
"star",
")",
"return",
"{",
"'id'",
":",
"star",
",",
"'mag'",
":",
... | Returns a fixed star from the Ephemeris. | [
"Returns",
"a",
"fixed",
"star",
"from",
"the",
"Ephemeris",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/swe.py#L135-L144 | train |
flatangle/flatlib | flatlib/ephem/swe.py | solarEclipseGlobal | 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],
} | python | 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],
} | [
"def",
"solarEclipseGlobal",
"(",
"jd",
",",
"backward",
")",
":",
"sweList",
"=",
"swisseph",
".",
"sol_eclipse_when_glob",
"(",
"jd",
",",
"backward",
"=",
"backward",
")",
"return",
"{",
"'maximum'",
":",
"sweList",
"[",
"1",
"]",
"[",
"0",
"]",
",",
... | Returns the jd details of previous or next global solar eclipse. | [
"Returns",
"the",
"jd",
"details",
"of",
"previous",
"or",
"next",
"global",
"solar",
"eclipse",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/swe.py#L149-L161 | train |
flatangle/flatlib | flatlib/ephem/swe.py | lunarEclipseGlobal | def lunarEclipseGlobal(jd, backward):
""" Returns the jd details of previous or next global lunar eclipse. """
sweList = swisseph.lun_eclipse_when(jd, backward=backward)
return {
'maximum': sweList[1][0],
'partial_begin': sweList[1][2],
'partial_end': sweList[1][3],
'totality_begin': sweList[1][4],
'totality_end': sweList[1][5],
'penumbral_begin': sweList[1][6],
'penumbral_end': sweList[1][7],
} | python | def lunarEclipseGlobal(jd, backward):
""" Returns the jd details of previous or next global lunar eclipse. """
sweList = swisseph.lun_eclipse_when(jd, backward=backward)
return {
'maximum': sweList[1][0],
'partial_begin': sweList[1][2],
'partial_end': sweList[1][3],
'totality_begin': sweList[1][4],
'totality_end': sweList[1][5],
'penumbral_begin': sweList[1][6],
'penumbral_end': sweList[1][7],
} | [
"def",
"lunarEclipseGlobal",
"(",
"jd",
",",
"backward",
")",
":",
"sweList",
"=",
"swisseph",
".",
"lun_eclipse_when",
"(",
"jd",
",",
"backward",
"=",
"backward",
")",
"return",
"{",
"'maximum'",
":",
"sweList",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"'p... | Returns the jd details of previous or next global lunar eclipse. | [
"Returns",
"the",
"jd",
"details",
"of",
"previous",
"or",
"next",
"global",
"lunar",
"eclipse",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/swe.py#L163-L175 | train |
flatangle/flatlib | flatlib/datetime.py | dateJDN | 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 | python | 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 | [
"def",
"dateJDN",
"(",
"year",
",",
"month",
",",
"day",
",",
"calendar",
")",
":",
"a",
"=",
"(",
"14",
"-",
"month",
")",
"//",
"12",
"y",
"=",
"year",
"+",
"4800",
"-",
"a",
"m",
"=",
"month",
"+",
"12",
"*",
"a",
"-",
"3",
"if",
"calend... | Converts date to Julian Day Number. | [
"Converts",
"date",
"to",
"Julian",
"Day",
"Number",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/datetime.py#L26-L34 | train |
flatangle/flatlib | flatlib/datetime.py | jdnDate | 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] | python | 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] | [
"def",
"jdnDate",
"(",
"jdn",
")",
":",
"a",
"=",
"jdn",
"+",
"32044",
"b",
"=",
"(",
"4",
"*",
"a",
"+",
"3",
")",
"//",
"146097",
"c",
"=",
"a",
"-",
"(",
"146097",
"*",
"b",
")",
"//",
"4",
"d",
"=",
"(",
"4",
"*",
"c",
"+",
"3",
"... | Converts Julian Day Number to Gregorian date. | [
"Converts",
"Julian",
"Day",
"Number",
"to",
"Gregorian",
"date",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/datetime.py#L36-L47 | train |
flatangle/flatlib | flatlib/datetime.py | Date.toList | def toList(self):
""" Returns date as signed list. """
date = self.date()
sign = '+' if date[0] >= 0 else '-'
date[0] = abs(date[0])
return list(sign) + date | python | def toList(self):
""" Returns date as signed list. """
date = self.date()
sign = '+' if date[0] >= 0 else '-'
date[0] = abs(date[0])
return list(sign) + date | [
"def",
"toList",
"(",
"self",
")",
":",
"date",
"=",
"self",
".",
"date",
"(",
")",
"sign",
"=",
"'+'",
"if",
"date",
"[",
"0",
"]",
">=",
"0",
"else",
"'-'",
"date",
"[",
"0",
"]",
"=",
"abs",
"(",
"date",
"[",
"0",
"]",
")",
"return",
"li... | Returns date as signed list. | [
"Returns",
"date",
"as",
"signed",
"list",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/datetime.py#L86-L91 | train |
flatangle/flatlib | flatlib/datetime.py | Date.toString | 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 | python | 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 | [
"def",
"toString",
"(",
"self",
")",
":",
"slist",
"=",
"self",
".",
"toList",
"(",
")",
"sign",
"=",
"''",
"if",
"slist",
"[",
"0",
"]",
"==",
"'+'",
"else",
"'-'",
"string",
"=",
"'/'",
".",
"join",
"(",
"[",
"'%02d'",
"%",
"v",
"for",
"v",
... | Returns date as string. | [
"Returns",
"date",
"as",
"string",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/datetime.py#L93-L98 | train |
flatangle/flatlib | flatlib/datetime.py | Time.getUTC | def getUTC(self, utcoffset):
""" Returns a new Time object set to UTC given
an offset Time object.
"""
newTime = (self.value - utcoffset.value) % 24
return Time(newTime) | python | def getUTC(self, utcoffset):
""" Returns a new Time object set to UTC given
an offset Time object.
"""
newTime = (self.value - utcoffset.value) % 24
return Time(newTime) | [
"def",
"getUTC",
"(",
"self",
",",
"utcoffset",
")",
":",
"newTime",
"=",
"(",
"self",
".",
"value",
"-",
"utcoffset",
".",
"value",
")",
"%",
"24",
"return",
"Time",
"(",
"newTime",
")"
] | Returns a new Time object set to UTC given
an offset Time object. | [
"Returns",
"a",
"new",
"Time",
"object",
"set",
"to",
"UTC",
"given",
"an",
"offset",
"Time",
"object",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/datetime.py#L121-L127 | train |
flatangle/flatlib | flatlib/datetime.py | Time.time | 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:] | python | 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:] | [
"def",
"time",
"(",
"self",
")",
":",
"slist",
"=",
"self",
".",
"toList",
"(",
")",
"if",
"slist",
"[",
"0",
"]",
"==",
"'-'",
":",
"slist",
"[",
"1",
"]",
"*=",
"-",
"1",
"# We must do a trick if we want to ",
"# make negative zeros explicit",
"if",
"s... | Returns time as list [hh,mm,ss]. | [
"Returns",
"time",
"as",
"list",
"[",
"hh",
"mm",
"ss",
"]",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/datetime.py#L129-L138 | train |
flatangle/flatlib | flatlib/datetime.py | Time.toList | 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 | python | 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 | [
"def",
"toList",
"(",
"self",
")",
":",
"slist",
"=",
"angle",
".",
"toList",
"(",
"self",
".",
"value",
")",
"# Keep hours in 0..23",
"slist",
"[",
"1",
"]",
"=",
"slist",
"[",
"1",
"]",
"%",
"24",
"return",
"slist"
] | Returns time as signed list. | [
"Returns",
"time",
"as",
"signed",
"list",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/datetime.py#L140-L145 | train |
flatangle/flatlib | flatlib/datetime.py | Time.toString | def toString(self):
""" Returns time as string. """
slist = self.toList()
string = angle.slistStr(slist)
return string if slist[0] == '-' else string[1:] | python | def toString(self):
""" Returns time as string. """
slist = self.toList()
string = angle.slistStr(slist)
return string if slist[0] == '-' else string[1:] | [
"def",
"toString",
"(",
"self",
")",
":",
"slist",
"=",
"self",
".",
"toList",
"(",
")",
"string",
"=",
"angle",
".",
"slistStr",
"(",
"slist",
")",
"return",
"string",
"if",
"slist",
"[",
"0",
"]",
"==",
"'-'",
"else",
"string",
"[",
"1",
":",
"... | Returns time as string. | [
"Returns",
"time",
"as",
"string",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/datetime.py#L147-L151 | train |
flatangle/flatlib | flatlib/datetime.py | Datetime.fromJD | 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) | python | 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) | [
"def",
"fromJD",
"(",
"jd",
",",
"utcoffset",
")",
":",
"if",
"not",
"isinstance",
"(",
"utcoffset",
",",
"Time",
")",
":",
"utcoffset",
"=",
"Time",
"(",
"utcoffset",
")",
"localJD",
"=",
"jd",
"+",
"utcoffset",
".",
"value",
"/",
"24.0",
"date",
"=... | Builds a Datetime object given a jd and utc offset. | [
"Builds",
"a",
"Datetime",
"object",
"given",
"a",
"jd",
"and",
"utc",
"offset",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/datetime.py#L194-L201 | train |
flatangle/flatlib | flatlib/datetime.py | Datetime.getUTC | def getUTC(self):
""" Returns this Datetime localized for UTC. """
timeUTC = self.time.getUTC(self.utcoffset)
dateUTC = Date(round(self.jd))
return Datetime(dateUTC, timeUTC) | python | def getUTC(self):
""" Returns this Datetime localized for UTC. """
timeUTC = self.time.getUTC(self.utcoffset)
dateUTC = Date(round(self.jd))
return Datetime(dateUTC, timeUTC) | [
"def",
"getUTC",
"(",
"self",
")",
":",
"timeUTC",
"=",
"self",
".",
"time",
".",
"getUTC",
"(",
"self",
".",
"utcoffset",
")",
"dateUTC",
"=",
"Date",
"(",
"round",
"(",
"self",
".",
"jd",
")",
")",
"return",
"Datetime",
"(",
"dateUTC",
",",
"time... | Returns this Datetime localized for UTC. | [
"Returns",
"this",
"Datetime",
"localized",
"for",
"UTC",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/datetime.py#L203-L207 | train |
flatangle/flatlib | flatlib/ephem/eph.py | getObject | 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 | python | 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 | [
"def",
"getObject",
"(",
"ID",
",",
"jd",
",",
"lat",
",",
"lon",
")",
":",
"if",
"ID",
"==",
"const",
".",
"SOUTH_NODE",
":",
"obj",
"=",
"swe",
".",
"sweObject",
"(",
"const",
".",
"NORTH_NODE",
",",
"jd",
")",
"obj",
".",
"update",
"(",
"{",
... | Returns an object for a specific date and
location. | [
"Returns",
"an",
"object",
"for",
"a",
"specific",
"date",
"and",
"location",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/eph.py#L23-L51 | train |
flatangle/flatlib | flatlib/ephem/eph.py | getHouses | def getHouses(jd, lat, lon, hsys):
""" Returns lists of houses and angles. """
houses, angles = swe.sweHouses(jd, lat, lon, hsys)
for house in houses:
_signInfo(house)
for angle in angles:
_signInfo(angle)
return (houses, angles) | python | def getHouses(jd, lat, lon, hsys):
""" Returns lists of houses and angles. """
houses, angles = swe.sweHouses(jd, lat, lon, hsys)
for house in houses:
_signInfo(house)
for angle in angles:
_signInfo(angle)
return (houses, angles) | [
"def",
"getHouses",
"(",
"jd",
",",
"lat",
",",
"lon",
",",
"hsys",
")",
":",
"houses",
",",
"angles",
"=",
"swe",
".",
"sweHouses",
"(",
"jd",
",",
"lat",
",",
"lon",
",",
"hsys",
")",
"for",
"house",
"in",
"houses",
":",
"_signInfo",
"(",
"hous... | Returns lists of houses and angles. | [
"Returns",
"lists",
"of",
"houses",
"and",
"angles",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/eph.py#L56-L63 | train |
flatangle/flatlib | flatlib/ephem/eph.py | getFixedStar | def getFixedStar(ID, jd):
""" Returns a fixed star. """
star = swe.sweFixedStar(ID, jd)
_signInfo(star)
return star | python | def getFixedStar(ID, jd):
""" Returns a fixed star. """
star = swe.sweFixedStar(ID, jd)
_signInfo(star)
return star | [
"def",
"getFixedStar",
"(",
"ID",
",",
"jd",
")",
":",
"star",
"=",
"swe",
".",
"sweFixedStar",
"(",
"ID",
",",
"jd",
")",
"_signInfo",
"(",
"star",
")",
"return",
"star"
] | Returns a fixed star. | [
"Returns",
"a",
"fixed",
"star",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/eph.py#L68-L72 | train |
flatangle/flatlib | flatlib/ephem/eph.py | nextSunrise | def nextSunrise(jd, lat, lon):
""" Returns the JD of the next sunrise. """
return swe.sweNextTransit(const.SUN, jd, lat, lon, 'RISE') | python | def nextSunrise(jd, lat, lon):
""" Returns the JD of the next sunrise. """
return swe.sweNextTransit(const.SUN, jd, lat, lon, 'RISE') | [
"def",
"nextSunrise",
"(",
"jd",
",",
"lat",
",",
"lon",
")",
":",
"return",
"swe",
".",
"sweNextTransit",
"(",
"const",
".",
"SUN",
",",
"jd",
",",
"lat",
",",
"lon",
",",
"'RISE'",
")"
] | Returns the JD of the next sunrise. | [
"Returns",
"the",
"JD",
"of",
"the",
"next",
"sunrise",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/eph.py#L88-L90 | train |
flatangle/flatlib | flatlib/ephem/eph.py | nextSunset | def nextSunset(jd, lat, lon):
""" Returns the JD of the next sunset. """
return swe.sweNextTransit(const.SUN, jd, lat, lon, 'SET') | python | def nextSunset(jd, lat, lon):
""" Returns the JD of the next sunset. """
return swe.sweNextTransit(const.SUN, jd, lat, lon, 'SET') | [
"def",
"nextSunset",
"(",
"jd",
",",
"lat",
",",
"lon",
")",
":",
"return",
"swe",
".",
"sweNextTransit",
"(",
"const",
".",
"SUN",
",",
"jd",
",",
"lat",
",",
"lon",
",",
"'SET'",
")"
] | Returns the JD of the next sunset. | [
"Returns",
"the",
"JD",
"of",
"the",
"next",
"sunset",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/eph.py#L92-L94 | train |
flatangle/flatlib | flatlib/ephem/eph.py | _signInfo | 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
}) | python | 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
}) | [
"def",
"_signInfo",
"(",
"obj",
")",
":",
"lon",
"=",
"obj",
"[",
"'lon'",
"]",
"obj",
".",
"update",
"(",
"{",
"'sign'",
":",
"const",
".",
"LIST_SIGNS",
"[",
"int",
"(",
"lon",
"/",
"30",
")",
"]",
",",
"'signlon'",
":",
"lon",
"%",
"30",
"}"... | Appends the sign id and longitude to an object. | [
"Appends",
"the",
"sign",
"id",
"and",
"longitude",
"to",
"an",
"object",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/eph.py#L114-L120 | train |
flatangle/flatlib | flatlib/ephem/tools.py | pfLon | def pfLon(jd, lat, lon):
""" Returns the ecliptic longitude of Pars Fortuna.
It considers diurnal or nocturnal conditions.
"""
sun = swe.sweObjectLon(const.SUN, jd)
moon = swe.sweObjectLon(const.MOON, jd)
asc = swe.sweHousesLon(jd, lat, lon,
const.HOUSES_DEFAULT)[1][0]
if isDiurnal(jd, lat, lon):
return angle.norm(asc + moon - sun)
else:
return angle.norm(asc + sun - moon) | python | def pfLon(jd, lat, lon):
""" Returns the ecliptic longitude of Pars Fortuna.
It considers diurnal or nocturnal conditions.
"""
sun = swe.sweObjectLon(const.SUN, jd)
moon = swe.sweObjectLon(const.MOON, jd)
asc = swe.sweHousesLon(jd, lat, lon,
const.HOUSES_DEFAULT)[1][0]
if isDiurnal(jd, lat, lon):
return angle.norm(asc + moon - sun)
else:
return angle.norm(asc + sun - moon) | [
"def",
"pfLon",
"(",
"jd",
",",
"lat",
",",
"lon",
")",
":",
"sun",
"=",
"swe",
".",
"sweObjectLon",
"(",
"const",
".",
"SUN",
",",
"jd",
")",
"moon",
"=",
"swe",
".",
"sweObjectLon",
"(",
"const",
".",
"MOON",
",",
"jd",
")",
"asc",
"=",
"swe"... | Returns the ecliptic longitude of Pars Fortuna.
It considers diurnal or nocturnal conditions. | [
"Returns",
"the",
"ecliptic",
"longitude",
"of",
"Pars",
"Fortuna",
".",
"It",
"considers",
"diurnal",
"or",
"nocturnal",
"conditions",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/tools.py#L23-L36 | train |
flatangle/flatlib | flatlib/ephem/tools.py | isDiurnal | 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) | python | 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) | [
"def",
"isDiurnal",
"(",
"jd",
",",
"lat",
",",
"lon",
")",
":",
"sun",
"=",
"swe",
".",
"sweObject",
"(",
"const",
".",
"SUN",
",",
"jd",
")",
"mc",
"=",
"swe",
".",
"sweHousesLon",
"(",
"jd",
",",
"lat",
",",
"lon",
",",
"const",
".",
"HOUSES... | Returns true if the sun is above the horizon
of a given date and location. | [
"Returns",
"true",
"if",
"the",
"sun",
"is",
"above",
"the",
"horizon",
"of",
"a",
"given",
"date",
"and",
"location",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/tools.py#L41-L51 | train |
flatangle/flatlib | flatlib/ephem/tools.py | syzygyJD | 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 | python | 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 | [
"def",
"syzygyJD",
"(",
"jd",
")",
":",
"sun",
"=",
"swe",
".",
"sweObjectLon",
"(",
"const",
".",
"SUN",
",",
"jd",
")",
"moon",
"=",
"swe",
".",
"sweObjectLon",
"(",
"const",
".",
"MOON",
",",
"jd",
")",
"dist",
"=",
"angle",
".",
"distance",
"... | Finds the latest new or full moon and
returns the julian date of that event. | [
"Finds",
"the",
"latest",
"new",
"or",
"full",
"moon",
"and",
"returns",
"the",
"julian",
"date",
"of",
"that",
"event",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/tools.py#L56-L73 | train |
flatangle/flatlib | flatlib/ephem/tools.py | solarReturnJD | 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 | python | 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 | [
"def",
"solarReturnJD",
"(",
"jd",
",",
"lon",
",",
"forward",
"=",
"True",
")",
":",
"sun",
"=",
"swe",
".",
"sweObjectLon",
"(",
"const",
".",
"SUN",
",",
"jd",
")",
"if",
"forward",
":",
"dist",
"=",
"angle",
".",
"distance",
"(",
"sun",
",",
... | Finds the julian date before or after
'jd' when the sun is at longitude 'lon'.
It searches forward by default. | [
"Finds",
"the",
"julian",
"date",
"before",
"or",
"after",
"jd",
"when",
"the",
"sun",
"is",
"at",
"longitude",
"lon",
".",
"It",
"searches",
"forward",
"by",
"default",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/tools.py#L75-L91 | train |
flatangle/flatlib | flatlib/ephem/tools.py | nextStationJD | def nextStationJD(ID, jd):
""" Finds the aproximate julian date of the
next station of a planet.
"""
speed = swe.sweObject(ID, jd)['lonspeed']
for i in range(2000):
nextjd = jd + i / 2
nextspeed = swe.sweObject(ID, nextjd)['lonspeed']
if speed * nextspeed <= 0:
return nextjd
return None | python | def nextStationJD(ID, jd):
""" Finds the aproximate julian date of the
next station of a planet.
"""
speed = swe.sweObject(ID, jd)['lonspeed']
for i in range(2000):
nextjd = jd + i / 2
nextspeed = swe.sweObject(ID, nextjd)['lonspeed']
if speed * nextspeed <= 0:
return nextjd
return None | [
"def",
"nextStationJD",
"(",
"ID",
",",
"jd",
")",
":",
"speed",
"=",
"swe",
".",
"sweObject",
"(",
"ID",
",",
"jd",
")",
"[",
"'lonspeed'",
"]",
"for",
"i",
"in",
"range",
"(",
"2000",
")",
":",
"nextjd",
"=",
"jd",
"+",
"i",
"/",
"2",
"nextsp... | Finds the aproximate julian date of the
next station of a planet. | [
"Finds",
"the",
"aproximate",
"julian",
"date",
"of",
"the",
"next",
"station",
"of",
"a",
"planet",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/tools.py#L96-L107 | train |
flatangle/flatlib | scripts/utils.py | clean_caches | def clean_caches(path):
"""
Removes all python cache files recursively on a path.
:param path: the path
:return: None
"""
for dirname, subdirlist, filelist in os.walk(path):
for f in filelist:
if f.endswith('pyc'):
try:
os.remove(os.path.join(dirname, f))
except FileNotFoundError:
pass
if dirname.endswith('__pycache__'):
shutil.rmtree(dirname) | python | def clean_caches(path):
"""
Removes all python cache files recursively on a path.
:param path: the path
:return: None
"""
for dirname, subdirlist, filelist in os.walk(path):
for f in filelist:
if f.endswith('pyc'):
try:
os.remove(os.path.join(dirname, f))
except FileNotFoundError:
pass
if dirname.endswith('__pycache__'):
shutil.rmtree(dirname) | [
"def",
"clean_caches",
"(",
"path",
")",
":",
"for",
"dirname",
",",
"subdirlist",
",",
"filelist",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"f",
"in",
"filelist",
":",
"if",
"f",
".",
"endswith",
"(",
"'pyc'",
")",
":",
"try",
":",
... | Removes all python cache files recursively on a path.
:param path: the path
:return: None | [
"Removes",
"all",
"python",
"cache",
"files",
"recursively",
"on",
"a",
"path",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/scripts/utils.py#L18-L36 | train |
flatangle/flatlib | scripts/utils.py | clean_py_files | def clean_py_files(path):
"""
Removes all .py files.
:param path: the path
:return: None
"""
for dirname, subdirlist, filelist in os.walk(path):
for f in filelist:
if f.endswith('py'):
os.remove(os.path.join(dirname, f)) | python | def clean_py_files(path):
"""
Removes all .py files.
:param path: the path
:return: None
"""
for dirname, subdirlist, filelist in os.walk(path):
for f in filelist:
if f.endswith('py'):
os.remove(os.path.join(dirname, f)) | [
"def",
"clean_py_files",
"(",
"path",
")",
":",
"for",
"dirname",
",",
"subdirlist",
",",
"filelist",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"f",
"in",
"filelist",
":",
"if",
"f",
".",
"endswith",
"(",
"'py'",
")",
":",
"os",
".",
... | Removes all .py files.
:param path: the path
:return: None | [
"Removes",
"all",
".",
"py",
"files",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/scripts/utils.py#L39-L51 | train |
flatangle/flatlib | flatlib/geopos.py | toFloat | def toFloat(value):
""" Converts angle representation to float.
Accepts angles and strings such as "12W30:00".
"""
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) | python | def toFloat(value):
""" Converts angle representation to float.
Accepts angles and strings such as "12W30:00".
"""
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) | [
"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'",... | Converts angle representation to float.
Accepts angles and strings such as "12W30:00". | [
"Converts",
"angle",
"representation",
"to",
"float",
".",
"Accepts",
"angles",
"and",
"strings",
"such",
"as",
"12W30",
":",
"00",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/geopos.py#L29-L41 | train |
flatangle/flatlib | flatlib/geopos.py | toString | 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:] | python | 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:] | [
"def",
"toString",
"(",
"value",
",",
"mode",
")",
":",
"string",
"=",
"angle",
".",
"toString",
"(",
"value",
")",
"sign",
"=",
"string",
"[",
"0",
"]",
"separator",
"=",
"CHAR",
"[",
"mode",
"]",
"[",
"sign",
"]",
"string",
"=",
"string",
".",
... | Converts angle float to string.
Mode refers to LAT/LON. | [
"Converts",
"angle",
"float",
"to",
"string",
".",
"Mode",
"refers",
"to",
"LAT",
"/",
"LON",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/geopos.py#L47-L56 | train |
flatangle/flatlib | flatlib/geopos.py | GeoPos.strings | def strings(self):
""" Return lat/lon as strings. """
return [
toString(self.lat, LAT),
toString(self.lon, LON)
] | python | def strings(self):
""" Return lat/lon as strings. """
return [
toString(self.lat, LAT),
toString(self.lon, LON)
] | [
"def",
"strings",
"(",
"self",
")",
":",
"return",
"[",
"toString",
"(",
"self",
".",
"lat",
",",
"LAT",
")",
",",
"toString",
"(",
"self",
".",
"lon",
",",
"LON",
")",
"]"
] | Return lat/lon as strings. | [
"Return",
"lat",
"/",
"lon",
"as",
"strings",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/geopos.py#L84-L89 | train |
flatangle/flatlib | flatlib/aspects.py | _orbList | 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
] | python | 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
] | [
"def",
"_orbList",
"(",
"obj1",
",",
"obj2",
",",
"aspList",
")",
":",
"sep",
"=",
"angle",
".",
"closestdistance",
"(",
"obj1",
".",
"lon",
",",
"obj2",
".",
"lon",
")",
"absSep",
"=",
"abs",
"(",
"sep",
")",
"return",
"[",
"{",
"'type'",
":",
"... | Returns a list with the orb and angular
distances from obj1 to obj2, considering a
list of possible aspects. | [
"Returns",
"a",
"list",
"with",
"the",
"orb",
"and",
"angular",
"distances",
"from",
"obj1",
"to",
"obj2",
"considering",
"a",
"list",
"of",
"possible",
"aspects",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/aspects.py#L43-L57 | train |
flatangle/flatlib | flatlib/aspects.py | _aspectDict | def _aspectDict(obj1, obj2, aspList):
""" Returns the properties of the aspect of
obj1 to obj2, considering a list of possible
aspects.
This function makes the following assumptions:
- Syzygy does not start aspects but receives
any aspect.
- Pars Fortuna and Moon Nodes only starts
conjunctions but receive any aspect.
- All other objects can start and receive
any aspect.
Note: this function returns the aspect
even if it is not within the orb of obj1
(but is within the orb of obj2).
"""
# 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 | python | def _aspectDict(obj1, obj2, aspList):
""" Returns the properties of the aspect of
obj1 to obj2, considering a list of possible
aspects.
This function makes the following assumptions:
- Syzygy does not start aspects but receives
any aspect.
- Pars Fortuna and Moon Nodes only starts
conjunctions but receive any aspect.
- All other objects can start and receive
any aspect.
Note: this function returns the aspect
even if it is not within the orb of obj1
(but is within the orb of obj2).
"""
# 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 | [
"def",
"_aspectDict",
"(",
"obj1",
",",
"obj2",
",",
"aspList",
")",
":",
"# Ignore aspects from same and Syzygy",
"if",
"obj1",
"==",
"obj2",
"or",
"obj1",
".",
"id",
"==",
"const",
".",
"SYZYGY",
":",
"return",
"None",
"orbs",
"=",
"_orbList",
"(",
"obj1... | Returns the properties of the aspect of
obj1 to obj2, considering a list of possible
aspects.
This function makes the following assumptions:
- Syzygy does not start aspects but receives
any aspect.
- Pars Fortuna and Moon Nodes only starts
conjunctions but receive any aspect.
- All other objects can start and receive
any aspect.
Note: this function returns the aspect
even if it is not within the orb of obj1
(but is within the orb of obj2). | [
"Returns",
"the",
"properties",
"of",
"the",
"aspect",
"of",
"obj1",
"to",
"obj2",
"considering",
"a",
"list",
"of",
"possible",
"aspects",
".",
"This",
"function",
"makes",
"the",
"following",
"assumptions",
":",
"-",
"Syzygy",
"does",
"not",
"start",
"aspe... | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/aspects.py#L59-L106 | train |
flatangle/flatlib | flatlib/aspects.py | _aspectProperties | 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 | python | 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 | [
"def",
"_aspectProperties",
"(",
"obj1",
",",
"obj2",
",",
"aspDict",
")",
":",
"orb",
"=",
"aspDict",
"[",
"'orb'",
"]",
"asp",
"=",
"aspDict",
"[",
"'type'",
"]",
"sep",
"=",
"aspDict",
"[",
"'separation'",
"]",
"# Properties",
"prop1",
"=",
"{",
"'i... | 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. | [
"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",
"... | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/aspects.py#L108-L181 | train |
flatangle/flatlib | flatlib/aspects.py | _getActivePassive | def _getActivePassive(obj1, obj2):
""" Returns which is the active and the passive objects. """
speed1 = abs(obj1.lonspeed) if obj1.isPlanet() else -1.0
speed2 = abs(obj2.lonspeed) if obj2.isPlanet() else -1.0
if speed1 > speed2:
return {
'active': obj1,
'passive': obj2
}
else:
return {
'active': obj2,
'passive': obj1
} | python | def _getActivePassive(obj1, obj2):
""" Returns which is the active and the passive objects. """
speed1 = abs(obj1.lonspeed) if obj1.isPlanet() else -1.0
speed2 = abs(obj2.lonspeed) if obj2.isPlanet() else -1.0
if speed1 > speed2:
return {
'active': obj1,
'passive': obj2
}
else:
return {
'active': obj2,
'passive': obj1
} | [
"def",
"_getActivePassive",
"(",
"obj1",
",",
"obj2",
")",
":",
"speed1",
"=",
"abs",
"(",
"obj1",
".",
"lonspeed",
")",
"if",
"obj1",
".",
"isPlanet",
"(",
")",
"else",
"-",
"1.0",
"speed2",
"=",
"abs",
"(",
"obj2",
".",
"lonspeed",
")",
"if",
"ob... | Returns which is the active and the passive objects. | [
"Returns",
"which",
"is",
"the",
"active",
"and",
"the",
"passive",
"objects",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/aspects.py#L183-L196 | train |
flatangle/flatlib | flatlib/aspects.py | aspectType | 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 | python | 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 | [
"def",
"aspectType",
"(",
"obj1",
",",
"obj2",
",",
"aspList",
")",
":",
"ap",
"=",
"_getActivePassive",
"(",
"obj1",
",",
"obj2",
")",
"aspDict",
"=",
"_aspectDict",
"(",
"ap",
"[",
"'active'",
"]",
",",
"ap",
"[",
"'passive'",
"]",
",",
"aspList",
... | Returns the aspect type between objects considering
a list of possible aspect types. | [
"Returns",
"the",
"aspect",
"type",
"between",
"objects",
"considering",
"a",
"list",
"of",
"possible",
"aspect",
"types",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/aspects.py#L201-L208 | train |
flatangle/flatlib | flatlib/aspects.py | hasAspect | def hasAspect(obj1, obj2, aspList):
""" Returns if there is an aspect between objects
considering a list of possible aspect types.
"""
aspType = aspectType(obj1, obj2, aspList)
return aspType != const.NO_ASPECT | python | def hasAspect(obj1, obj2, aspList):
""" Returns if there is an aspect between objects
considering a list of possible aspect types.
"""
aspType = aspectType(obj1, obj2, aspList)
return aspType != const.NO_ASPECT | [
"def",
"hasAspect",
"(",
"obj1",
",",
"obj2",
",",
"aspList",
")",
":",
"aspType",
"=",
"aspectType",
"(",
"obj1",
",",
"obj2",
",",
"aspList",
")",
"return",
"aspType",
"!=",
"const",
".",
"NO_ASPECT"
] | Returns if there is an aspect between objects
considering a list of possible aspect types. | [
"Returns",
"if",
"there",
"is",
"an",
"aspect",
"between",
"objects",
"considering",
"a",
"list",
"of",
"possible",
"aspect",
"types",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/aspects.py#L210-L216 | train |
flatangle/flatlib | flatlib/aspects.py | isAspecting | 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 | python | 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 | [
"def",
"isAspecting",
"(",
"obj1",
",",
"obj2",
",",
"aspList",
")",
":",
"aspDict",
"=",
"_aspectDict",
"(",
"obj1",
",",
"obj2",
",",
"aspList",
")",
"if",
"aspDict",
":",
"return",
"aspDict",
"[",
"'orb'",
"]",
"<",
"obj1",
".",
"orb",
"(",
")",
... | Returns if obj1 aspects obj2 within its orb,
considering a list of possible aspect types. | [
"Returns",
"if",
"obj1",
"aspects",
"obj2",
"within",
"its",
"orb",
"considering",
"a",
"list",
"of",
"possible",
"aspect",
"types",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/aspects.py#L218-L226 | train |
flatangle/flatlib | flatlib/aspects.py | getAspect | def getAspect(obj1, obj2, aspList):
""" Returns an Aspect object for the aspect between two
objects considering a list of possible aspect types.
"""
ap = _getActivePassive(obj1, obj2)
aspDict = _aspectDict(ap['active'], ap['passive'], aspList)
if not aspDict:
aspDict = {
'type': const.NO_ASPECT,
'orb': 0,
'separation': 0,
}
aspProp = _aspectProperties(ap['active'], ap['passive'], aspDict)
return Aspect(aspProp) | python | def getAspect(obj1, obj2, aspList):
""" Returns an Aspect object for the aspect between two
objects considering a list of possible aspect types.
"""
ap = _getActivePassive(obj1, obj2)
aspDict = _aspectDict(ap['active'], ap['passive'], aspList)
if not aspDict:
aspDict = {
'type': const.NO_ASPECT,
'orb': 0,
'separation': 0,
}
aspProp = _aspectProperties(ap['active'], ap['passive'], aspDict)
return Aspect(aspProp) | [
"def",
"getAspect",
"(",
"obj1",
",",
"obj2",
",",
"aspList",
")",
":",
"ap",
"=",
"_getActivePassive",
"(",
"obj1",
",",
"obj2",
")",
"aspDict",
"=",
"_aspectDict",
"(",
"ap",
"[",
"'active'",
"]",
",",
"ap",
"[",
"'passive'",
"]",
",",
"aspList",
"... | Returns an Aspect object for the aspect between two
objects considering a list of possible aspect types. | [
"Returns",
"an",
"Aspect",
"object",
"for",
"the",
"aspect",
"between",
"two",
"objects",
"considering",
"a",
"list",
"of",
"possible",
"aspect",
"types",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/aspects.py#L228-L242 | train |
flatangle/flatlib | flatlib/aspects.py | Aspect.movement | 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 | python | 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 | [
"def",
"movement",
"(",
"self",
")",
":",
"mov",
"=",
"self",
".",
"active",
".",
"movement",
"if",
"self",
".",
"orb",
"<",
"1",
"and",
"mov",
"==",
"const",
".",
"SEPARATIVE",
":",
"mov",
"=",
"const",
".",
"EXACT",
"return",
"mov"
] | 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. | [
"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",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/aspects.py#L275-L285 | train |
flatangle/flatlib | flatlib/aspects.py | Aspect.getRole | def getRole(self, ID):
""" Returns the role (active or passive) of an object
in this aspect.
"""
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 | python | def getRole(self, ID):
""" Returns the role (active or passive) of an object
in this aspect.
"""
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 | [
"def",
"getRole",
"(",
"self",
",",
"ID",
")",
":",
"if",
"self",
".",
"active",
".",
"id",
"==",
"ID",
":",
"return",
"{",
"'role'",
":",
"'active'",
",",
"'inOrb'",
":",
"self",
".",
"active",
".",
"inOrb",
",",
"'movement'",
":",
"self",
".",
... | Returns the role (active or passive) of an object
in this aspect. | [
"Returns",
"the",
"role",
"(",
"active",
"or",
"passive",
")",
"of",
"an",
"object",
"in",
"this",
"aspect",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/aspects.py#L298-L315 | train |
flatangle/flatlib | flatlib/dignities/essential.py | setFaces | def setFaces(variant):
"""
Sets the default faces variant
"""
global FACES
if variant == CHALDEAN_FACES:
FACES = tables.CHALDEAN_FACES
else:
FACES = tables.TRIPLICITY_FACES | python | def setFaces(variant):
"""
Sets the default faces variant
"""
global FACES
if variant == CHALDEAN_FACES:
FACES = tables.CHALDEAN_FACES
else:
FACES = tables.TRIPLICITY_FACES | [
"def",
"setFaces",
"(",
"variant",
")",
":",
"global",
"FACES",
"if",
"variant",
"==",
"CHALDEAN_FACES",
":",
"FACES",
"=",
"tables",
".",
"CHALDEAN_FACES",
"else",
":",
"FACES",
"=",
"tables",
".",
"TRIPLICITY_FACES"
] | Sets the default faces variant | [
"Sets",
"the",
"default",
"faces",
"variant"
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/dignities/essential.py#L33-L42 | train |
flatangle/flatlib | flatlib/dignities/essential.py | setTerms | def setTerms(variant):
"""
Sets the default terms of the Dignities
table.
"""
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 | python | def setTerms(variant):
"""
Sets the default terms of the Dignities
table.
"""
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 | [
"def",
"setTerms",
"(",
"variant",
")",
":",
"global",
"TERMS",
"if",
"variant",
"==",
"EGYPTIAN_TERMS",
":",
"TERMS",
"=",
"tables",
".",
"EGYPTIAN_TERMS",
"elif",
"variant",
"==",
"TETRABIBLOS_TERMS",
":",
"TERMS",
"=",
"tables",
".",
"TETRABIBLOS_TERMS",
"e... | Sets the default terms of the Dignities
table. | [
"Sets",
"the",
"default",
"terms",
"of",
"the",
"Dignities",
"table",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/dignities/essential.py#L45-L57 | train |
flatangle/flatlib | flatlib/dignities/essential.py | term | 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 | python | 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 | [
"def",
"term",
"(",
"sign",
",",
"lon",
")",
":",
"terms",
"=",
"TERMS",
"[",
"sign",
"]",
"for",
"(",
"ID",
",",
"a",
",",
"b",
")",
"in",
"terms",
":",
"if",
"(",
"a",
"<=",
"lon",
"<",
"b",
")",
":",
"return",
"ID",
"return",
"None"
] | Returns the term for a sign and longitude. | [
"Returns",
"the",
"term",
"for",
"a",
"sign",
"and",
"longitude",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/dignities/essential.py#L98-L104 | train |
flatangle/flatlib | flatlib/dignities/essential.py | face | 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] | python | 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] | [
"def",
"face",
"(",
"sign",
",",
"lon",
")",
":",
"faces",
"=",
"FACES",
"[",
"sign",
"]",
"if",
"lon",
"<",
"10",
":",
"return",
"faces",
"[",
"0",
"]",
"elif",
"lon",
"<",
"20",
":",
"return",
"faces",
"[",
"1",
"]",
"else",
":",
"return",
... | Returns the face for a sign and longitude. | [
"Returns",
"the",
"face",
"for",
"a",
"sign",
"and",
"longitude",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/dignities/essential.py#L106-L114 | train |
flatangle/flatlib | flatlib/dignities/essential.py | getInfo | def getInfo(sign, lon):
""" Returns the complete essential dignities
for a sign and longitude.
"""
return {
'ruler': ruler(sign),
'exalt': exalt(sign),
'dayTrip': dayTrip(sign),
'nightTrip': nightTrip(sign),
'partTrip': partTrip(sign),
'term': term(sign, lon),
'face': face(sign, lon),
'exile': exile(sign),
'fall': fall(sign)
} | python | def getInfo(sign, lon):
""" Returns the complete essential dignities
for a sign and longitude.
"""
return {
'ruler': ruler(sign),
'exalt': exalt(sign),
'dayTrip': dayTrip(sign),
'nightTrip': nightTrip(sign),
'partTrip': partTrip(sign),
'term': term(sign, lon),
'face': face(sign, lon),
'exile': exile(sign),
'fall': fall(sign)
} | [
"def",
"getInfo",
"(",
"sign",
",",
"lon",
")",
":",
"return",
"{",
"'ruler'",
":",
"ruler",
"(",
"sign",
")",
",",
"'exalt'",
":",
"exalt",
"(",
"sign",
")",
",",
"'dayTrip'",
":",
"dayTrip",
"(",
"sign",
")",
",",
"'nightTrip'",
":",
"nightTrip",
... | Returns the complete essential dignities
for a sign and longitude. | [
"Returns",
"the",
"complete",
"essential",
"dignities",
"for",
"a",
"sign",
"and",
"longitude",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/dignities/essential.py#L119-L134 | train |
flatangle/flatlib | flatlib/dignities/essential.py | isPeregrine | 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 | python | 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 | [
"def",
"isPeregrine",
"(",
"ID",
",",
"sign",
",",
"lon",
")",
":",
"info",
"=",
"getInfo",
"(",
"sign",
",",
"lon",
")",
"for",
"dign",
",",
"objID",
"in",
"info",
".",
"items",
"(",
")",
":",
"if",
"dign",
"not",
"in",
"[",
"'exile'",
",",
"'... | Returns if an object is peregrine
on a sign and longitude. | [
"Returns",
"if",
"an",
"object",
"is",
"peregrine",
"on",
"a",
"sign",
"and",
"longitude",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/dignities/essential.py#L136-L145 | train |
flatangle/flatlib | flatlib/dignities/essential.py | score | 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]) | python | 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]) | [
"def",
"score",
"(",
"ID",
",",
"sign",
",",
"lon",
")",
":",
"info",
"=",
"getInfo",
"(",
"sign",
",",
"lon",
")",
"dignities",
"=",
"[",
"dign",
"for",
"(",
"dign",
",",
"objID",
")",
"in",
"info",
".",
"items",
"(",
")",
"if",
"objID",
"==",... | Returns the score of an object on
a sign and longitude. | [
"Returns",
"the",
"score",
"of",
"an",
"object",
"on",
"a",
"sign",
"and",
"longitude",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/dignities/essential.py#L162-L169 | train |
flatangle/flatlib | flatlib/dignities/essential.py | almutem | 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] | python | 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] | [
"def",
"almutem",
"(",
"sign",
",",
"lon",
")",
":",
"planets",
"=",
"const",
".",
"LIST_SEVEN_PLANETS",
"res",
"=",
"[",
"None",
",",
"0",
"]",
"for",
"ID",
"in",
"planets",
":",
"sc",
"=",
"score",
"(",
"ID",
",",
"sign",
",",
"lon",
")",
"if",... | Returns the almutem for a given
sign and longitude. | [
"Returns",
"the",
"almutem",
"for",
"a",
"given",
"sign",
"and",
"longitude",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/dignities/essential.py#L171-L182 | train |
flatangle/flatlib | flatlib/dignities/essential.py | EssentialInfo.getDignities | 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 | python | 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 | [
"def",
"getDignities",
"(",
"self",
")",
":",
"info",
"=",
"self",
".",
"getInfo",
"(",
")",
"dignities",
"=",
"[",
"dign",
"for",
"(",
"dign",
",",
"objID",
")",
"in",
"info",
".",
"items",
"(",
")",
"if",
"objID",
"==",
"self",
".",
"obj",
".",... | Returns the dignities belonging to this object. | [
"Returns",
"the",
"dignities",
"belonging",
"to",
"this",
"object",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/dignities/essential.py#L208-L213 | train |
flatangle/flatlib | flatlib/dignities/essential.py | EssentialInfo.isPeregrine | def isPeregrine(self):
""" Returns if this object is peregrine. """
return isPeregrine(self.obj.id,
self.obj.sign,
self.obj.signlon) | python | def isPeregrine(self):
""" Returns if this object is peregrine. """
return isPeregrine(self.obj.id,
self.obj.sign,
self.obj.signlon) | [
"def",
"isPeregrine",
"(",
"self",
")",
":",
"return",
"isPeregrine",
"(",
"self",
".",
"obj",
".",
"id",
",",
"self",
".",
"obj",
".",
"sign",
",",
"self",
".",
"obj",
".",
"signlon",
")"
] | Returns if this object is peregrine. | [
"Returns",
"if",
"this",
"object",
"is",
"peregrine",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/dignities/essential.py#L215-L219 | train |
flatangle/flatlib | flatlib/predictives/returns.py | _computeChart | def _computeChart(chart, date):
""" Internal function to return a new chart for
a specific date using properties from old chart.
"""
pos = chart.pos
hsys = chart.hsys
IDs = [obj.id for obj in chart.objects]
return Chart(date, pos, IDs=IDs, hsys=hsys) | python | def _computeChart(chart, date):
""" Internal function to return a new chart for
a specific date using properties from old chart.
"""
pos = chart.pos
hsys = chart.hsys
IDs = [obj.id for obj in chart.objects]
return Chart(date, pos, IDs=IDs, hsys=hsys) | [
"def",
"_computeChart",
"(",
"chart",
",",
"date",
")",
":",
"pos",
"=",
"chart",
".",
"pos",
"hsys",
"=",
"chart",
".",
"hsys",
"IDs",
"=",
"[",
"obj",
".",
"id",
"for",
"obj",
"in",
"chart",
".",
"objects",
"]",
"return",
"Chart",
"(",
"date",
... | Internal function to return a new chart for
a specific date using properties from old chart. | [
"Internal",
"function",
"to",
"return",
"a",
"new",
"chart",
"for",
"a",
"specific",
"date",
"using",
"properties",
"from",
"old",
"chart",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/predictives/returns.py#L18-L26 | train |
flatangle/flatlib | flatlib/predictives/returns.py | nextSolarReturn | 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) | python | 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) | [
"def",
"nextSolarReturn",
"(",
"chart",
",",
"date",
")",
":",
"sun",
"=",
"chart",
".",
"getObject",
"(",
"const",
".",
"SUN",
")",
"srDate",
"=",
"ephem",
".",
"nextSolarReturn",
"(",
"date",
",",
"sun",
".",
"lon",
")",
"return",
"_computeChart",
"(... | Returns the solar return of a Chart
after a specific date. | [
"Returns",
"the",
"solar",
"return",
"of",
"a",
"Chart",
"after",
"a",
"specific",
"date",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/predictives/returns.py#L28-L35 | train |
flatangle/flatlib | flatlib/tools/planetarytime.py | hourTable | def hourTable(date, pos):
""" Creates the planetary hour table for a date
and position.
The table includes both diurnal and nocturnal
hour sequences and each of the 24 entries (12 * 2)
are like (startJD, endJD, ruler).
"""
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 | python | def hourTable(date, pos):
""" Creates the planetary hour table for a date
and position.
The table includes both diurnal and nocturnal
hour sequences and each of the 24 entries (12 * 2)
are like (startJD, endJD, ruler).
"""
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 | [
"def",
"hourTable",
"(",
"date",
",",
"pos",
")",
":",
"lastSunrise",
"=",
"ephem",
".",
"lastSunrise",
"(",
"date",
",",
"pos",
")",
"middleSunset",
"=",
"ephem",
".",
"nextSunset",
"(",
"lastSunrise",
",",
"pos",
")",
"nextSunrise",
"=",
"ephem",
".",
... | Creates the planetary hour table for a date
and position.
The table includes both diurnal and nocturnal
hour sequences and each of the 24 entries (12 * 2)
are like (startJD, endJD, ruler). | [
"Creates",
"the",
"planetary",
"hour",
"table",
"for",
"a",
"date",
"and",
"position",
".",
"The",
"table",
"includes",
"both",
"diurnal",
"and",
"nocturnal",
"hour",
"sequences",
"and",
"each",
"of",
"the",
"24",
"entries",
"(",
"12",
"*",
"2",
")",
"ar... | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/tools/planetarytime.py#L65-L96 | train |
flatangle/flatlib | flatlib/tools/planetarytime.py | getHourTable | def getHourTable(date, pos):
""" Returns an HourTable object. """
table = hourTable(date, pos)
return HourTable(table, date) | python | def getHourTable(date, pos):
""" Returns an HourTable object. """
table = hourTable(date, pos)
return HourTable(table, date) | [
"def",
"getHourTable",
"(",
"date",
",",
"pos",
")",
":",
"table",
"=",
"hourTable",
"(",
"date",
",",
"pos",
")",
"return",
"HourTable",
"(",
"table",
",",
"date",
")"
] | Returns an HourTable object. | [
"Returns",
"an",
"HourTable",
"object",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/tools/planetarytime.py#L98-L101 | train |
flatangle/flatlib | flatlib/tools/planetarytime.py | HourTable.index | def index(self, date):
""" Returns the index of a date in the table. """
for (i, (start, end, ruler)) in enumerate(self.table):
if start <= date.jd <= end:
return i
return None | python | def index(self, date):
""" Returns the index of a date in the table. """
for (i, (start, end, ruler)) in enumerate(self.table):
if start <= date.jd <= end:
return i
return None | [
"def",
"index",
"(",
"self",
",",
"date",
")",
":",
"for",
"(",
"i",
",",
"(",
"start",
",",
"end",
",",
"ruler",
")",
")",
"in",
"enumerate",
"(",
"self",
".",
"table",
")",
":",
"if",
"start",
"<=",
"date",
".",
"jd",
"<=",
"end",
":",
"ret... | Returns the index of a date in the table. | [
"Returns",
"the",
"index",
"of",
"a",
"date",
"in",
"the",
"table",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/tools/planetarytime.py#L119-L124 | train |
flatangle/flatlib | flatlib/tools/planetarytime.py | HourTable.indexInfo | def indexInfo(self, index):
""" Returns information about a specific
planetary time.
"""
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 | python | def indexInfo(self, index):
""" Returns information about a specific
planetary time.
"""
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 | [
"def",
"indexInfo",
"(",
"self",
",",
"index",
")",
":",
"entry",
"=",
"self",
".",
"table",
"[",
"index",
"]",
"info",
"=",
"{",
"# Default is diurnal",
"'mode'",
":",
"'Day'",
",",
"'ruler'",
":",
"self",
".",
"dayRuler",
"(",
")",
",",
"'dayRuler'",... | Returns information about a specific
planetary time. | [
"Returns",
"information",
"about",
"a",
"specific",
"planetary",
"time",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/tools/planetarytime.py#L157-L182 | train |
flatangle/flatlib | flatlib/predictives/profections.py | compute | 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 | python | 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 | [
"def",
"compute",
"(",
"chart",
",",
"date",
",",
"fixedObjects",
"=",
"False",
")",
":",
"sun",
"=",
"chart",
".",
"getObject",
"(",
"const",
".",
"SUN",
")",
"prevSr",
"=",
"ephem",
".",
"prevSolarReturn",
"(",
"date",
",",
"sun",
".",
"lon",
")",
... | Returns a profection chart for a given
date. Receives argument 'fixedObjects' to
fix chart objects in their natal locations. | [
"Returns",
"a",
"profection",
"chart",
"for",
"a",
"given",
"date",
".",
"Receives",
"argument",
"fixedObjects",
"to",
"fix",
"chart",
"objects",
"in",
"their",
"natal",
"locations",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/predictives/profections.py#L16-L44 | train |
flatangle/flatlib | flatlib/protocols/behavior.py | _merge | 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_) | python | 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_) | [
"def",
"_merge",
"(",
"listA",
",",
"listB",
")",
":",
"listA",
"=",
"[",
"x",
".",
"id",
"for",
"x",
"in",
"listA",
"]",
"listB",
"=",
"[",
"x",
".",
"id",
"for",
"x",
"in",
"listB",
"]",
"listA",
".",
"extend",
"(",
"listB",
")",
"set_",
"=... | Merges two list of objects removing
repetitions. | [
"Merges",
"two",
"list",
"of",
"objects",
"removing",
"repetitions",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/protocols/behavior.py#L16-L25 | train |
flatangle/flatlib | flatlib/protocols/behavior.py | compute | 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 | python | 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 | [
"def",
"compute",
"(",
"chart",
")",
":",
"factors",
"=",
"[",
"]",
"# Planets in House1 or Conjunct Asc",
"house1",
"=",
"chart",
".",
"getHouse",
"(",
"const",
".",
"HOUSE1",
")",
"planetsHouse1",
"=",
"chart",
".",
"objects",
".",
"getObjectsInHouse",
"(",
... | Computes the behavior. | [
"Computes",
"the",
"behavior",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/protocols/behavior.py#L28-L69 | train |
flatangle/flatlib | flatlib/dignities/tables.py | termLons | def termLons(TERMS):
""" Returns a list with the absolute longitude
of all terms.
"""
res = []
for i, sign in enumerate(SIGN_LIST):
termList = TERMS[sign]
res.extend([
ID,
sign,
start + 30 * i,
] for (ID, start, end) in termList)
return res | python | def termLons(TERMS):
""" Returns a list with the absolute longitude
of all terms.
"""
res = []
for i, sign in enumerate(SIGN_LIST):
termList = TERMS[sign]
res.extend([
ID,
sign,
start + 30 * i,
] for (ID, start, end) in termList)
return res | [
"def",
"termLons",
"(",
"TERMS",
")",
":",
"res",
"=",
"[",
"]",
"for",
"i",
",",
"sign",
"in",
"enumerate",
"(",
"SIGN_LIST",
")",
":",
"termList",
"=",
"TERMS",
"[",
"sign",
"]",
"res",
".",
"extend",
"(",
"[",
"ID",
",",
"sign",
",",
"start",
... | Returns a list with the absolute longitude
of all terms. | [
"Returns",
"a",
"list",
"with",
"the",
"absolute",
"longitude",
"of",
"all",
"terms",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/dignities/tables.py#L482-L495 | train |
flatangle/flatlib | flatlib/protocols/almutem.py | compute | 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 | python | 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 | [
"def",
"compute",
"(",
"chart",
")",
":",
"almutems",
"=",
"{",
"}",
"# Hylegic points",
"hylegic",
"=",
"[",
"chart",
".",
"getObject",
"(",
"const",
".",
"SUN",
")",
",",
"chart",
".",
"getObject",
"(",
"const",
".",
"MOON",
")",
",",
"chart",
".",... | Computes the Almutem table. | [
"Computes",
"the",
"Almutem",
"table",
"."
] | 44e05b2991a296c678adbc17a1d51b6a21bc867c | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/protocols/almutem.py#L58-L117 | train |
gophish/api-client-python | gophish/api/api.py | APIEndpoint.get | 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()] | python | 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()] | [
"def",
"get",
"(",
"self",
",",
"resource_id",
"=",
"None",
",",
"resource_action",
"=",
"None",
",",
"resource_cls",
"=",
"None",
",",
"single_resource",
"=",
"False",
")",
":",
"endpoint",
"=",
"self",
".",
"endpoint",
"if",
"not",
"resource_cls",
":",
... | 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 | [
"Gets",
"the",
"details",
"for",
"one",
"or",
"more",
"resources",
"by",
"ID"
] | 28a7790f19e13c92ef0fb7bde8cd89389df5c155 | https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/api/api.py#L40-L79 | train |
gophish/api-client-python | gophish/api/api.py | APIEndpoint.post | def post(self, resource):
""" Creates a new instance of the resource.
Args:
resource - gophish.models.Model - The resource instance
"""
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()) | python | def post(self, resource):
""" Creates a new instance of the resource.
Args:
resource - gophish.models.Model - The resource instance
"""
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()) | [
"def",
"post",
"(",
"self",
",",
"resource",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"execute",
"(",
"\"POST\"",
",",
"self",
".",
"endpoint",
",",
"json",
"=",
"(",
"resource",
".",
"as_dict",
"(",
")",
")",
")",
"if",
"not",
"response... | Creates a new instance of the resource.
Args:
resource - gophish.models.Model - The resource instance | [
"Creates",
"a",
"new",
"instance",
"of",
"the",
"resource",
"."
] | 28a7790f19e13c92ef0fb7bde8cd89389df5c155 | https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/api/api.py#L81-L94 | train |
gophish/api-client-python | gophish/api/api.py | APIEndpoint.put | 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()) | python | 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()) | [
"def",
"put",
"(",
"self",
",",
"resource",
")",
":",
"endpoint",
"=",
"self",
".",
"endpoint",
"if",
"resource",
".",
"id",
":",
"endpoint",
"=",
"self",
".",
"_build_url",
"(",
"endpoint",
",",
"resource",
".",
"id",
")",
"response",
"=",
"self",
"... | Edits an existing resource
Args:
resource - gophish.models.Model - The resource instance | [
"Edits",
"an",
"existing",
"resource"
] | 28a7790f19e13c92ef0fb7bde8cd89389df5c155 | https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/api/api.py#L96-L113 | train |
gophish/api-client-python | gophish/api/api.py | APIEndpoint.delete | def delete(self, resource_id):
""" Deletes an existing resource
Args:
resource_id - int - The resource ID to be deleted
"""
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()) | python | def delete(self, resource_id):
""" Deletes an existing resource
Args:
resource_id - int - The resource ID to be deleted
"""
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()) | [
"def",
"delete",
"(",
"self",
",",
"resource_id",
")",
":",
"endpoint",
"=",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"endpoint",
",",
"resource_id",
")",
"response",
"=",
"self",
".",
"api",
".",
"execute",
"(",
"\"DELETE\"",
",",
"endpoint",
")",
... | Deletes an existing resource
Args:
resource_id - int - The resource ID to be deleted | [
"Deletes",
"an",
"existing",
"resource"
] | 28a7790f19e13c92ef0fb7bde8cd89389df5c155 | https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/api/api.py#L115-L129 | train |
gophish/api-client-python | gophish/models.py | Model.as_dict | def as_dict(self):
""" Returns a dict representation of the resource """
result = {}
for key in self._valid_properties:
val = getattr(self, key)
if isinstance(val, datetime):
val = val.isoformat()
# Parse custom classes
elif val and not Model._is_builtin(val):
val = val.as_dict()
# Parse lists of objects
elif isinstance(val, list):
# We only want to call as_dict in the case where the item
# isn't a builtin type.
for i in range(len(val)):
if Model._is_builtin(val[i]):
continue
val[i] = val[i].as_dict()
# If it's a boolean, add it regardless of the value
elif isinstance(val, bool):
result[key] = val
# Add it if it's not None
if val:
result[key] = val
return result | python | def as_dict(self):
""" Returns a dict representation of the resource """
result = {}
for key in self._valid_properties:
val = getattr(self, key)
if isinstance(val, datetime):
val = val.isoformat()
# Parse custom classes
elif val and not Model._is_builtin(val):
val = val.as_dict()
# Parse lists of objects
elif isinstance(val, list):
# We only want to call as_dict in the case where the item
# isn't a builtin type.
for i in range(len(val)):
if Model._is_builtin(val[i]):
continue
val[i] = val[i].as_dict()
# If it's a boolean, add it regardless of the value
elif isinstance(val, bool):
result[key] = val
# Add it if it's not None
if val:
result[key] = val
return result | [
"def",
"as_dict",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"_valid_properties",
":",
"val",
"=",
"getattr",
"(",
"self",
",",
"key",
")",
"if",
"isinstance",
"(",
"val",
",",
"datetime",
")",
":",
"val",
"=",... | Returns a dict representation of the resource | [
"Returns",
"a",
"dict",
"representation",
"of",
"the",
"resource"
] | 28a7790f19e13c92ef0fb7bde8cd89389df5c155 | https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/models.py#L21-L46 | train |
gophish/api-client-python | gophish/client.py | GophishClient.execute | def execute(self, method, path, **kwargs):
""" Executes a request to a given endpoint, returning the result """
url = "{}{}".format(self.host, path)
kwargs.update(self._client_kwargs)
response = requests.request(
method,
url,
headers={"Authorization": "Bearer {}".format(self.api_key)},
**kwargs)
return response | python | def execute(self, method, path, **kwargs):
""" Executes a request to a given endpoint, returning the result """
url = "{}{}".format(self.host, path)
kwargs.update(self._client_kwargs)
response = requests.request(
method,
url,
headers={"Authorization": "Bearer {}".format(self.api_key)},
**kwargs)
return response | [
"def",
"execute",
"(",
"self",
",",
"method",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"\"{}{}\"",
".",
"format",
"(",
"self",
".",
"host",
",",
"path",
")",
"kwargs",
".",
"update",
"(",
"self",
".",
"_client_kwargs",
")",
"resp... | Executes a request to a given endpoint, returning the result | [
"Executes",
"a",
"request",
"to",
"a",
"given",
"endpoint",
"returning",
"the",
"result"
] | 28a7790f19e13c92ef0fb7bde8cd89389df5c155 | https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/client.py#L16-L26 | train |
gophish/api-client-python | gophish/api/campaigns.py | API.complete | def complete(self, campaign_id):
""" Complete an existing campaign (Stop processing events) """
return super(API, self).get(
resource_id=campaign_id, resource_action='complete') | python | def complete(self, campaign_id):
""" Complete an existing campaign (Stop processing events) """
return super(API, self).get(
resource_id=campaign_id, resource_action='complete') | [
"def",
"complete",
"(",
"self",
",",
"campaign_id",
")",
":",
"return",
"super",
"(",
"API",
",",
"self",
")",
".",
"get",
"(",
"resource_id",
"=",
"campaign_id",
",",
"resource_action",
"=",
"'complete'",
")"
] | Complete an existing campaign (Stop processing events) | [
"Complete",
"an",
"existing",
"campaign",
"(",
"Stop",
"processing",
"events",
")"
] | 28a7790f19e13c92ef0fb7bde8cd89389df5c155 | https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/api/campaigns.py#L32-L36 | train |
gophish/api-client-python | gophish/api/campaigns.py | API.summary | def summary(self, campaign_id=None):
""" Returns the campaign summary """
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) | python | def summary(self, campaign_id=None):
""" Returns the campaign summary """
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) | [
"def",
"summary",
"(",
"self",
",",
"campaign_id",
"=",
"None",
")",
":",
"resource_cls",
"=",
"CampaignSummary",
"single_resource",
"=",
"False",
"if",
"not",
"campaign_id",
":",
"resource_cls",
"=",
"CampaignSummaries",
"single_resource",
"=",
"True",
"return",
... | Returns the campaign summary | [
"Returns",
"the",
"campaign",
"summary"
] | 28a7790f19e13c92ef0fb7bde8cd89389df5c155 | https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/api/campaigns.py#L38-L51 | train |
gophish/api-client-python | gophish/api/campaigns.py | API.results | def results(self, campaign_id):
""" Returns just the results for a given campaign """
return super(API, self).get(
resource_id=campaign_id,
resource_action='results',
resource_cls=CampaignResults) | python | def results(self, campaign_id):
""" Returns just the results for a given campaign """
return super(API, self).get(
resource_id=campaign_id,
resource_action='results',
resource_cls=CampaignResults) | [
"def",
"results",
"(",
"self",
",",
"campaign_id",
")",
":",
"return",
"super",
"(",
"API",
",",
"self",
")",
".",
"get",
"(",
"resource_id",
"=",
"campaign_id",
",",
"resource_action",
"=",
"'results'",
",",
"resource_cls",
"=",
"CampaignResults",
")"
] | Returns just the results for a given campaign | [
"Returns",
"just",
"the",
"results",
"for",
"a",
"given",
"campaign"
] | 28a7790f19e13c92ef0fb7bde8cd89389df5c155 | https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/api/campaigns.py#L53-L58 | train |
gunthercox/jsondb | jsondb/db.py | Database.set_path | def set_path(self, file_path):
"""
Set the path of the database.
Create the file if it does not exist.
"""
if not file_path:
self.read_data = self.memory_read
self.write_data = self.memory_write
elif not is_valid(file_path):
self.write_data(file_path, {})
self.path = file_path | python | def set_path(self, file_path):
"""
Set the path of the database.
Create the file if it does not exist.
"""
if not file_path:
self.read_data = self.memory_read
self.write_data = self.memory_write
elif not is_valid(file_path):
self.write_data(file_path, {})
self.path = file_path | [
"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",
... | Set the path of the database.
Create the file if it does not exist. | [
"Set",
"the",
"path",
"of",
"the",
"database",
".",
"Create",
"the",
"file",
"if",
"it",
"does",
"not",
"exist",
"."
] | d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9 | https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/db.py#L38-L49 | train |
gunthercox/jsondb | jsondb/db.py | Database.delete | def delete(self, key):
"""
Removes the specified key from the database.
"""
obj = self._get_content()
obj.pop(key, None)
self.write_data(self.path, obj) | python | def delete(self, key):
"""
Removes the specified key from the database.
"""
obj = self._get_content()
obj.pop(key, None)
self.write_data(self.path, obj) | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"obj",
"=",
"self",
".",
"_get_content",
"(",
")",
"obj",
".",
"pop",
"(",
"key",
",",
"None",
")",
"self",
".",
"write_data",
"(",
"self",
".",
"path",
",",
"obj",
")"
] | Removes the specified key from the database. | [
"Removes",
"the",
"specified",
"key",
"from",
"the",
"database",
"."
] | d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9 | https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/db.py#L68-L75 | train |
gunthercox/jsondb | jsondb/db.py | Database.data | def data(self, **kwargs):
"""
If a key is passed in, a corresponding value will be returned.
If a key-value pair is passed in then the corresponding key in
the database will be set to the specified value.
A dictionary can be passed in as well.
If a key does not exist and a value is provided then an entry
will be created in the database.
"""
key = kwargs.pop('key', None)
value = kwargs.pop('value', None)
dictionary = kwargs.pop('dictionary', None)
# Fail if a key and a dictionary or a value and a dictionary are given
if (key is not None and dictionary is not None) or \
(value is not None and dictionary is not None):
raise ValueError
# If only a key was provided return the corresponding value
if key is not None and value is None:
return self._get_content(key)
# if a key and a value are passed in
if key is not None and value is not None:
self._set_content(key, value)
if dictionary is not None:
for key in dictionary.keys():
value = dictionary[key]
self._set_content(key, value)
return self._get_content() | python | def data(self, **kwargs):
"""
If a key is passed in, a corresponding value will be returned.
If a key-value pair is passed in then the corresponding key in
the database will be set to the specified value.
A dictionary can be passed in as well.
If a key does not exist and a value is provided then an entry
will be created in the database.
"""
key = kwargs.pop('key', None)
value = kwargs.pop('value', None)
dictionary = kwargs.pop('dictionary', None)
# Fail if a key and a dictionary or a value and a dictionary are given
if (key is not None and dictionary is not None) or \
(value is not None and dictionary is not None):
raise ValueError
# If only a key was provided return the corresponding value
if key is not None and value is None:
return self._get_content(key)
# if a key and a value are passed in
if key is not None and value is not None:
self._set_content(key, value)
if dictionary is not None:
for key in dictionary.keys():
value = dictionary[key]
self._set_content(key, value)
return self._get_content() | [
"def",
"data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"kwargs",
".",
"pop",
"(",
"'key'",
",",
"None",
")",
"value",
"=",
"kwargs",
".",
"pop",
"(",
"'value'",
",",
"None",
")",
"dictionary",
"=",
"kwargs",
".",
"pop",
"(",
... | If a key is passed in, a corresponding value will be returned.
If a key-value pair is passed in then the corresponding key in
the database will be set to the specified value.
A dictionary can be passed in as well.
If a key does not exist and a value is provided then an entry
will be created in the database. | [
"If",
"a",
"key",
"is",
"passed",
"in",
"a",
"corresponding",
"value",
"will",
"be",
"returned",
".",
"If",
"a",
"key",
"-",
"value",
"pair",
"is",
"passed",
"in",
"then",
"the",
"corresponding",
"key",
"in",
"the",
"database",
"will",
"be",
"set",
"to... | d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9 | https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/db.py#L77-L109 | train |
gunthercox/jsondb | jsondb/db.py | Database.filter | def filter(self, filter_arguments):
"""
Takes a dictionary of filter parameters.
Return a list of objects based on a list of parameters.
"""
results = self._get_content()
# Filter based on a dictionary of search parameters
if isinstance(filter_arguments, dict):
for item, content in iteritems(self._get_content()):
for key, value in iteritems(filter_arguments):
keys = key.split('.')
value = filter_arguments[key]
if not self._contains_value({item: content}, keys, value):
del results[item]
# Filter based on an input string that should match database key
if isinstance(filter_arguments, str):
if filter_arguments in results:
return [{filter_arguments: results[filter_arguments]}]
else:
return []
return results | python | def filter(self, filter_arguments):
"""
Takes a dictionary of filter parameters.
Return a list of objects based on a list of parameters.
"""
results = self._get_content()
# Filter based on a dictionary of search parameters
if isinstance(filter_arguments, dict):
for item, content in iteritems(self._get_content()):
for key, value in iteritems(filter_arguments):
keys = key.split('.')
value = filter_arguments[key]
if not self._contains_value({item: content}, keys, value):
del results[item]
# Filter based on an input string that should match database key
if isinstance(filter_arguments, str):
if filter_arguments in results:
return [{filter_arguments: results[filter_arguments]}]
else:
return []
return results | [
"def",
"filter",
"(",
"self",
",",
"filter_arguments",
")",
":",
"results",
"=",
"self",
".",
"_get_content",
"(",
")",
"# Filter based on a dictionary of search parameters",
"if",
"isinstance",
"(",
"filter_arguments",
",",
"dict",
")",
":",
"for",
"item",
",",
... | Takes a dictionary of filter parameters.
Return a list of objects based on a list of parameters. | [
"Takes",
"a",
"dictionary",
"of",
"filter",
"parameters",
".",
"Return",
"a",
"list",
"of",
"objects",
"based",
"on",
"a",
"list",
"of",
"parameters",
"."
] | d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9 | https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/db.py#L125-L149 | train |
gunthercox/jsondb | jsondb/db.py | Database.drop | 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 = {} | python | 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 = {} | [
"def",
"drop",
"(",
"self",
")",
":",
"import",
"os",
"if",
"self",
".",
"path",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"path",
")",
"else",
":",
"# Clear the in-mem... | Remove the database by deleting the JSON file. | [
"Remove",
"the",
"database",
"by",
"deleting",
"the",
"JSON",
"file",
"."
] | d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9 | https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/db.py#L151-L162 | train |
gunthercox/jsondb | jsondb/file_writer.py | read_data | def read_data(file_path):
"""
Reads a file and returns a json encoded representation of the file.
"""
if not is_valid(file_path):
write_data(file_path, {})
db = open_file_for_reading(file_path)
content = db.read()
obj = decode(content)
db.close()
return obj | python | def read_data(file_path):
"""
Reads a file and returns a json encoded representation of the file.
"""
if not is_valid(file_path):
write_data(file_path, {})
db = open_file_for_reading(file_path)
content = db.read()
obj = decode(content)
db.close()
return obj | [
"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",
"(",
... | Reads a file and returns a json encoded representation of the file. | [
"Reads",
"a",
"file",
"and",
"returns",
"a",
"json",
"encoded",
"representation",
"of",
"the",
"file",
"."
] | d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9 | https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/file_writer.py#L4-L19 | train |
gunthercox/jsondb | jsondb/file_writer.py | write_data | def write_data(path, obj):
"""
Writes to a file and returns the updated file content.
"""
with open_file_for_writing(path) as db:
db.write(encode(obj))
return obj | python | def write_data(path, obj):
"""
Writes to a file and returns the updated file content.
"""
with open_file_for_writing(path) as db:
db.write(encode(obj))
return obj | [
"def",
"write_data",
"(",
"path",
",",
"obj",
")",
":",
"with",
"open_file_for_writing",
"(",
"path",
")",
"as",
"db",
":",
"db",
".",
"write",
"(",
"encode",
"(",
"obj",
")",
")",
"return",
"obj"
] | Writes to a file and returns the updated file content. | [
"Writes",
"to",
"a",
"file",
"and",
"returns",
"the",
"updated",
"file",
"content",
"."
] | d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9 | https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/file_writer.py#L21-L28 | train |
gunthercox/jsondb | jsondb/file_writer.py | is_valid | 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 | python | 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 | [
"def",
"is_valid",
"(",
"file_path",
")",
":",
"from",
"os",
"import",
"path",
",",
"stat",
"can_open",
"=",
"False",
"try",
":",
"with",
"open",
"(",
"file_path",
")",
"as",
"fp",
":",
"can_open",
"=",
"True",
"except",
"IOError",
":",
"return",
"Fals... | Check to see if a file exists or is empty. | [
"Check",
"to",
"see",
"if",
"a",
"file",
"exists",
"or",
"is",
"empty",
"."
] | d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9 | https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/file_writer.py#L30-L46 | train |
nschloe/meshzoo | meshzoo/helpers.py | _refine | def _refine(node_coords, cells_nodes, edge_nodes, cells_edges):
"""Canonically refine a mesh by inserting nodes at all edge midpoints
and make four triangular elements where there was one.
This is a very crude refinement; don't use for actual applications.
"""
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 | python | def _refine(node_coords, cells_nodes, edge_nodes, cells_edges):
"""Canonically refine a mesh by inserting nodes at all edge midpoints
and make four triangular elements where there was one.
This is a very crude refinement; don't use for actual applications.
"""
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 | [
"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.dtyp... | Canonically refine a mesh by inserting nodes at all edge midpoints
and make four triangular elements where there was one.
This is a very crude refinement; don't use for actual applications. | [
"Canonically",
"refine",
"a",
"mesh",
"by",
"inserting",
"nodes",
"at",
"all",
"edge",
"midpoints",
"and",
"make",
"four",
"triangular",
"elements",
"where",
"there",
"was",
"one",
".",
"This",
"is",
"a",
"very",
"crude",
"refinement",
";",
"don",
"t",
"us... | 623b84c8b985dcc8e5ccc6250d1dbb989736dcef | https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/helpers.py#L7-L124 | train |
nschloe/meshzoo | meshzoo/helpers.py | create_edges | def create_edges(cells_nodes):
"""Setup edge-node and edge-cell relations. Adapted from voropy.
"""
# 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 | python | def create_edges(cells_nodes):
"""Setup edge-node and edge-cell relations. Adapted from voropy.
"""
# 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 | [
"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... | Setup edge-node and edge-cell relations. Adapted from voropy. | [
"Setup",
"edge",
"-",
"node",
"and",
"edge",
"-",
"cell",
"relations",
".",
"Adapted",
"from",
"voropy",
"."
] | 623b84c8b985dcc8e5ccc6250d1dbb989736dcef | https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/helpers.py#L127-L158 | train |
nschloe/meshzoo | meshzoo/helpers.py | plot2d | def plot2d(points, cells, mesh_color="k", show_axes=False):
"""Plot a 2D mesh using matplotlib.
"""
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 | python | def plot2d(points, cells, mesh_color="k", show_axes=False):
"""Plot a 2D mesh using matplotlib.
"""
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 | [
"def",
"plot2d",
"(",
"points",
",",
"cells",
",",
"mesh_color",
"=",
"\"k\"",
",",
"show_axes",
"=",
"False",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"from",
"matplotlib",
".",
"collections",
"import",
"LineCollection",
"fig",
"=",
"... | Plot a 2D mesh using matplotlib. | [
"Plot",
"a",
"2D",
"mesh",
"using",
"matplotlib",
"."
] | 623b84c8b985dcc8e5ccc6250d1dbb989736dcef | https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/helpers.py#L169-L203 | train |
shazow/workerpool | samples/blockingworker.py | BlockingWorkerPool.put | 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 | python | 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 | [
"def",
"put",
"(",
"self",
",",
"job",
",",
"result",
")",
":",
"self",
".",
"job",
".",
"put",
"(",
"job",
")",
"r",
"=",
"result",
".",
"get",
"(",
")",
"return",
"r"
] | Perform a job by a member in the pool and return the result. | [
"Perform",
"a",
"job",
"by",
"a",
"member",
"in",
"the",
"pool",
"and",
"return",
"the",
"result",
"."
] | 2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5 | https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/samples/blockingworker.py#L16-L20 | train |
shazow/workerpool | samples/blockingworker.py | BlockingWorkerPool.contract | 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 | python | 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 | [
"def",
"contract",
"(",
"self",
",",
"jobs",
",",
"result",
")",
":",
"for",
"j",
"in",
"jobs",
":",
"WorkerPool",
".",
"put",
"(",
"self",
",",
"j",
")",
"r",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"jobs",
")",
")",
":",... | Perform a contract on a number of jobs and block until a result is
retrieved for each job. | [
"Perform",
"a",
"contract",
"on",
"a",
"number",
"of",
"jobs",
"and",
"block",
"until",
"a",
"result",
"is",
"retrieved",
"for",
"each",
"job",
"."
] | 2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5 | https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/samples/blockingworker.py#L22-L34 | train |
nschloe/meshzoo | meshzoo/cube.py | cube | 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 | python | 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 | [
"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. | [
"Canonical",
"tetrahedrization",
"of",
"the",
"cube",
".",
"Input",
":",
"Edge",
"lenghts",
"of",
"the",
"cube",
"Number",
"of",
"nodes",
"along",
"the",
"edges",
"."
] | 623b84c8b985dcc8e5ccc6250d1dbb989736dcef | https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/cube.py#L6-L294 | train |
shazow/workerpool | workerpool/pools.py | WorkerPool.grow | def grow(self):
"Add another worker to the pool."
t = self.worker_factory(self)
t.start()
self._size += 1 | python | def grow(self):
"Add another worker to the pool."
t = self.worker_factory(self)
t.start()
self._size += 1 | [
"def",
"grow",
"(",
"self",
")",
":",
"t",
"=",
"self",
".",
"worker_factory",
"(",
"self",
")",
"t",
".",
"start",
"(",
")",
"self",
".",
"_size",
"+=",
"1"
] | Add another worker to the pool. | [
"Add",
"another",
"worker",
"to",
"the",
"pool",
"."
] | 2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5 | https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/pools.py#L66-L70 | train |
shazow/workerpool | workerpool/pools.py | WorkerPool.shrink | 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()) | python | 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()) | [
"def",
"shrink",
"(",
"self",
")",
":",
"if",
"self",
".",
"_size",
"<=",
"0",
":",
"raise",
"IndexError",
"(",
"\"pool is already empty\"",
")",
"self",
".",
"_size",
"-=",
"1",
"self",
".",
"put",
"(",
"SuicideJob",
"(",
")",
")"
] | Get rid of one worker from the pool. Raises IndexError if empty. | [
"Get",
"rid",
"of",
"one",
"worker",
"from",
"the",
"pool",
".",
"Raises",
"IndexError",
"if",
"empty",
"."
] | 2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5 | https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/pools.py#L72-L77 | train |
shazow/workerpool | workerpool/pools.py | WorkerPool.map | 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 | python | 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 | [
"def",
"map",
"(",
"self",
",",
"fn",
",",
"*",
"seq",
")",
":",
"\"block until done.\"",
"results",
"=",
"Queue",
"(",
")",
"args",
"=",
"zip",
"(",
"*",
"seq",
")",
"for",
"seq",
"in",
"args",
":",
"j",
"=",
"SimpleJob",
"(",
"results",
",",
"f... | Perform a map operation distributed among the workers. Will | [
"Perform",
"a",
"map",
"operation",
"distributed",
"among",
"the",
"workers",
".",
"Will"
] | 2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5 | https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/pools.py#L89-L103 | train |
nschloe/meshzoo | meshzoo/moebius.py | moebius | 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 | python | 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 | [
"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'`. | [
"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",
"w... | 623b84c8b985dcc8e5ccc6250d1dbb989736dcef | https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/moebius.py#L7-L83 | train |
shazow/workerpool | workerpool/workers.py | Worker.run | 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 | python | 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 | [
"def",
"run",
"(",
"self",
")",
":",
"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",
... | Get jobs from the queue and perform them as they arrive. | [
"Get",
"jobs",
"from",
"the",
"queue",
"and",
"perform",
"them",
"as",
"they",
"arrive",
"."
] | 2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5 | https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/workers.py#L28-L40 | train |
jwass/geojsonio.py | geojsonio/geojsonio.py | display | 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 | python | 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 | [
"def",
"display",
"(",
"contents",
",",
"domain",
"=",
"DEFAULT_DOMAIN",
",",
"force_gist",
"=",
"False",
")",
":",
"url",
"=",
"make_url",
"(",
"contents",
",",
"domain",
",",
"force_gist",
")",
"webbrowser",
".",
"open",
"(",
"url",
")",
"return",
"url... | 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 | [
"Open",
"a",
"web",
"browser",
"pointing",
"to",
"geojson",
".",
"io",
"with",
"the",
"specified",
"content",
"."
] | 8229a48238f128837e6dce49f18310df84968825 | https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L18-L38 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.