_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q177700
|
Distance2D_F64.distance
|
test
|
public static double distance( Polygon2D_F64 poly , Point2D_F64 p ) {
return Math.sqrt(distanceSq(poly, p, null));
}
|
java
|
{
"resource": ""
}
|
q177701
|
Distance2D_F64.distanceSq
|
test
|
public static double distanceSq( Polygon2D_F64 poly , Point2D_F64 p , LineSegment2D_F64 storage ) {
if( storage == null )
storage = LineSegment2D_F64.wrap(null,null);
double minimum = Double.MAX_VALUE;
for (int i = 0; i < poly.size(); i++) {
int j = (i+1)%poly.size();
storage.a = poly.vertexes.data[i];
storage.b = poly.vertexes.data[j];
double d = distanceSq(storage, p);
if( d < minimum )
minimum = d;
}
return minimum;
}
|
java
|
{
"resource": ""
}
|
q177702
|
Distance2D_F64.distanceOrigin
|
test
|
public static double distanceOrigin( LineParametric2D_F64 line ) {
double top = line.slope.y*line.p.x - line.slope.x*line.p.y;
return Math.abs(top)/line.slope.norm();
}
|
java
|
{
"resource": ""
}
|
q177703
|
Distance2D_F64.distance
|
test
|
public static double distance(EllipseRotated_F64 ellipse , Point2D_F64 p ) {
return Math.sqrt(distance2(ellipse, p));
}
|
java
|
{
"resource": ""
}
|
q177704
|
Distance2D_F64.distance2
|
test
|
public static double distance2(EllipseRotated_F64 ellipse , Point2D_F64 p ) {
// put point into ellipse's reference frame
double cphi = Math.cos(ellipse.phi);
double sphi = Math.sin(ellipse.phi);
double xc = p.x - ellipse.center.x;
double yc = p.y - ellipse.center.y;
double r = Math.sqrt(xc*xc + yc*yc);
double x = cphi*xc + sphi*yc;
double y = -sphi*xc + cphi*yc;
double ct = x/r;
double st = y/r;
x = ellipse.center.x + ellipse.a*ct*cphi - ellipse.b*st*sphi;
y = ellipse.center.y + ellipse.a*ct*sphi + ellipse.b*st*cphi;
return p.distance2(x,y);
}
|
java
|
{
"resource": ""
}
|
q177705
|
InvertibleTransformSequence.addTransform
|
test
|
public void addTransform( boolean forward, T tran ) {
path.add( new Node<T>( tran, forward ) );
}
|
java
|
{
"resource": ""
}
|
q177706
|
ClosestPoint2D_F64.closestPoint
|
test
|
public static Point2D_F64 closestPoint( LineSegment2D_F64 line,
Point2D_F64 p,
Point2D_F64 output ) {
if( output == null )
output = new Point2D_F64();
double slopeX = line.b.x - line.a.x;
double slopeY = line.b.y - line.a.y;
double t = slopeX * ( p.x - line.a.x ) + slopeY * ( p.y - line.a.y );
t /= slopeX*slopeX + slopeY*slopeY;
if( t < 0 )
t = 0;
else if( t > 1 )
t = 1;
output.x = line.a.x + slopeX * t;
output.y = line.a.y + slopeY * t;
return output;
}
|
java
|
{
"resource": ""
}
|
q177707
|
ClosestPoint2D_F64.closestPoint
|
test
|
public static Point2D_F64 closestPoint( EllipseRotated_F64 ellipse , Point2D_F64 p ) {
ClosestPointEllipseAngle_F64 alg = new ClosestPointEllipseAngle_F64(GrlConstants.TEST_F64,30);
alg.setEllipse(ellipse);
alg.process(p);
return alg.getClosest();
}
|
java
|
{
"resource": ""
}
|
q177708
|
FitPolynomialSolverTall_F64.process
|
test
|
public boolean process(double[] data, int offset , int length , PolynomialCurve_F64 output ) {
int N = length/2;
int numCoefs = output.size();
A.reshape(N,numCoefs);
b.reshape(N,1);
x.reshape(numCoefs,1);
int end = offset+length;
for (int i = offset, idxA=0; i < end; i += 2) {
double x = data[i];
double y = data[i+1];
double pow = 1.0;
for (int j = 0; j < numCoefs; j++) {
A.data[idxA++] = pow;
pow *= x;
}
b.data[i/2] = y;
}
if( !solver.setA(A) )
return false;
solver.solve(b,x);
for (int i = 0; i < numCoefs; i++) {
output.set(i, x.data[i]);
}
return true;
}
|
java
|
{
"resource": ""
}
|
q177709
|
UtilVector3D_F64.createRandom
|
test
|
public static Vector3D_F64 createRandom( double min, double max, Random rand ) {
double range = max - min;
Vector3D_F64 a = new Vector3D_F64();
a.x = range * rand.nextDouble() + min;
a.y = range * rand.nextDouble() + min;
a.z = range * rand.nextDouble() + min;
return a;
}
|
java
|
{
"resource": ""
}
|
q177710
|
UtilVector3D_F64.perpendicularCanonical
|
test
|
public static Vector3D_F64 perpendicularCanonical( Vector3D_F64 A , Vector3D_F64 output ) {
if( output == null )
output = new Vector3D_F64();
// normalize for scaling
double scale = Math.abs(A.x)+Math.abs(A.y)+Math.abs(A.z);
if( scale == 0 ) {
output.set(0,0,0);
} else {
double x = A.x / scale;
double y = A.y / scale;
double z = A.z / scale;
// For numerical stability ensure that the largest variable is swapped
if (Math.abs(x) > Math.abs(y)) {
output.set(z, 0, -x);
} else {
output.set(0, z,-y);
}
}
return output;
}
|
java
|
{
"resource": ""
}
|
q177711
|
UtilVector3D_F64.isIdentical
|
test
|
public static boolean isIdentical( Vector3D_F64 a, Vector3D_F64 b, double tol ) {
if( Math.abs( a.x - b.x ) > tol )
return false;
if( Math.abs( a.y - b.y ) > tol )
return false;
return Math.abs( a.z - b.z ) <= tol;
}
|
java
|
{
"resource": ""
}
|
q177712
|
UtilVector3D_F64.normalize
|
test
|
public static void normalize( Vector3D_F64 v ) {
double a = v.norm();
v.x /= a;
v.y /= a;
v.z /= a;
}
|
java
|
{
"resource": ""
}
|
q177713
|
UtilVector3D_F64.createMatrix
|
test
|
public static DMatrixRMaj createMatrix( DMatrixRMaj R, Vector3D_F64... v ) {
if( R == null ) {
R = new DMatrixRMaj( 3, v.length );
}
for( int i = 0; i < v.length; i++ ) {
R.set( 0, i, v[i].x );
R.set( 1, i, v[i].y );
R.set( 2, i, v[i].z );
}
return R;
}
|
java
|
{
"resource": ""
}
|
q177714
|
UtilVector3D_F64.convert
|
test
|
public static Vector3D_F64 convert( DMatrixRMaj m ) {
Vector3D_F64 v = new Vector3D_F64();
v.x = (double) m.data[0];
v.y = (double) m.data[1];
v.z = (double) m.data[2];
return v;
}
|
java
|
{
"resource": ""
}
|
q177715
|
GeoTuple2D_F64.distance
|
test
|
public double distance( double x , double y ) {
double dx = x - this.x;
double dy = y - this.y;
return Math.sqrt(dx*dx + dy*dy);
}
|
java
|
{
"resource": ""
}
|
q177716
|
ClosestPointEllipseAngle_F64.setEllipse
|
test
|
public void setEllipse( EllipseRotated_F64 ellipse ) {
this.ellipse = ellipse;
ce = Math.cos(ellipse.phi);
se = Math.sin(ellipse.phi);
}
|
java
|
{
"resource": ""
}
|
q177717
|
Quaternion_F64.normalize
|
test
|
public void normalize() {
double n = Math.sqrt( w * w + x * x + y * y + z * z);
w /= n;
x /= n;
y /= n;
z /= n;
}
|
java
|
{
"resource": ""
}
|
q177718
|
Area2D_F64.triangle
|
test
|
public static double triangle( Point2D_F64 a, Point2D_F64 b, Point2D_F64 c ) {
double inner = a.x*(b.y - c.y) + b.x*(c.y - a.y) + c.x*(a.y - b.y);
return Math.abs(inner/2.0);
}
|
java
|
{
"resource": ""
}
|
q177719
|
Area2D_F64.quadrilateral
|
test
|
public static double quadrilateral( Quadrilateral_F64 quad ) {
double bx = quad.b.x-quad.a.x;
double by = quad.b.y-quad.a.y;
double cx = quad.c.x-quad.a.x;
double cy = quad.c.y-quad.a.y;
double dx = quad.d.x-quad.a.x;
double dy = quad.d.y-quad.a.y;
if( (bx * cy - by * cx >= 0) == (cx * dy - cy * dx >= 0)) {
return triangle(quad.a,quad.b,quad.c) + triangle(quad.a,quad.c,quad.d);
} else {
return triangle(quad.a,quad.b,quad.d) + triangle(quad.b,quad.c,quad.d);
}
}
|
java
|
{
"resource": ""
}
|
q177720
|
Area2D_F64.polygonSimple
|
test
|
public static double polygonSimple( Polygon2D_F64 poly ) {
double total = 0;
Point2D_F64 v0 = poly.get(0);
Point2D_F64 v1 = poly.get(1);
for (int i = 2; i < poly.size(); i++) {
Point2D_F64 v2 = poly.get(i);
total += v1.x*( v2.y - v0.y);
v0 = v1; v1 = v2;
}
Point2D_F64 v2 = poly.get(0);
total += v1.x*( v2.y - v0.y);
v0 = v1; v1 = v2;
v2 = poly.get(1);
total += v1.x*( v2.y - v0.y);
return Math.abs(total/2.0);
}
|
java
|
{
"resource": ""
}
|
q177721
|
UtilPoint2D_F64.mean
|
test
|
public static Point2D_F64 mean( Point2D_F64[] list , int offset , int length , Point2D_F64 mean ) {
if( mean == null )
mean = new Point2D_F64();
double x = 0;
double y = 0;
for (int i = 0; i < length; i++) {
Point2D_F64 p = list[offset+i];
x += p.getX();
y += p.getY();
}
x /= length;
y /= length;
mean.set(x, y);
return mean;
}
|
java
|
{
"resource": ""
}
|
q177722
|
UtilPoint2D_F64.orderCCW
|
test
|
public static List<Point2D_F64> orderCCW( List<Point2D_F64> points ) {
Point2D_F64 center = mean(points,null);
double angles[] = new double[ points.size() ];
for (int i = 0; i < angles.length; i++) {
Point2D_F64 p = points.get(i);
double dx = p.x - center.x;
double dy = p.y - center.y;
angles[i] = Math.atan2(dy,dx);
}
int order[] = new int[ points.size() ];
QuickSort_F64 sorter = new QuickSort_F64();
sorter.sort(angles,0,points.size(),order);
List<Point2D_F64> out = new ArrayList<Point2D_F64>(points.size());
for (int i = 0; i < points.size(); i++) {
out.add(points.get(order[i]));
}
return out;
}
|
java
|
{
"resource": ""
}
|
q177723
|
UtilPoint2D_F64.computeNormal
|
test
|
public static void computeNormal(List<Point2D_F64> points , Point2D_F64 mean , DMatrix covariance ) {
if( covariance.getNumCols() != 2 || covariance.getNumRows() != 2 ) {
if (covariance instanceof ReshapeMatrix) {
((ReshapeMatrix)covariance).reshape(2,2);
} else {
throw new IllegalArgumentException("Must be a 2x2 matrix");
}
}
mean(points,mean);
double xx=0,xy=0,yy=0;
for (int i = 0; i < points.size(); i++) {
Point2D_F64 p = points.get(i);
double dx = p.x-mean.x;
double dy = p.y-mean.y;
xx += dx*dx;
xy += dx*dy;
yy += dy*dy;
}
xx /= points.size();
xy /= points.size();
yy /= points.size();
covariance.unsafe_set(0,0,xx);
covariance.unsafe_set(0,1,xy);
covariance.unsafe_set(1,0,xy);
covariance.unsafe_set(1,1,yy);
}
|
java
|
{
"resource": ""
}
|
q177724
|
UtilPolygons2D_I32.isConvex
|
test
|
public static boolean isConvex( Polygon2D_I32 poly ) {
// if the cross product of all consecutive triples is positive or negative then it is convex
final int N = poly.size();
int numPositive = 0;
for (int i = 0; i < N; i++) {
int j = (i+1)%N;
int k = (i+2)%N;
Point2D_I32 a = poly.vertexes.data[i];
Point2D_I32 b = poly.vertexes.data[j];
Point2D_I32 c = poly.vertexes.data[k];
int dx0 = a.x-b.x;
int dy0 = a.y-b.y;
int dx1 = c.x-b.x;
int dy1 = c.y-b.y;
int z = dx0 * dy1 - dy0 * dx1;
if( z > 0 )
numPositive++;
// z can be zero if there are duplicate points.
// not sure if it should throw an exception if its "bad" or not
}
return( numPositive == 0 || numPositive == N );
}
|
java
|
{
"resource": ""
}
|
q177725
|
GeoTuple4D_F64.timesIP
|
test
|
public void timesIP( double scalar ) {
x *= scalar;
y *= scalar;
z *= scalar;
w *= scalar;
}
|
java
|
{
"resource": ""
}
|
q177726
|
GeoTuple4D_F64.maxAbs
|
test
|
public double maxAbs() {
double absX = Math.abs(x);
double absY = Math.abs(y);
double absZ = Math.abs(z);
double absW = Math.abs(w);
double found = Math.max(absX,absY);
if( found < absZ )
found = absZ;
if( found < absW )
found = absW;
return found;
}
|
java
|
{
"resource": ""
}
|
q177727
|
UtilPoint3D_F64.distance
|
test
|
public static double distance( double x0 , double y0 , double z0 ,
double x1 , double y1 , double z1) {
return norm(x1-x0,y1-y0,z1-z0);
}
|
java
|
{
"resource": ""
}
|
q177728
|
UtilPoint3D_F64.distanceSq
|
test
|
public static double distanceSq( double x0 , double y0 , double z0 ,
double x1 , double y1 , double z1) {
double dx = x1-x0;
double dy = y1-y0;
double dz = z1-z0;
return dx*dx + dy*dy + dz*dz;
}
|
java
|
{
"resource": ""
}
|
q177729
|
UtilPoint3D_F64.random
|
test
|
public static List<Point3D_F64> random(PlaneNormal3D_F64 plane , double max , int num, Random rand ) {
List<Point3D_F64> ret = new ArrayList<>();
Vector3D_F64 axisX = new Vector3D_F64();
Vector3D_F64 axisY = new Vector3D_F64();
UtilPlane3D_F64.selectAxis2D(plane.n,axisX,axisY);
for (int i = 0; i < num; i++) {
double x = 2*max*(rand.nextDouble()-0.5);
double y = 2*max*(rand.nextDouble()-0.5);
Point3D_F64 p = new Point3D_F64();
p.x = plane.p.x + axisX.x*x + axisY.x*y;
p.y = plane.p.y + axisX.y*x + axisY.y*y;
p.z = plane.p.z + axisX.z*x + axisY.z*y;
ret.add( p );
}
return ret;
}
|
java
|
{
"resource": ""
}
|
q177730
|
UtilPoint3D_F64.random
|
test
|
public static List<Point3D_F64> random(Point3D_F64 mean ,
double minX , double maxX ,
double minY , double maxY ,
double minZ , double maxZ ,
int num, Random rand )
{
List<Point3D_F64> ret = new ArrayList<>();
for( int i = 0; i < num; i++ ) {
Point3D_F64 p = new Point3D_F64();
p.x = mean.x + rand.nextDouble() * (maxX-minX) + minX;
p.y = mean.y + rand.nextDouble() * (maxY-minY) + minY;
p.z = mean.z + rand.nextDouble() * (maxZ-minZ) + minZ;
ret.add( p );
}
return ret;
}
|
java
|
{
"resource": ""
}
|
q177731
|
UtilPoint3D_F64.randomN
|
test
|
public static List<Point3D_F64> randomN(Point3D_F64 mean ,
double stdX , double stdY , double stdZ ,
int num, Random rand )
{
List<Point3D_F64> ret = new ArrayList<>();
for( int i = 0; i < num; i++ ) {
Point3D_F64 p = new Point3D_F64();
p.x = mean.x + rand.nextGaussian() * stdX;
p.y = mean.y + rand.nextGaussian() * stdY;
p.z = mean.z + rand.nextGaussian() * stdZ;
ret.add( p );
}
return ret;
}
|
java
|
{
"resource": ""
}
|
q177732
|
UtilPoint3D_F64.mean
|
test
|
public static Point3D_F64 mean( List<Point3D_F64> points , Point3D_F64 mean ) {
if( mean == null )
mean = new Point3D_F64();
double x = 0, y = 0, z = 0;
for( Point3D_F64 p : points ) {
x += p.x;
y += p.y;
z += p.z;
}
mean.x = x / points.size();
mean.y = y / points.size();
mean.z = z / points.size();
return mean;
}
|
java
|
{
"resource": ""
}
|
q177733
|
UtilPoint3D_F64.mean
|
test
|
public static Point3D_F64 mean( List<Point3D_F64> points , int num , Point3D_F64 mean ) {
if( mean == null )
mean = new Point3D_F64();
double x = 0, y = 0, z = 0;
for( int i = 0; i < num; i++ ) {
Point3D_F64 p = points.get(i);
x += p.x;
y += p.y;
z += p.z;
}
mean.x = x / num;
mean.y = y / num;
mean.z = z / num;
return mean;
}
|
java
|
{
"resource": ""
}
|
q177734
|
CachingJwtAuthenticator.invalidateAll
|
test
|
public void invalidateAll(Iterable<JwtContext> credentials) {
credentials.forEach(context -> cache.invalidate(context.getJwt()));
}
|
java
|
{
"resource": ""
}
|
q177735
|
CachingJwtAuthenticator.invalidateAll
|
test
|
public void invalidateAll(Predicate<? super JwtContext> predicate) {
cache.asMap().entrySet().stream()
.map(entry -> entry.getValue().getKey())
.filter(predicate::test)
.map(JwtContext::getJwt)
.forEach(cache::invalidate);
}
|
java
|
{
"resource": ""
}
|
q177736
|
InstallFeatureUtil.combineToSet
|
test
|
@SafeVarargs
public static Set<String> combineToSet(Collection<String>... collections) {
Set<String> result = new HashSet<String>();
Set<String> lowercaseSet = new HashSet<String>();
for (Collection<String> collection : collections) {
if (collection != null) {
for (String value : collection) {
if (!lowercaseSet.contains(value.toLowerCase())) {
lowercaseSet.add(value.toLowerCase());
result.add(value);
}
}
}
}
return result;
}
|
java
|
{
"resource": ""
}
|
q177737
|
InstallFeatureUtil.getServerFeatures
|
test
|
public Set<String> getServerFeatures(File serverDirectory) {
Set<String> result = getConfigDropinsFeatures(null, serverDirectory, "defaults");
result = getServerXmlFeatures(result, new File(serverDirectory, "server.xml"), null);
// add the overrides at the end since they should not be replaced by any previous content
return getConfigDropinsFeatures(result, serverDirectory, "overrides");
}
|
java
|
{
"resource": ""
}
|
q177738
|
InstallFeatureUtil.getConfigDropinsFeatures
|
test
|
private Set<String> getConfigDropinsFeatures(Set<String> origResult, File serverDirectory, String folderName) {
Set<String> result = origResult;
File configDropinsFolder;
try {
configDropinsFolder = new File(new File(serverDirectory, "configDropins"), folderName).getCanonicalFile();
} catch (IOException e) {
// skip this directory if its path cannot be queried
warn("The " + serverDirectory + "/configDropins/" + folderName + " directory cannot be accessed. Skipping its server features.");
debug(e);
return result;
}
File[] configDropinsXmls = configDropinsFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".xml");
}
});
if (configDropinsXmls == null || configDropinsXmls.length == 0) {
return result;
}
// sort the files in alphabetical order so that overrides will happen in the proper order
Comparator<File> comparator = new Comparator<File>() {
@Override
public int compare(File left, File right) {
return left.getAbsolutePath().toLowerCase().compareTo(right.getAbsolutePath().toLowerCase());
}
};
Collections.sort(Arrays.asList(configDropinsXmls), comparator);
for (File xml : configDropinsXmls) {
Set<String> features = getServerXmlFeatures(result, xml, null);
if (features != null) {
result = features;
}
}
return result;
}
|
java
|
{
"resource": ""
}
|
q177739
|
InstallFeatureUtil.getServerXmlFeatures
|
test
|
private Set<String> getServerXmlFeatures(Set<String> origResult, File serverFile, List<File> parsedXmls) {
Set<String> result = origResult;
List<File> updatedParsedXmls = parsedXmls != null ? parsedXmls : new ArrayList<File>();
File canonicalServerFile;
try {
canonicalServerFile = serverFile.getCanonicalFile();
} catch (IOException e) {
// skip this server.xml if its path cannot be queried
warn("The server file " + serverFile + " cannot be accessed. Skipping its features.");
debug(e);
return result;
}
updatedParsedXmls.add(canonicalServerFile);
if (canonicalServerFile.exists()) {
try {
Document doc = new XmlDocument() {
public Document getDocument(File file) throws IOException, ParserConfigurationException, SAXException {
createDocument(file);
return doc;
}
}.getDocument(canonicalServerFile);
Element root = doc.getDocumentElement();
NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
if (nodes.item(i) instanceof Element) {
Element child = (Element) nodes.item(i);
if ("featureManager".equals(child.getNodeName())) {
if (result == null) {
result = new HashSet<String>();
}
result.addAll(parseFeatureManagerNode(child));
} else if ("include".equals(child.getNodeName())){
result = parseIncludeNode(result, canonicalServerFile, child, updatedParsedXmls);
}
}
}
} catch (IOException | ParserConfigurationException | SAXException e) {
// just skip this server.xml if it cannot be parsed
warn("The server file " + serverFile + " cannot be parsed. Skipping its features.");
debug(e);
return result;
}
}
return result;
}
|
java
|
{
"resource": ""
}
|
q177740
|
InstallFeatureUtil.parseIncludeNode
|
test
|
private Set<String> parseIncludeNode(Set<String> origResult, File serverFile, Element node,
List<File> updatedParsedXmls) {
Set<String> result = origResult;
String includeFileName = node.getAttribute("location");
if (includeFileName == null || includeFileName.trim().isEmpty()) {
return result;
}
File includeFile = null;
if (isURL(includeFileName)) {
try {
File tempFile = File.createTempFile("serverFromURL", ".xml");
FileUtils.copyURLToFile(new URL(includeFileName), tempFile, COPY_FILE_TIMEOUT_MILLIS, COPY_FILE_TIMEOUT_MILLIS);
includeFile = tempFile;
} catch (IOException e) {
// skip this xml if it cannot be accessed from URL
warn("The server file " + serverFile + " includes a URL " + includeFileName + " that cannot be accessed. Skipping the included features.");
debug(e);
return result;
}
} else {
includeFile = new File(includeFileName);
}
try {
if (!includeFile.isAbsolute()) {
includeFile = new File(serverFile.getParentFile().getAbsolutePath(), includeFileName)
.getCanonicalFile();
} else {
includeFile = includeFile.getCanonicalFile();
}
} catch (IOException e) {
// skip this xml if its path cannot be queried
warn("The server file " + serverFile + " includes a file " + includeFileName + " that cannot be accessed. Skipping the included features.");
debug(e);
return result;
}
if (!updatedParsedXmls.contains(includeFile)) {
String onConflict = node.getAttribute("onConflict");
Set<String> features = getServerXmlFeatures(null, includeFile, updatedParsedXmls);
result = handleOnConflict(result, onConflict, features);
}
return result;
}
|
java
|
{
"resource": ""
}
|
q177741
|
InstallFeatureUtil.parseFeatureManagerNode
|
test
|
private static Set<String> parseFeatureManagerNode(Element node) {
Set<String> result = new HashSet<String>();
NodeList features = node.getElementsByTagName("feature");
if (features != null) {
for (int j = 0; j < features.getLength(); j++) {
String content = features.item(j).getTextContent();
if (content != null) {
if (content.contains(":")) {
String[] split = content.split(":", 2);
result.add(split[1].trim().toLowerCase());
} else {
result.add(content.trim().toLowerCase());
}
}
}
}
return result;
}
|
java
|
{
"resource": ""
}
|
q177742
|
InstallFeatureUtil.downloadJsons
|
test
|
private File downloadJsons(String productId, String productVersion) {
String jsonGroupId = productId + ".features";
try {
return downloadArtifact(jsonGroupId, "features", "json", productVersion);
} catch (PluginExecutionException e) {
debug("Cannot find json for productId " + productId + ", productVersion " + productVersion, e);
return null;
}
}
|
java
|
{
"resource": ""
}
|
q177743
|
InstallFeatureUtil.getOpenLibertyFeatureSet
|
test
|
public static Set<String> getOpenLibertyFeatureSet(Set<File> jsons) throws PluginExecutionException {
Set<String> libertyFeatures = new HashSet<String>();
for (File file : jsons) {
Scanner s = null;
try {
s = new Scanner(file);
// scan Maven coordinates for artifactIds that belong to the Open Liberty groupId
while (s.findWithinHorizon(OPEN_LIBERTY_GROUP_ID + ":([^:]*):", 0) != null) {
MatchResult match = s.match();
if (match.groupCount() >= 1) {
libertyFeatures.add(match.group(1));
}
}
} catch (FileNotFoundException e) {
throw new PluginExecutionException("The JSON file is not found at " + file.getAbsolutePath(), e);
} finally {
if (s != null) {
s.close();
}
}
}
return libertyFeatures;
}
|
java
|
{
"resource": ""
}
|
q177744
|
InstallFeatureUtil.isOnlyOpenLibertyFeatures
|
test
|
private boolean isOnlyOpenLibertyFeatures(List<String> featuresToInstall) throws PluginExecutionException {
boolean result = containsIgnoreCase(getOpenLibertyFeatureSet(downloadedJsons), featuresToInstall);
debug("Is installing only Open Liberty features? " + result);
return result;
}
|
java
|
{
"resource": ""
}
|
q177745
|
InstallFeatureUtil.containsIgnoreCase
|
test
|
public static boolean containsIgnoreCase(Collection<String> reference, Collection<String> target) {
return toLowerCase(reference).containsAll(toLowerCase(target));
}
|
java
|
{
"resource": ""
}
|
q177746
|
InstallFeatureUtil.getNextProductVersion
|
test
|
public static String getNextProductVersion(String version) throws PluginExecutionException {
String result = null;
int versionSplittingIndex = version.lastIndexOf(".") + 1;
if (versionSplittingIndex == 0) {
throw new PluginExecutionException("Product version " + version
+ " is not in the expected format. It must have period separated version segments.");
}
String quarterVersion = version.substring(versionSplittingIndex);
int nextQuarterSpecifier;
try {
nextQuarterSpecifier = Integer.parseInt(quarterVersion) + 1;
} catch (NumberFormatException e) {
throw new PluginExecutionException("Product version " + version
+ " is not in the expected format. Its last segment is expected to be an integer.", e);
}
result = version.substring(0, versionSplittingIndex) + nextQuarterSpecifier;
return result;
}
|
java
|
{
"resource": ""
}
|
q177747
|
InstallFeatureUtil.extractSymbolicName
|
test
|
public static String extractSymbolicName(File jar) throws PluginExecutionException {
JarFile jarFile = null;
try {
jarFile = new JarFile(jar);
return jarFile.getManifest().getMainAttributes().getValue("Bundle-SymbolicName");
} catch (IOException e) {
throw new PluginExecutionException("Could not load the jar " + jar.getAbsolutePath(), e);
} finally {
if (jarFile != null) {
try {
jarFile.close();
} catch (IOException e) {
// nothing to do here
}
}
}
}
|
java
|
{
"resource": ""
}
|
q177748
|
InstallFeatureUtil.getMapBasedInstallKernelJar
|
test
|
public static File getMapBasedInstallKernelJar(File dir) {
File[] installMapJars = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(INSTALL_MAP_PREFIX) && name.endsWith(INSTALL_MAP_SUFFIX);
}
});
File result = null;
if (installMapJars != null) {
for (File jar : installMapJars) {
if (isReplacementJar(result, jar)) {
result = jar;
}
}
}
return result;
}
|
java
|
{
"resource": ""
}
|
q177749
|
InstallFeatureUtil.isReplacementJar
|
test
|
private static boolean isReplacementJar(File file1, File file2) {
if (file1 == null) {
return true;
} else if (file2 == null) {
return false;
} else {
String version1 = extractVersion(file1.getName());
String version2 = extractVersion(file2.getName());
return compare(version1, version2) < 0;
}
}
|
java
|
{
"resource": ""
}
|
q177750
|
InstallFeatureUtil.extractVersion
|
test
|
private static String extractVersion(String fileName) {
int startIndex = INSTALL_MAP_PREFIX.length() + 1; // skip the underscore after the prefix
int endIndex = fileName.lastIndexOf(INSTALL_MAP_SUFFIX);
if (startIndex < endIndex) {
return fileName.substring(startIndex, endIndex);
} else {
return null;
}
}
|
java
|
{
"resource": ""
}
|
q177751
|
InstallFeatureUtil.compare
|
test
|
private static int compare(String version1, String version2) {
if (version1 == null && version2 == null) {
return 0;
} else if (version1 == null && version2 != null) {
return -1;
} else if (version1 != null && version2 == null) {
return 1;
}
String[] components1 = version1.split("\\.");
String[] components2 = version2.split("\\.");
for (int i = 0; i < components1.length && i < components2.length; i++) {
int comparison;
try {
comparison = new Integer(components1[i]).compareTo(new Integer(components2[i]));
} catch (NumberFormatException e) {
comparison = components1[i].compareTo(components2[i]);
}
if (comparison != 0) {
return comparison;
}
}
return components1.length - components2.length;
}
|
java
|
{
"resource": ""
}
|
q177752
|
InstallFeatureUtil.productInfo
|
test
|
public static String productInfo(File installDirectory, String action) throws PluginExecutionException {
Process pr = null;
InputStream is = null;
Scanner s = null;
Worker worker = null;
try {
String command;
if (OSUtil.isWindows()) {
command = installDirectory + "\\bin\\productInfo.bat " + action;
} else {
command = installDirectory + "/bin/productInfo " + action;
}
pr = Runtime.getRuntime().exec(command);
worker = new Worker(pr);
worker.start();
worker.join(300000);
if (worker.exit == null) {
throw new PluginExecutionException("productInfo command timed out");
}
int exitValue = pr.exitValue();
if (exitValue != 0) {
throw new PluginExecutionException("productInfo exited with return code " + exitValue);
}
is = pr.getInputStream();
s = new Scanner(is);
// use regex to match the beginning of the input
s.useDelimiter("\\A");
if (s.hasNext()) {
return s.next();
}
return null;
} catch (IOException ex) {
throw new PluginExecutionException("productInfo error: " + ex);
} catch (InterruptedException ex) {
worker.interrupt();
Thread.currentThread().interrupt();
throw new PluginExecutionException("productInfo error: " + ex);
} finally {
if (s != null) {
s.close();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (pr != null) {
pr.destroy();
}
}
}
|
java
|
{
"resource": ""
}
|
q177753
|
SpringBootUtil.isSpringBootUberJar
|
test
|
public static boolean isSpringBootUberJar(File artifact) {
if (artifact == null || !artifact.exists() || !artifact.isFile()) {
return false;
}
try (JarFile jarFile = new JarFile(artifact)) {
Manifest manifest = jarFile.getManifest();
if (manifest != null) {
Attributes attributes = manifest.getMainAttributes();
if(attributes.getValue(BOOT_VERSION_ATTRIBUTE) != null
&& attributes.getValue(BOOT_START_CLASS_ATTRIBUTE) != null) {
return true;
} else { //Checking that there is a spring-boot-VERSION.RELEASE.jar in the BOOT-INF/lib directory
//Handles the Gradle case where the spring plugin does not set the properties in the manifest
Enumeration<JarEntry> entries = jarFile.entries();
while(entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if (!entryName.startsWith("org") && (entryName.matches(BOOT_JAR_EXPRESSION) || entryName.matches(BOOT_WAR_EXPRESSION))) {
return true;
}
}
}
}
} catch (IOException e) {}
return false;
}
|
java
|
{
"resource": ""
}
|
q177754
|
LibertyProperty.getArquillianProperty
|
test
|
private static LibertyPropertyI getArquillianProperty(String key, Class<?> cls)
throws ArquillianConfigurationException {
try {
if (cls == LibertyManagedObject.LibertyManagedProperty.class) {
return LibertyManagedObject.LibertyManagedProperty.valueOf(key);
} else if (cls == LibertyRemoteObject.LibertyRemoteProperty.class) {
return LibertyRemoteObject.LibertyRemoteProperty.valueOf(key);
}
} catch (IllegalArgumentException e) {
throw new ArquillianConfigurationException(
"Property \"" + key + "\" in arquillianProperties does not exist. You probably have a typo.");
}
throw new ArquillianConfigurationException("This should never happen.");
}
|
java
|
{
"resource": ""
}
|
q177755
|
ImageWebReporter.isWorkingInThisEnvironment
|
test
|
@Override
public boolean isWorkingInThisEnvironment(String forFile) {
return !GraphicsEnvironment.isHeadless()
&& GenericDiffReporter.isFileExtensionValid(forFile, GenericDiffReporter.IMAGE_FILE_EXTENSIONS);
}
|
java
|
{
"resource": ""
}
|
q177756
|
RecursiveSquare.moveBackToCenter
|
test
|
private static void moveBackToCenter(double length)
{
Tortoise.setPenUp();
Tortoise.turn(90);
Tortoise.move(length / 2);
Tortoise.turn(90);
Tortoise.move(length / 2);
Tortoise.turn(180);
Tortoise.setPenDown();
//
}
|
java
|
{
"resource": ""
}
|
q177757
|
ObjectUtils.isEqual
|
test
|
public static boolean isEqual(Object s1, Object s2) {
return s1 == s2 || (s1 != null) && s1.equals(s2);
}
|
java
|
{
"resource": ""
}
|
q177758
|
NumberUtils.load
|
test
|
public static int load(String i, int defaultValue, boolean stripNonNumeric)
{
try
{
i = stripNonNumeric ? StringUtils.stripNonNumeric(i, true, true) : i;
defaultValue = Integer.parseInt(i);
}
catch (Exception ignored)
{
}
return defaultValue;
}
|
java
|
{
"resource": ""
}
|
q177759
|
DeepDive07Objects.throwPizzaParty
|
test
|
private Tortoise[] throwPizzaParty()
{
Tortoise karai = new Tortoise();
Tortoise cecil = new Tortoise();
Tortoise michealangelo = new Tortoise();
Tortoise fred = new Tortoise();
return new Tortoise[]{karai, cecil, michealangelo, fred};
}
|
java
|
{
"resource": ""
}
|
q177760
|
TortoiseUtils.verify
|
test
|
public static void verify() {
try {
Approvals.verify(TURTLE.getImage());
} catch (Exception e) {
throw ObjectUtils.throwAsError(e);
} finally {
TortoiseUtils.resetTurtle();
}
}
|
java
|
{
"resource": ""
}
|
q177761
|
Puzzle.swapBlank
|
test
|
public Puzzle swapBlank(int target)
{
int[] copy = Arrays.copyOf(cells, cells.length);
int x = copy[target];
copy[getBlankIndex()] = x;
copy[target] = 8;
return new Puzzle(copy);
}
|
java
|
{
"resource": ""
}
|
q177762
|
Puzzle.getDistanceToGoal
|
test
|
public int getDistanceToGoal()
{
int distance = 0;
for (int i = 0; i < cells.length; i++)
{
distance += getDistance(i, cells[i]);
}
return distance;
}
|
java
|
{
"resource": ""
}
|
q177763
|
StdOut.printf
|
test
|
public static void printf(String format, Object... args)
{
out.printf(LOCALE, format, args);
out.flush();
}
|
java
|
{
"resource": ""
}
|
q177764
|
StdOut.printf
|
test
|
public static void printf(Locale locale, String format, Object... args)
{
out.printf(locale, format, args);
out.flush();
}
|
java
|
{
"resource": ""
}
|
q177765
|
WhichFish.makeAFishyDecision
|
test
|
public static void makeAFishyDecision(int numberOfFish)
{
// Use a switch...case on the numberOfFish
switch (numberOfFish)
{
// When the numberOfFish is -1
case -1 :
// Uncomment to create a string of this image
String image = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/thumb-up.png";
// Create a new ImageIcon from your image
ImageIcon icon = new ImageIcon(image);
// Show a message with the fancy message box this text, this title and this icon...
FancyMessageBox.showMesage("Had a Fish", "Not hungry anymore...", icon);
// End
break;
// When the numberOfFish is 0
case 0 :
// Uncomment to create a string of this image
String image0 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/information.png";
// Create a new ImageIcon from your image
ImageIcon icon0 = new ImageIcon(image0);
// Show a message with the fancy message box this text, this title and this icon...
FancyMessageBox.showMesage("No Fish", "Still hungry", icon0);
// End
break;
// When the numberOfFish is 1
case 1 :
// Uncomment to create a string of this image
String image1 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/star.png";
// Create a new ImageIcon from your image
ImageIcon icon1 = new ImageIcon(image1);
// Show a message with the fancy message box this text, this title and this icon...
FancyMessageBox.showMesage("One Fish", "This one has a little star", icon1);
// End
break;
// When the numberOfFish is 0
case 2 :
// Uncomment to create a string of this image
String image2 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/github.png";
// Create a new ImageIcon from your image
ImageIcon icon2 = new ImageIcon(image2);
// Show a message with the fancy message box this text, this title and this icon...
FancyMessageBox.showMesage("Two Fish", "Funny things are everywhere", icon2);
// End
break;
// Otherwise
default :
// Uncomment to create a string of this image
String image4 = "../TeachingKidsProgramming.Source.Java/src/main/resources/icons/hint.png";
// Create a new ImageIcon from your image
ImageIcon icon4 = new ImageIcon(image4);
// Show a message with the fancy message box this text, this title and this icon...
FancyMessageBox.showMesage("Vegetaraian meal", "Fish are icky", icon4);
// End
break;
}
}
|
java
|
{
"resource": ""
}
|
q177766
|
MySystem.variable
|
test
|
public synchronized static void variable(String name, Object value) {
if (!variable) {
return;
}
System.out.println(timeStamp() + "*=> " + name + " = '" + (value == null ? null : value.toString()) + "'");
}
|
java
|
{
"resource": ""
}
|
q177767
|
StdRandom.uniform
|
test
|
public static int uniform(int a, int b)
{
if (b <= a)
throw new IllegalArgumentException("Invalid range");
if ((long) b - a >= Integer.MAX_VALUE)
throw new IllegalArgumentException("Invalid range");
return a + uniform(b - a);
}
|
java
|
{
"resource": ""
}
|
q177768
|
StdRandom.uniform
|
test
|
public static double uniform(double a, double b)
{
if (!(a < b))
throw new IllegalArgumentException("Invalid range");
return a + uniform() * (b - a);
}
|
java
|
{
"resource": ""
}
|
q177769
|
StdRandom.poisson
|
test
|
public static int poisson(double lambda)
{
if (!(lambda > 0.0))
throw new IllegalArgumentException("Parameter lambda must be positive");
if (Double.isInfinite(lambda))
throw new IllegalArgumentException("Parameter lambda must not be infinite");
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do
{
k++;
p *= uniform();
}
while (p >= L);
return k - 1;
}
|
java
|
{
"resource": ""
}
|
q177770
|
StdRandom.discrete
|
test
|
public static int discrete(double[] a)
{
if (a == null)
throw new NullPointerException("argument array is null");
double EPSILON = 1E-14;
double sum = 0.0;
for (int i = 0; i < a.length; i++)
{
if (!(a[i] >= 0.0))
throw new IllegalArgumentException("array entry " + i + " must be nonnegative: " + a[i]);
sum = sum + a[i];
}
if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON)
throw new IllegalArgumentException("sum of array entries does not approximately equal 1.0: " + sum);
// the for loop may not return a value when both r is (nearly) 1.0 and when the
// cumulative sum is less than 1.0 (as a result of floating-point roundoff error)
while (true)
{
double r = uniform();
sum = 0.0;
for (int i = 0; i < a.length; i++)
{
sum = sum + a[i];
if (sum > r)
return i;
}
}
}
|
java
|
{
"resource": ""
}
|
q177771
|
StdRandom.main
|
test
|
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
if (args.length == 2)
StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = {.5, .3, .1, .1};
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++)
{
StdOut.printf("%2d ", uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b ", bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d ", discrete(t));
StdOut.println();
}
String[] a = "A B C D E F G".split(" ");
for (String s : a)
StdOut.print(s + " ");
StdOut.println();
}
|
java
|
{
"resource": ""
}
|
q177772
|
Strings.capitalizeFirstChar
|
test
|
public static final String capitalizeFirstChar(String word) {
return Character.toUpperCase(word.charAt(0)) + word.substring(1);
}
|
java
|
{
"resource": ""
}
|
q177773
|
Strings.unCapitalizeFirstChar
|
test
|
public static final String unCapitalizeFirstChar(String word) {
return Character.toLowerCase(word.charAt(0)) + word.substring(1);
}
|
java
|
{
"resource": ""
}
|
q177774
|
FileAssetServlet.fixPath
|
test
|
private String fixPath(String path) {
if (!path.isEmpty()) {
if (!path.endsWith("/"))
return path + '/';
else
return path;
} else
return path;
}
|
java
|
{
"resource": ""
}
|
q177775
|
HqlUtil.joinToString
|
test
|
public static String joinToString(CriteriaJoin criteriaJoin) {
StringBuilder builder = new StringBuilder("LEFT OUTER JOIN ")
.append(criteriaJoin.getEntityClass().getName())
.append(" ")
.append(criteriaJoin.getAlias())
.append(" ")
.append(" ON ");
if(criteriaJoin.getJoinRelations().size() == 0) {
throw new RuntimeException("Not found any Join Relations in " + criteriaJoin.getAlias() + " Join Criteria ! ");
}
StringJoiner joiner = new StringJoiner(" AND ");
List<JoinRelation> relationList = criteriaJoin.getJoinRelations();
for(JoinRelation joinRelation: relationList) {
StringBuilder relationBuilder = new StringBuilder("\n")
.append(joinRelation.getRelationCriteria().getAlias())
.append(".")
.append(joinRelation.getRelationField())
.append("=")
.append(joinRelation.getJoinedCriteria().getAlias())
.append(".")
.append(joinRelation.getJoinedField());
joiner.add(relationBuilder.toString());
}
if(joiner.length() > 0) {
builder.append(joiner.toString());
}
return builder.toString();
}
|
java
|
{
"resource": ""
}
|
q177776
|
TokenBasedAuthResponseFilter.getTokenSentence
|
test
|
public static String getTokenSentence(BasicToken token) throws Exception {
if (token == null)
return tokenKey + "=" + cookieSentence;
String sentence = tokenKey + "=" + token.getTokenString() + cookieSentence;
//TODO: Learn how to calculate expire according to the browser time.
// sentence = sentence.replace("{expireDate}", token.getExpirationDate().toGMTString());
return sentence;
}
|
java
|
{
"resource": ""
}
|
q177777
|
TokenBasedAuthResponseFilter.filter
|
test
|
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
String authToken = extractAuthTokenFromCookieList(requestContext.getHeaders().getFirst("Cookie"));
if (authToken != null && authToken.length() != 0) {
try {
BasicToken token = new BasicToken(authToken);
if (token.isExpired()) {
LOGGER.debug("ExpireDate : " + token.getExpirationDate().toString());
LOGGER.debug("Now: " + DateTime.now().toDate().toString());
responseContext.getHeaders().putSingle("Set-Cookie", getTokenSentence(null));
responseContext.setStatusInfo(Response.Status.UNAUTHORIZED);
responseContext.setEntity("Token expired. Please login again.");
LOGGER.info("Token expired. Please login again.");
} else {
token.setExpiration(token.getMaxAge());
if (!logoutPath.equals(requestContext.getUriInfo().getPath())) {
String cookie = getTokenSentence(token);
responseContext.getHeaders().putSingle("Set-Cookie", cookie);
}
}
} catch (Exception e) {
LOGGER.error("Token re-creation failed", e.getMessage());
responseContext.setStatusInfo(Response.Status.UNAUTHORIZED);
}
}
}
|
java
|
{
"resource": ""
}
|
q177778
|
TokenBasedAuthResponseFilter.extractAuthTokenFromCookieList
|
test
|
private String extractAuthTokenFromCookieList(String cookieList) {
if (cookieList == null || cookieList.length() == 0) {
return null;
}
String[] cookies = cookieList.split(";");
for (String cookie : cookies) {
if (cookie.trim().startsWith(tokenKey)) {
return cookie.trim().substring(tokenKey.length() + 1);
}
}
return null;
}
|
java
|
{
"resource": ""
}
|
q177779
|
JerseyUtil.registerGuiceBound
|
test
|
public static void registerGuiceBound(Injector injector, final JerseyEnvironment environment) {
while (injector != null) {
for (Key<?> key : injector.getBindings().keySet()) {
Type type = key.getTypeLiteral().getType();
if (type instanceof Class) {
Class<?> c = (Class) type;
if (isProviderClass(c)) {
logger.info("Registering {} as a provider class", c.getName());
environment.register(c);
} else if (isRootResourceClass(c)) {
// Jersey rejects resources that it doesn't think are acceptable
// Including abstract classes and interfaces, even if there is a valid Guice binding.
if (Resource.isAcceptable(c)) {
logger.info("Registering {} as a root resource class", c.getName());
environment.register(c);
} else {
logger.warn("Class {} was not registered as a resource. Bind a concrete implementation instead.", c.getName());
}
}
}
}
injector = injector.getParent();
}
}
|
java
|
{
"resource": ""
}
|
q177780
|
TokenAuthenticator.getAllRolePermissions
|
test
|
private void getAllRolePermissions(RoleEntry parent, Set<PermissionEntry> rolePermissions) {
rolePermissions.addAll(permissionStore.findByRoleId(parent.getId()));
Set<RoleGroupEntry> roleGroupEntries = (Set<RoleGroupEntry>) roleGroupStore.findByGroupId(parent.getId());
for (RoleGroupEntry entry : roleGroupEntries) {
Optional<RoleEntry> role = (Optional<RoleEntry>) roleStore.findByRoleId(entry.getRoleId());
getAllRolePermissions(role.get(), rolePermissions);
}
}
|
java
|
{
"resource": ""
}
|
q177781
|
ProjectionList.add
|
test
|
public ProjectionList add(Projection projection, String alias) {
return add(Projections.alias(projection, alias));
}
|
java
|
{
"resource": ""
}
|
q177782
|
JobInfoProvider.convert2JobDetail
|
test
|
public static JobDetail convert2JobDetail(JobInfo info) {
JobKey jobKey = JobKey.jobKey(info.getName());
JobDetail jobDetail = newJob(info.getJobClass()).
withIdentity(jobKey).
build();
return jobDetail;
}
|
java
|
{
"resource": ""
}
|
q177783
|
JobInfoProvider.convert2Trigger
|
test
|
public static Trigger convert2Trigger(TriggerInfo trig, JobInfo job) {
TriggerBuilder<Trigger> builder = newTrigger();
builder.withIdentity(trig.getName(), trig.getGroup());
builder.forJob(job.getName(), job.getGroup());
switch (trig.getType()) {
case CRON:
setStartEndTime(trig, builder);
if (!trig.getCron().isEmpty())
builder.withSchedule(CronScheduleBuilder.cronSchedule(trig.getCron()));
break;
case SIMPLE:
setStartEndTime(trig, builder);
setCountIntervalValues(trig, builder);
break;
}
return builder.build();
}
|
java
|
{
"resource": ""
}
|
q177784
|
JobInfoProvider.setCountIntervalValues
|
test
|
private static void setCountIntervalValues(TriggerInfo dto, TriggerBuilder<org.quartz.Trigger> builder) {
SimpleScheduleBuilder builderSc = SimpleScheduleBuilder.simpleSchedule();
if (dto.getRepeatCount() != 0)
builderSc.withRepeatCount(dto.getRepeatCount());
if (dto.getRepeatInterval() > 0)
builderSc.withIntervalInMilliseconds(dto.getRepeatInterval());
builder.withSchedule(builderSc);
}
|
java
|
{
"resource": ""
}
|
q177785
|
JobInfoProvider.setStartEndTime
|
test
|
private static void setStartEndTime(TriggerInfo dto, TriggerBuilder<org.quartz.Trigger> builder) {
if (dto.getStartTime() > -1)
builder.startAt(new Date(dto.getStartTime()));
else
builder.startNow();
if (dto.getEndTime() > -1)
builder.endAt(new Date(dto.getEndTime()));
}
|
java
|
{
"resource": ""
}
|
q177786
|
MailManager.sendMail
|
test
|
public static boolean sendMail(MailItem item) {
LOGGER.debug("Mail : " + item.toString());
boolean result = queue.add(item);
LOGGER.info("Adding mail to queue. Queue size: " + queue.size());
// If thread is alive leave the job to it
// Else create new thread and start.
if (!consumerThread.isAlive()) {
consumerThread = new Thread(consumer);
consumerThread.start();
}
return result;
}
|
java
|
{
"resource": ""
}
|
q177787
|
BufferedStreamingOutput.write
|
test
|
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
//Write until available bytes are less than buffer.
while (bufferedInputStream.available() > buffer.length) {
bufferedInputStream.read(buffer);
output.write(buffer);
}
//Write one more time to finish and exit.
buffer = new byte[bufferedInputStream.available()];
bufferedInputStream.read(buffer);
output.write(buffer);
bufferedInputStream.close();
}
|
java
|
{
"resource": ""
}
|
q177788
|
QuartzBundle.initializeScheduler
|
test
|
private void initializeScheduler(Properties properties) throws SchedulerException {
SchedulerFactory factory = new StdSchedulerFactory(properties);
Scheduler scheduler = factory.getScheduler();
scheduler.start();
JobManager.initialize(scheduler);
}
|
java
|
{
"resource": ""
}
|
q177789
|
Converter.getFields
|
test
|
protected final Collection<FieldEntry> getFields(Class clazz) {
LinkedList<FieldEntry> fieldList = getAllFields(clazz);
Collections.sort(fieldList, new Comparator<FieldEntry>() {
public int compare(FieldEntry o1, FieldEntry o2) {
return o1.compareTo(o2);
}
});
return fieldList;
}
|
java
|
{
"resource": ""
}
|
q177790
|
Converter.getFieldMap
|
test
|
protected final Map<String, Field> getFieldMap(Class clazz) {
Map<String, Field> fieldList = new HashMap<String, Field>();
for (FieldEntry entry : getAllFields(clazz)) {
Field field = entry.getValue();
fieldList.put(field.getName(), field);
}
return fieldList;
}
|
java
|
{
"resource": ""
}
|
q177791
|
RobeExceptionMapper.toResponse
|
test
|
@Override
public Response toResponse(Exception e) {
String id = System.nanoTime() + "";
LOGGER.error(id, e);
if (e instanceof RobeRuntimeException) {
return ((RobeRuntimeException) e).getResponse(id);
} else if (e instanceof ConstraintViolationException) {
ConstraintViolationException exception = (ConstraintViolationException) e;
RobeMessage[] errors = new RobeMessage[exception.getConstraintViolations().size()];
int i = 0;
for (ConstraintViolation error : exception.getConstraintViolations()) {
errors[i++] = new RobeMessage.Builder().message(error.getMessage()).status(422).id(id).build();
}
return Response.status(422).entity(errors).type(MediaType.APPLICATION_JSON).build();
} else if (e instanceof WebApplicationException) {
WebApplicationException we = (WebApplicationException) e;
RobeMessage error = new RobeMessage.Builder().id(id).message(we.getMessage()).status(we.getResponse().getStatus()).build();
return Response.fromResponse(we.getResponse()).entity(error).type(MediaType.APPLICATION_JSON).build();
} else {
if (e.getClass().getName().equals("org.hibernate.exception.ConstraintViolationException")) {
if (e.getCause() != null && e.getCause().getMessage() != null) {
RobeMessage error = new RobeMessage.Builder().message(e.getCause().getMessage().split("for")[0]).status(Response.Status.CONFLICT.getStatusCode()).id(id).build();
return Response.status(Response.Status.CONFLICT).entity(error).type(MediaType.APPLICATION_JSON).build();
}
}
RobeMessage error = new RobeMessage.Builder().message(e.getMessage()).id(id).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).type(MediaType.APPLICATION_JSON).build();
}
}
|
java
|
{
"resource": ""
}
|
q177792
|
BasicToken.configure
|
test
|
public static void configure(TokenBasedAuthConfiguration configuration) {
encryptor.setPoolSize(configuration.getPoolSize()); // This would be a good value for a 4-core system
if (configuration.getServerPassword().equals("auto")) {
encryptor.setPassword(UUID.randomUUID().toString());
} else {
encryptor.setPassword(configuration.getServerPassword());
}
encryptor.setAlgorithm(configuration.getAlgorithm());
encryptor.initialize();
BasicToken.defaultMaxAge = configuration.getMaxage();
//Create cache for permissions.
cache = CacheBuilder.newBuilder()
.expireAfterAccess(defaultMaxAge, TimeUnit.SECONDS)
.expireAfterWrite(defaultMaxAge, TimeUnit.SECONDS)
.build();
}
|
java
|
{
"resource": ""
}
|
q177793
|
BasicToken.generateAttributesHash
|
test
|
private void generateAttributesHash(Map<String, String> attributes) {
StringBuilder attr = new StringBuilder();
attr.append(attributes.get("userAgent"));
// attr.append(attributes.get("remoteAddr")); TODO: add remote ip address after you find how to get remote IP from HttpContext
attributesHash = Hashing.sha256().hashString(attr.toString(), StandardCharsets.UTF_8).toString();
resetTokenString();
}
|
java
|
{
"resource": ""
}
|
q177794
|
BasicToken.generateTokenString
|
test
|
private String generateTokenString() throws Exception {
//Renew age
//Stringify token data
StringBuilder dataString = new StringBuilder();
dataString
.append(getUserId())
.append(SEPARATOR)
.append(getUsername())
.append(SEPARATOR)
.append(getExpirationDate().getTime())
.append(SEPARATOR)
.append(attributesHash);
// Encrypt token data string
String newTokenString = encryptor.encrypt(dataString.toString());
newTokenString = BaseEncoding.base16().encode(newTokenString.getBytes());
tokenString = newTokenString;
return newTokenString;
}
|
java
|
{
"resource": ""
}
|
q177795
|
MailSender.sendMessage
|
test
|
public void sendMessage(MailItem item) throws MessagingException {
checkNotNull(item.getReceivers());
checkNotNull(item.getReceivers().get(0));
checkNotNull(item.getTitle());
checkNotNull(item.getBody());
//If sender is empty send with the account sender.
Message msg = new MimeMessage(session);
if (item.getSender() == null || item.getSender().length() == 0) {
item.setSender(configuration.getProperties().get(configuration.getUsernameKey()).toString());
}
InternetAddress from = new InternetAddress(item.getSender());
msg.setFrom(from);
InternetAddress[] to = new InternetAddress[item.getReceivers().size()];
for (int i = 0; i < item.getReceivers().size(); i++) {
to[i] = new InternetAddress(item.getReceivers().get(i));
}
msg.setRecipients(Message.RecipientType.TO, to);
msg.setSubject(item.getTitle());
MimeBodyPart body = new MimeBodyPart();
body.setContent(item.getBody(), "text/html; charset=UTF-8");
Multipart content = new MimeMultipart();
content.addBodyPart(body);
if (item.getAttachments() != null && item.getAttachments().size() > 0) {
for (DataSource attachment : item.getAttachments()) {
BodyPart itemBodyPart = new MimeBodyPart();
itemBodyPart.setDataHandler(new DataHandler(attachment));
itemBodyPart.setFileName(attachment.getName());
content.addBodyPart(itemBodyPart);
}
}
msg.setContent(content);
//update headers
msg.saveChanges();
Transport.send(msg);
// set header value
for (Map.Entry<String, String[]> entry : item.getHeaders().entrySet()) {
String[] value = msg.getHeader(entry.getKey());
if (value != null) {
entry.setValue(value);
}
}
}
|
java
|
{
"resource": ""
}
|
q177796
|
AbstractAuthResource.generateStrongPassword
|
test
|
public String generateStrongPassword(T user, String oldPassword) {
String newPassword;
do {
newPassword = generateStrongPassword();
// Continue until new password does not contain user info or same with old password
}
while (newPassword.contains(user.getUsername()) || oldPassword.equals(Hashing.sha256().hashString(newPassword, Charset.forName("UTF-8")).toString()));
return newPassword;
}
|
java
|
{
"resource": ""
}
|
q177797
|
AbstractAuthResource.changePassword
|
test
|
public void changePassword(T user, String currentPassword, String newPassword, String newPassword2) throws AuthenticationException {
verifyPassword(user, currentPassword);
if (!newPassword.equals(newPassword2)) {
throw new AuthenticationException(user.getUsername() + ": New password and re-type password must be same");
} else if (newPassword.equals(currentPassword)) {
throw new AuthenticationException(user.getUsername() + ": New password and old password must be different");
}
verifyPasswordStrength(currentPassword, newPassword, user);
Optional<? extends UserEntry> optional = userStore.changePassword(user.getUsername(), newPassword);
if (!optional.isPresent()) {
throw new AuthenticationException(user.getUsername() + ": Can't update UserEntry Password");
}
}
|
java
|
{
"resource": ""
}
|
q177798
|
AbstractAuthResource.getUser
|
test
|
public T getUser(String accountName) {
Optional<T> optional = (Optional<T>) userStore.findByUsername(accountName);
if (optional.isPresent()) {
return optional.get();
} else {
return null;
}
}
|
java
|
{
"resource": ""
}
|
q177799
|
AbstractAuthResource.hashPassword
|
test
|
public String hashPassword(String password, String accountName) {
return Hashing.sha256().hashString(password, Charset.forName("UTF-8")).toString();
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.