id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
230,000 | skyfielders/python-skyfield | skyfield/almanac.py | fraction_illuminated | 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
floating point number between zero and one. This simple routine
assumes that the body is a perfectly uniform sphere.
"""
a = phase_angle(ephemeris, body, t).radians
return 0.5 * (1.0 + cos(a)) | python | 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
floating point number between zero and one. This simple routine
assumes that the body is a perfectly uniform sphere.
"""
a = phase_angle(ephemeris, body, t).radians
return 0.5 * (1.0 + cos(a)) | [
"def",
"fraction_illuminated",
"(",
"ephemeris",
",",
"body",
",",
"t",
")",
":",
"a",
"=",
"phase_angle",
"(",
"ephemeris",
",",
"body",
",",
"t",
")",
".",
"radians",
"return",
"0.5",
"*",
"(",
"1.0",
"+",
"cos",
"(",
"a",
")",
")"
] | 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
floating point number between zero and one. This simple routine
assumes that the body is a perfectly uniform sphere. | [
"Compute",
"the",
"illuminated",
"fraction",
"of",
"a",
"body",
"viewed",
"from",
"Earth",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L29-L40 |
230,001 | skyfielders/python-skyfield | skyfield/almanac.py | find_discrete | 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 another. Use this to
search for events like sunrise or moon phases.
A tuple of two arrays is returned. The first array gives the times
at which the input function changes, and the second array specifies
the new value of the function at each corresponding time.
This is an expensive operation as it needs to repeatedly call the
function to narrow down the times that it changes. It continues
searching until it knows each time to at least an accuracy of
``epsilon`` Julian days. At each step, it creates an array of
``num`` new points between the lower and upper bound that it has
established for each transition. These two values can be changed to
tune the behavior of the search.
"""
ts = start_time.ts
jd0 = start_time.tt
jd1 = end_time.tt
if jd0 >= jd1:
raise ValueError('your start_time {0} is later than your end_time {1}'
.format(start_time, end_time))
periods = (jd1 - jd0) / f.rough_period
if periods < 1.0:
periods = 1.0
jd = linspace(jd0, jd1, periods * num // 1.0)
end_mask = linspace(0.0, 1.0, num)
start_mask = end_mask[::-1]
o = multiply.outer
while True:
t = ts.tt_jd(jd)
y = f(t)
indices = flatnonzero(diff(y))
if not len(indices):
return indices, y[0:0]
starts = jd.take(indices)
ends = jd.take(indices + 1)
# Since we start with equal intervals, they all should fall
# below epsilon at around the same time; so for efficiency we
# only test the first pair.
if ends[0] - starts[0] <= epsilon:
break
jd = o(starts, start_mask).flatten() + o(ends, end_mask).flatten()
return ts.tt_jd(ends), y.take(indices + 1) | python | 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 another. Use this to
search for events like sunrise or moon phases.
A tuple of two arrays is returned. The first array gives the times
at which the input function changes, and the second array specifies
the new value of the function at each corresponding time.
This is an expensive operation as it needs to repeatedly call the
function to narrow down the times that it changes. It continues
searching until it knows each time to at least an accuracy of
``epsilon`` Julian days. At each step, it creates an array of
``num`` new points between the lower and upper bound that it has
established for each transition. These two values can be changed to
tune the behavior of the search.
"""
ts = start_time.ts
jd0 = start_time.tt
jd1 = end_time.tt
if jd0 >= jd1:
raise ValueError('your start_time {0} is later than your end_time {1}'
.format(start_time, end_time))
periods = (jd1 - jd0) / f.rough_period
if periods < 1.0:
periods = 1.0
jd = linspace(jd0, jd1, periods * num // 1.0)
end_mask = linspace(0.0, 1.0, num)
start_mask = end_mask[::-1]
o = multiply.outer
while True:
t = ts.tt_jd(jd)
y = f(t)
indices = flatnonzero(diff(y))
if not len(indices):
return indices, y[0:0]
starts = jd.take(indices)
ends = jd.take(indices + 1)
# Since we start with equal intervals, they all should fall
# below epsilon at around the same time; so for efficiency we
# only test the first pair.
if ends[0] - starts[0] <= epsilon:
break
jd = o(starts, start_mask).flatten() + o(ends, end_mask).flatten()
return ts.tt_jd(ends), y.take(indices + 1) | [
"def",
"find_discrete",
"(",
"start_time",
",",
"end_time",
",",
"f",
",",
"epsilon",
"=",
"EPSILON",
",",
"num",
"=",
"12",
")",
":",
"ts",
"=",
"start_time",
".",
"ts",
"jd0",
"=",
"start_time",
".",
"tt",
"jd1",
"=",
"end_time",
".",
"tt",
"if",
"jd0",
">=",
"jd1",
":",
"raise",
"ValueError",
"(",
"'your start_time {0} is later than your end_time {1}'",
".",
"format",
"(",
"start_time",
",",
"end_time",
")",
")",
"periods",
"=",
"(",
"jd1",
"-",
"jd0",
")",
"/",
"f",
".",
"rough_period",
"if",
"periods",
"<",
"1.0",
":",
"periods",
"=",
"1.0",
"jd",
"=",
"linspace",
"(",
"jd0",
",",
"jd1",
",",
"periods",
"*",
"num",
"//",
"1.0",
")",
"end_mask",
"=",
"linspace",
"(",
"0.0",
",",
"1.0",
",",
"num",
")",
"start_mask",
"=",
"end_mask",
"[",
":",
":",
"-",
"1",
"]",
"o",
"=",
"multiply",
".",
"outer",
"while",
"True",
":",
"t",
"=",
"ts",
".",
"tt_jd",
"(",
"jd",
")",
"y",
"=",
"f",
"(",
"t",
")",
"indices",
"=",
"flatnonzero",
"(",
"diff",
"(",
"y",
")",
")",
"if",
"not",
"len",
"(",
"indices",
")",
":",
"return",
"indices",
",",
"y",
"[",
"0",
":",
"0",
"]",
"starts",
"=",
"jd",
".",
"take",
"(",
"indices",
")",
"ends",
"=",
"jd",
".",
"take",
"(",
"indices",
"+",
"1",
")",
"# Since we start with equal intervals, they all should fall",
"# below epsilon at around the same time; so for efficiency we",
"# only test the first pair.",
"if",
"ends",
"[",
"0",
"]",
"-",
"starts",
"[",
"0",
"]",
"<=",
"epsilon",
":",
"break",
"jd",
"=",
"o",
"(",
"starts",
",",
"start_mask",
")",
".",
"flatten",
"(",
")",
"+",
"o",
"(",
"ends",
",",
"end_mask",
")",
".",
"flatten",
"(",
")",
"return",
"ts",
".",
"tt_jd",
"(",
"ends",
")",
",",
"y",
".",
"take",
"(",
"indices",
"+",
"1",
")"
] | 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 another. Use this to
search for events like sunrise or moon phases.
A tuple of two arrays is returned. The first array gives the times
at which the input function changes, and the second array specifies
the new value of the function at each corresponding time.
This is an expensive operation as it needs to repeatedly call the
function to narrow down the times that it changes. It continues
searching until it knows each time to at least an accuracy of
``epsilon`` Julian days. At each step, it creates an array of
``num`` new points between the lower and upper bound that it has
established for each transition. These two values can be changed to
tune the behavior of the search. | [
"Find",
"the",
"times",
"when",
"a",
"function",
"changes",
"value",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L44-L101 |
230,002 | skyfielders/python-skyfield | skyfield/almanac.py | seasons | 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['earth']
sun = ephemeris['sun']
def season_at(t):
"""Return season 0 (Spring) through 3 (Winter) at time `t`."""
t._nutation_angles = iau2000b(t.tt)
e = earth.at(t)
_, slon, _ = e.observe(sun).apparent().ecliptic_latlon('date')
return (slon.radians // (tau / 4) % 4).astype(int)
season_at.rough_period = 90.0
return season_at | python | 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['earth']
sun = ephemeris['sun']
def season_at(t):
"""Return season 0 (Spring) through 3 (Winter) at time `t`."""
t._nutation_angles = iau2000b(t.tt)
e = earth.at(t)
_, slon, _ = e.observe(sun).apparent().ecliptic_latlon('date')
return (slon.radians // (tau / 4) % 4).astype(int)
season_at.rough_period = 90.0
return season_at | [
"def",
"seasons",
"(",
"ephemeris",
")",
":",
"earth",
"=",
"ephemeris",
"[",
"'earth'",
"]",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"def",
"season_at",
"(",
"t",
")",
":",
"\"\"\"Return season 0 (Spring) through 3 (Winter) at time `t`.\"\"\"",
"t",
".",
"_nutation_angles",
"=",
"iau2000b",
"(",
"t",
".",
"tt",
")",
"e",
"=",
"earth",
".",
"at",
"(",
"t",
")",
"_",
",",
"slon",
",",
"_",
"=",
"e",
".",
"observe",
"(",
"sun",
")",
".",
"apparent",
"(",
")",
".",
"ecliptic_latlon",
"(",
"'date'",
")",
"return",
"(",
"slon",
".",
"radians",
"//",
"(",
"tau",
"/",
"4",
")",
"%",
"4",
")",
".",
"astype",
"(",
"int",
")",
"season_at",
".",
"rough_period",
"=",
"90.0",
"return",
"season_at"
] | 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. | [
"Build",
"a",
"function",
"of",
"time",
"that",
"returns",
"the",
"quarter",
"of",
"the",
"year",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L161-L180 |
230,003 | skyfielders/python-skyfield | skyfield/almanac.py | sunrise_sunset | 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']
topos_at = (ephemeris['earth'] + topos).at
def is_sun_up_at(t):
"""Return `True` if the sun has risen by time `t`."""
t._nutation_angles = iau2000b(t.tt)
return topos_at(t).observe(sun).apparent().altaz()[0].degrees > -0.8333
is_sun_up_at.rough_period = 0.5 # twice a day
return is_sun_up_at | python | 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']
topos_at = (ephemeris['earth'] + topos).at
def is_sun_up_at(t):
"""Return `True` if the sun has risen by time `t`."""
t._nutation_angles = iau2000b(t.tt)
return topos_at(t).observe(sun).apparent().altaz()[0].degrees > -0.8333
is_sun_up_at.rough_period = 0.5 # twice a day
return is_sun_up_at | [
"def",
"sunrise_sunset",
"(",
"ephemeris",
",",
"topos",
")",
":",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"topos_at",
"=",
"(",
"ephemeris",
"[",
"'earth'",
"]",
"+",
"topos",
")",
".",
"at",
"def",
"is_sun_up_at",
"(",
"t",
")",
":",
"\"\"\"Return `True` if the sun has risen by time `t`.\"\"\"",
"t",
".",
"_nutation_angles",
"=",
"iau2000b",
"(",
"t",
".",
"tt",
")",
"return",
"topos_at",
"(",
"t",
")",
".",
"observe",
"(",
"sun",
")",
".",
"apparent",
"(",
")",
".",
"altaz",
"(",
")",
"[",
"0",
"]",
".",
"degrees",
">",
"-",
"0.8333",
"is_sun_up_at",
".",
"rough_period",
"=",
"0.5",
"# twice a day",
"return",
"is_sun_up_at"
] | 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``. | [
"Build",
"a",
"function",
"of",
"time",
"that",
"returns",
"whether",
"the",
"sun",
"is",
"up",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L182-L200 |
230,004 | skyfielders/python-skyfield | skyfield/almanac.py | moon_phases | 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
you want to give string names to each phase.
"""
earth = ephemeris['earth']
moon = ephemeris['moon']
sun = ephemeris['sun']
def moon_phase_at(t):
"""Return the phase of the moon 0 through 3 at time `t`."""
t._nutation_angles = iau2000b(t.tt)
e = earth.at(t)
_, mlon, _ = e.observe(moon).apparent().ecliptic_latlon('date')
_, slon, _ = e.observe(sun).apparent().ecliptic_latlon('date')
return ((mlon.radians - slon.radians) // (tau / 4) % 4).astype(int)
moon_phase_at.rough_period = 7.0 # one lunar phase per week
return moon_phase_at | python | 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
you want to give string names to each phase.
"""
earth = ephemeris['earth']
moon = ephemeris['moon']
sun = ephemeris['sun']
def moon_phase_at(t):
"""Return the phase of the moon 0 through 3 at time `t`."""
t._nutation_angles = iau2000b(t.tt)
e = earth.at(t)
_, mlon, _ = e.observe(moon).apparent().ecliptic_latlon('date')
_, slon, _ = e.observe(sun).apparent().ecliptic_latlon('date')
return ((mlon.radians - slon.radians) // (tau / 4) % 4).astype(int)
moon_phase_at.rough_period = 7.0 # one lunar phase per week
return moon_phase_at | [
"def",
"moon_phases",
"(",
"ephemeris",
")",
":",
"earth",
"=",
"ephemeris",
"[",
"'earth'",
"]",
"moon",
"=",
"ephemeris",
"[",
"'moon'",
"]",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"def",
"moon_phase_at",
"(",
"t",
")",
":",
"\"\"\"Return the phase of the moon 0 through 3 at time `t`.\"\"\"",
"t",
".",
"_nutation_angles",
"=",
"iau2000b",
"(",
"t",
".",
"tt",
")",
"e",
"=",
"earth",
".",
"at",
"(",
"t",
")",
"_",
",",
"mlon",
",",
"_",
"=",
"e",
".",
"observe",
"(",
"moon",
")",
".",
"apparent",
"(",
")",
".",
"ecliptic_latlon",
"(",
"'date'",
")",
"_",
",",
"slon",
",",
"_",
"=",
"e",
".",
"observe",
"(",
"sun",
")",
".",
"apparent",
"(",
")",
".",
"ecliptic_latlon",
"(",
"'date'",
")",
"return",
"(",
"(",
"mlon",
".",
"radians",
"-",
"slon",
".",
"radians",
")",
"//",
"(",
"tau",
"/",
"4",
")",
"%",
"4",
")",
".",
"astype",
"(",
"int",
")",
"moon_phase_at",
".",
"rough_period",
"=",
"7.0",
"# one lunar phase per week",
"return",
"moon_phase_at"
] | 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
you want to give string names to each phase. | [
"Build",
"a",
"function",
"of",
"time",
"that",
"returns",
"the",
"moon",
"phase",
"0",
"through",
"3",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L209-L231 |
230,005 | skyfielders/python-skyfield | skyfield/projections.py | _derive_stereographic | 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)
around_x = acos(-z_c)
# Apply rotations to produce an "o" = output vector.
v = Matrix([x, y, z])
xo, yo, zo = rot_axis1(around_x) * rot_axis3(-around_z) * v
# Which we then use the stereographic projection to produce the
# final "p" = plotting coordinates.
xp = xo / (1 - zo)
yp = yo / (1 - zo)
return xp, yp | python | 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)
around_x = acos(-z_c)
# Apply rotations to produce an "o" = output vector.
v = Matrix([x, y, z])
xo, yo, zo = rot_axis1(around_x) * rot_axis3(-around_z) * v
# Which we then use the stereographic projection to produce the
# final "p" = plotting coordinates.
xp = xo / (1 - zo)
yp = yo / (1 - zo)
return xp, yp | [
"def",
"_derive_stereographic",
"(",
")",
":",
"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",
")",
"around_x",
"=",
"acos",
"(",
"-",
"z_c",
")",
"# Apply rotations to produce an \"o\" = output vector.",
"v",
"=",
"Matrix",
"(",
"[",
"x",
",",
"y",
",",
"z",
"]",
")",
"xo",
",",
"yo",
",",
"zo",
"=",
"rot_axis1",
"(",
"around_x",
")",
"*",
"rot_axis3",
"(",
"-",
"around_z",
")",
"*",
"v",
"# Which we then use the stereographic projection to produce the",
"# final \"p\" = plotting coordinates.",
"xp",
"=",
"xo",
"/",
"(",
"1",
"-",
"zo",
")",
"yp",
"=",
"yo",
"/",
"(",
"1",
"-",
"zo",
")",
"return",
"xp",
",",
"yp"
] | Compute the formulae to cut-and-paste into the routine below. | [
"Compute",
"the",
"formulae",
"to",
"cut",
"-",
"and",
"-",
"paste",
"into",
"the",
"routine",
"below",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/projections.py#L5-L23 |
230,006 | reiinakano/scikit-plot | scikitplot/classifiers.py | classifier_factory | 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: If **clf** does not contain the instance methods
necessary for scikit-plot instance methods.
"""
required_methods = ['fit', 'score', 'predict']
for method in required_methods:
if not hasattr(clf, method):
raise TypeError('"{}" is not in clf. Did you pass a '
'classifier instance?'.format(method))
optional_methods = ['predict_proba']
for method in optional_methods:
if not hasattr(clf, method):
warnings.warn('{} not in clf. Some plots may '
'not be possible to generate.'.format(method))
additional_methods = {
'plot_learning_curve': plot_learning_curve,
'plot_confusion_matrix': plot_confusion_matrix_with_cv,
'plot_roc_curve': plot_roc_curve_with_cv,
'plot_ks_statistic': plot_ks_statistic_with_cv,
'plot_precision_recall_curve': plot_precision_recall_curve_with_cv,
'plot_feature_importances': plot_feature_importances
}
for key, fn in six.iteritems(additional_methods):
if hasattr(clf, key):
warnings.warn('"{}" method already in clf. '
'Overriding anyway. This may '
'result in unintended behavior.'.format(key))
setattr(clf, key, types.MethodType(fn, clf))
return clf | python | 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: If **clf** does not contain the instance methods
necessary for scikit-plot instance methods.
"""
required_methods = ['fit', 'score', 'predict']
for method in required_methods:
if not hasattr(clf, method):
raise TypeError('"{}" is not in clf. Did you pass a '
'classifier instance?'.format(method))
optional_methods = ['predict_proba']
for method in optional_methods:
if not hasattr(clf, method):
warnings.warn('{} not in clf. Some plots may '
'not be possible to generate.'.format(method))
additional_methods = {
'plot_learning_curve': plot_learning_curve,
'plot_confusion_matrix': plot_confusion_matrix_with_cv,
'plot_roc_curve': plot_roc_curve_with_cv,
'plot_ks_statistic': plot_ks_statistic_with_cv,
'plot_precision_recall_curve': plot_precision_recall_curve_with_cv,
'plot_feature_importances': plot_feature_importances
}
for key, fn in six.iteritems(additional_methods):
if hasattr(clf, key):
warnings.warn('"{}" method already in clf. '
'Overriding anyway. This may '
'result in unintended behavior.'.format(key))
setattr(clf, key, types.MethodType(fn, clf))
return clf | [
"def",
"classifier_factory",
"(",
"clf",
")",
":",
"required_methods",
"=",
"[",
"'fit'",
",",
"'score'",
",",
"'predict'",
"]",
"for",
"method",
"in",
"required_methods",
":",
"if",
"not",
"hasattr",
"(",
"clf",
",",
"method",
")",
":",
"raise",
"TypeError",
"(",
"'\"{}\" is not in clf. Did you pass a '",
"'classifier instance?'",
".",
"format",
"(",
"method",
")",
")",
"optional_methods",
"=",
"[",
"'predict_proba'",
"]",
"for",
"method",
"in",
"optional_methods",
":",
"if",
"not",
"hasattr",
"(",
"clf",
",",
"method",
")",
":",
"warnings",
".",
"warn",
"(",
"'{} not in clf. Some plots may '",
"'not be possible to generate.'",
".",
"format",
"(",
"method",
")",
")",
"additional_methods",
"=",
"{",
"'plot_learning_curve'",
":",
"plot_learning_curve",
",",
"'plot_confusion_matrix'",
":",
"plot_confusion_matrix_with_cv",
",",
"'plot_roc_curve'",
":",
"plot_roc_curve_with_cv",
",",
"'plot_ks_statistic'",
":",
"plot_ks_statistic_with_cv",
",",
"'plot_precision_recall_curve'",
":",
"plot_precision_recall_curve_with_cv",
",",
"'plot_feature_importances'",
":",
"plot_feature_importances",
"}",
"for",
"key",
",",
"fn",
"in",
"six",
".",
"iteritems",
"(",
"additional_methods",
")",
":",
"if",
"hasattr",
"(",
"clf",
",",
"key",
")",
":",
"warnings",
".",
"warn",
"(",
"'\"{}\" method already in clf. '",
"'Overriding anyway. This may '",
"'result in unintended behavior.'",
".",
"format",
"(",
"key",
")",
")",
"setattr",
"(",
"clf",
",",
"key",
",",
"types",
".",
"MethodType",
"(",
"fn",
",",
"clf",
")",
")",
"return",
"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: If **clf** does not contain the instance methods
necessary for scikit-plot instance methods. | [
"Embeds",
"scikit",
"-",
"plot",
"instance",
"methods",
"in",
"an",
"sklearn",
"classifier",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/classifiers.py#L24-L67 |
230,007 | reiinakano/scikit-plot | scikitplot/classifiers.py | plot_confusion_matrix_with_cv | 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,
shuffle=True, random_state=None, ax=None,
figsize=None, cmap='Blues',
title_fontsize="large",
text_fontsize="medium"):
"""Generates the confusion matrix for a given classifier and dataset.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset of
labels. If none is given, those that appear at least once in ``y``
are used in sorted order.
(new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> rf = classifier_factory(RandomForestClassifier())
>>> rf.plot_confusion_matrix(X, y, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix
"""
y = np.array(y)
if not do_cv:
y_pred = clf.predict(X)
y_true = y
else:
if cv is None:
cv = StratifiedKFold(shuffle=shuffle, random_state=random_state)
elif isinstance(cv, int):
cv = StratifiedKFold(n_splits=cv, shuffle=shuffle,
random_state=random_state)
else:
pass
clf_clone = clone(clf)
preds_list = []
trues_list = []
for train_index, test_index in cv.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf_clone.fit(X_train, y_train)
preds = clf_clone.predict(X_test)
preds_list.append(preds)
trues_list.append(y_test)
y_pred = np.concatenate(preds_list)
y_true = np.concatenate(trues_list)
ax = plotters.plot_confusion_matrix(y_true=y_true, y_pred=y_pred,
labels=labels, true_labels=true_labels,
pred_labels=pred_labels,
title=title, normalize=normalize,
hide_zeros=hide_zeros,
x_tick_rotation=x_tick_rotation, ax=ax,
figsize=figsize, cmap=cmap,
title_fontsize=title_fontsize,
text_fontsize=text_fontsize)
return ax | python | 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,
shuffle=True, random_state=None, ax=None,
figsize=None, cmap='Blues',
title_fontsize="large",
text_fontsize="medium"):
"""Generates the confusion matrix for a given classifier and dataset.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset of
labels. If none is given, those that appear at least once in ``y``
are used in sorted order.
(new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> rf = classifier_factory(RandomForestClassifier())
>>> rf.plot_confusion_matrix(X, y, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix
"""
y = np.array(y)
if not do_cv:
y_pred = clf.predict(X)
y_true = y
else:
if cv is None:
cv = StratifiedKFold(shuffle=shuffle, random_state=random_state)
elif isinstance(cv, int):
cv = StratifiedKFold(n_splits=cv, shuffle=shuffle,
random_state=random_state)
else:
pass
clf_clone = clone(clf)
preds_list = []
trues_list = []
for train_index, test_index in cv.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf_clone.fit(X_train, y_train)
preds = clf_clone.predict(X_test)
preds_list.append(preds)
trues_list.append(y_test)
y_pred = np.concatenate(preds_list)
y_true = np.concatenate(trues_list)
ax = plotters.plot_confusion_matrix(y_true=y_true, y_pred=y_pred,
labels=labels, true_labels=true_labels,
pred_labels=pred_labels,
title=title, normalize=normalize,
hide_zeros=hide_zeros,
x_tick_rotation=x_tick_rotation, ax=ax,
figsize=figsize, cmap=cmap,
title_fontsize=title_fontsize,
text_fontsize=text_fontsize)
return ax | [
"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",
",",
"shuffle",
"=",
"True",
",",
"random_state",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"cmap",
"=",
"'Blues'",
",",
"title_fontsize",
"=",
"\"large\"",
",",
"text_fontsize",
"=",
"\"medium\"",
")",
":",
"y",
"=",
"np",
".",
"array",
"(",
"y",
")",
"if",
"not",
"do_cv",
":",
"y_pred",
"=",
"clf",
".",
"predict",
"(",
"X",
")",
"y_true",
"=",
"y",
"else",
":",
"if",
"cv",
"is",
"None",
":",
"cv",
"=",
"StratifiedKFold",
"(",
"shuffle",
"=",
"shuffle",
",",
"random_state",
"=",
"random_state",
")",
"elif",
"isinstance",
"(",
"cv",
",",
"int",
")",
":",
"cv",
"=",
"StratifiedKFold",
"(",
"n_splits",
"=",
"cv",
",",
"shuffle",
"=",
"shuffle",
",",
"random_state",
"=",
"random_state",
")",
"else",
":",
"pass",
"clf_clone",
"=",
"clone",
"(",
"clf",
")",
"preds_list",
"=",
"[",
"]",
"trues_list",
"=",
"[",
"]",
"for",
"train_index",
",",
"test_index",
"in",
"cv",
".",
"split",
"(",
"X",
",",
"y",
")",
":",
"X_train",
",",
"X_test",
"=",
"X",
"[",
"train_index",
"]",
",",
"X",
"[",
"test_index",
"]",
"y_train",
",",
"y_test",
"=",
"y",
"[",
"train_index",
"]",
",",
"y",
"[",
"test_index",
"]",
"clf_clone",
".",
"fit",
"(",
"X_train",
",",
"y_train",
")",
"preds",
"=",
"clf_clone",
".",
"predict",
"(",
"X_test",
")",
"preds_list",
".",
"append",
"(",
"preds",
")",
"trues_list",
".",
"append",
"(",
"y_test",
")",
"y_pred",
"=",
"np",
".",
"concatenate",
"(",
"preds_list",
")",
"y_true",
"=",
"np",
".",
"concatenate",
"(",
"trues_list",
")",
"ax",
"=",
"plotters",
".",
"plot_confusion_matrix",
"(",
"y_true",
"=",
"y_true",
",",
"y_pred",
"=",
"y_pred",
",",
"labels",
"=",
"labels",
",",
"true_labels",
"=",
"true_labels",
",",
"pred_labels",
"=",
"pred_labels",
",",
"title",
"=",
"title",
",",
"normalize",
"=",
"normalize",
",",
"hide_zeros",
"=",
"hide_zeros",
",",
"x_tick_rotation",
"=",
"x_tick_rotation",
",",
"ax",
"=",
"ax",
",",
"figsize",
"=",
"figsize",
",",
"cmap",
"=",
"cmap",
",",
"title_fontsize",
"=",
"title_fontsize",
",",
"text_fontsize",
"=",
"text_fontsize",
")",
"return",
"ax"
] | Generates the confusion matrix for a given classifier and dataset.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset of
labels. If none is given, those that appear at least once in ``y``
are used in sorted order.
(new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> rf = classifier_factory(RandomForestClassifier())
>>> rf.plot_confusion_matrix(X, y, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix | [
"Generates",
"the",
"confusion",
"matrix",
"for",
"a",
"given",
"classifier",
"and",
"dataset",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/classifiers.py#L70-L219 |
230,008 | reiinakano/scikit-plot | scikitplot/classifiers.py | plot_ks_statistic_with_cv | 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 plot for a given classifier and dataset.
Args:
clf: Classifier instance that implements "fit" and "predict_proba"
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
title (string, optional): Title of the generated plot. Defaults to
"KS Statistic Plot".
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> lr = classifier_factory(LogisticRegression())
>>> lr.plot_ks_statistic(X, y, random_state=1)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_ks_statistic.png
:align: center
:alt: KS Statistic
"""
y = np.array(y)
if not hasattr(clf, 'predict_proba'):
raise TypeError('"predict_proba" method not in classifier. '
'Cannot calculate ROC Curve.')
if not do_cv:
probas = clf.predict_proba(X)
y_true = y
else:
if cv is None:
cv = StratifiedKFold(shuffle=shuffle, random_state=random_state)
elif isinstance(cv, int):
cv = StratifiedKFold(n_splits=cv, shuffle=shuffle,
random_state=random_state)
else:
pass
clf_clone = clone(clf)
preds_list = []
trues_list = []
for train_index, test_index in cv.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf_clone.fit(X_train, y_train)
preds = clf_clone.predict_proba(X_test)
preds_list.append(preds)
trues_list.append(y_test)
probas = np.concatenate(preds_list, axis=0)
y_true = np.concatenate(trues_list)
ax = plotters.plot_ks_statistic(y_true, probas, title=title,
ax=ax, figsize=figsize,
title_fontsize=title_fontsize,
text_fontsize=text_fontsize)
return ax | python | 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 plot for a given classifier and dataset.
Args:
clf: Classifier instance that implements "fit" and "predict_proba"
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
title (string, optional): Title of the generated plot. Defaults to
"KS Statistic Plot".
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> lr = classifier_factory(LogisticRegression())
>>> lr.plot_ks_statistic(X, y, random_state=1)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_ks_statistic.png
:align: center
:alt: KS Statistic
"""
y = np.array(y)
if not hasattr(clf, 'predict_proba'):
raise TypeError('"predict_proba" method not in classifier. '
'Cannot calculate ROC Curve.')
if not do_cv:
probas = clf.predict_proba(X)
y_true = y
else:
if cv is None:
cv = StratifiedKFold(shuffle=shuffle, random_state=random_state)
elif isinstance(cv, int):
cv = StratifiedKFold(n_splits=cv, shuffle=shuffle,
random_state=random_state)
else:
pass
clf_clone = clone(clf)
preds_list = []
trues_list = []
for train_index, test_index in cv.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf_clone.fit(X_train, y_train)
preds = clf_clone.predict_proba(X_test)
preds_list.append(preds)
trues_list.append(y_test)
probas = np.concatenate(preds_list, axis=0)
y_true = np.concatenate(trues_list)
ax = plotters.plot_ks_statistic(y_true, probas, title=title,
ax=ax, figsize=figsize,
title_fontsize=title_fontsize,
text_fontsize=text_fontsize)
return ax | [
"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\"",
")",
":",
"y",
"=",
"np",
".",
"array",
"(",
"y",
")",
"if",
"not",
"hasattr",
"(",
"clf",
",",
"'predict_proba'",
")",
":",
"raise",
"TypeError",
"(",
"'\"predict_proba\" method not in classifier. '",
"'Cannot calculate ROC Curve.'",
")",
"if",
"not",
"do_cv",
":",
"probas",
"=",
"clf",
".",
"predict_proba",
"(",
"X",
")",
"y_true",
"=",
"y",
"else",
":",
"if",
"cv",
"is",
"None",
":",
"cv",
"=",
"StratifiedKFold",
"(",
"shuffle",
"=",
"shuffle",
",",
"random_state",
"=",
"random_state",
")",
"elif",
"isinstance",
"(",
"cv",
",",
"int",
")",
":",
"cv",
"=",
"StratifiedKFold",
"(",
"n_splits",
"=",
"cv",
",",
"shuffle",
"=",
"shuffle",
",",
"random_state",
"=",
"random_state",
")",
"else",
":",
"pass",
"clf_clone",
"=",
"clone",
"(",
"clf",
")",
"preds_list",
"=",
"[",
"]",
"trues_list",
"=",
"[",
"]",
"for",
"train_index",
",",
"test_index",
"in",
"cv",
".",
"split",
"(",
"X",
",",
"y",
")",
":",
"X_train",
",",
"X_test",
"=",
"X",
"[",
"train_index",
"]",
",",
"X",
"[",
"test_index",
"]",
"y_train",
",",
"y_test",
"=",
"y",
"[",
"train_index",
"]",
",",
"y",
"[",
"test_index",
"]",
"clf_clone",
".",
"fit",
"(",
"X_train",
",",
"y_train",
")",
"preds",
"=",
"clf_clone",
".",
"predict_proba",
"(",
"X_test",
")",
"preds_list",
".",
"append",
"(",
"preds",
")",
"trues_list",
".",
"append",
"(",
"y_test",
")",
"probas",
"=",
"np",
".",
"concatenate",
"(",
"preds_list",
",",
"axis",
"=",
"0",
")",
"y_true",
"=",
"np",
".",
"concatenate",
"(",
"trues_list",
")",
"ax",
"=",
"plotters",
".",
"plot_ks_statistic",
"(",
"y_true",
",",
"probas",
",",
"title",
"=",
"title",
",",
"ax",
"=",
"ax",
",",
"figsize",
"=",
"figsize",
",",
"title_fontsize",
"=",
"title_fontsize",
",",
"text_fontsize",
"=",
"text_fontsize",
")",
"return",
"ax"
] | Generates the KS Statistic plot for a given classifier and dataset.
Args:
clf: Classifier instance that implements "fit" and "predict_proba"
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
title (string, optional): Title of the generated plot. Defaults to
"KS Statistic Plot".
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> lr = classifier_factory(LogisticRegression())
>>> lr.plot_ks_statistic(X, y, random_state=1)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_ks_statistic.png
:align: center
:alt: KS Statistic | [
"Generates",
"the",
"KS",
"Statistic",
"plot",
"for",
"a",
"given",
"classifier",
"and",
"dataset",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/classifiers.py#L352-L467 |
230,009 | reiinakano/scikit-plot | scikitplot/plotters.py | plot_confusion_matrix | 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",
text_fontsize="medium"):
"""Generates confusion matrix plot from predictions and true labels
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_pred (array-like, shape (n_samples)):
Estimated targets as returned by a classifier.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset
of labels. If none is given, those that appear at least once in
``y_true`` or ``y_pred`` are used in sorted order. (new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if `normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf = rf.fit(X_train, y_train)
>>> y_pred = rf.predict(X_test)
>>> skplt.plot_confusion_matrix(y_test, y_pred, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix
"""
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
cm = confusion_matrix(y_true, y_pred, labels=labels)
if labels is None:
classes = unique_labels(y_true, y_pred)
else:
classes = np.asarray(labels)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
cm = np.around(cm, decimals=2)
cm[np.isnan(cm)] = 0.0
if true_labels is None:
true_classes = classes
else:
validate_labels(classes, true_labels, "true_labels")
true_label_indexes = np.in1d(classes, true_labels)
true_classes = classes[true_label_indexes]
cm = cm[true_label_indexes]
if pred_labels is None:
pred_classes = classes
else:
validate_labels(classes, pred_labels, "pred_labels")
pred_label_indexes = np.in1d(classes, pred_labels)
pred_classes = classes[pred_label_indexes]
cm = cm[:, pred_label_indexes]
if title:
ax.set_title(title, fontsize=title_fontsize)
elif normalize:
ax.set_title('Normalized Confusion Matrix', fontsize=title_fontsize)
else:
ax.set_title('Confusion Matrix', fontsize=title_fontsize)
image = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.get_cmap(cmap))
plt.colorbar(mappable=image)
x_tick_marks = np.arange(len(pred_classes))
y_tick_marks = np.arange(len(true_classes))
ax.set_xticks(x_tick_marks)
ax.set_xticklabels(pred_classes, fontsize=text_fontsize,
rotation=x_tick_rotation)
ax.set_yticks(y_tick_marks)
ax.set_yticklabels(true_classes, fontsize=text_fontsize)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
if not (hide_zeros and cm[i, j] == 0):
ax.text(j, i, cm[i, j],
horizontalalignment="center",
verticalalignment="center",
fontsize=text_fontsize,
color="white" if cm[i, j] > thresh else "black")
ax.set_ylabel('True label', fontsize=text_fontsize)
ax.set_xlabel('Predicted label', fontsize=text_fontsize)
ax.grid('off')
return ax | python | 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",
text_fontsize="medium"):
"""Generates confusion matrix plot from predictions and true labels
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_pred (array-like, shape (n_samples)):
Estimated targets as returned by a classifier.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset
of labels. If none is given, those that appear at least once in
``y_true`` or ``y_pred`` are used in sorted order. (new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if `normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf = rf.fit(X_train, y_train)
>>> y_pred = rf.predict(X_test)
>>> skplt.plot_confusion_matrix(y_test, y_pred, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix
"""
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
cm = confusion_matrix(y_true, y_pred, labels=labels)
if labels is None:
classes = unique_labels(y_true, y_pred)
else:
classes = np.asarray(labels)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
cm = np.around(cm, decimals=2)
cm[np.isnan(cm)] = 0.0
if true_labels is None:
true_classes = classes
else:
validate_labels(classes, true_labels, "true_labels")
true_label_indexes = np.in1d(classes, true_labels)
true_classes = classes[true_label_indexes]
cm = cm[true_label_indexes]
if pred_labels is None:
pred_classes = classes
else:
validate_labels(classes, pred_labels, "pred_labels")
pred_label_indexes = np.in1d(classes, pred_labels)
pred_classes = classes[pred_label_indexes]
cm = cm[:, pred_label_indexes]
if title:
ax.set_title(title, fontsize=title_fontsize)
elif normalize:
ax.set_title('Normalized Confusion Matrix', fontsize=title_fontsize)
else:
ax.set_title('Confusion Matrix', fontsize=title_fontsize)
image = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.get_cmap(cmap))
plt.colorbar(mappable=image)
x_tick_marks = np.arange(len(pred_classes))
y_tick_marks = np.arange(len(true_classes))
ax.set_xticks(x_tick_marks)
ax.set_xticklabels(pred_classes, fontsize=text_fontsize,
rotation=x_tick_rotation)
ax.set_yticks(y_tick_marks)
ax.set_yticklabels(true_classes, fontsize=text_fontsize)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
if not (hide_zeros and cm[i, j] == 0):
ax.text(j, i, cm[i, j],
horizontalalignment="center",
verticalalignment="center",
fontsize=text_fontsize,
color="white" if cm[i, j] > thresh else "black")
ax.set_ylabel('True label', fontsize=text_fontsize)
ax.set_xlabel('Predicted label', fontsize=text_fontsize)
ax.grid('off')
return ax | [
"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\"",
",",
"text_fontsize",
"=",
"\"medium\"",
")",
":",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
",",
"figsize",
"=",
"figsize",
")",
"cm",
"=",
"confusion_matrix",
"(",
"y_true",
",",
"y_pred",
",",
"labels",
"=",
"labels",
")",
"if",
"labels",
"is",
"None",
":",
"classes",
"=",
"unique_labels",
"(",
"y_true",
",",
"y_pred",
")",
"else",
":",
"classes",
"=",
"np",
".",
"asarray",
"(",
"labels",
")",
"if",
"normalize",
":",
"cm",
"=",
"cm",
".",
"astype",
"(",
"'float'",
")",
"/",
"cm",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"cm",
"=",
"np",
".",
"around",
"(",
"cm",
",",
"decimals",
"=",
"2",
")",
"cm",
"[",
"np",
".",
"isnan",
"(",
"cm",
")",
"]",
"=",
"0.0",
"if",
"true_labels",
"is",
"None",
":",
"true_classes",
"=",
"classes",
"else",
":",
"validate_labels",
"(",
"classes",
",",
"true_labels",
",",
"\"true_labels\"",
")",
"true_label_indexes",
"=",
"np",
".",
"in1d",
"(",
"classes",
",",
"true_labels",
")",
"true_classes",
"=",
"classes",
"[",
"true_label_indexes",
"]",
"cm",
"=",
"cm",
"[",
"true_label_indexes",
"]",
"if",
"pred_labels",
"is",
"None",
":",
"pred_classes",
"=",
"classes",
"else",
":",
"validate_labels",
"(",
"classes",
",",
"pred_labels",
",",
"\"pred_labels\"",
")",
"pred_label_indexes",
"=",
"np",
".",
"in1d",
"(",
"classes",
",",
"pred_labels",
")",
"pred_classes",
"=",
"classes",
"[",
"pred_label_indexes",
"]",
"cm",
"=",
"cm",
"[",
":",
",",
"pred_label_indexes",
"]",
"if",
"title",
":",
"ax",
".",
"set_title",
"(",
"title",
",",
"fontsize",
"=",
"title_fontsize",
")",
"elif",
"normalize",
":",
"ax",
".",
"set_title",
"(",
"'Normalized Confusion Matrix'",
",",
"fontsize",
"=",
"title_fontsize",
")",
"else",
":",
"ax",
".",
"set_title",
"(",
"'Confusion Matrix'",
",",
"fontsize",
"=",
"title_fontsize",
")",
"image",
"=",
"ax",
".",
"imshow",
"(",
"cm",
",",
"interpolation",
"=",
"'nearest'",
",",
"cmap",
"=",
"plt",
".",
"cm",
".",
"get_cmap",
"(",
"cmap",
")",
")",
"plt",
".",
"colorbar",
"(",
"mappable",
"=",
"image",
")",
"x_tick_marks",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"pred_classes",
")",
")",
"y_tick_marks",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"true_classes",
")",
")",
"ax",
".",
"set_xticks",
"(",
"x_tick_marks",
")",
"ax",
".",
"set_xticklabels",
"(",
"pred_classes",
",",
"fontsize",
"=",
"text_fontsize",
",",
"rotation",
"=",
"x_tick_rotation",
")",
"ax",
".",
"set_yticks",
"(",
"y_tick_marks",
")",
"ax",
".",
"set_yticklabels",
"(",
"true_classes",
",",
"fontsize",
"=",
"text_fontsize",
")",
"thresh",
"=",
"cm",
".",
"max",
"(",
")",
"/",
"2.",
"for",
"i",
",",
"j",
"in",
"itertools",
".",
"product",
"(",
"range",
"(",
"cm",
".",
"shape",
"[",
"0",
"]",
")",
",",
"range",
"(",
"cm",
".",
"shape",
"[",
"1",
"]",
")",
")",
":",
"if",
"not",
"(",
"hide_zeros",
"and",
"cm",
"[",
"i",
",",
"j",
"]",
"==",
"0",
")",
":",
"ax",
".",
"text",
"(",
"j",
",",
"i",
",",
"cm",
"[",
"i",
",",
"j",
"]",
",",
"horizontalalignment",
"=",
"\"center\"",
",",
"verticalalignment",
"=",
"\"center\"",
",",
"fontsize",
"=",
"text_fontsize",
",",
"color",
"=",
"\"white\"",
"if",
"cm",
"[",
"i",
",",
"j",
"]",
">",
"thresh",
"else",
"\"black\"",
")",
"ax",
".",
"set_ylabel",
"(",
"'True label'",
",",
"fontsize",
"=",
"text_fontsize",
")",
"ax",
".",
"set_xlabel",
"(",
"'Predicted label'",
",",
"fontsize",
"=",
"text_fontsize",
")",
"ax",
".",
"grid",
"(",
"'off'",
")",
"return",
"ax"
] | Generates confusion matrix plot from predictions and true labels
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_pred (array-like, shape (n_samples)):
Estimated targets as returned by a classifier.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset
of labels. If none is given, those that appear at least once in
``y_true`` or ``y_pred`` are used in sorted order. (new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if `normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf = rf.fit(X_train, y_train)
>>> y_pred = rf.predict(X_test)
>>> skplt.plot_confusion_matrix(y_test, y_pred, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix | [
"Generates",
"confusion",
"matrix",
"plot",
"from",
"predictions",
"and",
"true",
"labels"
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/plotters.py#L42-L181 |
230,010 | reiinakano/scikit-plot | scikitplot/plotters.py | plot_feature_importances | 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="medium"):
"""Generates a plot of a classifier's feature importances.
Args:
clf: Classifier instance that implements ``fit`` and ``predict_proba``
methods. The classifier must also have a ``feature_importances_``
attribute.
title (string, optional): Title of the generated plot. Defaults to
"Feature importances".
feature_names (None, :obj:`list` of string, optional): Determines the
feature names used to plot the feature importances. If None,
feature names will be numbered.
max_num_features (int): Determines the maximum number of features to
plot. Defaults to 20.
order ('ascending', 'descending', or None, optional): Determines the
order in which the feature importances are plotted. Defaults to
'descending'.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf.fit(X, y)
>>> skplt.plot_feature_importances(
... rf, feature_names=['petal length', 'petal width',
... 'sepal length', 'sepal width'])
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_feature_importances.png
:align: center
:alt: Feature Importances
"""
if not hasattr(clf, 'feature_importances_'):
raise TypeError('"feature_importances_" attribute not in classifier. '
'Cannot plot feature importances.')
importances = clf.feature_importances_
if hasattr(clf, 'estimators_')\
and isinstance(clf.estimators_, list)\
and hasattr(clf.estimators_[0], 'feature_importances_'):
std = np.std([tree.feature_importances_ for tree in clf.estimators_],
axis=0)
else:
std = None
if order == 'descending':
indices = np.argsort(importances)[::-1]
elif order == 'ascending':
indices = np.argsort(importances)
elif order is None:
indices = np.array(range(len(importances)))
else:
raise ValueError('Invalid argument {} for "order"'.format(order))
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
if feature_names is None:
feature_names = indices
else:
feature_names = np.array(feature_names)[indices]
max_num_features = min(max_num_features, len(importances))
ax.set_title(title, fontsize=title_fontsize)
if std is not None:
ax.bar(range(max_num_features),
importances[indices][:max_num_features], color='r',
yerr=std[indices][:max_num_features], align='center')
else:
ax.bar(range(max_num_features),
importances[indices][:max_num_features],
color='r', align='center')
ax.set_xticks(range(max_num_features))
ax.set_xticklabels(feature_names[:max_num_features],
rotation=x_tick_rotation)
ax.set_xlim([-1, max_num_features])
ax.tick_params(labelsize=text_fontsize)
return ax | python | 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="medium"):
"""Generates a plot of a classifier's feature importances.
Args:
clf: Classifier instance that implements ``fit`` and ``predict_proba``
methods. The classifier must also have a ``feature_importances_``
attribute.
title (string, optional): Title of the generated plot. Defaults to
"Feature importances".
feature_names (None, :obj:`list` of string, optional): Determines the
feature names used to plot the feature importances. If None,
feature names will be numbered.
max_num_features (int): Determines the maximum number of features to
plot. Defaults to 20.
order ('ascending', 'descending', or None, optional): Determines the
order in which the feature importances are plotted. Defaults to
'descending'.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf.fit(X, y)
>>> skplt.plot_feature_importances(
... rf, feature_names=['petal length', 'petal width',
... 'sepal length', 'sepal width'])
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_feature_importances.png
:align: center
:alt: Feature Importances
"""
if not hasattr(clf, 'feature_importances_'):
raise TypeError('"feature_importances_" attribute not in classifier. '
'Cannot plot feature importances.')
importances = clf.feature_importances_
if hasattr(clf, 'estimators_')\
and isinstance(clf.estimators_, list)\
and hasattr(clf.estimators_[0], 'feature_importances_'):
std = np.std([tree.feature_importances_ for tree in clf.estimators_],
axis=0)
else:
std = None
if order == 'descending':
indices = np.argsort(importances)[::-1]
elif order == 'ascending':
indices = np.argsort(importances)
elif order is None:
indices = np.array(range(len(importances)))
else:
raise ValueError('Invalid argument {} for "order"'.format(order))
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
if feature_names is None:
feature_names = indices
else:
feature_names = np.array(feature_names)[indices]
max_num_features = min(max_num_features, len(importances))
ax.set_title(title, fontsize=title_fontsize)
if std is not None:
ax.bar(range(max_num_features),
importances[indices][:max_num_features], color='r',
yerr=std[indices][:max_num_features], align='center')
else:
ax.bar(range(max_num_features),
importances[indices][:max_num_features],
color='r', align='center')
ax.set_xticks(range(max_num_features))
ax.set_xticklabels(feature_names[:max_num_features],
rotation=x_tick_rotation)
ax.set_xlim([-1, max_num_features])
ax.tick_params(labelsize=text_fontsize)
return ax | [
"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",
"=",
"\"medium\"",
")",
":",
"if",
"not",
"hasattr",
"(",
"clf",
",",
"'feature_importances_'",
")",
":",
"raise",
"TypeError",
"(",
"'\"feature_importances_\" attribute not in classifier. '",
"'Cannot plot feature importances.'",
")",
"importances",
"=",
"clf",
".",
"feature_importances_",
"if",
"hasattr",
"(",
"clf",
",",
"'estimators_'",
")",
"and",
"isinstance",
"(",
"clf",
".",
"estimators_",
",",
"list",
")",
"and",
"hasattr",
"(",
"clf",
".",
"estimators_",
"[",
"0",
"]",
",",
"'feature_importances_'",
")",
":",
"std",
"=",
"np",
".",
"std",
"(",
"[",
"tree",
".",
"feature_importances_",
"for",
"tree",
"in",
"clf",
".",
"estimators_",
"]",
",",
"axis",
"=",
"0",
")",
"else",
":",
"std",
"=",
"None",
"if",
"order",
"==",
"'descending'",
":",
"indices",
"=",
"np",
".",
"argsort",
"(",
"importances",
")",
"[",
":",
":",
"-",
"1",
"]",
"elif",
"order",
"==",
"'ascending'",
":",
"indices",
"=",
"np",
".",
"argsort",
"(",
"importances",
")",
"elif",
"order",
"is",
"None",
":",
"indices",
"=",
"np",
".",
"array",
"(",
"range",
"(",
"len",
"(",
"importances",
")",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid argument {} for \"order\"'",
".",
"format",
"(",
"order",
")",
")",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
",",
"figsize",
"=",
"figsize",
")",
"if",
"feature_names",
"is",
"None",
":",
"feature_names",
"=",
"indices",
"else",
":",
"feature_names",
"=",
"np",
".",
"array",
"(",
"feature_names",
")",
"[",
"indices",
"]",
"max_num_features",
"=",
"min",
"(",
"max_num_features",
",",
"len",
"(",
"importances",
")",
")",
"ax",
".",
"set_title",
"(",
"title",
",",
"fontsize",
"=",
"title_fontsize",
")",
"if",
"std",
"is",
"not",
"None",
":",
"ax",
".",
"bar",
"(",
"range",
"(",
"max_num_features",
")",
",",
"importances",
"[",
"indices",
"]",
"[",
":",
"max_num_features",
"]",
",",
"color",
"=",
"'r'",
",",
"yerr",
"=",
"std",
"[",
"indices",
"]",
"[",
":",
"max_num_features",
"]",
",",
"align",
"=",
"'center'",
")",
"else",
":",
"ax",
".",
"bar",
"(",
"range",
"(",
"max_num_features",
")",
",",
"importances",
"[",
"indices",
"]",
"[",
":",
"max_num_features",
"]",
",",
"color",
"=",
"'r'",
",",
"align",
"=",
"'center'",
")",
"ax",
".",
"set_xticks",
"(",
"range",
"(",
"max_num_features",
")",
")",
"ax",
".",
"set_xticklabels",
"(",
"feature_names",
"[",
":",
"max_num_features",
"]",
",",
"rotation",
"=",
"x_tick_rotation",
")",
"ax",
".",
"set_xlim",
"(",
"[",
"-",
"1",
",",
"max_num_features",
"]",
")",
"ax",
".",
"tick_params",
"(",
"labelsize",
"=",
"text_fontsize",
")",
"return",
"ax"
] | Generates a plot of a classifier's feature importances.
Args:
clf: Classifier instance that implements ``fit`` and ``predict_proba``
methods. The classifier must also have a ``feature_importances_``
attribute.
title (string, optional): Title of the generated plot. Defaults to
"Feature importances".
feature_names (None, :obj:`list` of string, optional): Determines the
feature names used to plot the feature importances. If None,
feature names will be numbered.
max_num_features (int): Determines the maximum number of features to
plot. Defaults to 20.
order ('ascending', 'descending', or None, optional): Determines the
order in which the feature importances are plotted. Defaults to
'descending'.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf.fit(X, y)
>>> skplt.plot_feature_importances(
... rf, feature_names=['petal length', 'petal width',
... 'sepal length', 'sepal width'])
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_feature_importances.png
:align: center
:alt: Feature Importances | [
"Generates",
"a",
"plot",
"of",
"a",
"classifier",
"s",
"feature",
"importances",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/plotters.py#L546-L661 |
230,011 | reiinakano/scikit-plot | scikitplot/plotters.py | plot_silhouette | 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 instance that implements ``fit`` and ``fit_predict``
methods.
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is the number of features.
title (string, optional): Title of the generated plot. Defaults to
"Silhouette Analysis"
metric (string or callable, optional): The metric to use when
calculating distance between instances in a feature array.
If metric is a string, it must be one of the options allowed by
sklearn.metrics.pairwise.pairwise_distances. If X is
the distance array itself, use "precomputed" as the metric.
copy (boolean, optional): Determines whether ``fit`` is used on
**clf** or on a copy of **clf**.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> kmeans = KMeans(n_clusters=4, random_state=1)
>>> skplt.plot_silhouette(kmeans, X)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_silhouette.png
:align: center
:alt: Silhouette Plot
"""
if copy:
clf = clone(clf)
cluster_labels = clf.fit_predict(X)
n_clusters = len(set(cluster_labels))
silhouette_avg = silhouette_score(X, cluster_labels, metric=metric)
sample_silhouette_values = silhouette_samples(X, cluster_labels,
metric=metric)
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlim([-0.1, 1])
ax.set_ylim([0, len(X) + (n_clusters + 1) * 10 + 10])
ax.set_xlabel('Silhouette coefficient values', fontsize=text_fontsize)
ax.set_ylabel('Cluster label', fontsize=text_fontsize)
y_lower = 10
for i in range(n_clusters):
ith_cluster_silhouette_values = sample_silhouette_values[
cluster_labels == i]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i
color = plt.cm.get_cmap(cmap)(float(i) / n_clusters)
ax.fill_betweenx(np.arange(y_lower, y_upper),
0, ith_cluster_silhouette_values,
facecolor=color, edgecolor=color, alpha=0.7)
ax.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i),
fontsize=text_fontsize)
y_lower = y_upper + 10
ax.axvline(x=silhouette_avg, color="red", linestyle="--",
label='Silhouette score: {0:0.3f}'.format(silhouette_avg))
ax.set_yticks([]) # Clear the y-axis labels / ticks
ax.set_xticks(np.arange(-0.1, 1.0, 0.2))
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc='best', fontsize=text_fontsize)
return ax | python | 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 instance that implements ``fit`` and ``fit_predict``
methods.
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is the number of features.
title (string, optional): Title of the generated plot. Defaults to
"Silhouette Analysis"
metric (string or callable, optional): The metric to use when
calculating distance between instances in a feature array.
If metric is a string, it must be one of the options allowed by
sklearn.metrics.pairwise.pairwise_distances. If X is
the distance array itself, use "precomputed" as the metric.
copy (boolean, optional): Determines whether ``fit`` is used on
**clf** or on a copy of **clf**.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> kmeans = KMeans(n_clusters=4, random_state=1)
>>> skplt.plot_silhouette(kmeans, X)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_silhouette.png
:align: center
:alt: Silhouette Plot
"""
if copy:
clf = clone(clf)
cluster_labels = clf.fit_predict(X)
n_clusters = len(set(cluster_labels))
silhouette_avg = silhouette_score(X, cluster_labels, metric=metric)
sample_silhouette_values = silhouette_samples(X, cluster_labels,
metric=metric)
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlim([-0.1, 1])
ax.set_ylim([0, len(X) + (n_clusters + 1) * 10 + 10])
ax.set_xlabel('Silhouette coefficient values', fontsize=text_fontsize)
ax.set_ylabel('Cluster label', fontsize=text_fontsize)
y_lower = 10
for i in range(n_clusters):
ith_cluster_silhouette_values = sample_silhouette_values[
cluster_labels == i]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i
color = plt.cm.get_cmap(cmap)(float(i) / n_clusters)
ax.fill_betweenx(np.arange(y_lower, y_upper),
0, ith_cluster_silhouette_values,
facecolor=color, edgecolor=color, alpha=0.7)
ax.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i),
fontsize=text_fontsize)
y_lower = y_upper + 10
ax.axvline(x=silhouette_avg, color="red", linestyle="--",
label='Silhouette score: {0:0.3f}'.format(silhouette_avg))
ax.set_yticks([]) # Clear the y-axis labels / ticks
ax.set_xticks(np.arange(-0.1, 1.0, 0.2))
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc='best', fontsize=text_fontsize)
return ax | [
"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\"",
")",
":",
"if",
"copy",
":",
"clf",
"=",
"clone",
"(",
"clf",
")",
"cluster_labels",
"=",
"clf",
".",
"fit_predict",
"(",
"X",
")",
"n_clusters",
"=",
"len",
"(",
"set",
"(",
"cluster_labels",
")",
")",
"silhouette_avg",
"=",
"silhouette_score",
"(",
"X",
",",
"cluster_labels",
",",
"metric",
"=",
"metric",
")",
"sample_silhouette_values",
"=",
"silhouette_samples",
"(",
"X",
",",
"cluster_labels",
",",
"metric",
"=",
"metric",
")",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
",",
"figsize",
"=",
"figsize",
")",
"ax",
".",
"set_title",
"(",
"title",
",",
"fontsize",
"=",
"title_fontsize",
")",
"ax",
".",
"set_xlim",
"(",
"[",
"-",
"0.1",
",",
"1",
"]",
")",
"ax",
".",
"set_ylim",
"(",
"[",
"0",
",",
"len",
"(",
"X",
")",
"+",
"(",
"n_clusters",
"+",
"1",
")",
"*",
"10",
"+",
"10",
"]",
")",
"ax",
".",
"set_xlabel",
"(",
"'Silhouette coefficient values'",
",",
"fontsize",
"=",
"text_fontsize",
")",
"ax",
".",
"set_ylabel",
"(",
"'Cluster label'",
",",
"fontsize",
"=",
"text_fontsize",
")",
"y_lower",
"=",
"10",
"for",
"i",
"in",
"range",
"(",
"n_clusters",
")",
":",
"ith_cluster_silhouette_values",
"=",
"sample_silhouette_values",
"[",
"cluster_labels",
"==",
"i",
"]",
"ith_cluster_silhouette_values",
".",
"sort",
"(",
")",
"size_cluster_i",
"=",
"ith_cluster_silhouette_values",
".",
"shape",
"[",
"0",
"]",
"y_upper",
"=",
"y_lower",
"+",
"size_cluster_i",
"color",
"=",
"plt",
".",
"cm",
".",
"get_cmap",
"(",
"cmap",
")",
"(",
"float",
"(",
"i",
")",
"/",
"n_clusters",
")",
"ax",
".",
"fill_betweenx",
"(",
"np",
".",
"arange",
"(",
"y_lower",
",",
"y_upper",
")",
",",
"0",
",",
"ith_cluster_silhouette_values",
",",
"facecolor",
"=",
"color",
",",
"edgecolor",
"=",
"color",
",",
"alpha",
"=",
"0.7",
")",
"ax",
".",
"text",
"(",
"-",
"0.05",
",",
"y_lower",
"+",
"0.5",
"*",
"size_cluster_i",
",",
"str",
"(",
"i",
")",
",",
"fontsize",
"=",
"text_fontsize",
")",
"y_lower",
"=",
"y_upper",
"+",
"10",
"ax",
".",
"axvline",
"(",
"x",
"=",
"silhouette_avg",
",",
"color",
"=",
"\"red\"",
",",
"linestyle",
"=",
"\"--\"",
",",
"label",
"=",
"'Silhouette score: {0:0.3f}'",
".",
"format",
"(",
"silhouette_avg",
")",
")",
"ax",
".",
"set_yticks",
"(",
"[",
"]",
")",
"# Clear the y-axis labels / ticks",
"ax",
".",
"set_xticks",
"(",
"np",
".",
"arange",
"(",
"-",
"0.1",
",",
"1.0",
",",
"0.2",
")",
")",
"ax",
".",
"tick_params",
"(",
"labelsize",
"=",
"text_fontsize",
")",
"ax",
".",
"legend",
"(",
"loc",
"=",
"'best'",
",",
"fontsize",
"=",
"text_fontsize",
")",
"return",
"ax"
] | Plots silhouette analysis of clusters using fit_predict.
Args:
clf: Clusterer instance that implements ``fit`` and ``fit_predict``
methods.
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is the number of features.
title (string, optional): Title of the generated plot. Defaults to
"Silhouette Analysis"
metric (string or callable, optional): The metric to use when
calculating distance between instances in a feature array.
If metric is a string, it must be one of the options allowed by
sklearn.metrics.pairwise.pairwise_distances. If X is
the distance array itself, use "precomputed" as the metric.
copy (boolean, optional): Determines whether ``fit`` is used on
**clf** or on a copy of **clf**.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> kmeans = KMeans(n_clusters=4, random_state=1)
>>> skplt.plot_silhouette(kmeans, X)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_silhouette.png
:align: center
:alt: Silhouette Plot | [
"Plots",
"silhouette",
"analysis",
"of",
"clusters",
"using",
"fit_predict",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/plotters.py#L775-L888 |
230,012 | reiinakano/scikit-plot | scikitplot/cluster.py | _clone_and_score_clusterer | 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
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is the number of features.
n_clusters (int): Number of clusters
Returns:
score: Score of clusters
time: Number of seconds it took to fit cluster
"""
start = time.time()
clf = clone(clf)
setattr(clf, 'n_clusters', n_clusters)
return clf.fit(X).score(X), time.time() - start | python | 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
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is the number of features.
n_clusters (int): Number of clusters
Returns:
score: Score of clusters
time: Number of seconds it took to fit cluster
"""
start = time.time()
clf = clone(clf)
setattr(clf, 'n_clusters', n_clusters)
return clf.fit(X).score(X), time.time() - start | [
"def",
"_clone_and_score_clusterer",
"(",
"clf",
",",
"X",
",",
"n_clusters",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"clf",
"=",
"clone",
"(",
"clf",
")",
"setattr",
"(",
"clf",
",",
"'n_clusters'",
",",
"n_clusters",
")",
"return",
"clf",
".",
"fit",
"(",
"X",
")",
".",
"score",
"(",
"X",
")",
",",
"time",
".",
"time",
"(",
")",
"-",
"start"
] | 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
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is the number of features.
n_clusters (int): Number of clusters
Returns:
score: Score of clusters
time: Number of seconds it took to fit cluster | [
"Clones",
"and",
"scores",
"clusterer",
"instance",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/cluster.py#L110-L132 |
230,013 | reiinakano/scikit-plot | scikitplot/estimators.py | plot_learning_curve | 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"):
"""Generates a plot of the train and test learning curves for a classifier.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification or regression;
None for unsupervised learning.
title (string, optional): Title of the generated plot. Defaults to
"Learning Curve"
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
train_sizes (iterable, optional): Determines the training sizes used to
plot the learning curve. If None, ``np.linspace(.1, 1.0, 5)`` is
used.
n_jobs (int, optional): Number of jobs to run in parallel. Defaults to
1.
scoring (string, callable or None, optional): default: None
A string (see scikit-learn model evaluation documentation) or a
scorerbcallable object / function with signature
scorer(estimator, X, y).
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> skplt.estimators.plot_learning_curve(rf, X, y)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_learning_curve.png
:align: center
:alt: Learning Curve
"""
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
if train_sizes is None:
train_sizes = np.linspace(.1, 1.0, 5)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlabel("Training examples", fontsize=text_fontsize)
ax.set_ylabel("Score", fontsize=text_fontsize)
train_sizes, train_scores, test_scores = learning_curve(
clf, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes,
scoring=scoring, shuffle=shuffle, random_state=random_state)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
ax.grid()
ax.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1, color="r")
ax.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
ax.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
ax.plot(train_sizes, test_scores_mean, 'o-', color="g",
label="Cross-validation score")
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc="best", fontsize=text_fontsize)
return ax | python | 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"):
"""Generates a plot of the train and test learning curves for a classifier.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification or regression;
None for unsupervised learning.
title (string, optional): Title of the generated plot. Defaults to
"Learning Curve"
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
train_sizes (iterable, optional): Determines the training sizes used to
plot the learning curve. If None, ``np.linspace(.1, 1.0, 5)`` is
used.
n_jobs (int, optional): Number of jobs to run in parallel. Defaults to
1.
scoring (string, callable or None, optional): default: None
A string (see scikit-learn model evaluation documentation) or a
scorerbcallable object / function with signature
scorer(estimator, X, y).
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> skplt.estimators.plot_learning_curve(rf, X, y)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_learning_curve.png
:align: center
:alt: Learning Curve
"""
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
if train_sizes is None:
train_sizes = np.linspace(.1, 1.0, 5)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlabel("Training examples", fontsize=text_fontsize)
ax.set_ylabel("Score", fontsize=text_fontsize)
train_sizes, train_scores, test_scores = learning_curve(
clf, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes,
scoring=scoring, shuffle=shuffle, random_state=random_state)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
ax.grid()
ax.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1, color="r")
ax.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
ax.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
ax.plot(train_sizes, test_scores_mean, 'o-', color="g",
label="Cross-validation score")
ax.tick_params(labelsize=text_fontsize)
ax.legend(loc="best", fontsize=text_fontsize)
return ax | [
"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\"",
")",
":",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
",",
"figsize",
"=",
"figsize",
")",
"if",
"train_sizes",
"is",
"None",
":",
"train_sizes",
"=",
"np",
".",
"linspace",
"(",
".1",
",",
"1.0",
",",
"5",
")",
"ax",
".",
"set_title",
"(",
"title",
",",
"fontsize",
"=",
"title_fontsize",
")",
"ax",
".",
"set_xlabel",
"(",
"\"Training examples\"",
",",
"fontsize",
"=",
"text_fontsize",
")",
"ax",
".",
"set_ylabel",
"(",
"\"Score\"",
",",
"fontsize",
"=",
"text_fontsize",
")",
"train_sizes",
",",
"train_scores",
",",
"test_scores",
"=",
"learning_curve",
"(",
"clf",
",",
"X",
",",
"y",
",",
"cv",
"=",
"cv",
",",
"n_jobs",
"=",
"n_jobs",
",",
"train_sizes",
"=",
"train_sizes",
",",
"scoring",
"=",
"scoring",
",",
"shuffle",
"=",
"shuffle",
",",
"random_state",
"=",
"random_state",
")",
"train_scores_mean",
"=",
"np",
".",
"mean",
"(",
"train_scores",
",",
"axis",
"=",
"1",
")",
"train_scores_std",
"=",
"np",
".",
"std",
"(",
"train_scores",
",",
"axis",
"=",
"1",
")",
"test_scores_mean",
"=",
"np",
".",
"mean",
"(",
"test_scores",
",",
"axis",
"=",
"1",
")",
"test_scores_std",
"=",
"np",
".",
"std",
"(",
"test_scores",
",",
"axis",
"=",
"1",
")",
"ax",
".",
"grid",
"(",
")",
"ax",
".",
"fill_between",
"(",
"train_sizes",
",",
"train_scores_mean",
"-",
"train_scores_std",
",",
"train_scores_mean",
"+",
"train_scores_std",
",",
"alpha",
"=",
"0.1",
",",
"color",
"=",
"\"r\"",
")",
"ax",
".",
"fill_between",
"(",
"train_sizes",
",",
"test_scores_mean",
"-",
"test_scores_std",
",",
"test_scores_mean",
"+",
"test_scores_std",
",",
"alpha",
"=",
"0.1",
",",
"color",
"=",
"\"g\"",
")",
"ax",
".",
"plot",
"(",
"train_sizes",
",",
"train_scores_mean",
",",
"'o-'",
",",
"color",
"=",
"\"r\"",
",",
"label",
"=",
"\"Training score\"",
")",
"ax",
".",
"plot",
"(",
"train_sizes",
",",
"test_scores_mean",
",",
"'o-'",
",",
"color",
"=",
"\"g\"",
",",
"label",
"=",
"\"Cross-validation score\"",
")",
"ax",
".",
"tick_params",
"(",
"labelsize",
"=",
"text_fontsize",
")",
"ax",
".",
"legend",
"(",
"loc",
"=",
"\"best\"",
",",
"fontsize",
"=",
"text_fontsize",
")",
"return",
"ax"
] | Generates a plot of the train and test learning curves for a classifier.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification or regression;
None for unsupervised learning.
title (string, optional): Title of the generated plot. Defaults to
"Learning Curve"
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
train_sizes (iterable, optional): Determines the training sizes used to
plot the learning curve. If None, ``np.linspace(.1, 1.0, 5)`` is
used.
n_jobs (int, optional): Number of jobs to run in parallel. Defaults to
1.
scoring (string, callable or None, optional): default: None
A string (see scikit-learn model evaluation documentation) or a
scorerbcallable object / function with signature
scorer(estimator, X, y).
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> skplt.estimators.plot_learning_curve(rf, X, y)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_learning_curve.png
:align: center
:alt: Learning Curve | [
"Generates",
"a",
"plot",
"of",
"the",
"train",
"and",
"test",
"learning",
"curves",
"for",
"a",
"classifier",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/estimators.py#L135-L247 |
230,014 | reiinakano/scikit-plot | scikitplot/metrics.py | plot_calibration_curve | 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 calibration curves for a set of classifier probability estimates.
Plotting the calibration curves of a classifier is useful for determining
whether or not you can interpret their predicted probabilities directly as
as confidence level. For instance, a well-calibrated binary classifier
should classify the samples such that for samples to which it gave a score
of 0.8, around 80% should actually be from the positive class.
This function currently only works for binary classification.
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
probas_list (list of array-like, shape (n_samples, 2) or (n_samples,)):
A list containing the outputs of binary classifiers'
:func:`predict_proba` method or :func:`decision_function` method.
clf_names (list of str, optional): A list of strings, where each string
refers to the name of the classifier that produced the
corresponding probability estimates in `probas_list`. If ``None``,
the names "Classifier 1", "Classifier 2", etc. will be used.
n_bins (int, optional): Number of bins. A bigger number requires more
data.
title (string, optional): Title of the generated plot. Defaults to
"Calibration plots (Reliabilirt Curves)"
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
:class:`matplotlib.axes.Axes`: The axes on which the plot was drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> lr = LogisticRegression()
>>> nb = GaussianNB()
>>> svm = LinearSVC()
>>> rf_probas = rf.fit(X_train, y_train).predict_proba(X_test)
>>> lr_probas = lr.fit(X_train, y_train).predict_proba(X_test)
>>> nb_probas = nb.fit(X_train, y_train).predict_proba(X_test)
>>> svm_scores = svm.fit(X_train, y_train).decision_function(X_test)
>>> probas_list = [rf_probas, lr_probas, nb_probas, svm_scores]
>>> clf_names = ['Random Forest', 'Logistic Regression',
... 'Gaussian Naive Bayes', 'Support Vector Machine']
>>> skplt.metrics.plot_calibration_curve(y_test,
... probas_list,
... clf_names)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_calibration_curve.png
:align: center
:alt: Calibration Curves
"""
y_true = np.asarray(y_true)
if not isinstance(probas_list, list):
raise ValueError('`probas_list` does not contain a list.')
classes = np.unique(y_true)
if len(classes) > 2:
raise ValueError('plot_calibration_curve only '
'works for binary classification')
if clf_names is None:
clf_names = ['Classifier {}'.format(x+1)
for x in range(len(probas_list))]
if len(clf_names) != len(probas_list):
raise ValueError('Length {} of `clf_names` does not match length {} of'
' `probas_list`'.format(len(clf_names),
len(probas_list)))
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated")
for i, probas in enumerate(probas_list):
probas = np.asarray(probas)
if probas.ndim > 2:
raise ValueError('Index {} in probas_list has invalid '
'shape {}'.format(i, probas.shape))
if probas.ndim == 2:
probas = probas[:, 1]
if probas.shape != y_true.shape:
raise ValueError('Index {} in probas_list has invalid '
'shape {}'.format(i, probas.shape))
probas = (probas - probas.min()) / (probas.max() - probas.min())
fraction_of_positives, mean_predicted_value = \
calibration_curve(y_true, probas, n_bins=n_bins)
color = plt.cm.get_cmap(cmap)(float(i) / len(probas_list))
ax.plot(mean_predicted_value, fraction_of_positives, 's-',
label=clf_names[i], color=color)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlabel('Mean predicted value', fontsize=text_fontsize)
ax.set_ylabel('Fraction of positives', fontsize=text_fontsize)
ax.set_ylim([-0.05, 1.05])
ax.legend(loc='lower right')
return ax | python | 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 calibration curves for a set of classifier probability estimates.
Plotting the calibration curves of a classifier is useful for determining
whether or not you can interpret their predicted probabilities directly as
as confidence level. For instance, a well-calibrated binary classifier
should classify the samples such that for samples to which it gave a score
of 0.8, around 80% should actually be from the positive class.
This function currently only works for binary classification.
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
probas_list (list of array-like, shape (n_samples, 2) or (n_samples,)):
A list containing the outputs of binary classifiers'
:func:`predict_proba` method or :func:`decision_function` method.
clf_names (list of str, optional): A list of strings, where each string
refers to the name of the classifier that produced the
corresponding probability estimates in `probas_list`. If ``None``,
the names "Classifier 1", "Classifier 2", etc. will be used.
n_bins (int, optional): Number of bins. A bigger number requires more
data.
title (string, optional): Title of the generated plot. Defaults to
"Calibration plots (Reliabilirt Curves)"
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
:class:`matplotlib.axes.Axes`: The axes on which the plot was drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> lr = LogisticRegression()
>>> nb = GaussianNB()
>>> svm = LinearSVC()
>>> rf_probas = rf.fit(X_train, y_train).predict_proba(X_test)
>>> lr_probas = lr.fit(X_train, y_train).predict_proba(X_test)
>>> nb_probas = nb.fit(X_train, y_train).predict_proba(X_test)
>>> svm_scores = svm.fit(X_train, y_train).decision_function(X_test)
>>> probas_list = [rf_probas, lr_probas, nb_probas, svm_scores]
>>> clf_names = ['Random Forest', 'Logistic Regression',
... 'Gaussian Naive Bayes', 'Support Vector Machine']
>>> skplt.metrics.plot_calibration_curve(y_test,
... probas_list,
... clf_names)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_calibration_curve.png
:align: center
:alt: Calibration Curves
"""
y_true = np.asarray(y_true)
if not isinstance(probas_list, list):
raise ValueError('`probas_list` does not contain a list.')
classes = np.unique(y_true)
if len(classes) > 2:
raise ValueError('plot_calibration_curve only '
'works for binary classification')
if clf_names is None:
clf_names = ['Classifier {}'.format(x+1)
for x in range(len(probas_list))]
if len(clf_names) != len(probas_list):
raise ValueError('Length {} of `clf_names` does not match length {} of'
' `probas_list`'.format(len(clf_names),
len(probas_list)))
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
ax.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated")
for i, probas in enumerate(probas_list):
probas = np.asarray(probas)
if probas.ndim > 2:
raise ValueError('Index {} in probas_list has invalid '
'shape {}'.format(i, probas.shape))
if probas.ndim == 2:
probas = probas[:, 1]
if probas.shape != y_true.shape:
raise ValueError('Index {} in probas_list has invalid '
'shape {}'.format(i, probas.shape))
probas = (probas - probas.min()) / (probas.max() - probas.min())
fraction_of_positives, mean_predicted_value = \
calibration_curve(y_true, probas, n_bins=n_bins)
color = plt.cm.get_cmap(cmap)(float(i) / len(probas_list))
ax.plot(mean_predicted_value, fraction_of_positives, 's-',
label=clf_names[i], color=color)
ax.set_title(title, fontsize=title_fontsize)
ax.set_xlabel('Mean predicted value', fontsize=text_fontsize)
ax.set_ylabel('Fraction of positives', fontsize=text_fontsize)
ax.set_ylim([-0.05, 1.05])
ax.legend(loc='lower right')
return ax | [
"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\"",
")",
":",
"y_true",
"=",
"np",
".",
"asarray",
"(",
"y_true",
")",
"if",
"not",
"isinstance",
"(",
"probas_list",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"'`probas_list` does not contain a list.'",
")",
"classes",
"=",
"np",
".",
"unique",
"(",
"y_true",
")",
"if",
"len",
"(",
"classes",
")",
">",
"2",
":",
"raise",
"ValueError",
"(",
"'plot_calibration_curve only '",
"'works for binary classification'",
")",
"if",
"clf_names",
"is",
"None",
":",
"clf_names",
"=",
"[",
"'Classifier {}'",
".",
"format",
"(",
"x",
"+",
"1",
")",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"probas_list",
")",
")",
"]",
"if",
"len",
"(",
"clf_names",
")",
"!=",
"len",
"(",
"probas_list",
")",
":",
"raise",
"ValueError",
"(",
"'Length {} of `clf_names` does not match length {} of'",
"' `probas_list`'",
".",
"format",
"(",
"len",
"(",
"clf_names",
")",
",",
"len",
"(",
"probas_list",
")",
")",
")",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"1",
",",
"figsize",
"=",
"figsize",
")",
"ax",
".",
"plot",
"(",
"[",
"0",
",",
"1",
"]",
",",
"[",
"0",
",",
"1",
"]",
",",
"\"k:\"",
",",
"label",
"=",
"\"Perfectly calibrated\"",
")",
"for",
"i",
",",
"probas",
"in",
"enumerate",
"(",
"probas_list",
")",
":",
"probas",
"=",
"np",
".",
"asarray",
"(",
"probas",
")",
"if",
"probas",
".",
"ndim",
">",
"2",
":",
"raise",
"ValueError",
"(",
"'Index {} in probas_list has invalid '",
"'shape {}'",
".",
"format",
"(",
"i",
",",
"probas",
".",
"shape",
")",
")",
"if",
"probas",
".",
"ndim",
"==",
"2",
":",
"probas",
"=",
"probas",
"[",
":",
",",
"1",
"]",
"if",
"probas",
".",
"shape",
"!=",
"y_true",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"'Index {} in probas_list has invalid '",
"'shape {}'",
".",
"format",
"(",
"i",
",",
"probas",
".",
"shape",
")",
")",
"probas",
"=",
"(",
"probas",
"-",
"probas",
".",
"min",
"(",
")",
")",
"/",
"(",
"probas",
".",
"max",
"(",
")",
"-",
"probas",
".",
"min",
"(",
")",
")",
"fraction_of_positives",
",",
"mean_predicted_value",
"=",
"calibration_curve",
"(",
"y_true",
",",
"probas",
",",
"n_bins",
"=",
"n_bins",
")",
"color",
"=",
"plt",
".",
"cm",
".",
"get_cmap",
"(",
"cmap",
")",
"(",
"float",
"(",
"i",
")",
"/",
"len",
"(",
"probas_list",
")",
")",
"ax",
".",
"plot",
"(",
"mean_predicted_value",
",",
"fraction_of_positives",
",",
"'s-'",
",",
"label",
"=",
"clf_names",
"[",
"i",
"]",
",",
"color",
"=",
"color",
")",
"ax",
".",
"set_title",
"(",
"title",
",",
"fontsize",
"=",
"title_fontsize",
")",
"ax",
".",
"set_xlabel",
"(",
"'Mean predicted value'",
",",
"fontsize",
"=",
"text_fontsize",
")",
"ax",
".",
"set_ylabel",
"(",
"'Fraction of positives'",
",",
"fontsize",
"=",
"text_fontsize",
")",
"ax",
".",
"set_ylim",
"(",
"[",
"-",
"0.05",
",",
"1.05",
"]",
")",
"ax",
".",
"legend",
"(",
"loc",
"=",
"'lower right'",
")",
"return",
"ax"
] | Plots calibration curves for a set of classifier probability estimates.
Plotting the calibration curves of a classifier is useful for determining
whether or not you can interpret their predicted probabilities directly as
as confidence level. For instance, a well-calibrated binary classifier
should classify the samples such that for samples to which it gave a score
of 0.8, around 80% should actually be from the positive class.
This function currently only works for binary classification.
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
probas_list (list of array-like, shape (n_samples, 2) or (n_samples,)):
A list containing the outputs of binary classifiers'
:func:`predict_proba` method or :func:`decision_function` method.
clf_names (list of str, optional): A list of strings, where each string
refers to the name of the classifier that produced the
corresponding probability estimates in `probas_list`. If ``None``,
the names "Classifier 1", "Classifier 2", etc. will be used.
n_bins (int, optional): Number of bins. A bigger number requires more
data.
title (string, optional): Title of the generated plot. Defaults to
"Calibration plots (Reliabilirt Curves)"
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
:class:`matplotlib.axes.Axes`: The axes on which the plot was drawn.
Example:
>>> import scikitplot as skplt
>>> rf = RandomForestClassifier()
>>> lr = LogisticRegression()
>>> nb = GaussianNB()
>>> svm = LinearSVC()
>>> rf_probas = rf.fit(X_train, y_train).predict_proba(X_test)
>>> lr_probas = lr.fit(X_train, y_train).predict_proba(X_test)
>>> nb_probas = nb.fit(X_train, y_train).predict_proba(X_test)
>>> svm_scores = svm.fit(X_train, y_train).decision_function(X_test)
>>> probas_list = [rf_probas, lr_probas, nb_probas, svm_scores]
>>> clf_names = ['Random Forest', 'Logistic Regression',
... 'Gaussian Naive Bayes', 'Support Vector Machine']
>>> skplt.metrics.plot_calibration_curve(y_test,
... probas_list,
... clf_names)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_calibration_curve.png
:align: center
:alt: Calibration Curves | [
"Plots",
"calibration",
"curves",
"for",
"a",
"set",
"of",
"classifier",
"probability",
"estimates",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/metrics.py#L911-L1042 |
230,015 | reiinakano/scikit-plot | scikitplot/clustering.py | clustering_factory | 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:
ValueError: If **clf** does not contain the instance methods necessary
for scikit-plot instance methods.
"""
required_methods = ['fit', 'fit_predict']
for method in required_methods:
if not hasattr(clf, method):
raise TypeError('"{}" is not in clf. Did you '
'pass a clusterer instance?'.format(method))
additional_methods = {
'plot_silhouette': plot_silhouette,
'plot_elbow_curve': plot_elbow_curve
}
for key, fn in six.iteritems(additional_methods):
if hasattr(clf, key):
warnings.warn('"{}" method already in clf. '
'Overriding anyway. This may '
'result in unintended behavior.'.format(key))
setattr(clf, key, types.MethodType(fn, clf))
return clf | python | 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:
ValueError: If **clf** does not contain the instance methods necessary
for scikit-plot instance methods.
"""
required_methods = ['fit', 'fit_predict']
for method in required_methods:
if not hasattr(clf, method):
raise TypeError('"{}" is not in clf. Did you '
'pass a clusterer instance?'.format(method))
additional_methods = {
'plot_silhouette': plot_silhouette,
'plot_elbow_curve': plot_elbow_curve
}
for key, fn in six.iteritems(additional_methods):
if hasattr(clf, key):
warnings.warn('"{}" method already in clf. '
'Overriding anyway. This may '
'result in unintended behavior.'.format(key))
setattr(clf, key, types.MethodType(fn, clf))
return clf | [
"def",
"clustering_factory",
"(",
"clf",
")",
":",
"required_methods",
"=",
"[",
"'fit'",
",",
"'fit_predict'",
"]",
"for",
"method",
"in",
"required_methods",
":",
"if",
"not",
"hasattr",
"(",
"clf",
",",
"method",
")",
":",
"raise",
"TypeError",
"(",
"'\"{}\" is not in clf. Did you '",
"'pass a clusterer instance?'",
".",
"format",
"(",
"method",
")",
")",
"additional_methods",
"=",
"{",
"'plot_silhouette'",
":",
"plot_silhouette",
",",
"'plot_elbow_curve'",
":",
"plot_elbow_curve",
"}",
"for",
"key",
",",
"fn",
"in",
"six",
".",
"iteritems",
"(",
"additional_methods",
")",
":",
"if",
"hasattr",
"(",
"clf",
",",
"key",
")",
":",
"warnings",
".",
"warn",
"(",
"'\"{}\" method already in clf. '",
"'Overriding anyway. This may '",
"'result in unintended behavior.'",
".",
"format",
"(",
"key",
")",
")",
"setattr",
"(",
"clf",
",",
"key",
",",
"types",
".",
"MethodType",
"(",
"fn",
",",
"clf",
")",
")",
"return",
"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:
ValueError: If **clf** does not contain the instance methods necessary
for scikit-plot instance methods. | [
"Embeds",
"scikit",
"-",
"plot",
"plotting",
"methods",
"in",
"an",
"sklearn",
"clusterer",
"instance",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/clustering.py#L18-L50 |
230,016 | reiinakano/scikit-plot | scikitplot/helpers.py | validate_labels | 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 labels. Otherwise returns
None.
Args:
known_classes (array-like):
The classes that are known to appear in the data.
passed_labels (array-like):
The labels that were passed in through the argument.
argument_name (str):
The name of the argument being validated.
Example:
>>> known_classes = ["A", "B", "C"]
>>> passed_labels = ["A", "B"]
>>> validate_labels(known_classes, passed_labels, "true_labels")
"""
known_classes = np.array(known_classes)
passed_labels = np.array(passed_labels)
unique_labels, unique_indexes = np.unique(passed_labels, return_index=True)
if len(passed_labels) != len(unique_labels):
indexes = np.arange(0, len(passed_labels))
duplicate_indexes = indexes[~np.in1d(indexes, unique_indexes)]
duplicate_labels = [str(x) for x in passed_labels[duplicate_indexes]]
msg = "The following duplicate labels were passed into {0}: {1}" \
.format(argument_name, ", ".join(duplicate_labels))
raise ValueError(msg)
passed_labels_absent = ~np.in1d(passed_labels, known_classes)
if np.any(passed_labels_absent):
absent_labels = [str(x) for x in passed_labels[passed_labels_absent]]
msg = ("The following labels "
"were passed into {0}, "
"but were not found in "
"labels: {1}").format(argument_name, ", ".join(absent_labels))
raise ValueError(msg)
return | python | 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 labels. Otherwise returns
None.
Args:
known_classes (array-like):
The classes that are known to appear in the data.
passed_labels (array-like):
The labels that were passed in through the argument.
argument_name (str):
The name of the argument being validated.
Example:
>>> known_classes = ["A", "B", "C"]
>>> passed_labels = ["A", "B"]
>>> validate_labels(known_classes, passed_labels, "true_labels")
"""
known_classes = np.array(known_classes)
passed_labels = np.array(passed_labels)
unique_labels, unique_indexes = np.unique(passed_labels, return_index=True)
if len(passed_labels) != len(unique_labels):
indexes = np.arange(0, len(passed_labels))
duplicate_indexes = indexes[~np.in1d(indexes, unique_indexes)]
duplicate_labels = [str(x) for x in passed_labels[duplicate_indexes]]
msg = "The following duplicate labels were passed into {0}: {1}" \
.format(argument_name, ", ".join(duplicate_labels))
raise ValueError(msg)
passed_labels_absent = ~np.in1d(passed_labels, known_classes)
if np.any(passed_labels_absent):
absent_labels = [str(x) for x in passed_labels[passed_labels_absent]]
msg = ("The following labels "
"were passed into {0}, "
"but were not found in "
"labels: {1}").format(argument_name, ", ".join(absent_labels))
raise ValueError(msg)
return | [
"def",
"validate_labels",
"(",
"known_classes",
",",
"passed_labels",
",",
"argument_name",
")",
":",
"known_classes",
"=",
"np",
".",
"array",
"(",
"known_classes",
")",
"passed_labels",
"=",
"np",
".",
"array",
"(",
"passed_labels",
")",
"unique_labels",
",",
"unique_indexes",
"=",
"np",
".",
"unique",
"(",
"passed_labels",
",",
"return_index",
"=",
"True",
")",
"if",
"len",
"(",
"passed_labels",
")",
"!=",
"len",
"(",
"unique_labels",
")",
":",
"indexes",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"len",
"(",
"passed_labels",
")",
")",
"duplicate_indexes",
"=",
"indexes",
"[",
"~",
"np",
".",
"in1d",
"(",
"indexes",
",",
"unique_indexes",
")",
"]",
"duplicate_labels",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"passed_labels",
"[",
"duplicate_indexes",
"]",
"]",
"msg",
"=",
"\"The following duplicate labels were passed into {0}: {1}\"",
".",
"format",
"(",
"argument_name",
",",
"\", \"",
".",
"join",
"(",
"duplicate_labels",
")",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"passed_labels_absent",
"=",
"~",
"np",
".",
"in1d",
"(",
"passed_labels",
",",
"known_classes",
")",
"if",
"np",
".",
"any",
"(",
"passed_labels_absent",
")",
":",
"absent_labels",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"passed_labels",
"[",
"passed_labels_absent",
"]",
"]",
"msg",
"=",
"(",
"\"The following labels \"",
"\"were passed into {0}, \"",
"\"but were not found in \"",
"\"labels: {1}\"",
")",
".",
"format",
"(",
"argument_name",
",",
"\", \"",
".",
"join",
"(",
"absent_labels",
")",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"return"
] | 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 labels. Otherwise returns
None.
Args:
known_classes (array-like):
The classes that are known to appear in the data.
passed_labels (array-like):
The labels that were passed in through the argument.
argument_name (str):
The name of the argument being validated.
Example:
>>> known_classes = ["A", "B", "C"]
>>> passed_labels = ["A", "B"]
>>> validate_labels(known_classes, passed_labels, "true_labels") | [
"Validates",
"the",
"labels",
"passed",
"into",
"the",
"true_labels",
"or",
"pred_labels",
"arguments",
"in",
"the",
"plot_confusion_matrix",
"function",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/helpers.py#L108-L154 |
230,017 | reiinakano/scikit-plot | scikitplot/helpers.py | cumulative_gain_curve | 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 (array-like, shape (n_samples)): Target scores, can either be
probability estimates of the positive class, confidence values, or
non-thresholded measure of decisions (as returned by
decision_function on some classifiers).
pos_label (int or str, default=None): Label considered as positive and
others are considered negative
Returns:
percentages (numpy.ndarray): An array containing the X-axis values for
plotting the Cumulative Gains chart.
gains (numpy.ndarray): An array containing the Y-axis values for one
curve of the Cumulative Gains chart.
Raises:
ValueError: If `y_true` is not composed of 2 classes. The Cumulative
Gain Chart is only relevant in binary classification.
"""
y_true, y_score = np.asarray(y_true), np.asarray(y_score)
# ensure binary classification if pos_label is not specified
classes = np.unique(y_true)
if (pos_label is None and
not (np.array_equal(classes, [0, 1]) or
np.array_equal(classes, [-1, 1]) or
np.array_equal(classes, [0]) or
np.array_equal(classes, [-1]) or
np.array_equal(classes, [1]))):
raise ValueError("Data is not binary and pos_label is not specified")
elif pos_label is None:
pos_label = 1.
# make y_true a boolean vector
y_true = (y_true == pos_label)
sorted_indices = np.argsort(y_score)[::-1]
y_true = y_true[sorted_indices]
gains = np.cumsum(y_true)
percentages = np.arange(start=1, stop=len(y_true) + 1)
gains = gains / float(np.sum(y_true))
percentages = percentages / float(len(y_true))
gains = np.insert(gains, 0, [0])
percentages = np.insert(percentages, 0, [0])
return percentages, gains | python | 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 (array-like, shape (n_samples)): Target scores, can either be
probability estimates of the positive class, confidence values, or
non-thresholded measure of decisions (as returned by
decision_function on some classifiers).
pos_label (int or str, default=None): Label considered as positive and
others are considered negative
Returns:
percentages (numpy.ndarray): An array containing the X-axis values for
plotting the Cumulative Gains chart.
gains (numpy.ndarray): An array containing the Y-axis values for one
curve of the Cumulative Gains chart.
Raises:
ValueError: If `y_true` is not composed of 2 classes. The Cumulative
Gain Chart is only relevant in binary classification.
"""
y_true, y_score = np.asarray(y_true), np.asarray(y_score)
# ensure binary classification if pos_label is not specified
classes = np.unique(y_true)
if (pos_label is None and
not (np.array_equal(classes, [0, 1]) or
np.array_equal(classes, [-1, 1]) or
np.array_equal(classes, [0]) or
np.array_equal(classes, [-1]) or
np.array_equal(classes, [1]))):
raise ValueError("Data is not binary and pos_label is not specified")
elif pos_label is None:
pos_label = 1.
# make y_true a boolean vector
y_true = (y_true == pos_label)
sorted_indices = np.argsort(y_score)[::-1]
y_true = y_true[sorted_indices]
gains = np.cumsum(y_true)
percentages = np.arange(start=1, stop=len(y_true) + 1)
gains = gains / float(np.sum(y_true))
percentages = percentages / float(len(y_true))
gains = np.insert(gains, 0, [0])
percentages = np.insert(percentages, 0, [0])
return percentages, gains | [
"def",
"cumulative_gain_curve",
"(",
"y_true",
",",
"y_score",
",",
"pos_label",
"=",
"None",
")",
":",
"y_true",
",",
"y_score",
"=",
"np",
".",
"asarray",
"(",
"y_true",
")",
",",
"np",
".",
"asarray",
"(",
"y_score",
")",
"# ensure binary classification if pos_label is not specified",
"classes",
"=",
"np",
".",
"unique",
"(",
"y_true",
")",
"if",
"(",
"pos_label",
"is",
"None",
"and",
"not",
"(",
"np",
".",
"array_equal",
"(",
"classes",
",",
"[",
"0",
",",
"1",
"]",
")",
"or",
"np",
".",
"array_equal",
"(",
"classes",
",",
"[",
"-",
"1",
",",
"1",
"]",
")",
"or",
"np",
".",
"array_equal",
"(",
"classes",
",",
"[",
"0",
"]",
")",
"or",
"np",
".",
"array_equal",
"(",
"classes",
",",
"[",
"-",
"1",
"]",
")",
"or",
"np",
".",
"array_equal",
"(",
"classes",
",",
"[",
"1",
"]",
")",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Data is not binary and pos_label is not specified\"",
")",
"elif",
"pos_label",
"is",
"None",
":",
"pos_label",
"=",
"1.",
"# make y_true a boolean vector",
"y_true",
"=",
"(",
"y_true",
"==",
"pos_label",
")",
"sorted_indices",
"=",
"np",
".",
"argsort",
"(",
"y_score",
")",
"[",
":",
":",
"-",
"1",
"]",
"y_true",
"=",
"y_true",
"[",
"sorted_indices",
"]",
"gains",
"=",
"np",
".",
"cumsum",
"(",
"y_true",
")",
"percentages",
"=",
"np",
".",
"arange",
"(",
"start",
"=",
"1",
",",
"stop",
"=",
"len",
"(",
"y_true",
")",
"+",
"1",
")",
"gains",
"=",
"gains",
"/",
"float",
"(",
"np",
".",
"sum",
"(",
"y_true",
")",
")",
"percentages",
"=",
"percentages",
"/",
"float",
"(",
"len",
"(",
"y_true",
")",
")",
"gains",
"=",
"np",
".",
"insert",
"(",
"gains",
",",
"0",
",",
"[",
"0",
"]",
")",
"percentages",
"=",
"np",
".",
"insert",
"(",
"percentages",
",",
"0",
",",
"[",
"0",
"]",
")",
"return",
"percentages",
",",
"gains"
] | 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 (array-like, shape (n_samples)): Target scores, can either be
probability estimates of the positive class, confidence values, or
non-thresholded measure of decisions (as returned by
decision_function on some classifiers).
pos_label (int or str, default=None): Label considered as positive and
others are considered negative
Returns:
percentages (numpy.ndarray): An array containing the X-axis values for
plotting the Cumulative Gains chart.
gains (numpy.ndarray): An array containing the Y-axis values for one
curve of the Cumulative Gains chart.
Raises:
ValueError: If `y_true` is not composed of 2 classes. The Cumulative
Gain Chart is only relevant in binary classification. | [
"This",
"function",
"generates",
"the",
"points",
"necessary",
"to",
"plot",
"the",
"Cumulative",
"Gain"
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/helpers.py#L157-L213 |
230,018 | allure-framework/allure-python | allure-python-commons/src/utils.py | getargspec | 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 Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
Like inspect.getargspec but supports functools.partial as well.
"""
# noqa: E731 type: (Any) -> Any
if inspect.ismethod(func):
func = func.__func__
parts = 0, () # noqa: E731 type: Tuple[int, Tuple[unicode, ...]]
if type(func) is partial:
keywords = func.keywords
if keywords is None:
keywords = {}
parts = len(func.args), keywords.keys()
func = func.func
if not inspect.isfunction(func):
raise TypeError('%r is not a Python function' % func)
args, varargs, varkw = inspect.getargs(func.__code__)
func_defaults = func.__defaults__
if func_defaults is None:
func_defaults = []
else:
func_defaults = list(func_defaults)
if parts[0]:
args = args[parts[0]:]
if parts[1]:
for arg in parts[1]:
i = args.index(arg) - len(args) # type: ignore
del args[i]
try:
del func_defaults[i]
except IndexError:
pass
return inspect.ArgSpec(args, varargs, varkw, func_defaults) | python | 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 Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
Like inspect.getargspec but supports functools.partial as well.
"""
# noqa: E731 type: (Any) -> Any
if inspect.ismethod(func):
func = func.__func__
parts = 0, () # noqa: E731 type: Tuple[int, Tuple[unicode, ...]]
if type(func) is partial:
keywords = func.keywords
if keywords is None:
keywords = {}
parts = len(func.args), keywords.keys()
func = func.func
if not inspect.isfunction(func):
raise TypeError('%r is not a Python function' % func)
args, varargs, varkw = inspect.getargs(func.__code__)
func_defaults = func.__defaults__
if func_defaults is None:
func_defaults = []
else:
func_defaults = list(func_defaults)
if parts[0]:
args = args[parts[0]:]
if parts[1]:
for arg in parts[1]:
i = args.index(arg) - len(args) # type: ignore
del args[i]
try:
del func_defaults[i]
except IndexError:
pass
return inspect.ArgSpec(args, varargs, varkw, func_defaults) | [
"def",
"getargspec",
"(",
"func",
")",
":",
"# noqa: E731 type: (Any) -> Any",
"if",
"inspect",
".",
"ismethod",
"(",
"func",
")",
":",
"func",
"=",
"func",
".",
"__func__",
"parts",
"=",
"0",
",",
"(",
")",
"# noqa: E731 type: Tuple[int, Tuple[unicode, ...]]",
"if",
"type",
"(",
"func",
")",
"is",
"partial",
":",
"keywords",
"=",
"func",
".",
"keywords",
"if",
"keywords",
"is",
"None",
":",
"keywords",
"=",
"{",
"}",
"parts",
"=",
"len",
"(",
"func",
".",
"args",
")",
",",
"keywords",
".",
"keys",
"(",
")",
"func",
"=",
"func",
".",
"func",
"if",
"not",
"inspect",
".",
"isfunction",
"(",
"func",
")",
":",
"raise",
"TypeError",
"(",
"'%r is not a Python function'",
"%",
"func",
")",
"args",
",",
"varargs",
",",
"varkw",
"=",
"inspect",
".",
"getargs",
"(",
"func",
".",
"__code__",
")",
"func_defaults",
"=",
"func",
".",
"__defaults__",
"if",
"func_defaults",
"is",
"None",
":",
"func_defaults",
"=",
"[",
"]",
"else",
":",
"func_defaults",
"=",
"list",
"(",
"func_defaults",
")",
"if",
"parts",
"[",
"0",
"]",
":",
"args",
"=",
"args",
"[",
"parts",
"[",
"0",
"]",
":",
"]",
"if",
"parts",
"[",
"1",
"]",
":",
"for",
"arg",
"in",
"parts",
"[",
"1",
"]",
":",
"i",
"=",
"args",
".",
"index",
"(",
"arg",
")",
"-",
"len",
"(",
"args",
")",
"# type: ignore",
"del",
"args",
"[",
"i",
"]",
"try",
":",
"del",
"func_defaults",
"[",
"i",
"]",
"except",
"IndexError",
":",
"pass",
"return",
"inspect",
".",
"ArgSpec",
"(",
"args",
",",
"varargs",
",",
"varkw",
",",
"func_defaults",
")"
] | 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 Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
Like inspect.getargspec but supports functools.partial as well. | [
"Used",
"because",
"getargspec",
"for",
"python",
"2",
".",
"7",
"does",
"not",
"accept",
"functools",
".",
"partial",
"which",
"is",
"the",
"type",
"for",
"pytest",
"fixtures",
"."
] | 070fdcc093e8743cc5e58f5f108b21f12ec8ddaf | https://github.com/allure-framework/allure-python/blob/070fdcc093e8743cc5e58f5f108b21f12ec8ddaf/allure-python-commons/src/utils.py#L18-L61 |
230,019 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.querystring | 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 | 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[')} | [
"def",
"querystring",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"value",
"for",
"(",
"key",
",",
"value",
")",
"in",
"self",
".",
"qs",
".",
"items",
"(",
")",
"if",
"key",
".",
"startswith",
"(",
"self",
".",
"MANAGED_KEYS",
")",
"or",
"self",
".",
"_get_key_values",
"(",
"'filter['",
")",
"}"
] | Return original querystring but containing only managed keys
:return dict: dict of managed querystring parameter | [
"Return",
"original",
"querystring",
"but",
"containing",
"only",
"managed",
"keys"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L68-L74 |
230,020 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.filters | 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, TypeError):
raise InvalidFilters("Parse error")
if self._get_key_values('filter['):
results.extend(self._simple_filters(self._get_key_values('filter[')))
return results | python | 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, TypeError):
raise InvalidFilters("Parse error")
if self._get_key_values('filter['):
results.extend(self._simple_filters(self._get_key_values('filter[')))
return results | [
"def",
"filters",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"filters",
"=",
"self",
".",
"qs",
".",
"get",
"(",
"'filter'",
")",
"if",
"filters",
"is",
"not",
"None",
":",
"try",
":",
"results",
".",
"extend",
"(",
"json",
".",
"loads",
"(",
"filters",
")",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"raise",
"InvalidFilters",
"(",
"\"Parse error\"",
")",
"if",
"self",
".",
"_get_key_values",
"(",
"'filter['",
")",
":",
"results",
".",
"extend",
"(",
"self",
".",
"_simple_filters",
"(",
"self",
".",
"_get_key_values",
"(",
"'filter['",
")",
")",
")",
"return",
"results"
] | Return filters from query string.
:return list: filter information | [
"Return",
"filters",
"from",
"query",
"string",
"."
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L77-L91 |
230,021 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.pagination | 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',
}
Example with number strategy::
>>> query_string = {'page[number]': '25', 'page[size]': '10'}
>>> parsed_query.pagination
{'number': '25', 'size': '10'}
"""
# check values type
result = self._get_key_values('page')
for key, value in result.items():
if key not in ('number', 'size'):
raise BadRequest("{} is not a valid parameter of pagination".format(key), source={'parameter': 'page'})
try:
int(value)
except ValueError:
raise BadRequest("Parse error", source={'parameter': 'page[{}]'.format(key)})
if current_app.config.get('ALLOW_DISABLE_PAGINATION', True) is False and int(result.get('size', 1)) == 0:
raise BadRequest("You are not allowed to disable pagination", source={'parameter': 'page[size]'})
if current_app.config.get('MAX_PAGE_SIZE') is not None and 'size' in result:
if int(result['size']) > current_app.config['MAX_PAGE_SIZE']:
raise BadRequest("Maximum page size is {}".format(current_app.config['MAX_PAGE_SIZE']),
source={'parameter': 'page[size]'})
return result | python | 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',
}
Example with number strategy::
>>> query_string = {'page[number]': '25', 'page[size]': '10'}
>>> parsed_query.pagination
{'number': '25', 'size': '10'}
"""
# check values type
result = self._get_key_values('page')
for key, value in result.items():
if key not in ('number', 'size'):
raise BadRequest("{} is not a valid parameter of pagination".format(key), source={'parameter': 'page'})
try:
int(value)
except ValueError:
raise BadRequest("Parse error", source={'parameter': 'page[{}]'.format(key)})
if current_app.config.get('ALLOW_DISABLE_PAGINATION', True) is False and int(result.get('size', 1)) == 0:
raise BadRequest("You are not allowed to disable pagination", source={'parameter': 'page[size]'})
if current_app.config.get('MAX_PAGE_SIZE') is not None and 'size' in result:
if int(result['size']) > current_app.config['MAX_PAGE_SIZE']:
raise BadRequest("Maximum page size is {}".format(current_app.config['MAX_PAGE_SIZE']),
source={'parameter': 'page[size]'})
return result | [
"def",
"pagination",
"(",
"self",
")",
":",
"# check values type",
"result",
"=",
"self",
".",
"_get_key_values",
"(",
"'page'",
")",
"for",
"key",
",",
"value",
"in",
"result",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"(",
"'number'",
",",
"'size'",
")",
":",
"raise",
"BadRequest",
"(",
"\"{} is not a valid parameter of pagination\"",
".",
"format",
"(",
"key",
")",
",",
"source",
"=",
"{",
"'parameter'",
":",
"'page'",
"}",
")",
"try",
":",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"BadRequest",
"(",
"\"Parse error\"",
",",
"source",
"=",
"{",
"'parameter'",
":",
"'page[{}]'",
".",
"format",
"(",
"key",
")",
"}",
")",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'ALLOW_DISABLE_PAGINATION'",
",",
"True",
")",
"is",
"False",
"and",
"int",
"(",
"result",
".",
"get",
"(",
"'size'",
",",
"1",
")",
")",
"==",
"0",
":",
"raise",
"BadRequest",
"(",
"\"You are not allowed to disable pagination\"",
",",
"source",
"=",
"{",
"'parameter'",
":",
"'page[size]'",
"}",
")",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'MAX_PAGE_SIZE'",
")",
"is",
"not",
"None",
"and",
"'size'",
"in",
"result",
":",
"if",
"int",
"(",
"result",
"[",
"'size'",
"]",
")",
">",
"current_app",
".",
"config",
"[",
"'MAX_PAGE_SIZE'",
"]",
":",
"raise",
"BadRequest",
"(",
"\"Maximum page size is {}\"",
".",
"format",
"(",
"current_app",
".",
"config",
"[",
"'MAX_PAGE_SIZE'",
"]",
")",
",",
"source",
"=",
"{",
"'parameter'",
":",
"'page[size]'",
"}",
")",
"return",
"result"
] | 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',
}
Example with number strategy::
>>> query_string = {'page[number]': '25', 'page[size]': '10'}
>>> parsed_query.pagination
{'number': '25', 'size': '10'} | [
"Return",
"all",
"page",
"parameters",
"as",
"a",
"dict",
"."
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L94-L130 |
230,022 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.fields | 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_key_values('fields')
for key, value in result.items():
if not isinstance(value, list):
result[key] = [value]
for key, value in result.items():
schema = get_schema_from_type(key)
for obj in value:
if obj not in schema._declared_fields:
raise InvalidField("{} has no attribute {}".format(schema.__name__, obj))
return result | python | 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_key_values('fields')
for key, value in result.items():
if not isinstance(value, list):
result[key] = [value]
for key, value in result.items():
schema = get_schema_from_type(key)
for obj in value:
if obj not in schema._declared_fields:
raise InvalidField("{} has no attribute {}".format(schema.__name__, obj))
return result | [
"def",
"fields",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_get_key_values",
"(",
"'fields'",
")",
"for",
"key",
",",
"value",
"in",
"result",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"result",
"[",
"key",
"]",
"=",
"[",
"value",
"]",
"for",
"key",
",",
"value",
"in",
"result",
".",
"items",
"(",
")",
":",
"schema",
"=",
"get_schema_from_type",
"(",
"key",
")",
"for",
"obj",
"in",
"value",
":",
"if",
"obj",
"not",
"in",
"schema",
".",
"_declared_fields",
":",
"raise",
"InvalidField",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"schema",
".",
"__name__",
",",
"obj",
")",
")",
"return",
"result"
] | 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'],
} | [
"Return",
"fields",
"wanted",
"by",
"client",
"."
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L133-L156 |
230,023 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.sorting | 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'},
]
"""
if self.qs.get('sort'):
sorting_results = []
for sort_field in self.qs['sort'].split(','):
field = sort_field.replace('-', '')
if field not in self.schema._declared_fields:
raise InvalidSort("{} has no attribute {}".format(self.schema.__name__, field))
if field in get_relationships(self.schema):
raise InvalidSort("You can't sort on {} because it is a relationship field".format(field))
field = get_model_field(self.schema, field)
order = 'desc' if sort_field.startswith('-') else 'asc'
sorting_results.append({'field': field, 'order': order})
return sorting_results
return [] | python | 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'},
]
"""
if self.qs.get('sort'):
sorting_results = []
for sort_field in self.qs['sort'].split(','):
field = sort_field.replace('-', '')
if field not in self.schema._declared_fields:
raise InvalidSort("{} has no attribute {}".format(self.schema.__name__, field))
if field in get_relationships(self.schema):
raise InvalidSort("You can't sort on {} because it is a relationship field".format(field))
field = get_model_field(self.schema, field)
order = 'desc' if sort_field.startswith('-') else 'asc'
sorting_results.append({'field': field, 'order': order})
return sorting_results
return [] | [
"def",
"sorting",
"(",
"self",
")",
":",
"if",
"self",
".",
"qs",
".",
"get",
"(",
"'sort'",
")",
":",
"sorting_results",
"=",
"[",
"]",
"for",
"sort_field",
"in",
"self",
".",
"qs",
"[",
"'sort'",
"]",
".",
"split",
"(",
"','",
")",
":",
"field",
"=",
"sort_field",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"if",
"field",
"not",
"in",
"self",
".",
"schema",
".",
"_declared_fields",
":",
"raise",
"InvalidSort",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"self",
".",
"schema",
".",
"__name__",
",",
"field",
")",
")",
"if",
"field",
"in",
"get_relationships",
"(",
"self",
".",
"schema",
")",
":",
"raise",
"InvalidSort",
"(",
"\"You can't sort on {} because it is a relationship field\"",
".",
"format",
"(",
"field",
")",
")",
"field",
"=",
"get_model_field",
"(",
"self",
".",
"schema",
",",
"field",
")",
"order",
"=",
"'desc'",
"if",
"sort_field",
".",
"startswith",
"(",
"'-'",
")",
"else",
"'asc'",
"sorting_results",
".",
"append",
"(",
"{",
"'field'",
":",
"field",
",",
"'order'",
":",
"order",
"}",
")",
"return",
"sorting_results",
"return",
"[",
"]"
] | 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'},
] | [
"Return",
"fields",
"to",
"sort",
"by",
"including",
"sort",
"name",
"for",
"SQLAlchemy",
"and",
"row",
"sort",
"parameter",
"for",
"other",
"ORMs"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L159-L185 |
230,024 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.include | 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_path.split('.')) > current_app.config['MAX_INCLUDE_DEPTH']:
raise InvalidInclude("You can't use include through more than {} relationships"
.format(current_app.config['MAX_INCLUDE_DEPTH']))
return include_param.split(',') if include_param else [] | python | 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_path.split('.')) > current_app.config['MAX_INCLUDE_DEPTH']:
raise InvalidInclude("You can't use include through more than {} relationships"
.format(current_app.config['MAX_INCLUDE_DEPTH']))
return include_param.split(',') if include_param else [] | [
"def",
"include",
"(",
"self",
")",
":",
"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_path",
".",
"split",
"(",
"'.'",
")",
")",
">",
"current_app",
".",
"config",
"[",
"'MAX_INCLUDE_DEPTH'",
"]",
":",
"raise",
"InvalidInclude",
"(",
"\"You can't use include through more than {} relationships\"",
".",
"format",
"(",
"current_app",
".",
"config",
"[",
"'MAX_INCLUDE_DEPTH'",
"]",
")",
")",
"return",
"include_param",
".",
"split",
"(",
"','",
")",
"if",
"include_param",
"else",
"[",
"]"
] | Return fields to include
:return list: a list of include information | [
"Return",
"fields",
"to",
"include"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L188-L201 |
230,025 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/exceptions.py | JsonApiException.to_dict | 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)})
return error_dict | python | 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)})
return error_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"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",
")",
"}",
")",
"return",
"error_dict"
] | Return values of each fields of an jsonapi error | [
"Return",
"values",
"of",
"each",
"fields",
"of",
"an",
"jsonapi",
"error"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/exceptions.py#L30-L37 |
230,026 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | Resource.dispatch_request | 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 {}'.format(request.method)
headers = {'Content-Type': 'application/vnd.api+json'}
response = method(*args, **kwargs)
if isinstance(response, Response):
response.headers.add('Content-Type', 'application/vnd.api+json')
return response
if not isinstance(response, tuple):
if isinstance(response, dict):
response.update({'jsonapi': {'version': '1.0'}})
return make_response(json.dumps(response, cls=JSONEncoder), 200, headers)
try:
data, status_code, headers = response
headers.update({'Content-Type': 'application/vnd.api+json'})
except ValueError:
pass
try:
data, status_code = response
except ValueError:
pass
if isinstance(data, dict):
data.update({'jsonapi': {'version': '1.0'}})
return make_response(json.dumps(data, cls=JSONEncoder), status_code, headers) | python | 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 {}'.format(request.method)
headers = {'Content-Type': 'application/vnd.api+json'}
response = method(*args, **kwargs)
if isinstance(response, Response):
response.headers.add('Content-Type', 'application/vnd.api+json')
return response
if not isinstance(response, tuple):
if isinstance(response, dict):
response.update({'jsonapi': {'version': '1.0'}})
return make_response(json.dumps(response, cls=JSONEncoder), 200, headers)
try:
data, status_code, headers = response
headers.update({'Content-Type': 'application/vnd.api+json'})
except ValueError:
pass
try:
data, status_code = response
except ValueError:
pass
if isinstance(data, dict):
data.update({'jsonapi': {'version': '1.0'}})
return make_response(json.dumps(data, cls=JSONEncoder), status_code, headers) | [
"def",
"dispatch_request",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"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 {}'",
".",
"format",
"(",
"request",
".",
"method",
")",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/vnd.api+json'",
"}",
"response",
"=",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"response",
",",
"Response",
")",
":",
"response",
".",
"headers",
".",
"add",
"(",
"'Content-Type'",
",",
"'application/vnd.api+json'",
")",
"return",
"response",
"if",
"not",
"isinstance",
"(",
"response",
",",
"tuple",
")",
":",
"if",
"isinstance",
"(",
"response",
",",
"dict",
")",
":",
"response",
".",
"update",
"(",
"{",
"'jsonapi'",
":",
"{",
"'version'",
":",
"'1.0'",
"}",
"}",
")",
"return",
"make_response",
"(",
"json",
".",
"dumps",
"(",
"response",
",",
"cls",
"=",
"JSONEncoder",
")",
",",
"200",
",",
"headers",
")",
"try",
":",
"data",
",",
"status_code",
",",
"headers",
"=",
"response",
"headers",
".",
"update",
"(",
"{",
"'Content-Type'",
":",
"'application/vnd.api+json'",
"}",
")",
"except",
"ValueError",
":",
"pass",
"try",
":",
"data",
",",
"status_code",
"=",
"response",
"except",
"ValueError",
":",
"pass",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
".",
"update",
"(",
"{",
"'jsonapi'",
":",
"{",
"'version'",
":",
"'1.0'",
"}",
"}",
")",
"return",
"make_response",
"(",
"json",
".",
"dumps",
"(",
"data",
",",
"cls",
"=",
"JSONEncoder",
")",
",",
"status_code",
",",
"headers",
")"
] | Logic of how to handle a request | [
"Logic",
"of",
"how",
"to",
"handle",
"a",
"request"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L62-L96 |
230,027 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceList.get | 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_kwargs.update({'many': True})
self.before_marshmallow(args, kwargs)
schema = compute_schema(self.schema,
schema_kwargs,
qs,
qs.include)
result = schema.dump(objects).data
view_kwargs = request.view_args if getattr(self, 'view_kwargs', None) is True else dict()
add_pagination_links(result,
objects_count,
qs,
url_for(self.view, _external=True, **view_kwargs))
result.update({'meta': {'count': objects_count}})
final_result = self.after_get(result)
return final_result | python | 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_kwargs.update({'many': True})
self.before_marshmallow(args, kwargs)
schema = compute_schema(self.schema,
schema_kwargs,
qs,
qs.include)
result = schema.dump(objects).data
view_kwargs = request.view_args if getattr(self, 'view_kwargs', None) is True else dict()
add_pagination_links(result,
objects_count,
qs,
url_for(self.view, _external=True, **view_kwargs))
result.update({'meta': {'count': objects_count}})
final_result = self.after_get(result)
return final_result | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"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_kwargs",
".",
"update",
"(",
"{",
"'many'",
":",
"True",
"}",
")",
"self",
".",
"before_marshmallow",
"(",
"args",
",",
"kwargs",
")",
"schema",
"=",
"compute_schema",
"(",
"self",
".",
"schema",
",",
"schema_kwargs",
",",
"qs",
",",
"qs",
".",
"include",
")",
"result",
"=",
"schema",
".",
"dump",
"(",
"objects",
")",
".",
"data",
"view_kwargs",
"=",
"request",
".",
"view_args",
"if",
"getattr",
"(",
"self",
",",
"'view_kwargs'",
",",
"None",
")",
"is",
"True",
"else",
"dict",
"(",
")",
"add_pagination_links",
"(",
"result",
",",
"objects_count",
",",
"qs",
",",
"url_for",
"(",
"self",
".",
"view",
",",
"_external",
"=",
"True",
",",
"*",
"*",
"view_kwargs",
")",
")",
"result",
".",
"update",
"(",
"{",
"'meta'",
":",
"{",
"'count'",
":",
"objects_count",
"}",
"}",
")",
"final_result",
"=",
"self",
".",
"after_get",
"(",
"result",
")",
"return",
"final_result"
] | Retrieve a collection of objects | [
"Retrieve",
"a",
"collection",
"of",
"objects"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L103-L133 |
230,028 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceList.post | 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,
qs.include)
try:
data, errors = schema.load(json_data)
except IncorrectTypeError as e:
errors = e.messages
for error in errors['errors']:
error['status'] = '409'
error['title'] = "Incorrect type"
return errors, 409
except ValidationError as e:
errors = e.messages
for message in errors['errors']:
message['status'] = '422'
message['title'] = "Validation error"
return errors, 422
if errors:
for error in errors['errors']:
error['status'] = "422"
error['title'] = "Validation error"
return errors, 422
self.before_post(args, kwargs, data=data)
obj = self.create_object(data, kwargs)
result = schema.dump(obj).data
if result['data'].get('links', {}).get('self'):
final_result = (result, 201, {'Location': result['data']['links']['self']})
else:
final_result = (result, 201)
result = self.after_post(final_result)
return result | python | 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,
qs.include)
try:
data, errors = schema.load(json_data)
except IncorrectTypeError as e:
errors = e.messages
for error in errors['errors']:
error['status'] = '409'
error['title'] = "Incorrect type"
return errors, 409
except ValidationError as e:
errors = e.messages
for message in errors['errors']:
message['status'] = '422'
message['title'] = "Validation error"
return errors, 422
if errors:
for error in errors['errors']:
error['status'] = "422"
error['title'] = "Validation error"
return errors, 422
self.before_post(args, kwargs, data=data)
obj = self.create_object(data, kwargs)
result = schema.dump(obj).data
if result['data'].get('links', {}).get('self'):
final_result = (result, 201, {'Location': result['data']['links']['self']})
else:
final_result = (result, 201)
result = self.after_post(final_result)
return result | [
"def",
"post",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"json_data",
"=",
"request",
".",
"get_json",
"(",
")",
"or",
"{",
"}",
"qs",
"=",
"QSManager",
"(",
"request",
".",
"args",
",",
"self",
".",
"schema",
")",
"schema",
"=",
"compute_schema",
"(",
"self",
".",
"schema",
",",
"getattr",
"(",
"self",
",",
"'post_schema_kwargs'",
",",
"dict",
"(",
")",
")",
",",
"qs",
",",
"qs",
".",
"include",
")",
"try",
":",
"data",
",",
"errors",
"=",
"schema",
".",
"load",
"(",
"json_data",
")",
"except",
"IncorrectTypeError",
"as",
"e",
":",
"errors",
"=",
"e",
".",
"messages",
"for",
"error",
"in",
"errors",
"[",
"'errors'",
"]",
":",
"error",
"[",
"'status'",
"]",
"=",
"'409'",
"error",
"[",
"'title'",
"]",
"=",
"\"Incorrect type\"",
"return",
"errors",
",",
"409",
"except",
"ValidationError",
"as",
"e",
":",
"errors",
"=",
"e",
".",
"messages",
"for",
"message",
"in",
"errors",
"[",
"'errors'",
"]",
":",
"message",
"[",
"'status'",
"]",
"=",
"'422'",
"message",
"[",
"'title'",
"]",
"=",
"\"Validation error\"",
"return",
"errors",
",",
"422",
"if",
"errors",
":",
"for",
"error",
"in",
"errors",
"[",
"'errors'",
"]",
":",
"error",
"[",
"'status'",
"]",
"=",
"\"422\"",
"error",
"[",
"'title'",
"]",
"=",
"\"Validation error\"",
"return",
"errors",
",",
"422",
"self",
".",
"before_post",
"(",
"args",
",",
"kwargs",
",",
"data",
"=",
"data",
")",
"obj",
"=",
"self",
".",
"create_object",
"(",
"data",
",",
"kwargs",
")",
"result",
"=",
"schema",
".",
"dump",
"(",
"obj",
")",
".",
"data",
"if",
"result",
"[",
"'data'",
"]",
".",
"get",
"(",
"'links'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'self'",
")",
":",
"final_result",
"=",
"(",
"result",
",",
"201",
",",
"{",
"'Location'",
":",
"result",
"[",
"'data'",
"]",
"[",
"'links'",
"]",
"[",
"'self'",
"]",
"}",
")",
"else",
":",
"final_result",
"=",
"(",
"result",
",",
"201",
")",
"result",
"=",
"self",
".",
"after_post",
"(",
"final_result",
")",
"return",
"result"
] | Create an object | [
"Create",
"an",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L136-L181 |
230,029 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceDetail.get | 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,
getattr(self, 'get_schema_kwargs', dict()),
qs,
qs.include)
result = schema.dump(obj).data
final_result = self.after_get(result)
return final_result | python | 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,
getattr(self, 'get_schema_kwargs', dict()),
qs,
qs.include)
result = schema.dump(obj).data
final_result = self.after_get(result)
return final_result | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"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",
",",
"getattr",
"(",
"self",
",",
"'get_schema_kwargs'",
",",
"dict",
"(",
")",
")",
",",
"qs",
",",
"qs",
".",
"include",
")",
"result",
"=",
"schema",
".",
"dump",
"(",
"obj",
")",
".",
"data",
"final_result",
"=",
"self",
".",
"after_get",
"(",
"result",
")",
"return",
"final_result"
] | Get object details | [
"Get",
"object",
"details"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L213-L232 |
230,030 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceDetail.patch | 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, kwargs)
schema = compute_schema(self.schema,
schema_kwargs,
qs,
qs.include)
try:
data, errors = schema.load(json_data)
except IncorrectTypeError as e:
errors = e.messages
for error in errors['errors']:
error['status'] = '409'
error['title'] = "Incorrect type"
return errors, 409
except ValidationError as e:
errors = e.messages
for message in errors['errors']:
message['status'] = '422'
message['title'] = "Validation error"
return errors, 422
if errors:
for error in errors['errors']:
error['status'] = "422"
error['title'] = "Validation error"
return errors, 422
if 'id' not in json_data['data']:
raise BadRequest('Missing id in "data" node',
source={'pointer': '/data/id'})
if (str(json_data['data']['id']) != str(kwargs[getattr(self._data_layer, 'url_field', 'id')])):
raise BadRequest('Value of id does not match the resource identifier in url',
source={'pointer': '/data/id'})
self.before_patch(args, kwargs, data=data)
obj = self.update_object(data, qs, kwargs)
result = schema.dump(obj).data
final_result = self.after_patch(result)
return final_result | python | 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, kwargs)
schema = compute_schema(self.schema,
schema_kwargs,
qs,
qs.include)
try:
data, errors = schema.load(json_data)
except IncorrectTypeError as e:
errors = e.messages
for error in errors['errors']:
error['status'] = '409'
error['title'] = "Incorrect type"
return errors, 409
except ValidationError as e:
errors = e.messages
for message in errors['errors']:
message['status'] = '422'
message['title'] = "Validation error"
return errors, 422
if errors:
for error in errors['errors']:
error['status'] = "422"
error['title'] = "Validation error"
return errors, 422
if 'id' not in json_data['data']:
raise BadRequest('Missing id in "data" node',
source={'pointer': '/data/id'})
if (str(json_data['data']['id']) != str(kwargs[getattr(self._data_layer, 'url_field', 'id')])):
raise BadRequest('Value of id does not match the resource identifier in url',
source={'pointer': '/data/id'})
self.before_patch(args, kwargs, data=data)
obj = self.update_object(data, qs, kwargs)
result = schema.dump(obj).data
final_result = self.after_patch(result)
return final_result | [
"def",
"patch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"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",
",",
"kwargs",
")",
"schema",
"=",
"compute_schema",
"(",
"self",
".",
"schema",
",",
"schema_kwargs",
",",
"qs",
",",
"qs",
".",
"include",
")",
"try",
":",
"data",
",",
"errors",
"=",
"schema",
".",
"load",
"(",
"json_data",
")",
"except",
"IncorrectTypeError",
"as",
"e",
":",
"errors",
"=",
"e",
".",
"messages",
"for",
"error",
"in",
"errors",
"[",
"'errors'",
"]",
":",
"error",
"[",
"'status'",
"]",
"=",
"'409'",
"error",
"[",
"'title'",
"]",
"=",
"\"Incorrect type\"",
"return",
"errors",
",",
"409",
"except",
"ValidationError",
"as",
"e",
":",
"errors",
"=",
"e",
".",
"messages",
"for",
"message",
"in",
"errors",
"[",
"'errors'",
"]",
":",
"message",
"[",
"'status'",
"]",
"=",
"'422'",
"message",
"[",
"'title'",
"]",
"=",
"\"Validation error\"",
"return",
"errors",
",",
"422",
"if",
"errors",
":",
"for",
"error",
"in",
"errors",
"[",
"'errors'",
"]",
":",
"error",
"[",
"'status'",
"]",
"=",
"\"422\"",
"error",
"[",
"'title'",
"]",
"=",
"\"Validation error\"",
"return",
"errors",
",",
"422",
"if",
"'id'",
"not",
"in",
"json_data",
"[",
"'data'",
"]",
":",
"raise",
"BadRequest",
"(",
"'Missing id in \"data\" node'",
",",
"source",
"=",
"{",
"'pointer'",
":",
"'/data/id'",
"}",
")",
"if",
"(",
"str",
"(",
"json_data",
"[",
"'data'",
"]",
"[",
"'id'",
"]",
")",
"!=",
"str",
"(",
"kwargs",
"[",
"getattr",
"(",
"self",
".",
"_data_layer",
",",
"'url_field'",
",",
"'id'",
")",
"]",
")",
")",
":",
"raise",
"BadRequest",
"(",
"'Value of id does not match the resource identifier in url'",
",",
"source",
"=",
"{",
"'pointer'",
":",
"'/data/id'",
"}",
")",
"self",
".",
"before_patch",
"(",
"args",
",",
"kwargs",
",",
"data",
"=",
"data",
")",
"obj",
"=",
"self",
".",
"update_object",
"(",
"data",
",",
"qs",
",",
"kwargs",
")",
"result",
"=",
"schema",
".",
"dump",
"(",
"obj",
")",
".",
"data",
"final_result",
"=",
"self",
".",
"after_patch",
"(",
"result",
")",
"return",
"final_result"
] | Update an object | [
"Update",
"an",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L235-L286 |
230,031 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceDetail.delete | 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 | 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 | [
"def",
"delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"before_delete",
"(",
"args",
",",
"kwargs",
")",
"self",
".",
"delete_object",
"(",
"kwargs",
")",
"result",
"=",
"{",
"'meta'",
":",
"{",
"'message'",
":",
"'Object successfully deleted'",
"}",
"}",
"final_result",
"=",
"self",
".",
"after_delete",
"(",
"result",
")",
"return",
"final_result"
] | Delete an object | [
"Delete",
"an",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L289-L299 |
230,032 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceRelationship.get | 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,
related_type_,
related_id_field,
kwargs)
result = {'links': {'self': request.path,
'related': self.schema._declared_fields[relationship_field].get_related_url(obj)},
'data': data}
qs = QSManager(request.args, self.schema)
if qs.include:
schema = compute_schema(self.schema, dict(), qs, qs.include)
serialized_obj = schema.dump(obj)
result['included'] = serialized_obj.data.get('included', dict())
final_result = self.after_get(result)
return final_result | python | 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,
related_type_,
related_id_field,
kwargs)
result = {'links': {'self': request.path,
'related': self.schema._declared_fields[relationship_field].get_related_url(obj)},
'data': data}
qs = QSManager(request.args, self.schema)
if qs.include:
schema = compute_schema(self.schema, dict(), qs, qs.include)
serialized_obj = schema.dump(obj)
result['included'] = serialized_obj.data.get('included', dict())
final_result = self.after_get(result)
return final_result | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"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",
",",
"related_type_",
",",
"related_id_field",
",",
"kwargs",
")",
"result",
"=",
"{",
"'links'",
":",
"{",
"'self'",
":",
"request",
".",
"path",
",",
"'related'",
":",
"self",
".",
"schema",
".",
"_declared_fields",
"[",
"relationship_field",
"]",
".",
"get_related_url",
"(",
"obj",
")",
"}",
",",
"'data'",
":",
"data",
"}",
"qs",
"=",
"QSManager",
"(",
"request",
".",
"args",
",",
"self",
".",
"schema",
")",
"if",
"qs",
".",
"include",
":",
"schema",
"=",
"compute_schema",
"(",
"self",
".",
"schema",
",",
"dict",
"(",
")",
",",
"qs",
",",
"qs",
".",
"include",
")",
"serialized_obj",
"=",
"schema",
".",
"dump",
"(",
"obj",
")",
"result",
"[",
"'included'",
"]",
"=",
"serialized_obj",
".",
"data",
".",
"get",
"(",
"'included'",
",",
"dict",
"(",
")",
")",
"final_result",
"=",
"self",
".",
"after_get",
"(",
"result",
")",
"return",
"final_result"
] | Get a relationship details | [
"Get",
"a",
"relationship",
"details"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L346-L370 |
230,033 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceRelationship.patch | 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 data with a "data" route node', source={'pointer': '/data'})
if isinstance(json_data['data'], dict):
if 'type' not in json_data['data']:
raise BadRequest('Missing type in "data" node', source={'pointer': '/data/type'})
if 'id' not in json_data['data']:
raise BadRequest('Missing id in "data" node', source={'pointer': '/data/id'})
if json_data['data']['type'] != related_type_:
raise InvalidType('The type field does not match the resource type', source={'pointer': '/data/type'})
if isinstance(json_data['data'], list):
for obj in json_data['data']:
if 'type' not in obj:
raise BadRequest('Missing type in "data" node', source={'pointer': '/data/type'})
if 'id' not in obj:
raise BadRequest('Missing id in "data" node', source={'pointer': '/data/id'})
if obj['type'] != related_type_:
raise InvalidType('The type provided does not match the resource type',
source={'pointer': '/data/type'})
self.before_patch(args, kwargs, json_data=json_data)
obj_, updated = self._data_layer.update_relationship(json_data,
model_relationship_field,
related_id_field,
kwargs)
status_code = 200
result = {'meta': {'message': 'Relationship successfully updated'}}
if updated is False:
result = ''
status_code = 204
final_result = self.after_patch(result, status_code)
return final_result | python | 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 data with a "data" route node', source={'pointer': '/data'})
if isinstance(json_data['data'], dict):
if 'type' not in json_data['data']:
raise BadRequest('Missing type in "data" node', source={'pointer': '/data/type'})
if 'id' not in json_data['data']:
raise BadRequest('Missing id in "data" node', source={'pointer': '/data/id'})
if json_data['data']['type'] != related_type_:
raise InvalidType('The type field does not match the resource type', source={'pointer': '/data/type'})
if isinstance(json_data['data'], list):
for obj in json_data['data']:
if 'type' not in obj:
raise BadRequest('Missing type in "data" node', source={'pointer': '/data/type'})
if 'id' not in obj:
raise BadRequest('Missing id in "data" node', source={'pointer': '/data/id'})
if obj['type'] != related_type_:
raise InvalidType('The type provided does not match the resource type',
source={'pointer': '/data/type'})
self.before_patch(args, kwargs, json_data=json_data)
obj_, updated = self._data_layer.update_relationship(json_data,
model_relationship_field,
related_id_field,
kwargs)
status_code = 200
result = {'meta': {'message': 'Relationship successfully updated'}}
if updated is False:
result = ''
status_code = 204
final_result = self.after_patch(result, status_code)
return final_result | [
"def",
"patch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"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 data with a \"data\" route node'",
",",
"source",
"=",
"{",
"'pointer'",
":",
"'/data'",
"}",
")",
"if",
"isinstance",
"(",
"json_data",
"[",
"'data'",
"]",
",",
"dict",
")",
":",
"if",
"'type'",
"not",
"in",
"json_data",
"[",
"'data'",
"]",
":",
"raise",
"BadRequest",
"(",
"'Missing type in \"data\" node'",
",",
"source",
"=",
"{",
"'pointer'",
":",
"'/data/type'",
"}",
")",
"if",
"'id'",
"not",
"in",
"json_data",
"[",
"'data'",
"]",
":",
"raise",
"BadRequest",
"(",
"'Missing id in \"data\" node'",
",",
"source",
"=",
"{",
"'pointer'",
":",
"'/data/id'",
"}",
")",
"if",
"json_data",
"[",
"'data'",
"]",
"[",
"'type'",
"]",
"!=",
"related_type_",
":",
"raise",
"InvalidType",
"(",
"'The type field does not match the resource type'",
",",
"source",
"=",
"{",
"'pointer'",
":",
"'/data/type'",
"}",
")",
"if",
"isinstance",
"(",
"json_data",
"[",
"'data'",
"]",
",",
"list",
")",
":",
"for",
"obj",
"in",
"json_data",
"[",
"'data'",
"]",
":",
"if",
"'type'",
"not",
"in",
"obj",
":",
"raise",
"BadRequest",
"(",
"'Missing type in \"data\" node'",
",",
"source",
"=",
"{",
"'pointer'",
":",
"'/data/type'",
"}",
")",
"if",
"'id'",
"not",
"in",
"obj",
":",
"raise",
"BadRequest",
"(",
"'Missing id in \"data\" node'",
",",
"source",
"=",
"{",
"'pointer'",
":",
"'/data/id'",
"}",
")",
"if",
"obj",
"[",
"'type'",
"]",
"!=",
"related_type_",
":",
"raise",
"InvalidType",
"(",
"'The type provided does not match the resource type'",
",",
"source",
"=",
"{",
"'pointer'",
":",
"'/data/type'",
"}",
")",
"self",
".",
"before_patch",
"(",
"args",
",",
"kwargs",
",",
"json_data",
"=",
"json_data",
")",
"obj_",
",",
"updated",
"=",
"self",
".",
"_data_layer",
".",
"update_relationship",
"(",
"json_data",
",",
"model_relationship_field",
",",
"related_id_field",
",",
"kwargs",
")",
"status_code",
"=",
"200",
"result",
"=",
"{",
"'meta'",
":",
"{",
"'message'",
":",
"'Relationship successfully updated'",
"}",
"}",
"if",
"updated",
"is",
"False",
":",
"result",
"=",
"''",
"status_code",
"=",
"204",
"final_result",
"=",
"self",
".",
"after_patch",
"(",
"result",
",",
"status_code",
")",
"return",
"final_result"
] | Update a relationship | [
"Update",
"a",
"relationship"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L417-L458 |
230,034 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceRelationship._get_relationship_data | 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.__name__, relationship_field))
related_type_ = self.schema._declared_fields[relationship_field].type_
related_id_field = self.schema._declared_fields[relationship_field].id_field
model_relationship_field = get_model_field(self.schema, relationship_field)
return relationship_field, model_relationship_field, related_type_, related_id_field | python | 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.__name__, relationship_field))
related_type_ = self.schema._declared_fields[relationship_field].type_
related_id_field = self.schema._declared_fields[relationship_field].id_field
model_relationship_field = get_model_field(self.schema, relationship_field)
return relationship_field, model_relationship_field, related_type_, related_id_field | [
"def",
"_get_relationship_data",
"(",
"self",
")",
":",
"relationship_field",
"=",
"request",
".",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"if",
"relationship_field",
"not",
"in",
"get_relationships",
"(",
"self",
".",
"schema",
")",
":",
"raise",
"RelationNotFound",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"self",
".",
"schema",
".",
"__name__",
",",
"relationship_field",
")",
")",
"related_type_",
"=",
"self",
".",
"schema",
".",
"_declared_fields",
"[",
"relationship_field",
"]",
".",
"type_",
"related_id_field",
"=",
"self",
".",
"schema",
".",
"_declared_fields",
"[",
"relationship_field",
"]",
".",
"id_field",
"model_relationship_field",
"=",
"get_model_field",
"(",
"self",
".",
"schema",
",",
"relationship_field",
")",
"return",
"relationship_field",
",",
"model_relationship_field",
",",
"related_type_",
",",
"related_id_field"
] | Get useful data for relationship management | [
"Get",
"useful",
"data",
"for",
"relationship",
"management"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L504-L515 |
230,035 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | compute_schema | 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 to include data from
:return Schema schema: the schema computed
"""
# manage include_data parameter of the schema
schema_kwargs = default_kwargs
schema_kwargs['include_data'] = tuple()
# collect sub-related_includes
related_includes = {}
if include:
for include_path in include:
field = include_path.split('.')[0]
if field not in schema_cls._declared_fields:
raise InvalidInclude("{} has no attribute {}".format(schema_cls.__name__, field))
elif not isinstance(schema_cls._declared_fields[field], Relationship):
raise InvalidInclude("{} is not a relationship attribute of {}".format(field, schema_cls.__name__))
schema_kwargs['include_data'] += (field, )
if field not in related_includes:
related_includes[field] = []
if '.' in include_path:
related_includes[field] += ['.'.join(include_path.split('.')[1:])]
# make sure id field is in only parameter unless marshamllow will raise an Exception
if schema_kwargs.get('only') is not None and 'id' not in schema_kwargs['only']:
schema_kwargs['only'] += ('id',)
# create base schema instance
schema = schema_cls(**schema_kwargs)
# manage sparse fieldsets
if schema.opts.type_ in qs.fields:
tmp_only = set(schema.declared_fields.keys()) & set(qs.fields[schema.opts.type_])
if schema.only:
tmp_only &= set(schema.only)
schema.only = tuple(tmp_only)
# make sure again that id field is in only parameter unless marshamllow will raise an Exception
if schema.only is not None and 'id' not in schema.only:
schema.only += ('id',)
# manage compound documents
if include:
for include_path in include:
field = include_path.split('.')[0]
relation_field = schema.declared_fields[field]
related_schema_cls = schema.declared_fields[field].__dict__['_Relationship__schema']
related_schema_kwargs = {}
if 'context' in default_kwargs:
related_schema_kwargs['context'] = default_kwargs['context']
if isinstance(related_schema_cls, SchemaABC):
related_schema_kwargs['many'] = related_schema_cls.many
related_schema_cls = related_schema_cls.__class__
if isinstance(related_schema_cls, str):
related_schema_cls = class_registry.get_class(related_schema_cls)
related_schema = compute_schema(related_schema_cls,
related_schema_kwargs,
qs,
related_includes[field] or None)
relation_field.__dict__['_Relationship__schema'] = related_schema
return schema | python | 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 to include data from
:return Schema schema: the schema computed
"""
# manage include_data parameter of the schema
schema_kwargs = default_kwargs
schema_kwargs['include_data'] = tuple()
# collect sub-related_includes
related_includes = {}
if include:
for include_path in include:
field = include_path.split('.')[0]
if field not in schema_cls._declared_fields:
raise InvalidInclude("{} has no attribute {}".format(schema_cls.__name__, field))
elif not isinstance(schema_cls._declared_fields[field], Relationship):
raise InvalidInclude("{} is not a relationship attribute of {}".format(field, schema_cls.__name__))
schema_kwargs['include_data'] += (field, )
if field not in related_includes:
related_includes[field] = []
if '.' in include_path:
related_includes[field] += ['.'.join(include_path.split('.')[1:])]
# make sure id field is in only parameter unless marshamllow will raise an Exception
if schema_kwargs.get('only') is not None and 'id' not in schema_kwargs['only']:
schema_kwargs['only'] += ('id',)
# create base schema instance
schema = schema_cls(**schema_kwargs)
# manage sparse fieldsets
if schema.opts.type_ in qs.fields:
tmp_only = set(schema.declared_fields.keys()) & set(qs.fields[schema.opts.type_])
if schema.only:
tmp_only &= set(schema.only)
schema.only = tuple(tmp_only)
# make sure again that id field is in only parameter unless marshamllow will raise an Exception
if schema.only is not None and 'id' not in schema.only:
schema.only += ('id',)
# manage compound documents
if include:
for include_path in include:
field = include_path.split('.')[0]
relation_field = schema.declared_fields[field]
related_schema_cls = schema.declared_fields[field].__dict__['_Relationship__schema']
related_schema_kwargs = {}
if 'context' in default_kwargs:
related_schema_kwargs['context'] = default_kwargs['context']
if isinstance(related_schema_cls, SchemaABC):
related_schema_kwargs['many'] = related_schema_cls.many
related_schema_cls = related_schema_cls.__class__
if isinstance(related_schema_cls, str):
related_schema_cls = class_registry.get_class(related_schema_cls)
related_schema = compute_schema(related_schema_cls,
related_schema_kwargs,
qs,
related_includes[field] or None)
relation_field.__dict__['_Relationship__schema'] = related_schema
return schema | [
"def",
"compute_schema",
"(",
"schema_cls",
",",
"default_kwargs",
",",
"qs",
",",
"include",
")",
":",
"# manage include_data parameter of the schema",
"schema_kwargs",
"=",
"default_kwargs",
"schema_kwargs",
"[",
"'include_data'",
"]",
"=",
"tuple",
"(",
")",
"# collect sub-related_includes",
"related_includes",
"=",
"{",
"}",
"if",
"include",
":",
"for",
"include_path",
"in",
"include",
":",
"field",
"=",
"include_path",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"if",
"field",
"not",
"in",
"schema_cls",
".",
"_declared_fields",
":",
"raise",
"InvalidInclude",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"schema_cls",
".",
"__name__",
",",
"field",
")",
")",
"elif",
"not",
"isinstance",
"(",
"schema_cls",
".",
"_declared_fields",
"[",
"field",
"]",
",",
"Relationship",
")",
":",
"raise",
"InvalidInclude",
"(",
"\"{} is not a relationship attribute of {}\"",
".",
"format",
"(",
"field",
",",
"schema_cls",
".",
"__name__",
")",
")",
"schema_kwargs",
"[",
"'include_data'",
"]",
"+=",
"(",
"field",
",",
")",
"if",
"field",
"not",
"in",
"related_includes",
":",
"related_includes",
"[",
"field",
"]",
"=",
"[",
"]",
"if",
"'.'",
"in",
"include_path",
":",
"related_includes",
"[",
"field",
"]",
"+=",
"[",
"'.'",
".",
"join",
"(",
"include_path",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
":",
"]",
")",
"]",
"# make sure id field is in only parameter unless marshamllow will raise an Exception",
"if",
"schema_kwargs",
".",
"get",
"(",
"'only'",
")",
"is",
"not",
"None",
"and",
"'id'",
"not",
"in",
"schema_kwargs",
"[",
"'only'",
"]",
":",
"schema_kwargs",
"[",
"'only'",
"]",
"+=",
"(",
"'id'",
",",
")",
"# create base schema instance",
"schema",
"=",
"schema_cls",
"(",
"*",
"*",
"schema_kwargs",
")",
"# manage sparse fieldsets",
"if",
"schema",
".",
"opts",
".",
"type_",
"in",
"qs",
".",
"fields",
":",
"tmp_only",
"=",
"set",
"(",
"schema",
".",
"declared_fields",
".",
"keys",
"(",
")",
")",
"&",
"set",
"(",
"qs",
".",
"fields",
"[",
"schema",
".",
"opts",
".",
"type_",
"]",
")",
"if",
"schema",
".",
"only",
":",
"tmp_only",
"&=",
"set",
"(",
"schema",
".",
"only",
")",
"schema",
".",
"only",
"=",
"tuple",
"(",
"tmp_only",
")",
"# make sure again that id field is in only parameter unless marshamllow will raise an Exception",
"if",
"schema",
".",
"only",
"is",
"not",
"None",
"and",
"'id'",
"not",
"in",
"schema",
".",
"only",
":",
"schema",
".",
"only",
"+=",
"(",
"'id'",
",",
")",
"# manage compound documents",
"if",
"include",
":",
"for",
"include_path",
"in",
"include",
":",
"field",
"=",
"include_path",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"relation_field",
"=",
"schema",
".",
"declared_fields",
"[",
"field",
"]",
"related_schema_cls",
"=",
"schema",
".",
"declared_fields",
"[",
"field",
"]",
".",
"__dict__",
"[",
"'_Relationship__schema'",
"]",
"related_schema_kwargs",
"=",
"{",
"}",
"if",
"'context'",
"in",
"default_kwargs",
":",
"related_schema_kwargs",
"[",
"'context'",
"]",
"=",
"default_kwargs",
"[",
"'context'",
"]",
"if",
"isinstance",
"(",
"related_schema_cls",
",",
"SchemaABC",
")",
":",
"related_schema_kwargs",
"[",
"'many'",
"]",
"=",
"related_schema_cls",
".",
"many",
"related_schema_cls",
"=",
"related_schema_cls",
".",
"__class__",
"if",
"isinstance",
"(",
"related_schema_cls",
",",
"str",
")",
":",
"related_schema_cls",
"=",
"class_registry",
".",
"get_class",
"(",
"related_schema_cls",
")",
"related_schema",
"=",
"compute_schema",
"(",
"related_schema_cls",
",",
"related_schema_kwargs",
",",
"qs",
",",
"related_includes",
"[",
"field",
"]",
"or",
"None",
")",
"relation_field",
".",
"__dict__",
"[",
"'_Relationship__schema'",
"]",
"=",
"related_schema",
"return",
"schema"
] | 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 to include data from
:return Schema schema: the schema computed | [
"Compute",
"a",
"schema",
"around",
"compound",
"documents",
"and",
"sparse",
"fieldsets"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L12-L82 |
230,036 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_model_field | 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("{} has no attribute {}".format(schema.__name__, field))
if schema._declared_fields[field].attribute is not None:
return schema._declared_fields[field].attribute
return field | python | 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("{} has no attribute {}".format(schema.__name__, field))
if schema._declared_fields[field].attribute is not None:
return schema._declared_fields[field].attribute
return field | [
"def",
"get_model_field",
"(",
"schema",
",",
"field",
")",
":",
"if",
"schema",
".",
"_declared_fields",
".",
"get",
"(",
"field",
")",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"schema",
".",
"__name__",
",",
"field",
")",
")",
"if",
"schema",
".",
"_declared_fields",
"[",
"field",
"]",
".",
"attribute",
"is",
"not",
"None",
":",
"return",
"schema",
".",
"_declared_fields",
"[",
"field",
"]",
".",
"attribute",
"return",
"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 | [
"Get",
"the",
"model",
"field",
"of",
"a",
"schema",
"field"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L85-L97 |
230,037 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_nested_fields | 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_fields = []
for (key, value) in schema._declared_fields.items():
if isinstance(value, List) and isinstance(value.container, Nested):
nested_fields.append(key)
elif isinstance(value, Nested):
nested_fields.append(key)
if model_field is True:
nested_fields = [get_model_field(schema, key) for key in nested_fields]
return nested_fields | python | 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_fields = []
for (key, value) in schema._declared_fields.items():
if isinstance(value, List) and isinstance(value.container, Nested):
nested_fields.append(key)
elif isinstance(value, Nested):
nested_fields.append(key)
if model_field is True:
nested_fields = [get_model_field(schema, key) for key in nested_fields]
return nested_fields | [
"def",
"get_nested_fields",
"(",
"schema",
",",
"model_field",
"=",
"False",
")",
":",
"nested_fields",
"=",
"[",
"]",
"for",
"(",
"key",
",",
"value",
")",
"in",
"schema",
".",
"_declared_fields",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"List",
")",
"and",
"isinstance",
"(",
"value",
".",
"container",
",",
"Nested",
")",
":",
"nested_fields",
".",
"append",
"(",
"key",
")",
"elif",
"isinstance",
"(",
"value",
",",
"Nested",
")",
":",
"nested_fields",
".",
"append",
"(",
"key",
")",
"if",
"model_field",
"is",
"True",
":",
"nested_fields",
"=",
"[",
"get_model_field",
"(",
"schema",
",",
"key",
")",
"for",
"key",
"in",
"nested_fields",
"]",
"return",
"nested_fields"
] | 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 | [
"Return",
"nested",
"fields",
"of",
"a",
"schema",
"to",
"support",
"a",
"join"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L99-L117 |
230,038 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_relationships | 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)]
if model_field is True:
relationships = [get_model_field(schema, key) for key in relationships]
return relationships | python | 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)]
if model_field is True:
relationships = [get_model_field(schema, key) for key in relationships]
return relationships | [
"def",
"get_relationships",
"(",
"schema",
",",
"model_field",
"=",
"False",
")",
":",
"relationships",
"=",
"[",
"key",
"for",
"(",
"key",
",",
"value",
")",
"in",
"schema",
".",
"_declared_fields",
".",
"items",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"Relationship",
")",
"]",
"if",
"model_field",
"is",
"True",
":",
"relationships",
"=",
"[",
"get_model_field",
"(",
"schema",
",",
"key",
")",
"for",
"key",
"in",
"relationships",
"]",
"return",
"relationships"
] | Return relationship fields of a schema
:param Schema schema: a marshmallow schema
:param list: list of relationship fields of a schema | [
"Return",
"relationship",
"fields",
"of",
"a",
"schema"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L119-L130 |
230,039 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_schema_from_type | 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:
return cls[0]
except Exception:
pass
raise Exception("Couldn't find schema for type: {}".format(resource_type)) | python | 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:
return cls[0]
except Exception:
pass
raise Exception("Couldn't find schema for type: {}".format(resource_type)) | [
"def",
"get_schema_from_type",
"(",
"resource_type",
")",
":",
"for",
"cls_name",
",",
"cls",
"in",
"class_registry",
".",
"_registry",
".",
"items",
"(",
")",
":",
"try",
":",
"if",
"cls",
"[",
"0",
"]",
".",
"opts",
".",
"type_",
"==",
"resource_type",
":",
"return",
"cls",
"[",
"0",
"]",
"except",
"Exception",
":",
"pass",
"raise",
"Exception",
"(",
"\"Couldn't find schema for type: {}\"",
".",
"format",
"(",
"resource_type",
")",
")"
] | Retrieve a schema from the registry by his type
:param str type_: the type of the resource
:return Schema: the schema class | [
"Retrieve",
"a",
"schema",
"from",
"the",
"registry",
"by",
"his",
"type"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L143-L156 |
230,040 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_schema_field | 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) in schema._declared_fields.items()}
for key, value in schema_fields_to_model.items():
if value == field:
return key
raise Exception("Couldn't find schema field from {}".format(field)) | python | 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) in schema._declared_fields.items()}
for key, value in schema_fields_to_model.items():
if value == field:
return key
raise Exception("Couldn't find schema field from {}".format(field)) | [
"def",
"get_schema_field",
"(",
"schema",
",",
"field",
")",
":",
"schema_fields_to_model",
"=",
"{",
"key",
":",
"get_model_field",
"(",
"schema",
",",
"key",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"schema",
".",
"_declared_fields",
".",
"items",
"(",
")",
"}",
"for",
"key",
",",
"value",
"in",
"schema_fields_to_model",
".",
"items",
"(",
")",
":",
"if",
"value",
"==",
"field",
":",
"return",
"key",
"raise",
"Exception",
"(",
"\"Couldn't find schema field from {}\"",
".",
"format",
"(",
"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 | [
"Get",
"the",
"schema",
"field",
"of",
"a",
"model",
"field"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L159-L171 |
230,041 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/base.py | BaseDataLayer.bound_rewritable_methods | 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:
setattr(self, key, types.MethodType(value, self)) | python | 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:
setattr(self, key, types.MethodType(value, self)) | [
"def",
"bound_rewritable_methods",
"(",
"self",
",",
"methods",
")",
":",
"for",
"key",
",",
"value",
"in",
"methods",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self",
".",
"REWRITABLE_METHODS",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"types",
".",
"MethodType",
"(",
"value",
",",
"self",
")",
")"
] | Bound additional methods to current instance
:param class meta: information from Meta class used to configure the data layer instance | [
"Bound",
"additional",
"methods",
"to",
"current",
"instance"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/base.py#L318-L325 |
230,042 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | create_filters | 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 filter_info:
filters.append(Node(model, filter_, resource, resource.schema).resolve())
return filters | python | 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 filter_info:
filters.append(Node(model, filter_, resource, resource.schema).resolve())
return filters | [
"def",
"create_filters",
"(",
"model",
",",
"filter_info",
",",
"resource",
")",
":",
"filters",
"=",
"[",
"]",
"for",
"filter_",
"in",
"filter_info",
":",
"filters",
".",
"append",
"(",
"Node",
"(",
"model",
",",
"filter_",
",",
"resource",
",",
"resource",
".",
"schema",
")",
".",
"resolve",
"(",
")",
")",
"return",
"filters"
] | 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 | [
"Apply",
"filters",
"from",
"filters",
"information",
"to",
"base",
"query"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L11-L22 |
230,043 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.resolve | 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.resource, self.related_schema).resolve()
if '__' in self.filter_.get('name', ''):
value = {self.filter_['name'].split('__')[1]: value}
if isinstance(value, dict):
return getattr(self.column, self.operator)(**value)
else:
return getattr(self.column, self.operator)(value)
if 'or' in self.filter_:
return or_(Node(self.model, filt, self.resource, self.schema).resolve() for filt in self.filter_['or'])
if 'and' in self.filter_:
return and_(Node(self.model, filt, self.resource, self.schema).resolve() for filt in self.filter_['and'])
if 'not' in self.filter_:
return not_(Node(self.model, self.filter_['not'], self.resource, self.schema).resolve()) | python | 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.resource, self.related_schema).resolve()
if '__' in self.filter_.get('name', ''):
value = {self.filter_['name'].split('__')[1]: value}
if isinstance(value, dict):
return getattr(self.column, self.operator)(**value)
else:
return getattr(self.column, self.operator)(value)
if 'or' in self.filter_:
return or_(Node(self.model, filt, self.resource, self.schema).resolve() for filt in self.filter_['or'])
if 'and' in self.filter_:
return and_(Node(self.model, filt, self.resource, self.schema).resolve() for filt in self.filter_['and'])
if 'not' in self.filter_:
return not_(Node(self.model, self.filter_['not'], self.resource, self.schema).resolve()) | [
"def",
"resolve",
"(",
"self",
")",
":",
"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",
".",
"resource",
",",
"self",
".",
"related_schema",
")",
".",
"resolve",
"(",
")",
"if",
"'__'",
"in",
"self",
".",
"filter_",
".",
"get",
"(",
"'name'",
",",
"''",
")",
":",
"value",
"=",
"{",
"self",
".",
"filter_",
"[",
"'name'",
"]",
".",
"split",
"(",
"'__'",
")",
"[",
"1",
"]",
":",
"value",
"}",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"column",
",",
"self",
".",
"operator",
")",
"(",
"*",
"*",
"value",
")",
"else",
":",
"return",
"getattr",
"(",
"self",
".",
"column",
",",
"self",
".",
"operator",
")",
"(",
"value",
")",
"if",
"'or'",
"in",
"self",
".",
"filter_",
":",
"return",
"or_",
"(",
"Node",
"(",
"self",
".",
"model",
",",
"filt",
",",
"self",
".",
"resource",
",",
"self",
".",
"schema",
")",
".",
"resolve",
"(",
")",
"for",
"filt",
"in",
"self",
".",
"filter_",
"[",
"'or'",
"]",
")",
"if",
"'and'",
"in",
"self",
".",
"filter_",
":",
"return",
"and_",
"(",
"Node",
"(",
"self",
".",
"model",
",",
"filt",
",",
"self",
".",
"resource",
",",
"self",
".",
"schema",
")",
".",
"resolve",
"(",
")",
"for",
"filt",
"in",
"self",
".",
"filter_",
"[",
"'and'",
"]",
")",
"if",
"'not'",
"in",
"self",
".",
"filter_",
":",
"return",
"not_",
"(",
"Node",
"(",
"self",
".",
"model",
",",
"self",
".",
"filter_",
"[",
"'not'",
"]",
",",
"self",
".",
"resource",
",",
"self",
".",
"schema",
")",
".",
"resolve",
"(",
")",
")"
] | Create filter for a particular node of the filter tree | [
"Create",
"filter",
"for",
"a",
"particular",
"node",
"of",
"the",
"filter",
"tree"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L41-L62 |
230,044 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.name | 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:
name = name.split('__')[0]
if name not in self.schema._declared_fields:
raise InvalidFilters("{} has no attribute {}".format(self.schema.__name__, name))
return name | python | 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:
name = name.split('__')[0]
if name not in self.schema._declared_fields:
raise InvalidFilters("{} has no attribute {}".format(self.schema.__name__, name))
return name | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"filter_",
".",
"get",
"(",
"'name'",
")",
"if",
"name",
"is",
"None",
":",
"raise",
"InvalidFilters",
"(",
"\"Can't find name of a filter\"",
")",
"if",
"'__'",
"in",
"name",
":",
"name",
"=",
"name",
".",
"split",
"(",
"'__'",
")",
"[",
"0",
"]",
"if",
"name",
"not",
"in",
"self",
".",
"schema",
".",
"_declared_fields",
":",
"raise",
"InvalidFilters",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"self",
".",
"schema",
".",
"__name__",
",",
"name",
")",
")",
"return",
"name"
] | Return the name of the node or raise a BadRequest exception
:return str: the name of the field to filter on | [
"Return",
"the",
"name",
"of",
"the",
"node",
"or",
"raise",
"a",
"BadRequest",
"exception"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L65-L81 |
230,045 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.column | 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:
return getattr(self.model, model_field)
except AttributeError:
raise InvalidFilters("{} has no attribute {}".format(self.model.__name__, model_field)) | python | 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:
return getattr(self.model, model_field)
except AttributeError:
raise InvalidFilters("{} has no attribute {}".format(self.model.__name__, model_field)) | [
"def",
"column",
"(",
"self",
")",
":",
"field",
"=",
"self",
".",
"name",
"model_field",
"=",
"get_model_field",
"(",
"self",
".",
"schema",
",",
"field",
")",
"try",
":",
"return",
"getattr",
"(",
"self",
".",
"model",
",",
"model_field",
")",
"except",
"AttributeError",
":",
"raise",
"InvalidFilters",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"self",
".",
"model",
".",
"__name__",
",",
"model_field",
")",
")"
] | Get the column object
:param DeclarativeMeta model: the model
:param str field: the field
:return InstrumentedAttribute: the column to filter on | [
"Get",
"the",
"column",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L95-L109 |
230,046 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.operator | 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
raise InvalidFilters("{} has no operator {}".format(self.column.key, self.op)) | python | 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
raise InvalidFilters("{} has no operator {}".format(self.column.key, self.op)) | [
"def",
"operator",
"(",
"self",
")",
":",
"operators",
"=",
"(",
"self",
".",
"op",
",",
"self",
".",
"op",
"+",
"'_'",
",",
"'__'",
"+",
"self",
".",
"op",
"+",
"'__'",
")",
"for",
"op",
"in",
"operators",
":",
"if",
"hasattr",
"(",
"self",
".",
"column",
",",
"op",
")",
":",
"return",
"op",
"raise",
"InvalidFilters",
"(",
"\"{} has no operator {}\"",
".",
"format",
"(",
"self",
".",
"column",
".",
"key",
",",
"self",
".",
"op",
")",
")"
] | Get the function operator from his name
:return callable: a callable to make operation on a column | [
"Get",
"the",
"function",
"operator",
"from",
"his",
"name"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L112-L123 |
230,047 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.value | 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("{} has no attribute {}".format(self.model.__name__, self.filter_['field']))
else:
return result
else:
if 'val' not in self.filter_:
raise InvalidFilters("Can't find value or field in a filter")
return self.filter_['val'] | python | 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("{} has no attribute {}".format(self.model.__name__, self.filter_['field']))
else:
return result
else:
if 'val' not in self.filter_:
raise InvalidFilters("Can't find value or field in a filter")
return self.filter_['val'] | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"filter_",
".",
"get",
"(",
"'field'",
")",
"is",
"not",
"None",
":",
"try",
":",
"result",
"=",
"getattr",
"(",
"self",
".",
"model",
",",
"self",
".",
"filter_",
"[",
"'field'",
"]",
")",
"except",
"AttributeError",
":",
"raise",
"InvalidFilters",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"self",
".",
"model",
".",
"__name__",
",",
"self",
".",
"filter_",
"[",
"'field'",
"]",
")",
")",
"else",
":",
"return",
"result",
"else",
":",
"if",
"'val'",
"not",
"in",
"self",
".",
"filter_",
":",
"raise",
"InvalidFilters",
"(",
"\"Can't find value or field in a filter\"",
")",
"return",
"self",
".",
"filter_",
"[",
"'val'",
"]"
] | Get the value to filter on
:return: the value to filter on | [
"Get",
"the",
"value",
"to",
"filter",
"on"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L126-L142 |
230,048 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.related_model | 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 attribute {}".format(self.schema.__name__, relationship_field))
return getattr(self.model, get_model_field(self.schema, relationship_field)).property.mapper.class_ | python | 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 attribute {}".format(self.schema.__name__, relationship_field))
return getattr(self.model, get_model_field(self.schema, relationship_field)).property.mapper.class_ | [
"def",
"related_model",
"(",
"self",
")",
":",
"relationship_field",
"=",
"self",
".",
"name",
"if",
"relationship_field",
"not",
"in",
"get_relationships",
"(",
"self",
".",
"schema",
")",
":",
"raise",
"InvalidFilters",
"(",
"\"{} has no relationship attribute {}\"",
".",
"format",
"(",
"self",
".",
"schema",
".",
"__name__",
",",
"relationship_field",
")",
")",
"return",
"getattr",
"(",
"self",
".",
"model",
",",
"get_model_field",
"(",
"self",
".",
"schema",
",",
"relationship_field",
")",
")",
".",
"property",
".",
"mapper",
".",
"class_"
] | Get the related model of a relationship field
:return DeclarativeMeta: the related model | [
"Get",
"the",
"related",
"model",
"of",
"a",
"relationship",
"field"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L145-L155 |
230,049 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.related_schema | 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 {}".format(self.schema.__name__, relationship_field))
return self.schema._declared_fields[relationship_field].schema.__class__ | python | 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 {}".format(self.schema.__name__, relationship_field))
return self.schema._declared_fields[relationship_field].schema.__class__ | [
"def",
"related_schema",
"(",
"self",
")",
":",
"relationship_field",
"=",
"self",
".",
"name",
"if",
"relationship_field",
"not",
"in",
"get_relationships",
"(",
"self",
".",
"schema",
")",
":",
"raise",
"InvalidFilters",
"(",
"\"{} has no relationship attribute {}\"",
".",
"format",
"(",
"self",
".",
"schema",
".",
"__name__",
",",
"relationship_field",
")",
")",
"return",
"self",
".",
"schema",
".",
"_declared_fields",
"[",
"relationship_field",
"]",
".",
"schema",
".",
"__class__"
] | Get the related schema of a relationship field
:return Schema: the related schema | [
"Get",
"the",
"related",
"schema",
"of",
"a",
"relationship",
"field"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L158-L168 |
230,050 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.init_app | 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
for resource in self.resources:
self.route(resource['resource'],
resource['view'],
*resource['urls'],
url_rule_options=resource['url_rule_options'])
if self.blueprint is not None:
self.app.register_blueprint(self.blueprint)
if additional_blueprints is not None:
for blueprint in additional_blueprints:
self.app.register_blueprint(blueprint)
self.app.config.setdefault('PAGE_SIZE', 30) | python | 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
for resource in self.resources:
self.route(resource['resource'],
resource['view'],
*resource['urls'],
url_rule_options=resource['url_rule_options'])
if self.blueprint is not None:
self.app.register_blueprint(self.blueprint)
if additional_blueprints is not None:
for blueprint in additional_blueprints:
self.app.register_blueprint(blueprint)
self.app.config.setdefault('PAGE_SIZE', 30) | [
"def",
"init_app",
"(",
"self",
",",
"app",
"=",
"None",
",",
"blueprint",
"=",
"None",
",",
"additional_blueprints",
"=",
"None",
")",
":",
"if",
"app",
"is",
"not",
"None",
":",
"self",
".",
"app",
"=",
"app",
"if",
"blueprint",
"is",
"not",
"None",
":",
"self",
".",
"blueprint",
"=",
"blueprint",
"for",
"resource",
"in",
"self",
".",
"resources",
":",
"self",
".",
"route",
"(",
"resource",
"[",
"'resource'",
"]",
",",
"resource",
"[",
"'view'",
"]",
",",
"*",
"resource",
"[",
"'urls'",
"]",
",",
"url_rule_options",
"=",
"resource",
"[",
"'url_rule_options'",
"]",
")",
"if",
"self",
".",
"blueprint",
"is",
"not",
"None",
":",
"self",
".",
"app",
".",
"register_blueprint",
"(",
"self",
".",
"blueprint",
")",
"if",
"additional_blueprints",
"is",
"not",
"None",
":",
"for",
"blueprint",
"in",
"additional_blueprints",
":",
"self",
".",
"app",
".",
"register_blueprint",
"(",
"blueprint",
")",
"self",
".",
"app",
".",
"config",
".",
"setdefault",
"(",
"'PAGE_SIZE'",
",",
"30",
")"
] | Update flask application with our api
:param Application app: a flask application | [
"Update",
"flask",
"application",
"with",
"our",
"api"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L35-L59 |
230,051 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.route | 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 the route
"""
resource.view = view
url_rule_options = kwargs.get('url_rule_options') or dict()
view_func = resource.as_view(view)
if 'blueprint' in kwargs:
resource.view = '.'.join([kwargs['blueprint'].name, resource.view])
for url in urls:
kwargs['blueprint'].add_url_rule(url, view_func=view_func, **url_rule_options)
elif self.blueprint is not None:
resource.view = '.'.join([self.blueprint.name, resource.view])
for url in urls:
self.blueprint.add_url_rule(url, view_func=view_func, **url_rule_options)
elif self.app is not None:
for url in urls:
self.app.add_url_rule(url, view_func=view_func, **url_rule_options)
else:
self.resources.append({'resource': resource,
'view': view,
'urls': urls,
'url_rule_options': url_rule_options})
self.resource_registry.append(resource) | python | 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 the route
"""
resource.view = view
url_rule_options = kwargs.get('url_rule_options') or dict()
view_func = resource.as_view(view)
if 'blueprint' in kwargs:
resource.view = '.'.join([kwargs['blueprint'].name, resource.view])
for url in urls:
kwargs['blueprint'].add_url_rule(url, view_func=view_func, **url_rule_options)
elif self.blueprint is not None:
resource.view = '.'.join([self.blueprint.name, resource.view])
for url in urls:
self.blueprint.add_url_rule(url, view_func=view_func, **url_rule_options)
elif self.app is not None:
for url in urls:
self.app.add_url_rule(url, view_func=view_func, **url_rule_options)
else:
self.resources.append({'resource': resource,
'view': view,
'urls': urls,
'url_rule_options': url_rule_options})
self.resource_registry.append(resource) | [
"def",
"route",
"(",
"self",
",",
"resource",
",",
"view",
",",
"*",
"urls",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
".",
"view",
"=",
"view",
"url_rule_options",
"=",
"kwargs",
".",
"get",
"(",
"'url_rule_options'",
")",
"or",
"dict",
"(",
")",
"view_func",
"=",
"resource",
".",
"as_view",
"(",
"view",
")",
"if",
"'blueprint'",
"in",
"kwargs",
":",
"resource",
".",
"view",
"=",
"'.'",
".",
"join",
"(",
"[",
"kwargs",
"[",
"'blueprint'",
"]",
".",
"name",
",",
"resource",
".",
"view",
"]",
")",
"for",
"url",
"in",
"urls",
":",
"kwargs",
"[",
"'blueprint'",
"]",
".",
"add_url_rule",
"(",
"url",
",",
"view_func",
"=",
"view_func",
",",
"*",
"*",
"url_rule_options",
")",
"elif",
"self",
".",
"blueprint",
"is",
"not",
"None",
":",
"resource",
".",
"view",
"=",
"'.'",
".",
"join",
"(",
"[",
"self",
".",
"blueprint",
".",
"name",
",",
"resource",
".",
"view",
"]",
")",
"for",
"url",
"in",
"urls",
":",
"self",
".",
"blueprint",
".",
"add_url_rule",
"(",
"url",
",",
"view_func",
"=",
"view_func",
",",
"*",
"*",
"url_rule_options",
")",
"elif",
"self",
".",
"app",
"is",
"not",
"None",
":",
"for",
"url",
"in",
"urls",
":",
"self",
".",
"app",
".",
"add_url_rule",
"(",
"url",
",",
"view_func",
"=",
"view_func",
",",
"*",
"*",
"url_rule_options",
")",
"else",
":",
"self",
".",
"resources",
".",
"append",
"(",
"{",
"'resource'",
":",
"resource",
",",
"'view'",
":",
"view",
",",
"'urls'",
":",
"urls",
",",
"'url_rule_options'",
":",
"url_rule_options",
"}",
")",
"self",
".",
"resource_registry",
".",
"append",
"(",
"resource",
")"
] | 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 the route | [
"Create",
"an",
"api",
"view",
"."
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L61-L91 |
230,052 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.oauth_manager | 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].view_class
if not getattr(resource, 'disable_oauth'):
scopes = request.args.get('scopes')
if getattr(resource, 'schema'):
scopes = [self.build_scope(resource, request.method)]
elif scopes:
scopes = scopes.split(',')
if scopes:
scopes = scopes.split(',')
valid, req = oauth_manager.verify_request(scopes)
for func in oauth_manager._after_request_funcs:
valid, req = func(valid, req)
if not valid:
if oauth_manager._invalid_response:
return oauth_manager._invalid_response(req)
return abort(401)
request.oauth = req | python | 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].view_class
if not getattr(resource, 'disable_oauth'):
scopes = request.args.get('scopes')
if getattr(resource, 'schema'):
scopes = [self.build_scope(resource, request.method)]
elif scopes:
scopes = scopes.split(',')
if scopes:
scopes = scopes.split(',')
valid, req = oauth_manager.verify_request(scopes)
for func in oauth_manager._after_request_funcs:
valid, req = func(valid, req)
if not valid:
if oauth_manager._invalid_response:
return oauth_manager._invalid_response(req)
return abort(401)
request.oauth = req | [
"def",
"oauth_manager",
"(",
"self",
",",
"oauth_manager",
")",
":",
"@",
"self",
".",
"app",
".",
"before_request",
"def",
"before_request",
"(",
")",
":",
"endpoint",
"=",
"request",
".",
"endpoint",
"resource",
"=",
"self",
".",
"app",
".",
"view_functions",
"[",
"endpoint",
"]",
".",
"view_class",
"if",
"not",
"getattr",
"(",
"resource",
",",
"'disable_oauth'",
")",
":",
"scopes",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'scopes'",
")",
"if",
"getattr",
"(",
"resource",
",",
"'schema'",
")",
":",
"scopes",
"=",
"[",
"self",
".",
"build_scope",
"(",
"resource",
",",
"request",
".",
"method",
")",
"]",
"elif",
"scopes",
":",
"scopes",
"=",
"scopes",
".",
"split",
"(",
"','",
")",
"if",
"scopes",
":",
"scopes",
"=",
"scopes",
".",
"split",
"(",
"','",
")",
"valid",
",",
"req",
"=",
"oauth_manager",
".",
"verify_request",
"(",
"scopes",
")",
"for",
"func",
"in",
"oauth_manager",
".",
"_after_request_funcs",
":",
"valid",
",",
"req",
"=",
"func",
"(",
"valid",
",",
"req",
")",
"if",
"not",
"valid",
":",
"if",
"oauth_manager",
".",
"_invalid_response",
":",
"return",
"oauth_manager",
".",
"_invalid_response",
"(",
"req",
")",
"return",
"abort",
"(",
"401",
")",
"request",
".",
"oauth",
"=",
"req"
] | Use the oauth manager to enable oauth for API
:param oauth_manager: the oauth manager | [
"Use",
"the",
"oauth",
"manager",
"to",
"enable",
"oauth",
"for",
"API"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L93-L124 |
230,053 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.build_scope | 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':
prefix = 'list'
else:
method_to_prefix = {'GET': 'get',
'POST': 'create',
'PATCH': 'update',
'DELETE': 'delete'}
prefix = method_to_prefix[method]
if ResourceRelationship in inspect.getmro(resource):
prefix = '_'.join([prefix, 'relationship'])
return '_'.join([prefix, resource.schema.opts.type_]) | python | 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':
prefix = 'list'
else:
method_to_prefix = {'GET': 'get',
'POST': 'create',
'PATCH': 'update',
'DELETE': 'delete'}
prefix = method_to_prefix[method]
if ResourceRelationship in inspect.getmro(resource):
prefix = '_'.join([prefix, 'relationship'])
return '_'.join([prefix, resource.schema.opts.type_]) | [
"def",
"build_scope",
"(",
"resource",
",",
"method",
")",
":",
"if",
"ResourceList",
"in",
"inspect",
".",
"getmro",
"(",
"resource",
")",
"and",
"method",
"==",
"'GET'",
":",
"prefix",
"=",
"'list'",
"else",
":",
"method_to_prefix",
"=",
"{",
"'GET'",
":",
"'get'",
",",
"'POST'",
":",
"'create'",
",",
"'PATCH'",
":",
"'update'",
",",
"'DELETE'",
":",
"'delete'",
"}",
"prefix",
"=",
"method_to_prefix",
"[",
"method",
"]",
"if",
"ResourceRelationship",
"in",
"inspect",
".",
"getmro",
"(",
"resource",
")",
":",
"prefix",
"=",
"'_'",
".",
"join",
"(",
"[",
"prefix",
",",
"'relationship'",
"]",
")",
"return",
"'_'",
".",
"join",
"(",
"[",
"prefix",
",",
"resource",
".",
"schema",
".",
"opts",
".",
"type_",
"]",
")"
] | 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 | [
"Compute",
"the",
"name",
"of",
"the",
"scope",
"for",
"oauth"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L127-L146 |
230,054 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.permission_manager | 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(resource, 'disable_permission', None) is not True:
for method in getattr(resource, 'methods', ('GET', 'POST', 'PATCH', 'DELETE')):
setattr(resource,
method.lower(),
self.has_permission()(getattr(resource, method.lower()))) | python | 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(resource, 'disable_permission', None) is not True:
for method in getattr(resource, 'methods', ('GET', 'POST', 'PATCH', 'DELETE')):
setattr(resource,
method.lower(),
self.has_permission()(getattr(resource, method.lower()))) | [
"def",
"permission_manager",
"(",
"self",
",",
"permission_manager",
")",
":",
"self",
".",
"check_permissions",
"=",
"permission_manager",
"for",
"resource",
"in",
"self",
".",
"resource_registry",
":",
"if",
"getattr",
"(",
"resource",
",",
"'disable_permission'",
",",
"None",
")",
"is",
"not",
"True",
":",
"for",
"method",
"in",
"getattr",
"(",
"resource",
",",
"'methods'",
",",
"(",
"'GET'",
",",
"'POST'",
",",
"'PATCH'",
",",
"'DELETE'",
")",
")",
":",
"setattr",
"(",
"resource",
",",
"method",
".",
"lower",
"(",
")",
",",
"self",
".",
"has_permission",
"(",
")",
"(",
"getattr",
"(",
"resource",
",",
"method",
".",
"lower",
"(",
")",
")",
")",
")"
] | Use permission manager to enable permission for API
:param callable permission_manager: the permission manager | [
"Use",
"permission",
"manager",
"to",
"enable",
"permission",
"for",
"API"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L148-L160 |
230,055 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.has_permission | 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_formatter
def decorated(*view_args, **view_kwargs):
self.check_permissions(view, view_args, view_kwargs, *args, **kwargs)
return view(*view_args, **view_kwargs)
decorated._has_permissions_decorator = True
return decorated
return wrapper | python | 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_formatter
def decorated(*view_args, **view_kwargs):
self.check_permissions(view, view_args, view_kwargs, *args, **kwargs)
return view(*view_args, **view_kwargs)
decorated._has_permissions_decorator = True
return decorated
return wrapper | [
"def",
"has_permission",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrapper",
"(",
"view",
")",
":",
"if",
"getattr",
"(",
"view",
",",
"'_has_permissions_decorator'",
",",
"False",
")",
"is",
"True",
":",
"return",
"view",
"@",
"wraps",
"(",
"view",
")",
"@",
"jsonapi_exception_formatter",
"def",
"decorated",
"(",
"*",
"view_args",
",",
"*",
"*",
"view_kwargs",
")",
":",
"self",
".",
"check_permissions",
"(",
"view",
",",
"view_args",
",",
"view_kwargs",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"view",
"(",
"*",
"view_args",
",",
"*",
"*",
"view_kwargs",
")",
"decorated",
".",
"_has_permissions_decorator",
"=",
"True",
"return",
"decorated",
"return",
"wrapper"
] | Decorator used to check permissions before to call resource manager method | [
"Decorator",
"used",
"to",
"check",
"permissions",
"before",
"to",
"call",
"resource",
"manager",
"method"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L162-L175 |
230,056 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/decorators.py | check_headers | 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.headers and\
'application/vnd.api+json' in request.headers['Content-Type'] and\
request.headers['Content-Type'] != 'application/vnd.api+json':
error = json.dumps(jsonapi_errors([{'source': '',
'detail': "Content-Type header must be application/vnd.api+json",
'title': 'Invalid request header',
'status': '415'}]), cls=JSONEncoder)
return make_response(error, 415, {'Content-Type': 'application/vnd.api+json'})
if 'Accept' in request.headers:
flag = False
for accept in request.headers['Accept'].split(','):
if accept.strip() == 'application/vnd.api+json':
flag = False
break
if 'application/vnd.api+json' in accept and accept.strip() != 'application/vnd.api+json':
flag = True
if flag is True:
error = json.dumps(jsonapi_errors([{'source': '',
'detail': ('Accept header must be application/vnd.api+json without'
'media type parameters'),
'title': 'Invalid request header',
'status': '406'}]), cls=JSONEncoder)
return make_response(error, 406, {'Content-Type': 'application/vnd.api+json'})
return func(*args, **kwargs)
return wrapper | python | 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.headers and\
'application/vnd.api+json' in request.headers['Content-Type'] and\
request.headers['Content-Type'] != 'application/vnd.api+json':
error = json.dumps(jsonapi_errors([{'source': '',
'detail': "Content-Type header must be application/vnd.api+json",
'title': 'Invalid request header',
'status': '415'}]), cls=JSONEncoder)
return make_response(error, 415, {'Content-Type': 'application/vnd.api+json'})
if 'Accept' in request.headers:
flag = False
for accept in request.headers['Accept'].split(','):
if accept.strip() == 'application/vnd.api+json':
flag = False
break
if 'application/vnd.api+json' in accept and accept.strip() != 'application/vnd.api+json':
flag = True
if flag is True:
error = json.dumps(jsonapi_errors([{'source': '',
'detail': ('Accept header must be application/vnd.api+json without'
'media type parameters'),
'title': 'Invalid request header',
'status': '406'}]), cls=JSONEncoder)
return make_response(error, 406, {'Content-Type': 'application/vnd.api+json'})
return func(*args, **kwargs)
return wrapper | [
"def",
"check_headers",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
".",
"method",
"in",
"(",
"'POST'",
",",
"'PATCH'",
")",
":",
"if",
"'Content-Type'",
"in",
"request",
".",
"headers",
"and",
"'application/vnd.api+json'",
"in",
"request",
".",
"headers",
"[",
"'Content-Type'",
"]",
"and",
"request",
".",
"headers",
"[",
"'Content-Type'",
"]",
"!=",
"'application/vnd.api+json'",
":",
"error",
"=",
"json",
".",
"dumps",
"(",
"jsonapi_errors",
"(",
"[",
"{",
"'source'",
":",
"''",
",",
"'detail'",
":",
"\"Content-Type header must be application/vnd.api+json\"",
",",
"'title'",
":",
"'Invalid request header'",
",",
"'status'",
":",
"'415'",
"}",
"]",
")",
",",
"cls",
"=",
"JSONEncoder",
")",
"return",
"make_response",
"(",
"error",
",",
"415",
",",
"{",
"'Content-Type'",
":",
"'application/vnd.api+json'",
"}",
")",
"if",
"'Accept'",
"in",
"request",
".",
"headers",
":",
"flag",
"=",
"False",
"for",
"accept",
"in",
"request",
".",
"headers",
"[",
"'Accept'",
"]",
".",
"split",
"(",
"','",
")",
":",
"if",
"accept",
".",
"strip",
"(",
")",
"==",
"'application/vnd.api+json'",
":",
"flag",
"=",
"False",
"break",
"if",
"'application/vnd.api+json'",
"in",
"accept",
"and",
"accept",
".",
"strip",
"(",
")",
"!=",
"'application/vnd.api+json'",
":",
"flag",
"=",
"True",
"if",
"flag",
"is",
"True",
":",
"error",
"=",
"json",
".",
"dumps",
"(",
"jsonapi_errors",
"(",
"[",
"{",
"'source'",
":",
"''",
",",
"'detail'",
":",
"(",
"'Accept header must be application/vnd.api+json without'",
"'media type parameters'",
")",
",",
"'title'",
":",
"'Invalid request header'",
",",
"'status'",
":",
"'406'",
"}",
"]",
")",
",",
"cls",
"=",
"JSONEncoder",
")",
"return",
"make_response",
"(",
"error",
",",
"406",
",",
"{",
"'Content-Type'",
":",
"'application/vnd.api+json'",
"}",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | Check headers according to jsonapi reference
:param callable func: the function to decorate
:return callable: the wrapped function | [
"Check",
"headers",
"according",
"to",
"jsonapi",
"reference"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/decorators.py#L15-L48 |
230,057 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/decorators.py | check_method_requirements | 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 {method} method"
error_data = {'cls': args[0].__class__.__name__, 'method': request.method.lower()}
if request.method != 'DELETE':
if not hasattr(args[0], 'schema'):
error_data.update({'error_field': 'a schema class'})
raise Exception(error_message.format(**error_data))
return func(*args, **kwargs)
return wrapper | python | 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 {method} method"
error_data = {'cls': args[0].__class__.__name__, 'method': request.method.lower()}
if request.method != 'DELETE':
if not hasattr(args[0], 'schema'):
error_data.update({'error_field': 'a schema class'})
raise Exception(error_message.format(**error_data))
return func(*args, **kwargs)
return wrapper | [
"def",
"check_method_requirements",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"error_message",
"=",
"\"You must provide {error_field} in {cls} to get access to the default {method} method\"",
"error_data",
"=",
"{",
"'cls'",
":",
"args",
"[",
"0",
"]",
".",
"__class__",
".",
"__name__",
",",
"'method'",
":",
"request",
".",
"method",
".",
"lower",
"(",
")",
"}",
"if",
"request",
".",
"method",
"!=",
"'DELETE'",
":",
"if",
"not",
"hasattr",
"(",
"args",
"[",
"0",
"]",
",",
"'schema'",
")",
":",
"error_data",
".",
"update",
"(",
"{",
"'error_field'",
":",
"'a schema class'",
"}",
")",
"raise",
"Exception",
"(",
"error_message",
".",
"format",
"(",
"*",
"*",
"error_data",
")",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] | Check methods requirements
:param callable func: the function to decorate
:return callable: the wrapped function | [
"Check",
"methods",
"requirements"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/decorators.py#L51-L68 |
230,058 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.create_object | 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(data, view_kwargs)
relationship_fields = get_relationships(self.resource.schema, model_field=True)
nested_fields = get_nested_fields(self.resource.schema, model_field=True)
join_fields = relationship_fields + nested_fields
obj = self.model(**{key: value
for (key, value) in data.items() if key not in join_fields})
self.apply_relationships(data, obj)
self.apply_nested_fields(data, obj)
self.session.add(obj)
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Object creation error: " + str(e), source={'pointer': '/data'})
self.after_create_object(obj, data, view_kwargs)
return obj | python | 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(data, view_kwargs)
relationship_fields = get_relationships(self.resource.schema, model_field=True)
nested_fields = get_nested_fields(self.resource.schema, model_field=True)
join_fields = relationship_fields + nested_fields
obj = self.model(**{key: value
for (key, value) in data.items() if key not in join_fields})
self.apply_relationships(data, obj)
self.apply_nested_fields(data, obj)
self.session.add(obj)
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Object creation error: " + str(e), source={'pointer': '/data'})
self.after_create_object(obj, data, view_kwargs)
return obj | [
"def",
"create_object",
"(",
"self",
",",
"data",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_create_object",
"(",
"data",
",",
"view_kwargs",
")",
"relationship_fields",
"=",
"get_relationships",
"(",
"self",
".",
"resource",
".",
"schema",
",",
"model_field",
"=",
"True",
")",
"nested_fields",
"=",
"get_nested_fields",
"(",
"self",
".",
"resource",
".",
"schema",
",",
"model_field",
"=",
"True",
")",
"join_fields",
"=",
"relationship_fields",
"+",
"nested_fields",
"obj",
"=",
"self",
".",
"model",
"(",
"*",
"*",
"{",
"key",
":",
"value",
"for",
"(",
"key",
",",
"value",
")",
"in",
"data",
".",
"items",
"(",
")",
"if",
"key",
"not",
"in",
"join_fields",
"}",
")",
"self",
".",
"apply_relationships",
"(",
"data",
",",
"obj",
")",
"self",
".",
"apply_nested_fields",
"(",
"data",
",",
"obj",
")",
"self",
".",
"session",
".",
"add",
"(",
"obj",
")",
"try",
":",
"self",
".",
"session",
".",
"commit",
"(",
")",
"except",
"JsonApiException",
"as",
"e",
":",
"self",
".",
"session",
".",
"rollback",
"(",
")",
"raise",
"e",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"session",
".",
"rollback",
"(",
")",
"raise",
"JsonApiException",
"(",
"\"Object creation error: \"",
"+",
"str",
"(",
"e",
")",
",",
"source",
"=",
"{",
"'pointer'",
":",
"'/data'",
"}",
")",
"self",
".",
"after_create_object",
"(",
"obj",
",",
"data",
",",
"view_kwargs",
")",
"return",
"obj"
] | 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 | [
"Create",
"an",
"object",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L38-L69 |
230,059 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.get_object | 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', inspect(self.model).primary_key[0].key)
try:
filter_field = getattr(self.model, id_field)
except Exception:
raise Exception("{} has no attribute {}".format(self.model.__name__, id_field))
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
query = self.retrieve_object_query(view_kwargs, filter_field, filter_value)
if qs is not None:
query = self.eagerload_includes(query, qs)
try:
obj = query.one()
except NoResultFound:
obj = None
self.after_get_object(obj, view_kwargs)
return obj | python | 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', inspect(self.model).primary_key[0].key)
try:
filter_field = getattr(self.model, id_field)
except Exception:
raise Exception("{} has no attribute {}".format(self.model.__name__, id_field))
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
query = self.retrieve_object_query(view_kwargs, filter_field, filter_value)
if qs is not None:
query = self.eagerload_includes(query, qs)
try:
obj = query.one()
except NoResultFound:
obj = None
self.after_get_object(obj, view_kwargs)
return obj | [
"def",
"get_object",
"(",
"self",
",",
"view_kwargs",
",",
"qs",
"=",
"None",
")",
":",
"self",
".",
"before_get_object",
"(",
"view_kwargs",
")",
"id_field",
"=",
"getattr",
"(",
"self",
",",
"'id_field'",
",",
"inspect",
"(",
"self",
".",
"model",
")",
".",
"primary_key",
"[",
"0",
"]",
".",
"key",
")",
"try",
":",
"filter_field",
"=",
"getattr",
"(",
"self",
".",
"model",
",",
"id_field",
")",
"except",
"Exception",
":",
"raise",
"Exception",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"self",
".",
"model",
".",
"__name__",
",",
"id_field",
")",
")",
"url_field",
"=",
"getattr",
"(",
"self",
",",
"'url_field'",
",",
"'id'",
")",
"filter_value",
"=",
"view_kwargs",
"[",
"url_field",
"]",
"query",
"=",
"self",
".",
"retrieve_object_query",
"(",
"view_kwargs",
",",
"filter_field",
",",
"filter_value",
")",
"if",
"qs",
"is",
"not",
"None",
":",
"query",
"=",
"self",
".",
"eagerload_includes",
"(",
"query",
",",
"qs",
")",
"try",
":",
"obj",
"=",
"query",
".",
"one",
"(",
")",
"except",
"NoResultFound",
":",
"obj",
"=",
"None",
"self",
".",
"after_get_object",
"(",
"obj",
",",
"view_kwargs",
")",
"return",
"obj"
] | Retrieve an object through sqlalchemy
:params dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy | [
"Retrieve",
"an",
"object",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L71-L100 |
230,060 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.get_collection | def get_collection(self, qs, view_kwargs):
"""Retrieve a collection of objects through sqlalchemy
:param QueryStringManager qs: a querystring manager to retrieve information from url
:param dict view_kwargs: kwargs from the resource view
:return tuple: the number of object and the list of objects
"""
self.before_get_collection(qs, view_kwargs)
query = self.query(view_kwargs)
if qs.filters:
query = self.filter_query(query, qs.filters, self.model)
if qs.sorting:
query = self.sort_query(query, qs.sorting)
object_count = query.count()
if getattr(self, 'eagerload_includes', True):
query = self.eagerload_includes(query, qs)
query = self.paginate_query(query, qs.pagination)
collection = query.all()
collection = self.after_get_collection(collection, qs, view_kwargs)
return object_count, collection | python | def get_collection(self, qs, view_kwargs):
"""Retrieve a collection of objects through sqlalchemy
:param QueryStringManager qs: a querystring manager to retrieve information from url
:param dict view_kwargs: kwargs from the resource view
:return tuple: the number of object and the list of objects
"""
self.before_get_collection(qs, view_kwargs)
query = self.query(view_kwargs)
if qs.filters:
query = self.filter_query(query, qs.filters, self.model)
if qs.sorting:
query = self.sort_query(query, qs.sorting)
object_count = query.count()
if getattr(self, 'eagerload_includes', True):
query = self.eagerload_includes(query, qs)
query = self.paginate_query(query, qs.pagination)
collection = query.all()
collection = self.after_get_collection(collection, qs, view_kwargs)
return object_count, collection | [
"def",
"get_collection",
"(",
"self",
",",
"qs",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_get_collection",
"(",
"qs",
",",
"view_kwargs",
")",
"query",
"=",
"self",
".",
"query",
"(",
"view_kwargs",
")",
"if",
"qs",
".",
"filters",
":",
"query",
"=",
"self",
".",
"filter_query",
"(",
"query",
",",
"qs",
".",
"filters",
",",
"self",
".",
"model",
")",
"if",
"qs",
".",
"sorting",
":",
"query",
"=",
"self",
".",
"sort_query",
"(",
"query",
",",
"qs",
".",
"sorting",
")",
"object_count",
"=",
"query",
".",
"count",
"(",
")",
"if",
"getattr",
"(",
"self",
",",
"'eagerload_includes'",
",",
"True",
")",
":",
"query",
"=",
"self",
".",
"eagerload_includes",
"(",
"query",
",",
"qs",
")",
"query",
"=",
"self",
".",
"paginate_query",
"(",
"query",
",",
"qs",
".",
"pagination",
")",
"collection",
"=",
"query",
".",
"all",
"(",
")",
"collection",
"=",
"self",
".",
"after_get_collection",
"(",
"collection",
",",
"qs",
",",
"view_kwargs",
")",
"return",
"object_count",
",",
"collection"
] | Retrieve a collection of objects through sqlalchemy
:param QueryStringManager qs: a querystring manager to retrieve information from url
:param dict view_kwargs: kwargs from the resource view
:return tuple: the number of object and the list of objects | [
"Retrieve",
"a",
"collection",
"of",
"objects",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L102-L130 |
230,061 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.update_object | def update_object(self, obj, data, view_kwargs):
"""Update an object through sqlalchemy
:param DeclarativeMeta obj: an object from sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if object have changed else False
"""
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
self.before_update_object(obj, data, view_kwargs)
relationship_fields = get_relationships(self.resource.schema, model_field=True)
nested_fields = get_nested_fields(self.resource.schema, model_field=True)
join_fields = relationship_fields + nested_fields
for key, value in data.items():
if hasattr(obj, key) and key not in join_fields:
setattr(obj, key, value)
self.apply_relationships(data, obj)
self.apply_nested_fields(data, obj)
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Update object error: " + str(e), source={'pointer': '/data'})
self.after_update_object(obj, data, view_kwargs) | python | def update_object(self, obj, data, view_kwargs):
"""Update an object through sqlalchemy
:param DeclarativeMeta obj: an object from sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if object have changed else False
"""
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
self.before_update_object(obj, data, view_kwargs)
relationship_fields = get_relationships(self.resource.schema, model_field=True)
nested_fields = get_nested_fields(self.resource.schema, model_field=True)
join_fields = relationship_fields + nested_fields
for key, value in data.items():
if hasattr(obj, key) and key not in join_fields:
setattr(obj, key, value)
self.apply_relationships(data, obj)
self.apply_nested_fields(data, obj)
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Update object error: " + str(e), source={'pointer': '/data'})
self.after_update_object(obj, data, view_kwargs) | [
"def",
"update_object",
"(",
"self",
",",
"obj",
",",
"data",
",",
"view_kwargs",
")",
":",
"if",
"obj",
"is",
"None",
":",
"url_field",
"=",
"getattr",
"(",
"self",
",",
"'url_field'",
",",
"'id'",
")",
"filter_value",
"=",
"view_kwargs",
"[",
"url_field",
"]",
"raise",
"ObjectNotFound",
"(",
"'{}: {} not found'",
".",
"format",
"(",
"self",
".",
"model",
".",
"__name__",
",",
"filter_value",
")",
",",
"source",
"=",
"{",
"'parameter'",
":",
"url_field",
"}",
")",
"self",
".",
"before_update_object",
"(",
"obj",
",",
"data",
",",
"view_kwargs",
")",
"relationship_fields",
"=",
"get_relationships",
"(",
"self",
".",
"resource",
".",
"schema",
",",
"model_field",
"=",
"True",
")",
"nested_fields",
"=",
"get_nested_fields",
"(",
"self",
".",
"resource",
".",
"schema",
",",
"model_field",
"=",
"True",
")",
"join_fields",
"=",
"relationship_fields",
"+",
"nested_fields",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"key",
")",
"and",
"key",
"not",
"in",
"join_fields",
":",
"setattr",
"(",
"obj",
",",
"key",
",",
"value",
")",
"self",
".",
"apply_relationships",
"(",
"data",
",",
"obj",
")",
"self",
".",
"apply_nested_fields",
"(",
"data",
",",
"obj",
")",
"try",
":",
"self",
".",
"session",
".",
"commit",
"(",
")",
"except",
"JsonApiException",
"as",
"e",
":",
"self",
".",
"session",
".",
"rollback",
"(",
")",
"raise",
"e",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"session",
".",
"rollback",
"(",
")",
"raise",
"JsonApiException",
"(",
"\"Update object error: \"",
"+",
"str",
"(",
"e",
")",
",",
"source",
"=",
"{",
"'pointer'",
":",
"'/data'",
"}",
")",
"self",
".",
"after_update_object",
"(",
"obj",
",",
"data",
",",
"view_kwargs",
")"
] | Update an object through sqlalchemy
:param DeclarativeMeta obj: an object from sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if object have changed else False | [
"Update",
"an",
"object",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L132-L169 |
230,062 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.delete_object | def delete_object(self, obj, view_kwargs):
"""Delete an object through sqlalchemy
:param DeclarativeMeta item: an item from sqlalchemy
:param dict view_kwargs: kwargs from the resource view
"""
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
self.before_delete_object(obj, view_kwargs)
self.session.delete(obj)
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Delete object error: " + str(e))
self.after_delete_object(obj, view_kwargs) | python | def delete_object(self, obj, view_kwargs):
"""Delete an object through sqlalchemy
:param DeclarativeMeta item: an item from sqlalchemy
:param dict view_kwargs: kwargs from the resource view
"""
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
self.before_delete_object(obj, view_kwargs)
self.session.delete(obj)
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Delete object error: " + str(e))
self.after_delete_object(obj, view_kwargs) | [
"def",
"delete_object",
"(",
"self",
",",
"obj",
",",
"view_kwargs",
")",
":",
"if",
"obj",
"is",
"None",
":",
"url_field",
"=",
"getattr",
"(",
"self",
",",
"'url_field'",
",",
"'id'",
")",
"filter_value",
"=",
"view_kwargs",
"[",
"url_field",
"]",
"raise",
"ObjectNotFound",
"(",
"'{}: {} not found'",
".",
"format",
"(",
"self",
".",
"model",
".",
"__name__",
",",
"filter_value",
")",
",",
"source",
"=",
"{",
"'parameter'",
":",
"url_field",
"}",
")",
"self",
".",
"before_delete_object",
"(",
"obj",
",",
"view_kwargs",
")",
"self",
".",
"session",
".",
"delete",
"(",
"obj",
")",
"try",
":",
"self",
".",
"session",
".",
"commit",
"(",
")",
"except",
"JsonApiException",
"as",
"e",
":",
"self",
".",
"session",
".",
"rollback",
"(",
")",
"raise",
"e",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"session",
".",
"rollback",
"(",
")",
"raise",
"JsonApiException",
"(",
"\"Delete object error: \"",
"+",
"str",
"(",
"e",
")",
")",
"self",
".",
"after_delete_object",
"(",
"obj",
",",
"view_kwargs",
")"
] | Delete an object through sqlalchemy
:param DeclarativeMeta item: an item from sqlalchemy
:param dict view_kwargs: kwargs from the resource view | [
"Delete",
"an",
"object",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L171-L195 |
230,063 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.create_relationship | def create_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
"""Create a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if relationship have changed else False
"""
self.before_create_relationship(json_data, relationship_field, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
if not hasattr(obj, relationship_field):
raise RelationNotFound("{} has no attribute {}".format(obj.__class__.__name__, relationship_field))
related_model = getattr(obj.__class__, relationship_field).property.mapper.class_
updated = False
if isinstance(json_data['data'], list):
obj_ids = {str(getattr(obj__, related_id_field)) for obj__ in getattr(obj, relationship_field)}
for obj_ in json_data['data']:
if obj_['id'] not in obj_ids:
getattr(obj,
relationship_field).append(self.get_related_object(related_model, related_id_field, obj_))
updated = True
else:
related_object = None
if json_data['data'] is not None:
related_object = self.get_related_object(related_model, related_id_field, json_data['data'])
obj_id = getattr(getattr(obj, relationship_field), related_id_field, None)
new_obj_id = getattr(related_object, related_id_field, None)
if obj_id != new_obj_id:
setattr(obj, relationship_field, related_object)
updated = True
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Create relationship error: " + str(e))
self.after_create_relationship(obj, updated, json_data, relationship_field, related_id_field, view_kwargs)
return obj, updated | python | def create_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
"""Create a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if relationship have changed else False
"""
self.before_create_relationship(json_data, relationship_field, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
if not hasattr(obj, relationship_field):
raise RelationNotFound("{} has no attribute {}".format(obj.__class__.__name__, relationship_field))
related_model = getattr(obj.__class__, relationship_field).property.mapper.class_
updated = False
if isinstance(json_data['data'], list):
obj_ids = {str(getattr(obj__, related_id_field)) for obj__ in getattr(obj, relationship_field)}
for obj_ in json_data['data']:
if obj_['id'] not in obj_ids:
getattr(obj,
relationship_field).append(self.get_related_object(related_model, related_id_field, obj_))
updated = True
else:
related_object = None
if json_data['data'] is not None:
related_object = self.get_related_object(related_model, related_id_field, json_data['data'])
obj_id = getattr(getattr(obj, relationship_field), related_id_field, None)
new_obj_id = getattr(related_object, related_id_field, None)
if obj_id != new_obj_id:
setattr(obj, relationship_field, related_object)
updated = True
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Create relationship error: " + str(e))
self.after_create_relationship(obj, updated, json_data, relationship_field, related_id_field, view_kwargs)
return obj, updated | [
"def",
"create_relationship",
"(",
"self",
",",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_create_relationship",
"(",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_kwargs",
")",
"obj",
"=",
"self",
".",
"get_object",
"(",
"view_kwargs",
")",
"if",
"obj",
"is",
"None",
":",
"url_field",
"=",
"getattr",
"(",
"self",
",",
"'url_field'",
",",
"'id'",
")",
"filter_value",
"=",
"view_kwargs",
"[",
"url_field",
"]",
"raise",
"ObjectNotFound",
"(",
"'{}: {} not found'",
".",
"format",
"(",
"self",
".",
"model",
".",
"__name__",
",",
"filter_value",
")",
",",
"source",
"=",
"{",
"'parameter'",
":",
"url_field",
"}",
")",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"relationship_field",
")",
":",
"raise",
"RelationNotFound",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"obj",
".",
"__class__",
".",
"__name__",
",",
"relationship_field",
")",
")",
"related_model",
"=",
"getattr",
"(",
"obj",
".",
"__class__",
",",
"relationship_field",
")",
".",
"property",
".",
"mapper",
".",
"class_",
"updated",
"=",
"False",
"if",
"isinstance",
"(",
"json_data",
"[",
"'data'",
"]",
",",
"list",
")",
":",
"obj_ids",
"=",
"{",
"str",
"(",
"getattr",
"(",
"obj__",
",",
"related_id_field",
")",
")",
"for",
"obj__",
"in",
"getattr",
"(",
"obj",
",",
"relationship_field",
")",
"}",
"for",
"obj_",
"in",
"json_data",
"[",
"'data'",
"]",
":",
"if",
"obj_",
"[",
"'id'",
"]",
"not",
"in",
"obj_ids",
":",
"getattr",
"(",
"obj",
",",
"relationship_field",
")",
".",
"append",
"(",
"self",
".",
"get_related_object",
"(",
"related_model",
",",
"related_id_field",
",",
"obj_",
")",
")",
"updated",
"=",
"True",
"else",
":",
"related_object",
"=",
"None",
"if",
"json_data",
"[",
"'data'",
"]",
"is",
"not",
"None",
":",
"related_object",
"=",
"self",
".",
"get_related_object",
"(",
"related_model",
",",
"related_id_field",
",",
"json_data",
"[",
"'data'",
"]",
")",
"obj_id",
"=",
"getattr",
"(",
"getattr",
"(",
"obj",
",",
"relationship_field",
")",
",",
"related_id_field",
",",
"None",
")",
"new_obj_id",
"=",
"getattr",
"(",
"related_object",
",",
"related_id_field",
",",
"None",
")",
"if",
"obj_id",
"!=",
"new_obj_id",
":",
"setattr",
"(",
"obj",
",",
"relationship_field",
",",
"related_object",
")",
"updated",
"=",
"True",
"try",
":",
"self",
".",
"session",
".",
"commit",
"(",
")",
"except",
"JsonApiException",
"as",
"e",
":",
"self",
".",
"session",
".",
"rollback",
"(",
")",
"raise",
"e",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"session",
".",
"rollback",
"(",
")",
"raise",
"JsonApiException",
"(",
"\"Create relationship error: \"",
"+",
"str",
"(",
"e",
")",
")",
"self",
".",
"after_create_relationship",
"(",
"obj",
",",
"updated",
",",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_kwargs",
")",
"return",
"obj",
",",
"updated"
] | Create a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if relationship have changed else False | [
"Create",
"a",
"relationship"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L197-L254 |
230,064 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.get_relationship | def get_relationship(self, relationship_field, related_type_, related_id_field, view_kwargs):
"""Get a relationship
:param str relationship_field: the model attribute used for relationship
:param str related_type_: the related resource type
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return tuple: the object and related object(s)
"""
self.before_get_relationship(relationship_field, related_type_, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
if not hasattr(obj, relationship_field):
raise RelationNotFound("{} has no attribute {}".format(obj.__class__.__name__, relationship_field))
related_objects = getattr(obj, relationship_field)
if related_objects is None:
return obj, related_objects
self.after_get_relationship(obj, related_objects, relationship_field, related_type_, related_id_field,
view_kwargs)
if isinstance(related_objects, InstrumentedList):
return obj,\
[{'type': related_type_, 'id': getattr(obj_, related_id_field)} for obj_ in related_objects]
else:
return obj, {'type': related_type_, 'id': getattr(related_objects, related_id_field)} | python | def get_relationship(self, relationship_field, related_type_, related_id_field, view_kwargs):
"""Get a relationship
:param str relationship_field: the model attribute used for relationship
:param str related_type_: the related resource type
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return tuple: the object and related object(s)
"""
self.before_get_relationship(relationship_field, related_type_, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
if not hasattr(obj, relationship_field):
raise RelationNotFound("{} has no attribute {}".format(obj.__class__.__name__, relationship_field))
related_objects = getattr(obj, relationship_field)
if related_objects is None:
return obj, related_objects
self.after_get_relationship(obj, related_objects, relationship_field, related_type_, related_id_field,
view_kwargs)
if isinstance(related_objects, InstrumentedList):
return obj,\
[{'type': related_type_, 'id': getattr(obj_, related_id_field)} for obj_ in related_objects]
else:
return obj, {'type': related_type_, 'id': getattr(related_objects, related_id_field)} | [
"def",
"get_relationship",
"(",
"self",
",",
"relationship_field",
",",
"related_type_",
",",
"related_id_field",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_get_relationship",
"(",
"relationship_field",
",",
"related_type_",
",",
"related_id_field",
",",
"view_kwargs",
")",
"obj",
"=",
"self",
".",
"get_object",
"(",
"view_kwargs",
")",
"if",
"obj",
"is",
"None",
":",
"url_field",
"=",
"getattr",
"(",
"self",
",",
"'url_field'",
",",
"'id'",
")",
"filter_value",
"=",
"view_kwargs",
"[",
"url_field",
"]",
"raise",
"ObjectNotFound",
"(",
"'{}: {} not found'",
".",
"format",
"(",
"self",
".",
"model",
".",
"__name__",
",",
"filter_value",
")",
",",
"source",
"=",
"{",
"'parameter'",
":",
"url_field",
"}",
")",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"relationship_field",
")",
":",
"raise",
"RelationNotFound",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"obj",
".",
"__class__",
".",
"__name__",
",",
"relationship_field",
")",
")",
"related_objects",
"=",
"getattr",
"(",
"obj",
",",
"relationship_field",
")",
"if",
"related_objects",
"is",
"None",
":",
"return",
"obj",
",",
"related_objects",
"self",
".",
"after_get_relationship",
"(",
"obj",
",",
"related_objects",
",",
"relationship_field",
",",
"related_type_",
",",
"related_id_field",
",",
"view_kwargs",
")",
"if",
"isinstance",
"(",
"related_objects",
",",
"InstrumentedList",
")",
":",
"return",
"obj",
",",
"[",
"{",
"'type'",
":",
"related_type_",
",",
"'id'",
":",
"getattr",
"(",
"obj_",
",",
"related_id_field",
")",
"}",
"for",
"obj_",
"in",
"related_objects",
"]",
"else",
":",
"return",
"obj",
",",
"{",
"'type'",
":",
"related_type_",
",",
"'id'",
":",
"getattr",
"(",
"related_objects",
",",
"related_id_field",
")",
"}"
] | Get a relationship
:param str relationship_field: the model attribute used for relationship
:param str related_type_: the related resource type
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return tuple: the object and related object(s) | [
"Get",
"a",
"relationship"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L256-L290 |
230,065 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.delete_relationship | def delete_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
"""Delete a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
"""
self.before_delete_relationship(json_data, relationship_field, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
if not hasattr(obj, relationship_field):
raise RelationNotFound("{} has no attribute {}".format(obj.__class__.__name__, relationship_field))
related_model = getattr(obj.__class__, relationship_field).property.mapper.class_
updated = False
if isinstance(json_data['data'], list):
obj_ids = {str(getattr(obj__, related_id_field)) for obj__ in getattr(obj, relationship_field)}
for obj_ in json_data['data']:
if obj_['id'] in obj_ids:
getattr(obj,
relationship_field).remove(self.get_related_object(related_model, related_id_field, obj_))
updated = True
else:
setattr(obj, relationship_field, None)
updated = True
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Delete relationship error: " + str(e))
self.after_delete_relationship(obj, updated, json_data, relationship_field, related_id_field, view_kwargs)
return obj, updated | python | def delete_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
"""Delete a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
"""
self.before_delete_relationship(json_data, relationship_field, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter': url_field})
if not hasattr(obj, relationship_field):
raise RelationNotFound("{} has no attribute {}".format(obj.__class__.__name__, relationship_field))
related_model = getattr(obj.__class__, relationship_field).property.mapper.class_
updated = False
if isinstance(json_data['data'], list):
obj_ids = {str(getattr(obj__, related_id_field)) for obj__ in getattr(obj, relationship_field)}
for obj_ in json_data['data']:
if obj_['id'] in obj_ids:
getattr(obj,
relationship_field).remove(self.get_related_object(related_model, related_id_field, obj_))
updated = True
else:
setattr(obj, relationship_field, None)
updated = True
try:
self.session.commit()
except JsonApiException as e:
self.session.rollback()
raise e
except Exception as e:
self.session.rollback()
raise JsonApiException("Delete relationship error: " + str(e))
self.after_delete_relationship(obj, updated, json_data, relationship_field, related_id_field, view_kwargs)
return obj, updated | [
"def",
"delete_relationship",
"(",
"self",
",",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_delete_relationship",
"(",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_kwargs",
")",
"obj",
"=",
"self",
".",
"get_object",
"(",
"view_kwargs",
")",
"if",
"obj",
"is",
"None",
":",
"url_field",
"=",
"getattr",
"(",
"self",
",",
"'url_field'",
",",
"'id'",
")",
"filter_value",
"=",
"view_kwargs",
"[",
"url_field",
"]",
"raise",
"ObjectNotFound",
"(",
"'{}: {} not found'",
".",
"format",
"(",
"self",
".",
"model",
".",
"__name__",
",",
"filter_value",
")",
",",
"source",
"=",
"{",
"'parameter'",
":",
"url_field",
"}",
")",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"relationship_field",
")",
":",
"raise",
"RelationNotFound",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"obj",
".",
"__class__",
".",
"__name__",
",",
"relationship_field",
")",
")",
"related_model",
"=",
"getattr",
"(",
"obj",
".",
"__class__",
",",
"relationship_field",
")",
".",
"property",
".",
"mapper",
".",
"class_",
"updated",
"=",
"False",
"if",
"isinstance",
"(",
"json_data",
"[",
"'data'",
"]",
",",
"list",
")",
":",
"obj_ids",
"=",
"{",
"str",
"(",
"getattr",
"(",
"obj__",
",",
"related_id_field",
")",
")",
"for",
"obj__",
"in",
"getattr",
"(",
"obj",
",",
"relationship_field",
")",
"}",
"for",
"obj_",
"in",
"json_data",
"[",
"'data'",
"]",
":",
"if",
"obj_",
"[",
"'id'",
"]",
"in",
"obj_ids",
":",
"getattr",
"(",
"obj",
",",
"relationship_field",
")",
".",
"remove",
"(",
"self",
".",
"get_related_object",
"(",
"related_model",
",",
"related_id_field",
",",
"obj_",
")",
")",
"updated",
"=",
"True",
"else",
":",
"setattr",
"(",
"obj",
",",
"relationship_field",
",",
"None",
")",
"updated",
"=",
"True",
"try",
":",
"self",
".",
"session",
".",
"commit",
"(",
")",
"except",
"JsonApiException",
"as",
"e",
":",
"self",
".",
"session",
".",
"rollback",
"(",
")",
"raise",
"e",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"session",
".",
"rollback",
"(",
")",
"raise",
"JsonApiException",
"(",
"\"Delete relationship error: \"",
"+",
"str",
"(",
"e",
")",
")",
"self",
".",
"after_delete_relationship",
"(",
"obj",
",",
"updated",
",",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_kwargs",
")",
"return",
"obj",
",",
"updated"
] | Delete a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view | [
"Delete",
"a",
"relationship"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L355-L403 |
230,066 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.get_related_object | def get_related_object(self, related_model, related_id_field, obj):
"""Get a related object
:param Model related_model: an sqlalchemy model
:param str related_id_field: the identifier field of the related model
:param DeclarativeMeta obj: the sqlalchemy object to retrieve related objects from
:return DeclarativeMeta: a related object
"""
try:
related_object = self.session.query(related_model)\
.filter(getattr(related_model, related_id_field) == obj['id'])\
.one()
except NoResultFound:
raise RelatedObjectNotFound("{}.{}: {} not found".format(related_model.__name__,
related_id_field,
obj['id']))
return related_object | python | def get_related_object(self, related_model, related_id_field, obj):
"""Get a related object
:param Model related_model: an sqlalchemy model
:param str related_id_field: the identifier field of the related model
:param DeclarativeMeta obj: the sqlalchemy object to retrieve related objects from
:return DeclarativeMeta: a related object
"""
try:
related_object = self.session.query(related_model)\
.filter(getattr(related_model, related_id_field) == obj['id'])\
.one()
except NoResultFound:
raise RelatedObjectNotFound("{}.{}: {} not found".format(related_model.__name__,
related_id_field,
obj['id']))
return related_object | [
"def",
"get_related_object",
"(",
"self",
",",
"related_model",
",",
"related_id_field",
",",
"obj",
")",
":",
"try",
":",
"related_object",
"=",
"self",
".",
"session",
".",
"query",
"(",
"related_model",
")",
".",
"filter",
"(",
"getattr",
"(",
"related_model",
",",
"related_id_field",
")",
"==",
"obj",
"[",
"'id'",
"]",
")",
".",
"one",
"(",
")",
"except",
"NoResultFound",
":",
"raise",
"RelatedObjectNotFound",
"(",
"\"{}.{}: {} not found\"",
".",
"format",
"(",
"related_model",
".",
"__name__",
",",
"related_id_field",
",",
"obj",
"[",
"'id'",
"]",
")",
")",
"return",
"related_object"
] | Get a related object
:param Model related_model: an sqlalchemy model
:param str related_id_field: the identifier field of the related model
:param DeclarativeMeta obj: the sqlalchemy object to retrieve related objects from
:return DeclarativeMeta: a related object | [
"Get",
"a",
"related",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L405-L422 |
230,067 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.apply_relationships | def apply_relationships(self, data, obj):
"""Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False
"""
relationships_to_apply = []
relationship_fields = get_relationships(self.resource.schema, model_field=True)
for key, value in data.items():
if key in relationship_fields:
related_model = getattr(obj.__class__, key).property.mapper.class_
schema_field = get_schema_field(self.resource.schema, key)
related_id_field = self.resource.schema._declared_fields[schema_field].id_field
if isinstance(value, list):
related_objects = []
for identifier in value:
related_object = self.get_related_object(related_model, related_id_field, {'id': identifier})
related_objects.append(related_object)
relationships_to_apply.append({'field': key, 'value': related_objects})
else:
related_object = None
if value is not None:
related_object = self.get_related_object(related_model, related_id_field, {'id': value})
relationships_to_apply.append({'field': key, 'value': related_object})
for relationship in relationships_to_apply:
setattr(obj, relationship['field'], relationship['value']) | python | def apply_relationships(self, data, obj):
"""Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False
"""
relationships_to_apply = []
relationship_fields = get_relationships(self.resource.schema, model_field=True)
for key, value in data.items():
if key in relationship_fields:
related_model = getattr(obj.__class__, key).property.mapper.class_
schema_field = get_schema_field(self.resource.schema, key)
related_id_field = self.resource.schema._declared_fields[schema_field].id_field
if isinstance(value, list):
related_objects = []
for identifier in value:
related_object = self.get_related_object(related_model, related_id_field, {'id': identifier})
related_objects.append(related_object)
relationships_to_apply.append({'field': key, 'value': related_objects})
else:
related_object = None
if value is not None:
related_object = self.get_related_object(related_model, related_id_field, {'id': value})
relationships_to_apply.append({'field': key, 'value': related_object})
for relationship in relationships_to_apply:
setattr(obj, relationship['field'], relationship['value']) | [
"def",
"apply_relationships",
"(",
"self",
",",
"data",
",",
"obj",
")",
":",
"relationships_to_apply",
"=",
"[",
"]",
"relationship_fields",
"=",
"get_relationships",
"(",
"self",
".",
"resource",
".",
"schema",
",",
"model_field",
"=",
"True",
")",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"relationship_fields",
":",
"related_model",
"=",
"getattr",
"(",
"obj",
".",
"__class__",
",",
"key",
")",
".",
"property",
".",
"mapper",
".",
"class_",
"schema_field",
"=",
"get_schema_field",
"(",
"self",
".",
"resource",
".",
"schema",
",",
"key",
")",
"related_id_field",
"=",
"self",
".",
"resource",
".",
"schema",
".",
"_declared_fields",
"[",
"schema_field",
"]",
".",
"id_field",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"related_objects",
"=",
"[",
"]",
"for",
"identifier",
"in",
"value",
":",
"related_object",
"=",
"self",
".",
"get_related_object",
"(",
"related_model",
",",
"related_id_field",
",",
"{",
"'id'",
":",
"identifier",
"}",
")",
"related_objects",
".",
"append",
"(",
"related_object",
")",
"relationships_to_apply",
".",
"append",
"(",
"{",
"'field'",
":",
"key",
",",
"'value'",
":",
"related_objects",
"}",
")",
"else",
":",
"related_object",
"=",
"None",
"if",
"value",
"is",
"not",
"None",
":",
"related_object",
"=",
"self",
".",
"get_related_object",
"(",
"related_model",
",",
"related_id_field",
",",
"{",
"'id'",
":",
"value",
"}",
")",
"relationships_to_apply",
".",
"append",
"(",
"{",
"'field'",
":",
"key",
",",
"'value'",
":",
"related_object",
"}",
")",
"for",
"relationship",
"in",
"relationships_to_apply",
":",
"setattr",
"(",
"obj",
",",
"relationship",
"[",
"'field'",
"]",
",",
"relationship",
"[",
"'value'",
"]",
")"
] | Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False | [
"Apply",
"relationship",
"provided",
"by",
"data",
"to",
"obj"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L425-L457 |
230,068 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.filter_query | def filter_query(self, query, filter_info, model):
"""Filter query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param filter_info: filter information
:type filter_info: dict or None
:param DeclarativeMeta model: an sqlalchemy model
:return Query: the sorted query
"""
if filter_info:
filters = create_filters(model, filter_info, self.resource)
query = query.filter(*filters)
return query | python | def filter_query(self, query, filter_info, model):
"""Filter query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param filter_info: filter information
:type filter_info: dict or None
:param DeclarativeMeta model: an sqlalchemy model
:return Query: the sorted query
"""
if filter_info:
filters = create_filters(model, filter_info, self.resource)
query = query.filter(*filters)
return query | [
"def",
"filter_query",
"(",
"self",
",",
"query",
",",
"filter_info",
",",
"model",
")",
":",
"if",
"filter_info",
":",
"filters",
"=",
"create_filters",
"(",
"model",
",",
"filter_info",
",",
"self",
".",
"resource",
")",
"query",
"=",
"query",
".",
"filter",
"(",
"*",
"filters",
")",
"return",
"query"
] | Filter query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param filter_info: filter information
:type filter_info: dict or None
:param DeclarativeMeta model: an sqlalchemy model
:return Query: the sorted query | [
"Filter",
"query",
"according",
"to",
"jsonapi",
"1",
".",
"0"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L490-L503 |
230,069 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.sort_query | def sort_query(self, query, sort_info):
"""Sort query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param list sort_info: sort information
:return Query: the sorted query
"""
for sort_opt in sort_info:
field = sort_opt['field']
if not hasattr(self.model, field):
raise InvalidSort("{} has no attribute {}".format(self.model.__name__, field))
query = query.order_by(getattr(getattr(self.model, field), sort_opt['order'])())
return query | python | def sort_query(self, query, sort_info):
"""Sort query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param list sort_info: sort information
:return Query: the sorted query
"""
for sort_opt in sort_info:
field = sort_opt['field']
if not hasattr(self.model, field):
raise InvalidSort("{} has no attribute {}".format(self.model.__name__, field))
query = query.order_by(getattr(getattr(self.model, field), sort_opt['order'])())
return query | [
"def",
"sort_query",
"(",
"self",
",",
"query",
",",
"sort_info",
")",
":",
"for",
"sort_opt",
"in",
"sort_info",
":",
"field",
"=",
"sort_opt",
"[",
"'field'",
"]",
"if",
"not",
"hasattr",
"(",
"self",
".",
"model",
",",
"field",
")",
":",
"raise",
"InvalidSort",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"self",
".",
"model",
".",
"__name__",
",",
"field",
")",
")",
"query",
"=",
"query",
".",
"order_by",
"(",
"getattr",
"(",
"getattr",
"(",
"self",
".",
"model",
",",
"field",
")",
",",
"sort_opt",
"[",
"'order'",
"]",
")",
"(",
")",
")",
"return",
"query"
] | Sort query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param list sort_info: sort information
:return Query: the sorted query | [
"Sort",
"query",
"according",
"to",
"jsonapi",
"1",
".",
"0"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L505-L517 |
230,070 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.paginate_query | def paginate_query(self, query, paginate_info):
"""Paginate query according to jsonapi 1.0
:param Query query: sqlalchemy queryset
:param dict paginate_info: pagination information
:return Query: the paginated query
"""
if int(paginate_info.get('size', 1)) == 0:
return query
page_size = int(paginate_info.get('size', 0)) or current_app.config['PAGE_SIZE']
query = query.limit(page_size)
if paginate_info.get('number'):
query = query.offset((int(paginate_info['number']) - 1) * page_size)
return query | python | def paginate_query(self, query, paginate_info):
"""Paginate query according to jsonapi 1.0
:param Query query: sqlalchemy queryset
:param dict paginate_info: pagination information
:return Query: the paginated query
"""
if int(paginate_info.get('size', 1)) == 0:
return query
page_size = int(paginate_info.get('size', 0)) or current_app.config['PAGE_SIZE']
query = query.limit(page_size)
if paginate_info.get('number'):
query = query.offset((int(paginate_info['number']) - 1) * page_size)
return query | [
"def",
"paginate_query",
"(",
"self",
",",
"query",
",",
"paginate_info",
")",
":",
"if",
"int",
"(",
"paginate_info",
".",
"get",
"(",
"'size'",
",",
"1",
")",
")",
"==",
"0",
":",
"return",
"query",
"page_size",
"=",
"int",
"(",
"paginate_info",
".",
"get",
"(",
"'size'",
",",
"0",
")",
")",
"or",
"current_app",
".",
"config",
"[",
"'PAGE_SIZE'",
"]",
"query",
"=",
"query",
".",
"limit",
"(",
"page_size",
")",
"if",
"paginate_info",
".",
"get",
"(",
"'number'",
")",
":",
"query",
"=",
"query",
".",
"offset",
"(",
"(",
"int",
"(",
"paginate_info",
"[",
"'number'",
"]",
")",
"-",
"1",
")",
"*",
"page_size",
")",
"return",
"query"
] | Paginate query according to jsonapi 1.0
:param Query query: sqlalchemy queryset
:param dict paginate_info: pagination information
:return Query: the paginated query | [
"Paginate",
"query",
"according",
"to",
"jsonapi",
"1",
".",
"0"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L519-L534 |
230,071 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.eagerload_includes | def eagerload_includes(self, query, qs):
"""Use eagerload feature of sqlalchemy to optimize data retrieval for include querystring parameter
:param Query query: sqlalchemy queryset
:param QueryStringManager qs: a querystring manager to retrieve information from url
:return Query: the query with includes eagerloaded
"""
for include in qs.include:
joinload_object = None
if '.' in include:
current_schema = self.resource.schema
for obj in include.split('.'):
try:
field = get_model_field(current_schema, obj)
except Exception as e:
raise InvalidInclude(str(e))
if joinload_object is None:
joinload_object = joinedload(field)
else:
joinload_object = joinload_object.joinedload(field)
related_schema_cls = get_related_schema(current_schema, obj)
if isinstance(related_schema_cls, SchemaABC):
related_schema_cls = related_schema_cls.__class__
else:
related_schema_cls = class_registry.get_class(related_schema_cls)
current_schema = related_schema_cls
else:
try:
field = get_model_field(self.resource.schema, include)
except Exception as e:
raise InvalidInclude(str(e))
joinload_object = joinedload(field)
query = query.options(joinload_object)
return query | python | def eagerload_includes(self, query, qs):
"""Use eagerload feature of sqlalchemy to optimize data retrieval for include querystring parameter
:param Query query: sqlalchemy queryset
:param QueryStringManager qs: a querystring manager to retrieve information from url
:return Query: the query with includes eagerloaded
"""
for include in qs.include:
joinload_object = None
if '.' in include:
current_schema = self.resource.schema
for obj in include.split('.'):
try:
field = get_model_field(current_schema, obj)
except Exception as e:
raise InvalidInclude(str(e))
if joinload_object is None:
joinload_object = joinedload(field)
else:
joinload_object = joinload_object.joinedload(field)
related_schema_cls = get_related_schema(current_schema, obj)
if isinstance(related_schema_cls, SchemaABC):
related_schema_cls = related_schema_cls.__class__
else:
related_schema_cls = class_registry.get_class(related_schema_cls)
current_schema = related_schema_cls
else:
try:
field = get_model_field(self.resource.schema, include)
except Exception as e:
raise InvalidInclude(str(e))
joinload_object = joinedload(field)
query = query.options(joinload_object)
return query | [
"def",
"eagerload_includes",
"(",
"self",
",",
"query",
",",
"qs",
")",
":",
"for",
"include",
"in",
"qs",
".",
"include",
":",
"joinload_object",
"=",
"None",
"if",
"'.'",
"in",
"include",
":",
"current_schema",
"=",
"self",
".",
"resource",
".",
"schema",
"for",
"obj",
"in",
"include",
".",
"split",
"(",
"'.'",
")",
":",
"try",
":",
"field",
"=",
"get_model_field",
"(",
"current_schema",
",",
"obj",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"InvalidInclude",
"(",
"str",
"(",
"e",
")",
")",
"if",
"joinload_object",
"is",
"None",
":",
"joinload_object",
"=",
"joinedload",
"(",
"field",
")",
"else",
":",
"joinload_object",
"=",
"joinload_object",
".",
"joinedload",
"(",
"field",
")",
"related_schema_cls",
"=",
"get_related_schema",
"(",
"current_schema",
",",
"obj",
")",
"if",
"isinstance",
"(",
"related_schema_cls",
",",
"SchemaABC",
")",
":",
"related_schema_cls",
"=",
"related_schema_cls",
".",
"__class__",
"else",
":",
"related_schema_cls",
"=",
"class_registry",
".",
"get_class",
"(",
"related_schema_cls",
")",
"current_schema",
"=",
"related_schema_cls",
"else",
":",
"try",
":",
"field",
"=",
"get_model_field",
"(",
"self",
".",
"resource",
".",
"schema",
",",
"include",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"InvalidInclude",
"(",
"str",
"(",
"e",
")",
")",
"joinload_object",
"=",
"joinedload",
"(",
"field",
")",
"query",
"=",
"query",
".",
"options",
"(",
"joinload_object",
")",
"return",
"query"
] | Use eagerload feature of sqlalchemy to optimize data retrieval for include querystring parameter
:param Query query: sqlalchemy queryset
:param QueryStringManager qs: a querystring manager to retrieve information from url
:return Query: the query with includes eagerloaded | [
"Use",
"eagerload",
"feature",
"of",
"sqlalchemy",
"to",
"optimize",
"data",
"retrieval",
"for",
"include",
"querystring",
"parameter"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L536-L577 |
230,072 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.retrieve_object_query | def retrieve_object_query(self, view_kwargs, filter_field, filter_value):
"""Build query to retrieve object
:param dict view_kwargs: kwargs from the resource view
:params sqlalchemy_field filter_field: the field to filter on
:params filter_value: the value to filter with
:return sqlalchemy query: a query from sqlalchemy
"""
return self.session.query(self.model).filter(filter_field == filter_value) | python | def retrieve_object_query(self, view_kwargs, filter_field, filter_value):
"""Build query to retrieve object
:param dict view_kwargs: kwargs from the resource view
:params sqlalchemy_field filter_field: the field to filter on
:params filter_value: the value to filter with
:return sqlalchemy query: a query from sqlalchemy
"""
return self.session.query(self.model).filter(filter_field == filter_value) | [
"def",
"retrieve_object_query",
"(",
"self",
",",
"view_kwargs",
",",
"filter_field",
",",
"filter_value",
")",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"model",
")",
".",
"filter",
"(",
"filter_field",
"==",
"filter_value",
")"
] | Build query to retrieve object
:param dict view_kwargs: kwargs from the resource view
:params sqlalchemy_field filter_field: the field to filter on
:params filter_value: the value to filter with
:return sqlalchemy query: a query from sqlalchemy | [
"Build",
"query",
"to",
"retrieve",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L579-L587 |
230,073 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/pagination.py | add_pagination_links | def add_pagination_links(data, object_count, querystring, base_url):
"""Add pagination links to result
:param dict data: the result of the view
:param int object_count: number of objects in result
:param QueryStringManager querystring: the managed querystring fields and values
:param str base_url: the base url for pagination
"""
links = {}
all_qs_args = copy(querystring.querystring)
links['self'] = base_url
# compute self link
if all_qs_args:
links['self'] += '?' + urlencode(all_qs_args)
if querystring.pagination.get('size') != '0' and object_count > 1:
# compute last link
page_size = int(querystring.pagination.get('size', 0)) or current_app.config['PAGE_SIZE']
last_page = int(ceil(object_count / page_size))
if last_page > 1:
links['first'] = links['last'] = base_url
all_qs_args.pop('page[number]', None)
# compute first link
if all_qs_args:
links['first'] += '?' + urlencode(all_qs_args)
all_qs_args.update({'page[number]': last_page})
links['last'] += '?' + urlencode(all_qs_args)
# compute previous and next link
current_page = int(querystring.pagination.get('number', 0)) or 1
if current_page > 1:
all_qs_args.update({'page[number]': current_page - 1})
links['prev'] = '?'.join((base_url, urlencode(all_qs_args)))
if current_page < last_page:
all_qs_args.update({'page[number]': current_page + 1})
links['next'] = '?'.join((base_url, urlencode(all_qs_args)))
data['links'] = links | python | def add_pagination_links(data, object_count, querystring, base_url):
"""Add pagination links to result
:param dict data: the result of the view
:param int object_count: number of objects in result
:param QueryStringManager querystring: the managed querystring fields and values
:param str base_url: the base url for pagination
"""
links = {}
all_qs_args = copy(querystring.querystring)
links['self'] = base_url
# compute self link
if all_qs_args:
links['self'] += '?' + urlencode(all_qs_args)
if querystring.pagination.get('size') != '0' and object_count > 1:
# compute last link
page_size = int(querystring.pagination.get('size', 0)) or current_app.config['PAGE_SIZE']
last_page = int(ceil(object_count / page_size))
if last_page > 1:
links['first'] = links['last'] = base_url
all_qs_args.pop('page[number]', None)
# compute first link
if all_qs_args:
links['first'] += '?' + urlencode(all_qs_args)
all_qs_args.update({'page[number]': last_page})
links['last'] += '?' + urlencode(all_qs_args)
# compute previous and next link
current_page = int(querystring.pagination.get('number', 0)) or 1
if current_page > 1:
all_qs_args.update({'page[number]': current_page - 1})
links['prev'] = '?'.join((base_url, urlencode(all_qs_args)))
if current_page < last_page:
all_qs_args.update({'page[number]': current_page + 1})
links['next'] = '?'.join((base_url, urlencode(all_qs_args)))
data['links'] = links | [
"def",
"add_pagination_links",
"(",
"data",
",",
"object_count",
",",
"querystring",
",",
"base_url",
")",
":",
"links",
"=",
"{",
"}",
"all_qs_args",
"=",
"copy",
"(",
"querystring",
".",
"querystring",
")",
"links",
"[",
"'self'",
"]",
"=",
"base_url",
"# compute self link",
"if",
"all_qs_args",
":",
"links",
"[",
"'self'",
"]",
"+=",
"'?'",
"+",
"urlencode",
"(",
"all_qs_args",
")",
"if",
"querystring",
".",
"pagination",
".",
"get",
"(",
"'size'",
")",
"!=",
"'0'",
"and",
"object_count",
">",
"1",
":",
"# compute last link",
"page_size",
"=",
"int",
"(",
"querystring",
".",
"pagination",
".",
"get",
"(",
"'size'",
",",
"0",
")",
")",
"or",
"current_app",
".",
"config",
"[",
"'PAGE_SIZE'",
"]",
"last_page",
"=",
"int",
"(",
"ceil",
"(",
"object_count",
"/",
"page_size",
")",
")",
"if",
"last_page",
">",
"1",
":",
"links",
"[",
"'first'",
"]",
"=",
"links",
"[",
"'last'",
"]",
"=",
"base_url",
"all_qs_args",
".",
"pop",
"(",
"'page[number]'",
",",
"None",
")",
"# compute first link",
"if",
"all_qs_args",
":",
"links",
"[",
"'first'",
"]",
"+=",
"'?'",
"+",
"urlencode",
"(",
"all_qs_args",
")",
"all_qs_args",
".",
"update",
"(",
"{",
"'page[number]'",
":",
"last_page",
"}",
")",
"links",
"[",
"'last'",
"]",
"+=",
"'?'",
"+",
"urlencode",
"(",
"all_qs_args",
")",
"# compute previous and next link",
"current_page",
"=",
"int",
"(",
"querystring",
".",
"pagination",
".",
"get",
"(",
"'number'",
",",
"0",
")",
")",
"or",
"1",
"if",
"current_page",
">",
"1",
":",
"all_qs_args",
".",
"update",
"(",
"{",
"'page[number]'",
":",
"current_page",
"-",
"1",
"}",
")",
"links",
"[",
"'prev'",
"]",
"=",
"'?'",
".",
"join",
"(",
"(",
"base_url",
",",
"urlencode",
"(",
"all_qs_args",
")",
")",
")",
"if",
"current_page",
"<",
"last_page",
":",
"all_qs_args",
".",
"update",
"(",
"{",
"'page[number]'",
":",
"current_page",
"+",
"1",
"}",
")",
"links",
"[",
"'next'",
"]",
"=",
"'?'",
".",
"join",
"(",
"(",
"base_url",
",",
"urlencode",
"(",
"all_qs_args",
")",
")",
")",
"data",
"[",
"'links'",
"]",
"=",
"links"
] | Add pagination links to result
:param dict data: the result of the view
:param int object_count: number of objects in result
:param QueryStringManager querystring: the managed querystring fields and values
:param str base_url: the base url for pagination | [
"Add",
"pagination",
"links",
"to",
"result"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/pagination.py#L13-L56 |
230,074 | ethereum/py-evm | eth/tools/fixtures/generation.py | idfn | def idfn(fixture_params: Iterable[Any]) -> str:
"""
Function for pytest to produce uniform names for fixtures.
"""
return ":".join((str(item) for item in fixture_params)) | python | def idfn(fixture_params: Iterable[Any]) -> str:
"""
Function for pytest to produce uniform names for fixtures.
"""
return ":".join((str(item) for item in fixture_params)) | [
"def",
"idfn",
"(",
"fixture_params",
":",
"Iterable",
"[",
"Any",
"]",
")",
"->",
"str",
":",
"return",
"\":\"",
".",
"join",
"(",
"(",
"str",
"(",
"item",
")",
"for",
"item",
"in",
"fixture_params",
")",
")"
] | Function for pytest to produce uniform names for fixtures. | [
"Function",
"for",
"pytest",
"to",
"produce",
"uniform",
"names",
"for",
"fixtures",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/generation.py#L24-L28 |
230,075 | ethereum/py-evm | eth/tools/fixtures/generation.py | get_fixtures_file_hash | def get_fixtures_file_hash(all_fixture_paths: Iterable[str]) -> str:
"""
Returns the MD5 hash of the fixture files. Used for cache busting.
"""
hasher = hashlib.md5()
for fixture_path in sorted(all_fixture_paths):
with open(fixture_path, 'rb') as fixture_file:
hasher.update(fixture_file.read())
return hasher.hexdigest() | python | def get_fixtures_file_hash(all_fixture_paths: Iterable[str]) -> str:
"""
Returns the MD5 hash of the fixture files. Used for cache busting.
"""
hasher = hashlib.md5()
for fixture_path in sorted(all_fixture_paths):
with open(fixture_path, 'rb') as fixture_file:
hasher.update(fixture_file.read())
return hasher.hexdigest() | [
"def",
"get_fixtures_file_hash",
"(",
"all_fixture_paths",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"str",
":",
"hasher",
"=",
"hashlib",
".",
"md5",
"(",
")",
"for",
"fixture_path",
"in",
"sorted",
"(",
"all_fixture_paths",
")",
":",
"with",
"open",
"(",
"fixture_path",
",",
"'rb'",
")",
"as",
"fixture_file",
":",
"hasher",
".",
"update",
"(",
"fixture_file",
".",
"read",
"(",
")",
")",
"return",
"hasher",
".",
"hexdigest",
"(",
")"
] | Returns the MD5 hash of the fixture files. Used for cache busting. | [
"Returns",
"the",
"MD5",
"hash",
"of",
"the",
"fixture",
"files",
".",
"Used",
"for",
"cache",
"busting",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/generation.py#L31-L39 |
230,076 | ethereum/py-evm | eth/rlp/transactions.py | BaseTransaction.create_unsigned_transaction | def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
data: bytes) -> 'BaseUnsignedTransaction':
"""
Create an unsigned transaction.
"""
raise NotImplementedError("Must be implemented by subclasses") | python | def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
data: bytes) -> 'BaseUnsignedTransaction':
"""
Create an unsigned transaction.
"""
raise NotImplementedError("Must be implemented by subclasses") | [
"def",
"create_unsigned_transaction",
"(",
"cls",
",",
"*",
",",
"nonce",
":",
"int",
",",
"gas_price",
":",
"int",
",",
"gas",
":",
"int",
",",
"to",
":",
"Address",
",",
"value",
":",
"int",
",",
"data",
":",
"bytes",
")",
"->",
"'BaseUnsignedTransaction'",
":",
"raise",
"NotImplementedError",
"(",
"\"Must be implemented by subclasses\"",
")"
] | Create an unsigned transaction. | [
"Create",
"an",
"unsigned",
"transaction",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/rlp/transactions.py#L155-L166 |
230,077 | ethereum/py-evm | eth/chains/header.py | HeaderChain.import_header | def import_header(self,
header: BlockHeader
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Direct passthrough to `headerdb`
Also updates the local `header` property to be the latest canonical head.
Returns an iterable of headers representing the headers that are newly
part of the canonical chain.
- If the imported header is not part of the canonical chain then an
empty tuple will be returned.
- If the imported header simply extends the canonical chain then a
length-1 tuple with the imported header will be returned.
- If the header is part of a non-canonical chain which overtakes the
current canonical chain then the returned tuple will contain the
headers which are newly part of the canonical chain.
"""
new_canonical_headers = self.headerdb.persist_header(header)
self.header = self.get_canonical_head()
return new_canonical_headers | python | def import_header(self,
header: BlockHeader
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Direct passthrough to `headerdb`
Also updates the local `header` property to be the latest canonical head.
Returns an iterable of headers representing the headers that are newly
part of the canonical chain.
- If the imported header is not part of the canonical chain then an
empty tuple will be returned.
- If the imported header simply extends the canonical chain then a
length-1 tuple with the imported header will be returned.
- If the header is part of a non-canonical chain which overtakes the
current canonical chain then the returned tuple will contain the
headers which are newly part of the canonical chain.
"""
new_canonical_headers = self.headerdb.persist_header(header)
self.header = self.get_canonical_head()
return new_canonical_headers | [
"def",
"import_header",
"(",
"self",
",",
"header",
":",
"BlockHeader",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
",",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
"]",
":",
"new_canonical_headers",
"=",
"self",
".",
"headerdb",
".",
"persist_header",
"(",
"header",
")",
"self",
".",
"header",
"=",
"self",
".",
"get_canonical_head",
"(",
")",
"return",
"new_canonical_headers"
] | Direct passthrough to `headerdb`
Also updates the local `header` property to be the latest canonical head.
Returns an iterable of headers representing the headers that are newly
part of the canonical chain.
- If the imported header is not part of the canonical chain then an
empty tuple will be returned.
- If the imported header simply extends the canonical chain then a
length-1 tuple with the imported header will be returned.
- If the header is part of a non-canonical chain which overtakes the
current canonical chain then the returned tuple will contain the
headers which are newly part of the canonical chain. | [
"Direct",
"passthrough",
"to",
"headerdb"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/header.py#L165-L186 |
230,078 | ethereum/py-evm | eth/rlp/headers.py | BlockHeader.from_parent | def from_parent(cls,
parent: 'BlockHeader',
gas_limit: int,
difficulty: int,
timestamp: int,
coinbase: Address=ZERO_ADDRESS,
nonce: bytes=None,
extra_data: bytes=None,
transaction_root: bytes=None,
receipt_root: bytes=None) -> 'BlockHeader':
"""
Initialize a new block header with the `parent` header as the block's
parent hash.
"""
header_kwargs = {
'parent_hash': parent.hash,
'coinbase': coinbase,
'state_root': parent.state_root,
'gas_limit': gas_limit,
'difficulty': difficulty,
'block_number': parent.block_number + 1,
'timestamp': timestamp,
}
if nonce is not None:
header_kwargs['nonce'] = nonce
if extra_data is not None:
header_kwargs['extra_data'] = extra_data
if transaction_root is not None:
header_kwargs['transaction_root'] = transaction_root
if receipt_root is not None:
header_kwargs['receipt_root'] = receipt_root
header = cls(**header_kwargs)
return header | python | def from_parent(cls,
parent: 'BlockHeader',
gas_limit: int,
difficulty: int,
timestamp: int,
coinbase: Address=ZERO_ADDRESS,
nonce: bytes=None,
extra_data: bytes=None,
transaction_root: bytes=None,
receipt_root: bytes=None) -> 'BlockHeader':
"""
Initialize a new block header with the `parent` header as the block's
parent hash.
"""
header_kwargs = {
'parent_hash': parent.hash,
'coinbase': coinbase,
'state_root': parent.state_root,
'gas_limit': gas_limit,
'difficulty': difficulty,
'block_number': parent.block_number + 1,
'timestamp': timestamp,
}
if nonce is not None:
header_kwargs['nonce'] = nonce
if extra_data is not None:
header_kwargs['extra_data'] = extra_data
if transaction_root is not None:
header_kwargs['transaction_root'] = transaction_root
if receipt_root is not None:
header_kwargs['receipt_root'] = receipt_root
header = cls(**header_kwargs)
return header | [
"def",
"from_parent",
"(",
"cls",
",",
"parent",
":",
"'BlockHeader'",
",",
"gas_limit",
":",
"int",
",",
"difficulty",
":",
"int",
",",
"timestamp",
":",
"int",
",",
"coinbase",
":",
"Address",
"=",
"ZERO_ADDRESS",
",",
"nonce",
":",
"bytes",
"=",
"None",
",",
"extra_data",
":",
"bytes",
"=",
"None",
",",
"transaction_root",
":",
"bytes",
"=",
"None",
",",
"receipt_root",
":",
"bytes",
"=",
"None",
")",
"->",
"'BlockHeader'",
":",
"header_kwargs",
"=",
"{",
"'parent_hash'",
":",
"parent",
".",
"hash",
",",
"'coinbase'",
":",
"coinbase",
",",
"'state_root'",
":",
"parent",
".",
"state_root",
",",
"'gas_limit'",
":",
"gas_limit",
",",
"'difficulty'",
":",
"difficulty",
",",
"'block_number'",
":",
"parent",
".",
"block_number",
"+",
"1",
",",
"'timestamp'",
":",
"timestamp",
",",
"}",
"if",
"nonce",
"is",
"not",
"None",
":",
"header_kwargs",
"[",
"'nonce'",
"]",
"=",
"nonce",
"if",
"extra_data",
"is",
"not",
"None",
":",
"header_kwargs",
"[",
"'extra_data'",
"]",
"=",
"extra_data",
"if",
"transaction_root",
"is",
"not",
"None",
":",
"header_kwargs",
"[",
"'transaction_root'",
"]",
"=",
"transaction_root",
"if",
"receipt_root",
"is",
"not",
"None",
":",
"header_kwargs",
"[",
"'receipt_root'",
"]",
"=",
"receipt_root",
"header",
"=",
"cls",
"(",
"*",
"*",
"header_kwargs",
")",
"return",
"header"
] | Initialize a new block header with the `parent` header as the block's
parent hash. | [
"Initialize",
"a",
"new",
"block",
"header",
"with",
"the",
"parent",
"header",
"as",
"the",
"block",
"s",
"parent",
"hash",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/rlp/headers.py#L170-L203 |
230,079 | ethereum/py-evm | eth/db/chain.py | ChainDB.get_block_uncles | def get_block_uncles(self, uncles_hash: Hash32) -> List[BlockHeader]:
"""
Returns an iterable of uncle headers specified by the given uncles_hash
"""
validate_word(uncles_hash, title="Uncles Hash")
if uncles_hash == EMPTY_UNCLE_HASH:
return []
try:
encoded_uncles = self.db[uncles_hash]
except KeyError:
raise HeaderNotFound(
"No uncles found for hash {0}".format(uncles_hash)
)
else:
return rlp.decode(encoded_uncles, sedes=rlp.sedes.CountableList(BlockHeader)) | python | def get_block_uncles(self, uncles_hash: Hash32) -> List[BlockHeader]:
"""
Returns an iterable of uncle headers specified by the given uncles_hash
"""
validate_word(uncles_hash, title="Uncles Hash")
if uncles_hash == EMPTY_UNCLE_HASH:
return []
try:
encoded_uncles = self.db[uncles_hash]
except KeyError:
raise HeaderNotFound(
"No uncles found for hash {0}".format(uncles_hash)
)
else:
return rlp.decode(encoded_uncles, sedes=rlp.sedes.CountableList(BlockHeader)) | [
"def",
"get_block_uncles",
"(",
"self",
",",
"uncles_hash",
":",
"Hash32",
")",
"->",
"List",
"[",
"BlockHeader",
"]",
":",
"validate_word",
"(",
"uncles_hash",
",",
"title",
"=",
"\"Uncles Hash\"",
")",
"if",
"uncles_hash",
"==",
"EMPTY_UNCLE_HASH",
":",
"return",
"[",
"]",
"try",
":",
"encoded_uncles",
"=",
"self",
".",
"db",
"[",
"uncles_hash",
"]",
"except",
"KeyError",
":",
"raise",
"HeaderNotFound",
"(",
"\"No uncles found for hash {0}\"",
".",
"format",
"(",
"uncles_hash",
")",
")",
"else",
":",
"return",
"rlp",
".",
"decode",
"(",
"encoded_uncles",
",",
"sedes",
"=",
"rlp",
".",
"sedes",
".",
"CountableList",
"(",
"BlockHeader",
")",
")"
] | Returns an iterable of uncle headers specified by the given uncles_hash | [
"Returns",
"an",
"iterable",
"of",
"uncle",
"headers",
"specified",
"by",
"the",
"given",
"uncles_hash"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L175-L189 |
230,080 | ethereum/py-evm | eth/db/chain.py | ChainDB.persist_block | def persist_block(self,
block: 'BaseBlock'
) -> Tuple[Tuple[Hash32, ...], Tuple[Hash32, ...]]:
"""
Persist the given block's header and uncles.
Assumes all block transactions have been persisted already.
"""
with self.db.atomic_batch() as db:
return self._persist_block(db, block) | python | def persist_block(self,
block: 'BaseBlock'
) -> Tuple[Tuple[Hash32, ...], Tuple[Hash32, ...]]:
"""
Persist the given block's header and uncles.
Assumes all block transactions have been persisted already.
"""
with self.db.atomic_batch() as db:
return self._persist_block(db, block) | [
"def",
"persist_block",
"(",
"self",
",",
"block",
":",
"'BaseBlock'",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"Hash32",
",",
"...",
"]",
",",
"Tuple",
"[",
"Hash32",
",",
"...",
"]",
"]",
":",
"with",
"self",
".",
"db",
".",
"atomic_batch",
"(",
")",
"as",
"db",
":",
"return",
"self",
".",
"_persist_block",
"(",
"db",
",",
"block",
")"
] | Persist the given block's header and uncles.
Assumes all block transactions have been persisted already. | [
"Persist",
"the",
"given",
"block",
"s",
"header",
"and",
"uncles",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L228-L237 |
230,081 | ethereum/py-evm | eth/db/chain.py | ChainDB.persist_uncles | def persist_uncles(self, uncles: Tuple[BlockHeader]) -> Hash32:
"""
Persists the list of uncles to the database.
Returns the uncles hash.
"""
return self._persist_uncles(self.db, uncles) | python | def persist_uncles(self, uncles: Tuple[BlockHeader]) -> Hash32:
"""
Persists the list of uncles to the database.
Returns the uncles hash.
"""
return self._persist_uncles(self.db, uncles) | [
"def",
"persist_uncles",
"(",
"self",
",",
"uncles",
":",
"Tuple",
"[",
"BlockHeader",
"]",
")",
"->",
"Hash32",
":",
"return",
"self",
".",
"_persist_uncles",
"(",
"self",
".",
"db",
",",
"uncles",
")"
] | Persists the list of uncles to the database.
Returns the uncles hash. | [
"Persists",
"the",
"list",
"of",
"uncles",
"to",
"the",
"database",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L273-L279 |
230,082 | ethereum/py-evm | eth/db/chain.py | ChainDB.add_receipt | def add_receipt(self, block_header: BlockHeader, index_key: int, receipt: Receipt) -> Hash32:
"""
Adds the given receipt to the provided block header.
Returns the updated `receipts_root` for updated block header.
"""
receipt_db = HexaryTrie(db=self.db, root_hash=block_header.receipt_root)
receipt_db[index_key] = rlp.encode(receipt)
return receipt_db.root_hash | python | def add_receipt(self, block_header: BlockHeader, index_key: int, receipt: Receipt) -> Hash32:
"""
Adds the given receipt to the provided block header.
Returns the updated `receipts_root` for updated block header.
"""
receipt_db = HexaryTrie(db=self.db, root_hash=block_header.receipt_root)
receipt_db[index_key] = rlp.encode(receipt)
return receipt_db.root_hash | [
"def",
"add_receipt",
"(",
"self",
",",
"block_header",
":",
"BlockHeader",
",",
"index_key",
":",
"int",
",",
"receipt",
":",
"Receipt",
")",
"->",
"Hash32",
":",
"receipt_db",
"=",
"HexaryTrie",
"(",
"db",
"=",
"self",
".",
"db",
",",
"root_hash",
"=",
"block_header",
".",
"receipt_root",
")",
"receipt_db",
"[",
"index_key",
"]",
"=",
"rlp",
".",
"encode",
"(",
"receipt",
")",
"return",
"receipt_db",
".",
"root_hash"
] | Adds the given receipt to the provided block header.
Returns the updated `receipts_root` for updated block header. | [
"Adds",
"the",
"given",
"receipt",
"to",
"the",
"provided",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L292-L300 |
230,083 | ethereum/py-evm | eth/db/chain.py | ChainDB.add_transaction | def add_transaction(self,
block_header: BlockHeader,
index_key: int,
transaction: 'BaseTransaction') -> Hash32:
"""
Adds the given transaction to the provided block header.
Returns the updated `transactions_root` for updated block header.
"""
transaction_db = HexaryTrie(self.db, root_hash=block_header.transaction_root)
transaction_db[index_key] = rlp.encode(transaction)
return transaction_db.root_hash | python | def add_transaction(self,
block_header: BlockHeader,
index_key: int,
transaction: 'BaseTransaction') -> Hash32:
"""
Adds the given transaction to the provided block header.
Returns the updated `transactions_root` for updated block header.
"""
transaction_db = HexaryTrie(self.db, root_hash=block_header.transaction_root)
transaction_db[index_key] = rlp.encode(transaction)
return transaction_db.root_hash | [
"def",
"add_transaction",
"(",
"self",
",",
"block_header",
":",
"BlockHeader",
",",
"index_key",
":",
"int",
",",
"transaction",
":",
"'BaseTransaction'",
")",
"->",
"Hash32",
":",
"transaction_db",
"=",
"HexaryTrie",
"(",
"self",
".",
"db",
",",
"root_hash",
"=",
"block_header",
".",
"transaction_root",
")",
"transaction_db",
"[",
"index_key",
"]",
"=",
"rlp",
".",
"encode",
"(",
"transaction",
")",
"return",
"transaction_db",
".",
"root_hash"
] | Adds the given transaction to the provided block header.
Returns the updated `transactions_root` for updated block header. | [
"Adds",
"the",
"given",
"transaction",
"to",
"the",
"provided",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L302-L313 |
230,084 | ethereum/py-evm | eth/db/chain.py | ChainDB.get_block_transactions | def get_block_transactions(
self,
header: BlockHeader,
transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']:
"""
Returns an iterable of transactions for the block speficied by the
given block header.
"""
return self._get_block_transactions(header.transaction_root, transaction_class) | python | def get_block_transactions(
self,
header: BlockHeader,
transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']:
"""
Returns an iterable of transactions for the block speficied by the
given block header.
"""
return self._get_block_transactions(header.transaction_root, transaction_class) | [
"def",
"get_block_transactions",
"(",
"self",
",",
"header",
":",
"BlockHeader",
",",
"transaction_class",
":",
"Type",
"[",
"'BaseTransaction'",
"]",
")",
"->",
"Iterable",
"[",
"'BaseTransaction'",
"]",
":",
"return",
"self",
".",
"_get_block_transactions",
"(",
"header",
".",
"transaction_root",
",",
"transaction_class",
")"
] | Returns an iterable of transactions for the block speficied by the
given block header. | [
"Returns",
"an",
"iterable",
"of",
"transactions",
"for",
"the",
"block",
"speficied",
"by",
"the",
"given",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L315-L323 |
230,085 | ethereum/py-evm | eth/db/chain.py | ChainDB.get_block_transaction_hashes | def get_block_transaction_hashes(self, block_header: BlockHeader) -> Iterable[Hash32]:
"""
Returns an iterable of the transaction hashes from the block specified
by the given block header.
"""
return self._get_block_transaction_hashes(self.db, block_header) | python | def get_block_transaction_hashes(self, block_header: BlockHeader) -> Iterable[Hash32]:
"""
Returns an iterable of the transaction hashes from the block specified
by the given block header.
"""
return self._get_block_transaction_hashes(self.db, block_header) | [
"def",
"get_block_transaction_hashes",
"(",
"self",
",",
"block_header",
":",
"BlockHeader",
")",
"->",
"Iterable",
"[",
"Hash32",
"]",
":",
"return",
"self",
".",
"_get_block_transaction_hashes",
"(",
"self",
".",
"db",
",",
"block_header",
")"
] | Returns an iterable of the transaction hashes from the block specified
by the given block header. | [
"Returns",
"an",
"iterable",
"of",
"the",
"transaction",
"hashes",
"from",
"the",
"block",
"specified",
"by",
"the",
"given",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L325-L330 |
230,086 | ethereum/py-evm | eth/db/chain.py | ChainDB.get_receipts | def get_receipts(self,
header: BlockHeader,
receipt_class: Type[Receipt]) -> Iterable[Receipt]:
"""
Returns an iterable of receipts for the block specified by the given
block header.
"""
receipt_db = HexaryTrie(db=self.db, root_hash=header.receipt_root)
for receipt_idx in itertools.count():
receipt_key = rlp.encode(receipt_idx)
if receipt_key in receipt_db:
receipt_data = receipt_db[receipt_key]
yield rlp.decode(receipt_data, sedes=receipt_class)
else:
break | python | def get_receipts(self,
header: BlockHeader,
receipt_class: Type[Receipt]) -> Iterable[Receipt]:
"""
Returns an iterable of receipts for the block specified by the given
block header.
"""
receipt_db = HexaryTrie(db=self.db, root_hash=header.receipt_root)
for receipt_idx in itertools.count():
receipt_key = rlp.encode(receipt_idx)
if receipt_key in receipt_db:
receipt_data = receipt_db[receipt_key]
yield rlp.decode(receipt_data, sedes=receipt_class)
else:
break | [
"def",
"get_receipts",
"(",
"self",
",",
"header",
":",
"BlockHeader",
",",
"receipt_class",
":",
"Type",
"[",
"Receipt",
"]",
")",
"->",
"Iterable",
"[",
"Receipt",
"]",
":",
"receipt_db",
"=",
"HexaryTrie",
"(",
"db",
"=",
"self",
".",
"db",
",",
"root_hash",
"=",
"header",
".",
"receipt_root",
")",
"for",
"receipt_idx",
"in",
"itertools",
".",
"count",
"(",
")",
":",
"receipt_key",
"=",
"rlp",
".",
"encode",
"(",
"receipt_idx",
")",
"if",
"receipt_key",
"in",
"receipt_db",
":",
"receipt_data",
"=",
"receipt_db",
"[",
"receipt_key",
"]",
"yield",
"rlp",
".",
"decode",
"(",
"receipt_data",
",",
"sedes",
"=",
"receipt_class",
")",
"else",
":",
"break"
] | Returns an iterable of receipts for the block specified by the given
block header. | [
"Returns",
"an",
"iterable",
"of",
"receipts",
"for",
"the",
"block",
"specified",
"by",
"the",
"given",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L346-L360 |
230,087 | ethereum/py-evm | eth/db/chain.py | ChainDB.get_transaction_by_index | def get_transaction_by_index(
self,
block_number: BlockNumber,
transaction_index: int,
transaction_class: Type['BaseTransaction']) -> 'BaseTransaction':
"""
Returns the transaction at the specified `transaction_index` from the
block specified by `block_number` from the canonical chain.
Raises TransactionNotFound if no block
"""
try:
block_header = self.get_canonical_block_header_by_number(block_number)
except HeaderNotFound:
raise TransactionNotFound("Block {} is not in the canonical chain".format(block_number))
transaction_db = HexaryTrie(self.db, root_hash=block_header.transaction_root)
encoded_index = rlp.encode(transaction_index)
if encoded_index in transaction_db:
encoded_transaction = transaction_db[encoded_index]
return rlp.decode(encoded_transaction, sedes=transaction_class)
else:
raise TransactionNotFound(
"No transaction is at index {} of block {}".format(transaction_index, block_number)) | python | def get_transaction_by_index(
self,
block_number: BlockNumber,
transaction_index: int,
transaction_class: Type['BaseTransaction']) -> 'BaseTransaction':
"""
Returns the transaction at the specified `transaction_index` from the
block specified by `block_number` from the canonical chain.
Raises TransactionNotFound if no block
"""
try:
block_header = self.get_canonical_block_header_by_number(block_number)
except HeaderNotFound:
raise TransactionNotFound("Block {} is not in the canonical chain".format(block_number))
transaction_db = HexaryTrie(self.db, root_hash=block_header.transaction_root)
encoded_index = rlp.encode(transaction_index)
if encoded_index in transaction_db:
encoded_transaction = transaction_db[encoded_index]
return rlp.decode(encoded_transaction, sedes=transaction_class)
else:
raise TransactionNotFound(
"No transaction is at index {} of block {}".format(transaction_index, block_number)) | [
"def",
"get_transaction_by_index",
"(",
"self",
",",
"block_number",
":",
"BlockNumber",
",",
"transaction_index",
":",
"int",
",",
"transaction_class",
":",
"Type",
"[",
"'BaseTransaction'",
"]",
")",
"->",
"'BaseTransaction'",
":",
"try",
":",
"block_header",
"=",
"self",
".",
"get_canonical_block_header_by_number",
"(",
"block_number",
")",
"except",
"HeaderNotFound",
":",
"raise",
"TransactionNotFound",
"(",
"\"Block {} is not in the canonical chain\"",
".",
"format",
"(",
"block_number",
")",
")",
"transaction_db",
"=",
"HexaryTrie",
"(",
"self",
".",
"db",
",",
"root_hash",
"=",
"block_header",
".",
"transaction_root",
")",
"encoded_index",
"=",
"rlp",
".",
"encode",
"(",
"transaction_index",
")",
"if",
"encoded_index",
"in",
"transaction_db",
":",
"encoded_transaction",
"=",
"transaction_db",
"[",
"encoded_index",
"]",
"return",
"rlp",
".",
"decode",
"(",
"encoded_transaction",
",",
"sedes",
"=",
"transaction_class",
")",
"else",
":",
"raise",
"TransactionNotFound",
"(",
"\"No transaction is at index {} of block {}\"",
".",
"format",
"(",
"transaction_index",
",",
"block_number",
")",
")"
] | Returns the transaction at the specified `transaction_index` from the
block specified by `block_number` from the canonical chain.
Raises TransactionNotFound if no block | [
"Returns",
"the",
"transaction",
"at",
"the",
"specified",
"transaction_index",
"from",
"the",
"block",
"specified",
"by",
"block_number",
"from",
"the",
"canonical",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L362-L384 |
230,088 | ethereum/py-evm | eth/db/chain.py | ChainDB.get_receipt_by_index | def get_receipt_by_index(self,
block_number: BlockNumber,
receipt_index: int) -> Receipt:
"""
Returns the Receipt of the transaction at specified index
for the block header obtained by the specified block number
"""
try:
block_header = self.get_canonical_block_header_by_number(block_number)
except HeaderNotFound:
raise ReceiptNotFound("Block {} is not in the canonical chain".format(block_number))
receipt_db = HexaryTrie(db=self.db, root_hash=block_header.receipt_root)
receipt_key = rlp.encode(receipt_index)
if receipt_key in receipt_db:
receipt_data = receipt_db[receipt_key]
return rlp.decode(receipt_data, sedes=Receipt)
else:
raise ReceiptNotFound(
"Receipt with index {} not found in block".format(receipt_index)) | python | def get_receipt_by_index(self,
block_number: BlockNumber,
receipt_index: int) -> Receipt:
"""
Returns the Receipt of the transaction at specified index
for the block header obtained by the specified block number
"""
try:
block_header = self.get_canonical_block_header_by_number(block_number)
except HeaderNotFound:
raise ReceiptNotFound("Block {} is not in the canonical chain".format(block_number))
receipt_db = HexaryTrie(db=self.db, root_hash=block_header.receipt_root)
receipt_key = rlp.encode(receipt_index)
if receipt_key in receipt_db:
receipt_data = receipt_db[receipt_key]
return rlp.decode(receipt_data, sedes=Receipt)
else:
raise ReceiptNotFound(
"Receipt with index {} not found in block".format(receipt_index)) | [
"def",
"get_receipt_by_index",
"(",
"self",
",",
"block_number",
":",
"BlockNumber",
",",
"receipt_index",
":",
"int",
")",
"->",
"Receipt",
":",
"try",
":",
"block_header",
"=",
"self",
".",
"get_canonical_block_header_by_number",
"(",
"block_number",
")",
"except",
"HeaderNotFound",
":",
"raise",
"ReceiptNotFound",
"(",
"\"Block {} is not in the canonical chain\"",
".",
"format",
"(",
"block_number",
")",
")",
"receipt_db",
"=",
"HexaryTrie",
"(",
"db",
"=",
"self",
".",
"db",
",",
"root_hash",
"=",
"block_header",
".",
"receipt_root",
")",
"receipt_key",
"=",
"rlp",
".",
"encode",
"(",
"receipt_index",
")",
"if",
"receipt_key",
"in",
"receipt_db",
":",
"receipt_data",
"=",
"receipt_db",
"[",
"receipt_key",
"]",
"return",
"rlp",
".",
"decode",
"(",
"receipt_data",
",",
"sedes",
"=",
"Receipt",
")",
"else",
":",
"raise",
"ReceiptNotFound",
"(",
"\"Receipt with index {} not found in block\"",
".",
"format",
"(",
"receipt_index",
")",
")"
] | Returns the Receipt of the transaction at specified index
for the block header obtained by the specified block number | [
"Returns",
"the",
"Receipt",
"of",
"the",
"transaction",
"at",
"specified",
"index",
"for",
"the",
"block",
"header",
"obtained",
"by",
"the",
"specified",
"block",
"number"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L405-L424 |
230,089 | ethereum/py-evm | eth/db/chain.py | ChainDB._get_block_transaction_data | def _get_block_transaction_data(db: BaseDB, transaction_root: Hash32) -> Iterable[Hash32]:
"""
Returns iterable of the encoded transactions for the given block header
"""
transaction_db = HexaryTrie(db, root_hash=transaction_root)
for transaction_idx in itertools.count():
transaction_key = rlp.encode(transaction_idx)
if transaction_key in transaction_db:
yield transaction_db[transaction_key]
else:
break | python | def _get_block_transaction_data(db: BaseDB, transaction_root: Hash32) -> Iterable[Hash32]:
"""
Returns iterable of the encoded transactions for the given block header
"""
transaction_db = HexaryTrie(db, root_hash=transaction_root)
for transaction_idx in itertools.count():
transaction_key = rlp.encode(transaction_idx)
if transaction_key in transaction_db:
yield transaction_db[transaction_key]
else:
break | [
"def",
"_get_block_transaction_data",
"(",
"db",
":",
"BaseDB",
",",
"transaction_root",
":",
"Hash32",
")",
"->",
"Iterable",
"[",
"Hash32",
"]",
":",
"transaction_db",
"=",
"HexaryTrie",
"(",
"db",
",",
"root_hash",
"=",
"transaction_root",
")",
"for",
"transaction_idx",
"in",
"itertools",
".",
"count",
"(",
")",
":",
"transaction_key",
"=",
"rlp",
".",
"encode",
"(",
"transaction_idx",
")",
"if",
"transaction_key",
"in",
"transaction_db",
":",
"yield",
"transaction_db",
"[",
"transaction_key",
"]",
"else",
":",
"break"
] | Returns iterable of the encoded transactions for the given block header | [
"Returns",
"iterable",
"of",
"the",
"encoded",
"transactions",
"for",
"the",
"given",
"block",
"header"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L427-L437 |
230,090 | ethereum/py-evm | eth/db/chain.py | ChainDB._get_block_transactions | def _get_block_transactions(
self,
transaction_root: Hash32,
transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']:
"""
Memoizable version of `get_block_transactions`
"""
for encoded_transaction in self._get_block_transaction_data(self.db, transaction_root):
yield rlp.decode(encoded_transaction, sedes=transaction_class) | python | def _get_block_transactions(
self,
transaction_root: Hash32,
transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']:
"""
Memoizable version of `get_block_transactions`
"""
for encoded_transaction in self._get_block_transaction_data(self.db, transaction_root):
yield rlp.decode(encoded_transaction, sedes=transaction_class) | [
"def",
"_get_block_transactions",
"(",
"self",
",",
"transaction_root",
":",
"Hash32",
",",
"transaction_class",
":",
"Type",
"[",
"'BaseTransaction'",
"]",
")",
"->",
"Iterable",
"[",
"'BaseTransaction'",
"]",
":",
"for",
"encoded_transaction",
"in",
"self",
".",
"_get_block_transaction_data",
"(",
"self",
".",
"db",
",",
"transaction_root",
")",
":",
"yield",
"rlp",
".",
"decode",
"(",
"encoded_transaction",
",",
"sedes",
"=",
"transaction_class",
")"
] | Memoizable version of `get_block_transactions` | [
"Memoizable",
"version",
"of",
"get_block_transactions"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L441-L449 |
230,091 | ethereum/py-evm | eth/db/chain.py | ChainDB._remove_transaction_from_canonical_chain | def _remove_transaction_from_canonical_chain(db: BaseDB, transaction_hash: Hash32) -> None:
"""
Removes the transaction specified by the given hash from the canonical
chain.
"""
db.delete(SchemaV1.make_transaction_hash_to_block_lookup_key(transaction_hash)) | python | def _remove_transaction_from_canonical_chain(db: BaseDB, transaction_hash: Hash32) -> None:
"""
Removes the transaction specified by the given hash from the canonical
chain.
"""
db.delete(SchemaV1.make_transaction_hash_to_block_lookup_key(transaction_hash)) | [
"def",
"_remove_transaction_from_canonical_chain",
"(",
"db",
":",
"BaseDB",
",",
"transaction_hash",
":",
"Hash32",
")",
"->",
"None",
":",
"db",
".",
"delete",
"(",
"SchemaV1",
".",
"make_transaction_hash_to_block_lookup_key",
"(",
"transaction_hash",
")",
")"
] | Removes the transaction specified by the given hash from the canonical
chain. | [
"Removes",
"the",
"transaction",
"specified",
"by",
"the",
"given",
"hash",
"from",
"the",
"canonical",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L452-L457 |
230,092 | ethereum/py-evm | eth/db/chain.py | ChainDB.persist_trie_data_dict | def persist_trie_data_dict(self, trie_data_dict: Dict[Hash32, bytes]) -> None:
"""
Store raw trie data to db from a dict
"""
with self.db.atomic_batch() as db:
for key, value in trie_data_dict.items():
db[key] = value | python | def persist_trie_data_dict(self, trie_data_dict: Dict[Hash32, bytes]) -> None:
"""
Store raw trie data to db from a dict
"""
with self.db.atomic_batch() as db:
for key, value in trie_data_dict.items():
db[key] = value | [
"def",
"persist_trie_data_dict",
"(",
"self",
",",
"trie_data_dict",
":",
"Dict",
"[",
"Hash32",
",",
"bytes",
"]",
")",
"->",
"None",
":",
"with",
"self",
".",
"db",
".",
"atomic_batch",
"(",
")",
"as",
"db",
":",
"for",
"key",
",",
"value",
"in",
"trie_data_dict",
".",
"items",
"(",
")",
":",
"db",
"[",
"key",
"]",
"=",
"value"
] | Store raw trie data to db from a dict | [
"Store",
"raw",
"trie",
"data",
"to",
"db",
"from",
"a",
"dict"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L492-L498 |
230,093 | ethereum/py-evm | eth/vm/forks/frontier/blocks.py | FrontierBlock.from_header | def from_header(cls, header: BlockHeader, chaindb: BaseChainDB) -> BaseBlock:
"""
Returns the block denoted by the given block header.
"""
if header.uncles_hash == EMPTY_UNCLE_HASH:
uncles = [] # type: List[BlockHeader]
else:
uncles = chaindb.get_block_uncles(header.uncles_hash)
transactions = chaindb.get_block_transactions(header, cls.get_transaction_class())
return cls(
header=header,
transactions=transactions,
uncles=uncles,
) | python | def from_header(cls, header: BlockHeader, chaindb: BaseChainDB) -> BaseBlock:
"""
Returns the block denoted by the given block header.
"""
if header.uncles_hash == EMPTY_UNCLE_HASH:
uncles = [] # type: List[BlockHeader]
else:
uncles = chaindb.get_block_uncles(header.uncles_hash)
transactions = chaindb.get_block_transactions(header, cls.get_transaction_class())
return cls(
header=header,
transactions=transactions,
uncles=uncles,
) | [
"def",
"from_header",
"(",
"cls",
",",
"header",
":",
"BlockHeader",
",",
"chaindb",
":",
"BaseChainDB",
")",
"->",
"BaseBlock",
":",
"if",
"header",
".",
"uncles_hash",
"==",
"EMPTY_UNCLE_HASH",
":",
"uncles",
"=",
"[",
"]",
"# type: List[BlockHeader]",
"else",
":",
"uncles",
"=",
"chaindb",
".",
"get_block_uncles",
"(",
"header",
".",
"uncles_hash",
")",
"transactions",
"=",
"chaindb",
".",
"get_block_transactions",
"(",
"header",
",",
"cls",
".",
"get_transaction_class",
"(",
")",
")",
"return",
"cls",
"(",
"header",
"=",
"header",
",",
"transactions",
"=",
"transactions",
",",
"uncles",
"=",
"uncles",
",",
")"
] | Returns the block denoted by the given block header. | [
"Returns",
"the",
"block",
"denoted",
"by",
"the",
"given",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/forks/frontier/blocks.py#L104-L119 |
230,094 | ethereum/py-evm | eth/vm/logic/arithmetic.py | shl | def shl(computation: BaseComputation) -> None:
"""
Bitwise left shift
"""
shift_length, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
if shift_length >= 256:
result = 0
else:
result = (value << shift_length) & constants.UINT_256_MAX
computation.stack_push(result) | python | def shl(computation: BaseComputation) -> None:
"""
Bitwise left shift
"""
shift_length, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
if shift_length >= 256:
result = 0
else:
result = (value << shift_length) & constants.UINT_256_MAX
computation.stack_push(result) | [
"def",
"shl",
"(",
"computation",
":",
"BaseComputation",
")",
"->",
"None",
":",
"shift_length",
",",
"value",
"=",
"computation",
".",
"stack_pop",
"(",
"num_items",
"=",
"2",
",",
"type_hint",
"=",
"constants",
".",
"UINT256",
")",
"if",
"shift_length",
">=",
"256",
":",
"result",
"=",
"0",
"else",
":",
"result",
"=",
"(",
"value",
"<<",
"shift_length",
")",
"&",
"constants",
".",
"UINT_256_MAX",
"computation",
".",
"stack_push",
"(",
"result",
")"
] | Bitwise left shift | [
"Bitwise",
"left",
"shift"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/arithmetic.py#L186-L197 |
230,095 | ethereum/py-evm | eth/vm/logic/arithmetic.py | sar | def sar(computation: BaseComputation) -> None:
"""
Arithmetic bitwise right shift
"""
shift_length, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
value = unsigned_to_signed(value)
if shift_length >= 256:
result = 0 if value >= 0 else constants.UINT_255_NEGATIVE_ONE
else:
result = (value >> shift_length) & constants.UINT_256_MAX
computation.stack_push(result) | python | def sar(computation: BaseComputation) -> None:
"""
Arithmetic bitwise right shift
"""
shift_length, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
value = unsigned_to_signed(value)
if shift_length >= 256:
result = 0 if value >= 0 else constants.UINT_255_NEGATIVE_ONE
else:
result = (value >> shift_length) & constants.UINT_256_MAX
computation.stack_push(result) | [
"def",
"sar",
"(",
"computation",
":",
"BaseComputation",
")",
"->",
"None",
":",
"shift_length",
",",
"value",
"=",
"computation",
".",
"stack_pop",
"(",
"num_items",
"=",
"2",
",",
"type_hint",
"=",
"constants",
".",
"UINT256",
")",
"value",
"=",
"unsigned_to_signed",
"(",
"value",
")",
"if",
"shift_length",
">=",
"256",
":",
"result",
"=",
"0",
"if",
"value",
">=",
"0",
"else",
"constants",
".",
"UINT_255_NEGATIVE_ONE",
"else",
":",
"result",
"=",
"(",
"value",
">>",
"shift_length",
")",
"&",
"constants",
".",
"UINT_256_MAX",
"computation",
".",
"stack_push",
"(",
"result",
")"
] | Arithmetic bitwise right shift | [
"Arithmetic",
"bitwise",
"right",
"shift"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/arithmetic.py#L214-L226 |
230,096 | ethereum/py-evm | eth/vm/forks/frontier/headers.py | compute_frontier_difficulty | def compute_frontier_difficulty(parent_header: BlockHeader, timestamp: int) -> int:
"""
Computes the difficulty for a frontier block based on the parent block.
"""
validate_gt(timestamp, parent_header.timestamp, title="Header timestamp")
offset = parent_header.difficulty // DIFFICULTY_ADJUSTMENT_DENOMINATOR
# We set the minimum to the lowest of the protocol minimum and the parent
# minimum to allow for the initial frontier *warming* period during which
# the difficulty begins lower than the protocol minimum.
difficulty_minimum = min(parent_header.difficulty, DIFFICULTY_MINIMUM)
if timestamp - parent_header.timestamp < FRONTIER_DIFFICULTY_ADJUSTMENT_CUTOFF:
base_difficulty = max(
parent_header.difficulty + offset,
difficulty_minimum,
)
else:
base_difficulty = max(
parent_header.difficulty - offset,
difficulty_minimum,
)
# Adjust for difficulty bomb.
num_bomb_periods = (
(parent_header.block_number + 1) // BOMB_EXPONENTIAL_PERIOD
) - BOMB_EXPONENTIAL_FREE_PERIODS
if num_bomb_periods >= 0:
difficulty = max(
base_difficulty + 2**num_bomb_periods,
DIFFICULTY_MINIMUM,
)
else:
difficulty = base_difficulty
return difficulty | python | def compute_frontier_difficulty(parent_header: BlockHeader, timestamp: int) -> int:
"""
Computes the difficulty for a frontier block based on the parent block.
"""
validate_gt(timestamp, parent_header.timestamp, title="Header timestamp")
offset = parent_header.difficulty // DIFFICULTY_ADJUSTMENT_DENOMINATOR
# We set the minimum to the lowest of the protocol minimum and the parent
# minimum to allow for the initial frontier *warming* period during which
# the difficulty begins lower than the protocol minimum.
difficulty_minimum = min(parent_header.difficulty, DIFFICULTY_MINIMUM)
if timestamp - parent_header.timestamp < FRONTIER_DIFFICULTY_ADJUSTMENT_CUTOFF:
base_difficulty = max(
parent_header.difficulty + offset,
difficulty_minimum,
)
else:
base_difficulty = max(
parent_header.difficulty - offset,
difficulty_minimum,
)
# Adjust for difficulty bomb.
num_bomb_periods = (
(parent_header.block_number + 1) // BOMB_EXPONENTIAL_PERIOD
) - BOMB_EXPONENTIAL_FREE_PERIODS
if num_bomb_periods >= 0:
difficulty = max(
base_difficulty + 2**num_bomb_periods,
DIFFICULTY_MINIMUM,
)
else:
difficulty = base_difficulty
return difficulty | [
"def",
"compute_frontier_difficulty",
"(",
"parent_header",
":",
"BlockHeader",
",",
"timestamp",
":",
"int",
")",
"->",
"int",
":",
"validate_gt",
"(",
"timestamp",
",",
"parent_header",
".",
"timestamp",
",",
"title",
"=",
"\"Header timestamp\"",
")",
"offset",
"=",
"parent_header",
".",
"difficulty",
"//",
"DIFFICULTY_ADJUSTMENT_DENOMINATOR",
"# We set the minimum to the lowest of the protocol minimum and the parent",
"# minimum to allow for the initial frontier *warming* period during which",
"# the difficulty begins lower than the protocol minimum.",
"difficulty_minimum",
"=",
"min",
"(",
"parent_header",
".",
"difficulty",
",",
"DIFFICULTY_MINIMUM",
")",
"if",
"timestamp",
"-",
"parent_header",
".",
"timestamp",
"<",
"FRONTIER_DIFFICULTY_ADJUSTMENT_CUTOFF",
":",
"base_difficulty",
"=",
"max",
"(",
"parent_header",
".",
"difficulty",
"+",
"offset",
",",
"difficulty_minimum",
",",
")",
"else",
":",
"base_difficulty",
"=",
"max",
"(",
"parent_header",
".",
"difficulty",
"-",
"offset",
",",
"difficulty_minimum",
",",
")",
"# Adjust for difficulty bomb.",
"num_bomb_periods",
"=",
"(",
"(",
"parent_header",
".",
"block_number",
"+",
"1",
")",
"//",
"BOMB_EXPONENTIAL_PERIOD",
")",
"-",
"BOMB_EXPONENTIAL_FREE_PERIODS",
"if",
"num_bomb_periods",
">=",
"0",
":",
"difficulty",
"=",
"max",
"(",
"base_difficulty",
"+",
"2",
"**",
"num_bomb_periods",
",",
"DIFFICULTY_MINIMUM",
",",
")",
"else",
":",
"difficulty",
"=",
"base_difficulty",
"return",
"difficulty"
] | Computes the difficulty for a frontier block based on the parent block. | [
"Computes",
"the",
"difficulty",
"for",
"a",
"frontier",
"block",
"based",
"on",
"the",
"parent",
"block",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/forks/frontier/headers.py#L36-L73 |
230,097 | ethereum/py-evm | eth/vm/forks/frontier/state.py | FrontierTransactionExecutor.build_computation | def build_computation(self,
message: Message,
transaction: BaseOrSpoofTransaction) -> BaseComputation:
"""Apply the message to the VM."""
transaction_context = self.vm_state.get_transaction_context(transaction)
if message.is_create:
is_collision = self.vm_state.has_code_or_nonce(
message.storage_address
)
if is_collision:
# The address of the newly created contract has *somehow* collided
# with an existing contract address.
computation = self.vm_state.get_computation(message, transaction_context)
computation._error = ContractCreationCollision(
"Address collision while creating contract: {0}".format(
encode_hex(message.storage_address),
)
)
self.vm_state.logger.debug2(
"Address collision while creating contract: %s",
encode_hex(message.storage_address),
)
else:
computation = self.vm_state.get_computation(
message,
transaction_context,
).apply_create_message()
else:
computation = self.vm_state.get_computation(
message,
transaction_context).apply_message()
return computation | python | def build_computation(self,
message: Message,
transaction: BaseOrSpoofTransaction) -> BaseComputation:
"""Apply the message to the VM."""
transaction_context = self.vm_state.get_transaction_context(transaction)
if message.is_create:
is_collision = self.vm_state.has_code_or_nonce(
message.storage_address
)
if is_collision:
# The address of the newly created contract has *somehow* collided
# with an existing contract address.
computation = self.vm_state.get_computation(message, transaction_context)
computation._error = ContractCreationCollision(
"Address collision while creating contract: {0}".format(
encode_hex(message.storage_address),
)
)
self.vm_state.logger.debug2(
"Address collision while creating contract: %s",
encode_hex(message.storage_address),
)
else:
computation = self.vm_state.get_computation(
message,
transaction_context,
).apply_create_message()
else:
computation = self.vm_state.get_computation(
message,
transaction_context).apply_message()
return computation | [
"def",
"build_computation",
"(",
"self",
",",
"message",
":",
"Message",
",",
"transaction",
":",
"BaseOrSpoofTransaction",
")",
"->",
"BaseComputation",
":",
"transaction_context",
"=",
"self",
".",
"vm_state",
".",
"get_transaction_context",
"(",
"transaction",
")",
"if",
"message",
".",
"is_create",
":",
"is_collision",
"=",
"self",
".",
"vm_state",
".",
"has_code_or_nonce",
"(",
"message",
".",
"storage_address",
")",
"if",
"is_collision",
":",
"# The address of the newly created contract has *somehow* collided",
"# with an existing contract address.",
"computation",
"=",
"self",
".",
"vm_state",
".",
"get_computation",
"(",
"message",
",",
"transaction_context",
")",
"computation",
".",
"_error",
"=",
"ContractCreationCollision",
"(",
"\"Address collision while creating contract: {0}\"",
".",
"format",
"(",
"encode_hex",
"(",
"message",
".",
"storage_address",
")",
",",
")",
")",
"self",
".",
"vm_state",
".",
"logger",
".",
"debug2",
"(",
"\"Address collision while creating contract: %s\"",
",",
"encode_hex",
"(",
"message",
".",
"storage_address",
")",
",",
")",
"else",
":",
"computation",
"=",
"self",
".",
"vm_state",
".",
"get_computation",
"(",
"message",
",",
"transaction_context",
",",
")",
".",
"apply_create_message",
"(",
")",
"else",
":",
"computation",
"=",
"self",
".",
"vm_state",
".",
"get_computation",
"(",
"message",
",",
"transaction_context",
")",
".",
"apply_message",
"(",
")",
"return",
"computation"
] | Apply the message to the VM. | [
"Apply",
"the",
"message",
"to",
"the",
"VM",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/forks/frontier/state.py#L107-L140 |
230,098 | ethereum/py-evm | eth/vm/stack.py | Stack.push | def push(self, value: Union[int, bytes]) -> None:
"""
Push an item onto the stack.
"""
if len(self.values) > 1023:
raise FullStack('Stack limit reached')
validate_stack_item(value)
self.values.append(value) | python | def push(self, value: Union[int, bytes]) -> None:
"""
Push an item onto the stack.
"""
if len(self.values) > 1023:
raise FullStack('Stack limit reached')
validate_stack_item(value)
self.values.append(value) | [
"def",
"push",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"int",
",",
"bytes",
"]",
")",
"->",
"None",
":",
"if",
"len",
"(",
"self",
".",
"values",
")",
">",
"1023",
":",
"raise",
"FullStack",
"(",
"'Stack limit reached'",
")",
"validate_stack_item",
"(",
"value",
")",
"self",
".",
"values",
".",
"append",
"(",
"value",
")"
] | Push an item onto the stack. | [
"Push",
"an",
"item",
"onto",
"the",
"stack",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/stack.py#L38-L47 |
230,099 | ethereum/py-evm | eth/vm/stack.py | Stack.pop | def pop(self,
num_items: int,
type_hint: str) -> Union[int, bytes, Tuple[Union[int, bytes], ...]]:
"""
Pop an item off the stack.
Note: This function is optimized for speed over readability.
"""
try:
if num_items == 1:
return next(self._pop(num_items, type_hint))
else:
return tuple(self._pop(num_items, type_hint))
except IndexError:
raise InsufficientStack("No stack items") | python | def pop(self,
num_items: int,
type_hint: str) -> Union[int, bytes, Tuple[Union[int, bytes], ...]]:
"""
Pop an item off the stack.
Note: This function is optimized for speed over readability.
"""
try:
if num_items == 1:
return next(self._pop(num_items, type_hint))
else:
return tuple(self._pop(num_items, type_hint))
except IndexError:
raise InsufficientStack("No stack items") | [
"def",
"pop",
"(",
"self",
",",
"num_items",
":",
"int",
",",
"type_hint",
":",
"str",
")",
"->",
"Union",
"[",
"int",
",",
"bytes",
",",
"Tuple",
"[",
"Union",
"[",
"int",
",",
"bytes",
"]",
",",
"...",
"]",
"]",
":",
"try",
":",
"if",
"num_items",
"==",
"1",
":",
"return",
"next",
"(",
"self",
".",
"_pop",
"(",
"num_items",
",",
"type_hint",
")",
")",
"else",
":",
"return",
"tuple",
"(",
"self",
".",
"_pop",
"(",
"num_items",
",",
"type_hint",
")",
")",
"except",
"IndexError",
":",
"raise",
"InsufficientStack",
"(",
"\"No stack items\"",
")"
] | Pop an item off the stack.
Note: This function is optimized for speed over readability. | [
"Pop",
"an",
"item",
"off",
"the",
"stack",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/stack.py#L49-L63 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.