Cut the solid by a plane. Returns the solid on the back side of the plane
556018
function(plane) {
            if (this.polygons.length === 0) {
                return new CSG();
            }
            // Ideally we would like to do an intersection with a polygon of inifinite size
            // but this is not supported by our implementation. As a workaround, we will create
            // a cube, with one face on the plane, and a size larger enough so that the entire
            // solid fits in the cube.
            // find the max distance of any vertex to the center of the plane:
            var planecenter = plane.normal.times(plane.w);
            var maxdistance = 0;
            this.polygons.map(function(polygon) {
                polygon.vertices.map(function(vertex) {
                    var distance = vertex.pos.distanceToSquared(planecenter);
                    if (distance > maxdistance) maxdistance = distance;
                });
            });
            maxdistance = Math.sqrt(maxdistance);
            maxdistance *= 1.01; // make sure it's really larger
            // Now build a polygon on the plane, at any point farther than maxdistance from the plane center:
            var vertices = [];
            var orthobasis = new CSG.OrthoNormalBasis(plane);
            vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(maxdistance, -maxdistance))));
            vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(-maxdistance, -maxdistance))));
            vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(-maxdistance, maxdistance))));
            vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(maxdistance, maxdistance))));
            var polygon = new CSG.Polygon(vertices, null, plane.flipped());

            // and extrude the polygon into a cube, backwards of the plane:
            var cube = polygon.extrude(plane.normal.times(-maxdistance));

            // Now we can do the intersection:
            var result = this.intersect(cube);
            result.properties = this.properties; // keep original properties
            return result;
        }
643967
def make_simple(self):
        
        (inner_radius, outer_radius) = self.get_radii()
        radius = (inner_radius + outer_radius) / 2
        return cadquery.Workplane('XY') \
            .circle(radius).extrude(self.length)
77221
def _internal_get_cut_vertex_list(graph):
    
    list_of_cut_vertices = set()
    if graph.num_nodes() == 0:
        return list(list_of_cut_vertices)

    dfs_count = 0
    root_dfs_count = 1
    dfs_stack = deque()
    visited = defaultdict(lambda: False)
    parent = defaultdict(lambda: None)
    children = defaultdict(lambda: [])
    depth = {}
    low = {}
    preorder_processed = defaultdict(lambda: False)
    postorder_processed = defaultdict(lambda: False)

    # We're simulating a recursive DFS with an explicit stack, since Python has a really small function stack
    unvisited_nodes = set(graph.get_all_node_ids())
    while len(unvisited_nodes) > 0:
        # --Initialize the first stack frame, simulating the DFS call on the root node
        u = unvisited_nodes.pop()
        parent[u] = u
        stack_frame = {
            'u': u,
            'v': None,
            'remaining_children': graph.neighbors(u)
        }
        dfs_stack.appendleft(stack_frame)

        while len(dfs_stack) > 0:
            frame = dfs_stack.popleft()
            u = frame['u']
            v = frame['v']

            if not visited[u]:
                if u in unvisited_nodes:
                    unvisited_nodes.remove(u)
                visited[u] = True
                dfs_count += 1
                depth[u] = dfs_count
                low[u] = depth[u]
                if len(frame['remaining_children']) > 0:
                    v = frame['remaining_children'].pop()
                    frame['v'] = v

            if v is None:
                # --u has no neighbor nodes
                continue

            if not preorder_processed[v]:
                # --This is the preorder processing, done for each neighbor node ''v'' of u
                parent[v] = u
                children[u].append(v)
                preorder_processed[v] = True
                # print 'preorder for {}'.format(v)
                dfs_stack.appendleft(frame)

                # --Simulate the recursion to call the DFS on v
                new_frame = {
                    'u': v,
                    'v': None,
                    'remaining_children': graph.neighbors(v)
                }
                dfs_stack.appendleft(new_frame)
                continue

            elif not postorder_processed[v] and u == parent[v]:
                # --This is the postorder processing, done for each neighbor node ''v'' of u
                if low[v] >= depth[u] and depth[u] > 1:
                    list_of_cut_vertices.add(u)
                low[u] = min(low[u], low[v])
                postorder_processed[v] = True
                # print 'postorder for {}'.format(v)

            elif visited[v] and (parent[u] != v) and (depth[v] < depth[u]):
                # (u,v) is a backedge from u to its ancestor v
                low[u] = min(low[u], depth[v])

            if len(frame['remaining_children']) > 0:
                # --Continue onto the next neighbor node of u
                v = frame['remaining_children'].pop()
                frame['v'] = v
                dfs_stack.appendleft(frame)

    # The root node gets special treatment; it's a cut vertex iff it has multiple children
    if len(children[root_dfs_count]) > 1:
        for node_id, dfs in list(depth.items()):
            if dfs == root_dfs_count:
                list_of_cut_vertices.add(node_id)
                break

    return list(list_of_cut_vertices)
