text
stringlengths
1
1.05M
#!/bin/bash ./configure --prefix=$PREFIX --disable-static # First call only the install target as compilation for tests only works with an installed libunwind make install -j${CPU_COUNT} make -j${CPU_COUNT} make check -j${CPU_COUNT}
apm install go-plus apm install teletype
import React, { useState, useEffect } from "react"; import Algorithm from "../lib/algorithm"; export default function Player({ id, track }) { const [loading, setLoading] = useState(true); const [mp3, setMP3] = useState(""); const [error, setError] = useState(0); const host = process.env.NEXT_PUBLIC_API_HOST; const url = `${host}/file/${id}/${track}`; useEffect(() => { if (host == "algorithmia") { setLoading(true); const client = new Algorithm(); client.getFile(id, track).then((response) => { if (response.error) { console.log("Getting file from algo failed"); setLoading(false); setError(response.error); } else { console.log("Getting file from algo OK"); setLoading(false); setMP3(response.result); } }); } else { fetch(url, { method: "HEAD" }).then((response) => { if (response.status == 200) { setLoading(false); } else { setError("File not found"); } }); } }, []); if (error) { return ( <div className="text-sm text-center"> <p>{error}</p> </div> ); } if (loading) { return <div className="text-sm text-center">getting file</div>; } const src = host == "algorithmia" ? `data:audio/mp3;base64,${mp3}` : url; return ( <div> <audio className="w-full" controls> <source src={src} type="audio/mp3" /> </audio> </div> ); }
def capture_image(self): # Capture an image using the specified attributes with picamera.PiCamera() as camera: camera.resolution = self.resolution camera.framerate = self.framerate with picamera.array.PiRGBArray(camera) as stream: camera.capture(stream, format=self.format, use_video_port=self.use_video_port) image = stream.array # Perform any additional processing on the captured image # For example, resizing the image if specified if self.resize: image = cv2.resize(image, self.resize) return image
package resolver import ( "fmt" "github.com/miekg/dns" "github.com/chrisruffalo/gudgeon/util" ) type lbSource struct { name string sources []Source idx int askChan chan bool chosenChan chan Source closeChan chan bool } func newLoadBalancingSource(name string, sources []Source) Source { lb := &lbSource{ name: name, sources: sources, idx: 0, askChan: make(chan bool), chosenChan: make(chan Source), closeChan: make(chan bool), } go lb.router() return lb } func (lb *lbSource) Load(specification string) { // deliberate no-op } func (lb *lbSource) router() { for { select { case <-lb.askChan: lb.chosenChan <- lb.sources[lb.idx] lb.idx = (lb.idx + 1) % len(lb.sources) case <-lb.closeChan: lb.closeChan <- true return } } } func (lb *lbSource) Answer(rCon *RequestContext, context *ResolutionContext, request *dns.Msg) (*dns.Msg, error) { tries := len(lb.sources) for tries >= 0 { lb.askChan <- true source := <-lb.chosenChan response, err := source.Answer(rCon, context, request) if err == nil && !util.IsEmptyResponse(response) { if context != nil { context.SourceUsed = lb.Name() + "(" + source.Name() + ")" } return response, nil } // reduce number of tries tries-- } return nil, fmt.Errorf("Could not answer question in %d tries", len(lb.sources)) } func (lb *lbSource) Name() string { return "lb:" + lb.name } func (lb *lbSource) Close() { lb.closeChan <- true <-lb.closeChan close(lb.askChan) close(lb.chosenChan) for idx := 0; idx < len(lb.sources); idx++ { lb.sources[idx].Close() } }
/* * Copyright 2020-2020 the nameserviceangent team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.bmhm.nameserviceagent.agent.nameservice; import static io.github.bmhm.nameserviceagent.agent.nameservice.ProxyIpv4Helper.GOOGLE_IP; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.github.bmhm.nameserviceagent.api.NameService; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; class DefaultSequentialReachableNameServiceTest { public static final String GOOGLE_COM_DOMAIN = "google.com"; @Test void testPassThroughGetHostByAddr() throws UnknownHostException { // given final NameService original = mock(NameService.class); final DefaultSequentialReachableNameService defaultSequentialReachableNameService = new DefaultSequentialReachableNameService(original); // when defaultSequentialReachableNameService.getHostByAddr(GOOGLE_IP); // then verify(original).getHostByAddr(GOOGLE_IP); } @Test void testTryReachable() throws IOException { // given final NameService original = mock(NameService.class); final DefaultSequentialReachableNameService defaultSequentialReachableNameService = new DefaultSequentialReachableNameService(original); final InetAddress fakeInetAddress = ProxyIpv4Helper.proxyGoogleIpv4(); // when when(original.lookupAllHostAddr(GOOGLE_COM_DOMAIN)).then(args -> new InetAddress[] {fakeInetAddress}); final InetAddress[] inetAddresses = defaultSequentialReachableNameService.lookupAllHostAddr(GOOGLE_COM_DOMAIN); // then assertTrue(inetAddresses.length == 1); verify(original).lookupAllHostAddr(GOOGLE_COM_DOMAIN); verify(fakeInetAddress).isReachable(anyInt()); } }
<gh_stars>1-10 #ifndef TRAJ_UTILS_HPP #define TRAJ_UTILS_HPP #include "root_finder.hpp" #include <vector> #include <list> #include <Eigen/Eigen> // Polynomial order and trajectory dimension are fixed here constexpr int TrajOrder = 5; constexpr int TrajDim = 3; // Type for piece boundary condition and coefficient matrix typedef Eigen::Matrix<double, TrajDim, TrajOrder + 1> BoundaryCond; typedef Eigen::Matrix<double, TrajDim, TrajOrder + 1> CoefficientMat; typedef Eigen::Matrix<double, TrajDim, TrajOrder> VelCoefficientMat; typedef Eigen::Matrix<double, TrajDim, TrajOrder - 1> AccCoefficientMat; typedef Eigen::Matrix<double, TrajDim, TrajOrder - 2> JerkCoefficientMat; typedef Eigen::Matrix<double, 6, 1> StatePV; typedef Eigen::Matrix<double, 9, 1> StatePVA; typedef Eigen::Matrix<double, 10, 1> StatePVAM; typedef Eigen::Matrix<double, TrajDim, 1> ControlJrk; typedef Eigen::Matrix<double, TrajDim, 1> ControlAcc; // A single piece of a trajectory, which is indeed a polynomial class Piece { private: // Piece(t) = c5*t^5 + c4*t^4 + ... + c1*t + c0 // The natural coefficient matrix = [c5,c4,c3,c2,c1,c0] double duration; // Any time in [0, T] is normalized into [0.0, 1.0] // Therefore, nCoeffMat = [c5*T^5,c4*T^4,c3*T^3,c2*T^2,c1*T,c0*1] // is used for better numerical stability CoefficientMat nCoeffMat; public: Piece() = default; // Constructor from duration and coefficient Piece(double dur, const CoefficientMat &coeffs) : duration(dur) { double t = 1.0; for (int i = TrajOrder; i >= 0; i--) { nCoeffMat.col(i) = coeffs.col(i) * t; t *= dur; } } // Constructor from boundary condition and duration Piece(const BoundaryCond &boundCond, double dur) : duration(dur) { // The BoundaryCond matrix boundCond = [p(0),v(0),a(0),p(T),v(T),a(T)] double t1 = dur; double t2 = t1 * t1; // Inverse mapping is computed without explicit matrix inverse // It maps boundary condition to normalized coefficient matrix nCoeffMat.col(0) = 0.5 * (boundCond.col(5) - boundCond.col(2)) * t2 - 3.0 * (boundCond.col(1) + boundCond.col(4)) * t1 + 6.0 * (boundCond.col(3) - boundCond.col(0)); nCoeffMat.col(1) = (-boundCond.col(5) + 1.5 * boundCond.col(2)) * t2 + (8.0 * boundCond.col(1) + 7.0 * boundCond.col(4)) * t1 + 15.0 * (-boundCond.col(3) + boundCond.col(0)); nCoeffMat.col(2) = (0.5 * boundCond.col(5) - 1.5 * boundCond.col(2)) * t2 - (6.0 * boundCond.col(1) + 4.0 * boundCond.col(4)) * t1 + 10.0 * (boundCond.col(3) - boundCond.col(0)); nCoeffMat.col(3) = 0.5 * boundCond.col(2) * t2; nCoeffMat.col(4) = boundCond.col(1) * t1; nCoeffMat.col(5) = boundCond.col(0); } inline int getDim() const { return TrajDim; } inline int getOrder() const { return TrajOrder; } inline double getDuration() const { return duration; } // Get the position at time t in this piece inline Eigen::Vector3d getPos(double t) const { // Normalize the time t /= duration; Eigen::Vector3d pos(0.0, 0.0, 0.0); double tn = 1.0; for (int i = TrajOrder; i >= 0; i--) { pos += tn * nCoeffMat.col(i); tn *= t; } // The pos is not affected by normalization return pos; } // Get the velocity at time t in this piece inline Eigen::Vector3d getVel(double t) const { // Normalize the time t /= duration; Eigen::Vector3d vel(0.0, 0.0, 0.0); double tn = 1.0; int n = 1; for (int i = TrajOrder - 1; i >= 0; i--) { vel += n * tn * nCoeffMat.col(i); tn *= t; n++; } // Recover the actual vel vel /= duration; return vel; } // Get the acceleration at time t in this piece inline Eigen::Vector3d getAcc(double t) const { // Normalize the time t /= duration; Eigen::Vector3d acc(0.0, 0.0, 0.0); double tn = 1.0; int m = 1; int n = 2; for (int i = TrajOrder - 2; i >= 0; i--) { acc += m * n * tn * nCoeffMat.col(i); tn *= t; m++; n++; } // Recover the actual acc acc /= duration * duration; return acc; } // Get the jerk at time t in this piece inline Eigen::Vector3d getJerk(double t) const { // Normalize the time t /= duration; Eigen::Vector3d jerk(0.0, 0.0, 0.0); double tn = 1.0; int m = 1; int n = 2; int k = 3; for (int i = TrajOrder - 3; i >= 0; i--) { jerk += k * m * n * tn * nCoeffMat.col(i); tn *= t; k++; m++; n++; } // Recover the actual acc jerk /= duration * duration * duration; return jerk; } // Get the boundary condition of this piece inline BoundaryCond getBoundCond() const { BoundaryCond boundCond; boundCond << getPos(0.0), getVel(0.0), getAcc(0.0), getPos(duration), getVel(duration), getAcc(duration); return boundCond; } // Get the coefficient matrix of the piece // Default arg chooses the natural coefficients // If normalized version is needed, set the arg true inline CoefficientMat getCoeffMat(bool normalized = false) const { CoefficientMat posCoeffsMat; double t = 1; for (int i = TrajOrder; i >= 0; i--) { posCoeffsMat.col(i) = nCoeffMat.col(i) / t; t *= normalized ? 1.0 : duration; } return posCoeffsMat; } // Get the polynomial coefficients of velocity of this piece // Default arg chooses the natural coefficients // If normalized version is needed, set the arg true inline VelCoefficientMat getVelCoeffMat(bool normalized = false) const { VelCoefficientMat velCoeffMat; int n = 1; double t = 1.0; t *= normalized ? 1.0 : duration; for (int i = TrajOrder - 1; i >= 0; i--) { velCoeffMat.col(i) = n * nCoeffMat.col(i) / t; n++; t *= normalized ? 1.0 : duration; } return velCoeffMat; } // Get the polynomial coefficients of acceleration of this piece // Default arg chooses the natural coefficients // If normalized version is needed, set the arg true inline AccCoefficientMat getAccCoeffMat(bool normalized = false) const { AccCoefficientMat accCoeffMat; int n = 2; int m = 1; double t = 1.0; t *= normalized ? 1.0 : duration * duration; for (int i = TrajOrder - 2; i >= 0; i--) { accCoeffMat.col(i) = n * m * nCoeffMat.col(i) / t; n++; m++; t *= normalized ? 1.0 : duration; } return accCoeffMat; } // Get the polynomial coefficients of jerk of this piece // Default arg chooses the natural coefficients // If normalized version is needed, set the arg true inline JerkCoefficientMat getJerkCoeffMat(bool normalized = false) const { JerkCoefficientMat jerkCoeffMat; int n = 3; int m = 2; int l = 1; double t = 1.0; t *= normalized ? 1.0 : duration * duration * duration; for (int i = TrajOrder - 3; i >= 0; i--) { jerkCoeffMat.col(i) = n * m * l * nCoeffMat.col(i) / t; n++; m++; l++; t *= normalized ? 1.0 : duration; } return jerkCoeffMat; } // Get the max velocity rate of the piece inline double getMaxVelRate() const { // Compute normalized squared vel norm polynomial coefficient matrix Eigen::MatrixXd nVelCoeffMat = getVelCoeffMat(true); Eigen::VectorXd coeff = RootFinder::polySqr(nVelCoeffMat.row(0)) + RootFinder::polySqr(nVelCoeffMat.row(1)) + RootFinder::polySqr(nVelCoeffMat.row(2)); int N = coeff.size(); int n = N - 1; for (int i = 0; i < N; i++) { coeff(i) *= n; n--; } if (coeff.head(N - 1).squaredNorm() < DBL_EPSILON) { return 0.0; } else { // Search an open interval whose boundaries are not zeros double l = -0.0625; double r = 1.0625; while (fabs(RootFinder::polyVal(coeff.head(N - 1), l)) < DBL_EPSILON) { l = 0.5 * l; } while (fabs(RootFinder::polyVal(coeff.head(N - 1), r)) < DBL_EPSILON) { r = 0.5 * (r + 1.0); } // Find all stationaries std::set<double> candidates = RootFinder::solvePolynomial(coeff.head(N - 1), l, r, FLT_EPSILON / duration); // Check boundary points and stationaries within duration candidates.insert(0.0); candidates.insert(1.0); double maxVelRateSqr = -INFINITY; double tempNormSqr; for (std::set<double>::const_iterator it = candidates.begin(); it != candidates.end(); it++) { if (0.0 <= *it && 1.0 >= *it) { // Recover the actual time then get the vel squared norm tempNormSqr = getVel((*it) * duration).squaredNorm(); maxVelRateSqr = maxVelRateSqr < tempNormSqr ? tempNormSqr : maxVelRateSqr; } } return sqrt(maxVelRateSqr); } } // Get the max acceleration rate of the piece inline double getMaxAccRate() const { // Compute normalized squared acc norm polynomial coefficient matrix Eigen::MatrixXd nAccCoeffMat = getAccCoeffMat(true); Eigen::VectorXd coeff = RootFinder::polySqr(nAccCoeffMat.row(0)) + RootFinder::polySqr(nAccCoeffMat.row(1)) + RootFinder::polySqr(nAccCoeffMat.row(2)); int N = coeff.size(); int n = N - 1; for (int i = 0; i < N; i++) { coeff(i) *= n; n--; } if (coeff.head(N - 1).squaredNorm() < DBL_EPSILON) { return 0.0; } else { // Search an open interval whose boundaries are not zeros double l = -0.0625; double r = 1.0625; while (fabs(RootFinder::polyVal(coeff.head(N - 1), l)) < DBL_EPSILON) { l = 0.5 * l; } while (fabs(RootFinder::polyVal(coeff.head(N - 1), r)) < DBL_EPSILON) { r = 0.5 * (r + 1.0); } // Find all stationaries std::set<double> candidates = RootFinder::solvePolynomial(coeff.head(N - 1), l, r, FLT_EPSILON / duration); // Check boundary points and stationaries within duration candidates.insert(0.0); candidates.insert(1.0); double maxAccRateSqr = -INFINITY; double tempNormSqr; for (std::set<double>::const_iterator it = candidates.begin(); it != candidates.end(); it++) { if (0.0 <= *it && 1.0 >= *it) { // Recover the actual time then get the acc squared norm tempNormSqr = getAcc((*it) * duration).squaredNorm(); maxAccRateSqr = maxAccRateSqr < tempNormSqr ? tempNormSqr : maxAccRateSqr; } } return sqrt(maxAccRateSqr); } } inline double getMaxJerkRate() const { // Compute normalized squared jerk norm polynomial coefficient matrix Eigen::MatrixXd nJerkCoeffMat = getJerkCoeffMat(true); Eigen::VectorXd coeff = RootFinder::polySqr(nJerkCoeffMat.row(0)) + RootFinder::polySqr(nJerkCoeffMat.row(1)) + RootFinder::polySqr(nJerkCoeffMat.row(2)); int N = coeff.size(); int n = N - 1; for (int i = 0; i < N; i++) { coeff(i) *= n; n--; } if (coeff.head(N - 1).squaredNorm() < DBL_EPSILON) { return 0.0; } else { // Search an open interval whose boundaries are not zeros double l = -0.0625; double r = 1.0625; while (fabs(RootFinder::polyVal(coeff.head(N - 1), l)) < DBL_EPSILON) { l = 0.5 * l; } while (fabs(RootFinder::polyVal(coeff.head(N - 1), r)) < DBL_EPSILON) { r = 0.5 * (r + 1.0); } // Find all stationaries std::set<double> candidates = RootFinder::solvePolynomial(coeff.head(N - 1), l, r, FLT_EPSILON / duration); // Check boundary points and stationaries within duration candidates.insert(0.0); candidates.insert(1.0); double maxJerkRateSqr = -INFINITY; double tempNormSqr; for (std::set<double>::const_iterator it = candidates.begin(); it != candidates.end(); it++) { if (0.0 <= *it && 1.0 >= *it) { // Recover the actual time then get the acc squared norm tempNormSqr = getJerk((*it) * duration).squaredNorm(); maxJerkRateSqr = maxJerkRateSqr < tempNormSqr ? tempNormSqr : maxJerkRateSqr; } } return sqrt(maxJerkRateSqr); } } // Check whether velocity rate of the piece is always less than maxVelRate inline bool checkMaxVelRate(double maxVelRate) const { double sqrMaxVelRate = maxVelRate * maxVelRate; if (getVel(0.0).squaredNorm() >= sqrMaxVelRate || getVel(duration).squaredNorm() >= sqrMaxVelRate) { return false; } else { Eigen::MatrixXd nVelCoeffMat = getVelCoeffMat(true); Eigen::VectorXd coeff = RootFinder::polySqr(nVelCoeffMat.row(0)) + RootFinder::polySqr(nVelCoeffMat.row(1)) + RootFinder::polySqr(nVelCoeffMat.row(2)); // Convert the actual squared maxVelRate to a normalized one double t2 = duration * duration; coeff.tail<1>()(0) -= sqrMaxVelRate * t2; // Directly check the root existence in the normalized interval return RootFinder::countRoots(coeff, 0.0, 1.0) == 0; } } // Check whether accleration rate of the piece is always less than maxAccRate inline bool checkMaxAccRate(double maxAccRate) const { double sqrMaxAccRate = maxAccRate * maxAccRate; if (getAcc(0.0).squaredNorm() >= sqrMaxAccRate || getAcc(duration).squaredNorm() >= sqrMaxAccRate) { return false; } else { Eigen::MatrixXd nAccCoeffMat = getAccCoeffMat(true); Eigen::VectorXd coeff = RootFinder::polySqr(nAccCoeffMat.row(0)) + RootFinder::polySqr(nAccCoeffMat.row(1)) + RootFinder::polySqr(nAccCoeffMat.row(2)); // Convert the actual squared maxAccRate to a normalized one double t2 = duration * duration; double t4 = t2 * t2; coeff.tail<1>()(0) -= sqrMaxAccRate * t4; // Directly check the root existence in the normalized interval return RootFinder::countRoots(coeff, 0.0, 1.0) == 0; } } // Check whether jerk rate of the piece is always less than maxJerkRate inline bool checkMaxJerkRate(double maxJerkRate) const { double sqrMaxJerkRate = maxJerkRate * maxJerkRate; if (getJerk(0.0).squaredNorm() >= sqrMaxJerkRate || getJerk(duration).squaredNorm() >= sqrMaxJerkRate) { return false; } else { Eigen::MatrixXd nJerkCoeffMat = getJerkCoeffMat(true); Eigen::VectorXd coeff = RootFinder::polySqr(nJerkCoeffMat.row(0)) + RootFinder::polySqr(nJerkCoeffMat.row(1)) + RootFinder::polySqr(nJerkCoeffMat.row(2)); // Convert the actual squared maxJerkRate to a normalized one double t2 = duration * duration; double t4 = t2 * t2; double t6 = t4 * t2; coeff.tail<1>()(0) -= sqrMaxJerkRate * t6; // Directly check the root existence in the normalized interval return RootFinder::countRoots(coeff, 0.0, 1.0) == 0; } } //Scale the Piece(t) to Piece(k*t) inline void scaleTime(double k) { duration /= k; return; } inline void sampleOneSeg(std::vector< StatePVA >* vis_x) const { double dt = 0.005; for (double t = 0.0; t < duration; t += dt) { Eigen::Vector3d pos, vel, acc; pos = getPos(t); vel = getVel(t); acc = getAcc(t); StatePVA x; x << pos(0), pos(1), pos(2), vel(0), vel(1), vel(2), acc(0), acc(1), acc(2); vis_x->push_back(x); } } inline void sampleOneSeg(std::vector< StatePVAM >* vis_x, double sample_t, double ground_judge) const { double dt = sample_t; for (double t = 0.0; t < duration; t += dt) { Eigen::Vector3d pos, vel, acc; pos = getPos(t); vel = getVel(t); acc = getAcc(t); int motion_state = 0; if(pos[2] >= ground_judge) motion_state = 1; StatePVAM x; x << pos(0), pos(1), pos(2), vel(0), vel(1), vel(2), acc(0), acc(1), acc(2), motion_state; vis_x->push_back(x); } } // for 5th degree polynomial inline void cutPiece(const Piece &orig_piece, double ts, CoefficientMat &new_coeff) const { CoefficientMat ori_coeff = orig_piece.getCoeffMat(); double ts2 = ts * ts; double ts3 = ts2 * ts; double ts4 = ts3 * ts; double ts5 = ts4 * ts; for (int dim = 0; dim < 3; ++dim) { new_coeff(dim, 0) = ori_coeff(dim, 0); //c5*t^5 new_coeff(dim, 1) = ori_coeff(dim, 1) + 5*ori_coeff(dim, 0)*ts; //c4*4^4 new_coeff(dim, 2) = ori_coeff(dim, 2) + 4*ori_coeff(dim, 1)*ts + 10*ori_coeff(dim, 0)*ts2; new_coeff(dim, 3) = ori_coeff(dim, 3) + 3*ori_coeff(dim, 2)*ts + 6*ori_coeff(dim, 1)*ts2 + 10*ori_coeff(dim, 0)*ts3; new_coeff(dim, 4) = ori_coeff(dim, 4) + 2*ori_coeff(dim, 3)*ts + 3*ori_coeff(dim, 2)*ts2 + 4*ori_coeff(dim, 1)*ts3 + 5*ori_coeff(dim, 0)*ts4; new_coeff(dim, 5) = ori_coeff(dim, 5) + ori_coeff(dim, 4)*ts + ori_coeff(dim, 3)*ts2 + ori_coeff(dim, 2)*ts3 + ori_coeff(dim, 1)*ts4 + ori_coeff(dim, 0)*ts5; } } // for 5th degree polynomial, cost = integral(j^T rho j) + tau inline double calCost(const double &rho) const { double tau2 = duration * duration; double tau3 = tau2 * duration; double tau4 = tau3 * duration; double tau5 = tau4 * duration; CoefficientMat coeff = getCoeffMat(); Eigen::Matrix<double, 6, 6> B = Eigen::Matrix<double, 6, 6>::Zero(6, 6); B(0, 0) = 720 * tau5; B(1, 1) = 192 * tau3; B(2, 2) = 36 * duration; B(0, 1) = B(1, 0) = 360 * tau4; B(0, 2) = B(2, 0) = 120 * tau3; B(1, 2) = B(2, 1) = 72 * tau2; double cost(0.0); for (int i=0; i<3; i++) { cost += coeff.row(i) * B * coeff.row(i).transpose(); } cost *= rho; cost += duration; return cost; } inline double project_pt(const Eigen::Vector3d &pt, double &tt, Eigen::Vector3d &pro_pt) { // 2*(p-p0)^T * \dot{p} = 0 auto l_coeff = getCoeffMat(); l_coeff.col(5) = l_coeff.col(5) - pt; auto r_coeff = getVelCoeffMat(); Eigen::VectorXd eq = Eigen::VectorXd::Zero(2 * 5); for (int j = 0; j < l_coeff.rows(); ++j) { eq = eq + RootFinder::polyConv(l_coeff.row(j), r_coeff.row(j)); } double l = -0.0625; double r = duration + 0.0625; while (fabs(RootFinder::polyVal(eq, l)) < DBL_EPSILON) { l = 0.5 * l; } while (fabs(RootFinder::polyVal(eq, r)) < DBL_EPSILON) { r = 0.5 * (duration + r); } std::set<double> roots = RootFinder::solvePolynomial(eq, l, r, 1e-6); // std::cout << "# roots: " << roots.size() << std::endl; double min_dist = -1; for (const auto &root : roots) { // std::cout << "root: " << root << std::endl; if (root < 0 || root > duration) { continue; } if (getVel(root).norm() < 1e-6) { // velocity == 0, ignore it continue; } // std::cout << "find min!" << std::endl; Eigen::Vector3d p = getPos(root); // std::cout << "p: " << p.transpose() << std::endl; double distance = (p - pt).norm(); if (distance < min_dist || min_dist < 0) { min_dist = distance; tt = root; pro_pt = p; } } return min_dist; } inline bool intersection_plane(const Eigen::Vector3d p, const Eigen::Vector3d v, double &tt, Eigen::Vector3d &pt) const { // (pt - p)^T * v = 0 auto coeff = getCoeffMat(); coeff.col(5) = coeff.col(5) - p; Eigen::VectorXd eq = coeff.transpose() * v; double l = -0.0625; double r = duration + 0.0625; while (fabs(RootFinder::polyVal(eq, l)) < DBL_EPSILON) { l = 0.5 * l; } while (fabs(RootFinder::polyVal(eq, r)) < DBL_EPSILON) { r = 0.5 * (duration + r); } std::set<double> roots = RootFinder::solvePolynomial(eq, l, r, 1e-6); for (const auto &root : roots) { tt = root; pt = getPos(root); return true; } return false; } }; // A whole trajectory which contains multiple pieces class Trajectory { private: typedef std::vector<Piece> Pieces; Pieces pieces; public: Trajectory() = default; // Constructor from durations and coefficient matrices Trajectory(const std::vector<double> &durs, const std::vector<CoefficientMat> &coeffMats) { int N = std::min(durs.size(), coeffMats.size()); pieces.reserve(N); for (int i = 0; i < N; i++) { pieces.emplace_back(durs[i], coeffMats[i]); } } inline int getPieceNum() const { return pieces.size(); } // Get durations vector of all pieces inline std::vector<double> getDurations() const { std::vector<double> durations; durations.reserve(getPieceNum()); for (int i = 0; i < getPieceNum(); i++) { durations.push_back(pieces[i].getDuration()); } return durations; } // Get total duration of the trajectory inline double getTotalDuration() const { double totalDuration = 0.0; for (int i = 0; i < getPieceNum(); i++) { totalDuration += pieces[i].getDuration(); } return totalDuration; } // Reload the operator[] to reach the i-th piece inline const Piece &operator[](int i) const { return pieces[i]; } inline Piece &operator[](int i) { return pieces[i]; } inline void clear(void) { pieces.clear(); } inline Pieces::const_iterator begin() const { return pieces.begin(); } inline Pieces::const_iterator end() const { return pieces.end(); } inline void reserve(const int &n) { pieces.reserve(n); return; } // Put another piece at the tail of this trajectory inline void emplace_back(const Piece &piece) { pieces.emplace_back(piece); return; } // Two corresponding constructors of Piece both are supported here template <typename ArgTypeL, typename ArgTypeR> inline void emplace_back(const ArgTypeL &argL, const ArgTypeR &argR) { pieces.emplace_back(argL, argR); return; } // Append another Trajectory at the tail of this trajectory inline void append(const Trajectory &traj) { pieces.insert(pieces.end(), traj.begin(), traj.end()); return; } // Find the piece at which the time t is located // The index is returned and the offset in t is removed inline int locatePieceIdx(double &t) const { int idx; double dur; for (idx = 0; idx < getPieceNum() && t > (dur = pieces[idx].getDuration()); idx++) { t -= dur; } if (idx == getPieceNum()) { idx--; t += pieces[idx].getDuration(); } return idx; } // Get the position at time t of the trajectory inline Eigen::Vector3d getPos(double t) const { int pieceIdx = locatePieceIdx(t); return pieces[pieceIdx].getPos(t); } // Get the velocity at time t of the trajectory inline Eigen::Vector3d getVel(double t) const { int pieceIdx = locatePieceIdx(t); return pieces[pieceIdx].getVel(t); } // Get the acceleration at time t of the trajectory inline Eigen::Vector3d getAcc(double t) const { int pieceIdx = locatePieceIdx(t); return pieces[pieceIdx].getAcc(t); } // Get the position at the juncIdx-th waypoint inline Eigen::Vector3d getJuncPos(int juncIdx) const { if (juncIdx != getPieceNum()) { return pieces[juncIdx].getPos(0.0); } else { return pieces[juncIdx - 1].getPos(pieces[juncIdx - 1].getDuration()); } } // Get the velocity at the juncIdx-th waypoint inline Eigen::Vector3d getJuncVel(int juncIdx) const { if (juncIdx != getPieceNum()) { return pieces[juncIdx].getVel(0.0); } else { return pieces[juncIdx - 1].getVel(pieces[juncIdx - 1].getDuration()); } } // Get the acceleration at the juncIdx-th waypoint inline Eigen::Vector3d getJuncAcc(int juncIdx) const { if (juncIdx != getPieceNum()) { return pieces[juncIdx].getAcc(0.0); } else { return pieces[juncIdx - 1].getAcc(pieces[juncIdx - 1].getDuration()); } } // Get the max velocity rate of the trajectory inline double getMaxVelRate() const { double maxVelRate = -INFINITY; double tempNorm; for (int i = 0; i < getPieceNum(); i++) { tempNorm = pieces[i].getMaxVelRate(); maxVelRate = maxVelRate < tempNorm ? tempNorm : maxVelRate; } return maxVelRate; } // Get the max acceleration rate of the trajectory inline double getMaxAccRate() const { double maxAccRate = -INFINITY; double tempNorm; for (int i = 0; i < getPieceNum(); i++) { tempNorm = pieces[i].getMaxAccRate(); maxAccRate = maxAccRate < tempNorm ? tempNorm : maxAccRate; } return maxAccRate; } // Get the max jerk rate of the trajectory inline double getMaxJerkRate() const { double maxJerkRate = -INFINITY; double tempNorm; for (int i = 0; i < getPieceNum(); i++) { tempNorm = pieces[i].getMaxJerkRate(); maxJerkRate = maxJerkRate < tempNorm ? tempNorm : maxJerkRate; } return maxJerkRate; } // Check whether the velocity rate of this trajectory exceeds the threshold inline bool checkMaxVelRate(double maxVelRate) const { bool feasible = true; for (int i = 0; i < getPieceNum() && feasible; i++) { feasible = feasible && pieces[i].checkMaxVelRate(maxVelRate); } return feasible; } // Check whether the acceleration rate of this trajectory exceeds the threshold inline bool checkMaxAccRate(double maxAccRate) const { bool feasible = true; for (int i = 0; i < getPieceNum() && feasible; i++) { feasible = feasible && pieces[i].checkMaxAccRate(maxAccRate); } return feasible; } // Check whether the jerk rate of this trajectory exceeds the threshold inline bool checkMaxJerkRate(double maxJerkRate) const { bool feasible = true; for (int i = 0; i < getPieceNum() && feasible; i++) { feasible = feasible && pieces[i].checkMaxJerkRate(maxJerkRate); } return feasible; } // Scale the Trajectory(t) to Trajectory(k*t) inline void scaleTime(double k) { for (int i = 0; i < getPieceNum(); i++) { pieces[i].scaleTime(k); } } inline void sampleWholeTrajectory(std::vector< StatePVA >* vis_x) const { int n = getPieceNum(); for (int i = 0; i < n; ++i) { pieces[i].sampleOneSeg(vis_x); } } inline double calCost(const double &rho, double* seg_cost) const { double cost(0.0); for (int i = 0; i < getPieceNum(); i++) { seg_cost[i] = pieces[i].calCost(rho); cost += seg_cost[i]; } return cost; } inline void sampleWholeTrajectoryForOptimization(std::vector< StatePVAM >* vis_x, double sample_t, double ground_judge) const { int n = getPieceNum(); for (int i = 0; i < n; ++i) { pieces[i].sampleOneSeg(vis_x, sample_t, ground_judge); } } inline void getWpts(std::vector< StatePVA >* wpts) { Eigen::Vector3d pos, vel, acc; StatePVA x; pos = pieces[0].getPos(0); vel = pieces[0].getVel(0); acc = pieces[0].getAcc(0); x << pos(0), pos(1), pos(2), vel(0), vel(1), vel(2), acc(0), acc(1), acc(2); wpts->push_back(x); int n = getPieceNum(); for (int i = 0; i < n; ++i) { double t = pieces[i].getDuration(); pos = pieces[i].getPos(t); vel = pieces[i].getVel(t); acc = pieces[i].getAcc(t); x << pos(0), pos(1), pos(2), vel(0), vel(1), vel(2), acc(0), acc(1), acc(2); wpts->push_back(x); } } inline const Piece& getPiece(int i) const { return pieces[i]; } inline double project_pt(const Eigen::Vector3d &pt, int &ii, double &tt, Eigen::Vector3d &pro_pt) { double dist = -1; for (int i=0; i<getPieceNum(); ++i) { auto piece = pieces[i]; dist = piece.project_pt(pt, tt, pro_pt); if (dist > 0) { ii = i; break; } } // if (dist < 0) { // std::cout << "\033[32m" << "cannot project pt to traj" << "\033[0m" << std::endl; // // std::cout << "pt: " << pt.transpose() << std::endl; // // assert(false); // } return dist; } inline bool intersection_plane(const Eigen::Vector3d p, const Eigen::Vector3d v, int &ii, double &tt, Eigen::Vector3d &pt) { for (int i=0; i<getPieceNum(); ++i) { const auto& piece = pieces[i]; if ( piece.intersection_plane(p,v,tt,pt) ) { ii = i; return true; } } return false; } inline double evaluateTrajJerk() const { double objective = 0.0; int M = getPieceNum(); CoefficientMat cMat; double t1, t2, t3, t4, t5; for (int i = 0; i < M; i++) { cMat = operator[](i).getCoeffMat(); t1 = operator[](i).getDuration(); t2 = t1 * t1; t3 = t2 * t1; t4 = t2 * t2; t5 = t2 * t3; objective += 36.0 * cMat.col(2).squaredNorm() * t1 + 144.0 * cMat.col(1).dot(cMat.col(2)) * t2 + 192.0 * cMat.col(1).squaredNorm() * t3 + 240.0 * cMat.col(0).dot(cMat.col(2)) * t3 + 720.0 * cMat.col(0).dot(cMat.col(1)) * t4 + 720.0 * cMat.col(0).squaredNorm() * t5; } return objective; } }; // The banded system class is used for solving // banded linear system Ax=b efficiently. // A is an N*N band matrix with lower band width lowerBw // and upper band width upperBw. // Banded LU factorization has O(N) time complexity. class BandedSystem { public: // The size of A, as well as the lower/upper // banded width p/q are needed inline void create(const int &n, const int &p, const int &q) { // In case of re-creating before destroying destroy(); N = n; lowerBw = p; upperBw = q; int actualSize = N * (lowerBw + upperBw + 1); ptrData = new double[actualSize]; std::fill_n(ptrData, actualSize, 0.0); return; } inline void destroy() { if (ptrData != nullptr) { delete[] ptrData; ptrData = nullptr; } return; } private: int N; int lowerBw; int upperBw; // Compulsory nullptr initialization here double *ptrData = nullptr; public: // Reset the matrix to zero inline void reset(void) { std::fill_n(ptrData, N * (lowerBw + upperBw + 1), 0.0); return; } // The band matrix is stored as suggested in "Matrix Computation" inline const double &operator()(const int &i, const int &j) const { return ptrData[(i - j + upperBw) * N + j]; } inline double &operator()(const int &i, const int &j) { return ptrData[(i - j + upperBw) * N + j]; } // This function conducts banded LU factorization in place // Note that NO PIVOT is applied on the matrix "A" for efficiency!!! inline void factorizeLU() { int iM, jM; double cVl; for (int k = 0; k <= N - 2; k++) { iM = std::min(k + lowerBw, N - 1); cVl = operator()(k, k); for (int i = k + 1; i <= iM; i++) { if (operator()(i, k) != 0.0) { operator()(i, k) /= cVl; } } jM = std::min(k + upperBw, N - 1); for (int j = k + 1; j <= jM; j++) { cVl = operator()(k, j); if (cVl != 0.0) { for (int i = k + 1; i <= iM; i++) { if (operator()(i, k) != 0.0) { operator()(i, j) -= operator()(i, k) * cVl; } } } } } return; } // This function solves Ax=b, then stores x in b // The input b is required to be N*m, i.e., // m vectors to be solved. inline void solve(Eigen::MatrixXd &b) const { int iM; for (int j = 0; j <= N - 1; j++) { iM = std::min(j + lowerBw, N - 1); for (int i = j + 1; i <= iM; i++) { if (operator()(i, j) != 0.0) { b.row(i) -= operator()(i, j) * b.row(j); } } } for (int j = N - 1; j >= 0; j--) { b.row(j) /= operator()(j, j); iM = std::max(0, j - upperBw); for (int i = iM; i <= j - 1; i++) { if (operator()(i, j) != 0.0) { b.row(i) -= operator()(i, j) * b.row(j); } } } return; } // This function solves ATx=b, then stores x in b // The input b is required to be N*m, i.e., // m vectors to be solved. inline void solveAdj(Eigen::MatrixXd &b) const { int iM; for (int j = 0; j <= N - 1; j++) { b.row(j) /= operator()(j, j); iM = std::min(j + upperBw, N - 1); for (int i = j + 1; i <= iM; i++) { if (operator()(j, i) != 0.0) { b.row(i) -= operator()(j, i) * b.row(j); } } } for (int j = N - 1; j >= 0; j--) { iM = std::max(0, j - lowerBw); for (int i = iM; i <= j - 1; i++) { if (operator()(j, i) != 0.0) { b.row(i) -= operator()(j, i) * b.row(j); } } } return; } }; class MinJerkOpt { public: MinJerkOpt() = default; ~MinJerkOpt() { A.destroy(); } private: int N; Eigen::Matrix3d headPVA; Eigen::Matrix3d tailPVA; Eigen::VectorXd T1; BandedSystem A; Eigen::MatrixXd b; // Temp variables Eigen::VectorXd T2; Eigen::VectorXd T3; Eigen::VectorXd T4; Eigen::VectorXd T5; Eigen::MatrixXd gdC; private: template <typename EIGENVEC> inline void addGradJbyT(EIGENVEC &gdT) const { for (int i = 0; i < N; i++) { gdT(i) += 36.0 * b.row(6 * i + 3).squaredNorm() + 288.0 * b.row(6 * i + 4).dot(b.row(6 * i + 3)) * T1(i) + 576.0 * b.row(6 * i + 4).squaredNorm() * T2(i) + 720.0 * b.row(6 * i + 5).dot(b.row(6 * i + 3)) * T2(i) + 2880.0 * b.row(6 * i + 5).dot(b.row(6 * i + 4)) * T3(i) + 3600.0 * b.row(6 * i + 5).squaredNorm() * T4(i); } return; } template <typename EIGENMAT> inline void addGradJbyC(EIGENMAT &gdC) const { for (int i = 0; i < N; i++) { gdC.row(6 * i + 5) += 240.0 * b.row(6 * i + 3) * T3(i) + 720.0 * b.row(6 * i + 4) * T4(i) + 1440.0 * b.row(6 * i + 5) * T5(i); gdC.row(6 * i + 4) += 144.0 * b.row(6 * i + 3) * T2(i) + 384.0 * b.row(6 * i + 4) * T3(i) + 720.0 * b.row(6 * i + 5) * T4(i); gdC.row(6 * i + 3) += 72.0 * b.row(6 * i + 3) * T1(i) + 144.0 * b.row(6 * i + 4) * T2(i) + 240.0 * b.row(6 * i + 5) * T3(i); } return; } inline void solveAdjGradC(Eigen::MatrixXd &gdC) const { A.solveAdj(gdC); return; } template <typename EIGENVEC> inline void addPropCtoT(const Eigen::MatrixXd &adjGdC, EIGENVEC &gdT) const { Eigen::MatrixXd B1(6, 3), B2(3, 3); Eigen::RowVector3d negVel, negAcc, negJer, negSnp, negCrk; for (int i = 0; i < N - 1; i++) { negVel = -(b.row(i * 6 + 1) + 2.0 * T1(i) * b.row(i * 6 + 2) + 3.0 * T2(i) * b.row(i * 6 + 3) + 4.0 * T3(i) * b.row(i * 6 + 4) + 5.0 * T4(i) * b.row(i * 6 + 5)); negAcc = -(2.0 * b.row(i * 6 + 2) + 6.0 * T1(i) * b.row(i * 6 + 3) + 12.0 * T2(i) * b.row(i * 6 + 4) + 20.0 * T3(i) * b.row(i * 6 + 5)); negJer = -(6.0 * b.row(i * 6 + 3) + 24.0 * T1(i) * b.row(i * 6 + 4) + 60.0 * T2(i) * b.row(i * 6 + 5)); negSnp = -(24.0 * b.row(i * 6 + 4) + 120.0 * T1(i) * b.row(i * 6 + 5)); negCrk = -120.0 * b.row(i * 6 + 5); B1 << negSnp, negCrk, negVel, negVel, negAcc, negJer; gdT(i) += B1.cwiseProduct(adjGdC.block<6, 3>(6 * i + 3, 0)).sum(); } negVel = -(b.row(6 * N - 5) + 2.0 * T1(N - 1) * b.row(6 * N - 4) + 3.0 * T2(N - 1) * b.row(6 * N - 3) + 4.0 * T3(N - 1) * b.row(6 * N - 2) + 5.0 * T4(N - 1) * b.row(6 * N - 1)); negAcc = -(2.0 * b.row(6 * N - 4) + 6.0 * T1(N - 1) * b.row(6 * N - 3) + 12.0 * T2(N - 1) * b.row(6 * N - 2) + 20.0 * T3(N - 1) * b.row(6 * N - 1)); negJer = -(6.0 * b.row(6 * N - 3) + 24.0 * T1(N - 1) * b.row(6 * N - 2) + 60.0 * T2(N - 1) * b.row(6 * N - 1)); B2 << negVel, negAcc, negJer; gdT(N - 1) += B2.cwiseProduct(adjGdC.block<3, 3>(6 * N - 3, 0)).sum(); return; } template <typename EIGENMAT> inline void addPropCtoP(const Eigen::MatrixXd &adjGdC, EIGENMAT &gdInP) const { for (int i = 0; i < N - 1; i++) { gdInP.col(i) += adjGdC.row(6 * i + 5).transpose(); } return; } template <typename EIGENVEC> inline void addTimeIntPenalty(const Eigen::VectorXi cons, const Eigen::VectorXi &idxHs, const std::vector<Eigen::MatrixXd> &cfgHs, const double vmax, const double amax, const Eigen::Vector3d ci, double &cost, EIGENVEC &gdT, Eigen::MatrixXd &gdC) const { double pena = 0.0; const double vmaxSqr = vmax * vmax; const double amaxSqr = amax * amax; Eigen::Vector3d pos, vel, acc, jer; double step, alpha; double s1, s2, s3, s4, s5; Eigen::Matrix<double, 6, 1> beta0, beta1, beta2, beta3; Eigen::Vector3d outerNormal; int K; double violaPos, violaVel, violaAcc; double violaPosPenaD, violaVelPenaD, violaAccPenaD; double violaPosPena, violaVelPena, violaAccPena; Eigen::Matrix<double, 6, 3> gradViolaVc, gradViolaAc; double gradViolaVt, gradViolaAt; double omg; int innerLoop, idx; for (int i = 0; i < N; i++) { const auto &c = b.block<6, 3>(i * 6, 0); step = T1(i) / cons(i); s1 = 0.0; innerLoop = cons(i) + 1; for (int j = 0; j < innerLoop; j++) { s2 = s1 * s1; s3 = s2 * s1; s4 = s2 * s2; s5 = s4 * s1; beta0 << 1.0, s1, s2, s3, s4, s5; beta1 << 0.0, 1.0, 2.0 * s1, 3.0 * s2, 4.0 * s3, 5.0 * s4; beta2 << 0.0, 0.0, 2.0, 6.0 * s1, 12.0 * s2, 20.0 * s3; beta3 << 0.0, 0.0, 0.0, 6.0, 24.0 * s1, 60.0 * s2; alpha = 1.0 / cons(i) * j; pos = c.transpose() * beta0; vel = c.transpose() * beta1; acc = c.transpose() * beta2; jer = c.transpose() * beta3; violaVel = vel.squaredNorm() - vmaxSqr; violaAcc = acc.squaredNorm() - amaxSqr; omg = (j == 0 || j == innerLoop - 1) ? 0.5 : 1.0; idx = idxHs(i); K = cfgHs[idx].cols(); for (int k = 0; k < K; k++) { outerNormal = cfgHs[idx].col(k).head<3>(); violaPos = outerNormal.dot(pos - cfgHs[idx].col(k).tail<3>()); if (violaPos > 0.0) { violaPosPenaD = violaPos * violaPos; violaPosPena = violaPosPenaD * violaPos; violaPosPenaD *= 3.0; gdC.block<6, 3>(i * 6, 0) += omg * step * ci(0) * violaPosPenaD * beta0 * outerNormal.transpose(); gdT(i) += omg * (ci(0) * violaPosPenaD * alpha * outerNormal.dot(vel) * step + ci(0) * violaPosPena / cons(i)); pena += omg * step * ci(0) * violaPosPena; } } if (violaVel > 0.0) { violaVelPenaD = violaVel * violaVel; violaVelPena = violaVelPenaD * violaVel; violaVelPenaD *= 3.0; gradViolaVc = 2.0 * beta1 * vel.transpose(); gradViolaVt = 2.0 * alpha * vel.transpose() * acc; gdC.block<6, 3>(i * 6, 0) += omg * step * ci(1) * violaVelPenaD * gradViolaVc; gdT(i) += omg * (ci(1) * violaVelPenaD * gradViolaVt * step + ci(1) * violaVelPena / cons(i)); pena += omg * step * ci(1) * violaVelPena; } if (violaAcc > 0.0) { violaAccPenaD = violaAcc * violaAcc; violaAccPena = violaAccPenaD * violaAcc; violaAccPenaD *= 3.0; gradViolaAc = 2.0 * beta2 * acc.transpose(); gradViolaAt = 2.0 * alpha * acc.transpose() * jer; gdC.block<6, 3>(i * 6, 0) += omg * step * ci(2) * violaAccPenaD * gradViolaAc; gdT(i) += omg * (ci(2) * violaAccPenaD * gradViolaAt * step + ci(2) * violaAccPena / cons(i)); pena += omg * step * ci(2) * violaAccPena; } s1 += step; } } cost += pena; return; } public: inline void reset(const Eigen::Matrix3d &headState, const Eigen::Matrix3d &tailState, const int &pieceNum) { N = pieceNum; headPVA = headState; tailPVA = tailState; T1.resize(N); A.create(6 * N, 6, 6); b.resize(6 * N, 3); gdC.resize(6 * N, 3); return; } inline void generate(const Eigen::MatrixXd &inPs, const Eigen::VectorXd &ts) { T1 = ts; T2 = T1.cwiseProduct(T1); T3 = T2.cwiseProduct(T1); T4 = T2.cwiseProduct(T2); T5 = T4.cwiseProduct(T1); A.reset(); b.setZero(); A(0, 0) = 1.0; A(1, 1) = 1.0; A(2, 2) = 2.0; b.row(0) = headPVA.col(0).transpose(); b.row(1) = headPVA.col(1).transpose(); b.row(2) = headPVA.col(2).transpose(); for (int i = 0; i < N - 1; i++) { A(6 * i + 3, 6 * i + 3) = 6.0; A(6 * i + 3, 6 * i + 4) = 24.0 * T1(i); A(6 * i + 3, 6 * i + 5) = 60.0 * T2(i); A(6 * i + 3, 6 * i + 9) = -6.0; A(6 * i + 4, 6 * i + 4) = 24.0; A(6 * i + 4, 6 * i + 5) = 120.0 * T1(i); A(6 * i + 4, 6 * i + 10) = -24.0; A(6 * i + 5, 6 * i) = 1.0; A(6 * i + 5, 6 * i + 1) = T1(i); A(6 * i + 5, 6 * i + 2) = T2(i); A(6 * i + 5, 6 * i + 3) = T3(i); A(6 * i + 5, 6 * i + 4) = T4(i); A(6 * i + 5, 6 * i + 5) = T5(i); A(6 * i + 6, 6 * i) = 1.0; A(6 * i + 6, 6 * i + 1) = T1(i); A(6 * i + 6, 6 * i + 2) = T2(i); A(6 * i + 6, 6 * i + 3) = T3(i); A(6 * i + 6, 6 * i + 4) = T4(i); A(6 * i + 6, 6 * i + 5) = T5(i); A(6 * i + 6, 6 * i + 6) = -1.0; A(6 * i + 7, 6 * i + 1) = 1.0; A(6 * i + 7, 6 * i + 2) = 2 * T1(i); A(6 * i + 7, 6 * i + 3) = 3 * T2(i); A(6 * i + 7, 6 * i + 4) = 4 * T3(i); A(6 * i + 7, 6 * i + 5) = 5 * T4(i); A(6 * i + 7, 6 * i + 7) = -1.0; A(6 * i + 8, 6 * i + 2) = 2.0; A(6 * i + 8, 6 * i + 3) = 6 * T1(i); A(6 * i + 8, 6 * i + 4) = 12 * T2(i); A(6 * i + 8, 6 * i + 5) = 20 * T3(i); A(6 * i + 8, 6 * i + 8) = -2.0; b.row(6 * i + 5) = inPs.col(i).transpose(); } A(6 * N - 3, 6 * N - 6) = 1.0; A(6 * N - 3, 6 * N - 5) = T1(N - 1); A(6 * N - 3, 6 * N - 4) = T2(N - 1); A(6 * N - 3, 6 * N - 3) = T3(N - 1); A(6 * N - 3, 6 * N - 2) = T4(N - 1); A(6 * N - 3, 6 * N - 1) = T5(N - 1); A(6 * N - 2, 6 * N - 5) = 1.0; A(6 * N - 2, 6 * N - 4) = 2 * T1(N - 1); A(6 * N - 2, 6 * N - 3) = 3 * T2(N - 1); A(6 * N - 2, 6 * N - 2) = 4 * T3(N - 1); A(6 * N - 2, 6 * N - 1) = 5 * T4(N - 1); A(6 * N - 1, 6 * N - 4) = 2; A(6 * N - 1, 6 * N - 3) = 6 * T1(N - 1); A(6 * N - 1, 6 * N - 2) = 12 * T2(N - 1); A(6 * N - 1, 6 * N - 1) = 20 * T3(N - 1); b.row(6 * N - 3) = tailPVA.col(0).transpose(); b.row(6 * N - 2) = tailPVA.col(1).transpose(); b.row(6 * N - 1) = tailPVA.col(2).transpose(); A.factorizeLU(); A.solve(b); return; } inline double getTrajJerkCost() const { double objective = 0.0; for (int i = 0; i < N; i++) { objective += 36.0 * b.row(6 * i + 3).squaredNorm() * T1(i) + 144.0 * b.row(6 * i + 4).dot(b.row(6 * i + 3)) * T2(i) + 192.0 * b.row(6 * i + 4).squaredNorm() * T3(i) + 240.0 * b.row(6 * i + 5).dot(b.row(6 * i + 3)) * T3(i) + 720.0 * b.row(6 * i + 5).dot(b.row(6 * i + 4)) * T4(i) + 720.0 * b.row(6 * i + 5).squaredNorm() * T5(i); } return objective; } template <typename EIGENVEC, typename EIGENMAT> inline void evalTrajCostGrad(const Eigen::VectorXi &cons, const Eigen::VectorXi &idxHs, const std::vector<Eigen::MatrixXd> &cfgHs, const double &vmax, const double &amax, const Eigen::Vector3d &ci, double &cost, EIGENVEC &gdT, EIGENMAT &gdInPs) { gdT.setZero(); gdInPs.setZero(); gdC.setZero(); cost = getTrajJerkCost(); addGradJbyT(gdT); addGradJbyC(gdC); addTimeIntPenalty(cons, idxHs, cfgHs, vmax, amax, ci, cost, gdT, gdC); solveAdjGradC(gdC); addPropCtoT(gdC, gdT); addPropCtoP(gdC, gdInPs); } inline Trajectory getTraj(void) const { Trajectory traj; traj.reserve(N); for (int i = 0; i < N; i++) { traj.emplace_back(T1(i), b.block<6, 3>(6 * i, 0).transpose().rowwise().reverse()); } return traj; } // GaaiLam template <typename EIGENVEC, typename EIGENMAT> inline void initGradCost(EIGENVEC &gdT, EIGENMAT &gdInPs, double &cost) { gdT.setZero(); gdInPs.setZero(); gdC.setZero(); cost = getTrajJerkCost(); addGradJbyT(gdT); addGradJbyC(gdC); } template <class TRAJGEN, typename EIGENVEC> // TRAJGEN::grad_cost_p(const Eigen::Vector3d &p, // Eigen::Vector3d &gradp, // double &cost) {} inline void addGrad2PVA(TRAJGEN *ptrObj, EIGENVEC &gdT, double &cost, const int &K=4) { // Eigen::Vector3d pos, vel, acc, jer; Eigen::Vector3d gradp, gradv, grada; double costp, costv, costa; Eigen::Matrix<double, 6, 1> beta0, beta1, beta2, beta3; double s1, s2, s3, s4, s5; double step, alpha; Eigen::Matrix<double, 6, 3> gradViolaPc, gradViolaVc, gradViolaAc; double gradViolaPt, gradViolaVt, gradViolaAt; double omg; int innerLoop; for (int i=0; i<N; ++i) { const auto &c = b.block<6, 3>(i * 6, 0); step = T1(i) / K; s1 = 0.0; innerLoop = K+1; for (int j=0; j<innerLoop; ++j) { s2 = s1 * s1; s3 = s2 * s1; s4 = s2 * s2; s5 = s4 * s1; beta0 << 1.0, s1, s2, s3, s4, s5; beta1 << 0.0, 1.0, 2.0 * s1, 3.0 * s2, 4.0 * s3, 5.0 * s4; beta2 << 0.0, 0.0, 2.0, 6.0 * s1, 12.0 * s2, 20.0 * s3; beta3 << 0.0, 0.0, 0.0, 6.0, 24.0 * s1, 60.0 * s2; alpha = 1.0 / K * j; pos = c.transpose() * beta0; vel = c.transpose() * beta1; acc = c.transpose() * beta2; jer = c.transpose() * beta3; omg = (j == 0 || j == innerLoop - 1) ? 0.5 : 1.0; if ( ptrObj->grad_cost_p(pos, gradp, costp) ) { gradViolaPc = beta0 * gradp.transpose(); gradViolaPt = alpha * gradp.transpose() * vel; gdC.block<6, 3>(i * 6, 0) += omg * step * gradViolaPc; gdT(i) += omg * (costp/K + step * gradViolaPt); cost += omg * step * costp; } if ( ptrObj->grad_cost_v(vel, gradv, costv) ) { gradViolaVc = beta1 * gradv.transpose(); gradViolaVt = alpha * gradv.transpose() * acc; gdC.block<6, 3>(i * 6, 0) += omg * step * gradViolaVc; gdT(i) += omg * (costv/K + step * gradViolaVt); cost += omg * step * costv; } if ( ptrObj->grad_cost_a(acc, grada, costa) ) { gradViolaAc = beta2 * grada.transpose(); gradViolaAt = alpha * grada.transpose() * jer; gdC.block<6, 3>(i * 6, 0) += omg * step * gradViolaAc; gdT(i) += omg * (costa/K + step * gradViolaAt); cost += omg * step * costa; } s1 += step; } } } template <class TRAJGEN, typename EIGENVEC> // i: the ith piece of traj // w: percent of time of this piece // TRAJGEN::grad_cost_p_at inline void addGrad2P_at (TRAJGEN *ptrObj, const int &i, const double &w, EIGENVEC &gdT, double &cost) { const auto &c = b.block<6, 3>(i * 6, 0); Eigen::Vector3d pos, vel, gradp; double costp = 0; double s1 = w * T1(i); double s2 = s1 * s1; double s3 = s2 * s1; double s4 = s3 * s1; double s5 = s4 * s1; Eigen::Matrix<double, 6, 1> beta0, beta1; beta0 << 1.0, s1, s2, s3, s4, s5; beta1 << 0.0, 1.0, 2.0 * s1, 3.0 * s2, 4.0 * s3, 5.0 * s4; pos = c.transpose() * beta0; vel = c.transpose() * beta1; if ( ptrObj->grad_cost_p_at(pos, gradp, costp) ) { gdC.block<6, 3>(i * 6, 0) += beta0 * gradp.transpose(); gdT(i) += w * gradp.transpose() * vel; cost += costp; } } template <typename EIGENVEC, typename EIGENMAT> inline void getGrad2TP(EIGENVEC &gdT, EIGENMAT &gdInPs) { solveAdjGradC(gdC); addPropCtoT(gdC, gdT); addPropCtoP(gdC, gdInPs); } }; #endif
// var data = require('../data.json'); /* * GET home page. */ const { create } = require("express3-handlebars"); var comments = require('../comments.json'); exports.view = function(req, res){ // console.log(comments); res.render("create",comments); };
<reponame>shimpeiws/remote-patient-monitoring-api "use strict"; export default class Formatter { getCenterFormatter(queryResult: any) { return queryResult.Items[0]; } };
#!/usr/bin/env sh # set google doc id DOC_ID="1E4lncZE2jDkbE34eDyYQmXKA9O26BHUiwguz4S9qyE8" # set file locations SOURCE_HTML_FILE="spec/fixtures/reference_document.html" JSON_FILE="spec/fixtures/reference_document_parsed.json" HTML_EXPORT_FILE="spec/fixtures/reference_document_exported.html" # export the google doc to HTML ./bin/article_json_export_google_doc.rb ${DOC_ID} > ${SOURCE_HTML_FILE} # convert the google doc html export to JSON ./bin/article_json_parse_google_doc.rb < ${SOURCE_HTML_FILE} | jq . > ${JSON_FILE} # convert the JSON export to HTML ./bin/article_json_export_html.rb < ${JSON_FILE} > ${HTML_EXPORT_FILE}
/* * Adapt the exit.c test to launch several threads and call exit() * from *one* of them (main or side). Don't join or exit the other * threads, just let them run. * * This tests who gets fini-thread and who gets fini-process. * * By contrast, exit.c has multiple calls to exit() and pthread_exit() * as a stress test of concurrency. * * Copyright (c) 2007-2021, Rice University. * See the file LICENSE for details. * * $Id$ */ #include <sys/time.h> #include <sys/types.h> #include <err.h> #include <errno.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define PROGRAM_TIME 3 #define NUM_THREADS 4 #define EXIT_THREAD 2 int program_time = PROGRAM_TIME; int num_threads = NUM_THREADS; int exit_thread = EXIT_THREAD; struct timeval start; void wait_for_time(int secs) { struct timeval now; for (;;) { gettimeofday(&now, NULL); if (now.tv_sec >= start.tv_sec + secs) break; usleep(1); } } /* * Run all threads, including main. The exit thread calls exit() and * the others just keep running. */ void * my_thread(void *val) { long num = (long) val; int is_exit = (num == exit_thread); printf("start thread: %ld\n", num); wait_for_time(program_time - 1); if (num == 0) { printf("----------------------------------------\n"); } wait_for_time(program_time); if (is_exit) { printf("exit thread: %ld\n\n", num); exit(0); } /* other threads keep running */ wait_for_time(program_time + 10); printf("end thread: %ld (%s) -- should not get here\n", num, (is_exit ? "yes" : "no")); return NULL; } /* * Program args: num_threads, exit_thread. */ int main(int argc, char **argv) { pthread_t td; long i; if (argc < 2 || sscanf(argv[1], "%d", &num_threads) < 1) { num_threads = NUM_THREADS; } if (argc < 3 || sscanf(argv[2], "%d", &exit_thread) < 1) { exit_thread = EXIT_THREAD; } printf("num_threads = %d, exit_thread = %d\n\n", num_threads, exit_thread); gettimeofday(&start, NULL); for (i = 1; i <= num_threads - 1; i++) { if (pthread_create(&td, NULL, my_thread, (void *)i) != 0) errx(1, "pthread_create failed"); } my_thread(0); printf("main exit -- should not get here\n"); return 0; }
def minimax(game, is_player1): if game.is_finished(): return game.get_score() best_score = None for move in game.get_moves(): game.make_move(move) score = minimax(game, not is_player1) game.undo_move() if is_player1: if score > best_score or best_score is None: best_score = score else: if score < best_score or best_score is None: best_score = score return best_score
#!/bin/bash . activate "${BUILD_PREFIX}" cd "${SRC_DIR}" pushd cctools_build_final/ld64 make install if [[ ${DEBUG_C} == yes ]]; then dsymutil ${PREFIX}/bin/*ld fi popd
<filename>server/index.js const express = require("express"); const app = express(); const mongoose = require("mongoose"); const dotenv = require("dotenv"); const inventoryRoute = require("./routes/inventory"); const cors = require("cors"); dotenv.config(); // Connecting to Mongo db mongoose .connect(process.env.MONGO_URL) .then(() => console.log("db connected successfully")) .catch((err) => console.log(err)); // ======== Middleware ======== //json parser middleware app.use(express.json()); app.use(cors()); app.use("/api/inventory", inventoryRoute); app.get("/", (req, res) => res.send("Hello from Express!")); app.listen(process.env.PORT || 5000, () => { console.log("server running on 5000"); });
#!/bin/bash echo "-> Configuring home" pushd home bash install.sh popd echo "-> Installing binaries and scripts" pushd bin bash install.sh popd
def sequence_generator(n): result = [] for i in range(pow(10,n)): sequence = "" number = i while number>0: sequence = str(number%10) + sequence number = number//10 result.append(sequence) return filter(lambda x: len(x)==n, result)
#!/bin/bash set -e echo -n 'Cleaning Up...' && rm -rf dist.zip && echo 'done' echo 'Zipping...' && echo && zip -r dist.zip ./ -i '*.js' '*.html' 'manifest.json' 'package.json' 'README.md' 'LICENSE' 'icons/*' 'node_modules/codemirror/lib/codemirror.css' 'console.css' -x 'node_modules/jquery/src/*' 'node_modules/jquery/external/*' 'node_modules/codemirror/keymap/*' 'node_modules/lolcode/tests/*' 'node_modules/codemirror/src/*' && echo && echo 'DONE!!!'
<reponame>manojj-ms/maizzle-sellr-templates module.exports = { theme: { screens: { all: {raw: 'screen'}, sm: {max: '525px'}, }, extend: { colors: { inherit: 'inherit', slate: { darkest: '#333333', darker: '#444444', dark: '#666666', light: '#AAAAAA', lighter: '#E6E9ED', lightest: '#F5F7FA', }, ceej: { body: '#f4f4f4', black: '#111111', blue: '#539be2', 'blue-light': '#B3E5FC', red: '#ec6d64', 'red-light': '#FFE0DE', purple: '#7c72dc', 'purple-light': '#C6C2ED', orange: '#FFA73B', 'orange-light': '#FFECD1', green: '#66BB7F', 'green-light': '#C0EDE0', }, }, spacing: { screen: '100vw', full: '100%', px: '1px', 0: '0', 2: '2px', 3: '3px', 4: '4px', 5: '5px', 6: '6px', 7: '7px', 8: '8px', 9: '9px', 10: '10px', 11: '11px', 12: '12px', 14: '14px', 15: '15px', 16: '16px', 18: '18px', 20: '20px', 22: '22px', 24: '24px', 25: '25px', 26: '26px', 28: '28px', 30: '30px', 32: '32px', 35: '35px', 36: '36px', 40: '40px', 45: '45px', 48: '48px', 50: '50px', 60: '60px', 70: '70px', 115: '115px', 150: '150px', 240: '240px', 325: '325px', 350: '350px', 385: '385px', 500: '500px', 600: '600px', '1/2': '50%', '1/3': '33.333333%', '2/3': '66.666667%', '1/4': '25%', '2/4': '50%', '3/4': '75%', '1/5': '20%', '2/5': '40%', '3/5': '60%', '4/5': '80%', '1/6': '16.666667%', '2/6': '33.333333%', '3/6': '50%', '4/6': '66.666667%', '5/6': '83.333333%', '1/12': '8.333333%', '2/12': '16.666667%', '3/12': '25%', '4/12': '33.333333%', '5/12': '41.666667%', '6/12': '50%', '7/12': '58.333333%', '8/12': '66.666667%', '9/12': '75%', '10/12': '83.333333%', '11/12': '91.666667%', }, borderRadius: { sm: '2px', DEFAULT: '4px', lg: '8px', }, fontFamily: { lato: ['Lato', '-apple-system', '"Segoe UI"', 'sans-serif'], sans: ['-apple-system', '"Segoe UI"', 'sans-serif'], serif: ['Constantia', 'Georgia', 'serif'], mono: ['Menlo', 'Consolas', 'monospace'], }, fontSize: { '0': 0, xxs: '12px', xs: '13px', sm: '14px', base: '16px', lg: '18px', xl: '20px', '2xl': '22px', '3xl': '24px', '32px': '32px', '4xl': '36px', '5xl': '48px', }, inset: theme => ({ ...theme('spacing'), }), letterSpacing: theme => ({ tighter: '-2px', tight: '-1px', normal: '0', wide: '1px', wider: '2px', loose: '4px', ...theme('spacing'), }), lineHeight: theme => ({ ...theme('spacing'), }), maxHeight: theme => ({ ...theme('spacing'), }), maxWidth: theme => ({ ...theme('spacing'), }), minHeight: theme => ({ ...theme('spacing'), }), minWidth: theme => ({ ...theme('spacing'), }), }, }, corePlugins: { animation: false, backgroundOpacity: false, borderOpacity: false, divideOpacity: false, placeholderOpacity: false, textOpacity: false, }, }
import axios from 'axios' import history from '../history' /** * ACTION TYPES */ const GET_NOTES = 'GET_NOTES' const REMOVE_NOTE = 'REMOVE_NOTE' const EDIT_NOTE = 'EDIT_NOTE' const ADD_NOTE = 'ADD_NOTE' /** * INITIAL STATE */ const notes = {} /** * ACTION CREATORS */ const getNotes = userNotes => ({type: GET_NOTES, userNotes}) const removeNote = id => ({type: REMOVE_NOTE, id}) const editNote = note => ({type: EDIT_NOTE, note}) const addNote = note => ({type: ADD_NOTE, note}) /** * THUNK CREATORS */ export const fetchNotes = () => dispatch => { axios .get('/api/notes') .then(res => { dispatch(getNotes(res.data))}) .catch(err => console.log(err)) } export const deleteNote = id => dispatch => axios .delete('/notes', id) .then(() => dispatch(removeNote(id))) .catch(err => console.log(err)) export const updateNote = (id, note) => dispatch => axios .put(`/api/notes/${id}`, note) .then(res => dispatch(editNote(res.data))) .catch(err => console.log(err)) export const addANote = note => dispatch => axios .post('/notes', note) .then(() => dispatch(addNote(note))) .catch(err => console.log(err)) /** * REDUCER */ export default function (state = notes, action) { switch (action.type) { case GET_NOTES: return action.userNotes case REMOVE_NOTE: return state.filter(note => note.id !== action.id) case EDIT_NOTE: return state.map( allNotes => (action.note.id === allNotes.id ? action.note : allNotes) ); case ADD_NOTE: return [action.note, ... state] default: return state } }
#!/bin/bash LAYOUT_PATH="${INPUT_PATH:-layout_src}" ARTIFACTS_PATH="${INPUT_ARTIFACTS_PATH:-artifacts}" KEYMAP="${INPUT_KEYMAP:-neo}" KEYBOARD="${INPUT_KEYBOARD:-moonlander}" #echo "Setting up ZSA QMK fork ..." # moved into Dockerfile, TODO make configurable #qmk setup zsa/qmk_firmware -b firmware20 echo "Adding keymap $KEYMAP [$KEYBOARD] ..." qmk new-keymap -kb $KEYBOARD -km $KEYMAP echo "Overwrite keymap layout from $LAYOUT_PATH" cp $LAYOUT_PATH/* /qmk_firmware/keyboards/$KEYBOARD/keymaps/$KEYMAP ls /qmk_firmware/keyboards/$KEYBOARD/keymaps/$KEYMAP echo "Compiling keymap $KEYMAP ..." qmk compile -kb $KEYBOARD -km $KEYMAP # outfile: .build/moonlander_neo.bin echo "Copying out into artifacts folder [$ARTIFACTS_PATH] ..." pwd # /github/workspace ls -altr if [ ! -d "$ARTIFACTS_PATH" ]; then mkdir $ARTIFACTS_PATH fi cp -R /qmk_firmware/.build/* $ARTIFACTS_PATH/ echo "Artifacts list:" ls $ARTIFACTS_PATH echo "Done!"
/* * $Id: cdk.h,v 1.37 2012/03/20 22:01:57 tom Exp $ */ #ifndef CDK_H #define CDK_H #ifdef __cplusplus extern "C" { #endif /* * Changes 2000-2009,2012 copyright <NAME> * * Copyright 1999, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgment: * This product includes software developed by Mike Glover * and contributors. * 4. Neither the name of Mike Glover, nor the names of contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY MIKE GLOVER AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL MIKE GLOVER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <cdk_config.h> #include <cdk_version.h> #ifdef CDK_PERL_EXT #undef instr #endif #ifdef HAVE_XCURSES #include <xcurses.h> #ifndef mvwhline #define mvwhline(win,y,x,c,n) (wmove(win,y,x) == ERR ? ERR : whline(win,c,n)) #endif #ifndef mvwvline #define mvwvline(win,y,x,c,n) (wmove(win,y,x) == ERR ? ERR : wvline(win,c,n)) #endif #elif defined(HAVE_NCURSESW_NCURSES_H) #include <ncursesw/ncurses.h> #elif defined(HAVE_NCURSES_NCURSES_H) #include <ncurses/ncurses.h> #elif defined(HAVE_NCURSES_H) #include <ncurses.h> #else #include <curses.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_DIRENT_H #include <dirent.h> #endif #include <time.h> #include <errno.h> #ifdef HAVE_PWD_H #include <pwd.h> #endif #ifdef HAVE_GRP_H #include <grp.h> #endif #ifdef HAVE_LIMITS_H #include <limits.h> #endif #ifdef HAVE_GETOPT_HEADER #ifdef HAVE_GETOPT_H #include <getopt.h> #endif #else extern int optind; extern char * optarg; #endif /* * Definitions that we do not want if term.h does */ #ifdef buttons #undef buttons #endif #ifdef lines #undef lines #endif #ifdef newline #undef newline #endif /* * Values we normally get from limits.h (assume 32-bits) */ #ifndef INT_MIN #define INT_MIN (-INT_MAX - 1) #endif #ifndef INT_MAX #define INT_MAX 2147483647 #endif #ifndef GCC_UNUSED #define GCC_UNUSED /*nothing*/ #endif #ifdef HAVE_LIBDMALLOC #include <dmalloc.h> /* <NAME>'s library */ #else #undef HAVE_LIBDMALLOC #define HAVE_LIBDMALLOC 0 #endif #ifdef HAVE_LIBDBMALLOC #include <dbmalloc.h> /* <NAME>'s library */ #else #undef HAVE_LIBDBMALLOC #define HAVE_LIBDBMALLOC 0 #endif /* * This enumerated typedef lists all of the CDK widget types. */ typedef enum { vNULL = 0 ,vALPHALIST ,vBUTTON ,vBUTTONBOX ,vCALENDAR ,vDIALOG ,vDSCALE ,vENTRY ,vFSCALE ,vFSELECT ,vFSLIDER ,vGRAPH ,vHISTOGRAM ,vITEMLIST ,vLABEL ,vMARQUEE ,vMATRIX ,vMENTRY ,vMENU ,vRADIO ,vSCALE ,vSCROLL ,vSELECTION ,vSLIDER ,vSWINDOW ,vTEMPLATE ,vTRAVERSE ,vUSCALE ,vUSLIDER ,vVIEWER } EObjectType; /* * This enumerated typedef lists all the valid display types for * the entry, mentry, and template widgets. */ typedef enum { vINVALID = 0 ,vCHAR ,vHCHAR ,vINT ,vHINT ,vMIXED ,vHMIXED ,vUCHAR ,vLCHAR ,vUHCHAR ,vLHCHAR ,vUMIXED ,vLMIXED ,vUHMIXED ,vLHMIXED ,vVIEWONLY } EDisplayType; /* * This enumerated typedef lists all the display types for * the histogram widget. */ typedef enum {vNONE, vPERCENT, vFRACTION, vREAL} EHistogramDisplayType; /* * This enumerated typedef defines the display types for the graph. */ typedef enum {vPLOT, vLINE} EGraphDisplayType; /* * This enumerated typedef defines where white space is to be * stripped from in the function stripWhiteSpace. */ typedef enum {vFRONT, vBACK, vBOTH} EStripType; /* * This enumerated typedef defines the type of exits the widgets * recognize. */ typedef enum {vEARLY_EXIT, vESCAPE_HIT, vNORMAL, vNEVER_ACTIVATED, vERROR} EExitType; #if _WIN32 #define boolean CDKboolean #endif /* * This defines a boolean type. */ typedef int boolean; /* * Declare miscellaneous defines. */ #define LEFT 9000 #define RIGHT 9001 #define CENTER 9002 #define TOP 9003 #define BOTTOM 9004 #define HORIZONTAL 9005 #define VERTICAL 9006 #define FULL 9007 #define NONE 0 #define ROW 1 #define COL 2 #define MAX_BINDINGS 300 /* unused by widgets */ #define MAX_ITEMS 2000 /* unused by widgets */ #define MAX_BUTTONS 200 /* unused by widgets */ #define MAXIMUM(a,b) ((a) > (b) ? (a) : (b)) #define MINIMUM(a,b) ((a) < (b) ? (a) : (b)) #define HALF(a) ((a) >> 1) #ifndef COLOR_PAIR #define COLOR_PAIR(a) A_NORMAL #endif #define CONTROL(c) ((c) & 0x1f) /* obsolete: use CTRL() */ /* Define the 'GLOBAL DEBUG FILEHANDLE' */ extern FILE *CDKDEBUG; /* * ========================================================= * Declare Debugging Routines. * ========================================================= */ #define START_DEBUG(a) (CDKDEBUG=startCDKDebug(a)) #define WRITE_DEBUGMESG(a,b) (writeCDKDebugMessage (CDKDEBUG,__FILE__,a,__LINE__,b)) #define END_DEBUG (stopCDKDebug(CDKDEBUG) FILE *startCDKDebug(const char *filename); void writeCDKDebugMessage (FILE *fd, const char *filename, const char *function, int line, const char *message); void stopCDKDebug (FILE *fd); /* * These header files define miscellaneous values and prototypes. */ #include <cdkscreen.h> #include <curdefs.h> #include <binding.h> #include <cdk_util.h> #include <cdk_objs.h> #include <cdk_params.h> /* * Include the CDK widget header files. */ #include <alphalist.h> #include <buttonbox.h> #include <calendar.h> #include <dialog.h> #include <entry.h> #include <fselect.h> #include <graph.h> #include <histogram.h> #include <itemlist.h> #include <label.h> #include <marquee.h> //#include <matrix.h> #include <mentry.h> #include <menu.h> #include <radio.h> #include <scroll.h> #include <selection.h> #include <swindow.h> #include <template.h> //#include <viewer.h> #include <traverse.h> #include <button.h> /* * Generated headers: */ //#include <dscale.h> //#include <fscale.h> //#include <scale.h> //#include <uscale.h> // //#include <fslider.h> //#include <slider.h> //#include <uslider.h> /* * Low-level object drawing */ #include <draw.h> #ifdef __cplusplus } #endif #endif /* CDK_H */
SELECT Customers.Name FROM Orders INNER JOIN Customers ON Orders.CustomerId = Customers.Id WHERE OrderDate >= DATE_SUB(NOW(), INTERVAL 30 DAY)
mkdir ./dist cd ./src zip -r ../dist/switching-to-non-empty-workspace.zip ./*
function pascalTriangle(numRows) { let triangle = [[1]]; for (let i = 0; i < numRows; i++) { let row = []; for (let j = 0; j <= i; j++) { row.push(j === 0 || j === i ? 1 : triangle[i-1][j-1] + triangle[i-1][j]); } triangle.push(row); } console.log(triangle); }
# Neuroimaging BASH functions. # Written by Tim Schaefer. # # USAGE: # You should source this file in your scripts or in your shell startup config file. Then you can use the functions in your scripts or on the command line. # Do NOT run this file, it's not gonna help. # Example: # $ source ni_bash_functions.bash # $ create_subjectsfile_from_subjectsdir /Applications/freesurfer/subjects ~/fs_subjects_list.txt create_subjectsfile_from_subjectsdir () { ## Function to find all valid FreeSurfer subjects in a SUBJECTS_DIR and create a SUBJECTS_FILE from the list. ## This function will check all subdirs of the given SUBJECTS_DIR for the typical FreeSurfer sub directory 'mri'. ## All sub dirs which contain it are considered subjects, and added to the list in the SUBJECTS_FILE. ## Note that a SUBJECTS_FILE is a text file containing one subject per line. ## ## This function can be used in scripts, and is thus a lot better than first running `ls -1 > subejcts.txt` in the ## directory and them manually removing all invalid entries (other files/dirs in the SUBJECTS_DIR, including ## at least the file subjects.txt itself) manually with a text editor. ## ## USAGE: create_subjectsfile_from_subjectsdir <SUBJECTS_DIR> <SUBJECTS_FILE> [<DO_SUBDIR_CHECK>] ## where <DO_SUBDIR_CHECK> is optional, and must be "YES" or "NO". Defaults to "YES". local SUBJECTS_DIR=$1 local SUBJECTS_FILE=$2 local DO_SUBDIR_CHECK=$3 if [ -z "${SUBJECTS_DIR}" ]; then echo "ERROR: make_subjectsfile_in_subjectsdir(): Missing required 1st function parameter 'SUBJECTS_DIR'." return 1 fi if [ -z "${SUBJECTS_FILE}" ]; then echo "ERROR: make_subjectsfile_in_subjectsdir(): Missing required 2nd function parameter 'SUBJECTS_FILE'." return 1 fi if [ ! -d "${SUBJECTS_DIR}" ]; then echo "ERROR: make_subjectsfile_in_subjectsdir(): The given SUBJECTS_DIR '$SUBJECTS_DIR' does not exist or is not readable." return 1 fi if [ -z "$DO_SUBDIR_CHECK" ]; then DO_SUBDIR_CHECK="YES" fi if [ "$DO_SUBDIR_CHECK" = "YES" ]; then echo "INFO: make_subjectsfile_in_subjectsdir(): Performing check for 'mri' subdir." else if [ "$DO_SUBDIR_CHECK" = "NO" ]; then echo "INFO: make_subjectsfile_in_subjectsdir(): NOT performing check for 'mri' subdir." else echo "ERROR: make_subjectsfile_in_subjectsdir(): Invalid parameter DO_SUBDIR_CHECK, must be 'YES' or 'NO' if given." return 1 fi fi CURDIR=$(pwd) cd "${SUBJECTS_DIR}" VALID_FREESURFER_SINGLE_SUBJECT_DIRS="" SUBDIRS=$(ls -d */) NUM_SUBJECTS_FOUND=0 if [ -n "$SUBDIRS" ]; then # There may not be any. for SDIR in $SUBDIRS; do SDIR=${SDIR%/} # strip potential trailing slash, which would otherwise become part of the subject ID. if [ "${DO_SUBDIR_CHECK}" = "NO" -o -d "${SDIR}/mri/" ]; then NUM_SUBJECTS_FOUND=$((NUM_SUBJECTS_FOUND+1)) if [ -n "${VALID_FREESURFER_SINGLE_SUBJECT_DIRS}" ]; then VALID_FREESURFER_SINGLE_SUBJECT_DIRS="${VALID_FREESURFER_SINGLE_SUBJECT_DIRS} " # Add space for separation unless this is the first entry. fi VALID_FREESURFER_SINGLE_SUBJECT_DIRS="${VALID_FREESURFER_SINGLE_SUBJECT_DIRS}${SDIR}" fi done fi echo "Found ${NUM_SUBJECTS_FOUND} FreeSurfer subjects under dir '${SUBJECTS_DIR}', writing subjects file '${SUBJECTS_FILE}'." # Currently the dirs are separated by spaces, but we want them separated by newlines FSDIR_PER_LINE=$(echo "${VALID_FREESURFER_SINGLE_SUBJECT_DIRS}" | tr ' ' '\n') cd "${CURDIR}" && echo "${FSDIR_PER_LINE}" > "${SUBJECTS_FILE}" return 0 }
#!/bin/bash # Script that will execute a grid search of a part of the parameter space # Different sparsity options (Note: might be influenced by lamb_reg) python3 run.py --name="sparse01bin" --experiment=mixture --approach=dwa --weight_init="kaiming:xavier" --sparsity=0.1 --bin_sparsity=true --seed=0 --log_path="../res" python3 run.py --name="sparse02bin" --experiment=mixture --approach=dwa --weight_init="kaiming:xavier" --sparsity=0.2 --bin_sparsity=true --seed=0 --log_path="../res" python3 run.py --name="sparse05bin" --experiment=mixture --approach=dwa --weight_init="kaiming:xavier" --sparsity=0.5 --bin_sparsity=true --seed=0 --log_path="../res" python3 run.py --name="sparse01" --experiment=mixture --approach=dwa --weight_init="kaiming:xavier" --sparsity=0.1 --bin_sparsity=false --seed=0 --log_path="../res" python3 run.py --name="sparse02" --experiment=mixture --approach=dwa --weight_init="kaiming:xavier" --sparsity=0.2 --bin_sparsity=false --seed=0 --log_path="../res" python3 run.py --name="sparse05" --experiment=mixture --approach=dwa --weight_init="kaiming:xavier" --sparsity=0.5 --bin_sparsity=false --seed=0 --log_path="../res" # anchor losses python3 run.py --name="firstanchor" --experiment=mixture --approach=dwa --weight_init="kaiming:xavier" --use_anchor_first=true --seed=0 --log_path="../res" python3 run.py --name="scaleloss" --experiment=mixture --approach=dwa --weight_init="kaiming:xavier" --scale_att_loss=true --seed=0 --log_path="../res"
// Taken from https://github.com/vuejs/vue/blob/dev/packages/vue-template-compiler/browser.js var splitRE = /\r?\n/g; var emptyRE = /^\s*$/; var needFixRE = /^(\r?\n)*[\t\s]/; var deIndent = function deindent (str) { if (!needFixRE.test(str)) { return str } var lines = str.split(splitRE); var min = Infinity; var type, cur, c; for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (!emptyRE.test(line)) { if (!type) { c = line.charAt(0); if (c === ' ' || c === '\t') { type = c; cur = count(line, type); if (cur < min) { min = cur; } } else { return str } } else { cur = count(line, type); if (cur < min) { min = cur; } } } } return lines.map(function (line) { return line.slice(min) }).join('\n') }; function count (line, type) { var i = 0; while (line.charAt(i) === type) { i++; } return i } /* */ var emptyObject = Object.freeze({}); // these helpers produces better vm code in JS engines due to their // explicitness and function inlining function isUndef (v) { return v === undefined || v === null } /** * Check if value is primitive */ function isPrimitive (value) { return ( typeof value === 'string' || typeof value === 'number' || // $flow-disable-line typeof value === 'symbol' || typeof value === 'boolean' ) } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Get the raw type string of a value e.g. [object Object] */ var _toString = Object.prototype.toString; function toRawType (value) { return _toString.call(value).slice(8, -1) } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject (obj) { return _toString.call(obj) === '[object Object]' } /** * Check if val is a valid array index. */ function isValidArrayIndex (val) { var n = parseFloat(String(val)); return n >= 0 && Math.floor(n) === n && isFinite(val) } /** * Convert a value to a string that is actually rendered. */ /** * Convert a input value to a number for persistence. * If the conversion fails, return original string. */ /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Check if a attribute is a reserved attribute. */ var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); /** * Remove an item from an array */ function remove (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether the object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) } /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ /** * Simple bind polyfill for environments that do not support it... e.g. * PhantomJS 1.x. Technically we don't need this anymore since native bind is * now more performant in most browsers, but removing it would be breaking for * code that was able to run in PhantomJS 1.x, so this must be kept for * backwards compatibility. */ /* istanbul ignore next */ function polyfillBind (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } boundFn._length = fn.length; return boundFn } function nativeBind (fn, ctx) { return fn.bind(ctx) } var bind = Function.prototype.bind ? nativeBind : polyfillBind; /** * Convert an Array-like object to a real Array. */ /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Merge an Array of Objects into a single Object. */ /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/) */ function noop (a, b, c) {} /** * Always return false. */ var no = function (a, b, c) { return false; }; /** * Return same value */ var identity = function (_) { return _; }; /** * Generate a static keys string from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ /** * Ensure a function is called only once. */ /* */ var isUnaryTag = makeMap( 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr' ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source' ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track' ); /** * Not type-checking this file because it's mostly vendor code. */ /*! * HTML Parser By <NAME> (ejohn.org) * Modified by Juriy "kangax" Zaytsev * Original code by <NAME>, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js */ // Regular Expressions for parsing tags and attributes var attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; // could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName // but for Vue templates we can enforce a simple charset var ncname = '[a-zA-Z_][\\w\\-\\.]*'; var qnameCapture = "((?:" + ncname + "\\:)?" + ncname + ")"; var startTagOpen = new RegExp(("^<" + qnameCapture)); var startTagClose = /^\s*(\/?)>/; var endTag = new RegExp(("^<\\/" + qnameCapture + "[^>]*>")); var doctype = /^<!DOCTYPE [^>]+>/i; // #7298: escape - to avoid being pased as HTML comment when inlined in page var comment = /^<!\--/; var conditionalComment = /^<!\[/; var IS_REGEX_CAPTURING_BROKEN = false; 'x'.replace(/x(.)?/g, function (m, g) { IS_REGEX_CAPTURING_BROKEN = g === ''; }); // Special Elements (can contain anything) var isPlainTextElement = makeMap('script,style,textarea', true); var reCache = {}; var decodingMap = { '&lt;': '<', '&gt;': '>', '&quot;': '"', '&amp;': '&', '&#10;': '\n', '&#9;': '\t' }; var encodedAttr = /&(?:lt|gt|quot|amp);/g; var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10|#9);/g; // #5992 var isIgnoreNewlineTag = makeMap('pre,textarea', true); var shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\n'; }; function decodeAttr (value, shouldDecodeNewlines) { var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr; return value.replace(re, function (match) { return decodingMap[match]; }) } function parseHTML (html, options) { var stack = []; var expectHTML = options.expectHTML; var isUnaryTag$$1 = options.isUnaryTag || no; var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no; var index = 0; var last, lastTag; while (html) { last = html; // Make sure we're not in a plaintext content element like script/style if (!lastTag || !isPlainTextElement(lastTag)) { var textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment.test(html)) { var commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { if (options.shouldKeepComment) { options.comment(html.substring(4, commentEnd)); } advance(commentEnd + 3); continue } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { var conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue } } // Doctype: var doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue } // End tag: var endTagMatch = html.match(endTag); if (endTagMatch) { var curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); continue } // Start tag: var startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); if (shouldIgnoreFirstNewline(lastTag, html)) { advance(1); } continue } } var text = (void 0), rest = (void 0), next = (void 0); if (textEnd >= 0) { rest = html.slice(textEnd); while ( !endTag.test(rest) && !startTagOpen.test(rest) && !comment.test(rest) && !conditionalComment.test(rest) ) { // < in plain text, be forgiving and treat it as text next = rest.indexOf('<', 1); if (next < 0) { break } textEnd += next; rest = html.slice(textEnd); } text = html.substring(0, textEnd); advance(textEnd); } if (textEnd < 0) { text = html; html = ''; } if (options.chars && text) { options.chars(text); } } else { var endTagLength = 0; var stackedTag = lastTag.toLowerCase(); var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')); var rest$1 = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') { text = text .replace(/<!\--([\s\S]*?)-->/g, '$1') // #7298 .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1'); } if (shouldIgnoreFirstNewline(stackedTag, text)) { text = text.slice(1); } if (options.chars) { options.chars(text); } return '' }); index += html.length - rest$1.length; html = rest$1; parseEndTag(stackedTag, index - endTagLength, index); } if (html === last) { options.chars && options.chars(html); if ("development" !== 'production' && !stack.length && options.warn) { options.warn(("Mal-formatted tag at end of template: \"" + html + "\"")); } break } } // Clean up any remaining tags parseEndTag(); function advance (n) { index += n; html = html.substring(n); } function parseStartTag () { var start = html.match(startTagOpen); if (start) { var match = { tagName: start[1], attrs: [], start: index }; advance(start[0].length); var end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) { advance(attr[0].length); match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match } } } function handleStartTag (match) { var tagName = match.tagName; var unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) { parseEndTag(tagName); } } var unary = isUnaryTag$$1(tagName) || !!unarySlash; var l = match.attrs.length; var attrs = new Array(l); for (var i = 0; i < l; i++) { var args = match.attrs[i]; // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778 if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) { if (args[3] === '') { delete args[3]; } if (args[4] === '') { delete args[4]; } if (args[5] === '') { delete args[5]; } } var value = args[3] || args[4] || args[5] || ''; var shouldDecodeNewlines = tagName === 'a' && args[1] === 'href' ? options.shouldDecodeNewlinesForHref : options.shouldDecodeNewlines; attrs[i] = { name: args[1], value: decodeAttr(value, shouldDecodeNewlines) }; } if (!unary) { stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs }); lastTag = tagName; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag (tagName, start, end) { var pos, lowerCasedTagName; if (start == null) { start = index; } if (end == null) { end = index; } if (tagName) { lowerCasedTagName = tagName.toLowerCase(); } // Find the closest opened tag of the same type if (tagName) { for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { break } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (var i = stack.length - 1; i >= pos; i--) { if ("development" !== 'production' && (i > pos || !tagName) && options.warn ) { options.warn( ("tag <" + (stack[i].tag) + "> has no matching end tag.") ); } if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } /* */ var splitRE$1 = /\r?\n/g; var replaceRE = /./g; var isSpecialTag = makeMap('script,style,template', true); /** * Parse a single-file component (*.vue) file into an SFC Descriptor Object. */ export function parseComponent ( content, options ) { if ( options === void 0 ) options = {}; var sfc = { script: [], style: [], config: [], window: [], docs: [], attachment: [], link: [], others: [] }; var depth = 0; var currentBlock = null; function start ( tag, attrs, unary, start, end ) { if (depth === 0) { currentBlock = { type: tag, content: '', start: end, attrs: attrs.reduce(function (cumulated, ref) { var name = ref.name; var value = ref.value; cumulated[name] = value || true; return cumulated }, {}) }; if (sfc[tag]) { checkAttrs(currentBlock, attrs); sfc[tag].push(currentBlock); } else { // custom blocks sfc.others.push(currentBlock); } } if (!unary) { depth++; } } function checkAttrs (block, attrs) { for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; if (attr.name === 'lang') { block.lang = attr.value; } if (attr.name === 'scoped') { block.scoped = true; } if (attr.name === 'module') { block.module = attr.value || true; } if (attr.name === 'src') { block.src = attr.value; } } } function end (tag, start, end) { if (depth === 1 && currentBlock) { currentBlock.end = start; var text = deIndent(content.slice(currentBlock.start, currentBlock.end)); // pad content so that linters and pre-processors can output correct // line numbers in errors and warnings if (currentBlock.type !== 'template' && options.pad) { text = padContent(currentBlock, options.pad) + text; } currentBlock.content = text; currentBlock = null; } depth--; } function padContent (block, pad) { if (pad === 'space') { return content.slice(0, block.start).replace(replaceRE, ' ') } else { var offset = content.slice(0, block.start).split(splitRE$1).length; var padChar = block.type === 'script' && !block.lang ? '//\n' : '\n'; return Array(offset).join(padChar) } } parseHTML(content, { start: start, end: end }); return sfc }
#!/bin/bash conda install -c conda-forge -c defaults thrust=1.9
<filename>web/libs/base-ui/src/lib/image/image.spec.tsx import { render } from '@testing-library/react'; import Image from './image'; describe('Image', () => { it('should render successfully', () => { const { baseElement } = render( <Image src="https://www.datocms-assets.com/64528/1646636342-icon.png" width={512} height={512} /> ); expect(baseElement).toBeTruthy(); }); });
<gh_stars>0 export declare const INNERTUBE_CLIENT_VERSION = "2.20201209.01.00"; export declare const INNERTUBE_API_KEY = "<KEY>"; export declare const I_END_POINT = "https://www.youtube.com/youtubei/v1"; export declare const WATCH_END_POINT = "https://www.youtube.com/watch";
import { Component, OnInit, OnDestroy, NgZone } from '@angular/core'; import { NbDialogRef, NbDialogService } from '@nebular/theme'; import { Router } from '@angular/router'; import { Location } from '@angular/common'; import { Igijuser, Ogijuser, nano_time, MyDataBaseNames, Irolelist, Orolelist, OmySystem } from '../../interface'; import pouchdb, { emit } from 'pouchdb'; import pouchdbwebsql from 'pouchdb-adapter-websql'; import { ModalRoleListComponent } from './modal-rolelist/modal-rolelist.component' import 'rxjs/add/observable/of' import 'rxjs/add/operator/map'; import 'rxjs/add/operator/delay'; import { trigger, transition, query, stagger, animate, style } from '@angular/animations'; import PouchAuth from 'pouchdb-authentication'; // export const staggeranimation=trigger('races', [ // transition('* => *', [ // query(':leave', [ // stagger(500, [ // animate(1000, style({ opacity: 0 })) // ]) // ], { optional: true }), // query(':enter', [ // style({ opacity: 0 }), // animate(1000, style({ opacity: 1 })) // ], { optional: true }) // ]) // ]); @Component({ selector: 'ngx-role-list', templateUrl: './role-list.component.html', styleUrls: ['./role-list.component.scss'], //animations:[staggeranimation] }) export class RoleListComponent implements OnInit, OnDestroy { ngOnDestroy(): void { console.log('destroy role list'); } private db: PouchDB.Database<{}>; dbname: string = MyDataBaseNames.dbrolelist; remoteCouch = MyDataBaseNames.remoteCouch; fulldbname: string; _selectedObj: Irolelist; _arrayObj: Array<Irolelist>; _system = new OmySystem('task-manager'); _parent = new Array('task-manager-admin'); constructor(public zone: NgZone, private dialogService: NbDialogService, private router: Router, private _location: Location) { this._selectedObj = new Orolelist(); this._arrayObj = new Array<Irolelist>(); // prefixname+dbname+prefix; this.fulldbname = 'prefixname' + MyDataBaseNames.dbrolelist + 'prefix'; let url = this.remoteCouch + this.fulldbname; console.log('dbname url', this.fulldbname, url); pouchdb.plugin(pouchdbwebsql); pouchdb.plugin(PouchAuth); //pouchdb.adapter(socketpouch); this.db = new pouchdb(this.fulldbname, { adapter: 'websql' }); this.sync(url); } ngOnInit() { this.loadList(); } sync(url) { let parent = this; this.db.sync(url, { live: true, retry: true }).on('change', async (info) => { console.log('sync res'); console.log(info); if (info.direction == "pull") { console.log('PULL UPDATE'); this.zone.run(() => { parent.loadList(); }) } }).on('paused', function (err) { // replication paused (e.g. replication up to date, user went offline) console.log('paused'); }).on('active', function () { // replicate resumed (e.g. new changes replicating, user went back online) console.log('active'); }).on('denied', function (err) { // a document failed to replicate (e.g. due to permissions) console.log('denied'); }).on('complete', function (info) { // handle complete }).on('error', function (err) { console.log('sync err'); console.log(err); }); // url = 'ws://localhost:1314/'; // var client = PouchSync.createClient(); // console.log('start sync'); // let opts = { // live: true, // retry: true, // } // console.log(client); // var sync = client.sync(this.db, { // remoteName: MyDataBaseNames.remoteCouch+MyDataBaseNames.dbrolelist, // name remote db is known for // credentials: { token: 'some token' } // arbitrary // }); // client.connect(url); // client.emit('connect') // when connects // client.emit('disconnect') // when gets disconnected // client.emit('reconnect') // when starts attempting to reconnect // //sync.emit('change', change) // sync.emit('paused') // sync.emit('active') // sync.emit('denied') // sync.emit('complete') // //sync.emit('error', err) // //this.db = new socketpouch(this.fulldbname,{adapter: 'socket', name: this.fulldbname,auth:{username:'userx',password:'<PASSWORD>'}}); // // testonly // let remote = new socketpouch({socketOptions: {},url:url,adapter: 'socket', name: this.fulldbname,auth:{username:'userx',password:'<PASSWORD>'}},(r,e)=>{ // console.log(r); // console.log(e); // }); // console.log('start sync'); // let opts={ // live: true, // retry: true, // } // console.log(remote); // this.db.sync(remote,opts).on('change', async (info) => { // console.log('sync res'); // console.log(info); // if (info.direction == "pull") { // console.log('PULL UPDATE'); // this.zone.run(() => { // parent.loadList(); // }) // } // }).on('paused', function (err) { // // replication paused (e.g. replication up to date, user went offline) // console.log('paused'); // }).on('active', function () { // // replicate resumed (e.g. new changes replicating, user went back online) // console.log('active'); // }).on('denied', function (err) { // // a document failed to replicate (e.g. due to permissions) // console.log('denied'); // }).on('complete', function (info) { // // handle complete // }).on('error', function (err) { // console.log('sync err'); // console.log(err); // }); //var client = PouchSync.createClient(); // var sync = client.sync(this.db, { // //remoteName: 'todos-server', // name remote db is known for // credentials: { token: 'OK' } // arbitrary // }); // client.connect(url); // client.emit('connect') // when connects // client.emit('disconnect') // when gets disconnected // client.emit('reconnect') // when starts attempting to reconnect // sync.emit('change', (change)=>{ // console.log(change); // }); // sync.emit('paused') // sync.emit('active') // sync.emit('denied') // sync.emit('complete') // sync.emit('error', (err)=>{ // console.log(err); // }); //sync.cancel(); // remote.sync(url,{ // this.db.sync(url, { // live: true, // retry: true // }, (err, res) => { // console.log(err); // console.log(res); // }).on('change', async (info) => { // console.log('sync res'); // console.log(info); // if (info.direction == "pull") { // console.log('PULL UPDATE'); // this.zone.run(() => { // parent.loadList(); // }) // } // }).on('paused', function (err) { // // replication paused (e.g. replication up to date, user went offline) // console.log('paused'); // }).on('active', function () { // // replicate resumed (e.g. new changes replicating, user went back online) // console.log('active'); // }).on('denied', function (err) { // // a document failed to replicate (e.g. due to permissions) // console.log('denied'); // }).on('complete', function (info) { // // handle complete // }).on('error', function (err) { // console.log('sync err'); // console.log(err); // }); } update(id: string = '', rev: string = '', isdelete: boolean = false) { // new : rev ='' // delete : isdelete =true if (!isdelete) { if (id && rev && !isdelete) { // edit } else if (!id && !rev && !isdelete) {// add new this._selectedObj._id = nano_time.now(); } this.db.put(this._selectedObj).then(res => { console.log(res); }).catch(err => { console.log(err); }); } else { if (id && rev) { // delete this.db.remove(id, rev).then(res => { console.log(res); }).catch(err => { console.log(err); }); } else { console.log('NOTHING'); } } } get(id) { if (id) { this.db.get(id).then(res => { this._selectedObj = res as Irolelist; }).catch(err => { console.log(err); }); } else { console.log('empty id'); this._selectedObj = new Orolelist(); } } async loadList() { let maxpage = 10; let offset = 0; let parent = this; let arr = new Array<Irolelist>(); arr = await this.db.allDocs({ limit: maxpage, skip: offset, descending: true, include_docs: true, }).then(res => { for (let index = 0; index < res.rows.length; index++) { const element = res.rows[index].doc; arr.push(element as Irolelist) } console.log('load finished'); return arr; }); //this._arrayObj$ = of(arr).delay(1000); this._arrayObj = arr; } edit(id: string = '', rev: string = '', isdelete: boolean = false) { let dlg = this.dialogService.open(ModalRoleListComponent, { context: { _id: id, _rev: rev, isdelete: isdelete, } }); dlg.onClose.subscribe(result => { if (result ? (result.command == 'update' ? true : false) : false) { this.loadList(); } }); } searchrolename(searchkey) { //return this.db.query('by_timestamp', {endkey: when, descending: true}); let pagesize = 5; let offset = 0; return this.db.query(this.searchrolenameFunc, { startkey: searchkey, endkey: searchkey + '\uffff', descending: true, include_docs: true, limit: pagesize, skip: offset }); } searchrolenameFunc(doc: Irolelist) { if (doc.rolename) { emit(doc.rolename); } } }
<reponame>OCLC-Developer-Network/lbmc # Copyright 2016 OCLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # encoding: utf-8 # Copyright 2016 OCLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module ApplicationHelper def detect_unicode_block(str) matches = Array.new LBMC::LANGUAGES.each do |lang, lang_regex| matches << lang if str =~ lang_regex end puts ; puts matches ; puts matches end def detect_script(str) unicode_blocks = Array.new scripts = Array.new LBMC::LANGUAGES.each do |lang, lang_regex| unicode_blocks << lang if str =~ lang_regex xlang = lang if str =~ lang_regex unless scripts.include?(LBMC::SCRIPT_CODES[xlang]) || lang == "Arabic" || lang == "Cyrillic" if LBMC::NONMARC_LANGUAGES.include?(xlang) scripts << LBMC::SCRIPT_CODES[xlang] end end end if str str.split("").each do |char| if (char >= "\u{3000}" && char <= "\u{FAFF}") || (char >= "\u{FF00}" && char <= "\u{FFEF}") script_code = LBMC::SCRIPT_CODES["CJK"] unless scripts.include?(script_code) scripts << script_code end elsif unicode_blocks.include?("Arabic") if char >= "\u{0600}" && char <= "\u{0671}" script_code = LBMC::SCRIPT_CODES["ARABIC_BAS"] unless scripts.include?(script_code) scripts << script_code end elsif char >= "\u{0672}" && char <= "\u{06FF}" script_code = LBMC::SCRIPT_CODES["ARABIC_EXT"] unless scripts.include?(script_code) scripts << script_code end end elsif (char >= "\u{0400}" && char <= "\u{04FF}") # puts char.ord.to_s(16) if char >= "\u{0410}" && char <= "\u{0450}" script_code = LBMC::SCRIPT_CODES["CYRILLIC_BAS"] unless scripts.include?(script_code) scripts << script_code end else script_code = LBMC::SCRIPT_CODES["CYRILLIC_EXT"] unless scripts.include?(script_code) scripts << script_code end end # elsif (char >= "\u{0460}" && char <= "\u{052F}") || (char >= "\u{0500}" && char <= "\u{052F}") || (char >= "\u{2DE0}" && char <= "\u{2DFF}") || (char >= "\u{A640}" && char <= "\u{A69F}") elsif char == "\u{0400}" || (char >= "\u{0460}" && char <= "\u{0461}") || (char >= "\u{0464}" && char <= "\u{0469}") || (char >= "\u{046C}" && char <= "\u{0471}") || (char >= "\u{0476}" && char <= "\u{048F}") || (char >= "\u{0492}" && char <= "\u{04FF}") script_code = LBMC::SCRIPT_CODES["CYRILLIC_NONMARC"] unless scripts.include?(script_code) scripts << script_code end #elsif (char >= "\u{1200}" && char <= "\u{1399}") || (char >= "\u{2d80}" && char <= "\u{2ddf}") || (char >= "\u{ab00}" && char <= "\u{ab2f}") #script_code = LBMC::SCRIPT_CODES["ETHI"] #unless scripts.include?(script_code) #scripts << script_code # end end end scripts end def create_book_record record = MARC::Record.new record.leader[0,5] = '00000' record.leader[5] = 'n' record.leader[6] = 'a' record.leader[7] = 'm' record.leader[17] = '3' record.leader[18] = 'c' record end def book_fixed_length_data() fde = MARC::ControlField.new('008') fde.value = ''.rjust(40, ' ') now = Time.now year = now.year.to_s[2,2] month = now.month.to_s.rjust(2, '0') day = now.day.to_s.rjust(2, '0') fde.value[0,6] = "#{year}#{month}#{day}" fde.value[6,1] = 's' fde.value[7,4] = now.year.to_s fde.value[11,4] = ' ' fde.value[15,3] = 'xx ' fde.value[18,1] = ' ' fde.value[19,1] = ' ' fde.value[22,1] = ' ' fde.value[23,1] = ' ' fde.value[24,1] = ' ' fde.value[28,1] = ' ' fde.value[29,1] = '0' fde.value[30,1] = '0' fde.value[31,1] = '0' fde.value[33,1] = 'u' fde.value[34,1] = ' ' fde.value[35,3] = ' ' fde.value[38,1] = ' ' fde.value[39,1] = 'd' fde end def publication_date_is_positive_number?(publication_date) /^-?[1-9]\d*$/ =~ publication_date end def marc_record_from_params(record, params) # puts ; puts params.inspect ; puts marc_record = record # If the record value wasn't a MARC record ...create an instance of one, initialize 008 string and add an 040 for the OCLC symbol unless record.kind_of?(MARC::Record) # Create an instance of a MARC record marc_record = create_book_record # Initialize 008 marc_record << book_fixed_length_data() # Add the client OCLC symbol to the 040, maintaining conventional subfield order a, b, e, c, [d] field_tag = "040" field_array = Array.new subfield_hash = Hash.new subfield_hash["a"] = params[:oclc_symbol] subfield_hash["b"] = 'eng' subfield_hash["e"] = 'rda' subfield_hash["c"] = params[:oclc_symbol] field_hash = create_field_hash('a', ' ', ' ', subfield_hash) field_array.push(field_hash) update_field(marc_record, field_tag, field_array) end # CONTROL FIELDS unless params[:language].nil? language_code = '%-3.3s' % params[:language] update_control_field_value(marc_record, '008', 35, language_code) end unless params[:country_of_publication].nil? country_code = '%-3.3s' % params[:country_of_publication] update_control_field_value(marc_record, '008', 15, country_code) end pd = params[:publication_date] unless params[:pd1].nil? pd = params[:pd1] end unless pd.nil? if publication_date_is_positive_number?(pd) if params[:calendar_select].nil? || params[:calendar_select] == "gregorian" pd = pd.rjust(4, '0') else pd = pd[0..2]+"u" end update_control_field_value(marc_record, '008', 7, pd) end end # NON-LATIN SETUP v880_fields = Array.new v066_subfields = Array.new # AUTHOR MAIN ENTRY # Delete any existing author main entries delete_field(marc_record, ['100','110']) # Set the default first indicator for the title title_indicator_1 = '0' # If the author array has at least one value ... unless params[:author].empty? ainc = 0 # For each author params[:author].each do |author| # Get the first author that does not include non-Latin characters and treat it as the author main entry unless author.to_s == "" author_languages = detect_script(author) if author_languages.length == 0 param_text = 'author_field_'+ainc.to_s param_sym = param_text.to_sym field_tag = params[param_sym] field_indicator_1 = '1' if field_tag == "110" field_indicator_1 = '2' end field_array = Array.new subfield_hash = Hash.new subfield_hash["a"] = author field_hash = create_field_hash('a', field_indicator_1, ' ', subfield_hash) field_array.push(field_hash) update_field(marc_record, field_tag, field_array) # reset the title first indicator indicating the presence of a main entry title_indicator_1 = '1' # remove this author from the params[author] array params[:author].delete_at(ainc) # Quit looping through authors break end end ainc += 1 end end # AUTHOR ADDED ENTRIES # Delete any existing 700 and 710 entries and any 066s or 880s delete_field(marc_record, ['700','710','066','880']) # If there entries left in the author parameter array .. if params[:author].length > 0 aeinc = 0 v700s = Array.new v710s = Array.new params[:author].each do |a| unless a.empty? af = "author_field_"+aeinc.to_s if params[af] == "100" v700s.push(a) else v710s.push(a) end aeinc += 1 end end if v700s.length > 0 field_tag = "700" field_array = Array.new v700s.each do |v700| subfield_hash = Hash.new subfield_hash["a"] = v700 author_languages = detect_script(v700) if author_languages.length > 0 v066_subfields.concat author_languages # if an author main entry hasn't already been set, swap the field tag if title_indicator_1 == '0' field_tag = "100" title_indicator_1 = '1' else field_tag = "700" end subfield_hash["6"] = field_tag+'-00/'+author_languages[0] field_hash = create_field_hash('6', '1', ' ', subfield_hash) v880_fields.push(field_hash) else field_hash = create_field_hash('a', '1', ' ', subfield_hash) field_array.push(field_hash) end end if field_array.length > 0 update_field(marc_record, field_tag, field_array) end end if v710s.length > 0 field_tag = "710" field_array = Array.new v710s.each do |v710| subfield_hash = Hash.new subfield_hash["a"] = v710 author_languages = detect_script(v710) if author_languages.length > 0 v066_subfields.concat author_languages # if an author main entry hasn't already been set, swap the field tag if title_indicator_1 == '0' field_tag = "110" title_indicator_1 = '1' else field_tag = "710" end subfield_hash["6"] = field_tag+'-00/'+author_languages[0] field_hash = create_field_hash('6', '2', ' ', subfield_hash) v880_fields.push(field_hash) else field_hash = create_field_hash('a', '2', ' ', subfield_hash) field_array.push(field_hash) end end if field_array.length > 0 update_field(marc_record, field_tag, field_array) end end end # TITLE # Remove 245's delete_field(marc_record, ['245']) # Detect languages of the title string title_languages = detect_script(params[:title]) if title_languages.length > 0 # the title is in one or more non-Latin scripts # add language codes to the 066 subfield value array v066_subfields.concat title_languages # add a 245 with placeholder value and a pointer to an 880 field_tag = "245" field_array = Array.new subfield_hash = Hash.new subfield_hash["6"] = '880-01' subfield_hash["a"] = '<>' field_hash = create_field_hash('6', title_indicator_1, '0', subfield_hash) field_array.push(field_hash) update_field(marc_record, field_tag, field_array) # add an 880 with field tag, indicators, and subfields to the v880s array field_hash = Hash.new subfield_hash = Hash.new subfield_hash["a"] = params[:title] subfield_hash["6"] = '245-01/'+title_languages[0] field_hash = create_field_hash('6', title_indicator_1, '0', subfield_hash) v880_fields.push(field_hash) else # title is in Latin script only field_tag = "245" field_array = Array.new subfield_hash = Hash.new subfield_hash["a"] = params[:title] field_hash = create_field_hash('a', title_indicator_1, '0', subfield_hash) field_array.push(field_hash) update_field(marc_record, field_tag, field_array) end # PUBLICATION DATA field_tag = "264" field_array = Array.new subfield_hash = Hash.new unless params[:place_of_publication].to_s == '' subfield_hash["a"] = params[:place_of_publication] end unless params[:publisher].to_s == '' subfield_hash["b"] = params[:publisher] end unless params[:publication_date].to_s == '' subfield_hash["c"] = params[:publication_date] end field_hash = create_field_hash('', ' ', '1', subfield_hash) place_of_publication_languages = detect_script(params[:place_of_publication]) publisher_languages = detect_script(params[:publisher]) publication_date_languages = detect_script(params[:publication_date]) if place_of_publication_languages.length > 0 || publisher_languages.length > 0 || publication_date_languages.length > 0 publisher_v066 = Array.new publisher_v066.concat place_of_publication_languages publisher_v066.concat publisher_languages publisher_v066.concat publication_date_languages # add to 880s subfield_hash["6"] = field_tag+'-00/'+publisher_v066[0] field_hash = create_field_hash('6', ' ', '1', subfield_hash) v880_fields.push(field_hash) else unless subfield_hash.empty? field_hash = create_field_hash('', ' ', '1', subfield_hash) field_array.push(field_hash) end end update_field(marc_record, field_tag, field_array) # EXTENT if params[:extent].length > 0 field_tag = "300" field_array = Array.new subfield_hash = Hash.new subfield_hash["a"] = params[:extent] extent_languages = detect_script(params[:extent]) if extent_languages.length > 0 # add to 880s subfield_hash["6"] = field_tag+'-00/'+extent_languages[0] field_hash = create_field_hash('6', ' ', ' ', subfield_hash) v880_fields.push(field_hash) else field_hash = create_field_hash('a', ' ', ' ', subfield_hash) field_array.push(field_hash) end update_field(marc_record, field_tag, field_array) end # RDA CONTENT, MEDIA, AND CARRIER TYPE field_tag = "336" field_array = Array.new subfield_hash = Hash.new subfield_hash["a"] = "text" subfield_hash["b"] = "txt" subfield_hash["2"] = "rdacontent" field_hash = create_field_hash('a', ' ', ' ', subfield_hash) field_array.push(field_hash) update_field(marc_record, field_tag, field_array) field_tag = "337" field_array = Array.new subfield_hash = Hash.new subfield_hash["a"] = "unmediated" subfield_hash["b"] = "n" subfield_hash["2"] = "rdamedia" field_hash = create_field_hash('a', ' ', ' ', subfield_hash) field_array.push(field_hash) update_field(marc_record, field_tag, field_array) field_tag = "338" field_array = Array.new subfield_hash = Hash.new subfield_hash["a"] = "volume" subfield_hash["b"] = "nc" subfield_hash["2"] = "rdacarrier" field_hash = create_field_hash('a', ' ', ' ', subfield_hash) field_array.push(field_hash) update_field(marc_record, field_tag, field_array) # SUBJECTS # Define subject tags we care about subject_tags = Array.new(['600','610','611','630','648','650','651','653','655']) # Remove any existing subjects delete_field(marc_record, subject_tags) # Create empty arrays to hold different types of subjects subject_hash = Hash.new subject_tags.each do |st| subject_hash[st.to_s] = Array.new end # Step through the subjects parameter array and add its value to a subject_hash based on its corresponding subjects_type array value if params[:subject].kind_of?(Array) sinc = 0 params[:subject].each do |s| unless s.empty? field_tag = '653' unless params[:subject_type][sinc].nil? field_tag = params[:subject_type][sinc] end subfield_hash = Hash.new if params[:subject_raw][sinc].include?("$") subject_subfields = params[:subject_raw][sinc].split('$') subject_subfields.each do |ss| subfield_hash[ss[0]] = ss[1..ss.length] end else subfield_hash['a'] = s end if field_tag != '653' subfield_hash['2'] = 'fast' subfield_hash['0'] = params[:subject_id][sinc] end field_indicator_1 = '0' field_indicator_2 = ' ' unless params[:subject_indicator][sinc].nil? || field_tag == '653' field_indicator_1 = params[:subject_indicator][sinc] field_indicator_2 = '7' end if subfield_hash.has_key?("a") subject_languages = detect_script(s) if subject_languages.length > 0 # add to 880s subfield_hash["6"] = field_tag+'-00/'+extent_languages[0] field_hash = create_field_hash('6', field_indicator_1, field_indicator_2, subfield_hash) v880_fields.push(field_hash) else field_hash = create_field_hash('a', field_indicator_1, field_indicator_2, subfield_hash) subject_hash[field_tag].push(field_hash) sinc += 1 end end end end end # Step through the subject hash by tag and add arrays of fields field_default_subfield = 'a' subject_hash.each do |key, value| if subject_hash[key].length > 0 update_field(marc_record, key, subject_hash[key]) end end # ADD 066 SUBFIELDS unless v066_subfields.empty? v066_subfields = v066_subfields.uniq field_tag = "066" field_array = Array.new subfield_hash = Hash.new subfield_hash['c'] = v066_subfields field_hash = create_field_hash('c', ' ', ' ', subfield_hash) field_array.push(field_hash) update_field(marc_record, field_tag, field_array) end # ADD 880 FIELDS unless v880_fields.empty? field_tag = "880" update_field(marc_record, field_tag, v880_fields) end # ISBN unless params[:isbn].to_s == '' field_tag = "020" field_array = Array.new params[:isbn].each do |isbn| isbn = isbn.tr("-","") unless isbn.empty? subfield_hash = Hash.new subfield_hash["a"] = isbn field_hash = create_field_hash('a', ' ', ' ', subfield_hash) field_array.push(field_hash) end end unless field_array.empty? update_field(marc_record, field_tag, field_array) end end # RETURN MARC RECORD # puts ; puts marc_record ; puts marc_record end def sort_subfields(marc_record, data_field_number) marc_record[data_field_number].subfields.sort_by! {|subfield| subfield.code} end def update_control_field_value(marc_record, control_field_number, starting_position, new_value) control_field = marc_record[control_field_number] control_field.value[starting_position,new_value.length] = new_value end def delete_field(marc_record, data_field_number_array) data_field_number_array.each do |data_field_number| data_field = marc_record[data_field_number] unless data_field.nil? # data_field is not nil ... # remove all occurrences of data_field from marc_record marc_record.each_by_tag(data_field_number) do |field| marc_record.fields.delete(field) end end end end def create_field_hash(default_subfield, i1, i2, subfield_hash) field_hash = Hash.new field_hash["default_subfield"] = default_subfield field_hash["indicator"] = Hash.new field_hash["indicator"]["1"] = i1 field_hash["indicator"]["2"] = i2 field_hash["subfield"] = Hash.new subfield_hash.each do |key, value| unless value.to_s == "" field_hash["subfield"][key.to_s] = value end end field_hash end def update_field(marc_record, field_tag, field_array) # Create a new data field object for the given tag data_field = marc_record[field_tag] # Does at least one occurrence of the data_field currently exist? unless data_field.nil? # data_field is not nil ... # remove all occurrences of data_field from marc_record marc_record.each_by_tag(field_tag) do |field| marc_record.fields.delete(field) end end # Only do more if the field_array is an array if field_array.kind_of?(Array) # For each item in the field_array field_array.each do |item| # Expect it to be a hash (containing the default subfield, indicators, and a hash of subfields) if item.kind_of?(Hash) unless item['subfield'].empty? # If the default subfield's hash value is an array, add each as repeating subfields in the same field if item['subfield'][item['default_subfield']].kind_of?(Array) inc = 0 field = MARC::DataField.new(field_tag, item['indicator']['1'], item['indicator']['2'], MARC::Subfield.new(item['default_subfield'],item['subfield'][item['default_subfield']][0])) item['subfield'][item['default_subfield']].each do |i| if inc > 0 field.append(MARC::Subfield.new(item['default_subfield'],i)) end inc += 1 end # Otherwise, instantiate the field with the default subfield else field = MARC::DataField.new(field_tag, item['indicator']['1'], item['indicator']['2'], MARC::Subfield.new(item['default_subfield'],item['subfield'][item['default_subfield']])) end # add non-default subfields to the field item['subfield'].each do |key, value| if key != item['default_subfield'] unless item['subfield'][key].nil? field.append(MARC::Subfield.new(key,item['subfield'][key])) end end end # add the field to the record marc_record << field end # unless item['subfield' is empty end # if item is a hash end # each field_array end # if field_array is an array end # update_field # Will respond true if the data field is not null and the given subfield code # is the only subfield in the data field def field_is_deletable?(data_field, subfield_code) # Assume the given subfield_code matches the only subfield in the record. # If any others are encounterd, return false. data_field.subfields.reduce(true) do |deletable, subfield| deletable = false if subfield.code != subfield_code deletable end end # Will respond true if the 040 subfield a in the MARC record matches the provided OCLC symbol def belongs_to_current_user?(marc_record, oclc_symbol) oclc_symbol == marc_record['040']['a'] end # will response true if the id is in the session[:record_created] array def is_app_created(id) if session[:records_created] and session[:records_created].include?(id) result = true end end # Escapes HTML def h(text) Rack::Utils.escape_html(text) end end
package pulse.math; import pulse.properties.NumericProperty; /** * Implements the midpoint integration scheme for the evaluation of definite * integrals. * * @see <a href="https://en.wikipedia.org/wiki/Midpoint_method">Wiki page</a> * */ public abstract class MidpointIntegrator extends FixedIntervalIntegrator { public MidpointIntegrator(Segment bounds, NumericProperty segments) { super(bounds, segments); } public MidpointIntegrator(Segment bounds) { super(bounds); } /** * Performs the integration according to the midpoint scheme. This scheme * should be used when the function is not well-defined at either of the * integration bounds. */ @Override public double integrate() { final double a = getBounds().getMinimum(); final int points = (int) getIntegrationSegments().getValue(); double sum = 0; double h = stepSize(); for (int i = 0; i < points; i++) { sum += integrand(a + (i + 0.5) * h) * h; } return sum; } }
#ifndef H_LINGO_TEST_TYPES #define H_LINGO_TEST_TYPES #include <lingo/platform/wchar.hpp> #include "tuple_matrix.hpp" #include <cstdint> #include <cstddef> #include <tuple> #include <utility> namespace lingo { namespace test { /*using unit_types = std::tuple< char, #ifdef __cpp_char8_t char8_t, #endif wchar_t, char16_t, char32_t #ifndef _DEBUG signed char, unsigned char, int_least8_t, int_least16_t, int_least32_t int_least64_t uint_least8_t, uint_least16_t, uint_least32_t, uint_least64_t #endif >;*/ using unit_least_64_types = std::tuple< #if WCHAR_BITS >= 64 wchar_t #endif >; using unit_least_32_types = tuple_concat_t< std::tuple< #if WCHAR_BITS >= 32 && WCHAR_BITS < 64 wchar_t, #endif char32_t>, unit_least_64_types>; using unit_least_16_types = tuple_concat_t< std::tuple< #if WCHAR_BITS >= 16 && WCHAR_BITS < 32 wchar_t, #endif char16_t>, unit_least_32_types>; using unit_least_8_types = tuple_concat_t< std::tuple< #if WCHAR_BITS < 16 wchar_t, #endif #ifdef __cpp_char8_t char8_t, #endif char>, unit_least_16_types>; using unit_types = unit_least_8_types; using unit_type_matrix = tuple_matrix_t<unit_types, unit_types>; } } #endif
package arouter.dawn.zju.edu.module_mine.ui.setting; import com.alibaba.android.arouter.facade.annotation.Route; import arouter.dawn.zju.edu.module_mine.R; import baselib.base.BaseActivity; import baselib.constants.RouteConstants; /** * @Auther: Dawn * @Date: 2018/11/22 22:01 * @Description: * 设置页面 */ @Route(path = RouteConstants.AROUTER_SETTING_SETTING) public class SettingActivity extends BaseActivity { @Override protected void initView() { getSupportFragmentManager().beginTransaction() .add(R.id.container, new SettingFragment()).commit(); } @Override protected int getLayoutId() { return R.layout.activity_setting; } @Override protected boolean showHomeAsUp() { return true; } @Override protected void bindPresenter() { } }
<reponame>kira8565/WebAdmin<gh_stars>0 package com.xstudio.models.sys; import java.util.ArrayList; import java.util.Date; import java.util.List; public class SysUserExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ public SysUserExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andCommentIsNull() { addCriterion("comment is null"); return (Criteria) this; } public Criteria andCommentIsNotNull() { addCriterion("comment is not null"); return (Criteria) this; } public Criteria andCommentEqualTo(String value) { addCriterion("comment =", value, "comment"); return (Criteria) this; } public Criteria andCommentNotEqualTo(String value) { addCriterion("comment <>", value, "comment"); return (Criteria) this; } public Criteria andCommentGreaterThan(String value) { addCriterion("comment >", value, "comment"); return (Criteria) this; } public Criteria andCommentGreaterThanOrEqualTo(String value) { addCriterion("comment >=", value, "comment"); return (Criteria) this; } public Criteria andCommentLessThan(String value) { addCriterion("comment <", value, "comment"); return (Criteria) this; } public Criteria andCommentLessThanOrEqualTo(String value) { addCriterion("comment <=", value, "comment"); return (Criteria) this; } public Criteria andCommentLike(String value) { addCriterion("comment like", value, "comment"); return (Criteria) this; } public Criteria andCommentNotLike(String value) { addCriterion("comment not like", value, "comment"); return (Criteria) this; } public Criteria andCommentIn(List<String> values) { addCriterion("comment in", values, "comment"); return (Criteria) this; } public Criteria andCommentNotIn(List<String> values) { addCriterion("comment not in", values, "comment"); return (Criteria) this; } public Criteria andCommentBetween(String value1, String value2) { addCriterion("comment between", value1, value2, "comment"); return (Criteria) this; } public Criteria andCommentNotBetween(String value1, String value2) { addCriterion("comment not between", value1, value2, "comment"); return (Criteria) this; } public Criteria andEnabledIsNull() { addCriterion("enabled is null"); return (Criteria) this; } public Criteria andEnabledIsNotNull() { addCriterion("enabled is not null"); return (Criteria) this; } public Criteria andEnabledEqualTo(Integer value) { addCriterion("enabled =", value, "enabled"); return (Criteria) this; } public Criteria andEnabledNotEqualTo(Integer value) { addCriterion("enabled <>", value, "enabled"); return (Criteria) this; } public Criteria andEnabledGreaterThan(Integer value) { addCriterion("enabled >", value, "enabled"); return (Criteria) this; } public Criteria andEnabledGreaterThanOrEqualTo(Integer value) { addCriterion("enabled >=", value, "enabled"); return (Criteria) this; } public Criteria andEnabledLessThan(Integer value) { addCriterion("enabled <", value, "enabled"); return (Criteria) this; } public Criteria andEnabledLessThanOrEqualTo(Integer value) { addCriterion("enabled <=", value, "enabled"); return (Criteria) this; } public Criteria andEnabledIn(List<Integer> values) { addCriterion("enabled in", values, "enabled"); return (Criteria) this; } public Criteria andEnabledNotIn(List<Integer> values) { addCriterion("enabled not in", values, "enabled"); return (Criteria) this; } public Criteria andEnabledBetween(Integer value1, Integer value2) { addCriterion("enabled between", value1, value2, "enabled"); return (Criteria) this; } public Criteria andEnabledNotBetween(Integer value1, Integer value2) { addCriterion("enabled not between", value1, value2, "enabled"); return (Criteria) this; } public Criteria andPasswordIsNull() { addCriterion("password is null"); return (Criteria) this; } public Criteria andPasswordIsNotNull() { addCriterion("password is not null"); return (Criteria) this; } public Criteria andPasswordEqualTo(String value) { addCriterion("password =", value, "password"); return (Criteria) this; } public Criteria andPasswordNotEqualTo(String value) { addCriterion("password <>", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThan(String value) { addCriterion("password >", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThanOrEqualTo(String value) { addCriterion("password >=", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThan(String value) { addCriterion("password <", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThanOrEqualTo(String value) { addCriterion("password <=", value, "password"); return (Criteria) this; } public Criteria andPasswordLike(String value) { addCriterion("password like", value, "password"); return (Criteria) this; } public Criteria andPasswordNotLike(String value) { addCriterion("password not like", value, "password"); return (Criteria) this; } public Criteria andPasswordIn(List<String> values) { addCriterion("password in", values, "password"); return (Criteria) this; } public Criteria andPasswordNotIn(List<String> values) { addCriterion("password not in", values, "password"); return (Criteria) this; } public Criteria andPasswordBetween(String value1, String value2) { addCriterion("password between", value1, value2, "password"); return (Criteria) this; } public Criteria andPasswordNotBetween(String value1, String value2) { addCriterion("password not between", value1, value2, "password"); return (Criteria) this; } public Criteria andAccountsIsNull() { addCriterion("accounts is null"); return (Criteria) this; } public Criteria andAccountsIsNotNull() { addCriterion("accounts is not null"); return (Criteria) this; } public Criteria andAccountsEqualTo(String value) { addCriterion("accounts =", value, "accounts"); return (Criteria) this; } public Criteria andAccountsNotEqualTo(String value) { addCriterion("accounts <>", value, "accounts"); return (Criteria) this; } public Criteria andAccountsGreaterThan(String value) { addCriterion("accounts >", value, "accounts"); return (Criteria) this; } public Criteria andAccountsGreaterThanOrEqualTo(String value) { addCriterion("accounts >=", value, "accounts"); return (Criteria) this; } public Criteria andAccountsLessThan(String value) { addCriterion("accounts <", value, "accounts"); return (Criteria) this; } public Criteria andAccountsLessThanOrEqualTo(String value) { addCriterion("accounts <=", value, "accounts"); return (Criteria) this; } public Criteria andAccountsLike(String value) { addCriterion("accounts like", value, "accounts"); return (Criteria) this; } public Criteria andAccountsNotLike(String value) { addCriterion("accounts not like", value, "accounts"); return (Criteria) this; } public Criteria andAccountsIn(List<String> values) { addCriterion("accounts in", values, "accounts"); return (Criteria) this; } public Criteria andAccountsNotIn(List<String> values) { addCriterion("accounts not in", values, "accounts"); return (Criteria) this; } public Criteria andAccountsBetween(String value1, String value2) { addCriterion("accounts between", value1, value2, "accounts"); return (Criteria) this; } public Criteria andAccountsNotBetween(String value1, String value2) { addCriterion("accounts not between", value1, value2, "accounts"); return (Criteria) this; } public Criteria andCreatetimeIsNull() { addCriterion("createtime is null"); return (Criteria) this; } public Criteria andCreatetimeIsNotNull() { addCriterion("createtime is not null"); return (Criteria) this; } public Criteria andCreatetimeEqualTo(Date value) { addCriterion("createtime =", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeNotEqualTo(Date value) { addCriterion("createtime <>", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeGreaterThan(Date value) { addCriterion("createtime >", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeGreaterThanOrEqualTo(Date value) { addCriterion("createtime >=", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeLessThan(Date value) { addCriterion("createtime <", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeLessThanOrEqualTo(Date value) { addCriterion("createtime <=", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeIn(List<Date> values) { addCriterion("createtime in", values, "createtime"); return (Criteria) this; } public Criteria andCreatetimeNotIn(List<Date> values) { addCriterion("createtime not in", values, "createtime"); return (Criteria) this; } public Criteria andCreatetimeBetween(Date value1, Date value2) { addCriterion("createtime between", value1, value2, "createtime"); return (Criteria) this; } public Criteria andCreatetimeNotBetween(Date value1, Date value2) { addCriterion("createtime not between", value1, value2, "createtime"); return (Criteria) this; } public Criteria andCreatorIsNull() { addCriterion("creator is null"); return (Criteria) this; } public Criteria andCreatorIsNotNull() { addCriterion("creator is not null"); return (Criteria) this; } public Criteria andCreatorEqualTo(String value) { addCriterion("creator =", value, "creator"); return (Criteria) this; } public Criteria andCreatorNotEqualTo(String value) { addCriterion("creator <>", value, "creator"); return (Criteria) this; } public Criteria andCreatorGreaterThan(String value) { addCriterion("creator >", value, "creator"); return (Criteria) this; } public Criteria andCreatorGreaterThanOrEqualTo(String value) { addCriterion("creator >=", value, "creator"); return (Criteria) this; } public Criteria andCreatorLessThan(String value) { addCriterion("creator <", value, "creator"); return (Criteria) this; } public Criteria andCreatorLessThanOrEqualTo(String value) { addCriterion("creator <=", value, "creator"); return (Criteria) this; } public Criteria andCreatorLike(String value) { addCriterion("creator like", value, "creator"); return (Criteria) this; } public Criteria andCreatorNotLike(String value) { addCriterion("creator not like", value, "creator"); return (Criteria) this; } public Criteria andCreatorIn(List<String> values) { addCriterion("creator in", values, "creator"); return (Criteria) this; } public Criteria andCreatorNotIn(List<String> values) { addCriterion("creator not in", values, "creator"); return (Criteria) this; } public Criteria andCreatorBetween(String value1, String value2) { addCriterion("creator between", value1, value2, "creator"); return (Criteria) this; } public Criteria andCreatorNotBetween(String value1, String value2) { addCriterion("creator not between", value1, value2, "creator"); return (Criteria) this; } public Criteria andUpdatetimeIsNull() { addCriterion("updatetime is null"); return (Criteria) this; } public Criteria andUpdatetimeIsNotNull() { addCriterion("updatetime is not null"); return (Criteria) this; } public Criteria andUpdatetimeEqualTo(Date value) { addCriterion("updatetime =", value, "updatetime"); return (Criteria) this; } public Criteria andUpdatetimeNotEqualTo(Date value) { addCriterion("updatetime <>", value, "updatetime"); return (Criteria) this; } public Criteria andUpdatetimeGreaterThan(Date value) { addCriterion("updatetime >", value, "updatetime"); return (Criteria) this; } public Criteria andUpdatetimeGreaterThanOrEqualTo(Date value) { addCriterion("updatetime >=", value, "updatetime"); return (Criteria) this; } public Criteria andUpdatetimeLessThan(Date value) { addCriterion("updatetime <", value, "updatetime"); return (Criteria) this; } public Criteria andUpdatetimeLessThanOrEqualTo(Date value) { addCriterion("updatetime <=", value, "updatetime"); return (Criteria) this; } public Criteria andUpdatetimeIn(List<Date> values) { addCriterion("updatetime in", values, "updatetime"); return (Criteria) this; } public Criteria andUpdatetimeNotIn(List<Date> values) { addCriterion("updatetime not in", values, "updatetime"); return (Criteria) this; } public Criteria andUpdatetimeBetween(Date value1, Date value2) { addCriterion("updatetime between", value1, value2, "updatetime"); return (Criteria) this; } public Criteria andUpdatetimeNotBetween(Date value1, Date value2) { addCriterion("updatetime not between", value1, value2, "updatetime"); return (Criteria) this; } public Criteria andUpdatorIsNull() { addCriterion("updator is null"); return (Criteria) this; } public Criteria andUpdatorIsNotNull() { addCriterion("updator is not null"); return (Criteria) this; } public Criteria andUpdatorEqualTo(String value) { addCriterion("updator =", value, "updator"); return (Criteria) this; } public Criteria andUpdatorNotEqualTo(String value) { addCriterion("updator <>", value, "updator"); return (Criteria) this; } public Criteria andUpdatorGreaterThan(String value) { addCriterion("updator >", value, "updator"); return (Criteria) this; } public Criteria andUpdatorGreaterThanOrEqualTo(String value) { addCriterion("updator >=", value, "updator"); return (Criteria) this; } public Criteria andUpdatorLessThan(String value) { addCriterion("updator <", value, "updator"); return (Criteria) this; } public Criteria andUpdatorLessThanOrEqualTo(String value) { addCriterion("updator <=", value, "updator"); return (Criteria) this; } public Criteria andUpdatorLike(String value) { addCriterion("updator like", value, "updator"); return (Criteria) this; } public Criteria andUpdatorNotLike(String value) { addCriterion("updator not like", value, "updator"); return (Criteria) this; } public Criteria andUpdatorIn(List<String> values) { addCriterion("updator in", values, "updator"); return (Criteria) this; } public Criteria andUpdatorNotIn(List<String> values) { addCriterion("updator not in", values, "updator"); return (Criteria) this; } public Criteria andUpdatorBetween(String value1, String value2) { addCriterion("updator between", value1, value2, "updator"); return (Criteria) this; } public Criteria andUpdatorNotBetween(String value1, String value2) { addCriterion("updator not between", value1, value2, "updator"); return (Criteria) this; } public Criteria andTelIsNull() { addCriterion("tel is null"); return (Criteria) this; } public Criteria andTelIsNotNull() { addCriterion("tel is not null"); return (Criteria) this; } public Criteria andTelEqualTo(String value) { addCriterion("tel =", value, "tel"); return (Criteria) this; } public Criteria andTelNotEqualTo(String value) { addCriterion("tel <>", value, "tel"); return (Criteria) this; } public Criteria andTelGreaterThan(String value) { addCriterion("tel >", value, "tel"); return (Criteria) this; } public Criteria andTelGreaterThanOrEqualTo(String value) { addCriterion("tel >=", value, "tel"); return (Criteria) this; } public Criteria andTelLessThan(String value) { addCriterion("tel <", value, "tel"); return (Criteria) this; } public Criteria andTelLessThanOrEqualTo(String value) { addCriterion("tel <=", value, "tel"); return (Criteria) this; } public Criteria andTelLike(String value) { addCriterion("tel like", value, "tel"); return (Criteria) this; } public Criteria andTelNotLike(String value) { addCriterion("tel not like", value, "tel"); return (Criteria) this; } public Criteria andTelIn(List<String> values) { addCriterion("tel in", values, "tel"); return (Criteria) this; } public Criteria andTelNotIn(List<String> values) { addCriterion("tel not in", values, "tel"); return (Criteria) this; } public Criteria andTelBetween(String value1, String value2) { addCriterion("tel between", value1, value2, "tel"); return (Criteria) this; } public Criteria andTelNotBetween(String value1, String value2) { addCriterion("tel not between", value1, value2, "tel"); return (Criteria) this; } public Criteria andSexIsNull() { addCriterion("sex is null"); return (Criteria) this; } public Criteria andSexIsNotNull() { addCriterion("sex is not null"); return (Criteria) this; } public Criteria andSexEqualTo(Integer value) { addCriterion("sex =", value, "sex"); return (Criteria) this; } public Criteria andSexNotEqualTo(Integer value) { addCriterion("sex <>", value, "sex"); return (Criteria) this; } public Criteria andSexGreaterThan(Integer value) { addCriterion("sex >", value, "sex"); return (Criteria) this; } public Criteria andSexGreaterThanOrEqualTo(Integer value) { addCriterion("sex >=", value, "sex"); return (Criteria) this; } public Criteria andSexLessThan(Integer value) { addCriterion("sex <", value, "sex"); return (Criteria) this; } public Criteria andSexLessThanOrEqualTo(Integer value) { addCriterion("sex <=", value, "sex"); return (Criteria) this; } public Criteria andSexIn(List<Integer> values) { addCriterion("sex in", values, "sex"); return (Criteria) this; } public Criteria andSexNotIn(List<Integer> values) { addCriterion("sex not in", values, "sex"); return (Criteria) this; } public Criteria andSexBetween(Integer value1, Integer value2) { addCriterion("sex between", value1, value2, "sex"); return (Criteria) this; } public Criteria andSexNotBetween(Integer value1, Integer value2) { addCriterion("sex not between", value1, value2, "sex"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table sys_user * * @mbggenerated do_not_delete_during_merge Wed Jun 08 13:09:16 CST 2016 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table sys_user * * @mbggenerated Wed Jun 08 13:09:16 CST 2016 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
# Define a function for trajectory algorithms def trajectory_algorithm(start_point, end_point): # Set the dampening parameter, which determines how far the ball moves in each step d = 0.1 # Find the distance between start and end points dist = (end_point[0] - start_point[0])**2 + (end_point[1] - start_point[1])**2 # Define a loop to iterate through while dist > (d ** 2): # Move the ball closer to the end point start_point[0] = start_point[0] + ((end_point[0] - start_point[0]) * d) start_point[1] = start_point[1] + ((end_point[1] - start_point[1]) * d) # Redefine the distance for the next iteration dist = (end_point[0] - start_point[0])**2 + (end_point[1] - start_point[1])**2 # Return the final point return start_point
<reponame>elliotsegler/altimeter<gh_stars>10-100 """Resource for CloudWatchEvents EventBusses""" from typing import Type from botocore.client import BaseClient from altimeter.aws.resource.resource_spec import ListFromAWSResult from altimeter.aws.resource.events import EventsResourceSpec from altimeter.core.graph.field.scalar_field import ScalarField from altimeter.core.graph.schema import Schema class EventBusResourceSpec(EventsResourceSpec): """Resource for CloudWatchEvents EventBus""" type_name = "event-bus" schema = Schema(ScalarField("Name"), ScalarField("Arn"), ScalarField("Policy", optional=True),) @classmethod def list_from_aws( cls: Type["EventBusResourceSpec"], client: BaseClient, account_id: str, region: str ) -> ListFromAWSResult: """Return a dict of dicts of the format: {'event_bus_1_arn': {event_bus_1_dict}, 'event_bus_2_arn': {event_bus_2_dict}, ...} Where the dicts represent results from describe_event_bus.""" resp = client.describe_event_bus() arn = resp["Arn"] event_busses = {arn: resp} return ListFromAWSResult(resources=event_busses)
<reponame>parti-coop/demosx<gh_stars>10-100 package seoul.democracy.features.E_11_실행관리; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.test.context.support.WithUserDetails; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import seoul.democracy.action.domain.Action; import seoul.democracy.action.dto.ActionDto; import seoul.democracy.action.dto.ActionUpdateDto; import seoul.democracy.action.service.ActionService; import seoul.democracy.common.exception.BadRequestException; import seoul.democracy.common.exception.NotFoundException; import seoul.democracy.issue.domain.Issue; import seoul.democracy.issue.dto.IssueFileDto; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static seoul.democracy.action.dto.ActionDto.projection; import static seoul.democracy.action.predicate.ActionPredicate.equalId; /** * epic : 11. 실행관리 * story: 11.2 관리자는 실행을 수정할 수 있다. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "file:src/test/resources/egovframework/spring-test/context-*.xml", "file:src/main/webapp/WEB-INF/config/egovframework/springmvc/egov-com-*.xml" }) @Transactional @Rollback @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class S_11_2_관리자는_실행을_수정할_수_있다 { private final static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm"); private final static String ip = "127.0.0.2"; private MockHttpServletRequest request; @Autowired private ActionService actionService; private ActionUpdateDto updateDto; private Long notExistsId = 999L; @Before public void setUp() throws Exception { request = new MockHttpServletRequest(); request.setRemoteAddr(ip); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); updateDto = ActionUpdateDto.of(201L, "/images/test-thumbnail.jpg", "경제", "실행 등록합니다.", "실행 내용입니다.", Issue.Status.CLOSED, Arrays.asList(IssueFileDto.of("파일1", "file1"), IssueFileDto.of("파일2", "file2")), Arrays.asList(1L, 101L), null); } /** * 1. 관리자는 실행을 수정할 수 있다. */ @Test @WithUserDetails("<EMAIL>") public void T_1_관리자는_실행을_수정할_수_있다() { final String now = LocalDateTime.now().format(dateTimeFormatter); Action action = actionService.update(updateDto); assertThat(action.getId(), is(notNullValue())); ActionDto actionDto = actionService.getAction(equalId(action.getId()), projection, true, true); assertThat(actionDto.getModifiedDate().format(dateTimeFormatter), is(now)); assertThat(actionDto.getModifiedBy().getEmail(), is("<EMAIL>")); assertThat(actionDto.getModifiedIp(), is(ip)); assertThat(actionDto.getCategory().getName(), is(updateDto.getCategory())); assertThat(actionDto.getStats().getViewCount(), is(0L)); assertThat(actionDto.getThumbnail(), is(updateDto.getThumbnail())); assertThat(actionDto.getTitle(), is(updateDto.getTitle())); assertThat(actionDto.getContent(), is(updateDto.getContent())); assertThat(actionDto.getStatus(), is(updateDto.getStatus())); assertThat(actionDto.getFiles(), contains(updateDto.getFiles().toArray(new IssueFileDto[0]))); assertThat(actionDto.getRelations(), contains(updateDto.getRelations().toArray(new Long[0]))); } /** * 2. 매니저는 실행을 수정할 수 없다. */ @Test(expected = AccessDeniedException.class) @WithUserDetails("<EMAIL>") public void T_2_매니저는_실행을_수정할_수_없다() { actionService.update(updateDto); } /** * 3. 사용자는 실행을 수정할 수 없다. */ @Test(expected = AccessDeniedException.class) @WithUserDetails("<EMAIL>") public void T_3_사용자는_실행을_수정할_수_없다() { actionService.update(updateDto); } /** * 4. 없는 실행을 수정할 수 없다. */ @Test(expected = NotFoundException.class) @WithUserDetails("<EMAIL>") public void T_4_없는_실행을_등록할_수_없다() { updateDto.setId(notExistsId); actionService.update(updateDto); } /** * 5. 존재하지 않는 항목을 연관으로 수정할 수 없다. */ @Test(expected = BadRequestException.class) @WithUserDetails("<EMAIL>") public void T_5_존재하지_않는_항목을_연관으로_수정할_수_없다() { Long notExistsRelation = 999L; updateDto.setRelations(Arrays.asList(1L, 101L, notExistsRelation)); actionService.update(updateDto); } }
package mechconstruct.network; import io.netty.buffer.ByteBuf; import mechconstruct.MechConstruct; import mechconstruct.blockentities.BlockEntityMachine; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; public class PacketGuiTabMachine implements IMessage { public BlockPos pos; public int tab; public PacketGuiTabMachine() { } public PacketGuiTabMachine(BlockPos pos, int tab) { this.pos = pos; this.tab = tab; } @Override public void fromBytes(ByteBuf buf) { pos = BlockPos.fromLong(buf.readLong()); tab = buf.readInt(); } @Override public void toBytes(ByteBuf buf) { buf.writeLong(pos.toLong()); buf.writeInt(tab); } public static class Handler implements IMessageHandler<PacketGuiTabMachine, IMessage> { @Override public IMessage onMessage(PacketGuiTabMachine message, MessageContext ctx) { FMLCommonHandler.instance().getWorldThread(ctx.netHandler).addScheduledTask(() -> handle(message, ctx)); return null; } private void handle(PacketGuiTabMachine message, MessageContext context) { EntityPlayerMP playerEntity = context.getServerHandler().player; World world = playerEntity.getEntityWorld(); if (world.isBlockLoaded(message.pos)) { BlockEntityMachine machine = (BlockEntityMachine) world.getTileEntity(message.pos); machine.setCurrentTab(message.tab); playerEntity.openGui(MechConstruct.instance, 0, playerEntity.getEntityWorld(), message.pos.getX(), message.pos.getY(), message.pos.getZ()); } } } }
#!/usr/bin/env bash flask db upgrade flask run --host=0.0.0.0
#!/bin/sh -e VERSION=$1 if [ -z "$VERSION" ]; then echo "NO VERSION" exit 1 fi echo "Building Apache CouchDB $VERSION" RELDIR=apache-couchdb-$VERSION # make release dir rm -rf $RELDIR mkdir $RELDIR CURRENT_BRANCH=`git rev-parse --abbrev-ref HEAD` # copy sources over git archive $CURRENT_BRANCH | tar -xC $RELDIR/ mkdir $RELDIR/src cd src/ for repo in *; do cd $repo mkdir ../../$RELDIR/src/$repo git_ish=`git symbolic-ref -q --short HEAD || git describe --tags --exact-match` git archive $git_ish | tar -xC ../../$RELDIR/src/$repo/ cd .. done cd .. # update version # actual version detection TBD perl -pi -e "s/\{vsn, git\}/\{vsn, \"$VERSION\"\}/" $RELDIR/src/*/src/*.app.src # create THANKS file if test -e .git; then OS=`uname -s` case "$OS" in Linux|CYGWIN*) # GNU sed SED_ERE_FLAG=-r ;; *) # BSD sed SED_ERE_FLAG=-E ;; esac sed -e "/^#.*/d" THANKS.in > $RELDIR/THANKS CONTRIB_EMAIL_SED_COMMAND="s/^[[:blank:]]{5}[[:digit:]]+[[:blank:]]/ * /" git shortlog -se 6c976bd..HEAD \ | grep -v @apache.org \ | sed $SED_ERE_FLAG -e "$CONTRIB_EMAIL_SED_COMMAND" >> $RELDIR/THANKS echo "" >> $RELDIR/THANKS # simplest portable newline echo "For a list of authors see the \`AUTHORS\` file." >> $RELDIR/THANKS fi
import React from 'react'; import { Link } from 'react-router-dom'; import moment from 'moment'; import { Tip, ActionButtons, Button, Label } from 'modules/common/components'; import { Row as CommonRow } from '../../common/components'; import { Form } from './'; class Row extends CommonRow { constructor(props) { super(props); this.duplicateForm = this.duplicateForm.bind(this); } renderForm(props) { return <Form {...props} />; } duplicateForm() { const { object, duplicateForm } = this.props; duplicateForm(object._id); } renderActions() { const { object } = this.props; return ( <td> <ActionButtons> <Tip text="Manage Fields"> <Link to={`/fields/manage/form/${object._id}`}> <Button btnStyle="link" icon="navicon-round" /> </Link> </Tip> <Tip text="Duplicate"> <Button btnStyle="link" onClick={this.duplicateForm} icon="ios-browsers" /> </Tip> {this.renderEditAction()} {this.renderRemoveAction()} </ActionButtons> </td> ); } render() { const { object } = this.props; return ( <tr> <td>{object.title}</td> <td> <Label>{object.code}</Label> </td> <td>{object.description}</td> <td>{moment(object.createdAt).format('DD MMM YYYY')}</td> {this.renderActions()} </tr> ); } } export default Row;
/* global angular */ /** * @ngdoc module * @name compile-template * @module compile-template */ const moduleName = 'buildium.angular-ui.compiletemplate'; angular.module(moduleName, []) /** * @ngdoc directive * @name bdCompileTemplate * @module compile-template * * @restrict A * * @description * Compiles the HTML that is bound using ng-bing-html. * * * @example <example module="compileTemplateExample" name="bd-compile-template"> <file name="index.html"> <div ng-controller="ExampleController"> <label>Title <input type="text" ng-model="title" /> </label> <label>Compile Template <textarea ng-model="dynamicHtml" style="display: block"></textarea> </label> <h2>Result</h2> <div ng-bind-html="dynamicHtml" bd-compile-template></div> </div> </file> <file name="script.js"> angular.module('compileTemplateExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.title = 'Hello world'; $scope.dynamicHtml = '<b>{{title}}</b>' }]); </file> </example> * */ .directive('bdCompileTemplate', ['$compile', '$parse', function BdCompileTemplate($compile, $parse) { const directive = {}; directive.restrict = 'A'; directive.link = function link(scope, element, attr) { const parsed = $parse(attr.ngBindHtml); function getStringValue() { return (parsed(scope) || '').toString(); } //Recompile if the template changes scope.$watch(getStringValue, () => { $compile(element, null, -9999)(scope); //The -9999 makes it skip directives so that we do not recompile ourselves }); }; return directive; }]); module.exports = moduleName;
<filename>src/app/views/management/activities.component.ts import { Component, OnInit } from '@angular/core'; import { UserMaster } from '../../models/users/user-master'; import { SecureAuth } from '../../helpers/secure-auth'; import { Router } from '@angular/router'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { Activities } from '../../../assets/resources/activities'; @Component({ selector: 'app-activities', templateUrl: './activities.component.html' }) export class ActivitiesComponent implements OnInit { id: any; _title: string; _user: UserMaster; _userTypes: [] = []; _states: [] = []; _districts: [] = []; _talukas: [] = []; _cities: [] = []; _decryptedUser: any; _secureAuth: SecureAuth; _isMobileValid: boolean; _isEmailValid: boolean; _userObject: any public gridData: any[] = Activities; constructor(private _router: Router, private modalService: NgbModal) { const selectedClient = localStorage.getItem('selectedclient'); const parsedClientJson = JSON.parse(selectedClient); if (parsedClientJson) { let obj = atob(parsedClientJson); this._userObject = JSON.parse(obj); let sidebarRootElement = document.getElementById('root'); sidebarRootElement.style.display = 'none'; let sidebarChildElement = document.getElementById('child'); sidebarChildElement.style.display = 'block'; } else { this._title = "Add"; } this._user = new UserMaster(); } ngOnInit() {} AddAnUpdate(modal: any) { this.modalService.open(modal, { backdrop: true, centered: true }) } BackToList() { this._router.navigate(["/manage/client-management"]); } }
#!/bin/bash #Copyright (c) 2016, Allgeyer Tobias, Aumann Florian, Borella Jocelyn, Karrenbauer Oliver, Marek Felix, Meissner Pascal, Stroh Daniel, Trautmann Jeremias #All rights reserved. # #Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # #1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # #2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other #materials provided with the distribution. # #3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific #prior written permission. # #THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED #WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, #INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR #PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # read http://unix.stackexchange.com/questions/17116/prevent-pane-window-from-closing-when-command-completes-tmux # Starts additional simulation modules that cannot be launched before gazebo is running # wait for gazebo and rviz sleep 5 # while [[ ! $(rosservice list | grep gaz) ]]; do sleep 1; done; # while [[ ! $(xwininfo -root -all | grep rviz) ]]; do sleep 1; done; # make sure log folder exist, so all modules start safely export logFolder=~/log mkdir -p ${logFolder} #Starts scene recognition, pose prediction and provides a pane for interfaces with object localization simulation. tmux new-window -n 'ism' tmux send-keys -t asr:ism 'script -c "roslaunch --wait asr_recognizer_prediction_ism rp_ism_node.launch" -f '"${logFolder}"'/ism.log' C-m tmux split-window -t asr:ism tmux send-keys -t asr:ism.1 'echo Perform service calls to asr_fake_object_recognition from here.' C-m #Starts next-best-view calculation and world model. tmux new-window -n 'nbv' tmux send-keys -t asr:nbv 'script -c "roslaunch --wait asr_next_best_view next_best_view_core_sim.launch" -f '"${logFolder}"'/nbv.log' C-m tmux split-window -t asr:nbv tmux send-keys -t asr:nbv.1 'script -c "roslaunch --wait asr_world_model world_model.launch" -f '"${logFolder}"'/world_model.log' C-m #Starts visualization server to publish the room model. tmux new-window -n 'viz_server' tmux send-keys -t asr:viz_server 'script -c "roslaunch --wait asr_visualization_server visualization.launch" -f '"${logFolder}"'/viz_server.log' C-m #Starts state machine that controls all other components, required for active scene recognition. tmux new-window -n 'state_machine' tmux send-keys -t asr:state_machine 'script -c "roslaunch --wait asr_state_machine scene_exploration_sim.launch" -f '"${logFolder}"'/state_machine.log' C-m #Starts direct_search_manager that handles the direct search tmux new-window -n 'direct_search_manager' tmux send-keys -t asr:direct_search_manager 'script -c "roslaunch --wait asr_direct_search_manager direct_search_manager.launch" -f '"${logFolder}"'/direct_search_manager.log' C-m
let mongoose = require('mongoose'); var todayDate = new Date(); let scoreSchema = mongoose.Schema({ username: { type: String, required: true }, userId: { type: String, required: true }, score: { type: Number, required: true }, wordleNumber: { type: Number, required: true }, scoreId: { type: String, required: true }, scorePattern: { type: String, }, serverId: { type: String, required: true }, date: { type: Date, default: `${todayDate.getFullYear()}-${todayDate.getMonth()}-${todayDate.getDate()}` } }); let Score = module.exports = mongoose.model('Score', scoreSchema);
<filename>node_modules/concurrently/dist/src/flow-control/input-handler.js "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.InputHandler = void 0; const Rx = __importStar(require("rxjs")); const operators_1 = require("rxjs/operators"); const defaults = __importStar(require("../defaults")); /** * Sends input from concurrently through to commands. * * Input can start with a command identifier, in which case it will be sent to that specific command. * For instance, `0:bla` will send `bla` to command at index `0`, and `server:stop` will send `stop` * to command with name `server`. * * If the input doesn't start with a command identifier, it is then always sent to the default target. */ class InputHandler { constructor({ defaultInputTarget, inputStream, pauseInputStreamOnFinish, logger }) { this.logger = logger; this.defaultInputTarget = defaultInputTarget || defaults.defaultInputTarget; this.inputStream = inputStream; this.pauseInputStreamOnFinish = pauseInputStreamOnFinish !== false; } handle(commands) { if (!this.inputStream) { return { commands }; } Rx.fromEvent(this.inputStream, 'data') .pipe((0, operators_1.map)(data => data.toString())) .subscribe(data => { const dataParts = data.split(/:(.+)/); const targetId = dataParts.length > 1 ? dataParts[0] : this.defaultInputTarget; const input = dataParts[1] || data; const command = commands.find(command => (command.name === targetId || command.index.toString() === targetId.toString())); if (command && command.stdin) { command.stdin.write(input); } else { this.logger.logGlobalEvent(`Unable to find command ${targetId}, or it has no stdin open\n`); } }); return { commands, onFinish: () => { if (this.pauseInputStreamOnFinish) { // https://github.com/kimmobrunfeldt/concurrently/issues/252 this.inputStream.pause(); } }, }; } } exports.InputHandler = InputHandler; ;
<gh_stars>0 package mempool import ( "math/big" "sort" "testing" "github.com/nspcc-dev/neo-go/pkg/config/netmode" "github.com/nspcc-dev/neo-go/pkg/core/transaction" "github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/vm/opcode" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type FeerStub struct { feePerByte int64 } var balance = big.NewInt(10000000) func (fs *FeerStub) FeePerByte() int64 { return fs.feePerByte } func (fs *FeerStub) GetUtilityTokenBalance(uint160 util.Uint160) *big.Int { return balance } func testMemPoolAddRemoveWithFeer(t *testing.T, fs Feer) { mp := New(10) tx := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx.Nonce = 0 tx.Signers = []transaction.Signer{{Account: util.Uint160{1, 2, 3}}} _, ok := mp.TryGetValue(tx.Hash()) require.Equal(t, false, ok) require.NoError(t, mp.Add(tx, fs)) // Re-adding should fail. require.Error(t, mp.Add(tx, fs)) tx2, ok := mp.TryGetValue(tx.Hash()) require.Equal(t, true, ok) require.Equal(t, tx, tx2) mp.Remove(tx.Hash()) _, ok = mp.TryGetValue(tx.Hash()) require.Equal(t, false, ok) // Make sure nothing left in the mempool after removal. assert.Equal(t, 0, len(mp.verifiedMap)) assert.Equal(t, 0, len(mp.verifiedTxes)) } func TestMemPoolAddRemove(t *testing.T) { var fs = &FeerStub{} testMemPoolAddRemoveWithFeer(t, fs) } func TestOverCapacity(t *testing.T) { var fs = &FeerStub{} const mempoolSize = 10 mp := New(mempoolSize) for i := 0; i < mempoolSize; i++ { tx := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx.Nonce = uint32(i) tx.Signers = []transaction.Signer{{Account: util.Uint160{1, 2, 3}}} require.NoError(t, mp.Add(tx, fs)) } txcnt := uint32(mempoolSize) require.Equal(t, mempoolSize, mp.Count()) require.Equal(t, true, sort.IsSorted(sort.Reverse(mp.verifiedTxes))) bigScript := make([]byte, 64) bigScript[0] = byte(opcode.PUSH1) bigScript[1] = byte(opcode.RET) // Fees are also prioritized. for i := 0; i < mempoolSize; i++ { tx := transaction.New(netmode.UnitTestNet, bigScript, 0) tx.NetworkFee = 10000 tx.Nonce = txcnt tx.Signers = []transaction.Signer{{Account: util.Uint160{1, 2, 3}}} txcnt++ // size is ~90, networkFee is 10000 => feePerByte is 119 require.NoError(t, mp.Add(tx, fs)) require.Equal(t, mempoolSize, mp.Count()) require.Equal(t, true, sort.IsSorted(sort.Reverse(mp.verifiedTxes))) } // Less prioritized txes are not allowed anymore. tx := transaction.New(netmode.UnitTestNet, bigScript, 0) tx.NetworkFee = 100 tx.Nonce = txcnt tx.Signers = []transaction.Signer{{Account: util.Uint160{1, 2, 3}}} txcnt++ require.Error(t, mp.Add(tx, fs)) require.Equal(t, mempoolSize, mp.Count()) require.Equal(t, true, sort.IsSorted(sort.Reverse(mp.verifiedTxes))) // Low net fee, but higher per-byte fee is still a better combination. tx = transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx.Nonce = txcnt tx.NetworkFee = 7000 tx.Signers = []transaction.Signer{{Account: util.Uint160{1, 2, 3}}} txcnt++ // size is ~51 (small script), networkFee is 7000 (<10000) // => feePerByte is 137 (>119) require.NoError(t, mp.Add(tx, fs)) require.Equal(t, mempoolSize, mp.Count()) require.Equal(t, true, sort.IsSorted(sort.Reverse(mp.verifiedTxes))) // High priority always wins over low priority. for i := 0; i < mempoolSize; i++ { tx := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx.NetworkFee = 8000 tx.Nonce = txcnt tx.Signers = []transaction.Signer{{Account: util.Uint160{1, 2, 3}}} txcnt++ require.NoError(t, mp.Add(tx, fs)) require.Equal(t, mempoolSize, mp.Count()) require.Equal(t, true, sort.IsSorted(sort.Reverse(mp.verifiedTxes))) } // Good luck with low priority now. tx = transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx.Nonce = txcnt tx.NetworkFee = 7000 tx.Signers = []transaction.Signer{{Account: util.Uint160{1, 2, 3}}} require.Error(t, mp.Add(tx, fs)) require.Equal(t, mempoolSize, mp.Count()) require.Equal(t, true, sort.IsSorted(sort.Reverse(mp.verifiedTxes))) } func TestGetVerified(t *testing.T) { var fs = &FeerStub{} const mempoolSize = 10 mp := New(mempoolSize) txes := make([]*transaction.Transaction, 0, mempoolSize) for i := 0; i < mempoolSize; i++ { tx := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx.Nonce = uint32(i) tx.Signers = []transaction.Signer{{Account: util.Uint160{1, 2, 3}}} txes = append(txes, tx) require.NoError(t, mp.Add(tx, fs)) } require.Equal(t, mempoolSize, mp.Count()) verTxes := mp.GetVerifiedTransactions() require.Equal(t, mempoolSize, len(verTxes)) require.ElementsMatch(t, txes, verTxes) for _, tx := range txes { mp.Remove(tx.Hash()) } verTxes = mp.GetVerifiedTransactions() require.Equal(t, 0, len(verTxes)) } func TestRemoveStale(t *testing.T) { var fs = &FeerStub{} const mempoolSize = 10 mp := New(mempoolSize) txes1 := make([]*transaction.Transaction, 0, mempoolSize/2) txes2 := make([]*transaction.Transaction, 0, mempoolSize/2) for i := 0; i < mempoolSize; i++ { tx := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx.Nonce = uint32(i) tx.Signers = []transaction.Signer{{Account: util.Uint160{1, 2, 3}}} if i%2 == 0 { txes1 = append(txes1, tx) } else { txes2 = append(txes2, tx) } require.NoError(t, mp.Add(tx, fs)) } require.Equal(t, mempoolSize, mp.Count()) mp.RemoveStale(func(t *transaction.Transaction) bool { for _, tx := range txes2 { if tx == t { return true } } return false }, &FeerStub{}) require.Equal(t, mempoolSize/2, mp.Count()) verTxes := mp.GetVerifiedTransactions() for _, txf := range verTxes { require.NotContains(t, txes1, txf) require.Contains(t, txes2, txf) } } func TestMemPoolFees(t *testing.T) { mp := New(10) sender0 := util.Uint160{1, 2, 3} tx0 := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx0.NetworkFee = balance.Int64() + 1 tx0.Signers = []transaction.Signer{{Account: sender0}} // insufficient funds to add transaction, and balance shouldn't be stored require.Equal(t, false, mp.Verify(tx0, &FeerStub{})) require.Error(t, mp.Add(tx0, &FeerStub{})) require.Equal(t, 0, len(mp.fees)) balancePart := new(big.Int).Div(balance, big.NewInt(4)) // no problems with adding another transaction with lower fee tx1 := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx1.NetworkFee = balancePart.Int64() tx1.Signers = []transaction.Signer{{Account: sender0}} require.NoError(t, mp.Add(tx1, &FeerStub{})) require.Equal(t, 1, len(mp.fees)) require.Equal(t, utilityBalanceAndFees{ balance: balance, feeSum: big.NewInt(tx1.NetworkFee), }, mp.fees[sender0]) // balance shouldn't change after adding one more transaction tx2 := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx2.NetworkFee = new(big.Int).Sub(balance, balancePart).Int64() tx2.Signers = []transaction.Signer{{Account: sender0}} require.NoError(t, mp.Add(tx2, &FeerStub{})) require.Equal(t, 2, len(mp.verifiedTxes)) require.Equal(t, 1, len(mp.fees)) require.Equal(t, utilityBalanceAndFees{ balance: balance, feeSum: balance, }, mp.fees[sender0]) // can't add more transactions as we don't have enough GAS tx3 := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx3.NetworkFee = 1 tx3.Signers = []transaction.Signer{{Account: sender0}} require.Equal(t, false, mp.Verify(tx3, &FeerStub{})) require.Error(t, mp.Add(tx3, &FeerStub{})) require.Equal(t, 1, len(mp.fees)) require.Equal(t, utilityBalanceAndFees{ balance: balance, feeSum: balance, }, mp.fees[sender0]) // check whether sender's fee updates correctly mp.RemoveStale(func(t *transaction.Transaction) bool { if t == tx2 { return true } return false }, &FeerStub{}) require.Equal(t, 1, len(mp.fees)) require.Equal(t, utilityBalanceAndFees{ balance: balance, feeSum: big.NewInt(tx2.NetworkFee), }, mp.fees[sender0]) // there should be nothing left mp.RemoveStale(func(t *transaction.Transaction) bool { if t == tx3 { return true } return false }, &FeerStub{}) require.Equal(t, 0, len(mp.fees)) } func TestMempoolItemsOrder(t *testing.T) { sender0 := util.Uint160{1, 2, 3} tx1 := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx1.NetworkFee = new(big.Int).Div(balance, big.NewInt(8)).Int64() tx1.Signers = []transaction.Signer{{Account: sender0}} tx1.Attributes = []transaction.Attribute{{Type: transaction.HighPriority}} item1 := &item{txn: tx1} tx2 := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx2.NetworkFee = new(big.Int).Div(balance, big.NewInt(16)).Int64() tx2.Signers = []transaction.Signer{{Account: sender0}} tx2.Attributes = []transaction.Attribute{{Type: transaction.HighPriority}} item2 := &item{txn: tx2} tx3 := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx3.NetworkFee = new(big.Int).Div(balance, big.NewInt(2)).Int64() tx3.Signers = []transaction.Signer{{Account: sender0}} item3 := &item{txn: tx3} tx4 := transaction.New(netmode.UnitTestNet, []byte{byte(opcode.PUSH1)}, 0) tx4.NetworkFee = new(big.Int).Div(balance, big.NewInt(4)).Int64() tx4.Signers = []transaction.Signer{{Account: sender0}} item4 := &item{txn: tx4} require.True(t, item1.CompareTo(item2) > 0) require.True(t, item2.CompareTo(item1) < 0) require.True(t, item1.CompareTo(item3) > 0) require.True(t, item3.CompareTo(item1) < 0) require.True(t, item1.CompareTo(item4) > 0) require.True(t, item4.CompareTo(item1) < 0) require.True(t, item2.CompareTo(item3) > 0) require.True(t, item3.CompareTo(item2) < 0) require.True(t, item2.CompareTo(item4) > 0) require.True(t, item4.CompareTo(item2) < 0) require.True(t, item3.CompareTo(item4) > 0) require.True(t, item4.CompareTo(item3) < 0) }
#!/usr/bin/env bash # This script is designed to provision a new vm and start kyma with cli. It takes the following optional positional parameters: # custom VM image --image flag: Use this flag to specify the custom image for provisioning vms. If no flag is provided, the latest custom image is used. # Kyma version to install --kyma-version flag: Use this flag to indicate which Kyma version the CLI should install (default: same as the CLI) set -o errexit readonly SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" KYMA_PROJECT_DIR=${KYMA_PROJECT_DIR:-"/home/prow/go/src/github.com/kyma-project"} # shellcheck source=prow/scripts/lib/gcloud.sh source "${SCRIPT_DIR}/lib/gcloud.sh" # shellcheck source=prow/scripts/lib/log.sh source "${SCRIPT_DIR}/lib/log.sh" cleanup() { ARG=$? log::info "Removing instance cli-integration-test-${RANDOM_ID}" date gcloud compute instances delete --zone="${ZONE}" "cli-integration-test-${RANDOM_ID}" || true ### Workaround: not failing the job regardless of the vm deletion result exit $ARG } function testCustomImage() { CUSTOM_IMAGE="$1" IMAGE_EXISTS=$(gcloud compute images list --filter "name:${CUSTOM_IMAGE}" | tail -n +2 | awk '{print $1}') if [[ -z "$IMAGE_EXISTS" ]]; then log::error "${CUSTOM_IMAGE} is invalid, it is not available in GCP images list, the script will terminate ..." && exit 1 fi } gcloud::authenticate "${GOOGLE_APPLICATION_CREDENTIALS}" RANDOM_ID=$(openssl rand -hex 4) LABELS="" if [[ -z "${PULL_NUMBER}" ]]; then LABELS=(--labels "branch=$PULL_BASE_REF,job-name=cli-integration") else LABELS=(--labels "pull-number=$PULL_NUMBER,job-name=cli-integration") fi # Support configuration via ENV vars (can be be overwritten by CLI args) KUBERNETES_RUNTIME="${KUBERNETES_RUNTIME:=minikube}" TEST_SUITE="${TEST_SUITE:=default}" POSITIONAL=() while [[ $# -gt 0 ]] do key="$1" case ${key} in --image|-i) IMAGE="$2" testCustomImage "${IMAGE}" shift 2 ;; --kyma-version|-kv) SOURCE="--source $2" shift 2 ;; --kubernetes-runtime|-kr) KUBERNETES_RUNTIME="$2" shift 2 ;; --test-suite|-ts) TEST_SUITE="$2" shift 2 ;; --*) echo "Unknown flag ${1}" exit 1 ;; *) # unknown option POSITIONAL+=("$1") # save it in an array for later shift # past argument ;; esac done set -- "${POSITIONAL[@]}" # restore positional parameters if [[ -z "$IMAGE" ]]; then log::info "Provisioning vm using the latest default custom image ..." date IMAGE=$(gcloud compute images list --sort-by "~creationTimestamp" \ --filter "family:custom images AND labels.default:yes" --limit=1 | tail -n +2 | awk '{print $1}') if [[ -z "$IMAGE" ]]; then log::error "There are no default custom images, the script will exit ..." && exit 1 fi fi ZONE_LIMIT=${ZONE_LIMIT:-5} EU_ZONES=$(gcloud compute zones list --filter="name~europe" --limit="${ZONE_LIMIT}" | tail -n +2 | awk '{print $1}') for ZONE in ${EU_ZONES}; do log::info "Attempting to create a new instance named cli-integration-test-${RANDOM_ID} in zone ${ZONE} using image ${IMAGE}" date gcloud compute instances create "cli-integration-test-${RANDOM_ID}" \ --metadata enable-oslogin=TRUE \ --image "${IMAGE}" \ --machine-type n1-standard-4 \ --zone "${ZONE}" \ --boot-disk-size 30 "${LABELS[@]}" &&\ log::info "Created cli-integration-test-${RANDOM_ID} in zone ${ZONE}" && break log::error "Could not create machine in zone ${ZONE}" done || exit 1 trap cleanup exit INT log::info "Building Kyma CLI" date cd "${KYMA_PROJECT_DIR}/cli" make build-linux gcloud compute ssh --quiet --zone="${ZONE}" "cli-integration-test-${RANDOM_ID}" -- "mkdir \$HOME/bin" log::info "Copying Kyma CLI to the instance" date for i in $(seq 1 5); do [[ ${i} -gt 1 ]] && echo 'Retrying in 15 seconds..' && sleep 15; gcloud compute scp --quiet --zone="${ZONE}" "${KYMA_PROJECT_DIR}/cli/bin/kyma-linux" "cli-integration-test-${RANDOM_ID}":~/bin/kyma && break; [[ ${i} -ge 5 ]] && echo "Failed after $i attempts." && exit 1 done; gcloud compute ssh --quiet --zone="${ZONE}" "cli-integration-test-${RANDOM_ID}" -- "sudo cp \$HOME/bin/kyma /usr/local/bin/kyma" # Provision Kubernetes runtime log::info "Provisioning Kubernetes runtime '$KUBERNETES_RUNTIME'" date if [ "$KUBERNETES_RUNTIME" = 'minikube' ]; then gcloud compute ssh --quiet --zone="${ZONE}" "cli-integration-test-${RANDOM_ID}" -- "yes | sudo kyma provision minikube --non-interactive" else gcloud compute ssh --quiet --zone="${ZONE}" "cli-integration-test-${RANDOM_ID}" -- "yes | sudo kyma alpha provision k3s --non-interactive" fi # Run test suite # shellcheck disable=SC1090 source "${SCRIPT_DIR}/lib/clitests.sh" if clitests::testSuiteExists "$TEST_SUITE"; then clitests::execute "$TEST_SUITE" "${ZONE}" "cli-integration-test-${RANDOM_ID}" "$SOURCE" else log::error "Test suite '${TEST_SUITE}' not found" fi
#! /bin/bash -e # rs-attach-ebs-volume.sh <server_id> <ec2_ebs_volume_href> <device> . "$HOME/.rightscale/rs_api_config.sh" . "$HOME/.rightscale/rs_api_creds.sh" [[ ! $1 ]] && echo 'No server ID provided, exiting.' && exit 1 [[ ! $2 ]] && echo 'No EC2 EBS volume HRef provided, exiting.' && exit 1 [[ ! $3 ]] && echo 'No device name provided, exiting.' && exit 1 server_id="$1" ec2_ebs_volume_href="$2" device="$3" api_url="https://my.rightscale.com/api/acct/$rs_api_account_id/servers/$server_id/current/attach_volume" echo "[API $rs_api_version] POST: $api_url" api_result=$(curl -s -S -v -X POST -H "X-API-VERSION: $rs_api_version" -b "$rs_api_cookie" \ -d "server[ec2_ebs_volume_href]=$ec2_ebs_volume_href" \ -d "server[device]=$device" \ $api_url 2>&1) case $api_result in *"204 No Content"*) echo "EBS volume, $ec2_ebs_volume_href successfully attached to server, $server_id on $device." exit ;; *"EC2 error"*) echo "$api_result" | grep "EC2 error" exit 2 ;; *) echo 'Server start request failed!' echo "$api_result" exit 1 ;; esac
//============================================================================ // Copyright 2009-2020 ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // //============================================================================ #ifndef VIEWER_SRC_TEXTPAGER_TEXTPAGERSEARCHINTERFACE_HPP_ #define VIEWER_SRC_TEXTPAGER_TEXTPAGERSEARCHINTERFACE_HPP_ #include "AbstractTextEditSearchInterface.hpp" #include "TextPagerCursor.hpp" class TextPagerEdit; class TextPagerSearchInterface : public AbstractTextEditSearchInterface { public: TextPagerSearchInterface()= default; void setEditor(TextPagerEdit* e) {editor_=e;} bool findString (QString str, bool highlightAll, QTextDocument::FindFlags findFlags, QTextCursor::MoveOperation move, int iteration,StringMatchMode::Mode matchMode) override; void automaticSearchForKeywords(bool) override; void refreshSearch() override; void clearHighlights() override; void disableHighlights() override; void enableHighlights() override; bool highlightsNeedSearch() override {return false;} void gotoLastLine() override; protected: TextPagerCursor::MoveOperation translateCursorMoveOp(QTextCursor::MoveOperation move); TextPagerEdit *editor_{nullptr}; }; #endif /* VIEWER_SRC_TEXTPAGER_TEXTPAGERSEARCHINTERFACE_HPP_ */
<reponame>KimJeongYeon/jack2_android /* Copyright (C) 2001 <NAME> Copyright (C) 2004-2008 Grame This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "JackSystemDeps.h" #include "JackRestartThreadedDriver.h" #include "JackException.h" namespace Jack { bool JackRestartThreadedDriver::Execute() { try { // Keep running even in case of error while (fThread.GetStatus() == JackThread::kRunning) { Process(); } return false; } catch (JackNetException& e) { e.PrintMessage(); jack_info("Driver is restarted"); fThread.DropSelfRealTime(); // Thread in kIniting status again... fThread.SetStatus(JackThread::kIniting); if (Init()) { // Thread in kRunning status again... fThread.SetStatus(JackThread::kRunning); return true; } else { return false; } } } } // end of namespace
<filename>packages/ui/src/ResourcePropertyDisplay.tsx import { PropertySchema } from '@medplum/core'; import React from 'react'; import { AddressDisplay } from './AddressDisplay'; import { AttachmentArrayDisplay } from './AttachmentArrayDisplay'; import { AttachmentDisplay } from './AttachmentDisplay'; import { BackboneElementDisplay } from './BackboneElementDisplay'; import { CodeableConceptDisplay } from './CodeableConceptDisplay'; import { ContactPointDisplay } from './ContactPointDisplay'; import { DeviceNameDisplay } from './DeviceNameDisplay'; import { HumanNameDisplay } from './HumanNameDisplay'; import { IdentifierDisplay } from './IdentifierDisplay'; import { PatientLinkDisplay } from './PatientLinkDisplay'; import { ReferenceDisplay } from './ReferenceDisplay'; import { ResourceArrayDisplay } from './ResourceArrayDisplay'; export interface ResourcePropertyDisplayProps { property: PropertySchema; value: any; arrayElement?: boolean; } export function ResourcePropertyDisplay(props: ResourcePropertyDisplayProps) { const property = props.property; const value = props.value; if (property.array && !props.arrayElement) { if (property.type === 'Attachment') { return <AttachmentArrayDisplay values={value} /> } return <ResourceArrayDisplay property={property} values={value} /> } if (!value) { return null; } switch (property.type) { case 'string': case 'canonical': case 'date': case 'dateTime': case 'instant': case 'uri': case 'url': case 'http://hl7.org/fhirpath/System.String': return value; case 'number': case 'integer': case 'positiveInt': case 'unsignedInt': return value; case 'enum': return value; case 'boolean': return value; case 'markdown': return <pre>{value}</pre> case 'Address': return <AddressDisplay value={value} />; case 'Attachment': return <AttachmentDisplay value={value} />; case 'CodeableConcept': return <CodeableConceptDisplay value={value} />; case 'ContactPoint': return <ContactPointDisplay value={value} />; case 'Device_DeviceName': return <DeviceNameDisplay value={value} />; case 'HumanName': return <HumanNameDisplay value={value} />; case 'Identifier': return <IdentifierDisplay value={value} />; case 'Patient_Link': return <PatientLinkDisplay value={value} />; case 'Reference': return <ReferenceDisplay value={value} />; default: return <BackboneElementDisplay property={property} value={value} />; } }
var tuple = require("../lib/tiny-tuple.js"); exports["tuple"] = { setUp: function (done) { done(); }, small: function (test) { var x = tuple(1, 2); test.expect(2); test.equal(x.length, 2, "Should be '2'"); test.equal(Object.isFrozen(x), true, "Should be 'true'"); test.done(); }, large: function (test) { var x = tuple(1, 2, 3, tuple(1, 2)); test.expect(3); test.equal(x.length, 4, "Should be '4'"); test.equal(x[3].length, 2, "Should be '2'"); test.equal(x.extract().length, 5, "Should be '5'"); test.done(); }, proto: function (test) { test.expect(1); test.equal([].constructor === Array, true, "Should be 'true'"); test.done(); } };
public class Employee { private String name; private double salary; private int age; public Employee(String name, double salary, int age) { this.name = name; this.salary = salary; this.age = age; } public String getName() { return this.name; } public double getSalary() { return this.salary; } public int getAge() { return this.age; } public String toString() { String str = String.format("Name: %s, Salary: %.2f, Age: %d", this.name, this.salary, this.age); return str; } }
from __future__ import division import numpy as np import logging from collections import OrderedDict from astropy.extern import six from astropy.nddata.utils import extract_array, subpixel_indices from astropy.coordinates import SkyCoord import astropy.units as apu from astropy import table from astropy.modeling import Fittable2DModel from astropy.modeling.parameters import Parameter from astropy.modeling.fitting import LevMarLSQFitter import warnings logger = logging.getLogger('astropyp.phot.psf') psf_flags = OrderedDict([ (128, 'Bad Pixel'), # Bad pixels (64, 'Edge'), # Edge is closer than aperture radius (32, '<not used>'), (16, '<not used>'), (8, 'Low Peak'), # Amplitude is below minimum (4, 'Low Flux'), # Flux is below minimum (2, 'Elliptical'), # Source is elliptical, not circular (1, 'Crowded') # nearby source, requires group photometry ]) def select_psf_sources(img_data, catalog, aper_radius=None, min_flux=None, min_amplitude=None, min_dist=None, max_ratio=None, edge_dist=None, verbose=True, units='deg', badpix_flags=[], flag_max=0): """ From an image and a list of sources, generate a list of high SNR sources with circular profiles that are likely to be good sources to generate the psf. Parameters ---------- img_data: array-like The image data catalog: `~astropyp.catalog.ImageCatalog` Catalog of sources. The properties x, y, ra, dec, aper_flux, peak, a, b are all required to be mapped to the appropriate columns in the catalog.sources table. aper_radius: integer Radius to use to calculate psf flux. min_flux: integer, optional Minimum flux to be considered an valid source. If no ``min_flux`` is given then no cuts will be made based on the total flux min_aplitude: integer, optional Minimum peak flux of a pixel in for a psf source. If no ``min_amplitude`` is given then no cuts will be made based on maximum flux in a pixel. min_dist: integer, optional Minimum distance (in pixels) to the nearest neighbor for a PSF source. If no ``min_dist`` is specified the function will set ``min_dist=3*aperture_radius``. max_ratio: float Maximum ratio of a sources two axes to be considered sufficiently elliptical. To calculate max_ratio, ``a`` and ``b`` must be specified. The default value is the median(a/b)+stddev(a/b) for all of the sources edge_dist: integer, optional Maximum distance (in pixels) from the center of a source to the edge of the image. This defaults to the ``aperture_radius``+1. verbose: bool, optional Whether or not to log the results of the various cuts. *Default value is True* units: string or `~astropy.units.unit` Units of the ra and dec columns. *Default value is 'deg'* badpix_flags: list of strings or list of array-like, optional A list of column names in ``sources`` or a list of arrays with the badpixel flags for each source. *Default is an empty list* flag_max: integer, optional Maximum value of a bad pixel flag to be considered good. *Default value is 0* Returns ------- psf_idx: `~nump.ndarray` Boolean array that matches psf sources selected by the function flags: `~astropy.table.Table` Table of flags for all of the sources """ from scipy import spatial rows = catalog.shape[0] # Only select high signal to noise sources min_flux_flag = ~np.isnan(catalog.aper_flux) if min_flux is not None: min_flux_flag = min_flux_flag & (catalog.aper_flux>min_flux) if min_amplitude is not None: min_amp_flag = catalog.peak>min_amplitude # Eliminate Bad Pixel Sources bad_src_flag = np.ones((rows,), dtype=bool) for flags in badpix_flags: if isinstance(flags, six.string_types): flags = catalog[flags]<=flag_max bad_src_flag = bad_src_flag & flags # Cut out elliptical sources (likely galaxies) if catalog.a is not None and catalog.b is not None: a_b = catalog.b/catalog.a if max_ratio is None: max_ratio = np.median(a_b)-np.std(a_b)*1.5 elliptical_flag = catalog.b/catalog.a> max_ratio # Cut out all sources with a nearby neighbor if min_dist is None: min_dist = 3*aper_radius KDTree = spatial.cKDTree pts = zip(catalog.x,catalog.y) kdt = KDTree(pts) d2, idx = kdt.query(pts,2) distance_flag = d2[:,1]>min_dist # Cut out all source near the edge if edge_dist is None: edge_dist = aper_radius+1 edge_flag = ((catalog.x>edge_dist) & (catalog.y>edge_dist) & (catalog.x<img_data.shape[1]-edge_dist) & (catalog.y<img_data.shape[0]-edge_dist)) # Apply all of the cuts to the table of sources psf_idx = ( min_flux_flag & min_amp_flag & bad_src_flag & elliptical_flag & distance_flag & edge_flag) flags = ( ~bad_src_flag*128+ ~edge_flag*64+ ~min_flux_flag*4+ ~elliptical_flag*2+ ~distance_flag) catalog.sources['pipeline_flags'] = flags # Combine the flags into a table that can be used later flags = table.Table( [min_flux_flag, min_amp_flag, bad_src_flag, elliptical_flag, distance_flag, edge_flag], names=('min_flux', 'min_amp', 'bad_pix', 'ellipse', 'dist', 'edge') ) # If verbose, print information about the cuts if verbose: #level = logger.getEffectiveLevel() #logger.setLevel(logging.INFO) logger.info('Total sources: {0}'.format(rows)), logger.info('Sources with low flux: {0}'.format( rows-np.sum(min_flux_flag))) logger.info('Sources with low amplitude: {0}'.format( rows-np.sum(min_amp_flag))) logger.info('Sources with bad pixels: {0}'.format( rows-np.sum(bad_src_flag))) logger.info('Elliptical sources: {0}'.format( rows-np.sum(elliptical_flag))) logger.info('Source with close neighbors: {0}'.format( rows-np.sum(distance_flag))) logger.info('Sources near an edge: {0}'.format( rows-np.sum(edge_flag))) logger.info('Sources after cuts: {0}'.format(np.sum(psf_idx))), #logger.setLevel(level) return psf_idx, flags def build_psf(img_data, aper_radius, sources=None, x='x', y='y', subsampling=5, combine_mode='median', offset_buffer=3): """ Build a subsampled psf by stacking a list of psf sources and a its source image. Parameters ---------- img_data: array-like Image containing the sources aper_radius: integer Radius of the aperture to use for the psf source. This must be an odd number. sources: `~astropy.table.Table`, optional Table with x,y positions of psf sources. If sources is passed to the function, ``x`` and ``y`` should be the names of the x and y coordinates in the table. x: string or array-like, optional ``x`` can either be a string, the name of the x column in ``sources``, or an array of x coordinates of psf sources. *Defaults to 'x'* y: string or array-like, optional ``y`` can either be a string, the name of the y column in ``sources``, or an array of y coordinates of psf sources. *Defaults to 'y'* subsampling: integer, optional Number of subdivided pixel in the psf for each image pixel. *Defaults value is 5* combine_mode: string, optional Method to combine psf sources to build psf. Can be either "median" or "mean". *Defaults to "median"* offset_buffer: integer Error in image pixels for the center of a given source. This allows the code some leeway to re-center an image based on its subpixels. *Default is 3* """ from astropyp import utils if isinstance(x, six.string_types): x = sources[x] if isinstance(y, six.string_types): y = sources[y] if hasattr(x, 'shape'): rows = x.shape[0] else: rows = len(x) if combine_mode == 'median': combine = np.ma.median elif combine_mode == 'mean': combine = np.ma.mean else: raise Exception( "Invalid combine_mode, you must choose from ['median','mean']") # Load a patch centered on each PSF source and stack them to build the # final PSF src_width = 2*aper_radius+1 patches = [] obj_shape = (src_width, src_width) for n in range(rows): patch, X,Y, new_yx = utils.misc.get_subpixel_patch( img_data, (y[n],x[n]), obj_shape, max_offset=offset_buffer, subsampling=subsampling, normalize=True) if patch is not None: patches.append(patch) else: logger.info("{0} contains NaN values, skipping".format( (new_yx[1],new_yx[0]))) psf = combine(np.dstack(patches), axis=2) # Add a mask to hide values outside the aperture radius radius = aper_radius*subsampling ys, xs = psf.shape yc,xc = (np.array([ys,xs])-1)/2 y,x = np.ogrid[-yc:ys-yc, -xc:xs-xc] mask = x**2+y**2<=radius**2 circle_mask = np.ones(psf.shape) circle_mask[mask]=0 circle_mask psf_array = np.ma.array(psf, mask=circle_mask) return psf_array def perform_psf_photometry(data, catalog, psf, separation=None, verbose=False, fit_position=True, pos_range=0, indices=None, kd_tree=None, exptime=None, pool_size=None): """ Perform PSF photometry on all of the sources in the catalog, or if indices is specified, a subset of sources. Parameters ---------- data: `~numpy.ndarray` Image containing the sources catalog: `~astropyp.catalog.Catalog` Catalog of sources to use. This must contain the x,y keys. psf: `SinglePSF` PSF to use for the fit separation: float, optional Separation (in pixels) for members to be considered part of the same group *Default=1.5*psf width* verbose: bool, optional Whether or not to show info about the fit progress. *Default=False* fit_position: bool, optional Whether or not to fit the position along with the amplitude of each source. *Default=True* pos_range: int, optional Maximum number of pixels (in image pixels) that a sources position can be changed. If ``pos_range=0`` no bounds will be set. *Default=0* indices: `~numpy.ndarray` or string, optional Indices for sources to calculate PSF photometry. It is often advantageous to remove sources with bad pixels and sublinear flux to save processing time. All sources not included in indices will have their psf flux set to NaN. This can either be an array of indices for the positions in self.catalog or the name of a saved index in self.indices kd_tree: `scipy.spatial.KDTree`, optional KD tree containing all of the sources in the catalog exptime: float, optional Exposure time of the image (needed to calculate the psf magnitude). """ import astropyp.catalog # Get the positions and estimated amplitudes of # the sources to fit if indices is not None: positions = zip(catalog.x[indices], catalog.y[indices]) amplitudes = catalog.peak[indices] else: positions = zip(catalog.x, catalog.y) amplitudes = catalog.peak src_count = len(positions) src_indices = np.arange(0,len(catalog.sources),1) all_positions = np.array(zip(catalog.x, catalog.y)) all_amplitudes = catalog.peak total_sources = len(all_amplitudes) src_psfs = [] psf_flux = np.ones((total_sources,))*np.nan psf_flux_err = np.ones((total_sources,))*np.nan psf_x = np.ones((total_sources,))*np.nan psf_y = np.ones((total_sources,))*np.nan new_amplitudes = np.ones((total_sources,))*np.nan # Find nearest neighbors to avoid contamination by nearby sources if separation is not None: if kd_tree is None: from scipy import spatial KDTree = spatial.cKDTree kd_tree = KDTree(all_positions) idx, nidx = astropyp.catalog.find_neighbors(separation, kd_tree=kd_tree) # Set the number of processors to use if pool_size is None: import multiprocessing pool_size = multiprocessing.cpu_count() # Fit each source to the PSF, calcualte its flux, and its new # position if pool_size==1: for n in range(len(positions)): if verbose: #level = logger.getEffectiveLevel() logger.setLevel(logging.INFO) logger.info("Fitting {0}".format(group_id)) #logger.setLevel(level) src_idx = src_indices[indices][n] if separation is not None: n_indices = nidx[idx==src_idx] neighbor_positions = all_positions[n_indices] neighbor_amplitudes = all_amplitudes[n_indices] else: neighbor_positions = [] neighbor_amplitudes = [] src_psf = SinglePSF(psf._psf_array, amplitudes[n], positions[n][0], positions[n][1], subsampling=psf._subsampling, neighbor_positions=neighbor_positions, neighbor_amplitudes=neighbor_amplitudes) psf_flux[src_idx], psf_flux_err[src_idx], residual, new_pos = \ src_psf.fit(data) new_amplitudes[src_idx] = src_psf.amplitude.value psf_x[src_idx], psf_y[src_idx] = new_pos else: import multiprocessing if pool_size is None: pool_size = multiprocessing.cpu_count() pool = multiprocessing.Pool( processes=pool_size, initializer=_init_psf_phot_process, initargs=(data, all_positions, all_amplitudes, idx, nidx, psf, amplitudes, positions)) pool_args = [] for n in range(len(positions)): src_idx = src_indices[indices][n] pool_args.append((n,src_idx)) result = pool.map(_psf_phot_worker, pool_args) pool.close() pool.join() result = zip(*result) psf_indices = np.where(indices) psf_flux[psf_indices] = result[0] psf_flux_err[psf_indices] = result[1] new_amplitudes[psf_indices] = result[2] psf_x[psf_indices] = result[3] psf_y[psf_indices] = result[4] # Save the psf derived quantities in the catalog # Ignore divide by zero errors that occur when sources # have zero psf flux (i.e. bad sources) np_err = np.geterr() np.seterr(divide='ignore') catalog.sources['psf_flux'] = psf_flux catalog.sources['psf_flux_err'] = psf_flux_err if exptime is not None: psf_mag = -2.5*np.log10(psf_flux/exptime) catalog.sources['psf_mag'] = psf_mag catalog.sources['psf_mag_err'] = psf_flux_err/psf_flux catalog.sources['psf_x'] = psf_x catalog.sources['psf_y'] = psf_y np.seterr(**np_err) return catalog, src_psfs, kd_tree from astropyp.utils.misc import trace_unhandled_exceptions @trace_unhandled_exceptions def _init_psf_phot_process(data, all_positions, all_amplitudes, idx, nidx, psf, amplitudes, positions): """ Global variables for psf photometry processes """ import multiprocessing global gbl_data global gbl_all_positions global gbl_all_amplitudes global gbl_idx global gbl_nidx global gbl_psf global gbl_amplitudes global gbl_positions gbl_data = data gbl_all_positions = all_positions gbl_all_amplitudes = all_amplitudes gbl_idx = idx gbl_nidx = nidx gbl_psf = psf gbl_amplitudes = amplitudes gbl_positions = positions logger.info("Initializing process {0}".format( multiprocessing.current_process().name)) @trace_unhandled_exceptions def _psf_phot_worker(args): """ Worker to perform psf phot on individual images """ n, src_idx = args if gbl_nidx is not None: n_indices = gbl_nidx[gbl_idx==src_idx] neighbor_positions = gbl_all_positions[n_indices] neighbor_amplitudes = gbl_all_amplitudes[n_indices] else: neighbor_positions = [] neighbor_amplitudes = [] src_psf = SinglePSF(gbl_psf._psf_array, gbl_amplitudes[n], gbl_positions[n][0], gbl_positions[n][1], subsampling=gbl_psf._subsampling, neighbor_positions=neighbor_positions, neighbor_amplitudes=neighbor_amplitudes) psf_flux, psf_flux_err, residual, new_pos = \ src_psf.fit(gbl_data) amplitudes = src_psf.amplitude.value psf_x, psf_y = new_pos return psf_flux, psf_flux_err, amplitudes, psf_x, psf_y class SinglePSF(Fittable2DModel): """ A discrete PSF model for a single source. Before creating a SinglePSF model it is necessary to run `build_psf` create a ``psf_array`` that is used to calibrate the source by modifying its amplitude and (optionally) its position. Parameters ---------- psf_array: `numpy.ndarray` PSF array using ``subsampling`` subpixels for each pixel in the image amplitude: float Amplitude of the psf function x0: float X coordinate in the image y0: float Y coordinate in the image subsampling: int, optional Number of subpixels used in the ``psf_array`` for each pixel in the image recenter: bool Whether or not to recenter the data patch on the maximum value. *Default=True* fit_position: bool Whether or not to fit the positions and the amplitude or only the amplitude. *Default=True, fit positions and amplitude* pos_range: float +- bounds for the position (if ``fit_position=True``). If ``pos_range=0`` then no bounds are used and the x0 and y0 parameters are free. *Default=0* """ amplitude = Parameter('amplitude') x0 = Parameter('x0') y0 = Parameter('y0') _param_names = () def __init__(self, psf_array, amplitude, x0, y0, subsampling=5, recenter=True, dx=None, dy=None, amp_err=None, neighbor_positions=[], neighbor_amplitudes=[]): # Set parameters defined by the psf to None so that they show # up as class attributes. self.set_psf_array will set all # of these parameters automatically self._subpixel_width = None self._width = None self._radius = None self._subsampling = None self._psf_array = None self.recenter = recenter self.fitter = LevMarLSQFitter() # New CrowdedPSF attributes if len(neighbor_positions)!=len(neighbor_amplitudes): raise Exception("neighbor_positions and neighbors amplitudes " "lengths {0},{1} are nor equal".format( len(neighbor_positions), len(neighbor_amplitudes))) self.src_count = len(neighbor_positions) self.x0_names = ['nx_{0}'.format(n) for n in range(self.src_count)] self.y0_names = ['ny_{0}'.format(n) for n in range(self.src_count)] self.amp_names = ['namp{0}'.format(n) for n in range(self.src_count)] self._param_names = tuple( ['amplitude','x0','y0']+self.x0_names+self.y0_names+self.amp_names) super(SinglePSF, self).__init__(n_models=1, x0=x0, y0=y0, amplitude=amplitude) # Choose whether or not the position of the PSF can be moved if False: #fit_position: self.x0.fixed = False self.y0.fixed = False if pos_range>0: self.x0.bounds = (self.x0-pos_range, self.x0+pos_range) self.y0.bounds = (self.y0-pos_range, self.y0+pos_range) else: pass #self.x0.fixed = True #self.y0.fixed = True self.set_psf_array(psf_array, subsampling=subsampling) amplitudes = neighbor_amplitudes # Set parameters for neighboring sources (if any exist) if self.src_count>0: pos_array = np.array(neighbor_positions) x = pos_array[:,0] y = pos_array[:,1] kwargs = OrderedDict() for n in range(self.src_count): x0_name = self.x0_names[n] y0_name = self.y0_names[n] amp_name = self.amp_names[n] setattr(self, x0_name, x[n]) setattr(self, y0_name, y[n]) setattr(self, amp_name, amplitudes[n]) if dx is not None: x0 = getattr(self, x0_name) x0.bounds = (x[n]-dx,x[n]+dx) if dy is not None: y0 = getattr(self, y0_name) y0.bounds = (y[n]-dy,y[n]+dy) if amp_err is not None: amp = getattr(self, amp_name) amp.bounds = ( amplitudes[n]*(1-amp_err), amplitudes[n]*(1+amp_err)) @property def shape(self): """ Shape of the PSF image. """ return self._psf_array.shape def get_flux(self, amplitude=None): """ PSF Flux of the source """ if amplitude is None: amplitude = self.amplitude flux = np.sum(self._psf_array*amplitude)/self._subsampling**2 return flux def evaluate(self, X, Y, amplitude, x0, y0, *args): """ Evaluate the SinglePSF model. """ x = X[0,:] y = Y[:,0] result = amplitude * self._psf_func(y-y0,x-x0) # If the source has any neighbors, add their # fluxes as well nx,ny,namp = self._parse_eval_args(args) for n in range(self.src_count): result += namp[n]*self._psf_func(y-ny[n], x-nx[n]) result[self._psf_array.mask] = 0 return result def _parse_eval_args(self, args): """ Separate the x0, y0, and amplitudes into lists """ x0 = args[:self.src_count] y0 = args[self.src_count:2*self.src_count] amp = args[2*self.src_count:] return x0,y0,amp @property def param_names(self): return self._param_names def __getattr__(self, attr): if self._param_names and attr in self._param_names: return Parameter(attr, default=0.0, model=self) raise AttributeError(attr) def __setattr__(self, attr, value): if attr[0] != '_' and self._param_names and attr in self._param_names: param = Parameter(attr, default=0.0, model=self) # This is a little hackish, but we can actually reuse the # Parameter.__set__ method here param.__set__(self, value) else: super(SinglePSF, self).__setattr__(attr, value) def fit(self, img_data=None, fit_position=True, pos_range=0, indices=None, patch=None, X=None, Y=None): """ Fit the PSF to the data. Parameters ---------- img_data: array-like, optional Image data containing the source to fit. Either img_data must be specified or patch. fit_position: bool, optional Whether or not to fit the position. If ``fit_position=False`` only the amplitude will be fit pos_range: float, optional Maximum distance that the position is allowed to shift from ``x0,y0`` initial. This is most useful when fitting a group of sources where the code might try to significantly move one of the sources for the fit. The default range is 0, which does not set any bounds at all. indices: list of arrays, optional ``indices`` is a list that contains the X and Y indices to the img_data provided. The default is None, which uses the image scale and size of the psf to set the indices. patch: subsampled image patch, optional Subset of data to use for the fit. If not included (default) then img_data must be specified. This must be the same shape as the psf. X,Y: array-like, optional Positions for the coordinates on the x,y axes associated with the patch. These must be given if patch is not None. """ import astropyp.utils # Extract sub array with data of interest position = (self.y0.value, self.x0.value) if patch is None: patch,X,Y, new_pos = astropyp.utils.misc.get_subpixel_patch( img_data, position, (self._width, self._width), subsampling=self._subsampling, window_sampling=300, order=5, # Need to open these options up to the class init normalize=False) # If the source was too close to an edge a patch # cannot be loaded, source the source cannot be fit if patch is None: return np.nan,np.nan,np.nan,(np.nan,np.nan) self.y0.value, self.x0.value = new_pos else: new_pos = (self.y0.value, self.x0.value) x_radius = self.shape[1]/self._subsampling y_radius = self.shape[0]/self._subsampling x0 = self.x0.value y0 = self.y0.value X = np.linspace(x0-x_radius, x0+x_radius, self.shape[1]) Y = np.linspace(y0-y_radius, y0+y_radius, self.shape[0]) # Set the values outside the aperture to zero # so they will not affect the fit patch[self._psf_array.mask] = 0 X, Y = np.meshgrid(X, Y) # Fit only if PSF is completely contained in the image and no NaN # values are present if (patch.shape == self.shape and not np.isnan(patch).any()): m = self.fitter(self, X, Y, patch) for p in self._param_names: setattr(self,p,getattr(m,p)) residual = self.get_residual(X,Y,patch) self.psf_error = self.calculate_psf_error(residual) return (self.get_flux(), self.psf_error, residual, (self.x0.value,self.y0.value)) else: return (0, 0, patch, (self.x0.value,self.y0.value)) def get_residual(self, X,Y, patch): fit = self.__call__(X,Y) residual = patch-fit return residual def calculate_psf_error(self, residual=None, X=None, Y=None, patch=None): """ Given either a residual or a patch, calculate the error in PSF flux """ if residual is None: if patch is not None and X is not None and Y is not None: residual = self.get_residual(X,Y,patch) else: raise Exception( "You must either supply a residual or " "X,Y,patch to calculate psf error") psf_error = np.abs(np.sum(residual/self._subsampling**2)) return psf_error def set_psf_array(self, psf_array, subsampling=None): """ If a change is made to the psf function, it must be updated here so that all of the derived parameters (_width, _radius, _psf_array) can be updated """ try: from scipy import interpolate except ImportError: raise Exception( "You must have scipy installed to use the SinglePSF class") if subsampling is not None: self._subsampling = subsampling # Set the width and radius of the psf self._subpixel_width = max(psf_array.shape[0], psf_array.shape[1]) self._width = self._subpixel_width/self._subsampling self._radius = (self._width-1)/2. self._psf_array = psf_array # Set the function to determine the psf (up to an amplitude) X = np.linspace(-self._radius, self._radius, self._subpixel_width) Y = np.linspace(-self._radius, self._radius, self._subpixel_width) self._psf_func = interpolate.RectBivariateSpline(Y, X, self._psf_array) class GroupPSF: """ This represents the PSFs of a group of sources. In general a `GroupPSF` should only be created by the `ImagePSF` class. """ def __init__(self, group_id, psf, positions=None, amplitudes=None, bounds=None, mask_img=True, show_plots=True, **kwargs): if isinstance(psf, GroupPSF): self.__dict__ = psf.__dict__.copy() else: self.group_id = group_id self.psf = psf.copy() self.positions = positions self.amplitudes = amplitudes self.mask_img = mask_img self.show_plots = show_plots self.bounds = bounds self.combined_psf = None for k,v in kwargs: setattr(self, k, v) def get_patch(self, data, positions=None, patch_bounds=None, show_plots=None): """ Given a list of positions, get the patch of the data that contains all of the positions and their PSF radii and mask out all of the other pixels (to prevent sources outside the group from polluting the fit). Parameters ---------- data: ndarray Image array data positions: list or array (optional) List of positions to include in the patch. If no positions are passed the function will use ``GroupPSF.positions``. patch_bounds: list or array (optional) Boundaries of the data patch of the form [ymin,ymax,xmin,xmax] """ from scipy import interpolate if positions is None: positions = np.array(self.positions) if show_plots is None: show_plots = self.show_plots radius = int((self.psf._width-1)/2) x = positions[:,0] y = positions[:,1] # Extract the patch of data that includes all of the sources # and their psf radii if patch_bounds is None: if self.bounds is None: xc = np.round(x).astype('int') yc = np.round(y).astype('int') self.bounds = [ max(min(yc)-radius, 0), # ymin min(max(yc)+radius+1, data.shape[0]), #ymax max(min(xc)-radius, 0), #xmin min(max(xc)+radius+1, data.shape[1]) #xmax ] patch_bounds = self.bounds ymin,ymax,xmin,xmax = patch_bounds X_img = np.arange(xmin, xmax+1, 1) Y_img = np.arange(ymin, ymax+1, 1) Z = data[np.ix_(Y_img,X_img)] X = np.arange(xmin, xmax+1, 1/self.psf._subsampling) Y = np.arange(ymin, ymax+1, 1/self.psf._subsampling) data_func = interpolate.RectBivariateSpline(Y_img, X_img, Z) sub_data = data_func(Y, X, Z) # If the group is large enough, sources not contained # in the group might be located in the same square patch, # so we mask out everything outside of the radius the # individual sources PSFs if self.mask_img: sub_data = np.ma.array(sub_data) mask = np.ones(data.shape, dtype='bool') mask_X = np.arange(data.shape[1]) mask_Y = np.arange(data.shape[0]) mask_X, mask_Y = np.meshgrid(mask_X, mask_Y) for xc,yc in zip(x,y): mask = mask & ( (mask_X-xc)**2+(mask_Y-yc)**2>=(radius)**2) # Expand the mask to be the same size as the data patch subsampling = self.psf._subsampling sub_data.mask = np.kron(mask[np.ix_(Y_img,X_img)], np.ones((subsampling, subsampling), dtype=int)) sub_data = sub_data.filled(0) # Optionally plot the mask and data patch if show_plots: try: import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D except ImportError: raise Exception( "You must have matplotlib installed" " to create plots") # Plot mask if self.mask_img: plt.imshow(mask[ymin:ymax,xmin:xmax]) # Plot masked patch used for fit #Xplt = np.arange(0, sub_data.shape[1], 1) #Yplt = np.arange(0, sub_data.shape[0], 1) Xplt, Yplt = np.meshgrid(X, Y) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_wireframe(Xplt, Yplt, sub_data, rstride=5, cstride=5) plt.show() return sub_data, X, Y def fit(self, data, positions=None, psfs=None, amplitudes=None, patch_bounds=None, fitter=None): """ Simultaneously fit all of the sources in a PSF group. This functions makes a copy of the PSF for each source and creates an astropy `astropy.models.CompoundModel` that is fit but the PSF's ``fitter`` function. Parameters ---------- data: ndarray Image data array positions : List or array (optional) List of positions in pixel coordinates where to fit the PSF/PRF. Ex: [(0.0,0.0),(1.0,2.0), (10.3,-3.2)] psfs : list of PSFs (optional) It is possible to choose a different PSF for each model, in which case ``psfs`` should have the same length as positions amplitudes: list of floats, optional Amplitudes (peak values) for the sources. If amplitudes is none then the pixel value at the position is used patch_bounds: list or array (optional) Boundaries of the data patch of the form [ymin,ymax,xmin,xmax] fitter: `~astropy.modeling.Fitter` Fitting class to use to fit the data. *Default is self.fitter* """ if positions is None: positions = np.array(self.positions) x = positions[:,0] y = positions[:,1] # If not estimated ampltiudes are given for the sources, # use the pixel value at their positions if amplitudes is None: amplitudes = data[y.astype(int),x.astype(int)] if len(positions)==1: self.psf.x_0, self.psf.y_0 = positions[0] result = [self.psf.fit(data)] else: if psfs is None: psfs = [self.psf.copy() for p in range(len(positions))] if fitter is None: if self.psf is not None: fitter = self.psf.fitter else: fitter = psfs[0].fitter sub_data, X, Y = self.get_patch(data, positions, patch_bounds) X,Y = np.meshgrid(X,Y) # Create a CompoundModel that is a combination of the # individual PRF's combined_psf = None for x0, y0, single_psf, amplitude in zip(x,y,psfs,amplitudes): single_psf.x_0 = x0 single_psf.y_0 = y0 single_psf.amplitude = amplitude if combined_psf is None: combined_psf = single_psf else: combined_psf += single_psf # Fit the combined PRF self.combined_psf = fitter(combined_psf, X, Y, sub_data) # Return the list of fluxes for all of the sources in the group # and the combined PRF result = [getattr(self.combined_psf,'amplitude_'+str(n)).value for n in range(len(x))] return result
/* global DIR_E, DIR_W, DIR_SW, DIR_NW, DIR_NE, DIR_SE, WEAPON_SPEAR, MALE, ACTION_IDLE, engineView */ var BASE_IMG_DIR = "/img/critter/"; var WALK_ANIMATION_LENGTH = 800; var WALK_ANIMATION_MODIFIER_WHEN_FIRST = 100; // ========================================================================= var allUnits = []; var numOfImages = []; numOfImages['grass'] = 5; numOfImages['misc'] = 5; numOfImages['tree'] = 6; /** * This class represents animated unit/sprite/type to be displayed in the browser. * It's possible to change unit and animate it using animate() function. Commands can be chained like: * <p>var unit = new Unit(json).create()</p> * * Unit is identified by: * - sex - MALE/FEMALE * - dir - direction unit is facing - DIR_E, DIR_W, DIR_SE, DIR_SW, DIR_NE, DIR_NW 0 * - action - currently executed action - choose one of many constans prefixed ACTION_, SPEAR_ etc * - type - Fallout identifier of the type in the gif, use constants lik WARRIOR_MALE, WARRIOR_FEMALE etc * * @param json json string that will be used to create object * @returns Unit */ function Unit(json) { this._id = null; // Unique identifier for the unit this._sex = null; // Sex of this unit, use MALE or FEMALE this._action = null; // Curenntly executed action, use ACTION_* and others this._dir = null; // Direction unit is facing, use DIR_* this._type = null; // Type of this unit e.g. WARRIOR_MALE, WARRIOR_FEMALE this.staticImageDisplayMode = false; this.marginLeft = 0; this.marginTop = 0; this.positionPX = 0; // Position X in pixels this.positionPY = 0; // Position Y in pixels this._lastAnimationEndsAt = 0; this._divSelector = null; // ========================================================================= // Constructor this.constructor = function (json) { var parameters; if (typeof json === 'string') { parameters = JSON.parse(json); } else { parameters = json; } this._id = parameters['id'] ? parameters['id'] : __firstFreeUnitId++; this._sex = parameters['sex'] ? ("n" + parameters['sex'].toLowerCase()) : MALE; this._action = parameters['action'] ? parameters['action'] : ACTION_IDLE; this._dir = parameters['dir'] ? parameters['dir'] : DIR_SE; this._type = parameters['type']; if (!this._type) { console.log("Empty unit type for unit:"); console.log(this); alert("Empty unit type passed for new unit"); } allUnits[this._id] = this; }; this.constructor(json); // ========================================================================= // Display this.display = function (staticImageDisplayMode) { this.staticImageDisplayMode = staticImageDisplayMode; var imgObject = this.createImageElement(); var imageElement = imgObject['imageElement']; var imagePath = imgObject['imagePath']; // ========================================================================= // Create wrapper for the image if needed if (!this.staticImageDisplayMode) { this.createImageWrapper(); } // ========================================================================= var imageObject = new Image(); imageObject.unitId = this._id; imageObject.unit = this; imageObject.imageIsLoaded = false; function reloadImage(unitId, imgSource) { // $('#unit-img-' + unitId).attr('src', imgSource); // $('#unit-img-' + unitId).attr('src', "/img/empty.jpg"); $('#unit-img-' + unitId).attr('src', imgSource); } // Define image onload callback imageObject.onload = function (event) { var debugString = "<script>$('#unit-img-" + this.unitId + "').css('border', '1px solid rgba(255,0,0,0.2)')</script>"; +"<script>setTimeout(function() { $('#unit-img-" + this.unitId + "').css('border', 'none'); }, 1000)</script>"; $("#canvas-debug").html(debugString); var imgSource = $('#unit-img-' + this.unitId).attr('src'); // $('#unit-img-' + this.unitId).attr('src', ''); reloadImage(this.unitId, imgSource); if (this.imageIsLoaded) { return; } else { var unit = this.unit; this.imageIsLoaded = true; this.src = imagePath; var width = this.width; var height = this.height; var imageWrapperSelector = $("#unit-wrapper-" + this.unitId); // Add ready <img src=> element to the div wrapper, thus displaying the animation imageWrapperSelector.html(imageElement); // Assign current image dimensions to the image element var imageSelector = $("#unit-img-" + this.unitId); unit._imageSelector = imageSelector; imageSelector.attr({"imgwidth": width, "imgheight": height}); imageSelector.css('z-index', unit.positionPY); // ========================================================================= // Add extra STYLE to wrapping div if needed var styleString = buildStyleStringForImg( this, unit, staticImageDisplayMode, imageWrapperSelector, width, height ); if (styleString) { imageSelector.attr("style", styleString); } } }; // Assign image url imageObject.src = imagePath; return this; }; // ========================================================================= // Animation this._queueAnimations = []; this.queueAnimation = function (options, delay, animationLength) { var startAnimatingUnitAfterTime; var lastAnimationEndedAgo = this.timeSinceLastAnimationEndedAgo(); var canStartAnimationNow = lastAnimationEndedAgo >= -20; if (!animationLength) { animationLength = WALK_ANIMATION_LENGTH; // animationLength = 800; // animationLength = 2890; } if (!delay) { delay = 0; } // ========================================================================= // Define time when next animation could be potentially executed if (canStartAnimationNow) { startAnimatingUnitAfterTime = 0; this._lastAnimationEndsAt = this.timeNow() + delay + animationLength; } else { startAnimatingUnitAfterTime = -lastAnimationEndedAgo; this._lastAnimationEndsAt += delay + startAnimatingUnitAfterTime + animationLength; // this._lastAnimationEndsAt += delay + startAnimatingUnitAfterTime + animationLength; } // ========================================================================= // Either run an animation now or queue it // Run now if (canStartAnimationNow && this._queueAnimations.length === 0) { this._runAnimationNow(options, delay, animationLength); } // Doing something else now, so queue it else { var animationObject = { 'options': options, 'animationLength': animationLength, 'delay': delay }; this._queueAnimations.push(animationObject); } return this; }; this._runAnimationNow = function (options, delay, animationLength) { var unit = this; setTimeout(function () { // Run callback before the start of animation var callbackAnimationAfterStart = options['callbackAnimationAfterStart']; if (callbackAnimationAfterStart) { callbackAnimationAfterStart(unit, options); } unit._animate(options); // ========================================================================= setTimeout(function () { // Run callback at the end of animation var callbackAnimationEnded = options['callbackAnimationEnded']; if (callbackAnimationEnded) { callbackAnimationEnded(unit); } // Run next animation in enqueued unit.runNextQueuedAnimationIfNeeded(); }, animationLength, unit); }, delay); return this; }; this.runNextQueuedAnimationIfNeeded = function () { var nextAnimation = this._queueAnimations.shift(); if (nextAnimation !== undefined) { var options = nextAnimation['options']; var animationLength = nextAnimation['animationLength']; var delay = nextAnimation['delay']; this._runAnimationNow(options, delay, animationLength); } }; this._animate = function (options, afterTime) { if (!afterTime) { afterTime = 0; } if (!options) { options = []; } // ========================================================================= // Animation started callback var callbackAnimationBeforeStart = options['callbackAnimationBeforeStart']; if (callbackAnimationBeforeStart) { callbackAnimationBeforeStart(this); } // ========================================================================= var unit = this; setTimeout(function () { unit.handleOptions(options); unit.display(unit.staticImageDisplayMode); }, afterTime); this._lastAnimationStarted += afterTime; return this; }; this.timeSinceLastAnimationEndedAgo = function () { return this.timeNow() - this._lastAnimationEndsAt; }; this.timeNow = function () { return (new Date()).getTime(); }; // ========================================================================= // Animation generic this.animation = function (options, delay, animationLength) { if (!options) { options = {}; } if (!animationLength) { animationLength = 1700; } if (!delay || delay < 0) { delay = 0; } this.queueAnimation(options, delay, animationLength); return this; }; // Walk this.walk = function (options, delay) { // var walkAnimationTimespan = 990; var walkAnimationTimespan = WALK_ANIMATION_LENGTH + +(this._queueAnimations.length === 0 ? WALK_ANIMATION_MODIFIER_WHEN_FIRST : 0); // console.l og(this._queueAnimations.length + " / " + walkAnimationTimespan); // console.l og(walkAnimationTimespan); var lastAnimationEnded = this.timeSinceLastAnimationEndedAgo(); var startAnimatingUnitAfterTime; if (!delay) { delay = 0; } if (!options) { options = []; } // ========================================================================= options['callbackAnimationAfterStart'] = function (unit, options) { unit.convertActionToWalk(); }; options['callbackAnimationEnded'] = function (unit) { unit.handleWalkPositionChange(); if (unit._queueAnimations.length === 0) { unit.convertActionToIdle(); unit._animate(); } }; this.queueAnimation(options, delay, walkAnimationTimespan); return this; }; this.convertActionToWalk = function () { this._action = this._action.replaceAt(1, "b"); return this; }; this.convertActionToIdle = function () { this._action = this._action.replaceAt(1, "a"); return this; }; this.handleWalkPositionChange = function () { var fullStep = 82; var halfStep = 36; var dx = 0; var dy = 0; if (this._dir === DIR_E) { dx += fullStep; } else if (this._dir === DIR_W) { dx -= fullStep; } else if (this._dir === DIR_SE) { dx += halfStep; dy += halfStep; } else if (this._dir === DIR_SW) { dx -= halfStep; dy += halfStep; } else if (this._dir === DIR_NW) { dx -= halfStep; dy -= halfStep; } else if (this._dir === DIR_NE) { dx += halfStep; dy -= halfStep; } this.positionPX += dx; this.positionPY += dy; return this; }; // Equip weapons this.equipWeapon = function (weaponName, delay) { var options = {action: window[weaponName + "_EQUIP"]}; options['callbackAnimationEnded'] = function (unit) { unit._action = window[weaponName + "_IDLE"]; }; if (weaponName === WEAPON_SPEAR) { var animationLength = 1300; } else { var animationLength = 1300; } this.queueAnimation(options, delay, animationLength); return this; }; // ========================================================================= // Positioning this.positionRandomly = function () { this.positionPX = rand(0, engineView.width); this.positionPY = rand(0, engineView.height); return this; }; this.position = function (x, y) { if (!x && !y) { return {x: this.positionPX, y: this.positionPY}; } else { this.positionPX = x; this.positionPY = y; return this; } }; // ========================================================================= // HTML creation this.createImageElement = function () { var id = "unit-img-" + this._id; var idString = this._id ? "id='" + id + "'" : ""; var imgClass = ""; // Animated image if (!this.isStaticImage()) { var imgName = BASE_IMG_DIR + "all/" + this._sex + this._type + this._action + "_" + this._dir; // var imgName = "/image/critter/all/" + this._sex + this._type + this._action + "_" + this._dir; // var randomString = "?" + rand(100000, 999999); // var randomString = "?" + this._id + "-" + rand(0, 99999); // var randomString = "?" + this._id; // var imagePath = imgName + ".gif" + randomString; // var imagePath = imgName + ".gif?" + this._id; var imagePath = imgName + ".gif"; imgClass = "unit-alive"; // specialAttributes = "loop=infinite"; } // Static image else { var natureGroupName = this._type.substring(7); var imgName = "/img/nature/" + natureGroupName + "/" + rand(1, numOfImages[natureGroupName]); var imagePath = imgName + ".png"; } // ========================================================================= // Direction issues // if (!this.isActionStatic()) { // if (this.dirTowardEast()) { // this.marginLeft = 0; // } // else if (this.dirTowardWest()) { // this.marginLeft = 0; // } // } // this.marginTop = 60 + $("#" + id).height() * -1; // this.marginTop = 15; // if (this.dirTowardNorth()) { // } // ========================================================================= // Response contains various elements that can be needed, include them all // var styleString = "border: 1px solid red !important"; var imageElement = "<img " + idString + " class='" + imgClass + "' src='" + imagePath + "' />"; return {"imageElement": imageElement, "imagePath": imagePath}; }; // ========================================================================= // Low-level methods this.createImageWrapper = function () { var unitIdString = "unit-wrapper-" + this._id; if (this._divSelector !== null) { this._divSelector.html("<div class='engine-unit' id='" + unitIdString + "'></div>"); } else { $("#canvas").append("<div class='engine-unit' id='" + unitIdString + "'></div>"); this._divSelector = $("#canvas #" + unitIdString); } }; this.handleOptions = function (options) { if (options) { if (typeof options.action !== 'undefined') { this._action = options.action; } if (typeof options.sex !== 'undefined') { this._sex = options.sex; } if (typeof options.dir !== 'undefined') { this._dir = options.dir; } if (typeof options.type !== 'undefined') { this._type = options.type; } } return this; }; this.dirTowardEast = function () { return [DIR_E, DIR_SE, DIR_NE].indexOf(this._dir) !== -1; }; this.dirTowardWest = function () { return [DIR_W, DIR_NW, DIR_SW].indexOf(this._dir) !== -1; }; this.dirTowardNorth = function () { return [DIR_NW, DIR_NE].indexOf(this._dir) !== -1; }; this.dirTowardSouth = function () { return [DIR_SW, DIR_SE].indexOf(this._dir) !== -1; }; // this.isActionStatic = function () { // return [ACTION_IDLE, SPEAR_IDLE].indexOf(this._dir) != -1; // return false; // }; this.isStaticImage = function () { return this._type !== null && stringStartsWith(this._type, "nature_"); }; this.isActionWalk = function () { return this._action.charAt(1) === "b"; }; this.isActionWithWeapon = function (weaponName) { if (weaponName === WEAPON_SPEAR) { weaponLetter = "g"; } else { weaponLetter = "a"; // Generic actions } return this._action.charAt(0) === weaponLetter.charAt(0); }; // ========================================================================= // Getters and Setters /** * Getter or Setter for <b>dir</b> field. * @param newDir one of DIR_* variables */ this.dir = function (newDir) { if (newDir !== undefined) { this._dir = newDir; } else { return this._dir; } }; /** * Getter or Setter for <b>action</b> field. * @param newAction one of ACTION_* variables or others like that */ this.action = function (newAction) { if (newAction !== undefined) { this._action = newAction; } else { return this._action; } }; } // ========================================================================= __firstFreeUnitId = 100;
#!/bin/bash THEMEDIRECTORY=$(cd `dirname $0` && cd .. && pwd) FIREFOXFOLDER=~/.mozilla/firefox/ PROFILENAME="" FXACEXTRAS=false CHROMEFOLDER="chrome" # Get installation options while getopts 'f:p:eh' flag; do case "${flag}" in f) FIREFOXFOLDER="${OPTARG}" ;; p) PROFILENAME="${OPTARG}" ;; e) FXACEXTRAS=true ;; h) echo "Sweet_Pop! Install script usage: ./install.sh [ options ... ]" echo "where options include:" echo echo " -f <firefox_folder> (Set custom Firefox folder path)" echo " -p <profile_name> (Set custom profile name)" echo " -e (Install fx-autoconfig - Runs sudo to copy mozilla.cfg and local-settings.js to Application Binary folder)" echo " -h (Show help message)" exit 0 ;; esac done # Check if Firefox profiles.ini is installed or not PROFILES_FILE="${FIREFOXFOLDER}/profiles.ini" if [ ! -f "${PROFILES_FILE}" ]; then >&2 echo "Failed to locate profiles.ini at ${FIREFOXFOLDER} Exiting..." exit 1 fi echo echo "Profiles file found..." # Define default Profile folder path else use -p option if [ -z "$PROFILENAME" ]; then PROFILEFOLDER="${FIREFOXFOLDER}/$(grep -zoP '\[Install.*?\]\nDefault=\K(.*?)\n' $PROFILES_FILE | tr -d '\0')" else PROFILEFOLDER="${FIREFOXFOLDER}/${PROFILENAME}" fi # Enter Firefox profile folder if it exists if [ ! -d "$PROFILEFOLDER" ]; then >&2 echo "Failed to locate Profile folder at ${PROFILEFOLDER} Exiting..." exit 1 fi cd $PROFILEFOLDER # Copy theme repository inside chrome folder echo echo "Installing Sweet_Pop! in ${PWD}" # Create a chrome directory if it doesn't exist else take a backupold chrome folder if [ -d "$CHROMEFOLDER" ]; then echo "Moving existing $CHROMEFOLDER to ${CHROMEFOLDER}_bak" mv --backup=t $CHROMEFOLDER "${CHROMEFOLDER}_bak" || { exit 1; } fi mkdir -p $CHROMEFOLDER cd $CHROMEFOLDER cp -a "${THEMEDIRECTORY}/." $PWD # Symlink user.js to that of Sweet_Pop! echo echo "Setting configuration user.js file..." if [ -f ../user.js ]; then echo "Moving existing user.js to user.js.bak" mv --backup=t ../user.js ../user.js.bak || { exit 1; } fi ln -fs "`pwd`/programs/user.js" ../user.js # If FXACEXTRAS extras enabled, install necessary files if [ "$FXACEXTRAS" = true ] ; then APPLICATIONFOLDER=$(readlink -f `which firefox` | xargs -I{} dirname {}) echo echo "Enabling userChrome.js manager (fx-autoconfig)..." mkdir -p "${PWD}/utils" cd "${PWD}/utils" curl -sOL "https://raw.githubusercontent.com/MrOtherGuy/fx-autoconfig/master/profile/chrome/utils/boot.jsm" || { echo "Failed to fetch fx-autoconfig"; echo "Exiting..."; exit 1; } cat << EOF > chrome.manifest content userchromejs ./ content userscripts ../script/ content userchrome ../ resource content-accessible chrome://userchrome/content/layout/contentaccessible/ contentaccessible=yes EOF echo "Enabling Navbar Toolbar Button Slider..." cd ../script curl -sOL "https://raw.githubusercontent.com/aminomancer/uc.css.js/master/JS/navbarToolbarButtonSlider.uc.js" || { echo "Failed to fetch Navbar Toolbar Button Slider"; echo "Exiting..."; exit 1; } cd ../ echo echo "Copying mozilla.cfg and local-settings.js to ${APPLICATIONFOLDER}" chmod +x "${PWD}/programs/install-cfg.sh" sudo "${PWD}/programs/install-cfg.sh" $APPLICATIONFOLDER || { echo "Exiting..."; exit 1; } fi echo echo "Done!" echo "Note: Restart twice to apply changes"
import test from 'ava'; import { iterateFromIndex } from '../../src'; import { RedBlackTreeStructure } from '../../src/internals'; import { createTree, sortedValues } from '../test-utils'; let tree: RedBlackTreeStructure<any, any>; test.beforeEach(() => { tree = createTree(); }); test('returns an iterator starting from the specified index (negative index offset from the right)', t => { const expectedLeft = sortedValues.slice(25); const expectedRight = sortedValues.slice(sortedValues.length - 25); const expectedLeftReversed = sortedValues.slice(0, 25 + 1).reverse(); const expectedRightReversed = sortedValues.slice(0, sortedValues.length - 25 + 1).reverse(); const arrayLeft = Array.from(iterateFromIndex(false, 25, tree)).map(v => v.key); const arrayRight = Array.from(iterateFromIndex(false, -25, tree)).map(v => v.key); const arrayLeftReversed = Array.from(iterateFromIndex(true, 25, tree)).map(v => v.key); const arrayRightReversed = Array.from(iterateFromIndex(true, -25, tree)).map(v => v.key); t.deepEqual(arrayLeft, expectedLeft); t.deepEqual(arrayRight, expectedRight); t.deepEqual(arrayLeftReversed, expectedLeftReversed); t.deepEqual(arrayRightReversed, expectedRightReversed); }); test('the iterator should be in a completed state if the resolved index is out of range', t => { t.true(iterateFromIndex(false, sortedValues.length, tree).next().done); t.true(iterateFromIndex(false, -1 - sortedValues.length, tree).next().done); t.true(iterateFromIndex(true, sortedValues.length, tree).next().done); t.true(iterateFromIndex(true, -1 - sortedValues.length, tree).next().done); });
# Copyright 2019 ZTE Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from watcherclient._i18n import _ from watcherclient.common import command from watcherclient import exceptions from watcherclient.v1 import resource_fields as res_fields class ListDataModel(command.Lister): """List information on retrieved data model.""" def get_parser(self, prog_name): parser = super(ListDataModel, self).get_parser(prog_name) parser.add_argument( '--type', metavar='<type>', dest='type', help=_('Type of Datamodel user want to list. ' 'Supported values: compute. ' 'Future support values: storage, baremetal. ' 'Default type is compute.')) parser.add_argument( '--audit', metavar='<audit>', dest='audit', help=_('UUID of the audit')) parser.add_argument( '--detail', dest='detail', action='store_true', default=False, help=_("Show detailed information about data model.")) return parser def get_tuple(self, dic, fields): ret_tup = [] for item in fields: ret_tup.append(dic.get(item)) return tuple(ret_tup) def take_action(self, parsed_args): client = getattr(self.app.client_manager, "infra-optim") allowed_type = ['compute', 'storage', 'baremetal'] params = {} if parsed_args.audit: params["audit"] = parsed_args.audit if parsed_args.type: if parsed_args.type not in allowed_type: raise exceptions.CommandError( 'Type %s error, ' 'Please check the valid type!' % parsed_args.type) params["data_model_type"] = parsed_args.type try: data_model = client.data_model.list(**params) except exceptions.HTTPNotFound as exc: raise exceptions.CommandError(str(exc)) # TODO(chenker) Add Storage MODEL_FIELDS when using Storage Datamodel. if parsed_args.detail: fields = res_fields.COMPUTE_MODEL_LIST_FIELDS field_labels = res_fields.COMPUTE_MODEL_LIST_FIELD_LABELS else: fields = res_fields.COMPUTE_MODEL_SHORT_LIST_FIELDS field_labels = res_fields.COMPUTE_MODEL_SHORT_LIST_FIELD_LABELS return (field_labels, (self.get_tuple(item, fields) for item in data_model.context))
#!/bin/bash function print_help { echo "Usage: --all Display info for all wallets --key {key} Display info for wallet with key: {key}" } if [[ $1 == "--all" ]]; then curl http://127.0.0.1:8000/api/services/cryptocurrency/v1/wallets elif [[ $1 == "--key" ]]; then curl http://127.0.0.1:8000/api/services/cryptocurrency/v1/wallet/$2 else print_help exit fi
#!/bin/bash sudo apt-get -y update sudo apt-get install -y apache2 git git clone https://github.com/lalmanso/itmo544-fall2015-application.git mv ./itmo544-fall2015-application/images /var/www/html/images mv ./itmo544-fall2015-application/index.html /var/www/html mv ./itmo544-fall2015-application/page2.html /var/www/html echo "Lama Almansour" /tmp/hello.txt
#!/bin/bash npm run build rsync -av --delete-after dist/ crozet@ssh.cluster003.hosting.ovh.net:/home/crozet/rapier/demos3d # rsync -av dist/ammo.wasm.wasm crozet@ssh.cluster003.hosting.ovh.net:/home/crozet/rapier/ammo.wasm.wasm # rsync -av dist/physx.release.wasm crozet@ssh.cluster003.hosting.ovh.net:/home/crozet/rapier/physx.release.wasm
<reponame>errir503/cellular-automaton class Biome { /** * <pre> * Instantiate a new biome instance. * It contains biome parameters (elevation and climate) and some methods to help biome alteration and edition. * [Biome.type]{@link Biome#type} method allows to find which biome match given parameters. * </pre> * @param {String} name - Biome name * @param {String} frame - Default frame name for texture * @param {Number} e - Elevation parameter * @param {Number} c - Climate parameter * @category world */ constructor(name, frame, e, c) { /** * Name of biome. * @readonly * @type {String} */ this.name = name /** * Default frame used by biome. * @readonly * @type {String} */ this.frame = frame /** * Elevation scale. * @readonly * @type {Number} */ this.elevation = e /** * Climate scale. * @readonly * @type {Number} */ this.climate = c //Referencing biome Biome.LIST.set(this.name, this) Biome.MAX_ELEVATION = Math.max(Biome.MAX_ELEVATION, this.elevation) if (Life.ENV === "dev") { Biome.MAX_ELEVATION = Life.DEV.BIOME_MAX_ELEVATION } } /** * Tell if biome is same type as this one. * @param {Biome} as - Other biome to compare * @return {Boolean} True if same biome type */ same(as) { return this.name === as.name } /** * Tell if current biome is lower than the one given as argument. * @param {Biome} than - Other biome to compare * @return {Boolean} True if current biome is lower */ lower(than) { return this.elevation < than.elevation } /** * Tell if current biome is colder than the one given as argument. * @param {Biome} than - Other biome to compare * @return {Boolean} True if current biome is colder */ colder(than) { return this.climate < than.climate } /** * Tell which type of biome have matching parameters. * <div class="alert info"> * While <span class="bold">elevation</span> parameter is an integer, <span class="bold">climate</span> parameter is a float value between 0 and 1. * </div> * <div class="alert warning"> * As biome's singleton reference is returned, any modification on it will affect <span class="bold">all</span> usage of this biome ! * Be careful with it and avoid storing data in biomes instances. * </div> * @param {Number} e - Elevation parameter * @param {Number} c - Climate parameter * @return {Biome} Biome with given parameter */ static type(e, c) { if (e <= 0) { return Biome.LIST.get("ABYSSAL_SEA") } if (e == 1) { if (c > 0.70) return Biome.LIST.get("TROPICAL_SEA") if (c > 0.40) return Biome.LIST.get("TEMPERED_SEA") } if (e == 2) { if (c > 0.80) return Biome.LIST.get("TROPICAL_BEACH") if (c > 0.60) return Biome.LIST.get("TEMPERED_BEACH") if (c > 0.40) return Biome.LIST.get("POLAR_BEACH") } if (e == 3) { if (c > 0.80) return Biome.LIST.get("JUNGLE") if (c > 0.60) return Biome.LIST.get("PLAINS") if (c > 0.40) return Biome.LIST.get("FOREST") } if (e == 4) { if (c > 0.80) return Biome.LIST.get("ARID_MOUNTAINS") if (c > 0.60) return Biome.LIST.get("MOUNTAINS") if (c > 0.40) return Biome.LIST.get("CAVES") } if (e == 5) { if (c > 0.80) return Biome.LIST.get("VOLCANIC_PEAK") if (c > 0.60) return Biome.LIST.get("ROCKY_PEAK") if (c > 0.40) return Biome.LIST.get("GLACIAL_PEAK") } return null } /** * <pre> * Initialize biome list. * Must be called before using biome list. * </pre> * <div class="alert warning"> * Check that textures have been loaded in cache before calling this method. * </div> */ static init() { //Tell that biomes have already been initialized. if (Biome.INIT) { return } else { Biome.INIT = true } /** * List of biomes. * @type {Map} * @readonly */ Biome.LIST = new Map() /** * <pre> * Max elevation. * All biomes higher thatn this value won't be used by [World.generate]{@link World#generate} * </pre> * @type {Number} * @readonly */ //(Initialized later) Biome.MAX_ELEVATION = 0 /** * <pre> * Sea level (elevation). * All biomes lower than this value are considered as <span class="bold">aquatic</span>. * </pre> * @type {Number} * @readonly */ Biome.SEA_LEVEL = 1 //Create biomes new Biome("ABYSSAL_SEA", "B00_0.png", 0, 1) new Biome("TEMPERED_SEA", "B01_0.png", 1, 2) new Biome("TROPICAL_SEA", "B02_0.png", 1, 3) new Biome("POLAR_BEACH", "B03_0.png", 2, 1) new Biome("TEMPERED_BEACH", "B04_0.png", 2, 2) new Biome("TROPICAL_BEACH", "B05_0.png", 2, 3) new Biome("PLAINS", "B06_0.png", 3, 1) new Biome("FOREST", "B07_0.png", 3, 2) new Biome("JUNGLE", "B08_0.png", 3, 3) new Biome("CAVES", "B09_0.png", 4, 1) new Biome("MOUNTAINS", "B10_0.png", 4, 2) new Biome("ARID_MOUNTAINS", "B11_0.png", 4, 3) new Biome("GLACIAL_PEAK", "B12_0.png", 5, 1) new Biome("ROCKY_PEAK", "B13_0.png", 5, 2) new Biome("VOLCANIC_PEAK", "B14_0.png", 5, 3) } }
#!/bin/bash #SBATCH --job-name=/data/unibas/boittier/test-neighbours2 #SBATCH --nodes=1 #SBATCH --ntasks=1 #SBATCH --partition=short #SBATCH --output=/data/unibas/boittier/test-neighbours2_%A-%a.out hostname # Path to scripts and executables cubefit=/home/unibas/boittier/fdcm_project/mdcm_bin/cubefit.x fdcm=/home/unibas/boittier/fdcm_project/fdcm.x ars=/home/unibas/boittier/fdcm_project/ARS.py # Variables for the job n_steps=2 n_charges=24 scan_name=frame_ suffix=.chk cubes_dir=/data/unibas/boittier/fdcm/amide_graph output_dir=/data/unibas/boittier/test-neighbours2 frames=/home/unibas/boittier/fdcm_project/mdcms/amide/model1/frames.txt initial_fit=/home/unibas/boittier/fdcm_project/mdcms/amide/model1/24_charges_refined.xyz initial_fit_cube=/home/unibas/boittier/fdcm_project/mdcms/amide/model1/amide1.pdb.chk prev_frame=0 start_frame=91 next_frame=(91, 96) acd=/home/unibas/boittier/fdcm_project/0_fit.xyz.acd start=$start_frame next=$next_frame dir='frame_'$next output_name=$output_dir/$dir/$dir'-'$start'-'$next'.xyz' initial_fit=$output_dir/"frame_"$start/"frame_"$start'-'$prev_frame'-'$start'.xyz' # Go to the output directory mkdir -p $output_dir cd $output_dir mkdir -p $dir cd $dir # Do Initial Fit # for initial fit esp1=$cubes_dir/$scan_name$start$suffix'.p.cube' dens1=$cubes_dir/$scan_name$start$suffix'.d.cube' esp=$cubes_dir/$scan_name$next$suffix'.p.cube' dens=$cubes_dir/$scan_name$next$suffix'.d.cube' # adjust reference frame python $ars -charges $initial_fit -pcube $dens1 -pcube2 $dens -frames $frames -output $output_name -acd $acd > $output_name.ARS.log # do gradient descent fit $fdcm -xyz $output_name.global -dens $dens -esp $esp -stepsize 0.2 -n_steps $n_steps -learning_rate 0.5 -output $output_name > $output_name.GD.log # adjust reference frame python $ars -charges $output_name -pcube $esp -pcube2 $esp -frames $frames -output $output_name -acd $acd > $output_name.ARS-2.log # make a cube file for the fit $cubefit -v -generate -esp $esp -dens $dens -xyz refined.xyz > $output_name.cubemaking.log # do analysis $cubefit -v -analysis -esp $esp -esp2 $n_charges'charges.cube' -dens $dens > $output_name.analysis.log echo $PWD
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router'; import { Observable, onErrorResumeNext } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class MainGuard implements CanActivate { constructor(private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { if (localStorage.getItem("session") !== null && localStorage.getItem("session") !== null) { // TODO: Check with the server to see if these are still valid server side! return true; } // TODO: Flash message saying "You need to log in again." this.router.navigateByUrl("/home"); return false; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package arq.cmdline; import org.apache.jena.query.Syntax ; import org.apache.jena.rdf.model.ModelFactory ; import org.apache.jena.sparql.core.DatasetGraph ; public abstract class CmdUpdate extends CmdARQ { protected ModDataset modDataset = null ; protected Syntax updateSyntax = Syntax.defaultUpdateSyntax ; protected CmdUpdate(String[] argv) { super(argv) ; modDataset = setModeDataset() ; addModule(modDataset) ; } protected ModDataset setModeDataset() { return new ModDatasetGeneralAssembler() ; } @Override protected void processModulesAndArgs() { super.processModulesAndArgs() ; if ( super.cmdStrictMode ) updateSyntax = Syntax.syntaxSPARQL_11 ; } @Override protected final void exec() { DatasetGraph dataset = modDataset.getDatasetGraph() ; if ( dataset == null ) dataset = dealWithNoDataset() ; if ( dataset.getDefaultGraph() == null ) dataset.setDefaultGraph(ModelFactory.createDefaultModel().getGraph()) ; execUpdate(dataset) ; } protected abstract DatasetGraph dealWithNoDataset() ; protected abstract void execUpdate(DatasetGraph graphStore) ; }
export { default as OrderBookTable } from './OrderBookTable/OrderBookTable'; export { default as DecimalsSelect } from './DecimalsSelect/DecimalsSelect'; export { default as OrderRow } from './OrderRow/OrderRow';
//go:build go1.9 // +build go1.9 package s3crypto import ( "bytes" "encoding/hex" "encoding/json" "fmt" "io" "io/ioutil" "strings" "testing" ) // AES GCM func TestAES_GCM_NIST_gcmEncryptExtIV256_PTLen_128_Test_0(t *testing.T) { iv, _ := hex.DecodeString("0d18e06c7c725ac9e362e1ce") key, _ := hex.DecodeString("<KEY>") plaintext, _ := hex.DecodeString("2db5168e932556f8089a0622981d017d") expected, _ := hex.DecodeString("fa4362189661d163fcd6a56d8bf0405a") tag, _ := hex.DecodeString("d636ac1bbedd5cc3ee727dc2ab4a9489") aesgcmTest(t, iv, key, plaintext, expected, tag) } func TestAES_GCM_NIST_gcmEncryptExtIV256_PTLen_104_Test_3(t *testing.T) { iv, _ := hex.DecodeString("4742357c335913153ff0eb0f") key, _ := hex.DecodeString("<KEY>") plaintext, _ := hex.DecodeString("8499893e16b0ba8b007d54665a") expected, _ := hex.DecodeString("eb8e6175f1fe38eb1acf95fd51") tag, _ := hex.DecodeString("88a8b74bb74fda553e91020a23deed45") aesgcmTest(t, iv, key, plaintext, expected, tag) } func TestAES_GCM_NIST_gcmEncryptExtIV256_PTLen_256_Test_6(t *testing.T) { iv, _ := hex.DecodeString("a291484c3de8bec6b47f525f") key, _ := hex.DecodeString("37f39137416bafde6f75022a7a527cc593b6000a83ff51ec04871a0ff5360e4e") plaintext, _ := hex.DecodeString("fafd94cede8b5a0730394bec68a8e77dba288d6ccaa8e1563a81d6e7ccc7fc97") expected, _ := hex.DecodeString("44dc868006b21d49284016565ffb3979cc4271d967628bf7cdaf86db888e92e5") tag, _ := hex.DecodeString("01a2b578aa2f41ec6379a44a31cc019c") aesgcmTest(t, iv, key, plaintext, expected, tag) } func TestAES_GCM_NIST_gcmEncryptExtIV256_PTLen_408_Test_8(t *testing.T) { iv, _ := hex.DecodeString("92f258071d79af3e63672285") key, _ := hex.DecodeString("595f259c55abe00ae07535ca5d9b09d6efb9f7e9abb64605c337acbd6b14fc7e") plaintext, _ := hex.DecodeString("a6fee33eb110a2d769bbc52b0f36969c287874f665681477a25fc4c48015c541fbe2394133ba490a34ee2dd67b898177849a91") expected, _ := hex.DecodeString("bbca4a9e09ae9690c0f6f8d405e53dccd666aa9c5fa13c8758bc30abe1ddd1bcce0d36a1eaaaaffef20cd3c5970b9673f8a65c") tag, _ := hex.DecodeString("26ccecb9976fd6ac9c2c0f372c52c821") aesgcmTest(t, iv, key, plaintext, expected, tag) } type KAT struct { IV string `json:"iv"` Key string `json:"key"` Plaintext string `json:"pt"` AAD string `json:"aad"` CipherText string `json:"ct"` Tag string `json:"tag"` } func TestAES_GCM_KATS(t *testing.T) { fileContents, err := ioutil.ReadFile("testdata/aes_gcm.json") if err != nil { t.Fatalf("failed to read KAT file: %v", err) } var kats []KAT err = json.Unmarshal(fileContents, &kats) if err != nil { t.Fatalf("failed to unmarshal KAT json file: %v", err) } for i, kat := range kats { t.Run(fmt.Sprintf("Case%d", i), func(t *testing.T) { if len(kat.AAD) > 0 { t.Skip("Skipping... SDK implementation does not expose additional authenticated data") } iv, err := hex.DecodeString(kat.IV) if err != nil { t.Fatalf("failed to decode iv: %v", err) } key, err := hex.DecodeString(kat.Key) if err != nil { t.Fatalf("failed to decode key: %v", err) } plaintext, err := hex.DecodeString(kat.Plaintext) if err != nil { t.Fatalf("failed to decode plaintext: %v", err) } ciphertext, err := hex.DecodeString(kat.CipherText) if err != nil { t.Fatalf("failed to decode ciphertext: %v", err) } tag, err := hex.DecodeString(kat.Tag) if err != nil { t.Fatalf("failed to decode tag: %v", err) } aesgcmTest(t, iv, key, plaintext, ciphertext, tag) }) } } func TestGCMEncryptReader_SourceError(t *testing.T) { gcm := &gcmEncryptReader{ encrypter: &mockCipherAEAD{}, src: &mockSourceReader{err: fmt.Errorf("test read error")}, } b := make([]byte, 10) n, err := gcm.Read(b) if err == nil { t.Fatalf("expected error, but got nil") } else if err != nil && !strings.Contains(err.Error(), "test read error") { t.Fatalf("expected source read error, but got %v", err) } if n != 0 { t.Errorf("expected number of read bytes to be zero, but got %v", n) } } func TestGCMDecryptReader_SourceError(t *testing.T) { gcm := &gcmDecryptReader{ decrypter: &mockCipherAEAD{}, src: &mockSourceReader{err: fmt.Errorf("test read error")}, } b := make([]byte, 10) n, err := gcm.Read(b) if err == nil { t.Fatalf("expected error, but got nil") } else if err != nil && !strings.Contains(err.Error(), "test read error") { t.Fatalf("expected source read error, but got %v", err) } if n != 0 { t.Errorf("expected number of read bytes to be zero, but got %v", n) } } func TestGCMDecryptReader_DecrypterOpenError(t *testing.T) { gcm := &gcmDecryptReader{ decrypter: &mockCipherAEAD{openError: fmt.Errorf("test open error")}, src: &mockSourceReader{err: io.EOF}, } b := make([]byte, 10) n, err := gcm.Read(b) if err == nil { t.Fatalf("expected error, but got nil") } else if err != nil && !strings.Contains(err.Error(), "test open error") { t.Fatalf("expected source read error, but got %v", err) } if n != 0 { t.Errorf("expected number of read bytes to be zero, but got %v", n) } } func aesgcmTest(t *testing.T, iv, key, plaintext, expected, tag []byte) { t.Helper() const gcmTagSize = 16 cd := CipherData{ Key: key, IV: iv, } gcm, err := newAESGCM(cd) if err != nil { t.Errorf("expected no error, but received %v", err) } cipherdata := gcm.Encrypt(bytes.NewReader(plaintext)) ciphertext, err := ioutil.ReadAll(cipherdata) if err != nil { t.Errorf("expected no error, but received %v", err) } // splitting tag and ciphertext etag := ciphertext[len(ciphertext)-gcmTagSize:] if !bytes.Equal(etag, tag) { t.Errorf("expected tags to be equivalent") } if !bytes.Equal(ciphertext[:len(ciphertext)-gcmTagSize], expected) { t.Errorf("expected ciphertext to be equivalent") } data := gcm.Decrypt(bytes.NewReader(ciphertext)) text, err := ioutil.ReadAll(data) if err != nil { t.Errorf("expected no error, but received %v", err) } if !bytes.Equal(plaintext, text) { t.Errorf("expected ciphertext to be equivalent") } } type mockSourceReader struct { n int err error } func (b mockSourceReader) Read(p []byte) (n int, err error) { return b.n, b.err } type mockCipherAEAD struct { seal []byte openError error } func (m mockCipherAEAD) NonceSize() int { panic("implement me") } func (m mockCipherAEAD) Overhead() int { panic("implement me") } func (m mockCipherAEAD) Seal(dst, nonce, plaintext, additionalData []byte) []byte { return m.seal } func (m mockCipherAEAD) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { return []byte("mocked decrypt"), m.openError }
SELECT COUNT(*) FROM Articles a INNER JOIN Comments c ON a.id = c.article_id
<reponame>stungkit/cadence-web<gh_stars>0 // Copyright (c) 2017-2022 Uber Technologies Inc. // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import mapArchivedWorkflowResponse from './map-archived-workflow-response'; describe('mapArchivedWorkflowResponse', () => { it('should return a flattened results array when passed executions with 1 item', () => { const results = [ { closeStatus: 'closeStatusValue', closeTime: '2020-03-30T00:00:00Z', execution: { runId: 'runIdValue', workflowId: 'workflowIdValue', }, startTime: '2020-03-01T00:00:00Z', type: { name: 'workflowNameValue', }, }, ]; const output = mapArchivedWorkflowResponse({ results }); expect(output[0].closeStatus).toEqual('closeStatusValue'); expect(output[0].closeTime).toEqual('Mar 30, 2020 12:00:00 AM'); expect(output[0].runId).toEqual('runIdValue'); expect(output[0].startTime).toEqual('Mar 1, 2020 12:00:00 AM'); expect(output[0].workflowId).toEqual('workflowIdValue'); expect(output[0].workflowName).toEqual('workflowNameValue'); }); });
#!/bin/sh go build -o=s2c ../s2c rm -rf sfx-exe/ || true GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o ./sfx-exe/linux-amd64 ./_unpack/main.go GOOS=linux GOARCH=arm64 go build -trimpath -ldflags="-s -w" -o ./sfx-exe/linux-arm64 ./_unpack/main.go GOOS=linux GOARCH=arm go build -trimpath -ldflags="-s -w" -o ./sfx-exe/linux-arm ./_unpack/main.go GOOS=linux GOARCH=ppc64le go build -trimpath -ldflags="-s -w" -o ./sfx-exe/linux-ppc64le ./_unpack/main.go GOOS=linux GOARCH=mips64 go build -trimpath -ldflags="-s -w" -o ./sfx-exe/linux-mips64 ./_unpack/main.go GOOS=darwin GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o ./sfx-exe/darwin-amd64 ./_unpack/main.go GOOS=darwin GOARCH=arm64 go build -trimpath -ldflags="-s -w" -o ./sfx-exe/darwin-arm64 ./_unpack/main.go GOOS=windows GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o ./sfx-exe/windows-amd64 ./_unpack/main.go GOOS=windows GOARCH=386 go build -trimpath -ldflags="-s -w" -o ./sfx-exe/windows-386 ./_unpack/main.go ./s2c -rm -slower sfx-exe/* rm s2c
#!/bin/bash # NOTE: Need to pip install build & twine rm -rf dist/ rm -rf build/ rm -rf test_ai/*.egg-info # NOTE: If you get a version issue where it can't find the regex go in and add check if version == None python3 -m build # Upload build # NOTE: To upload put username __token__ then password put token python3 -m twine upload dist/* # Cleanup rm -rf dist/ rm -rf build/ rm -rf test_ai/*.egg-info
<gh_stars>0 import React from 'react'; import { Divider } from '@patternfly/react-core'; export const DividerInsetVariousBreakpoints: React.FunctionComponent = () => ( <Divider inset={{ default: 'insetMd', md: 'insetNone', lg: 'inset3xl', xl: 'insetLg' }} /> );
<gh_stars>0 'use sctrict'; (function ($) { let scroll_start = 0; const startchange = $('#startchange'); const offset = startchange.offset(); if (startchange.length) { $(document).scroll(function () { scroll_start = $(this).scrollTop(); if (scroll_start > offset.top) { $('.navbar-default').css('background-color', '#ffffff'); } else { $('.navbar-default').css('background-color', 'transparent'); } }); } }(jQuery));
package registry import ( "path" "time" log "github.com/coreos/fleet/Godeps/_workspace/src/github.com/golang/glog" "github.com/coreos/fleet/etcd" "github.com/coreos/fleet/job" ) func (r *EtcdRegistry) determineJobState(jobName string) *job.JobState { state := job.JobStateInactive tgt, err := r.jobTargetMachine(jobName) if err != nil { log.Errorf("Unable to determine target of Job(%s): %v", jobName, err) return nil } if tgt == "" { return &state } if r.getUnitState(jobName) == nil { return &state } state = job.JobStateLoaded agent, pulse := r.CheckJobPulse(jobName) if !pulse || agent != tgt { return &state } state = job.JobStateLaunched return &state } func (r *EtcdRegistry) JobHeartbeat(jobName, agentMachID string, ttl time.Duration) error { req := etcd.Set{ Key: r.jobHeartbeatPath(jobName), Value: agentMachID, TTL: ttl, } _, err := r.etcd.Do(&req) return err } func (r *EtcdRegistry) CheckJobPulse(jobName string) (string, bool) { req := etcd.Get{ Key: r.jobHeartbeatPath(jobName), } resp, err := r.etcd.Do(&req) if err != nil { return "", false } return resp.Node.Value, true } func (r *EtcdRegistry) ClearJobHeartbeat(jobName string) { req := etcd.Delete{ Key: r.jobHeartbeatPath(jobName), } r.etcd.Do(&req) } func (r *EtcdRegistry) jobHeartbeatPath(jobName string) string { return path.Join(r.keyPrefix, jobPrefix, jobName, "job-state") }
<reponame>zzz-s-2020/s-2020 package ru.zzz.demo.sber.shs.device; import org.springframework.lang.NonNull; /** * A base type of a request to a device. Subtypes describe commands. * Invariant for all commands: * /\ address!=null * /\ address is not empty */ public class Request { private final String address; private Request(String address) { if (address == null || address.isEmpty()) throw new IllegalArgumentException("address"); this.address = address; } public String getAddress() { return address; } @NonNull public static Request on(String address) { return new On(address); } @NonNull public static Request off(String address) { return new Off(address); } @NonNull public static Request set(String address, int val) { return new Set(address, val); } @NonNull public static Request get(String address) { return new Get(address); } public static class On extends Request { protected On(String address) { super(address); } } public static class Off extends Request { protected Off(String address) { super(address); } } public static class Set extends Request { private final int val; protected Set(String address, int val) { super(address); this.val = val; } public int getVal() { return val; } } public static class Get extends Request { protected Get(String address) { super(address); } } }
#!/usr/bin/env ash set -e name=$1 target_path=$(echo $name |sed -nE ${PATH_PATTERN}) if [[ -n "$target_path" ]] then target_url=s3:/$target_path echo uploading: $name to $target_url s3cmd sync --no-progress --no-check-md5 --skip-existing /home/upload/$1 "$target_url" \ && rm /home/upload/$1 else echo ignoring file: $name fi
<gh_stars>1-10 /** * Copyright © 2014-2021 The SiteWhere Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sitewhere.rest.model.device.event.request; import java.io.Serializable; import java.math.BigDecimal; import java.util.HashMap; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.sitewhere.rest.model.device.event.DeviceLocation; import com.sitewhere.spi.device.event.DeviceEventType; import com.sitewhere.spi.device.event.request.IDeviceLocationCreateRequest; /** * Model object used to create a new {@link DeviceLocation} via REST APIs. */ @JsonInclude(Include.NON_NULL) public class DeviceLocationCreateRequest extends DeviceEventCreateRequest implements IDeviceLocationCreateRequest, Serializable { /** Serialization version identifier */ private static final long serialVersionUID = -7160866457228082338L; /** Latitude value */ private BigDecimal latitude; /** Longitude value */ private BigDecimal longitude; /** Elevation value */ private BigDecimal elevation; public DeviceLocationCreateRequest() { setEventType(DeviceEventType.Location); } /* * @see com.sitewhere.spi.device.event.request.IDeviceLocationCreateRequest# * getLatitude() */ @Override public BigDecimal getLatitude() { return latitude; } public void setLatitude(BigDecimal latitude) { this.latitude = latitude; } /* * @see com.sitewhere.spi.device.event.request.IDeviceLocationCreateRequest# * getLongitude() */ @Override public BigDecimal getLongitude() { return longitude; } public void setLongitude(BigDecimal longitude) { this.longitude = longitude; } /* * @see com.sitewhere.spi.device.event.request.IDeviceLocationCreateRequest# * getElevation() */ @Override public BigDecimal getElevation() { return elevation; } public void setElevation(BigDecimal elevation) { this.elevation = elevation; } public static class Builder extends DeviceEventCreateRequest.Builder<DeviceLocationCreateRequest> { private DeviceLocationCreateRequest request = new DeviceLocationCreateRequest(); public Builder(BigDecimal latitude, BigDecimal longitude) { request.setLatitude(latitude); request.setLongitude(longitude); request.setElevation(BigDecimal.ZERO); } public Builder(double latitude, double longitude) { request.setLatitude(new BigDecimal(latitude)); request.setLongitude(new BigDecimal(longitude)); request.setElevation(BigDecimal.ZERO); } public Builder withElevation(BigDecimal value) { request.setElevation(value); return this; } public Builder withElevation(double value) { request.setElevation(new BigDecimal(value)); return this; } public Builder metadata(String name, String value) { if (request.getMetadata() == null) { request.setMetadata(new HashMap<String, String>()); } request.getMetadata().put(name, value); return this; } /* * (non-Javadoc) * * @see com.sitewhere.rest.model.device.event.request. * DeviceEventCreateRequest.Builder# getRequest() */ @Override public DeviceLocationCreateRequest getRequest() { return request; } /* * (non-Javadoc) * * @see com.sitewhere.rest.model.device.event.request. * DeviceEventCreateRequest.Builder# build() */ @Override public DeviceLocationCreateRequest build() { return request; } } }
<reponame>anauman/eosio /** * @file * @copyright defined in eos/LICENSE.txt */ #include <eosiolib/eos.hpp> #include <eosiolib/db.hpp>
#!/bin/bash # # Required vars : # # OBF_BUILD_PATH (absolute path of project build scripts, ie obuildfactory/openjdk8/linux) # OBF_SOURCES_PATH (absolute path of project sources) # # # Install JTReg (http://openjdk.java.net/jtreg) # function ensure_jtreg() { if [ ! -f $OBF_DROP_DIR/jtreg/win32/bin/jtreg ]; then JTREG_VERSION=b05 if [ ! -f $OBF_DROP_DIR/jtreg-$JTREG_VERSION.zip ]; then curl -L http://www.java.net/download/openjdk/jtreg/promoted/4.1/b05/jtreg-4.1-bin-b05_29_nov_2012.zip -o $OBF_DROP_DIR/jtreg-$JTREG_VERSION.zip fi rm -rf $OBF_DROP_DIR/jtreg mkdir $OBF_DROP_DIR/jtreg pushd $OBF_DROP_DIR >>/dev/null unzip jtreg-$JTREG_VERSION.zip popd >>/dev/null fi } ensure_jtreg BUILD_PROFILE="macosx-$OBF_BASE_ARCH-normal-server" if [ "$XDEBUG" = "true" ]; then BUILD_PROFILE+="-fastdebug" else BUILD_PROFILE+="-release" fi export PRODUCT_HOME=$OBF_SOURCES_PATH/build/$BUILD_PROFILE/images/j2sdk-image export JT_HOME=$OBF_DROP_DIR/jtreg pushd $OBF_SOURCES_PATH/test >>/dev/null if [ "$XCLEAN" = "true" ]; then CONF=$BUILD_PROFILE ALT_OUTPUTDIR=$OBF_SOURCES_PATH/build/$BUILD_PROFILE make clean fi CONF=$BUILD_PROFILE ALT_OUTPUTDIR=$OBF_SOURCES_PATH/build/$BUILD_PROFILE make popd >> /dev/null
#!/bin/sh ansible-playbook -i provisioning/hosts provisioning/image/deploy_and_restart/*.yml
<filename>gulpfile.babel.js // ------------------ // gulpfile.babel.js // ------------------ 'use strict' import { task, src, dest, series, parallel, watch } from 'gulp' import log from 'fancy-log' import gls from 'gulp-live-server' import webpack_server from './gulp_webpack_server.js' import fs from 'fs' import { spawn } from 'child_process' import rimraf from 'rimraf' // ------------------ // 動作モードの定義 // ------------------ const PRODUCTION = ( process.env.NODE_ENV === 'production' ) ? true : false const ENV_PATH = PRODUCTION ? 'prod': 'dev' if(PRODUCTION) { log.info("PRODUCTION MODE") } else { log.info("DEVELOPMENT MODE") process.env.NODE_ENV='development' } // ------------------ // tasks // ------------------ // クリーンアップ task('clean',(done)=>{ rimraf(`../dist/${ENV_PATH}`,done) }) // clientのビルド task('client:build',(done)=>{ // vue.config.js の生成 // https://cli.vuejs.org/config/ const vue_config={ publicPath: '/', assetsDir: './assets', outputDir: `../dist/${ENV_PATH}/public`, productionSourceMap: false } fs.writeFileSync('client/vue.config.js', "// このファイルは動的に生成されています\n" + "// 編集しないでください\n" + 'module.exports='+ JSON.stringify(vue_config) +'' ) // yarn --cwd client build の実行 spawn('yarn',['--cwd','client','build'],{ stdio: 'inherit' }).on('close',(code)=>{ done() }) }) // serverのビルド task('server:build',()=>{ return src('./server/src/server.es') .pipe(webpack_server({ // 埋め込まないモジュール externals: [ 'express', 'request', 'cors', 'querystring', 'cookie-parser', 'body-parser', 'connect-history-api-fallback', 'morgan' ], // ファイル名 filename: 'server.js' })) .pipe(dest(`dist/${ENV_PATH}/`)) }) task('build',series('clean','client:build','server:build')) task('serve:start',()=>{ const server=gls(`dist/${ENV_PATH}/server.js`,{ env: { NODE_ENV: process.env.NODE_ENV } }) server.start() watch('./server/src/**/**',series( 'server:build', (done)=>{ server.start(); done() } )) watch('./client/(public|src)/**',series( 'client:build', (done)=>{ server.start(); done() } )) }) task('serve', series('build','serve:start')) task('default',series('serve'))
<filename>src/components/Heading/Heading2/Heading2.js import React from 'react' import HeadingBase from '../HeadingBase' const Heading2 = props => ( <HeadingBase as="h2" fontSize={[1, 2, 3]} {...props} /> ) export default Heading2
<filename>src/emolib/util/eval/semeval/SemevalCorpusCategorizerNN.java /* * File : SemevalCorpusCategorizerNN.java * Created : 27-Feb-2009 * By : atrilla * * Emolib - Emotional Library * * Copyright (c) 2009 <NAME> & * 2007-2012 Enginyeria i Arquitectura La Salle (Universitat Ramon Llull) * * This file is part of Emolib. * * You should have received a copy of the rights granted with this * distribution of EmoLib. See COPYING. */ package emolib.util.eval.semeval; import emolib.classifier.machinelearning.KNearestNeighbour; import emolib.classifier.FeatureBox; import java.io.*; import java.util.ArrayList; /** * The <i>SemevalCorpusCategorizerNN</i> class decides the category for each * headline in the Semeval'07 corpus according to the Nearest Neighbour * algorithm. * * <p> * This class (with a main process) takes the six emotional dimensions * evaluated in the Semeval'07 task and treats them as vectors, which are * then summed in order to obtain a representation of the sentence in * question in the emotional plane (the circumplex). This representation is * then compared with the emotions accounted in EmoLib using the NN * procedure and as a result a category is decided. * </p> * <p> * This application requires that an original basic emotions distribution is * stated, so either the the Whissell reference values, the Scherer reference * values or the Russell reference values have to be previously decided. * As a result, the output file contains one line for each headline, and each * line contains the sentence emotional features as well as the corresponding * label. * In case a quick reference of its usage is needed, the class responds to the * typical help queries ("-h" or "--help") by showing the program's synopsis. * </p> * * @author <NAME> (<EMAIL>) */ public class SemevalCorpusCategorizerNN { private KNearestNeighbour theNN; private ArrayList<Float> theValences; private ArrayList<Float> theActivations; /** * Void constructor. */ public SemevalCorpusCategorizerNN() { } /** * Method to initialize the confusion matrix. */ public void initialize() { theNN = new KNearestNeighbour(); theNN.setNumberOfEmotionalDimensions(2); theValences = new ArrayList<Float>(); theActivations = new ArrayList<Float>(); } /** * Prints the synopsis. */ public void printSynopsis() { System.out.println("SemevalCorpusCategorizerNN usage:"); System.out.println("\tjava -cp EmoLib-X.Y.Z.jar emolib.util.eval.semeval.SemevalCorpusCategorizerNN " + "LANGUAGE russell|whissell|scherer INPUT_SEMEVAL_FILE OUTPUT_CATEGORIES_FILE"); } /** * Function to perform a change of base to compute the vector sums. * * @param theValue The value that has to be transformed. * * @return The transformed value. */ private Float changeBase(float theValue) { float newValue = theValue - Float.parseFloat("5.0"); Float newObjectValue = new Float(newValue); return newObjectValue; } /** * The method to compute the resulting emotional dimentions according to the base * reference emotions and their associated weight. * * @param theWeights The weights of the base reference emotions. * * @return The resulting emotional dimentions. */ public float[] computeResultingDimentions(String[] theWeights) { float resultVal = 5; float resultAct = 5; for (int counter = 1; counter < theWeights.length; counter++) { resultVal += (Float.parseFloat(theWeights[counter]) / Float.parseFloat("100")) * theValences.get(counter - 1).floatValue(); resultAct += (Float.parseFloat(theWeights[counter]) / Float.parseFloat("100")) * theActivations.get(counter - 1).floatValue(); } // Since the corpus evaluations have been performed on a subjective basis, // the vector sum should be clipped in order not to excede the dimentional // bounds. if (resultVal < 0) { resultVal = 0; } if (resultAct < 0) { resultAct = 0; } if (resultVal > 10) { resultVal = 10; } if (resultAct > 10) { resultAct = 10; } float[] theDims = new float[2]; theDims[0] = resultVal; theDims[1] = resultAct; return theDims; } /** * Method to train the classifier (NN). * * @param val The valence. * @param act The activation. * @param cat The category. */ public void trainClassifier(float val, float act, String cat) { FeatureBox tempFeatures = new FeatureBox(); tempFeatures.setNumberOfEmotionalDimensions(2); tempFeatures.setValence(val); tempFeatures.setActivation(act); theNN.inputTrainingExample(tempFeatures, cat); } /** * Methdo to add a valence with the appropriate base to compute vector operations. * * @param val The valence to add. */ public void addValence(float val) { theValences.add(changeBase(val)); } /** * Methdo to add an activation with the appropriate base to compute vector operations. * * @param act The activation to add. */ public void addActivation(float act) { theActivations.add(changeBase(act)); } /** * Function to obtain the nearest category from the classifier. * * @param val The valence. * @param act The activation. * @param uselessOne Useless parameter. Only two dimentions are needed. * @param uselessTwo Useless parameter. Only two dimentions are needed. */ public String getCategory(float val, float act, float uselessOne, String uselessTwo) { FeatureBox tempFeatures = new FeatureBox(); tempFeatures.setNumberOfEmotionalDimensions(2); tempFeatures.setValence(val); tempFeatures.setActivation(act); return theNN.getCategory(tempFeatures); } /** * The main method of the SemevalCorpusCategorizerNN application. * * @param args The input arguments. The first one corresponds to the language, * followed by the definitions of the * basic refernce emotions, followed by the input file from the Semeval corpus and finally, as * the fourth parameter, the desired output file containing the categories. */ public static void main(String[] args) throws Exception { SemevalCorpusCategorizerNN categorizer = new SemevalCorpusCategorizerNN(); categorizer.initialize(); if (args.length == 4) { if (args[1].equals("whissell")) { // The emotions in the Semeval dataset are ordered as follows: // anger disgust fear joy sadness surprise // "Disgust" is not accounted in EmoLib. if (args[0].equals("english")) { // Anger categorizer.trainClassifier(Float.parseFloat("2.91"), Float.parseFloat("5.64"), "anger"); categorizer.addValence(Float.parseFloat("2.91")); categorizer.addActivation(Float.parseFloat("5.64")); // Disgust categorizer.addValence(Float.parseFloat("3.82")); categorizer.addActivation(Float.parseFloat("7.09")); // Fear categorizer.trainClassifier(Float.parseFloat("4.18"), Float.parseFloat("6.91"), "fear"); categorizer.addValence(Float.parseFloat("4.18")); categorizer.addActivation(Float.parseFloat("6.91")); // Happiness categorizer.trainClassifier(Float.parseFloat("7.64"), Float.parseFloat("7.64"), "happiness"); categorizer.addValence(Float.parseFloat("7.64")); categorizer.addActivation(Float.parseFloat("7.64")); // Sorrow is actually sad, in the Whissell emotional dictionary. categorizer.trainClassifier(Float.parseFloat("2.36"), Float.parseFloat("4.91"), "sorrow"); categorizer.addValence(Float.parseFloat("2.36")); categorizer.addActivation(Float.parseFloat("4.91")); // Surprise categorizer.trainClassifier(Float.parseFloat("7.45"), Float.parseFloat("9.82"), "surprise"); categorizer.addValence(Float.parseFloat("7.45")); categorizer.addActivation(Float.parseFloat("9.82")); // Neutral categorizer.trainClassifier(Float.parseFloat("5.0"), Float.parseFloat("5.0"), "neutral"); } else if (args[0].equals("spanish")) { // Anger categorizer.trainClassifier(Float.parseFloat("2.91"), Float.parseFloat("5.64"), "enfado"); categorizer.addValence(Float.parseFloat("2.91")); categorizer.addActivation(Float.parseFloat("5.64")); // Disgust categorizer.addValence(Float.parseFloat("3.82")); categorizer.addActivation(Float.parseFloat("7.09")); // Fear categorizer.trainClassifier(Float.parseFloat("4.18"), Float.parseFloat("6.91"), "miedo"); categorizer.addValence(Float.parseFloat("4.18")); categorizer.addActivation(Float.parseFloat("6.91")); // Happiness categorizer.trainClassifier(Float.parseFloat("7.64"), Float.parseFloat("7.64"), "alegria"); categorizer.addValence(Float.parseFloat("7.64")); categorizer.addActivation(Float.parseFloat("7.64")); // Sorrow is actually sad, in the Whissell emotional dictionary. categorizer.trainClassifier(Float.parseFloat("2.36"), Float.parseFloat("4.91"), "tristeza"); categorizer.addValence(Float.parseFloat("2.36")); categorizer.addActivation(Float.parseFloat("4.91")); // Surprise categorizer.trainClassifier(Float.parseFloat("7.45"), Float.parseFloat("9.82"), "sorpresa"); categorizer.addValence(Float.parseFloat("7.45")); categorizer.addActivation(Float.parseFloat("9.82")); // Neutral categorizer.trainClassifier(Float.parseFloat("5.0"), Float.parseFloat("5.0"), "neutro"); } } else if (args[1].equals("scherer")) { // The emotions in the Semeval dataset are ordered as follows: // anger disgust fear joy sadness surprise // "Disgust" is not accounted in EmoLib. if (args[0].equals("english")) { // Anger categorizer.trainClassifier(Float.parseFloat("0.65"), Float.parseFloat("8.16"), "anger"); categorizer.addValence(Float.parseFloat("0.65")); categorizer.addActivation(Float.parseFloat("8.16")); // Disgust categorizer.addValence(Float.parseFloat("0.96")); categorizer.addActivation(Float.parseFloat("7.51")); // Fear is actually alarmed, in the Scherer emotional circumplex. categorizer.trainClassifier(Float.parseFloat("3.95"), Float.parseFloat("9.44"), "fear"); categorizer.addValence(Float.parseFloat("3.95")); categorizer.addActivation(Float.parseFloat("9.44")); // Happiness categorizer.trainClassifier(Float.parseFloat("9.20"), Float.parseFloat("6.02"), "happiness"); categorizer.addValence(Float.parseFloat("9.20")); categorizer.addActivation(Float.parseFloat("6.02")); // Sorrow is actually sad, in the Scherer emotional circumplex. categorizer.trainClassifier(Float.parseFloat("3.00"), Float.parseFloat("0.88"), "sorrow"); categorizer.addValence(Float.parseFloat("3.00")); categorizer.addActivation(Float.parseFloat("0.88")); // Surprise is actually astonished, in the Scherer emotional circumplex. categorizer.trainClassifier(Float.parseFloat("6.46"), Float.parseFloat("9.37"), "surprise"); categorizer.addValence(Float.parseFloat("6.46")); categorizer.addActivation(Float.parseFloat("9.37")); // Neutral categorizer.trainClassifier(Float.parseFloat("5.0"), Float.parseFloat("5.0"), "neutral"); } else if (args[0].equals("spanish")) { // Anger categorizer.trainClassifier(Float.parseFloat("0.65"), Float.parseFloat("8.16"), "enfado"); categorizer.addValence(Float.parseFloat("0.65")); categorizer.addActivation(Float.parseFloat("8.16")); // Disgust categorizer.addValence(Float.parseFloat("0.96")); categorizer.addActivation(Float.parseFloat("7.51")); // Fear is actually alarmed, in the Scherer emotional circumplex. categorizer.trainClassifier(Float.parseFloat("3.95"), Float.parseFloat("9.44"), "miedo"); categorizer.addValence(Float.parseFloat("3.95")); categorizer.addActivation(Float.parseFloat("9.44")); // Happiness categorizer.trainClassifier(Float.parseFloat("9.20"), Float.parseFloat("6.02"), "alegria"); categorizer.addValence(Float.parseFloat("9.20")); categorizer.addActivation(Float.parseFloat("6.02")); // Sorrow is actually sad, in the Scherer emotional circumplex. categorizer.trainClassifier(Float.parseFloat("3.00"), Float.parseFloat("0.88"), "tristeza"); categorizer.addValence(Float.parseFloat("3.00")); categorizer.addActivation(Float.parseFloat("0.88")); // Surprise is actually astonished, in the Scherer emotional circumplex. categorizer.trainClassifier(Float.parseFloat("6.46"), Float.parseFloat("9.37"), "sorpresa"); categorizer.addValence(Float.parseFloat("6.46")); categorizer.addActivation(Float.parseFloat("9.37")); // Neutral categorizer.trainClassifier(Float.parseFloat("5.0"), Float.parseFloat("5.0"), "neutro"); } } else if (args[1].equals("russell")) { // The emotions in the Semeval dataset are ordered as follows: // anger disgust fear joy sadness surprise // "Disgust" is not accounted in EmoLib. if (args[0].equals("english")) { // Anger categorizer.trainClassifier(Float.parseFloat("2.34"), Float.parseFloat("6.62"), "anger"); categorizer.addValence(Float.parseFloat("2.34")); categorizer.addActivation(Float.parseFloat("6.62")); // Disgust is actually distress categorizer.addValence(Float.parseFloat("1.83")); categorizer.addActivation(Float.parseFloat("6.00")); // Fear categorizer.trainClassifier(Float.parseFloat("2.61"), Float.parseFloat("6.83"), "fear"); categorizer.addValence(Float.parseFloat("2.61")); categorizer.addActivation(Float.parseFloat("6.83")); // Happiness categorizer.trainClassifier(Float.parseFloat("7.90"), Float.parseFloat("4.92"), "happiness"); categorizer.addValence(Float.parseFloat("7.90")); categorizer.addActivation(Float.parseFloat("4.92")); // Sorrow is actually sadness categorizer.trainClassifier(Float.parseFloat("2.68"), Float.parseFloat("1.98"), "sorrow"); categorizer.addValence(Float.parseFloat("2.68")); categorizer.addActivation(Float.parseFloat("1.98")); // Surprise is actually astonishment categorizer.trainClassifier(Float.parseFloat("5.18"), Float.parseFloat("7.92"), "surprise"); categorizer.addValence(Float.parseFloat("5.18")); categorizer.addActivation(Float.parseFloat("7.92")); // Neutral categorizer.trainClassifier(Float.parseFloat("5.0"), Float.parseFloat("5.0"), "neutral"); } else if (args[0].equals("spanish")) { // Anger categorizer.trainClassifier(Float.parseFloat("2.34"), Float.parseFloat("6.62"), "enfado"); categorizer.addValence(Float.parseFloat("2.34")); categorizer.addActivation(Float.parseFloat("6.62")); // Disgust is actually distress categorizer.addValence(Float.parseFloat("1.83")); categorizer.addActivation(Float.parseFloat("6.00")); // Fear categorizer.trainClassifier(Float.parseFloat("2.61"), Float.parseFloat("6.83"), "miedo"); categorizer.addValence(Float.parseFloat("2.61")); categorizer.addActivation(Float.parseFloat("6.83")); // Happiness categorizer.trainClassifier(Float.parseFloat("7.90"), Float.parseFloat("4.92"), "alegria"); categorizer.addValence(Float.parseFloat("7.90")); categorizer.addActivation(Float.parseFloat("4.92")); // Sorrow is actually sadness categorizer.trainClassifier(Float.parseFloat("2.68"), Float.parseFloat("1.98"), "tristeza"); categorizer.addValence(Float.parseFloat("2.68")); categorizer.addActivation(Float.parseFloat("1.98")); // Surprise is actually astonishment categorizer.trainClassifier(Float.parseFloat("5.18"), Float.parseFloat("7.92"), "sorpresa"); categorizer.addValence(Float.parseFloat("5.18")); categorizer.addActivation(Float.parseFloat("7.92")); // Neutral categorizer.trainClassifier(Float.parseFloat("5.0"), Float.parseFloat("5.0"), "neutro"); } } else { System.out.println("SemevalCorpusCategorizerNN: the basic reference emotions are not correct!"); } BufferedReader originalFile = new BufferedReader(new FileReader(args[2])); BufferedWriter predictionFile = new BufferedWriter(new FileWriter(args[3])); String[] evaluations; String lineOriginalFile = originalFile.readLine(); float[] theResultingDimentions; while (lineOriginalFile != null) { evaluations = lineOriginalFile.split(" "); theResultingDimentions = categorizer.computeResultingDimentions(evaluations); predictionFile.write(theResultingDimentions[0] + " "); predictionFile.write(theResultingDimentions[1] + " "); predictionFile.write(categorizer.getCategory(theResultingDimentions[0], theResultingDimentions[1], Float.parseFloat("1.0"), "hello")); predictionFile.newLine(); lineOriginalFile = originalFile.readLine(); } predictionFile.close(); } else if (args.length == 1) { if (args[0].equals("-h") || args[0].equals("--help")) { categorizer.printSynopsis(); } else { System.out.println("SemevalCorpusCategorizerNN: Please enter the correct parameters!"); System.out.println(""); categorizer.printSynopsis(); } } else { System.out.println("SemevalCorpusCategorizerNN: Please enter the correct parameters!"); System.out.println(""); categorizer.printSynopsis(); } } }
#!/bin/bash set -x ticker=${1:-MSFT} amount=${2:-200.00} partyName=${3:-O=PartyA,L=London,C=GB} curl -d "ticker=${ticker}&amount=${amount}&partyName=${partyName}" localhost:10050/create-stock
<gh_stars>0 var _ref_backend_id_8hpp = [ [ "RefBackendId", "_ref_backend_id_8hpp.xhtml#ae7d50846b2769f81521af24d063bc093", null ] ];
class SoftwarePackage { name: string; version: string; author: string; email: string; description: string; icon: string; constructor(name: string, version: string, author: string, email: string, description: string, icon: string) { this.name = name; this.version = version; this.author = author; this.email = email; this.description = description; this.icon = icon; } logPackageDetails(): void { console.log(`Name: ${this.name}`); console.log(`Version: ${this.version}`); console.log(`Author: ${this.author}`); console.log(`Email: ${this.email}`); console.log(`Description: ${this.description}`); console.log(`Icon: ${this.icon}`); } } // Example usage const package = new SoftwarePackage("SamplePackage", "1.0.0", "John Doe", "john@example.com", "Sample package description", "sample-icon.png"); package.logPackageDetails();
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // // cbind.h: Rcpp R/C++ interface class library -- cbind // // Copyright (C) 2016 <NAME> // // This file is part of Rcpp. // // Rcpp is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // Rcpp is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Rcpp. If not, see <http://www.gnu.org/licenses/>. #ifndef Rcpp__sugar__cbind_h #define Rcpp__sugar__cbind_h namespace Rcpp { namespace sugar { namespace cbind_impl { // override r_sexptype_traits<SEXP> for STRSXP template <typename T> struct cbind_sexptype_traits : public Rcpp::traits::r_sexptype_traits<T> {}; template <> struct cbind_sexptype_traits<SEXP> { enum { rtype = STRSXP }; }; // override storage_type<LGLSXP> (int) template <int RTYPE> struct cbind_storage_type : public Rcpp::traits::storage_type<RTYPE> {}; template <> struct cbind_storage_type<LGLSXP> { typedef bool type; }; // CRTP base template <int RTYPE, typename E> class BindableExpression { public: typedef typename cbind_storage_type<RTYPE>::type stored_type; inline stored_type operator[](R_xlen_t i) const { return static_cast<const E&>(*this)[i]; } inline stored_type operator()(R_xlen_t i, R_xlen_t j) const { return static_cast<const E&>(*this)(i, j); } inline R_xlen_t size() const { return static_cast<const E&>(*this).size(); } inline R_xlen_t nrow() const { return static_cast<const E&>(*this).nrow(); } inline R_xlen_t ncol() const { return static_cast<const E&>(*this).ncol(); } operator E&() { return static_cast<E&>(*this); } operator const E&() const { return static_cast<const E&>(*this); } }; // Matrix, Vector interface to BindableExpression template <int RTYPE, typename T> class ContainerBindable : public BindableExpression<RTYPE, ContainerBindable<RTYPE, T> > { public: typedef typename cbind_storage_type<RTYPE>::type stored_type; private: T vec; R_xlen_t len, nr, nc; public: ContainerBindable(const Rcpp::Matrix<RTYPE>& vec_) : vec(vec_), len(vec.ncol() * vec.nrow()), nr(vec.nrow()), nc(vec.ncol()) {} ContainerBindable(const Rcpp::Vector<RTYPE>& vec_) : vec(vec_), len(vec.size()), nr(vec.size()), nc(1) {} template <typename S> ContainerBindable(const BindableExpression<RTYPE, S>& e) : vec(e.size()), len(e.size()), nr(e.nrow()), nc(e.ncol()) { for (R_xlen_t i = 0; i < len; i++) { vec[i] = e[i]; } } inline R_xlen_t size() const { return len; } inline R_xlen_t nrow() const { return nr; } inline R_xlen_t ncol() const { return nc; } inline stored_type operator[](R_xlen_t i) const { return vec[i]; } inline stored_type operator()(R_xlen_t i, R_xlen_t j) const { return vec[i + nr * j]; } }; template <int RTYPE> struct scalar { typedef typename cbind_storage_type<RTYPE>::type type; }; // scalar interface to BindableExpression template <typename T> class ScalarBindable : public BindableExpression< cbind_sexptype_traits<T>::rtype, ScalarBindable<T> > { public: typedef T stored_type; enum { RTYPE = cbind_sexptype_traits<T>::rtype }; private: T t; public: ScalarBindable(const T& t_) : t(t_) {} inline R_xlen_t size() const { return 1; } inline R_xlen_t nrow() const { return 1; } inline R_xlen_t ncol() const { return 1; } inline stored_type operator[](R_xlen_t i) const { return t; } inline stored_type operator()(R_xlen_t i, R_xlen_t j) const { return t; } }; // binding logic; non-scalar operands template <int RTYPE, typename E1, typename E2> class JoinOp : public BindableExpression<RTYPE, JoinOp<RTYPE, E1, E2> >, public Rcpp::MatrixBase<RTYPE, true, JoinOp<RTYPE, E1, E2> > { public: typedef typename cbind_storage_type<RTYPE>::type stored_type; private: const E1& e1; const E2& e2; public: JoinOp(const BindableExpression<RTYPE, E1>& e1_, const BindableExpression<RTYPE, E2>& e2_) : e1(e1_), e2(e2_) { if (e1.nrow() != e2.nrow()) { std::string msg = "Error in cbind: " "Matrix and Vector operands " "must have equal " "number of rows (length)."; Rcpp::stop(msg); } } inline R_xlen_t size() const { return e1.size() + e2.size(); } inline R_xlen_t nrow() const { return e1.nrow(); } inline R_xlen_t ncol() const { return e1.ncol() + e2.ncol(); } inline stored_type operator[](R_xlen_t i) const { return (i < e1.size()) ? e1[i] : e2[i - e1.size()]; } inline stored_type operator()(R_xlen_t i, R_xlen_t j) const { R_xlen_t index = i + nrow() * j; return (*this)[index]; } }; // binding logic; rhs scalar template <int RTYPE, typename E1> class JoinOp<RTYPE, E1, ScalarBindable<typename scalar<RTYPE>::type> > : public BindableExpression<RTYPE, JoinOp<RTYPE, E1, ScalarBindable<typename scalar<RTYPE>::type> > >, public Rcpp::MatrixBase<RTYPE, true, JoinOp<RTYPE, E1, ScalarBindable<typename scalar<RTYPE>::type> > > { public: typedef typename cbind_storage_type<RTYPE>::type stored_type; typedef ScalarBindable<typename scalar<RTYPE>::type> E2; private: const E1& e1; const E2& e2; public: JoinOp(const BindableExpression<RTYPE, E1>& e1_, const BindableExpression<RTYPE, E2>& e2_) : e1(e1_), e2(e2_) {} inline R_xlen_t size() const { return e1.size() + e1.nrow(); } inline R_xlen_t nrow() const { return e1.nrow(); } inline R_xlen_t ncol() const { return e1.ncol() + 1; } inline stored_type operator[](R_xlen_t i) const { return (i < e1.size()) ? e1[i] : e2[i]; } inline stored_type operator()(R_xlen_t i, R_xlen_t j) const { R_xlen_t index = i + nrow() * j; return (*this)[index]; } }; // binding logic; lhs scalar template <int RTYPE, typename E2> class JoinOp<RTYPE, ScalarBindable<typename scalar<RTYPE>::type>, E2> : public BindableExpression<RTYPE, JoinOp<RTYPE, ScalarBindable<typename scalar<RTYPE>::type>, E2> >, public Rcpp::MatrixBase<RTYPE, true, JoinOp<RTYPE, ScalarBindable<typename scalar<RTYPE>::type>, E2> > { public: typedef typename cbind_storage_type<RTYPE>::type stored_type; typedef ScalarBindable<typename scalar<RTYPE>::type> E1; private: const E1& e1; const E2& e2; public: JoinOp(const BindableExpression<RTYPE, E1>& e1_, const BindableExpression<RTYPE, E2>& e2_) : e1(e1_), e2(e2_) {} inline R_xlen_t size() const { return e2.size() + e2.nrow(); } inline R_xlen_t nrow() const { return e2.nrow(); } inline R_xlen_t ncol() const { return e2.ncol() + 1; } inline stored_type operator[](R_xlen_t i) const { return (i < e2.nrow()) ? e1[i] : e2[i - e2.nrow()]; } inline stored_type operator()(R_xlen_t i, R_xlen_t j) const { R_xlen_t index = i + nrow() * j; return (*this)[index]; } }; // binding logic; both scalar template <int RTYPE> class JoinOp<RTYPE, ScalarBindable<typename scalar<RTYPE>::type>, ScalarBindable<typename scalar<RTYPE>::type> > : public BindableExpression<RTYPE, JoinOp<RTYPE, ScalarBindable<typename scalar<RTYPE>::type>, ScalarBindable<typename scalar<RTYPE>::type> > >, public Rcpp::MatrixBase<RTYPE, true, JoinOp<RTYPE, ScalarBindable<typename scalar<RTYPE>::type>, ScalarBindable<typename scalar<RTYPE>::type> > > { public: typedef typename cbind_storage_type<RTYPE>::type stored_type; typedef ScalarBindable<typename scalar<RTYPE>::type> E1; typedef ScalarBindable<typename scalar<RTYPE>::type> E2; private: const E1& e1; const E2& e2; public: JoinOp(const BindableExpression<RTYPE, E1>& e1_, const BindableExpression<RTYPE, E2>& e2_) : e1(e1_), e2(e2_) {} inline R_xlen_t size() const { return e2.size() + e2.nrow(); } inline R_xlen_t nrow() const { return e2.nrow(); } inline R_xlen_t ncol() const { return e2.ncol() + 1; } inline stored_type operator[](R_xlen_t i) const { return (i < e2.nrow()) ? e1[i] : e2[i]; } inline stored_type operator()(R_xlen_t i, R_xlen_t j) const { R_xlen_t index = i + nrow() * j; return (*this)[index]; } }; // for template argument deduction template <int RTYPE> inline ContainerBindable<RTYPE, Rcpp::Matrix<RTYPE> > MakeContainerBindable(const Rcpp::Matrix<RTYPE>& x) { return ContainerBindable<RTYPE, Rcpp::Matrix<RTYPE> >(x); } template <int RTYPE> inline ContainerBindable<RTYPE, Rcpp::Vector<RTYPE> > MakeContainerBindable(const Rcpp::Vector<RTYPE>& x) { return ContainerBindable<RTYPE, Rcpp::Vector<RTYPE> >(x); } template <> inline ContainerBindable<LGLSXP, Rcpp::Matrix<LGLSXP> > MakeContainerBindable(const Rcpp::Matrix<LGLSXP>& x) { return ContainerBindable<LGLSXP, Rcpp::Matrix<LGLSXP> >(x); } template <> inline ContainerBindable<LGLSXP, Rcpp::Vector<LGLSXP> > MakeContainerBindable(const Rcpp::Vector<LGLSXP>& x) { return ContainerBindable<LGLSXP, Rcpp::Vector<LGLSXP> >(x); } template <typename T> inline ScalarBindable<T> MakeScalarBindable(const T& t) { return ScalarBindable<T>(t); } // for expressions of arbitrary length template <int RTYPE, typename E1, typename E2> inline JoinOp<RTYPE, E1, E2> operator,( const BindableExpression<RTYPE, E1>& e1, const BindableExpression<RTYPE, E2>& e2) { return JoinOp<RTYPE, E1, E2>(e1, e2); } // helpers namespace detail { // distinguish Matrix/Vector from scalar template <typename T> class has_stored_type { private: typedef char yes; typedef struct { char array[2]; } no; template <typename C> static yes test(typename C::stored_type*); template <typename C> static no test(...); public: static const bool value = sizeof(test<T>(0)) == sizeof(yes); }; // functor to dispatch appropriate Make*Bindable() call template <typename T, bool is_container = has_stored_type<T>::value> struct MakeBindableCall {}; template <typename T> struct MakeBindableCall<T, true> { typedef typename cbind_storage_type< cbind_sexptype_traits<typename T::stored_type>::rtype >::type stored_type; enum { RTYPE = cbind_sexptype_traits<stored_type>::rtype }; ContainerBindable<RTYPE, T> operator()(const T& t) const { return MakeContainerBindable(t); } }; // specialize for LGLSXP template <> struct MakeBindableCall<Rcpp::Matrix<LGLSXP>, true> { typedef Rcpp::Matrix<LGLSXP> T; typedef bool stored_type; enum { RTYPE = cbind_sexptype_traits<stored_type>::rtype }; ContainerBindable<LGLSXP, T> operator()(const T& t) const { return MakeContainerBindable(t); } }; template <> struct MakeBindableCall<Rcpp::Vector<LGLSXP>, true> { typedef Rcpp::Vector<LGLSXP> T; typedef bool stored_type; enum { RTYPE = cbind_sexptype_traits<stored_type>::rtype }; ContainerBindable<LGLSXP, T> operator()(const T& t) const { return MakeContainerBindable(t); } }; template <typename T> struct MakeBindableCall<T, false> { enum { RTYPE = cbind_sexptype_traits<T>::rtype }; ScalarBindable<T> operator()(const T& t) const { return MakeScalarBindable(t); } }; template <typename T> inline typename Rcpp::traits::enable_if< has_stored_type<T>::value, MakeBindableCall<T, true> >::type MakeBindable(const T& t) { return MakeBindableCall<T, true>(); } template <typename T> inline typename Rcpp::traits::enable_if< !has_stored_type<T>::value, MakeBindableCall<T, false> >::type MakeBindable(const T& t) { return MakeBindableCall<T, false>(); } // determine cbind return type from first template // parameter, agnostic of Matrix/Vector/scalar template <typename T, bool is_container = has_stored_type<T>::value> struct matrix_return {}; template <typename T> struct matrix_return<T, true> { typedef typename cbind_storage_type< cbind_sexptype_traits<typename T::stored_type>::rtype >::type stored_type; enum { RTYPE = cbind_sexptype_traits<stored_type>::rtype }; typedef Rcpp::Matrix<RTYPE> type; }; // specialize for LGLSXP // normally would default to IntegerMatrix template <> struct matrix_return<Rcpp::Matrix<LGLSXP>, true> { typedef Rcpp::Matrix<LGLSXP> type; }; template <> struct matrix_return<Rcpp::Vector<LGLSXP>, true> { typedef Rcpp::Matrix<LGLSXP> type; }; template <> struct matrix_return<bool, false> { typedef Rcpp::Matrix<LGLSXP> type; }; template <typename T> struct matrix_return<T, false> { enum { RTYPE = cbind_sexptype_traits<T>::rtype }; typedef Rcpp::Matrix<RTYPE> type; }; } // detail template <typename T, bool B = detail::has_stored_type<T>::value> struct matrix_return : public detail::matrix_return<T, B> {}; template <typename T> struct matrix_return<T, false> : public detail::matrix_return<T, false> {}; } // cbind_impl #define MakeBindable(x) (cbind_impl::detail::MakeBindable(x)(x)) // begin cbind overloads template<typename T1, typename T2> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2) { return (MakeBindable(t1), MakeBindable(t2)); } template<typename T1, typename T2, typename T3> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3)); } template<typename T1, typename T2, typename T3, typename T4> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4)); } // 5 template<typename T1, typename T2, typename T3, typename T4, typename T5> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9)); } // 10 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14)); } // 15 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19)); } // 20 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24)); } // 25 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29)); } // 30 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34)); } // 35 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38, const T39& t39) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38), MakeBindable(t39)); } // 40 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38, const T39& t39, const T40& t40) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38), MakeBindable(t39), MakeBindable(t40)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38, const T39& t39, const T40& t40, const T41& t41) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38), MakeBindable(t39), MakeBindable(t40), MakeBindable(t41)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38, const T39& t39, const T40& t40, const T41& t41, const T42& t42) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38), MakeBindable(t39), MakeBindable(t40), MakeBindable(t41), MakeBindable(t42)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38, const T39& t39, const T40& t40, const T41& t41, const T42& t42, const T43& t43) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38), MakeBindable(t39), MakeBindable(t40), MakeBindable(t41), MakeBindable(t42), MakeBindable(t43)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38, const T39& t39, const T40& t40, const T41& t41, const T42& t42, const T43& t43, const T44& t44) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38), MakeBindable(t39), MakeBindable(t40), MakeBindable(t41), MakeBindable(t42), MakeBindable(t43), MakeBindable(t44)); } // 45 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38, const T39& t39, const T40& t40, const T41& t41, const T42& t42, const T43& t43, const T44& t44, const T45& t45) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38), MakeBindable(t39), MakeBindable(t40), MakeBindable(t41), MakeBindable(t42), MakeBindable(t43), MakeBindable(t44), MakeBindable(t45)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38, const T39& t39, const T40& t40, const T41& t41, const T42& t42, const T43& t43, const T44& t44, const T45& t45, const T46& t46) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38), MakeBindable(t39), MakeBindable(t40), MakeBindable(t41), MakeBindable(t42), MakeBindable(t43), MakeBindable(t44), MakeBindable(t45), MakeBindable(t46)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38, const T39& t39, const T40& t40, const T41& t41, const T42& t42, const T43& t43, const T44& t44, const T45& t45, const T46& t46, const T47& t47) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38), MakeBindable(t39), MakeBindable(t40), MakeBindable(t41), MakeBindable(t42), MakeBindable(t43), MakeBindable(t44), MakeBindable(t45), MakeBindable(t46), MakeBindable(t47)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38, const T39& t39, const T40& t40, const T41& t41, const T42& t42, const T43& t43, const T44& t44, const T45& t45, const T46& t46, const T47& t47, const T48& t48) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38), MakeBindable(t39), MakeBindable(t40), MakeBindable(t41), MakeBindable(t42), MakeBindable(t43), MakeBindable(t44), MakeBindable(t45), MakeBindable(t46), MakeBindable(t47), MakeBindable(t48)); } template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48, typename T49> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38, const T39& t39, const T40& t40, const T41& t41, const T42& t42, const T43& t43, const T44& t44, const T45& t45, const T46& t46, const T47& t47, const T48& t48, const T49& t49) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38), MakeBindable(t39), MakeBindable(t40), MakeBindable(t41), MakeBindable(t42), MakeBindable(t43), MakeBindable(t44), MakeBindable(t45), MakeBindable(t46), MakeBindable(t47), MakeBindable(t48), MakeBindable(t49)); } // 50 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48, typename T49, typename T50> inline typename cbind_impl::matrix_return<T1>::type cbind(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10, const T11& t11, const T12& t12, const T13& t13, const T14& t14, const T15& t15, const T16& t16, const T17& t17, const T18& t18, const T19& t19, const T20& t20, const T21& t21, const T22& t22, const T23& t23, const T24& t24, const T25& t25, const T26& t26, const T27& t27, const T28& t28, const T29& t29, const T30& t30, const T31& t31, const T32& t32, const T33& t33, const T34& t34, const T35& t35, const T36& t36, const T37& t37, const T38& t38, const T39& t39, const T40& t40, const T41& t41, const T42& t42, const T43& t43, const T44& t44, const T45& t45, const T46& t46, const T47& t47, const T48& t48, const T49& t49, const T50& t50) { return (MakeBindable(t1), MakeBindable(t2), MakeBindable(t3), MakeBindable(t4), MakeBindable(t5), MakeBindable(t6), MakeBindable(t7), MakeBindable(t8), MakeBindable(t9), MakeBindable(t10), MakeBindable(t11), MakeBindable(t12), MakeBindable(t13), MakeBindable(t14), MakeBindable(t15), MakeBindable(t16), MakeBindable(t17), MakeBindable(t18), MakeBindable(t19), MakeBindable(t20), MakeBindable(t21), MakeBindable(t22), MakeBindable(t23), MakeBindable(t24), MakeBindable(t25), MakeBindable(t26), MakeBindable(t27), MakeBindable(t28), MakeBindable(t29), MakeBindable(t30), MakeBindable(t31), MakeBindable(t32), MakeBindable(t33), MakeBindable(t34), MakeBindable(t35), MakeBindable(t36), MakeBindable(t37), MakeBindable(t38), MakeBindable(t39), MakeBindable(t40), MakeBindable(t41), MakeBindable(t42), MakeBindable(t43), MakeBindable(t44), MakeBindable(t45), MakeBindable(t46), MakeBindable(t47), MakeBindable(t48), MakeBindable(t49), MakeBindable(t50)); } // end cbind overloads #undef MakeBindable } // sugar namespace { using sugar::cbind; } } // Rcpp #endif // Rcpp__sugar__cbind_h
import React from 'react' const SectionBreak = () => { return ( <hr className="govuk-section-break govuk-section-break--m govuk-section-break--visible" /> ) } export default SectionBreak
#include "Project.h" class ProjectLibrary { private: vector<Project> projects; public: ProjectLibrary() {} // Create a project void createProject(string name, string description) { Project project(name, description); projects.push_back(project); } // Delete a project void deleteProject(int id) { for (int i = 0; i < projects.size(); i++) { if (projects[i].getId() == id) { projects.erase(projects.begin() + i); } } } // Update a project void updateProject(int id, string newName, string newDescription) { for (int i = 0; i < projects.size(); i++) { if (projects[i].getId() == id) { projects[i].setName(newName); projects[i].setDescription(newDescription); } } } };
<filename>module_setting/src/main/java/arouter/dawn/zju/edu/module_mine/ui/mine/MineContract.java<gh_stars>1-10 package arouter.dawn.zju.edu.module_mine.ui.mine; import baselib.base.BaseContract; /** * @Auther: Dawn * @Date: 2018/11/22 22:01 * @Description: */ public interface MineContract { interface View extends BaseContract.BaseView { void refreshCashCouponCount(int count); } interface Presenter extends BaseContract.BasePresenter<View> { void refreshCashCouponCount(); } }
<filename>core/server/worker/src/main/java/alluxio/worker/block/meta/StorageTierView.java<gh_stars>1-10 /* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.worker.block.meta; import alluxio.worker.block.BlockMetadataManagerView; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.annotation.concurrent.ThreadSafe; /** * This class is a wrapper of {@link StorageTier} to provide more limited access. */ @ThreadSafe public final class StorageTierView { /** The {@link StorageTier} this view is derived from. */ private final StorageTier mTier; /** A list of {@link StorageDirView} under this StorageTierView. */ private final List<StorageDirView> mDirViews = new ArrayList<>(); /** The {@link BlockMetadataManagerView} this {@link StorageTierView} is under. */ private final BlockMetadataManagerView mManagerView; /** * Creates a {@link StorageTierView} using the actual {@link StorageTier} and the above * {@link BlockMetadataManagerView}. * * @param tier which the tierView is constructed from * @param view the {@link BlockMetadataManagerView} this tierView is associated with */ public StorageTierView(StorageTier tier, BlockMetadataManagerView view) { mTier = Preconditions.checkNotNull(tier); mManagerView = Preconditions.checkNotNull(view); for (StorageDir dir : mTier.getStorageDirs()) { StorageDirView dirView = new StorageDirView(dir, this, view); mDirViews.add(dirView); } } /** * @return a list of directory views in this storage tier view */ public List<StorageDirView> getDirViews() { return Collections.unmodifiableList(mDirViews); } /** * Returns a directory view for the given index. * * @param dirIndex the directory view index * @return a directory view */ public StorageDirView getDirView(int dirIndex) { return mDirViews.get(dirIndex); } /** * @return the storage tier view alias */ public String getTierViewAlias() { return mTier.getTierAlias(); } /** * @return the ordinal value of the storage tier view */ public int getTierViewOrdinal() { return mTier.getTierOrdinal(); } /** * @return the block metadata manager view for this storage tier view */ public BlockMetadataManagerView getBlockMetadataManagerView() { return mManagerView; } }
<reponame>bishernob/bus_mall var Name_of_Images =[]; var Images_arr =[]; var view=0; var vote=0; function Images_of_product(img_name,img_src){ this.img_src = img_src; Name_of_Images.push(img_name); Images_arr.push(img_src); } var leftimg; var centerimg; var rightimg; var maximum_of_clicks=25; var num_of_clicks=0; var all_of_imgs= document.getElementById('all_of_imgs'); var firstimg = document.getElementById('firstimg'); var secondimg = document.getElementById('secondimg'); var thirdimg = document.getElementById('thirdimg'); var result = document.getElementById('final_result'); var form = document.getElementById('form'); var button_result = document.getElementById('button_result'); new Images_of_product('bag','img/bag.jpg'); new Images_of_product('banana','img/banana.jpg'); new Images_of_product('bathroom','img/bathroom.jpg'); new Images_of_product('boots','img/boots.jpg'); new Images_of_product('breakfast','img/breakfast.jpg'); new Images_of_product('bubblegum','img/bubblegum.jpg'); new Images_of_product('chair','img/chair.jpg'); new Images_of_product('cthulhu','img/cthulhu.jpg'); new Images_of_product('dog-duck','img/dog-duck.jpg'); new Images_of_product('dragon','img/dragon.jpg'); new Images_of_product('pen','img/pen.jpg'); new Images_of_product('pet-sweep','img/pet-sweep.jpg'); new Images_of_product('scissors','img/scissors.jpg'); new Images_of_product('shark','img/shark.jpg'); new Images_of_product('sweep','img/sweep.png'); new Images_of_product('tauntaun','img/tauntaun.jpg'); new Images_of_product('unicorn','img/unicorn.jpg'); new Images_of_product('usb','img/usb.gif'); new Images_of_product('water-can','img/water-can.jpg'); new Images_of_product('wine-glass','img/wine-glass.jpg'); function random_images(){ return Math.floor(Math.random()*20); } function render() { leftimg = random_images(); do { rightimg = random_images(); centerimg = random_images(); } while (leftimg===rightimg ||leftimg===centerimg||centerimg===rightimg); firstimg.setAttribute("src",Images_arr[leftimg]); Images_arr[leftimg] secondimg.setAttribute("src",Images_arr[centerimg]); Images_arr[centerimg] thirdimg.setAttribute("src",Images_arr[rightimg]); Images_arr[rightimg] } render(); function User_selection() { num_of_clicks= num_of_clicks+1; view++; if (num_of_clicks < maximum_of_clicks){ if(event.target.id==='firstimg') { Images_arr[leftimg]; vote++; render(); } else if(event.target.id ==='secondimg') { Images_arr[centerimg]; vote++; render(); } else if(event.target.id ==='thirdimg') { Images_arr[rightimg]; vote++; render(); } else { all_of_imgs.removeEventListener('click',User_selection); } } } function Results() { for (var x = 0; x< Images_arr.length; x++) { var finalresult=document.createElement('li'); finalresult.textContent= Name_of_Images[x] + ' click ' + num_of_clicks + ' and number of views = '+ view + ' number of votes '+ vote+ ' percentage for this image '+ (vote * 100 / view)+'%'; result.appendChild(finalresult); } showChart(); } // function Rounds(event) { // maximum_of_clicks = event.target.round_number.value; //} all_of_imgs.addEventListener('click',User_selection); button_result.addEventListener('click',Results); function showChart() { var votes_arr=[]; var view_arr=[]; for (var i = 0; i < Images_arr.length; i++) { votes_arr.push(vote); view_arr.push(view); } var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { type: 'bar', data: { labels: Name_of_Images, datasets: [{ label: 'votes', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: votes_arr, }, { label: 'Your view', backgroundColor: 'rgb(0, 0, 0)', borderColor: 'rgb(0, 0, 0)', data: view_arr, } ] }, options: { scales: { yAxes: [{ ticks: { max: 10, min: 0, beginAtZero: 0, stepSize: 1, } }], } } }); }
<filename>src/main/java/com/infinities/skyport/timeout/service/TimedIdentityServices.java /******************************************************************************* * Copyright 2015 InfinitiesSoft Solutions Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. *******************************************************************************/ package com.infinities.skyport.timeout.service; import java.util.concurrent.ExecutorService; import org.dasein.cloud.identity.IdentityAndAccessSupport; import org.dasein.cloud.identity.IdentityServices; import org.dasein.cloud.identity.ShellKeySupport; import com.infinities.skyport.exception.InitializationException; import com.infinities.skyport.model.configuration.service.IdentityConfiguration; import com.infinities.skyport.timeout.ServiceProviderTimeLimiter; public class TimedIdentityServices implements IdentityServices { private final IdentityServices inner; private IdentityAndAccessSupport timedIdentityAndAccessSupport; private ShellKeySupport timedShellKeySupport; public TimedIdentityServices(IdentityServices inner, IdentityConfiguration identityConfiguration, ExecutorService executor) throws InitializationException { this.inner = inner; ServiceProviderTimeLimiter timedLimiter = new ServiceProviderTimeLimiter(executor); if (inner.hasIdentityAndAccessSupport()) { this.timedIdentityAndAccessSupport = timedLimiter.newProxy(inner.getIdentityAndAccessSupport(), IdentityAndAccessSupport.class, identityConfiguration.getIdentityAndAccessConfiguration()); } if (inner.hasShellKeySupport()) { this.timedShellKeySupport = timedLimiter.newProxy(inner.getShellKeySupport(), ShellKeySupport.class, identityConfiguration.getShellKeyConfiguration()); } } @Override public IdentityAndAccessSupport getIdentityAndAccessSupport() { return this.timedIdentityAndAccessSupport; } @Override public ShellKeySupport getShellKeySupport() { return this.timedShellKeySupport; } @Override public boolean hasIdentityAndAccessSupport() { return inner.hasIdentityAndAccessSupport(); } @Override public boolean hasShellKeySupport() { return inner.hasShellKeySupport(); } }
package gocal import ( "bufio" "fmt" "io" "strconv" "strings" "time" "github.com/apognu/gocal/parser" ) func NewParser(r io.Reader) *Gocal { return &Gocal{ scanner: bufio.NewScanner(r), Events: make([]Event, 0), Strict: StrictParams{ Mode: StrictModeFailFeed, }, SkipBounds: false, } } func (gc *Gocal) Parse() error { if gc.Start == nil { start := time.Now().Add(-1 * 24 * time.Hour) gc.Start = &start } if gc.End == nil { end := time.Now().Add(3 * 30 * 24 * time.Hour) gc.End = &end } gc.scanner.Scan() rInstances := make([]Event, 0) ctx := &Context{Value: ContextRoot} for { l, err, done := gc.parseLine() if err != nil { if done { break } continue } if l.IsValue("VCALENDAR") { continue } if ctx.Value == ContextRoot && l.Is("BEGIN", "VEVENT") { ctx = ctx.Nest(ContextEvent) gc.buffer = &Event{Valid: true, delayed: make([]*Line, 0)} } else if ctx.Value == ContextRoot && l.IsKey("METHOD") { gc.Method = l.Value } else if ctx.Value == ContextEvent && l.Is("END", "VEVENT") { if ctx.Previous == nil { return fmt.Errorf("got an END:* without matching BEGIN:*") } ctx = ctx.Previous for _, d := range gc.buffer.delayed { gc.parseEvent(d) } // Some tools return single full day events as inclusive (same DTSTART // and DTEND) which goes against RFC. Standard tools still handle those // as events spanning 24 hours. if gc.buffer.RawStart.Value == gc.buffer.RawEnd.Value { if value, ok := gc.buffer.RawEnd.Params["VALUE"]; ok && value == "DATE" { gc.buffer.End, err = parser.ParseTime(gc.buffer.RawEnd.Value, gc.buffer.RawEnd.Params, parser.TimeEnd, true) } } // If an event has a VALUE=DATE start date and no end date, event lasts a day if gc.buffer.End == nil && gc.buffer.RawStart.Params["VALUE"] == "DATE" { d := (*gc.buffer.Start).Add(24 * time.Hour) gc.buffer.End = &d } err := gc.checkEvent() if err != nil { switch gc.Strict.Mode { case StrictModeFailFeed: return fmt.Errorf(fmt.Sprintf("gocal error: %s", err)) case StrictModeFailEvent: continue } } if gc.buffer.Start == nil || gc.buffer.End == nil { continue } if gc.buffer.IsRecurring { rInstances = append(rInstances, gc.ExpandRecurringEvent(gc.buffer)...) } else { if gc.buffer.End == nil || gc.buffer.Start == nil { continue } if !gc.SkipBounds && !gc.IsInRange(*gc.buffer) { continue } gc.Events = append(gc.Events, *gc.buffer) } } else if l.IsKey("BEGIN") { ctx = ctx.Nest(ContextUnknown) } else if l.IsKey("END") { if ctx.Previous == nil { return fmt.Errorf("got an END:%s without matching BEGIN:%s", l.Value, l.Value) } ctx = ctx.Previous } else if ctx.Value == ContextEvent { err := gc.parseEvent(l) if err != nil { return fmt.Errorf(fmt.Sprintf("gocal error: %s", err)) } } else { continue } if done { break } } for _, i := range rInstances { if !gc.IsRecurringInstanceOverriden(&i) && gc.IsInRange(i) { gc.Events = append(gc.Events, i) } } return nil } func (gc *Gocal) parseLine() (*Line, error, bool) { // Get initial current line and check if that was the last one l := gc.scanner.Text() done := !gc.scanner.Scan() // If not, try and figure out if value is continued on next line if !done { for strings.HasPrefix(gc.scanner.Text(), " ") { l = l + strings.TrimPrefix(gc.scanner.Text(), " ") if done = !gc.scanner.Scan(); done { break } } } tokens := strings.SplitN(l, ":", 2) if len(tokens) < 2 { return nil, fmt.Errorf("could not parse item: %s", l), done } attr, params := parser.ParseParameters(tokens[0]) return &Line{Key: attr, Params: params, Value: parser.UnescapeString(strings.TrimPrefix(tokens[1], " "))}, nil, done } func (gc *Gocal) parseEvent(l *Line) error { var err error // If this is nil, that means we did not get a BEGIN:VEVENT if gc.buffer == nil { return nil } switch l.Key { case "UID": if gc.buffer.Uid != "" { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } gc.buffer.Uid = l.Value case "SUMMARY": if gc.buffer.Summary != "" { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } gc.buffer.Summary = l.Value case "DESCRIPTION": if gc.buffer.Description != "" { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } gc.buffer.Description = l.Value case "DTSTART": if gc.buffer.Start != nil { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } gc.buffer.Start, err = parser.ParseTime(l.Value, l.Params, parser.TimeStart, false) gc.buffer.RawStart = RawDate{Value: l.Value, Params: l.Params} if err != nil { return fmt.Errorf("could not parse %s: %s", l.Key, l.Value) } case "DTEND": gc.buffer.End, err = parser.ParseTime(l.Value, l.Params, parser.TimeEnd, false) gc.buffer.RawEnd = RawDate{Value: l.Value, Params: l.Params} if err != nil { return fmt.Errorf("could not parse %s: %s", l.Key, l.Value) } case "DURATION": if gc.buffer.Start == nil { gc.buffer.delayed = append(gc.buffer.delayed, l) return nil } duration, err := parser.ParseDuration(l.Value) if err != nil { return fmt.Errorf("could not parse %s: %s", l.Key, l.Value) } gc.buffer.Duration = duration end := gc.buffer.Start.Add(*duration) gc.buffer.End = &end case "DTSTAMP": gc.buffer.Stamp, err = parser.ParseTime(l.Value, l.Params, parser.TimeStart, false) if err != nil { return fmt.Errorf("could not parse %s: %s", l.Key, l.Value) } case "CREATED": if gc.buffer.Created != nil { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } gc.buffer.Created, err = parser.ParseTime(l.Value, l.Params, parser.TimeStart, false) if err != nil { return fmt.Errorf("could not parse %s: %s", l.Key, l.Value) } case "LAST-MODIFIED": if gc.buffer.LastModified != nil { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } gc.buffer.LastModified, err = parser.ParseTime(l.Value, l.Params, parser.TimeStart, false) if err != nil { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } case "RRULE": if len(gc.buffer.RecurrenceRule) != 0 { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } gc.buffer.IsRecurring = true gc.buffer.RecurrenceRule, err = parser.ParseRecurrenceRule(l.Value) case "RECURRENCE-ID": if gc.buffer.RecurrenceID != "" { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } gc.buffer.RecurrenceID = l.Value case "EXDATE": d, err := parser.ParseTime(l.Value, map[string]string{}, parser.TimeStart, false) if err == nil { gc.buffer.ExcludeDates = append(gc.buffer.ExcludeDates, *d) } case "SEQUENCE": gc.buffer.Sequence, _ = strconv.Atoi(l.Value) case "LOCATION": if gc.buffer.Location != "" { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } gc.buffer.Location = l.Value case "STATUS": if gc.buffer.Status != "" { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } gc.buffer.Status = l.Value case "ORGANIZER": if gc.buffer.Organizer != nil { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } gc.buffer.Organizer = &Organizer{ Cn: l.Params["CN"], DirectoryDn: l.Params["DIR"], Value: l.Value, } case "ATTENDEE": attendee := Attendee{ Value: l.Value, } for key, val := range l.Params { key := strings.ToUpper(key) switch key { case "CN": attendee.Cn = val case "DIR": attendee.DirectoryDn = val case "PARTSTAT": attendee.Status = val default: if strings.HasPrefix(key, "X-") { if attendee.CustomAttributes == nil { attendee.CustomAttributes = make(map[string]string) } attendee.CustomAttributes[key] = val } } } gc.buffer.Attendees = append(gc.buffer.Attendees, attendee) case "ATTACH": gc.buffer.Attachments = append(gc.buffer.Attachments, Attachment{ Type: l.Params["VALUE"], Encoding: l.Params["ENCODING"], Mime: l.Params["FMTTYPE"], Filename: l.Params["FILENAME"], Value: l.Value, }) case "GEO": if gc.buffer.Geo != nil { return fmt.Errorf("could not parse duplicate %s: %s", l.Key, l.Value) } lat, long, err := parser.ParseGeo(l.Value) if err != nil { return err } gc.buffer.Geo = &Geo{lat, long} case "CATEGORIES": gc.buffer.Categories = strings.Split(l.Value, ",") case "URL": gc.buffer.URL = l.Value case "COMMENT": gc.buffer.Comment = l.Value default: key := strings.ToUpper(l.Key) if strings.HasPrefix(key, "X-") { if gc.buffer.CustomAttributes == nil { gc.buffer.CustomAttributes = make(map[string]string) } gc.buffer.CustomAttributes[key] = l.Value } } return nil } func (gc *Gocal) checkEvent() error { if gc.buffer.Uid == "" { gc.buffer.Valid = false return fmt.Errorf("could not parse event without UID") } if gc.buffer.Start == nil { gc.buffer.Valid = false return fmt.Errorf("could not parse event without DTSTART") } if gc.buffer.Stamp == nil { gc.buffer.Valid = false return fmt.Errorf("could not parse event without DTSTAMP") } if gc.buffer.RawEnd.Value != "" && gc.buffer.Duration != nil { return fmt.Errorf("only one of DTEND and DURATION must be provided") } return nil } func SetTZMapper(cb func(s string) (*time.Location, error)) { parser.TZMapper = cb }
import random def monte_carlo_simulation(func): # Generate random points within range N = 1000 x_values = [random.uniform(0, 1) for _ in range(N)] # Calculate function value for each point y_values = [func(x) for x in x_values] # Sum all y values total = sum(y_values) # Calculate simulation result monte_simulation = (1/N) * total return monte_simulation # Example f = lambda x: x**2 monte_carlo_simulation(f)
#!/bin/sh # SPDX-License-Identifier: BSD-2-Clause # # Copyright 2016 Bernard Parent # # Redistribution and use in source and binary forms, with or without modification, are # permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of # conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, this list # of conditions and the following disclaimer in the documentation and/or other # materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY # WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. if [ $# = 1 ] then { indent -nut -nv -gnu -l110 -br -brf -brs -ce -cdw -sob -npsl -nbfda -nprs -bap -pcs -bad -ncs $1 } else { echo "Wrong number of arguments!" echo "" echo "To change the format of test.c to the WARP standard format:" echo "$ indentwithwarpstyle.sh test.c" echo "" echo "To change the format of all */*.c files to the WARP standard format:" echo "$ indentwithwarpstyle.sh '*/*.c'" } fi;
<gh_stars>1-10 import pickle import time from abc import abstractmethod, ABC from threading import Timer from typing import List, Optional from .session import HttpSession class ISessionProvider(ABC): """ session 提供者基类,自定义 session 提供者时应该继承此类 此类不可被实例化 """ def __init__(self, expired: int, *args, **kwargs): """ :param expired: 过期时长,单位为秒 """ self.expired = expired # 每 5 秒执行一次检查 self.timer = Timer(5, self._drop_expire_session) self.timer.start() def _drop_expire_session(self): time_before = time.time() - self.expired expired_sessions = self.get_expired_session(time_before) for session_id in expired_sessions: # print('Drop expired session:' + session.id) self.remove(session_id) def is_expired(self, session: HttpSession) -> bool: return time.time() - session.last_access_time > self.expired def create(self, session_id: str) -> HttpSession: session = HttpSession(session_id, self.set, self.remove) # 实际存储了数据再创建 # self.set(session) return session @abstractmethod def get_expired_session(self, time_before: float) -> List[str]: """ 查询已经过期的 session 的 id :param time_before: 在此时间之前的 session 即为过期 :return: """ pass @abstractmethod def get(self, session_id: str) -> Optional[HttpSession]: """ 获取指定 id 的 session :param session_id: :return: """ pass @abstractmethod def set(self, session: HttpSession): """ 添加或更新指定的 session :param session: :return: """ pass @abstractmethod def exists(self, session_id: str) -> bool: """ 检索指定 id 的 session 是否存在 :param session_id: :return: """ pass @abstractmethod def remove(self, session_id: str): """ 销毁一个 session :param session_id: :return: """ @abstractmethod def dispose(self): """ 清空所有的 session, 回收 session provider :return: """ self.timer.join() class IDbSessionProvider(ISessionProvider): def __init__(self, pool, expired: int, *args, **kwargs): self.pool = pool """ :type: PooledDB """ if not self.table_exists(): self.create_table() super().__init__(expired, *args, **kwargs) def connect(self, shareable=True): return self.pool.connection(shareable) @abstractmethod def table_exists(self) -> bool: """ 判断 session 表是否存在 :return: """ pass @abstractmethod def create_table(self): """ 创建 session 表 :return: """ pass def parse(self, data: dict) -> HttpSession: """ 用于将字典转换成 HttpSession 对象 :param data: :return: """ session = HttpSession(data['id'], self.set, self.remove) session.creation_time = int(data['creation_time']) session.last_access_time = int(data['last_access_time']) session.store = pickle.loads(data['store']) return session def set(self, session: HttpSession): self.upsert(session.id, session.creation_time, session.last_access_time, pickle.dumps(session.store)) @abstractmethod def upsert(self, session_id: str, creation_time: float, last_access_time: float, store: bytes): pass @abstractmethod def dispose(self): self.pool.close()