code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
handler = WSGIHandler()
try:
from django.contrib.staticfiles.handlers import StaticFilesHandler
except ImportError:
return handler
use_static_handler = options.get('use_static_handler', True)
insecure_serving = options.get('insecure_serving', Fals... | def get_handler(self, *args, **options) | Returns the django.contrib.staticfiles handler. | 2.648917 | 2.407609 | 1.100227 |
for handler, pattern in self.handlers:
no_channel = not pattern and not socket.channels
if self.name.endswith("subscribe") and pattern:
matches = [pattern.match(args[0])]
else:
matches = [pattern.match(c) for c in socket.channels if pa... | def send(self, request, socket, context, *args) | When an event is sent, run all relevant handlers. Relevant
handlers are those without a channel pattern when the given
socket is not subscribed to any particular channel, or the
handlers with a channel pattern that matches any of the
channels that the given socket is subscribed to.
... | 4.847256 | 4.148442 | 1.168452 |
context = {"rooms": ChatRoom.objects.all()}
return render(request, template, context) | def rooms(request, template="rooms.html") | Homepage - lists all rooms. | 3.14245 | 2.81094 | 1.117936 |
context = {"room": get_object_or_404(ChatRoom, slug=slug)}
return render(request, template, context) | def room(request, slug, template="room.html") | Show a room. | 2.43496 | 2.222161 | 1.095762 |
name = request.POST.get("name")
if name:
room, created = ChatRoom.objects.get_or_create(name=name)
return redirect(room)
return redirect(rooms) | def create(request) | Handles post from the "Add room" form on the homepage, and
redirects to the new room. | 3.269981 | 3.127995 | 1.045392 |
if isinstance(color, tuple) and len(color) == 3: # already a tuple of RGB values
return color
try:
import matplotlib.colors as mplcolors
except:
raise ImportError("Error importing matplotlib. If running from within a jupyter notebook, try calling '%matplotlib inline' beforehan... | def get_color(color) | Takes a string for a color name defined in matplotlib and returns of a 3-tuple of RGB values.
Will simply return passed value if it's a tuple of length three.
Parameters
----------
color : str
Name of matplotlib color to calculate RGB values for. | 3.211849 | 3.15154 | 1.019136 |
try:
from matplotlib.collections import LineCollection
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
except:
raise ImportError("Error importing matplotlib and/or numpy. Plotting functions not available. If running from within a jupyter notebook, tr... | def fading_line(x, y, color='black', alpha_initial=1., alpha_final=0., glow=False, **kwargs) | Returns a matplotlib LineCollection connecting the points in the x and y lists, with a single color and alpha varying from alpha_initial to alpha_final along the line.
Can pass any kwargs you can pass to LineCollection, like linewidgth.
Parameters
----------
x : list or array of floats for the po... | 2.127546 | 2.159368 | 0.985263 |
if t>self.tmax or t<self.tmin:
raise ValueError("Requested time outside of baseline stored in binary file.")
# Bisection method
l = 0
r = len(self)
while True:
bi = l+(r-l)//2
if self.t[bi]>t:
r = bi
else:
... | def _getSnapshotIndex(self, t) | Return the index for the snapshot just before t | 4.552226 | 4.4973 | 1.012213 |
if mode not in ['snapshot', 'close', 'exact']:
raise AttributeError("Unknown mode.")
bi, bt = self._getSnapshotIndex(t)
sim = Simulation()
w = c_int(0)
clibrebound.reb_create_simulation_from_simulationarchive_with_messages(byref(sim),byref(self),bi,byref(w))... | def getSimulation(self, t, mode='snapshot', keep_unsynchronized=1) | This function returns a simulation object at (or close to) the requested time `t`.
Everytime this function is called a new simulation object is created.
Arguments
---------
t : float
Requested time. Needs to be within tmin and tmax of this Simulation Archive.
mode ... | 5.395493 | 5.544243 | 0.97317 |
for t in times:
yield self.getSimulation(t, **kwargs) | def getSimulations(self, times, **kwargs) | A generator to quickly access many simulations.
The arguments are the same as for `getSimulation`. | 4.173199 | 3.288859 | 1.268889 |
import numpy as np
Npoints = len(self)*3-2
if len(self)<=1:
raise Runtim
Nparticles = self[0].N
verts = np.zeros((Npoints,Nparticles,2))
xy = np.zeros((len(self),Nparticles,2))
if origin=="com":
origin = -2
elif origin is ... | def getBezierPaths(self,origin=None) | This function returns array that can be used as a Cubic Bezier
Path in matplotlib.
The function returns two arrays, the first one contains
the verticies for each particles and has the shape
(Nvert, Nparticles, 2) where Nvert is the number of verticies.
The second array returned ... | 2.932801 | 2.791596 | 1.050582 |
np = Particle()
memmove(byref(np), byref(self), sizeof(self))
return np | def copy(self) | Returns a deep copy of the particle. The particle is not added to any simulation by default. | 9.116388 | 5.591738 | 1.630332 |
if not self._sim:
# Particle not in a simulation
if primary is None:
raise ValueError("Particle does not belong to any simulation and no primary given. Cannot calculate orbit.")
if G is None:
raise ValueError("Particle does not belong ... | def calculate_orbit(self, primary=None, G=None) | Returns a rebound.Orbit object with the keplerian orbital elements
corresponding to the particle around the passed primary
(rebound.Particle) If no primary is passed, defaults to Jacobi coordinates
(with mu = G*Minc, where Minc is the total mass from index 0 to the particle's index, inclusive). ... | 4.81449 | 4.313882 | 1.116046 |
pts = []
if primary is None:
primary = self.jacobi_com
o = self.calculate_orbit(primary=primary)
if timespan is None:
if o.a < 0.: # hyperbolic orbit
timespan = 2*math.pi*o.d/o.v # rough time to cross display box
else:
... | def sample_orbit(self, Npts=100, primary=None, trailing=True, timespan=None, useTrueAnomaly=True) | Returns a nested list of xyz positions along the osculating orbit of the particle.
If primary is not passed, returns xyz positions along the Jacobi osculating orbit
(with mu = G*Minc, where Minc is the total mass from index 0 to the particle's index, inclusive).
Parameters
----------
... | 4.303813 | 3.911779 | 1.100219 |
if simp==None:
simp = self.simp
if self.autorefresh==0 and isauto==1:
return
sim = simp.contents
size_changed = clibrebound.reb_display_copy_data(simp)
clibrebound.reb_display_prepare_data(simp,c_int(self.orbits))
if sim.N>0:
... | def refresh(self, simp=None, isauto=0) | Manually refreshes a widget.
Note that this function can also be called using the wrapper function of
the Simulation object: sim.refreshWidgets(). | 4.456234 | 4.43067 | 1.00577 |
self.archive = archive
if resetCounter:
self.screenshotcountall = 0
self.screenshotprefix = prefix
self.screenshotcount = 0
self.overlay = "REBOUND"
self.screenshot = ""
if archive is None:
if times is None:
times ... | def takeScreenshot(self, times=None, prefix="./screenshot", resetCounter=False, archive=None,mode="snapshot") | Take one or more screenshots of the widget and save the images to a file.
The images can be used to create a video.
This function cannot be called multiple times within one cell.
Note: this is a new feature and might not work on all systems.
It was tested on python 2.7.10 and 3.5.2 on... | 5.470926 | 5.624726 | 0.972657 |
i = self._coordinates
for name, _i in COORDINATES.items():
if i==_i:
return name
return i | def coordinates(self) | Get or set the internal coordinate system.
Available coordinate systems are:
- ``'jacobi'`` (default)
- ``'democraticheliocentric'``
- ``'whds'`` | 9.348881 | 10.450334 | 0.894601 |
warnings.warn( "rebound.Simulation.from_archive(filename,snapshot) is deprecated and will be removed in the future. Use rebound.Simulation(filename,snapshot) instead", FutureWarning)
return cls(filename=filename,snapshot=snapshot) | def from_archive(cls, filename,snapshot=-1) | rebound.Simulation.from_archive(filename,snapshot) is deprecated and will be removed in the futute. Use rebound.Simulation(filename,snapshot) instead | 3.988977 | 2.234042 | 1.785543 |
w = c_int(0)
sim = Simulation()
clibrebound._reb_copy_simulation_with_messages(byref(sim),byref(self),byref(w))
for majorerror, value, message in BINARY_WARNINGS:
if w.value & value:
if majorerror:
raise RuntimeError(message)
... | def copy(self) | Returns a deep copy of a REBOUND simulation. You need to reset
any function pointers on the copy.
Returns
-------
A rebound.Simulation object. | 9.344072 | 8.416058 | 1.110267 |
from .widget import Widget # ondemand
from ipywidgets import DOMWidget
from IPython.display import display, HTML
if not hasattr(self, '_widgets'):
self._widgets = []
def display_heartbeat(simp):
for w in self._widgets:
... | def getWidget(self,**kwargs) | Wrapper function that returns a new widget attached to this simulation.
Widgets provide real-time 3D visualizations from within an Jupyter notebook.
See the Widget class for more details on the possible arguments.
Arguments
---------
All arguments passed to thi... | 11.118963 | 11.472612 | 0.969174 |
if hasattr(self, '_widgets'):
for w in self._widgets:
w.refresh(isauto=0)
else:
raise RuntimeError("No widgets found") | def refreshWidgets(self) | This function manually refreshed all widgets attached to this simulation.
You want to call this function if any particle data has been manually changed. | 6.784305 | 6.732412 | 1.007708 |
modes = sum(1 for i in [interval, walltime,step] if i != None)
if modes != 1:
raise AttributeError("Need to specify either interval, walltime, or step")
if deletefile and os.path.isfile(filename):
os.remove(filename)
if interval:
clibrebound.r... | def automateSimulationArchive(self, filename, interval=None, walltime=None, step=None, deletefile=False) | This function automates taking snapshots during a simulationusing the Simulation Archive.
Instead of using this function, one can also call simulationarchive_snapshot() manually
to create snapshots.
Arguments
---------
filename : str
Filename of the binary f... | 2.426007 | 2.971781 | 0.816348 |
clibrebound.reb_simulationarchive_snapshot(byref(self), c_char_p(filename.encode("ascii"))) | def simulationarchive_snapshot(self, filename) | Take a snapshot and save it to a SimulationArchive file.
If the file does not exist yet, a new one will be created.
If the file does exist, a snapshot will be appended.
Arguments
---------
filename : str
Filename of the binary file. | 7.288963 | 10.762334 | 0.677266 |
from rebound import __version__, __build__
s= ""
s += "---------------------------------\n"
s += "REBOUND version: \t%s\n" %__version__
s += "REBOUND built on: \t%s\n" %__build__
s += "Number of particles: \t%d\n" %self.N
s += "Selected inte... | def status(self) | Prints a summary of the current status
of the simulation. | 3.139601 | 2.988282 | 1.050637 |
i = self._integrator
for name, _i in INTEGRATORS.items():
if i==_i:
return name
return i | def integrator(self) | Get or set the intergrator module.
Available integrators are:
- ``'ias15'`` (default)
- ``'whfast'``
- ``'sei'``
- ``'leapfrog'``
- ``'janus'``
- ``'mercurius'``
- ``'bs'``
- ``'none'``
Check the online documentation for a full d... | 7.266043 | 7.537865 | 0.963939 |
i = self._boundary
for name, _i in BOUNDARIES.items():
if i==_i:
return name
return i | def boundary(self) | Get or set the boundary module.
Available boundary modules are:
- ``'none'`` (default)
- ``'open'``
- ``'periodic'``
- ``'shear'``
Check the online documentation for a full description of each of the modules. | 9.508259 | 11.815009 | 0.804761 |
i = self._gravity
for name, _i in GRAVITIES.items():
if i==_i:
return name
return i | def gravity(self) | Get or set the gravity module.
Available gravity modules are:
- ``'none'``
- ``'basic'`` (default)
- ``'compensated'``
- ``'tree'``
Check the online documentation for a full description of each of the modules. | 9.675379 | 10.675131 | 0.906348 |
i = self._collision
for name, _i in COLLISIONS.items():
if i==_i:
return name
return i | def collision(self) | Get or set the collision module.
Available collision modules are:
- ``'none'`` (default)
- ``'direct'``
- ``'tree'``
- ``'mercurius'``
- ``'direct'``
Check the online documentation for a full description of each of the modules. | 8.77113 | 10.134928 | 0.865436 |
return {'length':hash_to_unit(self.python_unit_l), 'mass':hash_to_unit(self.python_unit_m), 'time':hash_to_unit(self.python_unit_t)} | def units(self) | Tuple of the units for length, time and mass. Can be set in any order, and strings are not case-sensitive. See ipython_examples/Units.ipynb for more information. You can check the units' exact values and add Additional units in rebound/rebound/units.py. Units should be set before adding particles to the simulation ... | 5.048948 | 4.85325 | 1.040323 |
raise AttributeError("Must set sim.units before calling convert_particle_units in order to know what units to convert from.")
new_l, new_t, new_m = check_units(args)
for p in self.particles:
units_convert_particle(p, hash_to_unit(self.python_unit_l), hash_to_unit(self.python_unit... | def convert_particle_units(self, *args):
if self.python_unit_l == 0 or self.python_unit_m == 0 or self.python_unit_t == 0 | Will convert the units for the simulation (i.e. convert G) as well as the particles' cartesian elements.
Must have set sim.units ahead of calling this function so REBOUND knows what units to convert from.
Parameters
----------
3 strings corresponding to units of time, length and mass. ... | 3.815821 | 3.421046 | 1.115396 |
cur_var_config_N = self.var_config_N
if order==1:
index = clibrebound.reb_add_var_1st_order(byref(self),c_int(testparticle))
elif order==2:
if first_order is None:
raise AttributeError("Please specify corresponding first order variational equation... | def add_variation(self,order=1,first_order=None, first_order_2=None, testparticle=-1) | This function adds a set of variational particles to the simulation.
If there are N real particles in the simulation, this functions adds N additional variational
particles. To see how many particles (real and variational) are in a simulation, use ``'sim.N'``.
To see how many variational par... | 4.868663 | 4.417874 | 1.102038 |
if seed is None:
clibrebound.reb_tools_megno_init(byref(self))
else:
clibrebound.reb_tools_megno_init_seed(byref(self), c_uint(seed)) | def init_megno(self, seed=None) | This function initialises the chaos indicator MEGNO particles and enables their integration.
MEGNO is short for Mean Exponential Growth of Nearby orbits. It can be used to test
if a system is chaotic or not. In the backend, the integrator is integrating an additional set
of particles using the ... | 4.788415 | 4.614296 | 1.037735 |
if self._calculate_megno==0:
raise RuntimeError("MEGNO cannot be calculated. Make sure to call init_megno() after adding all particles but before integrating the simulation.")
clibrebound.reb_tools_calculate_megno.restype = c_double
return clibrebound.reb_tools_calculate_me... | def calculate_megno(self) | Return the current MEGNO value.
Note that you need to call init_megno() before the start of the simulation. | 7.901402 | 5.945397 | 1.328995 |
if self._calculate_megno==0:
raise RuntimeError("Lyapunov Characteristic Number cannot be calculated. Make sure to call init_megno() after adding all particles but before integrating the simulation.")
clibrebound.reb_tools_calculate_lyapunov.restype = c_double
return clibre... | def calculate_lyapunov(self) | Return the current Lyapunov Characteristic Number (LCN).
Note that you need to call init_megno() before the start of the simulation.
To get a timescale (the Lyapunov timescale), take the inverse of this quantity. | 11.080628 | 6.148474 | 1.802175 |
if isinstance(particle, Particle):
if (self.gravity == "tree" or self.collision == "tree") and self.root_size <=0.:
raise ValueError("The tree code for gravity and/or collision detection has been selected. However, the simulation box has not been configured yet. You canno... | def add(self, particle=None, **kwargs):
if particle is not None | Adds a particle to REBOUND. Accepts one of the following:
1) A single Particle structure.
2) The particle's mass and a set of cartesian coordinates: m,x,y,z,vx,vy,vz.
3) The primary as a Particle structure, the particle's mass and a set of orbital elements: primary,m,a,anom,e,omega,inv,Omega,ME... | 7.203328 | 6.749108 | 1.067301 |
if index is not None:
clibrebound.reb_remove(byref(self), index, keepSorted)
if hash is not None:
hash_types = c_uint32, c_uint, c_ulong
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
int_types = int,
... | def remove(self, index=None, hash=None, keepSorted=True) | Removes a particle from the simulation.
Parameters
----------
index : int, optional
Specify particle to remove by index.
hash : c_uint32 or string, optional
Specifiy particle to remove by hash (if a string is passed, the corresponding hash is calculated).
... | 2.880172 | 2.809786 | 1.02505 |
s = ""
for p in self.particles:
s += (("%%.%de "%prec) * 8)%(p.m, p.r, p.x, p.y, p.z, p.vx, p.vy, p.vz) + "\n"
if len(s):
s = s[:-1]
return s | def particles_ascii(self, prec=8) | Returns an ASCII string with all particles' masses, radii, positions and velocities.
Parameters
----------
prec : int, optional
Number of digits after decimal point. Default 8. | 3.465431 | 3.341079 | 1.037219 |
for l in s.split("\n"):
r = l.split()
if len(r):
try:
r = [float(x) for x in r]
p = Particle(simulation=self, m=r[0], r=r[1], x=r[2], y=r[3], z=r[4], vx=r[5], vy=r[6], vz=r[7])
self.add(p)
... | def add_particles_ascii(self, s) | Adds particles from an ASCII string.
Parameters
----------
s : string
One particle per line. Each line should include particle's mass, radius, position and velocity. | 2.696072 | 2.520487 | 1.069663 |
orbits = []
if heliocentric is not None or barycentric is not None:
raise AttributeError('heliocentric and barycentric keywords in calculate_orbits are deprecated. Pass primary keyword instead (sim.particles[0] for heliocentric and sim.calculate_com() for barycentric)')
... | def calculate_orbits(self, primary=None, jacobi_masses=False, heliocentric=None, barycentric=None) | Calculate orbital parameters for all partices in the simulation.
By default this functions returns the orbits in Jacobi coordinates.
If MEGNO is enabled, variational particles will be ignored.
Parameters
----------
primary : rebound.Particle, optional
Set the ... | 5.380496 | 4.782621 | 1.12501 |
if last is None:
last = self.N_real
clibrebound.reb_get_com_range.restype = Particle
return clibrebound.reb_get_com_range(byref(self), c_int(first), c_int(last)) | def calculate_com(self, first=0, last=None) | Returns the center of momentum for all particles in the simulation.
Parameters
----------
first: int, optional
If ``first`` is specified, only calculate the center of momentum starting
from index=``first``.
last : int or None, optional
If ``last`` is ... | 5.302313 | 6.464428 | 0.820229 |
N = self.N
possible_keys = ["hash","m","r","xyz","vxvyvz","xyzvxvyvz"]
d = {x:None for x in possible_keys}
for k,v in kwargs.items():
if k in d:
if k == "hash":
if v.dtype!= "uint32":
raise AttributeError("E... | def serialize_particle_data(self,**kwargs) | Fast way to access serialized particle data via numpy arrays.
This function can directly set the values of numpy arrays to
current particle data. This is significantly faster than accessing
particle data via `sim.particles` as all the copying is done
on the C side.
No memory i... | 2.614686 | 2.320778 | 1.126642 |
clibrebound.reb_tools_energy.restype = c_double
return clibrebound.reb_tools_energy(byref(self)) | def calculate_energy(self) | Returns the sum of potential and kinetic energy of all particles in the simulation. | 10.186749 | 7.862191 | 1.295663 |
clibrebound.reb_tools_angular_momentum.restype = reb_vec3d
L = clibrebound.reb_tools_angular_momentum(byref(self))
return [L.x, L.y, L.z] | def calculate_angular_momentum(self) | Returns a list of the three (x,y,z) components of the total angular momentum of all particles in the simulation. | 6.314867 | 5.430882 | 1.16277 |
clibrebound.reb_configure_box(byref(self), c_double(boxsize), c_int(root_nx), c_int(root_ny), c_int(root_nz))
return | def configure_box(self, boxsize, root_nx=1, root_ny=1, root_nz=1) | Initialize the simulation box.
This function only needs to be called it boundary conditions other than "none"
are used. In such a case the boxsize must be known and is set with this function.
Parameters
----------
boxsize : float, optional
The size of one root box.
... | 3.617522 | 4.421557 | 0.818155 |
clibrebound.nghostx = c_int(nghostx)
clibrebound.nghosty = c_int(nghosty)
clibrebound.nghostz = c_int(nghostz)
return | def configure_ghostboxes(self, nghostx=0, nghosty=0, nghostz=0) | Initialize the ghost boxes.
This function only needs to be called it boundary conditions other than "none" or
"open" are used. In such a case the number of ghostboxes must be known and is set
with this function.
Parameters
----------
nghostx, nghosty, nghostz ... | 3.024731 | 3.337265 | 0.90635 |
clibrebound.reb_output_binary(byref(self), c_char_p(filename.encode("ascii"))) | def save(self, filename) | Save the entire REBOUND simulation to a binary file. | 18.240425 | 7.856945 | 2.321567 |
if debug.integrator_package =="REBOUND":
self.exact_finish_time = c_int(exact_finish_time)
ret_value = clibrebound.reb_integrate(byref(self), c_double(tmax))
if ret_value == 1:
self.process_messages()
raise SimulationError("An error oc... | def integrate(self, tmax, exact_finish_time=1) | Main integration function. Call this function when you have setup your simulation and want to integrate it forward (or backward) in time. The function might be called many times to integrate the simulation in steps and create outputs in-between steps.
Parameters
----------
tmax : float
... | 5.96017 | 5.004393 | 1.190988 |
if self.order==2 and variation2 is None:
variation2 = variation
if self._sim is not None:
sim = self._sim.contents
particles = sim.particles
else:
raise RuntimeError("Something went wrong. Cannot seem to find simulation corresponding to va... | def vary(self, particle_index, variation, variation2=None, primary=None) | This function can be used to initialize the variational particles that are
part of a Variation.
Note that rather than using this convenience function, one can
also directly manipulate the particles' coordinate using the following
syntax:
>>> var = sim.add_variation()
... | 4.356681 | 4.532327 | 0.961246 |
sim = self._sim.contents
ps = []
if self.testparticle>=0:
N = 1
else:
N = sim.N-sim.N_var
ParticleList = Particle*N
ps = ParticleList.from_address(ctypes.addressof(sim._particles.contents)+self.index*ctypes.sizeof(Particle))
... | def particles(self) | Access the variational particles corresponding to this set of variational equations.
The function returns a list of particles which are sorted in the same way as those in
sim.particles
The particles are pointers and thus can be modified.
If there are N real particles, this function ... | 8.399372 | 9.014688 | 0.931743 |
link_object = {}
if not getattr(instance, 'pk', None):
# If instance doesn't have a `pk` field, we'll assume it doesn't
# have a canonical resource URL to hang a link off of.
# This generally only affectes Ephemeral Objects.
return data
link_fields = serializer.get_li... | def merge_link_object(serializer, data, instance) | Add a 'links' attribute to the data that maps field names to URLs.
NOTE: This is the format that Ember Data supports, but alternative
implementations are possible to support other formats. | 6.034217 | 5.794843 | 1.041308 |
global POST_PROCESSORS
key = func.__name__
POST_PROCESSORS[key] = func
return func | def register_post_processor(func) | Register a post processor function to be run as the final step in
serialization. The data passed in will already have gone through the
sideloading processor.
Usage:
@register_post_processor
def my_post_processor(data):
# do stuff with `data`
return data | 4.741318 | 5.278626 | 0.898211 |
if isinstance(obj, list):
for key, o in enumerate(obj):
# traverse into lists of objects
self.process(o, parent=obj, parent_key=key, depth=depth)
elif isinstance(obj, dict):
dynamic = self.is_dynamic(obj)
returned = isinstance(... | def process(self, obj, parent=None, parent_key=None, depth=0) | Recursively process the data for sideloading.
Converts the nested representation into a sideloaded representation. | 4.745172 | 4.733169 | 1.002536 |
if not self.parent:
return None
if not getattr(self.parent, 'request_fields'):
return None
if not isinstance(self.parent.request_fields, dict):
return None
return self.parent.request_fields.get(self.field_name) | def _get_request_fields_from_parent(self) | Get request fields from the parent serializer. | 2.49554 | 2.113918 | 1.180528 |
import copy
import django
def prefetch_one_level(instances, prefetcher, lookup, level):
rel_qs, rel_obj_attr, instance_attr, single, cache_name = (
prefetcher.get_prefetch_queryset(
instances, lookup.get_current_queryset(level)))
additional_lookups = [
... | def patch_prefetch_one_level() | This patch address Django bug https://code.djangoproject.com/ticket/24873,
which was merged into Django master
in commit 025c6553771a09b80563baedb5b8300a8b01312f
into django.db.models.query.
The code that follows is identical to the code in the above commit,
with all comments stripped out. | 3.02306 | 2.921202 | 1.034868 |
metadata = super(
DynamicMetadata,
self).determine_metadata(
request,
view)
metadata['features'] = getattr(view, 'features', [])
if hasattr(view, 'get_serializer'):
serializer = view.get_serializer(dynamic=False)
if... | def determine_metadata(self, request, view) | Adds `properties` and `features` to the metadata response. | 2.767339 | 2.446041 | 1.131354 |
field_info = OrderedDict()
for attr in ('required', 'read_only', 'default', 'label'):
field_info[attr] = getattr(field, attr)
if field_info['default'] is empty:
field_info['default'] = None
if hasattr(field, 'immutable'):
field_info['immutable... | def get_field_info(self, field) | Adds `related_to` and `nullable` to the metadata response. | 2.644306 | 2.483678 | 1.064674 |
meta = model._meta
try:
if DJANGO19:
field = meta.get_field(field_name)
else:
field = meta.get_field_by_name(field_name)[0]
return field
except:
if DJANGO19:
related_objs = (
f for f in meta.get_fields()
... | def get_model_field(model, field_name) | Return a field given a model and field name.
Arguments:
model: a Django model
field_name: the name of a field
Returns:
A Django field if `field_name` is a valid field for `model`,
None otherwise. | 1.871753 | 1.933026 | 0.968302 |
if not hasattr(model, '_meta'):
# ephemeral model with no metaclass
return False
model_field = get_model_field(model, field_name)
return isinstance(model_field, (ManyToManyField, RelatedObject)) | def is_field_remote(model, field_name) | Check whether a given model field is a remote field.
A remote field is the inverse of a one-to-many or a
many-to-many relationship.
Arguments:
model: a Django model
field_name: the name of a field
Returns:
True if `field_name` is a remote field, False otherwise. | 4.755122 | 5.513414 | 0.862464 |
def wrapper(self):
if not hasattr(self, '_resettable_cached_properties'):
self._resettable_cached_properties = {}
if func.__name__ not in self._resettable_cached_properties:
self._resettable_cached_properties[func.__name__] = func(self)
return self._resettable_c... | def resettable_cached_property(func) | Decorator to add cached computed properties to an object.
Similar to Django's `cached_property` decorator, except stores
all the data under a single well-known key so that it can easily
be blown away. | 2.223562 | 2.036888 | 1.091647 |
def reset(self):
if hasattr(self, '_resettable_cached_properties'):
self._resettable_cached_properties = {}
cls.reset = reset
return cls | def cacheable_object(cls) | Decorator to add a reset() method that clears data cached by
the @resettable_cached_property decorator. Technically this could
be a mixin... | 5.523616 | 2.999158 | 1.841722 |
setting, value = kwargs['setting'], kwargs['value']
if setting == self.name:
self._reload(value) | def _settings_changed(self, *args, **kwargs) | Handle changes to core settings. | 6.51578 | 4.766717 | 1.366932 |
if self.bound: # Prevent double-binding
return
super(DynamicRelationField, self).bind(*args, **kwargs)
self.bound = True
parent_model = getattr(self.parent.Meta, 'model', None)
remote = is_field_remote(parent_model, self.source)
try:
mo... | def bind(self, *args, **kwargs) | Bind to the parent serializer. | 3.551992 | 3.317404 | 1.070714 |
if not self.parent:
# Don't cache, so that we'd recompute if parent is set.
return None
node = self
seen = set()
while True:
seen.add(node)
if getattr(node, 'parent', None):
node = node.parent
if no... | def root_serializer(self) | Return the root serializer (serializer for the primary resource). | 4.503519 | 4.159592 | 1.082683 |
if not self.parent or not self._is_dynamic:
return kwargs
if 'request_fields' not in kwargs:
# If 'request_fields' isn't explicitly set, pull it from the
# parent serializer.
request_fields = self._get_request_fields_from_parent()
if... | def _inherit_parent_kwargs(self, kwargs) | Extract any necessary attributes from parent serializer to
propagate down to child serializer. | 3.637237 | 3.545919 | 1.025753 |
init_args = {
k: v for k, v in six.iteritems(self.kwargs)
if k in self.SERIALIZER_KWARGS
}
kwargs = self._inherit_parent_kwargs(kwargs)
init_args.update(kwargs)
if self.embed and self._is_dynamic:
init_args['embed'] = True
r... | def get_serializer(self, *args, **kwargs) | Get an instance of the child serializer. | 4.378504 | 4.245718 | 1.031275 |
serializer = self.serializer
model = serializer.get_model()
source = self.source
if not self.kwargs['many'] and serializer.id_only():
# attempt to optimize by reading the related ID directly
# from the current instance rather than from the related object... | def to_representation(self, instance) | Represent the relationship, either as an ID or object. | 5.611247 | 5.394092 | 1.040258 |
related_model = serializer.Meta.model
if isinstance(data, related_model):
return data
try:
instance = related_model.objects.get(pk=data)
except related_model.DoesNotExist:
raise ValidationError(
"Invalid value for '%s': %s obje... | def to_internal_value_single(self, data, serializer) | Return the underlying object, given the serialized form. | 2.589294 | 2.492923 | 1.038658 |
if self.kwargs['many']:
serializer = self.serializer.child
if not isinstance(data, list):
raise ParseError("'%s' value must be a list" % self.field_name)
return [
self.to_internal_value_single(
instance,
... | def to_internal_value(self, data) | Return the underlying object(s), given the serialized form. | 3.427453 | 3.1882 | 1.075043 |
serializer_class = self._serializer_class
if not isinstance(serializer_class, six.string_types):
return serializer_class
parts = serializer_class.split('.')
module_path = '.'.join(parts[:-1])
if not module_path:
if getattr(self, 'parent', None) i... | def serializer_class(self) | Get the class of the child serializer.
Resolves string imports. | 3.023305 | 2.948531 | 1.02536 |
prefetches = []
for field, fprefetch in self.prefetches.items():
has_query = hasattr(fprefetch, 'query')
qs = fprefetch.query.queryset if has_query else None
prefetches.append(
Prefetch(field, queryset=qs)
)
queryset = se... | def _get_django_queryset(self) | Return Django QuerySet with prefetches properly configured. | 3.609435 | 2.955045 | 1.221449 |
if isinstance(value, list):
for val in value:
self.appendlist(key, val)
else:
self.appendlist(key, value) | def add(self, key, value) | Method to accept a list of values and append to flat list.
QueryDict.appendlist(), if given a list, will append the list,
which creates nested lists. In most cases, we want to be able
to pass in a list (for convenience) but have it appended into
a flattened list.
TODO: Possibly t... | 2.974802 | 2.039631 | 1.4585 |
def handle_encodings(request):
try:
return QueryParams(request.GET)
except UnicodeEncodeError:
pass
s = request.environ.get('QUERY_STRING', '')
try:
s = s.encode('utf-8')
except Un... | def initialize_request(self, request, *args, **kargs) | Override DRF initialize_request() method to swap request.GET
(which is aliased by request.query_params) with a mutable instance
of QueryParams, and to convert request MergeDict to a subclass of dict
for consistency (MergeDict is not a subclass of dict) | 5.312441 | 4.68688 | 1.133471 |
renderers = super(WithDynamicViewSetMixin, self).get_renderers()
if settings.ENABLE_BROWSABLE_API is False:
return [
r for r in renderers if not isinstance(r, BrowsableAPIRenderer)
]
else:
return renderers | def get_renderers(self) | Optionally block Browsable API rendering. | 4.65143 | 3.411795 | 1.363338 |
if '[]' in name:
# array-type
return self.request.query_params.getlist(
name) if name in self.features else None
elif '{}' in name:
# object-type (keys are not consistent)
return self._extract_object_params(
name) i... | def get_request_feature(self, name) | Parses the request for a particular feature.
Arguments:
name: A feature name.
Returns:
A feature parsed from the URL if the feature is supported, or None. | 4.056142 | 4.377256 | 0.92664 |
params = self.request.query_params.lists()
params_map = {}
prefix = name[:-1]
offset = len(prefix)
for name, value in params:
if name.startswith(prefix):
if name.endswith('}'):
name = name[offset:-1]
elif n... | def _extract_object_params(self, name) | Extract object params, return as dict | 5.437516 | 5.356097 | 1.015201 |
serializer = self.get_serializer()
return getattr(self, 'queryset', serializer.Meta.model.objects.all()) | def get_queryset(self, queryset=None) | Returns a queryset for this request.
Arguments:
queryset: Optional root-level queryset. | 5.398056 | 7.974971 | 0.676875 |
if hasattr(self, '_request_fields'):
return self._request_fields
include_fields = self.get_request_feature(self.INCLUDE)
exclude_fields = self.get_request_feature(self.EXCLUDE)
request_fields = {}
for fields, include in(
(include_fields, True... | def get_request_fields(self) | Parses the INCLUDE and EXCLUDE features.
Extracts the dynamic field features from the request parameters
into a field map that can be passed to a serializer.
Returns:
A nested dict mapping serializer keys to
True (include) or False (exclude). | 2.461994 | 2.237964 | 1.100104 |
# Explicitly disable support filtering. Applying filters to this
# endpoint would require us to pass through sideload filters, which
# can have unintended consequences when applied asynchronously.
if self.get_request_feature(self.FILTER):
raise ValidationError(
... | def list_related(self, request, pk=None, field_name=None) | Fetch related object(s), as if sideloaded (used to support
link objects).
This method gets mapped to `/<resource>/<pk>/<field_name>/` by
DynamicRouter for all DynamicRelationField fields. Generally,
this method probably shouldn't be overridden.
An alternative implementation wou... | 5.930616 | 5.833632 | 1.016625 |
# noqa
if self.ENABLE_BULK_UPDATE:
patch_all = self.get_request_patch_all()
if self.ENABLE_PATCH_ALL and patch_all:
# patch-all update
data = request.data
return self._patch_all(
data,
query... | def update(self, request, *args, **kwargs) | Update one or more model instances.
If ENABLE_BULK_UPDATE is set, multiple previously-fetched records
may be updated in a single call, provided their IDs.
If ENABLE_PATCH_ALL is set, multiple records
may be updated in a single PATCH call, even without knowing their IDs.
*WARNI... | 5.619061 | 5.585114 | 1.006078 |
bulk_payload = self._get_bulk_payload(request)
if bulk_payload:
return self._create_many(bulk_payload)
return super(DynamicModelViewSet, self).create(
request, *args, **kwargs) | def create(self, request, *args, **kwargs) | Either create a single or many model instances in bulk
using the Serializer's many=True ability from Django REST >= 2.2.5.
The data can be represented by the serializer name (single or plural
forms), dict or list.
Examples:
POST /dogs/
{
"name": "Fido",
... | 3.742463 | 4.10638 | 0.911378 |
bulk_payload = self._get_bulk_payload(request)
if bulk_payload:
return self._destroy_many(bulk_payload)
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg not in kwargs:
# assume that it is a poorly formatted bulk request
... | def destroy(self, request, *args, **kwargs) | Either delete a single or many model instances in bulk
DELETE /dogs/
{
"dogs": [
{"id": 1},
{"id": 2}
]
}
DELETE /dogs/
[
{"id": 1},
{"id": 2}
] | 3.251379 | 3.365566 | 0.966072 |
model = self.get_model()
if model:
return get_model_table(model)
else:
return self.get_name() | def get_resource_key(self) | Return canonical resource key, usually the DB table name. | 5.450719 | 4.065629 | 1.340683 |
data = super(DynamicListSerializer, self).data
processed_data = ReturnDict(
SideloadingProcessor(self, data).data,
serializer=self
) if self.child.envelope else ReturnList(
data,
serializer=self
)
processed_data = post_proc... | def data(self) | Get the data, after performing post-processing if necessary. | 9.832927 | 8.48591 | 1.158736 |
if not self.dynamic:
return
if (isinstance(self.request_fields, dict) and
self.request_fields.pop('*', None) is False):
exclude_fields = '*'
only_fields = set(only_fields or [])
include_fields = include_fields or []
exclude_fiel... | def _dynamic_init(self, only_fields, include_fields, exclude_fields) | Modifies `request_fields` via higher-level dynamic field interfaces.
Arguments:
only_fields: List of field names to render.
All other fields will be deferred (respects sideloads).
include_fields: List of field names to include.
Adds to default field set, ... | 2.900916 | 2.644125 | 1.097117 |
if not hasattr(cls.Meta, 'name'):
class_name = getattr(cls.get_model(), '__name__', None)
setattr(
cls.Meta,
'name',
inflection.underscore(class_name) if class_name else None
)
return cls.Meta.name | def get_name(cls) | Get the serializer name.
The name can be defined on the Meta class or will be generated
automatically from the model name. | 3.45427 | 3.168839 | 1.090074 |
if not hasattr(cls.Meta, 'plural_name'):
setattr(
cls.Meta,
'plural_name',
inflection.pluralize(cls.get_name())
)
return cls.Meta.plural_name | def get_plural_name(cls) | Get the serializer's plural name.
The plural name may be defined on the Meta class.
If the plural name is not defined,
the pluralized form of the name will be returned. | 2.83799 | 3.037679 | 0.934263 |
if (
not settings.ENABLE_FIELDS_CACHE or
not self.ENABLE_FIELDS_CACHE or
self.__class__ not in FIELDS_CACHE
):
all_fields = super(
WithDynamicSerializerMixin,
self
).get_fields()
if (
... | def _all_fields(self) | Returns the entire serializer field set.
Does not respect dynamic field inclusions/exclusions. | 2.853302 | 2.645564 | 1.078523 |
all_fields = self.get_all_fields()
if self.dynamic is False:
return all_fields
if self.id_only():
return {}
serializer_fields = copy.deepcopy(all_fields)
request_fields = self.request_fields
deferred = self._get_deferred_field_names(seri... | def get_fields(self) | Returns the serializer's field set.
If `dynamic` is True, respects field inclusions/exlcusions.
Otherwise, reverts back to standard DRF behavior. | 3.679257 | 3.482058 | 1.056633 |
query_params = self.get_request_attribute('query_params', {})
if 'exclude_links' in query_params:
return {}
else:
all_fields = self.get_all_fields()
return {
name: field for name, field in six.iteritems(all_fields)
if i... | def _link_fields(self) | Construct dict of name:field for linkable fields. | 5.152291 | 4.737242 | 1.087614 |
ret = {}
fields = self._readable_fields
is_fast = isinstance(instance, prefetch.FastObject)
id_fields = self._readable_id_fields
for field in fields:
attribute = None
# we exclude dynamic fields here because the proper fastquery
# ... | def _faster_to_representation(self, instance) | Modified to_representation with optimizations.
1) Returns a plain old dict as opposed to OrderedDict.
(Constructing ordered dict is ~100x slower than `{}`.)
2) Ensure we use a cached list of fields
(this optimization exists in DRF 3.2 but not 3.1)
Arguments:
... | 4.624118 | 4.612341 | 1.002553 |
if self.enable_optimization:
representation = self._faster_to_representation(instance)
else:
representation = super(
WithDynamicSerializerMixin,
self
).to_representation(instance)
if settings.ENABLE_LINKS:
... | def _to_representation(self, instance) | Uncached `to_representation`. | 5.729294 | 5.374195 | 1.066075 |
if self.id_only():
return instance.pk
pk = getattr(instance, 'pk', None)
if not settings.ENABLE_SERIALIZER_OBJECT_CACHE or pk is None:
return self._to_representation(instance)
else:
if pk not in self.obj_cache:
self.obj_cache[... | def to_representation(self, instance) | Modified to_representation method. Optionally may cache objects.
Arguments:
instance: A model instance or data object.
Returns:
Instance ID if the serializer is meant to represent its ID.
Otherwise, a tagged data dict representation. | 3.278243 | 2.926517 | 1.120186 |
update = getattr(self, 'instance', None) is not None
instance = super(
WithDynamicSerializerMixin,
self
).save(
*args,
**kwargs
)
view = self._context.get('view')
if view and update:
if int(DRF_VERSION[0... | def save(self, *args, **kwargs) | Serializer save that address prefetch issues. | 5.630423 | 4.919737 | 1.144456 |
model = self.get_model()
out = [model._meta.pk.name] # get PK field name
# If this is being called, it means it
# is a many-relation to its parent.
# Django wants the FK to the parent,
# but since accurately inferring the FK
# pointing back to the par... | def get_id_fields(self) | Called to return a list of fields consisting of, at minimum,
the PK field name. The output of this method is used to
construct a Prefetch object with a .only() queryset
when this field is not being sideloaded but we need to
return a list of IDs. | 10.095717 | 9.551258 | 1.057004 |
if not isinstance(instance, dict):
data = super(
DynamicEphemeralSerializer,
self
).to_representation(instance)
else:
data = instance
instance = EphemeralObject(data)
if self.id_only():
return ... | def to_representation(self, instance) | Provides post processing. Sub-classes should implement their own
to_representation method, but pass the resulting dict through
this function to get tagging and field selection.
Arguments:
instance: Serialized dict, or object. If object,
it will be serialized by the s... | 6.478725 | 5.908912 | 1.096433 |
def get_url(url):
return reverse(url, request=request) if url else url
def is_active_url(path, url):
return path.startswith(url) if url and path else False
path = request.path
directory_list = []
def sort_key(r):
return r[0]
# TODO(ant): support arbitrarily nest... | def get_directory(request) | Get API directory as a nested list of lists. | 3.222152 | 3.166271 | 1.017649 |
class API(views.APIView):
_ignore_model_permissions = True
def get(self, request, *args, **kwargs):
directory_list = get_directory(request)
result = OrderedDict()
for group_name, url, endpoints, _ in directory_list:
... | def get_api_root_view(self, **kwargs) | Return API root view, using the global directory. | 3.139354 | 2.857528 | 1.098626 |
if base_name is None:
base_name = prefix
super(DynamicRouter, self).register(prefix, viewset, base_name)
prefix_parts = prefix.split('/')
if len(prefix_parts) > 1:
prefix = prefix_parts[0]
endpoint = '/'.join(prefix_parts[1:])
else:
... | def register(self, prefix, viewset, base_name=None) | Add any registered route into a global API directory.
If the prefix includes a path separator,
store the URL in the directory under the first path segment.
Otherwise, store it as-is.
For example, if there are two registered prefixes,
'v1/users' and 'groups', `directory` will lo... | 2.768459 | 2.612054 | 1.059878 |
# Try to extract resource name from viewset.
try:
serializer = viewset.serializer_class()
resource_key = serializer.get_resource_key()
resource_name = serializer.get_name()
path_name = serializer.get_plural_name()
except:
impo... | def register_resource(self, viewset, namespace=None) | Register a viewset that should be considered the canonical
endpoint for a particular resource. In addition to generating
and registering the route, it adds the route in a reverse map
to allow DREST to build the canonical URL for a given resource.
Arguments:
viewset - viewset... | 3.486202 | 3.283626 | 1.061693 |
if resource_key not in resource_map:
# Note: Maybe raise?
return None
base_path = get_script_prefix() + resource_map[resource_key]['path']
if pk:
return '%s/%s/' % (base_path, pk)
else:
return base_path | def get_canonical_path(resource_key, pk=None) | Return canonical resource path.
Arguments:
resource_key - Canonical resource key
i.e. Serializer.get_resource_key().
pk - (Optional) Object's primary key for a single-resource URL.
Returns: Absolute URL as string. | 4.018827 | 3.800351 | 1.057488 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.