code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
@app.context_processor
def inject_links():
return {
'websub_self_url': stack.top.websub_self_url,
'websub_hub_url': stack.top.websub_hub_url,
'websub_self_link': stack.top.websub_self_link,
'websub_hub_link': stack.top.websub_hub_link,
} | def init_publisher(app) | Calling this with your flask app as argument is required for the
publisher decorator to work. | 2.669652 | 2.534519 | 1.053317 |
def decorator(topic_view):
@functools.wraps(topic_view)
def wrapper(*args, **kwargs):
nonlocal hub_url, self_url
if not self_url:
self_url = request.url
if not hub_url:
try:
hub_url = url_for('websub_hub.en... | def publisher(self_url=None, hub_url=None) | This decorator makes it easier to implement a websub publisher. You use
it on an endpoint, and Link headers will automatically be added. To also
include these links in your template html/atom/rss (and you should!) you
can use the following to get the raw links:
- {{ websub_self_url }}
- {{ websub_h... | 2.532007 | 2.25988 | 1.120416 |
q = select(columns=[func.count(True)], from_obj=q.alias())
return cube.engine.execute(q).scalar() | def count_results(cube, q) | Get the count of records matching the query. | 8.557602 | 6.463563 | 1.323976 |
if q._limit is not None and q._limit < 1:
return
rp = cube.engine.execute(q)
while True:
row = rp.fetchone()
if row is None:
return
yield dict(row.items()) | def generate_results(cube, q) | Generate the resulting records for this query, applying pagination.
Values will be returned by their reference. | 5.223974 | 4.251287 | 1.228798 |
info = []
for (ref, direction) in self.parse(ordering):
info.append((ref, direction))
table, column = self.cube.model[ref].bind(self.cube)
if distinct is not None and distinct != ref:
column = asc(ref) if direction == 'asc' else desc(ref)
... | def apply(self, q, bindings, ordering, distinct=None) | Sort on a set of field specifications of the type (ref, direction)
in order of the submitted list. | 4.090587 | 3.762344 | 1.087244 |
'''
Returns a deep copy with all of the numpy arrays copied
If only is a list of strings, i.e. ['f', 'v'], then only those properties will be copied
'''
if only is None:
return Mesh(self)
else:
import copy
m = Mesh()
for a i... | def copy(self, only=None) | Returns a deep copy with all of the numpy arrays copied
If only is a list of strings, i.e. ['f', 'v'], then only those properties will be copied | 5.02423 | 2.198597 | 2.285198 |
nargs = len(args)
if nargs == 1:
return args[0]
vs = [a.v for a in args if a.v is not None]
vcs = [a.vc for a in args if a.vc is not None]
fs = [a.f for a in args if a.f is not None]
if vs and len(vs) != nargs:
raise ValueError('Expected... | def concatenate(cls, *args) | Concatenates an arbitrary number of meshes.
Currently supports vertices, vertex colors, and faces. | 2.889354 | 2.61635 | 1.104345 |
kargs = dict(kargs)
if len(args) > 0:
if len(args) >= 1:
kargs['host'] = args[0]
if len(args) >= 2:
kargs['user'] = args[1]
if len(args) >= 3:
kargs['passwd'] = args[2]
if len(args) >= 4:
kargs['db'] = args[3]
if len(args) >= 5:
kargs['port'] = args[4]
if len(args) >= 6:
kargs['commitO... | def getNewConnection(*args, **kargs) | Quickly Create a new PySQLConnection class
@param host: Hostname for your database
@param username: Username to use to connect to database
@param password: Password to use to connect to database
@param schema: Schema to use
@param port: Port to connect on
@param commitOnEnd: Default False, When query is comple... | 1.635437 | 1.622215 | 1.008151 |
if connection is None:
return query.PySQLQuery(getNewConnection(*args, **kargs), commitOnEnd = commitOnEnd)
else:
#Updated 7/24/08 to include commitOnEnd here
#-Chandler Prall
return query.PySQLQuery(connection, commitOnEnd = commitOnEnd) | def getNewQuery(connection = None, commitOnEnd=False, *args, **kargs) | Create a new PySQLQuery Class
@param PySQLConnectionObj: Connection Object representing your connection string
@param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a one time auto commit
@author: Nick Verbeck
@since: 5/12/2008
@updated: 7/19/2008 - Added commitOnEnd suppo... | 6.08032 | 6.108356 | 0.99541 |
key = retrieve_public_key('{}/{}' .format(username, repository))
if env_file:
if path:
config = load_travis_configuration(path)
for env_var, value in dotenv_values(env_file).items():
encrypted_env = encrypt_key(key, value.encode())
config.se... | def cli(username, repository, path, password, deploy, env, clipboard, env_file) | Encrypt passwords and environment variables for use with Travis CI.
Travis Encrypt requires as arguments the user's GitHub username and repository name.
Once the arguments are passed, a password prompt will ask for the password that needs
to be encrypted. The given password will then be encrypted via the P... | 2.428437 | 2.372588 | 1.023539 |
info = []
group_by = None
for field in self.parse(fields):
for concept in self.cube.model.match(field):
info.append(concept.ref)
table, column = concept.bind(self.cube)
bindings.append(Binding(table, concept.ref))
... | def apply(self, q, bindings, fields, distinct=False) | Define a set of fields to return for a non-aggregated query. | 3.79231 | 3.647291 | 1.039761 |
# //Mouse drag, calculate rotation (Point2fT Quat4fT)
X = 0
Y = 1
Z = 2
W = 3
self.m_EnVec = self._mapToSphere(NewPt)
# //Compute the vector perpendicular to the begin and end vectors
# Perp = Vector3fT()
Perp = Vector3fCross(self.m_StVe... | def drag(self, NewPt) | drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec | 4.996058 | 4.76351 | 1.048818 |
self.cell_volumes = numpy.array(
[
abs(
self.node_coords[cell["nodes"]][1]
- self.node_coords[cell["nodes"]][0]
)
for cell in self.cells
]
)
return | def create_cell_volumes(self) | Computes the volumes of the "cells" in the mesh. | 3.65108 | 3.103703 | 1.176363 |
self.control_volumes = numpy.zeros(len(self.node_coords), dtype=float)
for k, cell in enumerate(self.cells):
node_ids = cell["nodes"]
self.control_volumes[node_ids] += 0.5 * self.cell_volumes[k]
# Sanity checks.
sum_cv = sum(self.control_volumes)
... | def create_control_volumes(self) | Compute the control volumes of all nodes in the mesh. | 3.426841 | 3.017859 | 1.13552 |
'''
Return a Mesh which is an axis-aligned rectangular prism. One vertex is
`origin`; the diametrically opposite vertex is `origin + size`.
size: 3x1 array.
'''
from lace.topology import quads_to_tris
lower_base_plane = np.array([
# Lower base plane
origin,
origin ... | def create_rectangular_prism(origin, size) | Return a Mesh which is an axis-aligned rectangular prism. One vertex is
`origin`; the diametrically opposite vertex is `origin + size`.
size: 3x1 array. | 2.558706 | 1.958128 | 1.306711 |
'''
Return a Mesh which is a triangular prism whose base is the triangle
p1, p2, p3. If the vertices are oriented in a counterclockwise
direction, the prism extends from behind them.
'''
from blmath.geometry import Plane
base_plane = Plane.from_points(p1, p2, p3)
lower_base_to_upper_ba... | def create_triangular_prism(p1, p2, p3, height) | Return a Mesh which is a triangular prism whose base is the triangle
p1, p2, p3. If the vertices are oriented in a counterclockwise
direction, the prism extends from behind them. | 2.854884 | 2.230609 | 1.279867 |
'''
Creates a horizontal plane.
'''
v = np.array([
[1., 0., 0.],
[-1., 0., 0.],
[0., 0., 1.],
[0., 0., -1.]
])
f = [[0, 1, 2], [3, 1, 0]]
return Mesh(v=v, f=f) | def create_horizontal_plane() | Creates a horizontal plane. | 2.749474 | 2.676817 | 1.027143 |
if ref in self.refs:
self._matched_ref = ref
return True
return False | def match_ref(self, ref) | Check if the ref matches one the concept's aliases.
If so, mark the matched ref so that we use it as the column label. | 5.736784 | 4.528136 | 1.26692 |
table_name = self.model.fact_table_name
if '.' in column_name:
table_name, column_name = column_name.split('.', 1)
table = cube._load_table(table_name)
if column_name not in table.columns:
raise BindingException('Column %r does not exist on table %r' % (
... | def _physical_column(self, cube, column_name) | Return the SQLAlchemy Column object matching a given, possibly
qualified, column name (i.e.: 'table.column'). If no table is named,
the fact table is assumed. | 3.018092 | 2.749224 | 1.097798 |
table, column = self._physical_column(cube, self.column_name)
column = column.label(self.matched_ref)
column.quote = True
return table, column | def bind(self, cube) | Map a model reference to an physical column in the database. | 11.808641 | 8.74645 | 1.350107 |
customer = self.retrieve_from_stripe()
customer.source = source_token
customer.save()
if stripe_js_response:
self.stripe_js_response = stripe_js_response
self._update_from_stripe_object(customer) | def add_new_source(self, source_token, stripe_js_response=None) | Add new source (for example: a new card) to the customer
The new source will be automatically set as customer's default payment source.
Passing stripe_js_response is optional. If set, StripeCustomer.stripe_js_response will be updated. | 3.447769 | 2.837679 | 1.214996 |
fields_to_update = self.STRIPE_FIELDS - set(exclude_fields or [])
update_data = {key: stripe_coupon[key] for key in fields_to_update}
for field in ["created", "redeem_by"]:
if update_data.get(field):
update_data[field] = timestamp_to_timezone_aware_date(updat... | def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True) | Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve.
To only update the object, set the commit param to False.
Returns the number of rows altered or None if commit is False. | 2.846936 | 2.900806 | 0.981429 |
stripe.api_key = stripe_settings.API_KEY
if self._previous_is_deleted != self.is_deleted and self.is_deleted:
try:
stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
# make sure to delete correct coupon
if self.created == timestamp... | def save(self, force_retrieve=False, *args, **kwargs) | Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe
API or update the local object with data fetched from Stripe. | 2.715348 | 2.656614 | 1.022108 |
n = pts.shape[1]
assert cells.shape[1] == n + 1
p = pts[cells]
p = numpy.concatenate([p, numpy.ones(list(p.shape[:2]) + [1])], axis=-1)
return numpy.linalg.det(p) / math.factorial(n) | def get_signed_simplex_volumes(cells, pts) | Signed volume of a simplex in nD. Note that signing only makes sense for
n-simplices in R^n. | 3.274776 | 3.158344 | 1.036865 |
# https://stackoverflow.com/a/50394587/353337
m = numpy.concatenate([[True], a[:-1] != a[1:], [True]])
idx = numpy.flatnonzero(m)
return idx[:-1], numpy.diff(idx) | def grp_start_len(a) | Given a sorted 1D input array `a`, e.g., [0 0, 1, 2, 3, 4, 4, 4], this
routine returns the indices where the blocks of equal integers start and
how long the blocks are. | 4.816814 | 4.493369 | 1.071983 |
# The input argument are the dot products
#
# <e1, e2>
# <e2, e0>
# <e0, e1>
#
# of the edges
#
# e0: x1->x2,
# e1: x2->x0,
# e2: x0->x1.
#
# Note that edge e_i is opposite of node i and the edges add up to 0.
# The trilinear coordinates of the c... | def compute_triangle_circumcenters(X, ei_dot_ei, ei_dot_ej) | Computes the circumcenters of all given triangles. | 3.446167 | 3.467874 | 0.993741 |
if subdomain is None:
# https://stackoverflow.com/a/42392791/353337
return numpy.s_[:]
if subdomain not in self.subdomains:
self._mark_vertices(subdomain)
# A face is inside if all its edges are in.
# An edge is inside if all its nodes are i... | def get_edge_mask(self, subdomain=None) | Get faces which are fully in subdomain. | 6.604586 | 6.406221 | 1.030964 |
if subdomain is None:
# https://stackoverflow.com/a/42392791/353337
return numpy.s_[:]
if subdomain not in self.subdomains:
self._mark_vertices(subdomain)
# A face is inside if all its edges are in.
# An edge is inside if all its nodes are i... | def get_face_mask(self, subdomain) | Get faces which are fully in subdomain. | 6.22618 | 6.022689 | 1.033787 |
if subdomain is None:
is_inside = numpy.ones(len(self.node_coords), dtype=bool)
else:
is_inside = subdomain.is_inside(self.node_coords.T).T
if subdomain.is_boundary_only:
# Filter boundary
self.mark_boundary()
... | def _mark_vertices(self, subdomain) | Mark faces/edges which are fully in subdomain. | 4.501773 | 4.370415 | 1.030056 |
class OrderedDumper(Dumper):
pass
def dict_representer(dumper, data):
return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items())
OrderedDumper.add_representer(OrderedDict, dict_representer)
return yaml.dump(data, stream, OrderedDumper, **kwds) | def ordered_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds) | Dump a yaml configuration as an OrderedDict. | 1.505363 | 1.553981 | 0.968714 |
if isinstance(value, list):
return [self._check_type(ref, val) for val in value]
model_type = self.cube.model[ref].datatype
if model_type is None:
return
query_type = self._api_type(value)
if query_type == model_type:
return
e... | def _check_type(self, ref, value) | Checks whether the type of the cut value matches the type of the
concept being cut, and raises a QueryException if it doesn't match | 4.141212 | 3.509327 | 1.180059 |
if isinstance(value, six.string_types):
return 'string'
elif isinstance(value, six.integer_types):
return 'integer'
elif type(value) is datetime.datetime:
return 'date' | def _api_type(self, value) | Returns the API type of the given value based on its python type. | 2.51787 | 2.199566 | 1.144712 |
info = []
for (ref, operator, value) in self.parse(cuts):
if map_is_class and isinstance(value, map):
value = list(value)
self._check_type(ref, value)
info.append({'ref': ref, 'operator': operator, 'value': value})
table, column = ... | def apply(self, q, bindings, cuts) | Apply a set of filters, which can be given as a set of tuples in
the form (ref, operator, value), or as a string in query form. If it
is ``None``, no filter will be applied. | 6.013085 | 5.300697 | 1.134395 |
'''
Given an array of size NxM (usually Nx3), we accept color in the following ways:
- A string color name. The accepted names are roughly what's in X11's rgb.txt
- An explicit rgb triple, in (3, ), (3, 1), or (1, 3) shape
- A list of values (N, ), (N, 1), or (1, N) that are put through a colormap t... | def colors_like(color, arr, colormap=DEFAULT_COLORMAP) | Given an array of size NxM (usually Nx3), we accept color in the following ways:
- A string color name. The accepted names are roughly what's in X11's rgb.txt
- An explicit rgb triple, in (3, ), (3, 1), or (1, 3) shape
- A list of values (N, ), (N, 1), or (1, N) that are put through a colormap to get per ve... | 4.734642 | 1.777023 | 2.664367 |
# height == 0 -> saturation = 0.
# height == threshold -> saturation = 1.
color_weights = np.minimum(heights / threshold, 1.)
color_weights = color_weights * color_weights
self.set_vertex_colors_from_weights(color_weights, scale_to_range_1=False)
e... | def color_by_height(self, axis=1, threshold=None, color=DEFAULT_COLORMAP): # pylint: disable=unused-argument
'''
Color each vertex by its height above the floor point.
axis: The axis to use. 0 means x, 1 means y, 2 means z.
threshold: The top of the range. Points at and above this heigh... | Color each vertex by its height above the floor point.
axis: The axis to use. 0 means x, 1 means y, 2 means z.
threshold: The top of the range. Points at and above this height will
be the same color. | 4.447854 | 4.517402 | 0.984604 |
'''
Truncate weights to the range [0, max_weight] and rescale, as you would
want for a heatmap with known scale.
'''
import numpy as np
adjusted_weights = np.clip(weights, 0., max_weight) / max_weight
self.vc = colors_like(adjusted_weights, self.v, colormap=color) | def color_as_heatmap(self, weights, max_weight=1.0, color=DEFAULT_COLORMAP) | Truncate weights to the range [0, max_weight] and rescale, as you would
want for a heatmap with known scale. | 8.33903 | 3.69896 | 2.254426 |
'''
Convert quad faces to triangular faces.
quads: An nx4 array.
Return a 2nx3 array.
'''
import numpy as np
tris = np.empty((2 * len(quads), 3))
tris[0::2, :] = quads[:, [0, 1, 2]]
tris[1::2, :] = quads[:, [0, 2, 3]]
return tris | def quads_to_tris(quads) | Convert quad faces to triangular faces.
quads: An nx4 array.
Return a 2nx3 array. | 3.025805 | 1.992954 | 1.518251 |
'''
returns all of the faces that contain at least one of the vertices in v_indices
'''
import numpy as np
included_vertices = np.zeros(self.v.shape[0], dtype=bool)
included_vertices[np.array(v_indices, dtype=np.uint32)] = True
faces_with_verts = included_vertices... | def all_faces_with_verts(self, v_indices, as_boolean=False) | returns all of the faces that contain at least one of the vertices in v_indices | 2.616611 | 2.225772 | 1.175597 |
'''
Given a list of segment names, return an array of vertex indices for
all the vertices in those faces.
Args:
segments: a list of segment names,
ret_face_indices: if it is `True`, returns face indices
'''
import numpy as np
import warnin... | def vertex_indices_in_segments(self, segments, ret_face_indices=False) | Given a list of segment names, return an array of vertex indices for
all the vertices in those faces.
Args:
segments: a list of segment names,
ret_face_indices: if it is `True`, returns face indices | 3.88562 | 2.785502 | 1.394945 |
'''
Keep the faces and vertices for given segments, discarding all others.
When preserve_segmentation is false self.segm is discarded for speed.
'''
v_ind, f_ind = self.vertex_indices_in_segments(segments_to_keep, ret_face_indices=True)
self.segm = {name: self.segm[name] ... | def keep_segments(self, segments_to_keep, preserve_segmentation=True) | Keep the faces and vertices for given segments, discarding all others.
When preserve_segmentation is false self.segm is discarded for speed. | 4.130917 | 2.407463 | 1.71588 |
''' Remove the faces and vertices for given segments, keeping all others.
Args:
segments_to_remove: a list of segnments whose vertices will be removed
'''
v_ind = self.vertex_indices_in_segments(segments_to_remove)
self.segm = {name: faces for name, faces in self.seg... | def remove_segments(self, segments_to_remove) | Remove the faces and vertices for given segments, keeping all others.
Args:
segments_to_remove: a list of segnments whose vertices will be removed | 5.201475 | 3.072752 | 1.692774 |
verts_by_segm = self.verts_by_segm
return sorted(reduce(lambda s0, s1: s0.intersection(s1),
[set(verts_by_segm[segm]) for segm in segments])) | def verts_in_common(self, segments) | returns array of all vertex indices common to each segment in segments | 3.606757 | 3.53405 | 1.020573 |
import numpy as np
from lace.mesh import Mesh
new_mesh = Mesh(v=self.v[self.f.flatten()], f=np.array(range(len(self.f.flatten()))).reshape(-1, 3))
if self.vn is None:
self.reset_normals()
new_mesh.vn = self.vn[self.f.flatten()]
if self.vt is not Non... | def uniquified_mesh(self) | This function returns a copy of the mesh in which vertices are copied such that
each vertex appears in only one face, and hence has only one texture | 3.347276 | 3.070707 | 1.090067 |
from lace.mesh import Mesh
if self.f is not None:
raise ValueError(
'Function `downsampled_mesh` does not support faces.')
low = Mesh()
if self.v is not None:
low.v = self.v[::step]
if self.vc is not None:
low.vc = se... | def downsampled_mesh(self, step) | Returns a downsampled copy of this mesh.
Args:
step: the step size for the sampling
Returns:
a new, downsampled Mesh object.
Raises:
ValueError if this Mesh has faces. | 4.742308 | 3.955859 | 1.198806 |
'''
Keep the given vertices and discard the others, and any faces to which
they may belong.
If `ret_kept_faces` is `True`, return the original indices of the kept
faces. Otherwise return `self` for chaining.
'''
import numpy as np
if self.v is None:
... | def keep_vertices(self, indices_to_keep, ret_kept_faces=False) | Keep the given vertices and discard the others, and any faces to which
they may belong.
If `ret_kept_faces` is `True`, return the original indices of the kept
faces. Otherwise return `self` for chaining. | 2.61773 | 2.277899 | 1.149186 |
'''
Return a copy of mesh with line vertices and edges added.
mesh: A Mesh
lines: A list of Polyline or Lines objects.
'''
mesh_with_lines = mesh.copy()
mesh_with_lines.add_lines(lines)
return mesh_with_lines | def create_from_mesh_and_lines(cls, mesh, lines) | Return a copy of mesh with line vertices and edges added.
mesh: A Mesh
lines: A list of Polyline or Lines objects. | 5.790839 | 2.4237 | 2.389256 |
'''
Add line vertices and edges to the mesh.
lines: A list of Polyline or Lines objects.
'''
import numpy as np
if not lines:
return
v_lines = np.vstack([l.v for l in lines])
v_index_offset = np.cumsum([0] + [len(l.v) for l in lines])
... | def add_lines(self, lines) | Add line vertices and edges to the mesh.
lines: A list of Polyline or Lines objects. | 3.299051 | 2.600148 | 1.268793 |
import numpy as np
import scipy.sparse as sp
from blmath.numerics.matlab import row
vpv = sp.csc_matrix((len(self.v), len(self.v)))
# for each column in the faces...
for i in range(3):
IS = self.f[:, i]
JS = self.f[:, (i+1)%3]
... | def vert_connectivity(self) | Returns a sparse matrix (of size #verts x #verts) where each nonzero
element indicates a neighborhood relation. For example, if there is a
nonzero element in position (15, 12), that means vertex 15 is connected
by an edge to vertex 12. | 4.295174 | 4.10191 | 1.047116 |
result = {}
for f in self.f:
for i in range(3):
key = [f[i], f[(i+1)%3]]
key.sort()
key = tuple(key)
val = f[(i+2)%3]
if key in result:
result[key].append(val)
else:
... | def vert_opposites_per_edge(self) | Returns a dictionary from vertidx-pairs to opposites.
For example, a key consist of [4, 5)] meaning the edge between
vertices 4 and 5, and a value might be [10, 11] which are the indices
of the vertices opposing this edge. | 2.724389 | 2.283055 | 1.193309 |
import numpy as np
import scipy.sparse as sp
from blmath.numerics.matlab import col
IS = np.repeat(np.arange(len(self.f)), 3)
JS = self.f.ravel()
data = np.ones(IS.size)
f2v = sp.csc_matrix((data, (IS, JS)), shape=(len(self.f), np.max(self.f.ravel())+1))
... | def faces_per_edge(self) | Returns an Ex2 array of adjacencies between faces, where
each element in the array is a face index. Each edge is included
only once. Edges that are not shared by 2 faces are not included. | 2.937773 | 2.795127 | 1.051034 |
import numpy as np
return np.asarray([vertices_in_common(e[0], e[1]) for e in self.f[self.faces_per_edge]]) | def vertices_per_edge(self) | Returns an Ex2 array of adjacencies between vertices, where
each element in the array is a vertex index. Each edge is included
only once. Edges that are not shared by 2 faces are not included. | 8.104687 | 6.937208 | 1.168292 |
import numpy as np
import scipy.sparse as sp
vpe = np.asarray(self.vertices_per_edge, dtype=np.int32)
IS = np.repeat(np.arange(len(vpe)), 2)
JS = vpe.flatten()
data = np.ones_like(vpe)
data[:, 1] = -1
data = data.flatten()
if want_xyz:
... | def get_vertices_to_edges_matrix(self, want_xyz=True) | Returns a matrix M, which if multiplied by vertices,
gives back edges (so "e = M.dot(v)"). Note that this generates
one edge per edge, *not* two edges per triangle.
Args:
want_xyz: if true, takes and returns xyz coordinates, otherwise
takes and returns x *or* y *or* ... | 2.487127 | 2.732424 | 0.910227 |
import numpy as np
from scipy.spatial import cKDTree # FIXME pylint: disable=no-name-in-module
fshape = self.f.shape
tree = cKDTree(self.v)
close_pairs = list(tree.query_pairs(eps))
if close_pairs:
close_pairs = np.sort(close_pairs, axis=1)
... | def remove_redundant_verts(self, eps=1e-10) | Given verts and faces, this remove colocated vertices | 3.128873 | 3.02772 | 1.033409 |
if self.cardinality:
if self.cardinality > 1000:
return 'high'
if self.cardinality > 50:
return 'medium'
if self.cardinality > 7:
return 'low'
return 'tiny' | def cardinality_class(self) | Group the cardinality of the dimension into one of four buckets,
from very small (less than 5) to very large (more than 1000). | 3.259968 | 2.755533 | 1.183062 |
# http://mathworld.wolfram.com/TriangleArea.html
assert (
self.node_coords.shape[1] == 2
), "Signed areas only make sense for triangles in 2D."
if self._signed_cell_areas is None:
# One could make p contiguous by adding a copy(), but that's not
... | def signed_cell_areas(self) | Signed area of a triangle in 2D. | 3.470793 | 3.247355 | 1.068806 |
# Reshape into individual edges.
# Sort the columns to make it possible for `unique()` to identify
# individual edges.
s = self.idx_hierarchy.shape
a = numpy.sort(self.idx_hierarchy.reshape(s[0], -1).T)
a_unique, inv, cts = unique_rows(a)
assert numpy.al... | def create_edges(self) | Set up edge-node and edge-cell relations. | 6.870696 | 6.466628 | 1.062485 |
if self.edges is None:
self.create_edges()
num_edges = len(self.edges["nodes"])
counts = numpy.zeros(num_edges, dtype=int)
fastfunc.add.at(
counts,
self.cells["edges"],
numpy.ones(self.cells["edges"].shape, dtype=int),
)
... | def _compute_edges_cells(self) | This creates interior edge->cells relations. While it's not
necessary for many applications, it sometimes does come in handy. | 3.476104 | 3.430982 | 1.013151 |
if self._cell_centroids is None:
self._cell_centroids = (
numpy.sum(self.node_coords[self.cells["nodes"]], axis=1) / 3.0
)
return self._cell_centroids | def cell_centroids(self) | The centroids (barycenters) of all triangles. | 3.491867 | 3.020233 | 1.156158 |
# The integral of any linear function over a triangle is the average of
# the values of the function in each of the three corners, times the
# area of the triangle.
right_triangle_vols = self.cell_partitions
node_edges = self.idx_hierarchy
corner = self.node_co... | def _compute_integral_x(self) | Computes the integral of x,
\\int_V x,
over all atomic "triangles", i.e., areas cornered by a node, an edge
midpoint, and a circumcenter. | 7.61324 | 6.968099 | 1.092585 |
# Each of the three edges may contribute to the surface areas of all
# three vertices. Here, only the two adjacent nodes receive a
# contribution, but other approaches (e.g., the flat cell corrector),
# may contribute to all three nodes.
cn = self.cells["nodes"][cell_ids... | def _compute_surface_areas(self, cell_ids) | For each edge, one half of the the edge goes to each of the end
points. Used for Neumann boundary conditions if on the boundary of the
mesh and transition conditions if in the interior. | 5.068338 | 4.880264 | 1.038538 |
# Compute the projection of A on the edge at each edge midpoint.
# Take the average of `vector_field` at the endpoints to get the
# approximate value at the edge midpoint.
A = 0.5 * numpy.sum(vector_field[self.idx_hierarchy], axis=0)
# sum of <edge, A> for all three edge... | def compute_curl(self, vector_field) | Computes the curl of a vector field over the mesh. While the vector
field is point-based, the curl will be cell-based. The approximation is
based on
.. math::
n\\cdot curl(F) = \\lim_{A\\to 0} |A|^{-1} <\\int_{dGamma}, F> dr;
see <https://en.wikipedia.org/wiki/Curl_(mathema... | 5.903768 | 5.408608 | 1.09155 |
# Importing matplotlib takes a while, so don't do that at the header.
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
# from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca()
# plt.axis("equal")
... | def plot(
self,
show_coedges=True,
show_centroids=True,
mesh_color="k",
nondelaunay_edge_color="#d62728", # mpl 2.0 default red
boundary_edge_color=None,
comesh_color=(0.8, 0.8, 0.8),
show_axes=True,
) | Show the mesh using matplotlib. | 2.455279 | 2.447319 | 1.003253 |
# Importing matplotlib takes a while, so don't do that at the header.
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.gca()
plt.axis("equal")
# Find the edges that contain the vertex
edge_gids = numpy.where((self.edges["nodes"] == node_... | def show_vertex(self, node_id, show_ce_ratio=True) | Plot the vicinity of a node and its ce_ratio.
:param node_id: Node ID of the node to be shown.
:type node_id: int
:param show_ce_ratio: If true, shows the ce_ratio of the node, too.
:type show_ce_ratio: bool, optional | 2.707894 | 2.766783 | 0.978716 |
'''
Writes a mesh to collada file format.
'''
dae = mesh_to_collada(mesh)
dae.write(f.name) | def _dump(f, mesh) | Writes a mesh to collada file format. | 9.54915 | 4.617535 | 2.068019 |
'''
Generates a UTF-8 XML string containing the mesh, in collada format.
'''
from lxml import etree
dae = mesh_to_collada(mesh)
# Update the xmlnode.
dae.save()
return etree.tostring(dae.xmlnode, encoding='UTF-8') | def dumps(mesh) | Generates a UTF-8 XML string containing the mesh, in collada format. | 7.697158 | 4.546546 | 1.692968 |
'''
Supports per-vertex color, but nothing else.
'''
import numpy as np
try:
from collada import Collada, scene
except ImportError:
raise ImportError("lace.serialization.dae.mesh_to_collade requires package pycollada.")
def create_material(dae):
from collada import ... | def mesh_to_collada(mesh) | Supports per-vertex color, but nothing else. | 3.251222 | 3.079234 | 1.055854 |
'''
Convert the mesh from one set of units to another.
These calls are equivalent:
- mesh.convert_units(from_units='cm', to_units='m')
- mesh.scale(.01)
'''
from blmath import units
factor = units.factor(
from_units=from_units,
t... | def convert_units(self, from_units, to_units) | Convert the mesh from one set of units to another.
These calls are equivalent:
- mesh.convert_units(from_units='cm', to_units='m')
- mesh.scale(.01) | 5.128229 | 2.589006 | 1.980771 |
'''
There is no prediction for united states unit system.
This may fail when a mesh is not axis-aligned
'''
longest_dist = np.max(np.max(self.v, axis=0) - np.min(self.v, axis=0))
if round(longest_dist / 1000) > 0:
return 'mm'
if round(longest_dist / 10... | def predict_body_units(self) | There is no prediction for united states unit system.
This may fail when a mesh is not axis-aligned | 4.453479 | 2.288785 | 1.945783 |
'''
Reorient the mesh by specifying two vectors.
up: The foot-to-head direction.
look: The direction the body is facing.
In the result, the up will end up along +y, and look along +z
(i.e. facing towards a default OpenGL camera).
'''
from blmath.geometr... | def reorient(self, up, look) | Reorient the mesh by specifying two vectors.
up: The foot-to-head direction.
look: The direction the body is facing.
In the result, the up will end up along +y, and look along +z
(i.e. facing towards a default OpenGL camera). | 5.565792 | 2.193313 | 2.537618 |
'''
Flip the mesh across the given axis: 0 for x, 1 for y, 2 for z.
When `preserve_centroid` is True, translate after flipping to
preserve the location of the centroid.
'''
self.v[:, axis] *= -1
if preserve_centroid:
self.v[:, axis] -= 2 * self.cent... | def flip(self, axis=0, preserve_centroid=False) | Flip the mesh across the given axis: 0 for x, 1 for y, 2 for z.
When `preserve_centroid` is True, translate after flipping to
preserve the location of the centroid. | 5.457006 | 2.715813 | 2.009346 |
'''
Return the geometric center.
'''
if self.v is None:
raise ValueError('Mesh has no vertices; centroid is not defined')
return np.mean(self.v, axis=0) | def centroid(self) | Return the geometric center. | 6.901389 | 5.016507 | 1.375736 |
'''
Return the point on the floor that lies below the centroid.
'''
floor_point = self.centroid
# y to floor
floor_point[1] = self.v[:, 1].min()
return floor_point | def floor_point(self) | Return the point on the floor that lies below the centroid. | 9.612205 | 5.253183 | 1.829787 |
'''
Find the most extreme vertex in the direction of the axis provided.
axis: A vector, which is an 3x1 np.array.
'''
from blmath.geometry.apex import apex
return apex(self.v, axis) | def apex(self, axis) | Find the most extreme vertex in the direction of the axis provided.
axis: A vector, which is an 3x1 np.array. | 11.508432 | 2.991165 | 3.847475 |
'''
Flatten the mesh to the plane, dropping the dimension identified by
`squash_axis`: 0 for x, 1 for y, 2 for z. Cast a ray from `origin`,
pointing along `initial_direction`. Sweep the ray, like a radar, until
encountering the mesh, and return that vertex: like the first blip of... | def first_blip(self, squash_axis, origin, initial_direction) | Flatten the mesh to the plane, dropping the dimension identified by
`squash_axis`: 0 for x, 1 for y, 2 for z. Cast a ray from `origin`,
pointing along `initial_direction`. Sweep the ray, like a radar, until
encountering the mesh, and return that vertex: like the first blip of
the radar. ... | 5.968061 | 1.948868 | 3.062322 |
'''
Cut the mesh by a plane, discarding vertices that lie behind that
plane. Or cut the mesh by two parallel planes, discarding vertices
that lie outside them.
The region to keep is defined by an axis of perpendicularity,
specified by `dim`: 0 means x, 1 means y, 2 means... | def cut_across_axis(self, dim, minval=None, maxval=None) | Cut the mesh by a plane, discarding vertices that lie behind that
plane. Or cut the mesh by two parallel planes, discarding vertices
that lie outside them.
The region to keep is defined by an axis of perpendicularity,
specified by `dim`: 0 means x, 1 means y, 2 means z. `minval`
... | 3.55694 | 1.700034 | 2.092276 |
'''
Like cut_across_axis, except the subset of vertices is
constrained by percentile of the data along a given axis
instead of specific values. (See numpy.percentile.)
For example, if the mesh has 50,000 vertices, `dim` is 2, and
`minpct` is 10, this method drops the 5,0... | def cut_across_axis_by_percentile(self, dim, minpct=0, maxpct=100) | Like cut_across_axis, except the subset of vertices is
constrained by percentile of the data along a given axis
instead of specific values. (See numpy.percentile.)
For example, if the mesh has 50,000 vertices, `dim` is 2, and
`minpct` is 10, this method drops the 5,000 vertices which ar... | 6.265182 | 1.586275 | 3.94962 |
'''
Like cut_across_axis, but works with an arbitrary plane. Keeps
vertices that lie in front of the plane (i.e. in the direction
of the plane normal).
inverted: When `True`, invert the logic, to keep the vertices
that lie behind the plane instead.
Return the ... | def cut_by_plane(self, plane, inverted=False) | Like cut_across_axis, but works with an arbitrary plane. Keeps
vertices that lie in front of the plane (i.e. in the direction
of the plane normal).
inverted: When `True`, invert the logic, to keep the vertices
that lie behind the plane instead.
Return the original indices of ... | 7.903635 | 2.163771 | 3.652714 |
'''
returns the surface area of each face
'''
e_1 = self.v[self.f[:, 1]] - self.v[self.f[:, 0]]
e_2 = self.v[self.f[:, 2]] - self.v[self.f[:, 0]]
cross_products = np.array([e_1[:, 1]*e_2[:, 2] - e_1[:, 2]*e_2[:, 1],
e_1[:, 2]*e_2[:, 0] ... | def surface_areas(self) | returns the surface area of each face | 1.989365 | 1.874284 | 1.0614 |
keys = list(env.traceability_all_items.keys())
for key in keys:
if env.traceability_all_items[key]['docname'] == docname:
del env.traceability_all_items[key] | def purge_items(app, env, docname) | Clean, if existing, ``item`` entries in ``traceability_all_items``
environment variable, for all the source docs being purged.
This function should be triggered upon ``env-purge-doc`` event. | 3.258173 | 2.521702 | 1.292053 |
env = app.builder.env
all_items = sorted(env.traceability_all_items, key=naturalsortkey)
# Item matrix:
# Create table with related items, printing their target references.
# Only source and target items matching respective regexp shall be included
for node in doctree.traverse(item_matrix... | def process_item_nodes(app, doctree, fromdocname) | This function should be triggered upon ``doctree-resolved event``
Replace all item_list nodes with a list of the collected items.
Augment each item with a backlink to the original location. | 2.922521 | 2.925102 | 0.999117 |
env = app.builder.env
env.relationships = {}
for rel in list(app.config.traceability_relationships.keys()):
env.relationships[rel] = app.config.traceability_relationships[rel]
env.relationships[app.config.traceability_relationships[rel]] = rel
for rel in sorted(list(env.relationsh... | def update_available_item_relationships(app) | Update directive option_spec with custom relationships defined in
configuration file ``traceability_relationships`` variable. Both
keys (relationships) and values (reverse relationships) are added.
This handler should be called upon builder initialization, before
processing any directive.
Functio... | 3.73926 | 2.808184 | 1.331558 |
env = app.builder.env
# Assure ``traceability_all_items`` will always be there.
if not hasattr(env, 'traceability_all_items'):
env.traceability_all_items = {}
update_available_item_relationships(app) | def initialize_environment(app) | Perform initializations needed before the build process starts. | 8.032403 | 7.655802 | 1.049192 |
id = item_info['target']['refid']
if item_info['caption'] != '':
caption = ', ' + item_info['caption']
else:
caption = ''
para = nodes.paragraph()
newnode = nodes.reference('', '')
innernode = nodes.emphasis(id + caption, id + caption)
newnode['refdocname'] = item_info... | def make_item_ref(app, env, fromdocname, item_info) | Creates a reference node for an item, embedded in a
paragraph. Reference text adds also a caption if it exists. | 3.027557 | 2.824122 | 1.072035 |
return [int(part) if part.isdigit() else part
for part in re.split('([0-9]+)', s)] | def naturalsortkey(s) | Natural sort order | 2.445477 | 2.67592 | 0.913883 |
if not relationships:
relationships = list(env.relationships.keys())
for rel in relationships:
if (target in env.traceability_all_items[source][rel] or
source in
env.traceability_all_items[target][env.relationships[rel]]):
return True
return Fal... | def are_related(env, source, target, relationships) | Returns ``True`` if ``source`` and ``target`` items are related
according a list, ``relationships``, of relationship types.
``False`` is returned otherwise
If the list of relationship types is empty, all available
relationship types are to be considered. | 4.777719 | 4.607137 | 1.037026 |
if not test_for_opengl():
return Dummy()
mv = MeshViewerLocal(
shape=(1, 1), uid=uid, titlebar=titlebar, keepalive=keepalive,
window_width=window_width, window_height=window_height
)
result = mv.get_subwindows()[0][0]
result.snapshot_camera = snapshot_camera
if stati... | def MeshViewer(
titlebar='Mesh Viewer', static_meshes=None, static_lines=None, uid=None,
autorecenter=True, keepalive=False, window_width=1280, window_height=960,
snapshot_camera=None
) | Allows visual inspection of geometric primitives.
Write-only Attributes:
titlebar: string printed in the window titlebar
dynamic_meshes: list of Mesh objects to be displayed
static_meshes: list of Mesh objects to be displayed
dynamic_lines: list of Lines objects to be displayed
... | 3.09916 | 4.130001 | 0.750402 |
if not test_for_opengl():
return Dummy()
mv = MeshViewerLocal(
shape=shape, titlebar=titlebar, uid=None, keepalive=keepalive,
window_width=window_width, window_height=window_height
)
return mv.get_subwindows() | def MeshViewers(
shape=(1, 1), titlebar="Mesh Viewers", keepalive=False,
window_width=1280, window_height=960
) | Allows subplot-style inspection of primitives in multiple subwindows.
Args:
shape: a tuple indicating the number of vertical and horizontal windows requested
Returns: a list of lists of MeshViewer objects: one per window requested. | 5.163929 | 6.411607 | 0.805403 |
from blmath.geometry.transform.rodrigues import as_rotation_matrix
if self.isdragging:
mouse_pt = arcball.Point2fT(cursor_x, cursor_y)
# Update End Vector And Get Rotation As Quaternion
ThisQuat = self.arcball.drag(mouse_pt)
# Convert Quaternion I... | def on_drag(self, cursor_x, cursor_y) | Mouse cursor is moving
Glut calls this function (when mouse button is down)
and pases the mouse cursor postion in window coords as the mouse moves. | 7.409363 | 7.281552 | 1.017553 |
self.isdragging = False
if button == glut.GLUT_LEFT_BUTTON and button_state == glut.GLUT_UP:
# Left button released
self.lastrot = copy.copy(self.thisrot) # Set Last Static Rotation To Last Dynamic One
elif button == glut.GLUT_LEFT_BUTTON and button_state == glu... | def on_click(self, button, button_state, cursor_x, cursor_y) | Mouse button clicked.
Glut calls this function when a mouse button is
clicked or released. | 2.80353 | 2.781896 | 1.007777 |
# Just like for triangular cells, tetrahedron circumcenters are most easily
# computed with the quadrilateral coordinates available.
# Luckily, we have the circumcenter-face distances (cfd):
#
# CC = (
# + cfd[0] * face_area[0] / sum(cfd*face_area) * X[0]... | def _compute_cell_circumcenters(self) | Computes the center of the circumsphere of each cell. | 4.589852 | 4.566595 | 1.005093 |
if self._control_volumes is None:
# 1/3. * (0.5 * edge_length) * covolume
# = 1/6 * edge_length**2 * ce_ratio_edge_ratio
v = self.ei_dot_ei * self.ce_ratios / 6.0
# Explicitly sum up contributions per cell first. Makes
# numpy.add.at faster.... | def control_volumes(self) | Compute the control volumes of all nodes in the mesh. | 8.226829 | 7.739757 | 1.062931 |
# pylint: disable=unused-variable,relative-import
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
if "faces" not in self.cells:
self.create_cell_face_relationships()
if "edges" not in self.faces:
self.create_face_edge... | def show_edge(self, edge_id) | Displays edge with ce_ratio.
:param edge_id: Edge ID for which to show the ce_ratio.
:type edge_id: int | 2.7833 | 2.79952 | 0.994206 |
try:
if isinstance(text, six.integer_types):
return text
elif isinstance(text, six.string_types):
return int(text)
else:
return fallback
except ValueError:
return fallback | def parse_int(text, fallback=None) | Try to extract an integer from a string, return the fallback if that's
not possible. | 2.046624 | 2.041834 | 1.002346 |
table = self._tables.get(name, None)
if table is not None:
return table
if not self.engine.has_table(name):
raise BindingException('Table does not exist: %r' % name,
table=name)
table = Table(name, self.meta, autoload=Tr... | def _load_table(self, name) | Reflect a given table from the database. | 2.704767 | 2.631586 | 1.027809 |
keys = [c for c in self.fact_table.columns if c.primary_key]
return keys[0] | def fact_pk(self) | Try to determine the primary key of the fact table for use in
fact table counting.
If more than one column exists, return the first column of the pk. | 7.318588 | 3.097268 | 2.362917 |
def prep(cuts, drilldowns=False, aggregates=False, columns=None):
q = select(columns)
bindings = []
cuts, q, bindings = Cuts(self).apply(q, bindings, cuts)
attributes = None
if drilldowns is not False:
attributes, q, bindings... | def aggregate(self, aggregates=None, drilldowns=None, cuts=None,
order=None, page=None, page_size=None, page_max=None) | Main aggregation function. This is used to compute a given set of
aggregates, grouped by a given set of drilldown dimensions (i.e.
dividers). The query can also be filtered and sorted. | 3.060877 | 3.093801 | 0.989358 |
def prep(cuts, ref, order, columns=None):
q = select(columns=columns)
bindings = []
cuts, q, bindings = Cuts(self).apply(q, bindings, cuts)
fields, q, bindings = \
Fields(self).apply(q, bindings, ref, distinct=True)
ordering, q... | def members(self, ref, cuts=None, order=None, page=None, page_size=None) | List all the distinct members of the given reference, filtered and
paginated. If the reference describes a dimension, all attributes are
returned. | 3.733898 | 3.762342 | 0.99244 |
def prep(cuts, columns=None):
q = select(columns=columns).select_from(self.fact_table)
bindings = []
_, q, bindings = Cuts(self).apply(q, bindings, cuts)
q = self.restrict_joins(q, bindings)
return q, bindings
# Count
count =... | def facts(self, fields=None, cuts=None, order=None, page=None,
page_size=None, page_max=None) | List all facts in the cube, returning only the specified references
if these are specified. | 3.783008 | 3.827679 | 0.98833 |
for dimension in self.model.dimensions:
result = self.members(dimension.ref, page_size=0)
dimension.spec['cardinality'] = result.get('total_member_count') | def compute_cardinalities(self) | This will count the number of distinct values for each dimension in
the dataset and add that count to the model so that it can be used as a
hint by UI components. | 13.735018 | 10.97733 | 1.251217 |
if len(q.froms) == 1:
return q
else:
for binding in bindings:
if binding.table == self.fact_table:
continue
concept = self.model[binding.ref]
if isinstance(concept, Dimension):
dimens... | def restrict_joins(self, q, bindings) | Restrict the joins across all tables referenced in the database
query to those specified in the model for the relevant dimensions.
If a single table is used for the query, no unnecessary joins are
performed. If more than one table are referenced, this ensures
their returned rows are conn... | 2.463981 | 2.340859 | 1.052597 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.