_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q225300
sidereal_time
train
def sidereal_time(t): """Compute Greenwich sidereal time at the given ``Time``.""" # Compute the Earth Rotation Angle. Time argument is UT1. theta = earth_rotation_angle(t.ut1) # The equinox method. See Circular 179, Section 2.6.2. # Precession-in-RA terms in mean sidereal time taken from third...
python
{ "resource": "" }
q225301
refraction
train
def refraction(alt_degrees, temperature_C, pressure_mbar): """Given an observed altitude, return how much the image is refracted. Zero refraction is returned both for objects very near the zenith, as well as for objects more than one degree below the horizon. """ r = 0.016667 / tan((alt_degrees + ...
python
{ "resource": "" }
q225302
refract
train
def refract(alt_degrees, temperature_C, pressure_mbar): """Given an unrefracted `alt` determine where it will appear in the sky.""" alt = alt_degrees while True: alt1 = alt alt = alt_degrees + refraction(alt, temperature_C, pressure_mbar) converged = abs(alt - alt1) <= 3.0e-5 ...
python
{ "resource": "" }
q225303
compute_precession
train
def compute_precession(jd_tdb): """Return the rotation matrices for precessing to an array of epochs. `jd_tdb` - array of TDB Julian dates The array returned has the shape `(3, 3, n)` where `n` is the number of dates that have been provided as input. """ eps0 = 84381.406 # 't' is time in...
python
{ "resource": "" }
q225304
compute_nutation
train
def compute_nutation(t): """Generate the nutation rotations for Time `t`. If the Julian date is scalar, a simple ``(3, 3)`` matrix is returned; if the date is an array of length ``n``, then an array of matrices is returned with dimensions ``(3, 3, n)``. """ oblm, oblt, eqeq, psi, eps = t._eart...
python
{ "resource": "" }
q225305
earth_tilt
train
def earth_tilt(t): """Return a tuple of information about the earth's axis and position. `t` - A Time object. The returned tuple contains five items: ``mean_ob`` - Mean obliquity of the ecliptic in degrees. ``true_ob`` - True obliquity of the ecliptic in degrees. ``eq_eq`` - Equation of the e...
python
{ "resource": "" }
q225306
mean_obliquity
train
def mean_obliquity(jd_tdb): """Return the mean obliquity of the ecliptic in arcseconds. `jd_tt` - TDB time as a Julian date float, or NumPy array of floats """ # Compute time in Julian centuries from epoch J2000.0. t = (jd_tdb - T0) / 36525.0 # Compute the mean obliquity in arcseconds. Use ...
python
{ "resource": "" }
q225307
equation_of_the_equinoxes_complimentary_terms
train
def equation_of_the_equinoxes_complimentary_terms(jd_tt): """Compute the complementary terms of the equation of the equinoxes. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats """ # Interval between fundamental epoch J2000.0 and current date. t = (jd_tt - T0) / 36525.0 ...
python
{ "resource": "" }
q225308
iau2000a
train
def iau2000a(jd_tt): """Compute Earth nutation based on the IAU 2000A nutation model. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of a micro-arcsecond. Each value is either a float, or a NumPy array with...
python
{ "resource": "" }
q225309
iau2000b
train
def iau2000b(jd_tt): """Compute Earth nutation based on the faster IAU 2000B nutation model. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of a micro-arcsecond. Each is either a float, or a NumPy array with ...
python
{ "resource": "" }
q225310
load_dataframe
train
def load_dataframe(fobj, compression='gzip'): """Given an open file for `hip_main.dat.gz`, return a parsed dataframe. If your copy of ``hip_main.dat`` has already been unzipped, pass the optional argument ``compression=None``. """ try: from pandas import read_fwf except ImportError: ...
python
{ "resource": "" }
q225311
Topos._altaz_rotation
train
def _altaz_rotation(self, t): """Compute the rotation from the ICRF into the alt-az system.""" R_lon = rot_z(- self.longitude.radians - t.gast * tau / 24.0) return einsum('ij...,jk...,kl...->il...', self.R_lat, R_lon, t.M)
python
{ "resource": "" }
q225312
Topos._at
train
def _at(self, t): """Compute the GCRS position and velocity of this Topos at time `t`.""" pos, vel = terra(self.latitude.radians, self.longitude.radians, self.elevation.au, t.gast) pos = einsum('ij...,j...->i...', t.MT, pos) vel = einsum('ij...,j...->i...', t.MT,...
python
{ "resource": "" }
q225313
osculating_elements_of
train
def osculating_elements_of(position, reference_frame=None): """Produce the osculating orbital elements for a position. The ``position`` should be an :class:`~skyfield.positionlib.ICRF` instance like that returned by the ``at()`` method of any Solar System body, specifying a position, a velocity, and a ...
python
{ "resource": "" }
q225314
theta_GMST1982
train
def theta_GMST1982(jd_ut1): """Return the angle of Greenwich Mean Standard Time 1982 given the JD. This angle defines the difference between the idiosyncratic True Equator Mean Equinox (TEME) frame of reference used by SGP4 and the more standard Pseudo Earth Fixed (PEF) frame of reference. From AI...
python
{ "resource": "" }
q225315
TEME_to_ITRF
train
def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0): """Convert TEME position and velocity into standard ITRS coordinates. This converts a position and velocity vector in the idiosyncratic True Equator Mean Equinox (TEME) frame of reference used by the SGP4 theory into vectors into the more standard...
python
{ "resource": "" }
q225316
EarthSatellite.ITRF_position_velocity_error
train
def ITRF_position_velocity_error(self, t): """Return the ITRF position, velocity, and error at time `t`. The position is an x,y,z vector measured in au, the velocity is an x,y,z vector measured in au/day, and the error is a vector of possible error messages for the time or vector of tim...
python
{ "resource": "" }
q225317
EarthSatellite._at
train
def _at(self, t): """Compute this satellite's GCRS position and velocity at time `t`.""" rITRF, vITRF, error = self.ITRF_position_velocity_error(t) rGCRS, vGCRS = ITRF_to_GCRS2(t, rITRF, vITRF) return rGCRS, vGCRS, rGCRS, error
python
{ "resource": "" }
q225318
morrison_and_stephenson_2004_table
train
def morrison_and_stephenson_2004_table(): """Table of smoothed Delta T values from Morrison and Stephenson, 2004.""" import pandas as pd f = load.open('http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html') tables = pd.read_html(f.read()) df = tables[0] return pd.DataFrame({'year': df[0], 'delta_t': ...
python
{ "resource": "" }
q225319
angle_between
train
def angle_between(u_vec, v_vec): """Given 2 vectors in `v` and `u`, return the angle separating them. This works whether `v` and `u` each have the shape ``(3,)``, or whether they are each whole arrays of corresponding x, y, and z coordinates and have shape ``(3, N)``. The returned angle will be bet...
python
{ "resource": "" }
q225320
Star._compute_vectors
train
def _compute_vectors(self): """Compute the star's position as an ICRF position and velocity.""" # Use 1 gigaparsec for stars whose parallax is zero. parallax = self.parallax_mas if parallax <= 0.0: parallax = 1.0e-6 # Convert right ascension, declination, and paral...
python
{ "resource": "" }
q225321
_to_array
train
def _to_array(value): """As a convenience, turn Python lists and tuples into NumPy arrays.""" if isinstance(value, (tuple, list)): return array(value) elif isinstance(value, (float, int)): return np.float64(value) else: return value
python
{ "resource": "" }
q225322
_sexagesimalize_to_float
train
def _sexagesimalize_to_float(value): """Decompose `value` into units, minutes, and seconds. Note that this routine is not appropriate for displaying a value, because rounding to the smallest digit of display is necessary before showing a value to the user. Use `_sexagesimalize_to_int()` for data b...
python
{ "resource": "" }
q225323
_sexagesimalize_to_int
train
def _sexagesimalize_to_int(value, places=0): """Decompose `value` into units, minutes, seconds, and second fractions. This routine prepares a value for sexagesimal display, with its seconds fraction expressed as an integer with `places` digits. The result is a tuple of five integers: ``(sign [eit...
python
{ "resource": "" }
q225324
_hstr
train
def _hstr(hours, places=2): """Convert floating point `hours` into a sexagesimal string. >>> _hstr(12.125) '12h 07m 30.00s' >>> _hstr(12.125, places=4) '12h 07m 30.0000s' >>> _hstr(float('nan')) 'nan' """ if isnan(hours): return 'nan' sgn, h, m, s, etc = _sexagesimalize...
python
{ "resource": "" }
q225325
_dstr
train
def _dstr(degrees, places=1, signed=False): r"""Convert floating point `degrees` into a sexagesimal string. >>> _dstr(181.875) '181deg 52\' 30.0"' >>> _dstr(181.875, places=3) '181deg 52\' 30.000"' >>> _dstr(181.875, signed=True) '+181deg 52\' 30.0"' >>> _dstr(float('nan')) 'nan' ...
python
{ "resource": "" }
q225326
_interpret_angle
train
def _interpret_angle(name, angle_object, angle_float, unit='degrees'): """Return an angle in radians from one of two arguments. It is common for Skyfield routines to accept both an argument like `alt` that takes an Angle object as well as an `alt_degrees` that can be given a bare float or a sexagesimal...
python
{ "resource": "" }
q225327
_interpret_ltude
train
def _interpret_ltude(value, name, psuffix, nsuffix): """Interpret a string, float, or tuple as a latitude or longitude angle. `value` - The string to interpret. `name` - 'latitude' or 'longitude', for use in exception messages. `positive` - The string that indicates a positive angle ('N' or 'E'). `...
python
{ "resource": "" }
q225328
Distance.to
train
def to(self, unit): """Convert this distance to the given AstroPy unit.""" from astropy.units import au return (self.au * au).to(unit)
python
{ "resource": "" }
q225329
Velocity.to
train
def to(self, unit): """Convert this velocity to the given AstroPy unit.""" from astropy.units import au, d return (self.au_per_d * au / d).to(unit)
python
{ "resource": "" }
q225330
Angle.hstr
train
def hstr(self, places=2, warn=True): """Convert to a string like ``12h 07m 30.00s``.""" if warn and self.preference != 'hours': raise WrongUnitError('hstr') if self.radians.size == 0: return '<Angle []>' hours = self._hours shape = getattr(hours, 'shape', ...
python
{ "resource": "" }
q225331
Angle.dstr
train
def dstr(self, places=1, warn=True): """Convert to a string like ``181deg 52\' 30.0"``.""" if warn and self.preference != 'degrees': raise WrongUnitError('dstr') if self.radians.size == 0: return '<Angle []>' degrees = self._degrees signed = self.signed ...
python
{ "resource": "" }
q225332
Angle.to
train
def to(self, unit): """Convert this angle to the given AstroPy unit.""" from astropy.units import rad return (self.radians * rad).to(unit) # Or should this do: from astropy.coordinates import Angle from astropy.units import rad return Angle(self.radians, rad).to(...
python
{ "resource": "" }
q225333
ICRF.separation_from
train
def separation_from(self, another_icrf): """Return the angle between this position and another. >>> print(ICRF([1,0,0]).separation_from(ICRF([1,1,0]))) 45deg 00' 00.0" You can also compute separations across an array of positions. >>> directions = ICRF([[1,0,-1,0], [0,1,0,-1],...
python
{ "resource": "" }
q225334
ICRF.to_skycoord
train
def to_skycoord(self, unit=None): """Convert this distance to an AstroPy ``SkyCoord`` object.""" from astropy.coordinates import SkyCoord from astropy.units import au x, y, z = self.position.au return SkyCoord(representation='cartesian', x=x, y=y, z=z, unit=au)
python
{ "resource": "" }
q225335
ICRF.from_altaz
train
def from_altaz(self, alt=None, az=None, alt_degrees=None, az_degrees=None, distance=Distance(au=0.1)): """Generate an Apparent position from an altitude and azimuth. The altitude and azimuth can each be provided as an `Angle` object, or else as a number of degrees provided as...
python
{ "resource": "" }
q225336
Barycentric.observe
train
def observe(self, body): """Compute the `Astrometric` position of a body from this location. To compute the body's astrometric position, it is first asked for its position at the time `t` of this position itself. The distance to the body is then divided by the speed of light to ...
python
{ "resource": "" }
q225337
Geocentric.subpoint
train
def subpoint(self): """Return the latitude and longitude directly beneath this position. Returns a :class:`~skyfield.toposlib.Topos` whose ``longitude`` and ``latitude`` are those of the point on the Earth's surface directly beneath this position, and whose ``elevation`` is the ...
python
{ "resource": "" }
q225338
_plot_stars
train
def _plot_stars(catalog, observer, project, ax, mag1, mag2, margin=1.25): """Experiment in progress, hence the underscore; expect changes.""" art = [] # from astropy import wcs # w = wcs.WCS(naxis=2) # w.wcs.crpix = [-234.75, 8.3393] # w.wcs.cdelt = np.array([-0.066667, 0.066667]) # w.wcs....
python
{ "resource": "" }
q225339
phase_angle
train
def phase_angle(ephemeris, body, t): """Compute the phase angle of a body viewed from Earth. The ``body`` should be an integer or string that can be looked up in the given ``ephemeris``, which will also be asked to provide positions for the Earth and Sun. The return value will be an :class:`~skyfi...
python
{ "resource": "" }
q225340
fraction_illuminated
train
def fraction_illuminated(ephemeris, body, t): """Compute the illuminated fraction of a body viewed from Earth. The ``body`` should be an integer or string that can be looked up in the given ``ephemeris``, which will also be asked to provide positions for the Earth and Sun. The return value will be a ...
python
{ "resource": "" }
q225341
find_discrete
train
def find_discrete(start_time, end_time, f, epsilon=EPSILON, num=12): """Find the times when a function changes value. Searches between ``start_time`` and ``end_time``, which should both be :class:`~skyfield.timelib.Time` objects, for the occasions where the function ``f`` changes from one value to anot...
python
{ "resource": "" }
q225342
seasons
train
def seasons(ephemeris): """Build a function of time that returns the quarter of the year. The function that this returns will expect a single argument that is a :class:`~skyfield.timelib.Time` and will return 0 through 3 for the seasons Spring, Summer, Autumn, and Winter. """ earth = ephemeris...
python
{ "resource": "" }
q225343
sunrise_sunset
train
def sunrise_sunset(ephemeris, topos): """Build a function of time that returns whether the sun is up. The function that this returns will expect a single argument that is a :class:`~skyfield.timelib.Time` and will return ``True`` if the sun is up, else ``False``. """ sun = ephemeris['sun'] ...
python
{ "resource": "" }
q225344
moon_phases
train
def moon_phases(ephemeris): """Build a function of time that returns the moon phase 0 through 3. The function that this returns will expect a single argument that is a :class:`~skyfield.timelib.Time` and will return the phase of the moon as an integer. See the accompanying array ``MOON_PHASES`` if ...
python
{ "resource": "" }
q225345
_derive_stereographic
train
def _derive_stereographic(): """Compute the formulae to cut-and-paste into the routine below.""" from sympy import symbols, atan2, acos, rot_axis1, rot_axis3, Matrix x_c, y_c, z_c, x, y, z = symbols('x_c y_c z_c x y z') # The angles we'll need to rotate through. around_z = atan2(x_c, y_c) aroun...
python
{ "resource": "" }
q225346
classifier_factory
train
def classifier_factory(clf): """Embeds scikit-plot instance methods in an sklearn classifier. Args: clf: Scikit-learn classifier instance Returns: The same scikit-learn classifier instance passed in **clf** with embedded scikit-plot instance methods. Raises: ValueError...
python
{ "resource": "" }
q225347
plot_confusion_matrix_with_cv
train
def plot_confusion_matrix_with_cv(clf, X, y, labels=None, true_labels=None, pred_labels=None, title=None, normalize=False, hide_zeros=False, x_tick_rotation=0, do_cv=True, cv=None, shu...
python
{ "resource": "" }
q225348
plot_ks_statistic_with_cv
train
def plot_ks_statistic_with_cv(clf, X, y, title='KS Statistic Plot', do_cv=True, cv=None, shuffle=True, random_state=None, ax=None, figsize=None, title_fontsize="large", text_fontsize="medium"): """Generates the KS Statistic pl...
python
{ "resource": "" }
q225349
plot_confusion_matrix
train
def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None, pred_labels=None, title=None, normalize=False, hide_zeros=False, x_tick_rotation=0, ax=None, figsize=None, cmap='Blues', title_fontsize="large", ...
python
{ "resource": "" }
q225350
plot_feature_importances
train
def plot_feature_importances(clf, title='Feature Importance', feature_names=None, max_num_features=20, order='descending', x_tick_rotation=0, ax=None, figsize=None, title_fontsize="large", text_fontsize="...
python
{ "resource": "" }
q225351
plot_silhouette
train
def plot_silhouette(clf, X, title='Silhouette Analysis', metric='euclidean', copy=True, ax=None, figsize=None, cmap='nipy_spectral', title_fontsize="large", text_fontsize="medium"): """Plots silhouette analysis of clusters using fit_predict. Args: clf: Clusterer ...
python
{ "resource": "" }
q225352
_clone_and_score_clusterer
train
def _clone_and_score_clusterer(clf, X, n_clusters): """Clones and scores clusterer instance. Args: clf: Clusterer instance that implements ``fit``,``fit_predict``, and ``score`` methods, and an ``n_clusters`` hyperparameter. e.g. :class:`sklearn.cluster.KMeans` instance ...
python
{ "resource": "" }
q225353
plot_learning_curve
train
def plot_learning_curve(clf, X, y, title='Learning Curve', cv=None, shuffle=False, random_state=None, train_sizes=None, n_jobs=1, scoring=None, ax=None, figsize=None, title_fontsize="large", text_fontsize="medium"): """G...
python
{ "resource": "" }
q225354
plot_calibration_curve
train
def plot_calibration_curve(y_true, probas_list, clf_names=None, n_bins=10, title='Calibration plots (Reliability Curves)', ax=None, figsize=None, cmap='nipy_spectral', title_fontsize="large", text_fontsize="medium"): """Plots calibrati...
python
{ "resource": "" }
q225355
clustering_factory
train
def clustering_factory(clf): """Embeds scikit-plot plotting methods in an sklearn clusterer instance. Args: clf: Scikit-learn clusterer instance Returns: The same scikit-learn clusterer instance passed in **clf** with embedded scikit-plot instance methods. Raises: Valu...
python
{ "resource": "" }
q225356
validate_labels
train
def validate_labels(known_classes, passed_labels, argument_name): """Validates the labels passed into the true_labels or pred_labels arguments in the plot_confusion_matrix function. Raises a ValueError exception if any of the passed labels are not in the set of known classes or if there are duplicate l...
python
{ "resource": "" }
q225357
cumulative_gain_curve
train
def cumulative_gain_curve(y_true, y_score, pos_label=None): """This function generates the points necessary to plot the Cumulative Gain Note: This implementation is restricted to the binary classification task. Args: y_true (array-like, shape (n_samples)): True labels of the data. y_score...
python
{ "resource": "" }
q225358
getargspec
train
def getargspec(func): """ Used because getargspec for python 2.7 does not accept functools.partial which is the type for pytest fixtures. getargspec excerpted from: sphinx.util.inspect ~~~~~~~~~~~~~~~~~~~ Helpers for inspecting Python modules. :copyright: Copyright 2007-2018 by the Sph...
python
{ "resource": "" }
q225359
QueryStringManager.querystring
train
def querystring(self): """Return original querystring but containing only managed keys :return dict: dict of managed querystring parameter """ return {key: value for (key, value) in self.qs.items() if key.startswith(self.MANAGED_KEYS) or self._get_key_values('filter[')}
python
{ "resource": "" }
q225360
QueryStringManager.filters
train
def filters(self): """Return filters from query string. :return list: filter information """ results = [] filters = self.qs.get('filter') if filters is not None: try: results.extend(json.loads(filters)) except (ValueError, TypeErro...
python
{ "resource": "" }
q225361
QueryStringManager.pagination
train
def pagination(self): """Return all page parameters as a dict. :return dict: a dict of pagination information To allow multiples strategies, all parameters starting with `page` will be included. e.g:: { "number": '25', "size": '150', } ...
python
{ "resource": "" }
q225362
QueryStringManager.fields
train
def fields(self): """Return fields wanted by client. :return dict: a dict of sparse fieldsets information Return value will be a dict containing all fields by resource, for example:: { "user": ['name', 'email'], } """ result = self._get...
python
{ "resource": "" }
q225363
QueryStringManager.sorting
train
def sorting(self): """Return fields to sort by including sort name for SQLAlchemy and row sort parameter for other ORMs :return list: a list of sorting information Example of return value:: [ {'field': 'created_at', 'order': 'desc'}, ] ...
python
{ "resource": "" }
q225364
QueryStringManager.include
train
def include(self): """Return fields to include :return list: a list of include information """ include_param = self.qs.get('include', []) if current_app.config.get('MAX_INCLUDE_DEPTH') is not None: for include_path in include_param: if len(include_pa...
python
{ "resource": "" }
q225365
JsonApiException.to_dict
train
def to_dict(self): """Return values of each fields of an jsonapi error""" error_dict = {} for field in ('status', 'source', 'title', 'detail', 'id', 'code', 'links', 'meta'): if getattr(self, field, None): error_dict.update({field: getattr(self, field)}) retu...
python
{ "resource": "" }
q225366
Resource.dispatch_request
train
def dispatch_request(self, *args, **kwargs): """Logic of how to handle a request""" method = getattr(self, request.method.lower(), None) if method is None and request.method == 'HEAD': method = getattr(self, 'get', None) assert method is not None, 'Unimplemented method {}'.fo...
python
{ "resource": "" }
q225367
ResourceList.get
train
def get(self, *args, **kwargs): """Retrieve a collection of objects""" self.before_get(args, kwargs) qs = QSManager(request.args, self.schema) objects_count, objects = self.get_collection(qs, kwargs) schema_kwargs = getattr(self, 'get_schema_kwargs', dict()) schema_kwa...
python
{ "resource": "" }
q225368
ResourceList.post
train
def post(self, *args, **kwargs): """Create an object""" json_data = request.get_json() or {} qs = QSManager(request.args, self.schema) schema = compute_schema(self.schema, getattr(self, 'post_schema_kwargs', dict()), qs, ...
python
{ "resource": "" }
q225369
ResourceDetail.get
train
def get(self, *args, **kwargs): """Get object details""" self.before_get(args, kwargs) qs = QSManager(request.args, self.schema) obj = self.get_object(kwargs, qs) self.before_marshmallow(args, kwargs) schema = compute_schema(self.schema, ...
python
{ "resource": "" }
q225370
ResourceDetail.patch
train
def patch(self, *args, **kwargs): """Update an object""" json_data = request.get_json() or {} qs = QSManager(request.args, self.schema) schema_kwargs = getattr(self, 'patch_schema_kwargs', dict()) schema_kwargs.update({'partial': True}) self.before_marshmallow(args, kwa...
python
{ "resource": "" }
q225371
ResourceDetail.delete
train
def delete(self, *args, **kwargs): """Delete an object""" self.before_delete(args, kwargs) self.delete_object(kwargs) result = {'meta': {'message': 'Object successfully deleted'}} final_result = self.after_delete(result) return final_result
python
{ "resource": "" }
q225372
ResourceRelationship.get
train
def get(self, *args, **kwargs): """Get a relationship details""" self.before_get(args, kwargs) relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data() obj, data = self._data_layer.get_relationship(model_relationship_field, ...
python
{ "resource": "" }
q225373
ResourceRelationship.patch
train
def patch(self, *args, **kwargs): """Update a relationship""" json_data = request.get_json() or {} relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data() if 'data' not in json_data: raise BadRequest('You must provide da...
python
{ "resource": "" }
q225374
ResourceRelationship._get_relationship_data
train
def _get_relationship_data(self): """Get useful data for relationship management""" relationship_field = request.path.split('/')[-1].replace('-', '_') if relationship_field not in get_relationships(self.schema): raise RelationNotFound("{} has no attribute {}".format(self.schema.__na...
python
{ "resource": "" }
q225375
compute_schema
train
def compute_schema(schema_cls, default_kwargs, qs, include): """Compute a schema around compound documents and sparse fieldsets :param Schema schema_cls: the schema class :param dict default_kwargs: the schema default kwargs :param QueryStringManager qs: qs :param list include: the relation field t...
python
{ "resource": "" }
q225376
get_model_field
train
def get_model_field(schema, field): """Get the model field of a schema field :param Schema schema: a marshmallow schema :param str field: the name of the schema field :return str: the name of the field in the model """ if schema._declared_fields.get(field) is None: raise Exception("{} h...
python
{ "resource": "" }
q225377
get_nested_fields
train
def get_nested_fields(schema, model_field=False): """Return nested fields of a schema to support a join :param Schema schema: a marshmallow schema :param boolean model_field: whether to extract the model field for the nested fields :return list: list of nested fields of the schema """ nested_f...
python
{ "resource": "" }
q225378
get_relationships
train
def get_relationships(schema, model_field=False): """Return relationship fields of a schema :param Schema schema: a marshmallow schema :param list: list of relationship fields of a schema """ relationships = [key for (key, value) in schema._declared_fields.items() if isinstance(value, Relationship)...
python
{ "resource": "" }
q225379
get_schema_from_type
train
def get_schema_from_type(resource_type): """Retrieve a schema from the registry by his type :param str type_: the type of the resource :return Schema: the schema class """ for cls_name, cls in class_registry._registry.items(): try: if cls[0].opts.type_ == resource_type: ...
python
{ "resource": "" }
q225380
get_schema_field
train
def get_schema_field(schema, field): """Get the schema field of a model field :param Schema schema: a marshmallow schema :param str field: the name of the model field :return str: the name of the field in the schema """ schema_fields_to_model = {key: get_model_field(schema, key) for (key, value...
python
{ "resource": "" }
q225381
BaseDataLayer.bound_rewritable_methods
train
def bound_rewritable_methods(self, methods): """Bound additional methods to current instance :param class meta: information from Meta class used to configure the data layer instance """ for key, value in methods.items(): if key in self.REWRITABLE_METHODS: set...
python
{ "resource": "" }
q225382
create_filters
train
def create_filters(model, filter_info, resource): """Apply filters from filters information to base query :param DeclarativeMeta model: the model of the node :param dict filter_info: current node filter information :param Resource resource: the resource """ filters = [] for filter_ in filte...
python
{ "resource": "" }
q225383
Node.resolve
train
def resolve(self): """Create filter for a particular node of the filter tree""" if 'or' not in self.filter_ and 'and' not in self.filter_ and 'not' not in self.filter_: value = self.value if isinstance(value, dict): value = Node(self.related_model, value, self.re...
python
{ "resource": "" }
q225384
Node.name
train
def name(self): """Return the name of the node or raise a BadRequest exception :return str: the name of the field to filter on """ name = self.filter_.get('name') if name is None: raise InvalidFilters("Can't find name of a filter") if '__' in name: ...
python
{ "resource": "" }
q225385
Node.column
train
def column(self): """Get the column object :param DeclarativeMeta model: the model :param str field: the field :return InstrumentedAttribute: the column to filter on """ field = self.name model_field = get_model_field(self.schema, field) try: ...
python
{ "resource": "" }
q225386
Node.operator
train
def operator(self): """Get the function operator from his name :return callable: a callable to make operation on a column """ operators = (self.op, self.op + '_', '__' + self.op + '__') for op in operators: if hasattr(self.column, op): return op ...
python
{ "resource": "" }
q225387
Node.value
train
def value(self): """Get the value to filter on :return: the value to filter on """ if self.filter_.get('field') is not None: try: result = getattr(self.model, self.filter_['field']) except AttributeError: raise InvalidFilters("{} h...
python
{ "resource": "" }
q225388
Node.related_model
train
def related_model(self): """Get the related model of a relationship field :return DeclarativeMeta: the related model """ relationship_field = self.name if relationship_field not in get_relationships(self.schema): raise InvalidFilters("{} has no relationship attribut...
python
{ "resource": "" }
q225389
Node.related_schema
train
def related_schema(self): """Get the related schema of a relationship field :return Schema: the related schema """ relationship_field = self.name if relationship_field not in get_relationships(self.schema): raise InvalidFilters("{} has no relationship attribute {}"....
python
{ "resource": "" }
q225390
Api.init_app
train
def init_app(self, app=None, blueprint=None, additional_blueprints=None): """Update flask application with our api :param Application app: a flask application """ if app is not None: self.app = app if blueprint is not None: self.blueprint = blueprint ...
python
{ "resource": "" }
q225391
Api.route
train
def route(self, resource, view, *urls, **kwargs): """Create an api view. :param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource :param str view: the view name :param list urls: the urls of the view :param dict kwargs: additional options of...
python
{ "resource": "" }
q225392
Api.oauth_manager
train
def oauth_manager(self, oauth_manager): """Use the oauth manager to enable oauth for API :param oauth_manager: the oauth manager """ @self.app.before_request def before_request(): endpoint = request.endpoint resource = self.app.view_functions[endpoint].vi...
python
{ "resource": "" }
q225393
Api.build_scope
train
def build_scope(resource, method): """Compute the name of the scope for oauth :param Resource resource: the resource manager :param str method: an http method :return str: the name of the scope """ if ResourceList in inspect.getmro(resource) and method == 'GET': ...
python
{ "resource": "" }
q225394
Api.permission_manager
train
def permission_manager(self, permission_manager): """Use permission manager to enable permission for API :param callable permission_manager: the permission manager """ self.check_permissions = permission_manager for resource in self.resource_registry: if getattr(res...
python
{ "resource": "" }
q225395
Api.has_permission
train
def has_permission(self, *args, **kwargs): """Decorator used to check permissions before to call resource manager method""" def wrapper(view): if getattr(view, '_has_permissions_decorator', False) is True: return view @wraps(view) @jsonapi_exception_f...
python
{ "resource": "" }
q225396
check_headers
train
def check_headers(func): """Check headers according to jsonapi reference :param callable func: the function to decorate :return callable: the wrapped function """ @wraps(func) def wrapper(*args, **kwargs): if request.method in ('POST', 'PATCH'): if 'Content-Type' in request....
python
{ "resource": "" }
q225397
check_method_requirements
train
def check_method_requirements(func): """Check methods requirements :param callable func: the function to decorate :return callable: the wrapped function """ @wraps(func) def wrapper(*args, **kwargs): error_message = "You must provide {error_field} in {cls} to get access to the default {...
python
{ "resource": "" }
q225398
SqlalchemyDataLayer.create_object
train
def create_object(self, data, view_kwargs): """Create an object through sqlalchemy :param dict data: the data validated by marshmallow :param dict view_kwargs: kwargs from the resource view :return DeclarativeMeta: an object from sqlalchemy """ self.before_create_object(...
python
{ "resource": "" }
q225399
SqlalchemyDataLayer.get_object
train
def get_object(self, view_kwargs, qs=None): """Retrieve an object through sqlalchemy :params dict view_kwargs: kwargs from the resource view :return DeclarativeMeta: an object from sqlalchemy """ self.before_get_object(view_kwargs) id_field = getattr(self, 'id_field', i...
python
{ "resource": "" }