1228010
function(obj) {
                if (this.intersects(obj) || this.contains(obj)) { return 0; }
                if (obj.anchor) {
                  // obj is a plane or line
                  var A = this.anchor.elements, B = obj.anchor.elements, N = this.normal.elements;
                  return Math.abs((A[0] - B[0]) * N[0] + (A[1] - B[1]) * N[1] + (A[2] - B[2]) * N[2]);
                } else {
                  // obj is a point
                  var P = obj.elements || obj;
                  var A = this.anchor.elements, N = this.normal.elements;
                  return Math.abs((A[0] - P[0]) * N[0] + (A[1] - P[1]) * N[1] + (A[2] - (P[2] || 0)) * N[2]);
                }
              }
1118617
def _get_cuts(transition, direction):
    """"""
    n = transition.network.size

    if direction is Direction.BIDIRECTIONAL:
        yielded = set()
        for cut in chain(_get_cuts(transition, Direction.CAUSE),
                         _get_cuts(transition, Direction.EFFECT)):
            cm = utils.np_hashable(cut.cut_matrix(n))
            if cm not in yielded:
                yielded.add(cm)
                yield cut

    else:
        mechanism = transition.mechanism_indices(direction)
        purview = transition.purview_indices(direction)
        for partition in mip_partitions(mechanism, purview,
                                        transition.node_labels):
            yield ActualCut(direction, partition, transition.node_labels)
