code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
record_set_md5 = get_record_set_md5(rs_dict["Name"], rs_dict["Type"])
rs = route53.RecordSetType.from_dict(record_set_md5, rs_dict)
rs = add_hosted_zone_id_if_missing(rs, self.hosted_zone_id)
rs = self.add_hosted_zone_id_for_alias_target_if_missing(rs)
return self.templa... | def create_record_set(self, rs_dict) | Accept a record_set dict. Return a Troposphere record_set object. | 3.369064 | 2.985924 | 1.128315 |
rs = route53.RecordSetGroup.from_dict(name, g_dict)
rs = add_hosted_zone_id_if_missing(rs, self.hosted_zone_id)
rs = self.add_hosted_zone_id_for_alias_target_if_missing(rs)
return self.template.add_resource(rs) | def create_record_set_group(self, name, g_dict) | Accept a record_set dict. Return a Troposphere record_set object. | 3.938939 | 3.432224 | 1.147635 |
record_set_objects = []
for record_set_dict in record_set_dicts:
# pop removes the 'Enabled' key and tests if True.
if record_set_dict.pop('Enabled', True):
record_set_objects.append(
self.create_record_set(record_set_dict)
... | def create_record_sets(self, record_set_dicts) | Accept list of record_set dicts.
Return list of record_set objects. | 3.108451 | 2.879383 | 1.079555 |
record_set_groups = []
for name, group in record_set_group_dicts.iteritems():
# pop removes the 'Enabled' key and tests if True.
if group.pop('Enabled', True):
record_set_groups.append(
self.create_record_set_group(name, group)
... | def create_record_set_groups(self, record_set_group_dicts) | Accept list of record_set_group dicts.
Return list of record_set_group objects. | 3.546461 | 3.463072 | 1.02408 |
list_buckets = [s3_arn(b) for b in buckets]
object_buckets = [s3_objects_arn(b, folder) for b in buckets]
bucket_resources = list_buckets + object_buckets
return [
Statement(
Effect=Allow,
Resource=[s3_arn("*")],
Action=[s3.ListAllMyBuckets]
),
... | def read_only_s3_bucket_policy_statements(buckets, folder="*") | Read only policy an s3 bucket. | 3.162121 | 3.199392 | 0.988351 |
return Policy(
Statement=[
Statement(
Effect=Allow,
Principal=Principal("*"),
Action=[s3.GetObject],
Resource=[s3_objects_arn(bucket)],
)
]
) | def static_website_bucket_policy(bucket) | Attach this policy directly to an S3 bucket to make it a static website.
This policy grants read access to **all unauthenticated** users. | 2.978918 | 3.459396 | 0.861109 |
return [
Statement(
Effect=Allow,
Resource=['*'],
Action=[
ec2.CreateNetworkInterface,
ec2.DescribeNetworkInterfaces,
ec2.DeleteNetworkInterface,
]
)
] | def lambda_vpc_execution_statements() | Allow Lambda to manipuate EC2 ENIs for VPC support. | 2.80062 | 2.444338 | 1.145758 |
return Policy(
Statement=[
Statement(
Effect=Allow,
Resource=dynamodb_arns(tables),
Action=[
dynamodb.DescribeTable,
dynamodb.UpdateTable,
]
),
Statement(
... | def dynamodb_autoscaling_policy(tables) | Policy to allow AutoScaling a list of DynamoDB tables. | 2.074776 | 2.036027 | 1.019032 |
return healpix_to_lonlat(healpix_index, self.nside, dx=dx, dy=dy, order=self.order) | def healpix_to_lonlat(self, healpix_index, dx=None, dy=None) | Convert HEALPix indices (optionally with offsets) to longitudes/latitudes
Parameters
----------
healpix_index : `~numpy.ndarray`
1-D array of HEALPix indices
dx, dy : `~numpy.ndarray`, optional
1-D arrays of offsets inside the HEALPix pixel, which must be in
... | 3.020779 | 6.224352 | 0.485316 |
return lonlat_to_healpix(lon, lat, self.nside,
return_offsets=return_offsets, order=self.order) | def lonlat_to_healpix(self, lon, lat, return_offsets=False) | Convert longitudes/latitudes to HEALPix indices (optionally with offsets)
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity` instances
with angle units.
return_offsets : bool
... | 3.381206 | 7.115204 | 0.475209 |
return bilinear_interpolation_weights(lon, lat, self.nside, order=self.order) | def bilinear_interpolation_weights(self, lon, lat) | Get the four neighbours for each (lon, lat) position and the weight
associated with each one for bilinear interpolation.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as
:class:`~astropy.units.Quantity` instan... | 5.585576 | 10.212564 | 0.546932 |
if len(values) != self.npix:
raise ValueError('values must be an array of length {0} (got {1})'.format(self.npix, len(values)))
return interpolate_bilinear_lonlat(lon, lat, values, order=self.order) | def interpolate_bilinear_lonlat(self, lon, lat, values) | Interpolate values at specific longitudes/latitudes using bilinear interpolation
If a position does not have four neighbours, this currently returns NaN.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.... | 2.905203 | 3.352129 | 0.866674 |
if not lon.isscalar or not lat.isscalar or not radius.isscalar:
raise ValueError('The longitude, latitude and radius must be '
'scalar Quantity objects')
return healpix_cone_search(lon, lat, radius, self.nside, order=self.order) | def cone_search_lonlat(self, lon, lat, radius) | Find all the HEALPix pixels within a given radius of a longitude/latitude.
Note that this returns all pixels that overlap, including partially, with
the search cone. This function can only be used for a single lon/lat pair at
a time, since different calls to the function may result in a differe... | 4.085165 | 4.395921 | 0.929308 |
return boundaries_lonlat(healpix_index, step, self.nside, order=self.order) | def boundaries_lonlat(self, healpix_index, step) | Return the longitude and latitude of the edges of HEALPix pixels
This returns the longitude and latitude of points along the edge of each
HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
so setting ``step`` to 1 returns just the corners.
Parameters
-... | 4.010952 | 11.983257 | 0.334713 |
return neighbours(healpix_index, self.nside, order=self.order) | def neighbours(self, healpix_index) | Find all the HEALPix pixels that are the neighbours of a HEALPix pixel
Parameters
----------
healpix_index : `~numpy.ndarray`
Array of HEALPix pixels
Returns
-------
neigh : `~numpy.ndarray`
Array giving the neighbours starting SW and rotating cl... | 4.837823 | 10.275853 | 0.470795 |
if self.frame is None:
raise NoFrameError("healpix_to_skycoord")
lon, lat = self.healpix_to_lonlat(healpix_index, dx=dx, dy=dy)
representation = UnitSphericalRepresentation(lon, lat, copy=False)
return SkyCoord(self.frame.realize_frame(representation)) | def healpix_to_skycoord(self, healpix_index, dx=None, dy=None) | Convert HEALPix indices (optionally with offsets) to celestial coordinates.
Note that this method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame, you
can instead use :meth:`~astropy_healpix.HEALPix.healpix_to_lonlat`.
... | 2.994009 | 3.092947 | 0.968012 |
if self.frame is None:
raise NoFrameError("skycoord_to_healpix")
skycoord = skycoord.transform_to(self.frame)
representation = skycoord.represent_as(UnitSphericalRepresentation)
lon, lat = representation.lon, representation.lat
return self.lonlat_to_healpix(l... | def skycoord_to_healpix(self, skycoord, return_offsets=False) | Convert celestial coordinates to HEALPix indices (optionally with offsets).
Note that this method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial frame, you
can instead use :meth:`~astropy_healpix.HEALPix.lonlat_to_healpix`.
... | 2.643105 | 2.550197 | 1.036432 |
if self.frame is None:
raise NoFrameError("interpolate_bilinear_skycoord")
skycoord = skycoord.transform_to(self.frame)
representation = skycoord.represent_as(UnitSphericalRepresentation)
lon, lat = representation.lon, representation.lat
return self.interpola... | def interpolate_bilinear_skycoord(self, skycoord, values) | Interpolate values at specific celestial coordinates using bilinear interpolation.
If a position does not have four neighbours, this currently returns NaN.
Note that this method requires that a celestial frame was specified when
initializing HEALPix. If you don't know or need the celestial fra... | 2.921476 | 3.215598 | 0.908533 |
if self.frame is None:
raise NoFrameError("cone_search_skycoord")
skycoord = skycoord.transform_to(self.frame)
representation = skycoord.represent_as(UnitSphericalRepresentation)
lon, lat = representation.lon, representation.lat
return self.cone_search_lonlat... | def cone_search_skycoord(self, skycoord, radius) | Find all the HEALPix pixels within a given radius of a celestial position.
Note that this returns all pixels that overlap, including partially,
with the search cone. This function can only be used for a single
celestial position at a time, since different calls to the function may
resul... | 2.822258 | 2.991918 | 0.943294 |
if self.frame is None:
raise NoFrameError("boundaries_skycoord")
lon, lat = self.boundaries_lonlat(healpix_index, step)
representation = UnitSphericalRepresentation(lon, lat, copy=False)
return SkyCoord(self.frame.realize_frame(representation)) | def boundaries_skycoord(self, healpix_index, step) | Return the celestial coordinates of the edges of HEALPix pixels
This returns the celestial coordinates of points along the edge of each
HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
so setting ``step`` to 1 returns just the corners.
This method requires t... | 3.932909 | 3.767884 | 1.043798 |
level = np.asarray(level, dtype=np.int64)
_validate_level(level)
return 2 ** level | def level_to_nside(level) | Find the pixel dimensions of the top-level HEALPix tiles.
This is given by ``nside = 2**level``.
Parameters
----------
level : int
The resolution level
Returns
-------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. | 4.753771 | 9.311908 | 0.510505 |
nside = np.asarray(nside, dtype=np.int64)
_validate_nside(nside)
return np.log2(nside).astype(np.int64) | def nside_to_level(nside) | Find the HEALPix level for a given nside.
This is given by ``level = log2(nside)``.
This function is the inverse of `level_to_nside`.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Must be a power of two.
Returns... | 2.776373 | 5.36861 | 0.517149 |
uniq = np.asarray(uniq, dtype=np.int64)
level = (np.log2(uniq//4)) // 2
level = level.astype(np.int64)
_validate_level(level)
ipix = uniq - (1 << 2*(level + 1))
_validate_npix(level, ipix)
return level, ipix | def uniq_to_level_ipix(uniq) | Convert a HEALPix cell uniq number to its (level, ipix) equivalent.
A uniq number is a 64 bits integer equaling to : ipix + 4*(4**level). Please read
this `paper <http://ivoa.net/documents/MOC/20140602/REC-MOC-1.0-20140602.pdf>`_
for more details about uniq numbers.
Parameters
----------
uniq ... | 3.949273 | 4.587614 | 0.860856 |
level = np.asarray(level, dtype=np.int64)
ipix = np.asarray(ipix, dtype=np.int64)
_validate_level(level)
_validate_npix(level, ipix)
return ipix + (1 << 2*(level + 1)) | def level_ipix_to_uniq(level, ipix) | Convert a level and HEALPix index into a uniq number representing the cell.
This function is the inverse of `uniq_to_level_ipix`.
Parameters
----------
level : int
The level of the HEALPix cell
ipix : int
The index of the HEALPix cell
Returns
-------
uniq : int
... | 3.117934 | 4.299514 | 0.725183 |
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
npix = 12 * nside * nside
pixel_area = 4 * math.pi / npix * u.sr
return pixel_area | def nside_to_pixel_area(nside) | Find the area of HEALPix pixels given the pixel dimensions of one of
the 12 'top-level' HEALPix tiles.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
pixel_area : :class:`~astropy.units.Quantity`
... | 3.164237 | 4.785823 | 0.661169 |
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
return (nside_to_pixel_area(nside) ** 0.5).to(u.arcmin) | def nside_to_pixel_resolution(nside) | Find the resolution of HEALPix pixels given the pixel dimensions of one of
the 12 'top-level' HEALPix tiles.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
resolution : :class:`~astropy.units.Quantity`
... | 2.97333 | 5.323918 | 0.558485 |
resolution = resolution.to(u.rad).value
pixel_area = resolution * resolution
npix = 4 * math.pi / pixel_area
nside = np.sqrt(npix / 12)
# Now we have to round to the closest ``nside``
# Since ``nside`` must be a power of two,
# we first compute the corresponding ``level = log2(nside)`
... | def pixel_resolution_to_nside(resolution, round='nearest') | Find closest HEALPix nside for a given angular resolution.
This function is the inverse of `nside_to_pixel_resolution`,
for the default rounding scheme of ``round='nearest'``.
If you choose ``round='up'``, you'll get HEALPix pixels that
have at least the requested resolution (usually a bit better
... | 4.175046 | 4.756621 | 0.877734 |
nside = np.asanyarray(nside, dtype=np.int64)
_validate_nside(nside)
return 12 * nside ** 2 | def nside_to_npix(nside) | Find the number of pixels corresponding to a HEALPix resolution.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
npix : int
The number of pixels in the HEALPix map. | 3.204844 | 5.655866 | 0.566641 |
npix = np.asanyarray(npix, dtype=np.int64)
if not np.all(npix % 12 == 0):
raise ValueError('Number of pixels must be divisible by 12')
square_root = np.sqrt(npix / 12)
if not np.all(square_root ** 2 == npix / 12):
raise ValueError('Number of pixels is not of the form 12 * nside *... | def npix_to_nside(npix) | Find the number of pixels on the side of one of the 12 'top-level' HEALPix
tiles given a total number of pixels.
Parameters
----------
npix : int
The number of pixels in the HEALPix map.
Returns
-------
nside : int
The number of pixels on the side of one of the 12 'top-leve... | 2.698411 | 2.882182 | 0.936239 |
_validate_nside(nside)
if _validate_order(order) == 'ring':
func = _core.healpix_ring_to_lonlat
else: # _validate_order(order) == 'nested'
func = _core.healpix_nested_to_lonlat
if dx is None:
dx = 0.5
else:
_validate_offset('x', dx)
if dy is None:
... | def healpix_to_lonlat(healpix_index, nside, dx=None, dy=None, order='ring') | Convert HEALPix indices (optionally with offsets) to longitudes/latitudes.
If no offsets (``dx`` and ``dy``) are provided, the coordinates will default
to those at the center of the HEALPix pixels.
Parameters
----------
healpix_index : int or `~numpy.ndarray`
HEALPix indices (as a scalar o... | 2.203311 | 2.13926 | 1.029941 |
if _validate_order(order) == 'ring':
func = _core.lonlat_to_healpix_ring
else: # _validate_order(order) == 'nested'
func = _core.lonlat_to_healpix_nested
nside = np.asarray(nside, dtype=np.intc)
lon = lon.to_value(u.rad)
lat = lat.to_value(u.rad)
healpix_index, dx, dy =... | def lonlat_to_healpix(lon, lat, nside, return_offsets=False, order='ring') | Convert longitudes/latitudes to HEALPix indices
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity`
instances with angle units.
nside : int or `~numpy.ndarray`
Number of pixels along the side of ... | 2.473161 | 2.367261 | 1.044735 |
nside = np.asarray(nside, dtype=np.intc)
return _core.nested_to_ring(nested_index, nside) | def nested_to_ring(nested_index, nside) | Convert a HEALPix 'nested' index to a HEALPix 'ring' index
Parameters
----------
nested_index : int or `~numpy.ndarray`
Healpix index using the 'nested' ordering
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
Returns
--... | 4.212154 | 7.886545 | 0.534094 |
nside = np.asarray(nside, dtype=np.intc)
return _core.ring_to_nested(ring_index, nside) | def ring_to_nested(ring_index, nside) | Convert a HEALPix 'ring' index to a HEALPix 'nested' index
Parameters
----------
ring_index : int or `~numpy.ndarray`
Healpix index using the 'ring' ordering
nside : int or `~numpy.ndarray`
Number of pixels along the side of each of the 12 top-level HEALPix tiles
Returns
------... | 4.088155 | 7.70601 | 0.530515 |
lon = lon.to_value(u.rad)
lat = lat.to_value(u.rad)
_validate_nside(nside)
nside = np.asarray(nside, dtype=np.intc)
result = _core.bilinear_interpolation_weights(lon, lat, nside)
indices = np.stack(result[:4])
weights = np.stack(result[4:])
if _validate_order(order) == 'nested'... | def bilinear_interpolation_weights(lon, lat, nside, order='ring') | Get the four neighbours for each (lon, lat) position and the weight
associated with each one for bilinear interpolation.
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity`
instances with angle units.
... | 3.625296 | 3.210458 | 1.129215 |
nside = npix_to_nside(values.shape[0])
indices, weights = bilinear_interpolation_weights(lon, lat, nside, order=order)
values = values[indices]
# At this point values has shape (N, M) where both N and M might be several
# dimensions, and weights has shape (N,), so we need to transpose in order
... | def interpolate_bilinear_lonlat(lon, lat, values, order='ring') | Interpolate values at specific longitudes/latitudes using bilinear interpolation
Parameters
----------
lon, lat : :class:`~astropy.units.Quantity`
The longitude and latitude values as :class:`~astropy.units.Quantity` instances
with angle units.
values : `~numpy.ndarray`
Array wi... | 5.861803 | 6.694654 | 0.875595 |
_validate_nside(nside)
nside = np.asarray(nside, dtype=np.intc)
if _validate_order(order) == 'ring':
func = _core.neighbours_ring
else: # _validate_order(order) == 'nested'
func = _core.neighbours_nested
return np.stack(func(healpix_index, nside)) | def neighbours(healpix_index, nside, order='ring') | Find all the HEALPix pixels that are the neighbours of a HEALPix pixel
Parameters
----------
healpix_index : `~numpy.ndarray`
Array of HEALPix pixels
nside : int
Number of pixels along the side of each of the 12 top-level HEALPix tiles
order : { 'nested' | 'ring' }
Order of ... | 3.364803 | 3.943699 | 0.85321 |
lon = lon.to_value(u.deg)
lat = lat.to_value(u.deg)
radius = radius.to_value(u.deg)
_validate_nside(nside)
order = _validate_order(order)
return _core.healpix_cone_search(lon, lat, radius, nside, order) | def healpix_cone_search(lon, lat, radius, nside, order='ring') | Find all the HEALPix pixels within a given radius of a longitude/latitude.
Note that this returns all pixels that overlap, including partially, with
the search cone. This function can only be used for a single lon/lat pair at
a time, since different calls to the function may result in a different
numbe... | 2.117633 | 2.719937 | 0.778559 |
healpix_index = np.asarray(healpix_index, dtype=np.int64)
step = int(step)
if step < 1:
raise ValueError('step must be at least 1')
# PERF: this could be optimized by writing a Cython routine to do this to
# avoid allocating temporary arrays
frac = np.linspace(0., 1., step + 1)[... | def boundaries_lonlat(healpix_index, step, nside, order='ring') | Return the longitude and latitude of the edges of HEALPix pixels
This returns the longitude and latitude of points along the edge of each
HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
so setting ``step`` to 1 returns just the corners.
Parameters
----------
healpi... | 2.609551 | 2.464078 | 1.059038 |
resolution = nside_to_pixel_resolution(nside)
if arcmin:
return resolution.to(u.arcmin).value
else:
return resolution.to(u.rad).value | def nside2resol(nside, arcmin=False) | Drop-in replacement for healpy `~healpy.pixelfunc.nside2resol`. | 2.682082 | 2.749458 | 0.975495 |
area = nside_to_pixel_area(nside)
if degrees:
return area.to(u.deg ** 2).value
else:
return area.to(u.sr).value | def nside2pixarea(nside, degrees=False) | Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`. | 2.354523 | 2.604379 | 0.904063 |
lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring')
return _lonlat_to_healpy(lon, lat, lonlat=lonlat) | def pix2ang(nside, ipix, nest=False, lonlat=False) | Drop-in replacement for healpy `~healpy.pixelfunc.pix2ang`. | 3.447283 | 3.199796 | 1.077344 |
lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat)
return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring') | def ang2pix(nside, theta, phi, nest=False, lonlat=False) | Drop-in replacement for healpy `~healpy.pixelfunc.ang2pix`. | 3.974988 | 3.71977 | 1.068611 |
lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring')
return ang2vec(*_lonlat_to_healpy(lon, lat)) | def pix2vec(nside, ipix, nest=False) | Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`. | 4.445826 | 4.251808 | 1.045632 |
theta, phi = vec2ang(np.transpose([x, y, z]))
# hp.vec2ang() returns raveled arrays, which are 1D.
if np.isscalar(x):
theta = theta.item()
phi = phi.item()
else:
shape = np.shape(x)
theta = theta.reshape(shape)
phi = phi.reshape(shape)
lon, lat = _healpy_... | def vec2pix(nside, x, y, z, nest=False) | Drop-in replacement for healpy `~healpy.pixelfunc.vec2pix`. | 3.841968 | 3.604975 | 1.06574 |
ipix = np.atleast_1d(ipix).astype(np.int64, copy=False)
return nested_to_ring(ipix, nside) | def nest2ring(nside, ipix) | Drop-in replacement for healpy `~healpy.pixelfunc.nest2ring`. | 3.223363 | 2.96521 | 1.087061 |
ipix = np.atleast_1d(ipix).astype(np.int64, copy=False)
return ring_to_nested(ipix, nside) | def ring2nest(nside, ipix) | Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`. | 3.395591 | 3.210824 | 1.057545 |
pix = np.asarray(pix)
if pix.ndim > 1:
# For consistency with healpy we only support scalars or 1D arrays
raise ValueError("Array has to be one dimensional")
lon, lat = boundaries_lonlat(pix, step, nside, order='nested' if nest else 'ring')
rep_sph = UnitSphericalRepresentation(lon,... | def boundaries(nside, pix, step=1, nest=False) | Drop-in replacement for healpy `~healpy.boundaries`. | 4.372715 | 4.210114 | 1.038622 |
x, y, z = vectors.transpose()
rep_car = CartesianRepresentation(x, y, z)
rep_sph = rep_car.represent_as(UnitSphericalRepresentation)
return _lonlat_to_healpy(rep_sph.lon.ravel(), rep_sph.lat.ravel(), lonlat=lonlat) | def vec2ang(vectors, lonlat=False) | Drop-in replacement for healpy `~healpy.pixelfunc.vec2ang`. | 3.894551 | 3.650446 | 1.06687 |
lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat)
rep_sph = UnitSphericalRepresentation(lon, lat)
rep_car = rep_sph.represent_as(CartesianRepresentation)
return rep_car.xyz.value | def ang2vec(theta, phi, lonlat=False) | Drop-in replacement for healpy `~healpy.pixelfunc.ang2vec`. | 3.557552 | 3.277907 | 1.085312 |
# if phi is not given, theta is interpreted as pixel number
if phi is None:
theta, phi = pix2ang(nside, ipix=theta, nest=nest)
lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat)
return bilinear_interpolation_weights(lon, lat, nside, order='nested' if nest else 'ring') | def get_interp_weights(nside, theta, phi=None, nest=False, lonlat=False) | Drop-in replacement for healpy `~healpy.pixelfunc.get_interp_weights`.
Although note that the order of the weights and pixels may differ. | 3.912051 | 4.048783 | 0.966229 |
lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat)
return interpolate_bilinear_lonlat(lon, lat, m, order='nested' if nest else 'ring') | def get_interp_val(m, theta, phi, nest=False, lonlat=False) | Drop-in replacement for healpy `~healpy.pixelfunc.get_interp_val`. | 5.76376 | 5.151153 | 1.118926 |
results = []
if fast:
SIZES = [10, 1e3, 1e5]
else:
SIZES = [10, 1e3, 1e6]
for nest in [True, False]:
for size in SIZES:
for nside in [1, 128]:
results.append(run_single('pix2ang', bench_pix2ang, fast=fast,
... | def bench_run(fast=False) | Run all benchmarks. Return results as a dict. | 1.742473 | 1.733453 | 1.005204 |
table = Table(names=['function', 'nest', 'nside', 'size',
'time_healpy', 'time_self', 'ratio'],
dtype=['S20', bool, int, int, float, float, float], masked=True)
for row in results:
table.add_row(row)
table['time_self'].format = '10.7f'
if HEALPY... | def bench_report(results) | Print a report for given benchmark results to the console. | 3.824862 | 3.946434 | 0.969194 |
print('Running benchmarks...\n')
results = bench_run(fast=fast)
bench_report(results) | def main(fast=False) | Run all benchmarks and print report to the console. | 8.428847 | 5.519098 | 1.527215 |
app.scoped_session = self
@app.teardown_appcontext
def remove_scoped_session(*args, **kwargs):
# pylint: disable=missing-docstring,unused-argument,unused-variable
app.scoped_session.remove() | def init_app(self, app) | Setup scoped sesssion creation and teardown for the passed ``app``.
:param app: a :class:`~flask.Flask` application | 3.874642 | 4.521788 | 0.856883 |
cache = f.cache = {}
@functools.wraps(f)
def decorator(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = f(*args, **kwargs)
return cache[key]
return decorator | def cached(f) | Cache decorator for functions taking one or more arguments.
:param f: The function to be cached.
:return: The cached value. | 1.981943 | 2.205919 | 0.898466 |
templates_folder = 'templates'
static_folder = 'dist'
default_config = {
'client_realm': 'null',
'client_id': 'null',
'client_secret': 'null',
'app_name': 'null',
'docExpansion': "none",
'jsonEditor': False,
'defaultModelRendering': 'schema',
... | def register_swaggerui_app(app, swagger_uri, api_url, page_title='Swagger UI', favicon_url=None, config=None, uri_prefix="") | :type app: falcon.API | 2.99204 | 2.869084 | 1.042856 |
self.app = app
self.dynamic_url = self.app.config.get('APIDOC_DYNAMIC_URL', self.dynamic_url)
self.allow_absolute_url = self.app.config.get('APIDOC_ALLOW_ABSOLUTE_URL', self.allow_absolute_url)
url = self.url_path
if not self.url_path.endswith('/'):
url +... | def init_app(self, app) | Adds the flask url routes for the apidoc files.
:param app: the flask application. | 2.630974 | 2.553069 | 1.030514 |
if not path:
path = 'index.html'
file_name = join(self.folder_path, path)
# the api_project.js has the absolute url
# hard coded so we replace them by the current url.
if self.dynamic_url and path == 'api_project.js':
return self.__send_api_fil... | def __send_static_file(self, path=None) | Send apidoc files from the apidoc folder to the browser.
:param path: the apidoc file. | 5.904084 | 5.508704 | 1.071774 |
file_name = join(self.app.static_folder, file_name)
with codecs.open(file_name, 'r', 'utf-8') as file:
data = file.read()
# replaces the hard coded url by the current url.
api_project = self.__read_api_project()
old_url = api_project.get('url')
#... | def __send_api_file(self, file_name) | Send apidoc files from the apidoc folder to the browser.
This method replaces all absolute urls in the file by
the current url.
:param file_name: the apidoc file. | 3.583632 | 3.221468 | 1.112422 |
file_name = join(self.app.static_folder, file_name)
with codecs.open(file_name, 'r', 'utf-8') as file:
data = file.read()
data = data.replace(
'fields.article.url = apiProject.url + fields.article.url;',
'''if (fields.article.url.substr(0, 4).toLow... | def __send_main_file(self, file_name) | Send apidoc files from the apidoc folder to the browser.
This method replaces all absolute urls in the file by
the current url.
:param file_name: the apidoc file. | 3.304463 | 3.121084 | 1.058755 |
file_name = join(self.app.static_folder, self.folder_path, 'api_project.json')
with open(file_name, 'rt') as file:
data = file.read()
return json.loads(data) | def __read_api_project(self) | Reads the api_project.json file from apidoc folder as a json string.
:return: a json string | 4.219954 | 3.570947 | 1.181746 |
text_dict = {
"error": reason
}
if data is not None:
text_dict["errors"] = data
raise cls(
text=json.dumps(text_dict),
content_type="application/json"
) | def _raise_exception(cls, reason, data=None) | Raise aiohttp exception and pass payload/reason into it. | 3.154145 | 2.842243 | 1.109738 |
validator = validator_cls(schema)
_errors = defaultdict(list)
for err in validator.iter_errors(data):
path = err.schema_path
# Code courtesy: Ruslan Karalkin
# Looking in error schema path for
# property that failed validation
# Schema example:
# {
... | def _validate_data(data, schema, validator_cls) | Validate the dict against given schema (using given validator class). | 5.124474 | 5.108462 | 1.003134 |
def wrapper(func):
# Validating the schemas itself.
# Die with exception if they aren't valid
if request_schema is not None:
_request_schema_validator = validator_for(request_schema)
_request_schema_validator.check_schema(request_schema)
if response_sche... | def validate(request_schema=None, response_schema=None) | Decorate request handler to make it automagically validate it's request
and response. | 2.886258 | 2.856065 | 1.010572 |
print(JsonSchemaGenerator(yamlfile, format).serialize(inline=inline)) | def cli(yamlfile, inline, format) | Generate JSON Schema representation of a biolink model | 10.185239 | 8.489369 | 1.199764 |
rval = dict()
for k, v in data.__dict__.items():
if not k.startswith('_') and v is not None and (not isinstance(v, (dict, list)) or v):
rval[k] = v
return dumper.represent_data(rval) | def root_representer(dumper: yaml.Dumper, data: YAMLRoot) | YAML callback -- used to filter out empty values (None, {}, [] and false)
@param dumper: data dumper
@param data: data to be dumped
@return: | 3.213667 | 3.101948 | 1.036016 |
MarkdownGenerator(yamlfile, format).serialize(classes=classes, directory=dir, image_dir=img, noimages=noimages) | def cli(yamlfile, format, dir, classes, img, noimages) | Generate markdown documentation of a biolink model | 5.614479 | 5.8095 | 0.966431 |
if not self.gen_classes:
return True
elif en in self.schema.classes:
return en in self.gen_classes_neighborhood.classrefs
elif en in self.schema.slots:
return en in self.gen_classes_neighborhood.slotrefs
elif en in self.schema.types:
... | def is_secondary_ref(self, en: str) -> bool | Determine whether 'en' is the name of something in the neighborhood of the requested classes
@param en: element name
@return: True if 'en' is the name of a slot, class or type in the immediate neighborhood of of what we are
building | 3.761022 | 2.836947 | 1.325729 |
return obj.name if isinstance(obj, Element ) else f'**{obj}**' if obj in builtin_names else obj | def bbin(obj: Union[str, Element]) -> str | Boldify built in types
@param obj: object name or id
@return: | 14.442898 | 13.74709 | 1.050615 |
if obj.description and doing_descs:
if isinstance(obj, SlotDefinition) and obj.is_a:
parent = self.schema.slots[obj.is_a]
elif isinstance(obj, ClassDefinition) and obj.is_a:
parent = self.schema.classes[obj.is_a]
else:
... | def desc_for(self, obj: Element, doing_descs: bool) -> str | Return a description for object if it is unique (different than its parent)
@param obj: object to be described
@param doing_descs: If false, always return an empty string
@return: text or empty string | 2.956663 | 2.92631 | 1.010373 |
obj = self.obj_for(ref) if isinstance(ref, str) else ref
nl = '\n'
if isinstance(obj, str) or obj is None or not self.is_secondary_ref(obj.name):
return self.bbin(ref)
if isinstance(obj, SlotDefinition):
link_name = ((be(obj.domain) + '.') if obj.alias el... | def link(self, ref: Optional[Union[str, Element]], *, after_link: str = None, use_desc: bool=False,
add_subset: bool=True) -> str | Create a link to ref if appropriate.
@param ref: the name or value of a class, slot, type or the name of a built in type.
@param after_link: Text to put between link and description
@param use_desc: True means append a description after the link if available
@param add_subset: True mean... | 5.036597 | 4.902555 | 1.027341 |
print(OwlSchemaGenerator(yamlfile, format).serialize(output=output)) | def cli(yamlfile, format, output) | Generate an OWL representation of a biolink model | 12.318312 | 10.428553 | 1.18121 |
# Note: We use the raw name in OWL and add a subProperty arc
slot_uri = self.prop_uri(slot.name)
# Parent slots
if slot.is_a:
self.graph.add((slot_uri, RDFS.subPropertyOf, self.prop_uri(slot.is_a)))
for mixin in slot.mixins:
self.graph.add((slot_... | def visit_slot(self, slot_name: str, slot: SlotDefinition) -> None | Add a slot definition per slot
@param slot_name:
@param slot:
@return: | 2.154574 | 2.147642 | 1.003228 |
if isinstance(data, str):
if '\n' in data:
return load_raw_schema((cast(TextIO, StringIO(data)))) # Not sure why typing doesn't see StringIO as TextIO
elif '://' in data:
# TODO: complete and test URL access
req = Request(data)
req.add_header("Ac... | def load_raw_schema(data: Union[str, TextIO],
source_file: str=None,
source_file_date: str=None,
source_file_size: int=None,
base_dir: Optional[str]=None) -> SchemaDefinition | Load and flatten SchemaDefinition from a file name, a URL or a block of text
@param data: URL, file name or block of text
@param source_file: Source file name for the schema
@param source_file_date: timestamp of source file
@param source_file_size: size of source file
@param base_dir: Working direc... | 2.940408 | 2.914275 | 1.008967 |
mapping = {}
for key_node, value_node in node.value:
key = loader.construct_object(key_node, deep=deep)
value = loader.construct_object(value_node, deep=deep)
if key in mapping:
raise ValueError(f"Duplicate key: \"{key}\"")
mapping... | def map_constructor(self, loader, node, deep=False) | Walk the mapping, recording any duplicate keys. | 1.977479 | 1.810911 | 1.09198 |
sys.exit(compare_files(file1, file2, comments)) | def cli(file1, file2, comments) -> int | Compare file1 to file2 using a filter | 7.765019 | 4.56438 | 1.701221 |
print(GolrSchemaGenerator(file, format).serialize(dirname=dir)) | def cli(file, dir, format) | Generate GOLR representation of a biolink model | 30.643219 | 14.1519 | 2.165308 |
DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out) | def cli(yamlfile, directory, out, classname, format) | Generate graphviz representations of the biolink model | 10.984835 | 12.743958 | 0.861964 |
print(JSONLDGenerator(yamlfile, format).serialize(context=context)) | def cli(yamlfile, format, context) | Generate JSONLD file from biolink schema | 9.790858 | 8.254242 | 1.186161 |
print(RDFGenerator(yamlfile, format).serialize(output=output, context=context)) | def cli(yamlfile, format, output, context) | Generate an RDF representation of a biolink model | 6.729128 | 5.783667 | 1.163471 |
if not isinstance(cls, ClassDefinition):
cls = self.schema.classes[cls]
return [self.schema.slots[s] for s in cls.slots] | def cls_slots(self, cls: CLASS_OR_CLASSNAME) -> List[SlotDefinition] | Return the list of slots directly included in the class definition. Includes slots whose
domain is cls -- as declared in slot.domain or class.slots
Does not include slots declared in mixins, apply_to or is_a links
@param cls: class name or class definition name
@return: all direct cla... | 3.055183 | 3.859171 | 0.791668 |
def merge_definitions(cls_name: Optional[ClassDefinitionName]) -> None:
if cls_name:
for slot in self.all_slots(cls_name):
aliased_name = self.aliased_slot_name(slot)
if aliased_name not in known_slots:
known_sl... | def all_slots(self, cls: CLASS_OR_CLASSNAME, *, cls_slots_first: bool = False) \
-> List[SlotDefinition] | Return all slots that are part of the class definition. This includes all is_a, mixin and apply_to slots
but does NOT include slot_usage targets. If class B has a slot_usage entry for slot "s", only the slot
definition for the redefined slot will be included, not its base. Slots are added in the orde... | 2.525023 | 2.549406 | 0.990436 |
definition = self.obj_for(definition)
if definition is not None:
return [definition.name] + self.ancestors(definition.is_a)
else:
return [] | def ancestors(self, definition: Union[SLOT_OR_SLOTNAME,
CLASS_OR_CLASSNAME]) \
-> List[Union[SlotDefinitionName, ClassDefinitionName]] | Return an ordered list of ancestor names for the supplied slot or class
@param definition: Slot or class name or definition
@return: List of ancestor names | 4.551906 | 6.005414 | 0.757967 |
touches = References()
for element in elements:
if element in self.schema.classes:
touches.classrefs.add(element)
if None in touches.classrefs:
raise ValueError("1")
cls = self.schema.classes[element]
... | def neighborhood(self, elements: List[ELEMENT_NAME]) \
-> References | Return a list of all slots, classes and types that touch any element in elements, including the element
itself
@param elements: Elements to do proximity with
@return: All slots and classes that touch element | 2.131791 | 2.122395 | 1.004427 |
if slot is not None and not isinstance(slot, str):
slot = slot.range
if slot is None:
return DEFAULT_BUILTIN_TYPE_NAME # Default type name
elif slot in builtin_names:
return slot
elif slot in self.schema.types:
return self.... | def grounded_slot_range(self, slot: Optional[Union[SlotDefinition, Optional[str]]]) -> str | Chase the slot range to its final form
@param slot: slot to check
@return: name of resolved range | 4.769011 | 4.862785 | 0.980716 |
if isinstance(slot, str):
slot = self.schema.slots[slot]
return slot.alias if slot.alias else slot.name | def aliased_slot_name(self, slot: SLOT_OR_SLOTNAME) -> str | Return the overloaded slot name -- the alias if one exists otherwise the actual name
@param slot: either a slot name or a definition
@return: overloaded name | 3.840322 | 4.183863 | 0.917889 |
return {self.aliased_slot_name(sn) for sn in slot_names} | def aliased_slot_names(self, slot_names: List[SlotDefinitionName]) -> Set[str] | Return the aliased slot names for all members of the list
@param slot_names: actual slot names
@return: aliases w/ duplicates removed | 3.716951 | 4.776956 | 0.7781 |
name = obj_or_name.name if isinstance(obj_or_name, Element) else obj_or_name
return self.schema.classes[name] if name in self.schema.classes \
else self.schema.slots[name] if name in self.schema.slots \
else self.schema.types[name] if name in self.schema.types else name ... | def obj_for(self, obj_or_name: Union[str, Element]) -> Optional[Union[str, Element]] | Return the class, slot or type that represents name or name itself if it is a builtin
@param obj_or_name: Object or name
@return: Corresponding element or None if not found (most likely cause is that it is a builtin type) | 2.693197 | 2.299294 | 1.171315 |
if isinstance(obj, str):
obj = self.obj_for(obj)
if isinstance(obj, SlotDefinition):
return underscore(self.aliased_slot_name(obj))
else:
return camelcase(obj if isinstance(obj, str) else obj.name) | def obj_name(self, obj: Union[str, Element]) -> str | Return the formatted name used for the supplied definition | 5.228339 | 4.386481 | 1.191921 |
print(CsvGenerator(yamlfile, format).serialize(classes=root)) | def cli(yamlfile, root, format) | Generate CSV/TSV file from biolink model | 28.328901 | 26.298582 | 1.077203 |
inherited_head = 'inherited_slots: List[str] = ['
inherited_slots = ', '.join([f'"{underscore(slot.name)}"' for slot in self.schema.slots.values()
if slot.inherited])
is_rows = split_line(inherited_slots, 120 - len(inherited_head))
return inh... | def gen_inherited(self) -> str | Generate the list of slot properties that are inherited across slot_usage or is_a paths | 5.074507 | 4.613853 | 1.099842 |
rval = []
for cls in self.schema.classes.values():
pkeys = self.primary_keys_for(cls)
for pk in pkeys:
pk_slot = self.schema.slots[pk]
classname = camelcase(cls.name) + camelcase(pk)
if cls.is_a and getattr(self.schema.clas... | def gen_references(self) -> str | Generate python type declarations for all identifiers (primary keys) | 3.963918 | 3.562686 | 1.112621 |
rval = []
for typ in self.schema.types.values():
typname = self.python_name_for(typ.name)
parent = self.python_name_for(typ.typeof)
rval.append(f'class {typname}({parent}):\n\tpass')
return '\n\n\n'.join(rval) + ('\n' if rval else '') | def gen_typedefs(self) -> str | Generate python type declarations for all defined types | 4.215275 | 3.610689 | 1.167443 |
return '\n'.join([self.gen_classdef(k, v) for k, v in self.schema.classes.items() if not v.mixin]) | def gen_classdefs(self) -> str | Create class definitions for all non-mixin classes in the model
Note that apply_to classes are transformed to mixins | 4.716027 | 3.249808 | 1.451171 |
parentref = f'({self.python_name_for(cls.is_a) if cls.is_a else "YAMLRoot"})'
slotdefs = self.gen_slot_variables(cls)
postinits = self.gen_postinits(cls)
if not slotdefs:
slotdefs = 'pass'
wrapped_description = f'''
''' if be(cls.description) else ''
... | def gen_classdef(self, clsname: str, cls: ClassDefinition) -> str | Generate python definition for class clsname | 6.55223 | 6.156785 | 1.064229 |
return '\n\t'.join([self.gen_slot_variable(cls, pk) for pk in self.primary_keys_for(cls)] +
[self.gen_slot_variable(cls, slot)
for slot in cls.slots
if not self.schema.slots[slot].primary_key and not self.schema.slots[sl... | def gen_slot_variables(self, cls: ClassDefinition) -> str | Generate python definition for class cls, generating primary keys first followed by the rest of the slots | 3.802263 | 2.843565 | 1.337146 |
slot = self.schema.slots[slotname]
# Alias allows re-use of slot names in different contexts
if slot.alias:
slotname = slot.alias
range_type = self.range_type_name(slot, cls.name)
# Python version < 3.7 -- forward references have to be quoted
if slo... | def gen_slot_variable(self, cls: ClassDefinition, slotname: str) -> str | Generate a slot variable for slotname as defined in class | 5.396708 | 5.288744 | 1.020414 |
post_inits = []
if not cls.abstract:
pkeys = self.primary_keys_for(cls)
for pkey in pkeys:
post_inits.append(self.gen_postinit(cls, pkey))
for slotname in cls.slots:
slot = self.schema.slots[slotname]
if not (slot.primary_k... | def gen_postinits(self, cls: ClassDefinition) -> str | Generate all the typing and existence checks post initialize | 3.127403 | 2.98967 | 1.04607 |
rlines: List[str] = []
slot = self.schema.slots[slotname]
if slot.alias:
slotname = slot.alias
slotname = self.python_name_for(slotname)
range_type_name = self.range_type_name(slot, cls.name)
# Generate existence check for required slots. Note that ... | def gen_postinit(self, cls: ClassDefinition, slotname: str) -> Optional[str] | Generate python post init rules for slot in class | 3.064825 | 3.016366 | 1.016065 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.