_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q22900 | unbool | train | def unbool(element, true=object(), false=object()):
"""
A hack to make True and 1 and False and 0 unique for ``uniq``.
"""
if element is True:
return true
elif element is False:
return false
return element | python | {
"resource": ""
} |
q22901 | uniq | train | def uniq(container):
"""
Check if all of a container's elements are unique.
Successively tries first to rely that the elements are hashable, then
falls back on them being sortable, and finally falls back on brute
force.
"""
try:
return len(set(unbool(i) for i in container)) == len... | python | {
"resource": ""
} |
q22902 | FormatChecker.checks | train | def checks(self, format, raises=()):
"""
Register a decorated function as validating a new format.
Arguments:
format (str):
The format that the decorated function will check.
raises (Exception):
The exception(s) raised by the decorated... | python | {
"resource": ""
} |
q22903 | _generate_legacy_type_checks | train | def _generate_legacy_type_checks(types=()):
"""
Generate newer-style type checks out of JSON-type-name-to-type mappings.
Arguments:
types (dict):
A mapping of type names to their Python types
Returns:
A dictionary of definitions to pass to `TypeChecker`
"""
types... | python | {
"resource": ""
} |
q22904 | extend | train | def extend(validator, validators=(), version=None, type_checker=None):
"""
Create a new validator class by extending an existing one.
Arguments:
validator (jsonschema.IValidator):
an existing validator class
validators (collections.Mapping):
a mapping of new vali... | python | {
"resource": ""
} |
q22905 | validator_for | train | def validator_for(schema, default=_LATEST_VERSION):
"""
Retrieve the validator class appropriate for validating the given schema.
Uses the :validator:`$schema` property that should be present in the given
schema to look up the appropriate validator class.
Arguments:
schema (collections.Ma... | python | {
"resource": ""
} |
q22906 | RefResolver.resolving | train | def resolving(self, ref):
"""
Resolve the given ``ref`` and enter its resolution scope.
Exits the scope on exit of this context manager.
Arguments:
ref (str):
The reference to resolve
"""
url, resolved = self.resolve(ref)
self.push... | python | {
"resource": ""
} |
q22907 | ErrorTree.total_errors | train | def total_errors(self):
"""
The total number of errors in the entire tree, including children.
"""
child_errors = sum(len(tree) for _, tree in iteritems(self._contents))
return len(self.errors) + child_errors | python | {
"resource": ""
} |
q22908 | setup | train | def setup(app):
"""
Install the plugin.
Arguments:
app (sphinx.application.Sphinx):
the Sphinx application context
"""
app.add_config_value("cache_path", "_cache", "")
try:
os.makedirs(app.config.cache_path)
except OSError as error:
if error.errno !=... | python | {
"resource": ""
} |
q22909 | fetch_or_load | train | def fetch_or_load(spec_path):
"""
Fetch a new specification or use the cache if it's current.
Arguments:
cache_path:
the path to a cached specification
"""
headers = {}
try:
modified = datetime.utcfromtimestamp(os.path.getmtime(spec_path))
date = modifie... | python | {
"resource": ""
} |
q22910 | namedAny | train | def namedAny(name):
"""
Retrieve a Python object by its fully qualified name from the global Python
module namespace. The first part of the name, that describes a module,
will be discovered and imported. Each subsequent part of the name is
treated as the name of an attribute of the object specifie... | python | {
"resource": ""
} |
q22911 | face_adjacency_unshared | train | def face_adjacency_unshared(mesh):
"""
Return the vertex index of the two vertices not in the shared
edge between two adjacent faces
Parameters
----------
mesh : Trimesh object
Returns
-----------
vid_unshared : (len(mesh.face_adjacency), 2) int
Indexes of mesh.vertices
... | python | {
"resource": ""
} |
q22912 | face_adjacency_radius | train | def face_adjacency_radius(mesh):
"""
Compute an approximate radius between adjacent faces.
Parameters
--------------
mesh : trimesh.Trimesh
Returns
-------------
radii : (len(self.face_adjacency),) float
Approximate radius between faces
Parallel faces will have a value ... | python | {
"resource": ""
} |
q22913 | vertex_adjacency_graph | train | def vertex_adjacency_graph(mesh):
"""
Returns a networkx graph representing the vertices and
their connections in the mesh.
Parameters
----------
mesh : Trimesh object
Returns
---------
graph : networkx.Graph
Graph representing vertices and edges between
them where ... | python | {
"resource": ""
} |
q22914 | shared_edges | train | def shared_edges(faces_a, faces_b):
"""
Given two sets of faces, find the edges which are in both sets.
Parameters
---------
faces_a: (n,3) int, set of faces
faces_b: (m,3) int, set of faces
Returns
---------
shared: (p, 2) int, set of edges
"""
e_a = np.sort(faces_to_edges... | python | {
"resource": ""
} |
q22915 | connected_edges | train | def connected_edges(G, nodes):
"""
Given graph G and list of nodes, return the list of edges that
are connected to nodes
"""
nodes_in_G = collections.deque()
for node in nodes:
if not G.has_node(node):
continue
nodes_in_G.extend(nx.node_connected_component(G, node))
... | python | {
"resource": ""
} |
q22916 | facets | train | def facets(mesh, engine=None):
"""
Find the list of parallel adjacent faces.
Parameters
---------
mesh : trimesh.Trimesh
engine : str
Which graph engine to use:
('scipy', 'networkx', 'graphtool')
Returns
---------
facets : sequence of (n,) int
Groups of face ... | python | {
"resource": ""
} |
q22917 | split | train | def split(mesh,
only_watertight=True,
adjacency=None,
engine=None):
"""
Split a mesh into multiple meshes from face connectivity.
If only_watertight is true, it will only return watertight meshes
and will attempt single triangle/quad repairs.
Parameters
----------... | python | {
"resource": ""
} |
q22918 | connected_component_labels | train | def connected_component_labels(edges, node_count=None):
"""
Label graph nodes from an edge list, using scipy.sparse.csgraph
Parameters
----------
edges : (n, 2) int
Edges of a graph
node_count : int, or None
The largest node in the graph.
Returns
---------
labels : (... | python | {
"resource": ""
} |
q22919 | split_traversal | train | def split_traversal(traversal,
edges,
edges_hash=None):
"""
Given a traversal as a list of nodes, split the traversal
if a sequential index pair is not in the given edges.
Parameters
--------------
edges : (n, 2) int
Graph edge indexes
traversa... | python | {
"resource": ""
} |
q22920 | fill_traversals | train | def fill_traversals(traversals, edges, edges_hash=None):
"""
Convert a traversal of a list of edges into a sequence of
traversals where every pair of consecutive node indexes
is an edge in a passed edge list
Parameters
-------------
traversals : sequence of (m,) int
Node indexes of t... | python | {
"resource": ""
} |
q22921 | traversals | train | def traversals(edges, mode='bfs'):
"""
Given an edge list, generate a sequence of ordered
depth first search traversals, using scipy.csgraph routines.
Parameters
------------
edges : (n,2) int, undirected edges of a graph
mode : str, 'bfs', or 'dfs'
Returns
-----------
travers... | python | {
"resource": ""
} |
q22922 | edges_to_coo | train | def edges_to_coo(edges, count=None, data=None):
"""
Given an edge list, return a boolean scipy.sparse.coo_matrix
representing the edges in matrix form.
Parameters
------------
edges : (n,2) int
Edges of a graph
count : int
The total number of nodes in the graph
if None: co... | python | {
"resource": ""
} |
q22923 | smoothed | train | def smoothed(mesh, angle):
"""
Return a non- watertight version of the mesh which will
render nicely with smooth shading by disconnecting faces
at sharp angles to each other.
Parameters
---------
mesh : trimesh.Trimesh
Source geometry
angle : float
Angle in radians, adjacent... | python | {
"resource": ""
} |
q22924 | graph_to_svg | train | def graph_to_svg(graph):
"""
Turn a networkx graph into an SVG string, using graphviz dot.
Parameters
----------
graph: networkx graph
Returns
---------
svg: string, pictoral layout in SVG format
"""
import tempfile
import subprocess
with tempfile.NamedTemporaryFile() ... | python | {
"resource": ""
} |
q22925 | multigraph_paths | train | def multigraph_paths(G, source, cutoff=None):
"""
For a networkx MultiDiGraph, find all paths from a source node
to leaf nodes. This function returns edge instance numbers
in addition to nodes, unlike networkx.all_simple_paths.
Parameters
---------------
G : networkx.MultiDiGraph
Grap... | python | {
"resource": ""
} |
q22926 | multigraph_collect | train | def multigraph_collect(G, traversal, attrib=None):
"""
Given a MultiDiGraph traversal, collect attributes along it.
Parameters
-------------
G: networkx.MultiDiGraph
traversal: (n) list of (node, instance) tuples
attrib: dict key, name to collect. If None, will return all
... | python | {
"resource": ""
} |
q22927 | kwargs_to_matrix | train | def kwargs_to_matrix(**kwargs):
"""
Turn a set of keyword arguments into a transformation matrix.
"""
matrix = np.eye(4)
if 'matrix' in kwargs:
# a matrix takes precedence over other options
matrix = kwargs['matrix']
elif 'quaternion' in kwargs:
matrix = transformations.q... | python | {
"resource": ""
} |
q22928 | TransformForest.update | train | def update(self, frame_to, frame_from=None, **kwargs):
"""
Update a transform in the tree.
Parameters
---------
frame_from : hashable object
Usually a string (eg 'world').
If left as None it will be set to self.base_frame
frame_to : hashable object
... | python | {
"resource": ""
} |
q22929 | TransformForest.md5 | train | def md5(self):
"""
"Hash" of transforms
Returns
-----------
md5 : str
Approximate hash of transforms
"""
result = str(self._updated) + str(self.base_frame)
return result | python | {
"resource": ""
} |
q22930 | TransformForest.copy | train | def copy(self):
"""
Return a copy of the current TransformForest
Returns
------------
copied: TransformForest
"""
copied = TransformForest()
copied.base_frame = copy.deepcopy(self.base_frame)
copied.transforms = copy.deepcopy(self.transforms)
... | python | {
"resource": ""
} |
q22931 | TransformForest.to_flattened | train | def to_flattened(self, base_frame=None):
"""
Export the current transform graph as a flattened
"""
if base_frame is None:
base_frame = self.base_frame
flat = {}
for node in self.nodes:
if node == base_frame:
continue
tr... | python | {
"resource": ""
} |
q22932 | TransformForest.to_gltf | train | def to_gltf(self, scene):
"""
Export a transforms as the 'nodes' section of a GLTF dict.
Flattens tree.
Returns
--------
gltf : dict
with keys:
'nodes': list of dicts
"""
# geometry is an OrderedDict
# {geometry key : i... | python | {
"resource": ""
} |
q22933 | TransformForest.from_edgelist | train | def from_edgelist(self, edges, strict=True):
"""
Load transform data from an edge list into the current
scene graph.
Parameters
-------------
edgelist : (n,) tuples
(node_a, node_b, {key: value})
strict : bool
If true, raise a ValueError w... | python | {
"resource": ""
} |
q22934 | TransformForest.nodes | train | def nodes(self):
"""
A list of every node in the graph.
Returns
-------------
nodes: (n,) array, of node names
"""
nodes = np.array(list(self.transforms.nodes()))
return nodes | python | {
"resource": ""
} |
q22935 | TransformForest.nodes_geometry | train | def nodes_geometry(self):
"""
The nodes in the scene graph with geometry attached.
Returns
------------
nodes_geometry: (m,) array, of node names
"""
nodes = np.array([
n for n in self.transforms.nodes()
if 'geometry' in self.transforms.n... | python | {
"resource": ""
} |
q22936 | TransformForest.get | train | def get(self, frame_to, frame_from=None):
"""
Get the transform from one frame to another, assuming they are connected
in the transform tree.
If the frames are not connected a NetworkXNoPath error will be raised.
Parameters
---------
frame_from: hashable object,... | python | {
"resource": ""
} |
q22937 | TransformForest.show | train | def show(self):
"""
Plot the graph layout of the scene.
"""
import matplotlib.pyplot as plt
nx.draw(self.transforms, with_labels=True)
plt.show() | python | {
"resource": ""
} |
q22938 | TransformForest._get_path | train | def _get_path(self, frame_from, frame_to):
"""
Find a path between two frames, either from cached paths or
from the transform graph.
Parameters
---------
frame_from: a frame key, usually a string
eg, 'world'
frame_to: a frame key, usually a ... | python | {
"resource": ""
} |
q22939 | is_ccw | train | def is_ccw(points):
"""
Check if connected planar points are counterclockwise.
Parameters
-----------
points: (n,2) float, connected points on a plane
Returns
----------
ccw: bool, True if points are counterclockwise
"""
points = np.asanyarray(points, dtype=np.float64)
if ... | python | {
"resource": ""
} |
q22940 | concatenate | train | def concatenate(paths):
"""
Concatenate multiple paths into a single path.
Parameters
-------------
paths: list of Path, Path2D, or Path3D objects
Returns
-------------
concat: Path, Path2D, or Path3D object
"""
# if only one path object just return copy
if len(paths) == 1:... | python | {
"resource": ""
} |
q22941 | filter_humphrey | train | def filter_humphrey(mesh,
alpha=0.1,
beta=0.5,
iterations=10,
laplacian_operator=None):
"""
Smooth a mesh in-place using laplacian smoothing
and Humphrey filtering.
Articles
"Improved Laplacian Smoothing of Noisy Surfac... | python | {
"resource": ""
} |
q22942 | filter_taubin | train | def filter_taubin(mesh,
lamb=0.5,
nu=0.5,
iterations=10,
laplacian_operator=None):
"""
Smooth a mesh in-place using laplacian smoothing
and taubin filtering.
Articles
"Improved Laplacian Smoothing of Noisy Surface Meshes"
J... | python | {
"resource": ""
} |
q22943 | laplacian_calculation | train | def laplacian_calculation(mesh, equal_weight=True):
"""
Calculate a sparse matrix for laplacian operations.
Parameters
-------------
mesh : trimesh.Trimesh
Input geometry
equal_weight : bool
If True, all neighbors will be considered equally
If False, all neightbors will be wei... | python | {
"resource": ""
} |
q22944 | is_circle | train | def is_circle(points, scale, verbose=False):
"""
Given a set of points, quickly determine if they represent
a circle or not.
Parameters
-------------
points: (n,2) float, points in space
scale: float, scale of overall drawing
verbose: bool, print all fit messages or not
Returns
... | python | {
"resource": ""
} |
q22945 | merge_colinear | train | def merge_colinear(points, scale):
"""
Given a set of points representing a path in space,
merge points which are colinear.
Parameters
----------
points: (n, d) set of points (where d is dimension)
scale: float, scale of drawing
Returns
----------
merged: (j, d) set of points ... | python | {
"resource": ""
} |
q22946 | resample_spline | train | def resample_spline(points, smooth=.001, count=None, degree=3):
"""
Resample a path in space, smoothing along a b-spline.
Parameters
-----------
points: (n, dimension) float, points in space
smooth: float, smoothing amount
count: number of samples in output
degree: int, degree of splin... | python | {
"resource": ""
} |
q22947 | points_to_spline_entity | train | def points_to_spline_entity(points, smooth=None, count=None):
"""
Create a spline entity from a curve in space
Parameters
-----------
points: (n, dimension) float, points in space
smooth: float, smoothing amount
count: int, number of samples in result
Returns
---------
entity:... | python | {
"resource": ""
} |
q22948 | simplify_basic | train | def simplify_basic(drawing, process=False, **kwargs):
"""
Merge colinear segments and fit circles.
Parameters
-----------
drawing: Path2D object, will not be modified.
Returns
-----------
simplified: Path2D with circles.
"""
if any(i.__class__.__name__ != 'Line'
for... | python | {
"resource": ""
} |
q22949 | simplify_spline | train | def simplify_spline(path, smooth=None, verbose=False):
"""
Replace discrete curves with b-spline or Arc and
return the result as a new Path2D object.
Parameters
------------
path : trimesh.path.Path2D
Input geometry
smooth : float
Distance to smooth
Returns
------------... | python | {
"resource": ""
} |
q22950 | boolean | train | def boolean(meshes, operation='difference'):
"""
Run an operation on a set of meshes
"""
script = operation + '(){'
for i in range(len(meshes)):
script += 'import(\"$mesh_' + str(i) + '\");'
script += '}'
return interface_scad(meshes, script) | python | {
"resource": ""
} |
q22951 | parse_mtl | train | def parse_mtl(mtl):
"""
Parse a loaded MTL file.
Parameters
-------------
mtl : str or bytes
Data from an MTL file
Returns
------------
mtllibs : list of dict
Each dict has keys: newmtl, map_Kd, Kd
"""
# decode bytes if necessary
if hasattr(mtl, 'decode'):
... | python | {
"resource": ""
} |
q22952 | export_wavefront | train | def export_wavefront(mesh,
include_normals=True,
include_texture=True):
"""
Export a mesh as a Wavefront OBJ file
Parameters
-----------
mesh: Trimesh object
Returns
-----------
export: str, string of OBJ format output
"""
# store the m... | python | {
"resource": ""
} |
q22953 | RayMeshIntersector._scale | train | def _scale(self):
"""
Scaling factor for precision.
"""
if self._scale_to_box:
# scale vertices to approximately a cube to help with
# numerical issues at very large/small scales
scale = 100.0 / self.mesh.scale
else:
scale = 1.0
... | python | {
"resource": ""
} |
q22954 | RayMeshIntersector._scene | train | def _scene(self):
"""
A cached version of the pyembree scene.
"""
return _EmbreeWrap(vertices=self.mesh.vertices,
faces=self.mesh.faces,
scale=self._scale) | python | {
"resource": ""
} |
q22955 | RayMeshIntersector.intersects_location | train | def intersects_location(self,
ray_origins,
ray_directions,
multiple_hits=True):
"""
Return the location of where a ray hits a surface.
Parameters
----------
ray_origins: (n,3) float, origins o... | python | {
"resource": ""
} |
q22956 | RayMeshIntersector.intersects_id | train | def intersects_id(self,
ray_origins,
ray_directions,
multiple_hits=True,
max_hits=20,
return_locations=False):
"""
Find the triangles hit by a list of rays, including
optionally multiple... | python | {
"resource": ""
} |
q22957 | RayMeshIntersector.intersects_first | train | def intersects_first(self,
ray_origins,
ray_directions):
"""
Find the index of the first triangle a ray hits.
Parameters
----------
ray_origins: (n,3) float, origins of rays
ray_directions: (n,3) float, direction (vec... | python | {
"resource": ""
} |
q22958 | RayMeshIntersector.intersects_any | train | def intersects_any(self,
ray_origins,
ray_directions):
"""
Check if a list of rays hits the surface.
Parameters
----------
ray_origins: (n,3) float, origins of rays
ray_directions: (n,3) float, direction (vector) of rays
... | python | {
"resource": ""
} |
q22959 | _attrib_to_transform | train | def _attrib_to_transform(attrib):
"""
Extract a homogenous transform from a dictionary.
Parameters
------------
attrib: dict, optionally containing 'transform'
Returns
------------
transform: (4, 4) float, homogeonous transformation
"""
transform = np.eye(4, dtype=np.float64)
... | python | {
"resource": ""
} |
q22960 | check | train | def check(a, b, digits):
"""
Check input ranges, convert them to vector form,
and get a fixed precision integer version of them.
Parameters
--------------
a : (2, ) or (2, n) float
Start and end of a 1D interval
b : (2, ) or (2, n) float
Start and end of a 1D interval
digits... | python | {
"resource": ""
} |
q22961 | intersection | train | def intersection(a, b, digits=8):
"""
Given a pair of ranges, merge them in to
one range if they overlap at all
Parameters
--------------
a : (2, ) float
Start and end of a 1D interval
b : (2, ) float
Start and end of a 1D interval
digits : int
How many digits to consi... | python | {
"resource": ""
} |
q22962 | geometry_hash | train | def geometry_hash(geometry):
"""
Get an MD5 for a geometry object
Parameters
------------
geometry : object
Returns
------------
MD5 : str
"""
if hasattr(geometry, 'md5'):
# for most of our trimesh objects
md5 = geometry.md5()
elif hasattr(geometry, 'tostrin... | python | {
"resource": ""
} |
q22963 | render_scene | train | def render_scene(scene,
resolution=(1080, 1080),
visible=True,
**kwargs):
"""
Render a preview of a scene to a PNG.
Parameters
------------
scene : trimesh.Scene
Geometry to be rendered
resolution : (2,) int
Resolution in pixels
... | python | {
"resource": ""
} |
q22964 | SceneViewer.add_geometry | train | def add_geometry(self, name, geometry, **kwargs):
"""
Add a geometry to the viewer.
Parameters
--------------
name : hashable
Name that references geometry
geometry : Trimesh, Path2D, Path3D, PointCloud
Geometry to display in the viewer window
... | python | {
"resource": ""
} |
q22965 | SceneViewer.reset_view | train | def reset_view(self, flags=None):
"""
Set view to the default view.
Parameters
--------------
flags : None or dict
If any view key passed override the default
e.g. {'cull': False}
"""
self.view = {
'cull': True,
'axis':... | python | {
"resource": ""
} |
q22966 | SceneViewer.init_gl | train | def init_gl(self):
"""
Perform the magic incantations to create an
OpenGL scene using pyglet.
"""
# default background color is white-ish
background = [.99, .99, .99, 1.0]
# if user passed a background color use it
if 'background' in self.kwargs:
... | python | {
"resource": ""
} |
q22967 | SceneViewer._gl_enable_lighting | train | def _gl_enable_lighting(scene):
"""
Take the lights defined in scene.lights and
apply them as openGL lights.
"""
gl.glEnable(gl.GL_LIGHTING)
# opengl only supports 7 lights?
for i, light in enumerate(scene.lights[:7]):
# the index of which light we hav... | python | {
"resource": ""
} |
q22968 | SceneViewer.update_flags | train | def update_flags(self):
"""
Check the view flags, and call required GL functions.
"""
# view mode, filled vs wirefrom
if self.view['wireframe']:
gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE)
else:
gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_F... | python | {
"resource": ""
} |
q22969 | SceneViewer.on_resize | train | def on_resize(self, width, height):
"""
Handle resized windows.
"""
width, height = self._update_perspective(width, height)
self.scene.camera.resolution = (width, height)
self.view['ball'].resize(self.scene.camera.resolution)
self.scene.camera.transform = self.vie... | python | {
"resource": ""
} |
q22970 | SceneViewer.on_mouse_press | train | def on_mouse_press(self, x, y, buttons, modifiers):
"""
Set the start point of the drag.
"""
self.view['ball'].set_state(Trackball.STATE_ROTATE)
if (buttons == pyglet.window.mouse.LEFT):
ctrl = (modifiers & pyglet.window.key.MOD_CTRL)
shift = (modifiers & ... | python | {
"resource": ""
} |
q22971 | SceneViewer.on_mouse_drag | train | def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
"""
Pan or rotate the view.
"""
self.view['ball'].drag(np.array([x, y]))
self.scene.camera.transform = self.view['ball'].pose | python | {
"resource": ""
} |
q22972 | SceneViewer.on_mouse_scroll | train | def on_mouse_scroll(self, x, y, dx, dy):
"""
Zoom the view.
"""
self.view['ball'].scroll(dy)
self.scene.camera.transform = self.view['ball'].pose | python | {
"resource": ""
} |
q22973 | SceneViewer.on_key_press | train | def on_key_press(self, symbol, modifiers):
"""
Call appropriate functions given key presses.
"""
magnitude = 10
if symbol == pyglet.window.key.W:
self.toggle_wireframe()
elif symbol == pyglet.window.key.Z:
self.reset_view()
elif symbol == p... | python | {
"resource": ""
} |
q22974 | SceneViewer.on_draw | train | def on_draw(self):
"""
Run the actual draw calls.
"""
self._update_meshes()
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
gl.glLoadIdentity()
# pull the new camera transform from the scene
transform_camera = self.scene.graph.get(
... | python | {
"resource": ""
} |
q22975 | SceneViewer.save_image | train | def save_image(self, file_obj):
"""
Save the current color buffer to a file object
in PNG format.
Parameters
-------------
file_obj: file name, or file- like object
"""
manager = pyglet.image.get_buffer_manager()
colorbuffer = manager.get_color_bu... | python | {
"resource": ""
} |
q22976 | unit_conversion | train | def unit_conversion(current, desired):
"""
Calculate the conversion from one set of units to another.
Parameters
---------
current : str
Unit system values are in now (eg 'millimeters')
desired : str
Unit system we'd like values in (eg 'inches')
Returns
---------
co... | python | {
"resource": ""
} |
q22977 | units_from_metadata | train | def units_from_metadata(obj, guess=True):
"""
Try to extract hints from metadata and if that fails
guess based on the object scale.
Parameters
------------
obj: object
Has attributes 'metadata' (dict) and 'scale' (float)
guess : bool
If metadata doesn't indicate units, gues... | python | {
"resource": ""
} |
q22978 | _convert_units | train | def _convert_units(obj, desired, guess=False):
"""
Given an object with scale and units try to scale
to different units via the object's `apply_scale`.
Parameters
---------
obj : object
With apply_scale method (i.e. Trimesh, Path2D, etc)
desired : str
Units desired (eg 'inc... | python | {
"resource": ""
} |
q22979 | export_path | train | def export_path(path,
file_type=None,
file_obj=None,
**kwargs):
"""
Export a Path object to a file- like object, or to a filename
Parameters
---------
file_obj: None, str, or file object
A filename string or a file-like object
file_type: No... | python | {
"resource": ""
} |
q22980 | export_dict | train | def export_dict(path):
"""
Export a path as a dict of kwargs for the Path constructor.
"""
export_entities = [e.to_dict() for e in path.entities]
export_object = {'entities': export_entities,
'vertices': path.vertices.tolist()}
return export_object | python | {
"resource": ""
} |
q22981 | _write_export | train | def _write_export(export, file_obj=None):
"""
Write a string to a file.
If file_obj isn't specified, return the string
Parameters
---------
export: a string of the export data
file_obj: a file-like object or a filename
"""
if file_obj is None:
return export
if hasattr(... | python | {
"resource": ""
} |
q22982 | sample_surface | train | def sample_surface(mesh, count):
"""
Sample the surface of a mesh, returning the specified
number of points
For individual triangle sampling uses this method:
http://mathworld.wolfram.com/TrianglePointPicking.html
Parameters
---------
mesh: Trimesh object
count: number of points to... | python | {
"resource": ""
} |
q22983 | volume_mesh | train | def volume_mesh(mesh, count):
"""
Use rejection sampling to produce points randomly distributed
in the volume of a mesh.
Parameters
----------
mesh: Trimesh object
count: int, number of samples desired
Returns
----------
samples: (n,3) float, points in the volume of the mesh.
... | python | {
"resource": ""
} |
q22984 | volume_rectangular | train | def volume_rectangular(extents,
count,
transform=None):
"""
Return random samples inside a rectangular volume.
Parameters
----------
extents: (3,) float, side lengths of rectangular solid
count: int, number of points to return
transform: (... | python | {
"resource": ""
} |
q22985 | sample_surface_even | train | def sample_surface_even(mesh, count):
"""
Sample the surface of a mesh, returning samples which are
approximately evenly spaced.
Parameters
---------
mesh: Trimesh object
count: number of points to return
Returns
---------
samples: (count,3) points in space on the surface of m... | python | {
"resource": ""
} |
q22986 | sample_surface_sphere | train | def sample_surface_sphere(count):
"""
Correctly pick random points on the surface of a unit sphere
Uses this method:
http://mathworld.wolfram.com/SpherePointPicking.html
Parameters
----------
count: int, number of points to return
Returns
----------
points: (count,3) float, li... | python | {
"resource": ""
} |
q22987 | parameters_to_segments | train | def parameters_to_segments(origins, vectors, parameters):
"""
Convert a parametric line segment representation to
a two point line segment representation
Parameters
------------
origins : (n, 3) float
Line origin point
vectors : (n, 3) float
Unit line directions
parameters... | python | {
"resource": ""
} |
q22988 | colinear_pairs | train | def colinear_pairs(segments,
radius=.01,
angle=.01,
length=None):
"""
Find pairs of segments which are colinear.
Parameters
-------------
segments : (n, 2, (2, 3)) float
Two or three dimensional line segments
radius : float
Ma... | python | {
"resource": ""
} |
q22989 | unique | train | def unique(segments, digits=5):
"""
Find unique line segments.
Parameters
------------
segments : (n, 2, (2|3)) float
Line segments in space
digits : int
How many digits to consider when merging vertices
Returns
-----------
unique : (m, 2, (2|3)) float
Segments wi... | python | {
"resource": ""
} |
q22990 | overlap | train | def overlap(origins, vectors, params):
"""
Find the overlap of two parallel line segments.
Parameters
------------
origins : (2, 3) float
Origin points of lines in space
vectors : (2, 3) float
Unit direction vectors of lines
params : (2, 2) float
Two (start, end) distan... | python | {
"resource": ""
} |
q22991 | _load_texture | train | def _load_texture(file_name, resolver):
"""
Load a texture from a file into a PIL image.
"""
file_data = resolver.get(file_name)
image = PIL.Image.open(util.wrap_as_stream(file_data))
return image | python | {
"resource": ""
} |
q22992 | _parse_material | train | def _parse_material(effect, resolver):
"""
Turn a COLLADA effect into a trimesh material.
"""
# Compute base color
baseColorFactor = np.ones(4)
baseColorTexture = None
if isinstance(effect.diffuse, collada.material.Map):
try:
baseColorTexture = _load_texture(
... | python | {
"resource": ""
} |
q22993 | _unparse_material | train | def _unparse_material(material):
"""
Turn a trimesh material into a COLLADA material.
"""
# TODO EXPORT TEXTURES
if isinstance(material, visual.texture.PBRMaterial):
diffuse = material.baseColorFactor
if diffuse is not None:
diffuse = list(diffuse)
emission = mat... | python | {
"resource": ""
} |
q22994 | load_zae | train | def load_zae(file_obj, resolver=None, **kwargs):
"""
Load a ZAE file, which is just a zipped DAE file.
Parameters
-------------
file_obj : file object
Contains ZAE data
resolver : trimesh.visual.Resolver
Resolver to load additional assets
kwargs : dict
Passed to load_colla... | python | {
"resource": ""
} |
q22995 | load_off | train | def load_off(file_obj, **kwargs):
"""
Load an OFF file into the kwargs for a Trimesh constructor
Parameters
----------
file_obj : file object
Contains an OFF file
Returns
----------
loaded : dict
kwargs for Trimesh constructor
"""
header_string =... | python | {
"resource": ""
} |
q22996 | load_msgpack | train | def load_msgpack(blob, **kwargs):
"""
Load a dict packed with msgpack into kwargs for
a Trimesh constructor
Parameters
----------
blob : bytes
msgpack packed dict containing
keys 'vertices' and 'faces'
Returns
----------
loaded : dict
Keyword args for Trimesh const... | python | {
"resource": ""
} |
q22997 | discretize_bspline | train | def discretize_bspline(control,
knots,
count=None,
scale=1.0):
"""
Given a B-Splines control points and knot vector, return
a sampled version of the curve.
Parameters
----------
control : (o, d) float
Control points of t... | python | {
"resource": ""
} |
q22998 | binomial | train | def binomial(n):
"""
Return all binomial coefficients for a given order.
For n > 5, scipy.special.binom is used, below we hardcode
to avoid the scipy.special dependency.
Parameters
--------------
n : int
Order
Returns
---------------
binom : (n + 1,) int
Binomial c... | python | {
"resource": ""
} |
q22999 | Path.process | train | def process(self):
"""
Apply basic cleaning functions to the Path object, in- place.
"""
log.debug('Processing drawing')
with self._cache:
for func in self._process_functions():
func()
return self | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.