232990
function splitPolygonByPlane (splane, polygon) {
  let result = {
    type: null,
    front: null,
    back: null
  }
  // cache in local lets (speedup):
  let vertices = polygon.vertices
  let numvertices = vertices.length
  if (plane.equals(polygon.plane, splane)) {
    result.type = 0
  } else {
    let hasfront = false
    let hasback = false
    let vertexIsBack = []
    let MINEPS = -EPS
    for (let i = 0; i < numvertices; i++) {
      let t = vec3.dot(splane, vertices[i]) - splane[3]
      let isback = (t < 0)
      vertexIsBack.push(isback)
      if (t > EPS) hasfront = true
      if (t < MINEPS) hasback = true
    }
    if ((!hasfront) && (!hasback)) {
      // all points coplanar
      let t = vec3.dot(splane, polygon.plane)
      result.type = (t >= 0) ? 0 : 1
    } else if (!hasback) {
      result.type = 2
    } else if (!hasfront) {
      result.type = 3
    } else {
      // spanning
      result.type = 4
      let frontvertices = []
      let backvertices = []
      let isback = vertexIsBack[0]
      for (let vertexindex = 0; vertexindex < numvertices; vertexindex++) {
        let vertex = vertices[vertexindex]
        let nextvertexindex = vertexindex + 1
        if (nextvertexindex >= numvertices) nextvertexindex = 0
        let nextisback = vertexIsBack[nextvertexindex]
        if (isback === nextisback) {
          // line segment is on one side of the plane:
          if (isback) {
            backvertices.push(vertex)
          } else {
            frontvertices.push(vertex)
          }
        } else {
          // line segment intersects plane:
          let point = vertex
          let nextpoint = vertices[nextvertexindex]
          let intersectionpoint = splitLineSegmentByPlane(splane, point, nextpoint)
          if (isback) {
            backvertices.push(vertex)
            backvertices.push(intersectionpoint)
            frontvertices.push(intersectionpoint)
          } else {
            frontvertices.push(vertex)
            frontvertices.push(intersectionpoint)
            backvertices.push(intersectionpoint)
          }
        }
        isback = nextisback
      } // for vertexindex
      // remove duplicate vertices:
      let EPS_SQUARED = EPS * EPS
      if (backvertices.length >= 3) {
        let prevvertex = backvertices[backvertices.length - 1]
        for (let vertexindex = 0; vertexindex < backvertices.length; vertexindex++) {
          let vertex = backvertices[vertexindex]
          if (vec3.squaredDistance(vertex, prevvertex) < EPS_SQUARED) {
            backvertices.splice(vertexindex, 1)
            vertexindex--
          }
          prevvertex = vertex
        }
      }
      if (frontvertices.length >= 3) {
        let prevvertex = frontvertices[frontvertices.length - 1]
        for (let vertexindex = 0; vertexindex < frontvertices.length; vertexindex++) {
          let vertex = frontvertices[vertexindex]
          if (vec3.squaredDistance(vertex, prevvertex) < EPS_SQUARED) {
            frontvertices.splice(vertexindex, 1)
            vertexindex--
          }
          prevvertex = vertex
        }
      }
      if (frontvertices.length >= 3) {
        result.front = poly3.fromPoints(frontvertices, polygon.plane)
      }
      if (backvertices.length >= 3) {
        result.back = poly3.fromPoints(backvertices, polygon.plane)
      }
    }
  }
  return result
}
182165
@Pure
	public Plane3D<?> getPlane() {
		return toPlane(
				getX1(), getY1(), getZ1(),
				getX1(), getY1(), getZ1(),
				getX1(), getY1(), getZ1());
	}
185083
function (splane, coplanarfrontnodes, coplanarbacknodes, frontnodes, backnodes) {
    let polygon = this.polygon
    if (polygon) {
      let bound = poly3.measureBoundingSphere(polygon)
      let sphereradius = bound[1] + EPS // FIXME Why add imprecision?
      let spherecenter = bound[0]
      let d = vec3.dot(splane, spherecenter) - splane[3]
      if (d > sphereradius) {
        frontnodes.push(this)
      } else if (d < -sphereradius) {
        backnodes.push(this)
      } else {
        let splitresult = splitPolygonByPlane(splane, polygon)
        switch (splitresult.type) {
          case 0:
            // coplanar front:
            coplanarfrontnodes.push(this)
            break

          case 1:
            // coplanar back:
            coplanarbacknodes.push(this)
            break

          case 2:
            // front:
            frontnodes.push(this)
            break

          case 3:
            // back:
            backnodes.push(this)
            break

          case 4:
            // spanning:
            if (splitresult.front) {
              let frontnode = this.addChild(splitresult.front)
              frontnodes.push(frontnode)
            }
            if (splitresult.back) {
              let backnode = this.addChild(splitresult.back)
              backnodes.push(backnode)
            }
            break
        }
      }
    }
  }
252120
def damaged_by_cut(self, subsystem):
        
        return (subsystem.cut.splits_mechanism(self.mechanism) or
                np.any(self._relevant_connections(subsystem) *
                       subsystem.cut.cut_matrix(subsystem.network.size) == 1))
1083522
def crop_bezier(seg, t0, t1):
    """"""
    assert t0 < t1
    if t0 == 0:
        cropped_seg = seg.split(t1)[0]
    elif t1 == 1:
        cropped_seg = seg.split(t0)[1]
    else:
        pt1 = seg.point(t1)

        # trim off the 0 <= t < t0 part
        trimmed_seg = crop_bezier(seg, t0, 1)

        # find the adjusted t1 (i.e. the t1 such that
        # trimmed_seg.point(t1) ~= pt))and trim off the t1 < t <= 1 part
        t1_adj = trimmed_seg.radialrange(pt1)[0][1]
        cropped_seg = crop_bezier(trimmed_seg, 0, t1_adj)
    return cropped_seg
837688
def plane
      # Such a change is only possible if the Slice instance has a Contour with at least three Coordinates:
      raise "This Slice does not contain a Contour. Plane determination is not possible." if @contours.length == 0
      raise "This Slice does not contain a Contour with at least 3 Coordinates. Plane determination is not possible." if @contours.first.coordinates.length < 3
      # Get three coordinates from our Contour:
      contour = @contours.first
      num_coords = contour.coordinates.length
      c1 = contour.coordinates.first
      c2 = contour.coordinates[num_coords / 3]
      c3 = contour.coordinates[2 * num_coords / 3]
      return Plane.calculate(c1, c2, c3)
    end
799144
def cut_edges(image, numPix):
    
    nx, ny = image.shape
    if nx < numPix or ny < numPix:
        print('WARNING: image can not be resized, in routine cut_edges.')
        return image
    if nx % 2 == 0 or ny % 2 == 0 or numPix % 2 == 0:
        #pass
        print("WARNING: image or cutout side are even number. This routine only works for odd numbers %s %s %s"
                         % (nx, ny, numPix))
    cx = int((nx-1)/2)
    cy = int((ny-1)/2)
    d = int((numPix-1)/2)
    if nx % 2 == 0:
        cx += 1
    if ny % 2 == 0:
        cy += 1
    resized = image[cx-d:cx+d+1, cy-d:cy+d+1]
    return copy.deepcopy(resized)
436547
def create_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)
1210025
def slices(img, shape=[3, 4]):
    
    sh = np.asarray(shape)
    i_max = np.prod(sh)
    allimg = np.zeros(img.shape[-2:] * sh)

    for i in range(0, i_max):
        # i = 0
        islice = round((img.shape[0] / float(i_max)) * i)
        #         print(islice)
        imgi = img[islice, :, :]
        coords = index_to_coords(i, sh)
        aic = np.asarray(img.shape[-2:]) * coords

        allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi

    #     plt.imshow(imgi)
    #     print(imgi.shape)
    #     print(img.shape)
    return allimg
1226019
function cutBezier(bezierArray, t) {
        function __(t) {
            return function(p, q) {
                return p + t * (q - p);
            };
        }
        var _ = __(t || 0.5),
            ba = bezierArray,
            ax = ba[0],
            ay = ba[1],
            bx = ba[2],
            by = ba[3],
            cx = ba[4],
            cy = ba[5],
            dx = ba[6],
            dy = ba[7],
            ex = _(ax, bx),
            ey = _(ay, by),
            fx = _(bx, cx),
            fy = _(by, cy),
            gx = _(cx, dx),
            gy = _(cy, dy),
            hx = _(ex, fx),
            hy = _(ey, fy),
            jx = _(fx, gx),
            jy = _(fy, gy),
            kx = _(hx, jx),
            ky = _(hy, jy);
        return [
            [ax, ay, ex, ey, hx, hy, kx, ky],
            [kx, ky, jx, jy, gx, gy, dx, dy]
        ];
    }
1207542
def clipTo(self, bsp):
        
        self.polygons = bsp.clipPolygons(self.polygons)
        if self.front: 
            self.front.clipTo(bsp)
        if self.back: 
            self.back.clipTo(bsp)
683713
def split(self, t):
        """"""
        bpoints1, bpoints2 = split_bezier(self.bpoints(), t)
        return QuadraticBezier(*bpoints1), QuadraticBezier(*bpoints2)