hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
be195bee1eb66f3aa6482539a63f24e7a32bd903 | 38,424 | /****************************************************************************
* Copyright AGAT-Team (2014)
*
* Contributors:
* J.F. Randrianasoa
* K. Kurtz
* E. Desjardin
* N. Passat
*
* This software is a computer program whose purpose is to [describe
* functionalities and technical features of your software].
*
* This software is governed by the CeCILL-B license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-B
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*
* The full license is in the file LICENSE, distributed with this software.
*****************************************************************************/
package evaluation.datastructure;
import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeMap;
import datastructure.Node;
import ui.ImFrame;
import utils.ImTool;
import utils.LabelMatrix;
import utils.Log;
import utils.SegmentByConnexityRaw;
/**
*
* Segment of reference from a ground truth GT.
*
*/
public class SegReference{
/**
* Pixels of the segment according to its bounding box.
*/
public ArrayList<Point> bbPoints;
/**
* Height of the bounding box.
*/
public int bbHeight;
/**
* Width of the bounding box.
*/
public int bbWidth;
/**
* Best matching node.
*/
public Node bestN = null;
/**
* Best score of similarity associated with the best matched node 'lamda(S_i)'.
*/
public double bestSimilarityScore = 0.0;
/**
* Background color of the GT image.
*/
public int bgColor;
/**
* Bounding box including a margin.\n
*
* <ul>
* <li>boundingBox[0] is the cell coordinate of the upper-left point
* <li>boundingBox[1] is the cell coordinate of the lower-right point
* <li>boundingBox[2] is the row coordinate of the upper-left point
* <li>boundingBox[3] is the row coordinate of the lower-right point
* </ul>
*/
public int[] boundingBox = new int[4];
/**
* Path where the extracted GT informations are stored.
*/
public String gtPath;
/**
* Pixels of a segment contained in a GT image.
*/
public ArrayList<Point> gtPoints;
/**
* Path of the GT image associated to the segment.
*/
public String imgGtPath;
/**
* Height of the crop image containing only the segment.
*/
public int imgGtHeight;
/**
* Width of the GT image containing only the segment.
*/
public int imgGtWidth;
/**
* Index of the segment.
*/
public int index;
/**
* value[0] -> Number of segments in the class. <br>
* value[1] -> Size of all segments in the class. <br>
* value[2] -> Score f1 <br>
* value[3] -> Score f2 <br>
* Only the first segment of a list should contain this value.
*/
public TreeMap<Integer, Double[]> listOfAllSemanticLabels;
/**
* Number of pixels that will be added around the bounding box when computing a crop of the segment.
*/
public int margin;
/**
* A matrix containing the real valor of 'sigma_s(x)' i.e. < 0 for x in the segment, 0 on the border of the segment and > 0 outside the segment and contains also the value of 'Mu_alpha'.
* muMap[x][y][0] -> distance value <br>
* muMap[x][y][1] -> mu value
*/
public double[][][] muMap;
public static int nbSegs = 0;
/**
* Coordinates of the real bounding box without margins.
*/
public int[] realBoundingBox;
/**
* Thematic label.
*/
public int semanticLabel;
/**
* If true. the number of segments of each class and the total size of each class are computed.
* Only the first segment of the list should contain this value.
*/
public boolean sizeAndNbSet;
/**
* Prepare a segment of reference.
* @param index : identification of the segment.
* @param points ~ pixels contained in the segment of reference.
* @param semanticLabel : thematic label.
* @param bgColor : background color of the GT image.
*/
public SegReference(ArrayList<Point> points, int semanticLabel, int bgColor) {
this.index = ++SegReference.nbSegs;
this.gtPoints = points;
this.semanticLabel = semanticLabel;
this.bgColor = bgColor;
}
/**
* Prepare a segment of reference.
* @param imgGtPath : Path of an image containing only the segment having a white background.
* @param semanticLabel : thematic label
* @param bgColor : background color of the GT image.
* @param computeBB : if 'true', compute the bounding box and also fill a list of points having coordinates according to the bounding box.
*/
public SegReference(String imgGtPath, int semanticLabel, int bgColor, boolean computeBB){
this.index = ++SegReference.nbSegs;
/* Remember the gt crop image path. */
this.imgGtPath = imgGtPath;
/*
* Load the GT image.
*/
BufferedImage img = ImTool.read(this.imgGtPath);
this.imgGtWidth= img.getWidth();
this.imgGtHeight= img.getHeight();
/*
* Set the background color of the initial GT image containing the segments.
*/
// this.initBgColor(bgColor);
this.bgColor = bgColor;
/*
* Get the list of integer points.
*/
this.gtPoints = new ArrayList<Point>();
for(int x=0;x<this.imgGtWidth;x++) {
for(int y=0;y<this.imgGtHeight;y++) {
if(img.getRGB(x, y) != this.bgColor) {
Point p = new Point(x, y);
this.gtPoints.add(p);
}
}
}
/*
* Store a semantic label.
*/
this.semanticLabel = semanticLabel;
if(computeBB){
/*
* Compute the bounding box.
*/
this.computeRegionBoundingBox();
}
}
/**
* Create a segment of reference having a specified label.
* @param semanticLabel : thematic label.
* @param gtWidth : width of the GT image.
* @param gtHeight : height of the GT image.
* @param gtImgPath : path of the GT image.
* @param alpha : >0 allow controlling the degree of uncertainty.
*/
public SegReference(int semanticLabel, int gtWidth, int gtHeight, String gtImgPath, double alpha){
this.index = ++SegReference.nbSegs;
this.semanticLabel = semanticLabel;
this.imgGtWidth = gtWidth;
this.imgGtHeight = gtHeight;
this.imgGtPath = gtImgPath;
/* Pixel margin around the real bounding box */
if(alpha != 0) {
this.margin = (int)(Math.log((1 / 0.001) - 1) / alpha); /* in px */
}else {
this.margin = 0;
}
this.gtPoints = new ArrayList<Point>();
}
/**
* Create a segment of reference having a specified label.
* @param semanticLabel : thematic label.
* @param gtWidth : width of the GT image.
* @param gtHeight : height of the GT image.
* @param gtImgPath : path of the GT image.
* @param bgColor : background color of the GT image.
* @param alpha : >0 allow controlling the degree of uncertainty.
*/
public SegReference(int semanticLabel, int gtWidth, int gtHeight, String gtImgPath, int bgColor, double alpha){
this.index = ++SegReference.nbSegs;
this.semanticLabel = semanticLabel;
this.imgGtWidth = gtWidth;
this.imgGtHeight = gtHeight;
this.imgGtPath = gtImgPath;
this.bgColor = bgColor;
/* Pixel margin around the real bounding box */
if(alpha != 0) {
this.margin = (int)(Math.log((1 / 0.001) - 1) / alpha); /* in px */
}else {
this.margin = 0;
}
this.gtPoints = new ArrayList<Point>();
}
/**
* Add a pixel from a GT image.
* @param point ~ pixel to add.
*/
public void addGtPoint(Point point){
this.gtPoints.add(point);
}
/**
* Compute the bounding box BB of the segment and translate the pixels' location according to this BB.
* @return the real bounding box values.
*/
public int[] computeRegionBoundingBox() {
this.boundingBox = new int[4];
this.realBoundingBox = new int[4];
/* Compute a bounding box */
int minX = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int minY = Integer.MAX_VALUE;
int maxY = Integer.MIN_VALUE;
for(Point p : this.gtPoints) {
int x= p.x;
int y= p.y;
if(x < minX)
minX = x;
if(x > maxX)
maxX = x;
if(y < minY)
minY = y;
if(y > maxY)
maxY = y;
}
/* Remember the crop bounding box */
int minXMargin = minX - this.margin;
int maxXMargin = maxX + this.margin;
int minYMargin = minY - this.margin;
int maxYMargin = maxY + this.margin;
if(minXMargin >= 0) this.boundingBox[0] = minXMargin;
else this.boundingBox[0] = 0;
if(maxXMargin <= this.imgGtWidth) this.boundingBox[1] = maxXMargin;
else this.boundingBox[1] = this.imgGtWidth;
if(minYMargin >= 0) this.boundingBox[2] = minYMargin;
else this.boundingBox[2] = 0;
if(maxYMargin <= this.imgGtHeight) this.boundingBox[3] = maxYMargin;
else this.boundingBox[3] = this.imgGtHeight;
/* real bounding box values */
this.realBoundingBox[0] = minX;
this.realBoundingBox[1] = maxX;
this.realBoundingBox[2] = minY;
this.realBoundingBox[3] = maxY;
/* Compute the width and the height of the bounding box */
this.bbWidth = this.boundingBox[1] - this.boundingBox[0] + 1;
this.bbHeight = this.boundingBox[3] - this.boundingBox[2] + 1;
if(this.bbWidth <= 0) this.bbWidth = 1;
if(this.bbHeight <= 0) this.bbHeight = 1;
/* Update the pixel location values according to the bounding box */
this.gtToBB();
return realBoundingBox;
}
/**
* Removes a segment from a list of segments of reference according to its RGB integer color value.
* @param segReferences tree map containing some segments of reference.
* @param color of the segment to remove.
*/
public static void deleteSegment(TreeMap<Integer, SegReference> segReferences, int color) {
SegReference seg = segReferences.get(color);
if(seg != null){
segReferences.remove(color);
int i = 0;
for(Entry <Integer, SegReference> entry: segReferences.entrySet()) {
SegReference sr = entry.getValue();
sr.index = i++;
}
}
Log.println("Delete a seg. ref.", "nb. remaining segs.: "+ segReferences.size() +"\n");
}
/**
* Extracts all segments of a fat zone image and saves the valuable information in some files.
*
* @param gtImgPath : Path of the image GT having white background.
* @param alpha : >0 allow controlling the degree of uncertainty.
* @param generateCrops : saving map images and the segments in a file.
* @return
*/
public static TreeMap<Integer, SegReference> extractSegmentsOfReference(String gtImgPath, double alpha, boolean generateCrops){
Log.println("GT-EXTRACTION", "Starting");
/* Load the image */
BufferedImage gtImg = ImTool.read(gtImgPath);
int gtWidth = gtImg.getWidth();
int gtHeight = gtImg.getHeight();
/* Set containing list of segments of reference */
TreeMap<Integer, SegReference> listOfSegs = new TreeMap<Integer, SegReference>();
/* Get all the connected regions contained in the GT image */
SegmentByConnexityRaw sbc = new SegmentByConnexityRaw(gtImg);
LabelMatrix inputLabelMatrix = sbc.runForFullImage();
/* Extract the segments */
TreeMap<Integer, Double[]> semanticLabels = new TreeMap<Integer, Double[]>();
for(int y=0; y < gtHeight; ++y){
for(int x=0; x < gtWidth; ++x){
boolean isBlack = true;
int nbBands = Math.min(ImTool.getNbBandsOf(gtImg), 3);
for(int band = 0; band < nbBands; ++band) {
double val = ImTool.getPixelValue(x, y, band, gtImg);
if(val != 0) {
isBlack = false;
break;
}
}
if(!isBlack) { // drop the black background
int segLabNonSem = inputLabelMatrix.getLabel(x, y);
int rgbVal = gtImg.getRGB(x, y);
if(!listOfSegs.containsKey(segLabNonSem)){
/* create a segment of reference object, add it to the list with its semantic label */
int semanticLabel = rgbVal;
listOfSegs.put(segLabNonSem, new SegReference(semanticLabel, gtWidth, gtHeight, gtImgPath, alpha));
if(!semanticLabels.containsKey(semanticLabel)){
Double[] val = new Double[4];
val[0] = 0.0;
val[1] = 0.0;
val[2] = 0.0;
val[3] = 0.0;
semanticLabels.put(semanticLabel, val);
}
}
/* store the point ~ pixel in the segment of reference object */
listOfSegs.get(segLabNonSem).addGtPoint(new Point(x, y));
}
}
}
/* Use the first segment to store the information about the semantic labels */
listOfSegs.firstEntry().getValue().listOfAllSemanticLabels = semanticLabels;
/* Identify the correct path where the segment outputs will be stored */
String folderPath[] = gtImgPath.split("\\\\");
int lastIndex = folderPath.length - 1;
String gtImgName = folderPath[lastIndex];
String fpath[] = gtImgPath.split(gtImgName);
String gtPath = fpath[0] +"segref_("+ gtImgName +")";
/* Save a manifest file if it's not already existing */
String manifPath = gtPath +"//manifest";
File mf = new File(manifPath);
if(!mf.exists() || mf.isDirectory()){ /* create a file and register the number of segments and the 1st alpha used */
try {
/* global info on the list of segments */
new File(gtPath).mkdir();
PrintWriter manifWriter = new PrintWriter(manifPath, "UTF-8");
manifWriter.println(listOfSegs.size()); /* save <nb_segments> */
int it = 0;
for(Entry<Integer, Double[]> entry: semanticLabels.entrySet()){
manifWriter.print(entry.getKey());
if(it < semanticLabels.size() - 1)
manifWriter.print(";");
it++;
}
manifWriter.println();
manifWriter.print(alpha);
manifWriter.close();
} catch (Exception e){
e.printStackTrace();
}
}else{
/* add the current alpha in the manifest file */
try(FileWriter fw = new FileWriter(manifPath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)){
out.print(";"+ alpha); /* save alpha in the manifest file */
out.close();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/* Compute the distance map and save files for each segment of reference */
for(Map.Entry<Integer, SegReference> entry : listOfSegs.entrySet()){
SegReference s = entry.getValue();
s.muMap = DistanceMap.compute(s, alpha, gtPath);
if(generateCrops) {
String gtVisuPath = gtPath +"//gt-visu";
new File(gtVisuPath).mkdirs();
ImTool.save(s.toBufferedImage(), gtVisuPath +"//s-"+ s.index +".png");
}
}
int nbRegions = inputLabelMatrix.getNbRegions();
Log.println("Segment of reference", "number of segments including the background segments : "+ nbRegions);
Log.println("Segment of reference", "number of semantic labels : "+ semanticLabels.size());
return listOfSegs;
}
/**
* Get the set of pixels by considering their location in the bounding box.
* @return List of Point.
*/
public ArrayList<Point> getBbIntegerPoints(){
return this.bbPoints;
}
/**
* Get the set of pixels by considering their location in the GT image.
* @return List of Point.
*/
public ArrayList<Point> getPoints(){
return this.gtPoints;
}
/**
* From a saved file, get all segments. <br>
* The alpha considered for the mu maps is the first alpha mentioned in the manifest file. <br>
* @param path Folder containing save files. <br>
* @param visu if yes, show segments in windows. <br>
* @return a list of segments.
*/
public static TreeMap<Integer, SegReference> getSegReferences(String path, double alpha, boolean visu) {
/* Set containing list of segments of reference */
TreeMap<Integer, SegReference> listOfSegs = new TreeMap<Integer, SegReference>();
/* get important information for the manifest */
try {
/* read the manifest file and start to get information */
String manifPath = path +"//manifest";
BufferedReader br = new BufferedReader(new FileReader(manifPath));
String line = br.readLine(); /* got the number of segments */
String lineElems[];
String sep = ";";
int nbSegs = Integer.parseInt(line);
line = br.readLine();/* got the list of labels <lab1;lab2;...> */
lineElems = line.split(sep);
TreeMap<Integer, Double[]> semanticLabels = new TreeMap<Integer, Double[]>();
for(int i = 0; i < lineElems.length; ++i){
Double[] val = new Double[4];
val[0] = 0.0;
val[1] = 0.0;
val[2] = 0.0;
val[3] = 0.0;
semanticLabels.put(Integer.parseInt(lineElems[i]), val);
}
line = br.readLine(); /* got the alphas */
String alphas[] = line.split(sep);
/* parse each files corresponding to each segment */
for(int ns = 1; ns <= nbSegs; ++ns){
/* seg info */
String sPath = path +"//s-"+ ns;
BufferedReader segBr = new BufferedReader(new FileReader(sPath));
line = segBr.readLine(); /* got <index;semantic_label> */
lineElems = line.split(sep);
int index = Integer.parseInt(lineElems[0]);
int semanticLabel = Integer.parseInt(lineElems[1]);
line = segBr.readLine(); /* got <imgGtPath;imgGTWidth;imgGTHeight> */
lineElems = line.split(sep);
String gtImgPath = lineElems[0];
int gtWidth = Integer.parseInt(lineElems[1]);
int gtHeight = Integer.parseInt(lineElems[2]);
line = segBr.readLine(); /* got the real bounding box values <minX;maxX;minY;maxY> */
lineElems = line.split(sep);
int minX = Integer.parseInt(lineElems[0]);
int maxX = Integer.parseInt(lineElems[1]);
int minY = Integer.parseInt(lineElems[2]);
int maxY = Integer.parseInt(lineElems[3]);
line = segBr.readLine(); /* got the real int <bgcolor> */
int bgColor = Integer.parseInt(line);
/* create the base of the segment */
SegReference s = new SegReference(semanticLabel, gtWidth, gtHeight, gtImgPath, bgColor, alpha);
s.index = index; /* just in case */
s.bgColor = bgColor;
/* fill the crop bounding box information */
/* Remember the crop bounding box */
if(alpha >= 0){ /* use margin */
int minXMargin = minX - s.margin;
int maxXMargin = maxX + s.margin;
int minYMargin = minY - s.margin;
int maxYMargin = maxY + s.margin;
if(minXMargin >= 0) s.boundingBox[0] = minXMargin;
else s.boundingBox[0] = 0;
if(maxXMargin <= s.imgGtWidth) s.boundingBox[1] = maxXMargin;
else s.boundingBox[1] = s.imgGtWidth;
if(minYMargin >= 0) s.boundingBox[2] = minYMargin;
else s.boundingBox[2] = 0;
if(maxYMargin <= s.imgGtHeight) s.boundingBox[3] = maxYMargin;
else s.boundingBox[3] = s.imgGtHeight;
}else{
s.boundingBox[0] = minX;
s.boundingBox[1] = maxX;
s.boundingBox[2] = minY;
s.boundingBox[3] = maxY;
}
/* Compute the width and the height of the bounding box */
s.bbWidth = s.boundingBox[1] - s.boundingBox[0] + 1;
s.bbHeight = s.boundingBox[3] - s.boundingBox[2] + 1;
if(s.bbWidth <= 0) s.bbWidth = 1;
if(s.bbHeight <= 0) s.bbHeight = 1;
/* fill the gt points */
line = segBr.readLine(); /* got the <nbPoints> */
int nbPoints = Integer.parseInt(line);
for(int np = 0; np < nbPoints; ++np){
line = segBr.readLine(); /* got the gt point value */
String splited[] = line.split("_");
int x = Integer.parseInt(splited[0]);
int y = Integer.parseInt(splited[1]);
Point p = new Point(x, y);
s.gtPoints.add(p);
}
/* fill the bb points */
s.gtToBB();
/* add the segment in the list */
listOfSegs.put(ns, s);
/*
* In case of soft evaluation.
*/
/* check if the alpha exists in the manifest file */
if(alpha >=0 ){
int t = 0; // comme trouver
boolean found = false;
while(!found && t < alphas.length){
if(Double.parseDouble(alphas[t]) == alpha){
found = true;
}
t++;
}
if(!found){ /* compute an new mu map if the specified alpha is not found */
s.muMap = DistanceMap.compute(s, alpha, false, path);
s.margin = (int)(Math.log((1 / 0.001) - 1) / alpha); /* en px */
/* add the current alpha in the manifest file */
try(FileWriter fw = new FileWriter(manifPath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.print(";"+ alpha); /* save alpha in the manifest file */
out.close();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}else{
String distancePath = path +"//dist-"+ s.index +"-"+ alpha +".csv";
String muPath = path +"//mu-"+ s.index +"-"+ alpha +".csv";
BufferedReader dBr = new BufferedReader(new FileReader(distancePath));
BufferedReader mBr = new BufferedReader(new FileReader(muPath));
String line2, lineElems2[];
s.muMap = new double[s.bbWidth][s.bbHeight][2];
for(int h=0; h<s.bbHeight; ++h){
line = dBr.readLine(); /* got one row from the distance file */
lineElems = line.split(sep);
line2 = mBr.readLine(); /* got one row from the mu file */
lineElems2 = line2.split(sep);
for(int w=0; w<s.bbWidth; ++w){
s.muMap[w][h][0] = Double.parseDouble(lineElems[w]); /* set the distance value */
s.muMap[w][h][1] = Double.parseDouble(lineElems2[w]); /* set the mu value */
}
}
dBr.close();
mBr.close();
}
}
/* visualize the crop */
if(visu){
/* generate the segment crop image */
int white = 255;
int black = 0;
LabelMatrix crop = new LabelMatrix(s.bbWidth, s.bbHeight);
for (int j = 0; j < s.bbHeight; ++j){
for(int i = 0; i < s.bbWidth; ++i){
Point tmpPoint = new Point(i, j);
if(s.getBbIntegerPoints().contains(tmpPoint)) {
crop.setLabel(white, i, j);
}
else{
crop.setLabel(black, i, j);
}
}
}
/* show images in windows */
BufferedImage cropImg = ImTool.generateRegions(crop, null);
ImTool.show(cropImg, 50);
}
segBr.close();
}
/* Use the first segment to store the information about the semantic labels */
listOfSegs.firstEntry().getValue().listOfAllSemanticLabels = semanticLabels;
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return listOfSegs;
}
/**
* TODO obsolete
* From an image GT, get each segments.
* @param gtImgPath : Path of the image GT having white background.
* @param bgColor : background color of the GT image.
* @param alpha : >0 allow controlling the degree of uncertainty.
* @param computeDistanceMap : if true, compute the matrix of distance map and containing also the membership function.
* @param showMaps : if true, show the distance and the mu maps.
* @param save : saving map images and the segments in a file.
* @return
*/
public static TreeMap<Integer, SegReference> getSegReferences(String gtImgPath, int bgColor, double alpha, boolean computeDistanceMap, boolean showMaps, boolean save){
/* Load the image */
BufferedImage gtImg = ImTool.read(gtImgPath);
/* GT image width and height */
int gtWidth = gtImg.getWidth();
int gtHeight = gtImg.getHeight();
/* set the background color value */
int bgC = bgColor;
/* Set containing list of segments of reference */
TreeMap<Integer, SegReference> listOfSegs = new TreeMap<Integer, SegReference>();
/* Get all the segments contained in the GT image including its background */
SegmentByConnexityRaw sbc = new SegmentByConnexityRaw(gtImg);
LabelMatrix inputLabelMatrix = sbc.runForFullImage();
//inputLabelMatrix.print();
/* get all segments and drop the background */
TreeMap<Integer, Double[]> semanticLabels = new TreeMap<Integer, Double[]>();
for(int y=0; y < gtHeight; ++y){
for(int x=0; x < gtWidth; ++x){
int segLabNonSem = inputLabelMatrix.getLabel(x, y);
/* drop the background */
int rgbVal = gtImg.getRGB(x, y);
Color myColor = new Color(rgbVal);
rgbVal = ImTool.getRGBValueFrom(myColor.getRed(), myColor.getGreen(), myColor.getBlue());
System.out.println("\n\n rgbval: "+ rgbVal +", bgC: "+ bgC +"\n\n");
if(rgbVal != bgC){
if(!listOfSegs.containsKey(segLabNonSem)){
/* create a segment of reference object, add it to the list with its semantic label */
int semanticLabel = rgbVal;
listOfSegs.put(segLabNonSem, new SegReference(semanticLabel, gtWidth, gtHeight, gtImgPath, bgColor, alpha));
if(!semanticLabels.containsKey(semanticLabel)){
Double[] val = new Double[4];
val[0] = 0.0;
val[1] = 0.0;
val[2] = 0.0;
val[3] = 0.0;
semanticLabels.put(semanticLabel, val);
}
}
/* store the point ~ pixel in the segment of reference object */
listOfSegs.get(segLabNonSem).addGtPoint(new Point(x, y));
}
}
}
/* Use the first segment to store the information about the semantic labels */
listOfSegs.firstEntry().getValue().listOfAllSemanticLabels = semanticLabels;
/* preparing a path and a manifest file */
String path = null;
if(save){
/* set a correct path */
String folderPath[] = gtImgPath.split("//");
int lastIndex = folderPath.length - 1;
String gtImgName = folderPath[lastIndex];
String fpath[] = gtImgPath.split(gtImgName);
path = fpath[0] +"segref_("+ gtImgName +")";
/* save a manifest file if it's not already existing */
String manifPath = path +"//manifest";
File mf = new File(manifPath);
if(!mf.exists() || mf.isDirectory()){ /* create a file and register the number of segments and the 1st alpha used */
try {
/* global info on the list of segments */
new File(path).mkdir();
PrintWriter manifWriter = new PrintWriter(manifPath, "UTF-8");
manifWriter.println(listOfSegs.size()); /* save <nb_segments> */
int it = 0;
for(Entry<Integer, Double[]> entry: semanticLabels.entrySet()){
manifWriter.print(entry.getKey());
if(it < semanticLabels.size() - 1)
manifWriter.print(";");
it++;
}
manifWriter.println();
manifWriter.print(alpha);
manifWriter.close();
} catch (Exception e){
e.printStackTrace();
}
}else{
/* add the current alpha in the manifest file */
try(FileWriter fw = new FileWriter(manifPath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.print(";"+ alpha); /* save alpha in the manifest file */
out.close();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
boolean visu = true;
/* visualize the crop */
if(visu){
BufferedImage imgWithBBRect = ImTool.clone(gtImg);
for(Map.Entry<Integer, SegReference> entry : listOfSegs.entrySet()){
SegReference s = entry.getValue();
System.out.println(s.index);
int realBoundingBox[] = s.computeRegionBoundingBox();
/* generate the segment crop image */
int white = 1;
int black = 0;
LabelMatrix crop = new LabelMatrix(s.bbWidth, s.bbHeight);
System.out.println("bbWidth: "+ s.bbWidth +" bbHeight: "+ s.bbHeight);
for (int j = 0; j < s.bbHeight; ++j){
for(int i = 0; i < s.bbWidth; ++i){
Point tmpPoint = new Point(i, j);
if(s.getBbIntegerPoints().contains(tmpPoint)) {
crop.setLabel(white, i, j);
}
else{
crop.setLabel(black, i, j);
}
}
}
/* show images in windows */
HashMap<Integer, Color> lut = new HashMap<Integer, Color>();
lut.put(0, Color.black);
lut.put(1, Color.white);
BufferedImage cropImg = ImTool.generateRegions(crop, lut);
ImTool.show(cropImg, 30);
/* draw bounding boxes */
Random rand = new Random();
int r = rand.nextInt();
int g = rand.nextInt();
int b = rand.nextInt();
int color = ImTool.getRGBValueFrom(r, g, b);
ImTool.drawRectangleOn(imgWithBBRect,
realBoundingBox[0],
realBoundingBox[1],
realBoundingBox[2],
realBoundingBox[3],
color);
}
ImTool.show(imgWithBBRect, 30);
}
/* Compute or not the distance map */
if(computeDistanceMap)
for(Map.Entry<Integer, SegReference> entry : listOfSegs.entrySet()){
SegReference s = entry.getValue();
s.muMap = DistanceMap.compute(s, alpha, showMaps, path);
}
int nbRegions = inputLabelMatrix.getNbRegions();
Log.println("Segment of reference", "number of segments including the background segments : "+ nbRegions);
Log.println("Segment of reference", "number of semantic labels : "+ semanticLabels.size());
return listOfSegs;
}
/**
* Convert an x coordinate of the bounding box to the real x coordinate of the input gt image.
* @param x coordinate in the bounding box.
* @return X real coordinate in the gt input image.
*/
public int getSegRealX(int x) {
return this.boundingBox[0] + x;
}
/**
* Convert an y coordinate of the bounding box to the real y coordinate of the input gt image.
* @param y coordinate in the bounding box.
* @return y real coordinate in the gt input image.
*/
public int getSegRealY(int y) {
return this.boundingBox[2] + y;
}
/**
* Convert the value of each point from the GT image to the bounding box;
*/
public void gtToBB(){
int xdecal = this.boundingBox[0];
int ydecal = this.boundingBox[2];
this.bbPoints = new ArrayList<Point>();
for(Point pixel : this.gtPoints){
int xGt = pixel.x; // X POSITION OF THE POINT IN THE GT IMAGE.
int yGt = pixel.y; // Y POSITION OF THE POINT IN THE GT IMAGE.
Point newPixel = new Point((xGt - xdecal), (yGt - ydecal));
this.bbPoints.add(newPixel);
}
}
// /**
// * Initialize the background color picked from the GT image.
// * @param bgColor
// */
// private void initBgColor(BgColor bgColor) {
//
// switch(bgColor){
// case WHITE:
// this.bgColor = 255;
// break;
// case BLACK:
// this.bgColor = 0;
// break;
// default :
// this.bgColor = 0;
// break;
// }
//
// }
// /**
// * Possible background color of the GT image.
// *
// */
// public enum BgColor{
// WHITE,
// BLACK
// }
/**
* Retain the best matching node 'n' and the associated similarity score lambda(S_i).
* @param n
* @param lambda
*/
public void setBestMatchedNode(Node n, double lambda){
this.bestN = n;
this.bestSimilarityScore = lambda;
}
/**
* Create an image representing the segment and show it in a window.
* @param percent defines how the image covers the screen
*
* Example of values are:
* <li> {@link ImFrame#IMAGE_REAL_SIZE }
* <li> {@link ImFrame#IMAGE_DEFAULT_SIZE }
*/
public void show(int percent) {
ImTool.show(this.toBufferedImage(), percent, "S-"+ this.index);
}
public static BufferedImage showBoundingBoxes(TreeMap<Integer, SegReference> segReferences, BufferedImage image, int percent, String title) {
BufferedImage imgWithBBRect = ImTool.clone(image);
for(Map.Entry<Integer, SegReference> entry : segReferences.entrySet()){
SegReference s = entry.getValue();
s.show(percent);
/* draw bounding boxes */
Random rand = new Random();
int r = rand.nextInt();
int g = rand.nextInt();
int b = rand.nextInt();
int color = ImTool.getRGBValueFrom(r, g, b);
ImTool.drawRectangleOn(imgWithBBRect,
s.realBoundingBox[0],
s.realBoundingBox[1],
s.realBoundingBox[2],
s.realBoundingBox[3],
color);
}
ImTool.show(imgWithBBRect, percent, title);
return imgWithBBRect;
}
public int size(){
return this.gtPoints.size();
}
public BufferedImage toBufferedImage() {
this.computeRegionBoundingBox();
/* Generate the segment crop image */
int white = 1;
int black = 0;
LabelMatrix crop = new LabelMatrix(this.bbWidth, this.bbHeight);
for (int j = 0; j < this.bbHeight; ++j){
for(int i = 0; i < this.bbWidth; ++i){
Point tmpPoint = new Point(i, j);
if(this.getBbIntegerPoints().contains(tmpPoint)) {
crop.setLabel(white, i, j);
}
else{
crop.setLabel(black, i, j);
}
}
}
/* Generate a buffered image from the label matrix */
HashMap<Integer, Color> lut = new HashMap<Integer, Color>();
lut.put(white, Color.white);
lut.put(black, Color.black);
return ImTool.generateRegions(crop, lut);
}
/**
* From a saved file, get all segments. <br>
* @param path Folder containing the saved files.
* @param alpha
* @param visu
* @return
*/
// public static TreeMap<Integer, SegReference> getSegReferences(String path, double alpha, boolean visu) {
//
// /* Set containing list of segments of reference */
// TreeMap<Integer, SegReference> listOfSegs = SegReference.getSegReferences(path, visu);
//
// /* fill the distance map and the mu map */
// String line, lineElems[];
// String sep = ";";
// try{
//
// for(Entry<Integer,SegReference> entry: listOfSegs.entrySet()){
//
// SegReference s = entry.getValue();
//
// String distancePath = path +"//dist-"+ s.index +"-"+ alpha +".csv";
// String muPath = path +"//mu-"+ s.index +"-"+ alpha +".csv";
// BufferedReader dBr = new BufferedReader(new FileReader(distancePath));
// BufferedReader mBr = new BufferedReader(new FileReader(muPath));
// String line2, lineElems2[];
// s.muMap = new double[s.bbWidth][s.bbHeight][2];
// for(int h=0; h<s.bbHeight; ++h){
// line = dBr.readLine(); /* got one row from the distance file */
// lineElems = line.split(sep);
// line2 = mBr.readLine(); /* got one row from the mu file */
// lineElems2 = line2.split(sep);
// for(int w=0; w<s.bbWidth; ++w){
//
// s.muMap[w][h][0] = Double.parseDouble(lineElems[w]); /* set the distance value */
// s.muMap[w][h][1] = Double.parseDouble(lineElems2[w]); /* set the mu value */
//
// }
// }
// dBr.close();
// mBr.close();
//
// }
//
// }catch(Exception e){
// e.printStackTrace();
// }
//
// /* verification if the mu map for the specified alpha is not already computed and stored in a file */
// String manifPath = path +"//manifest";
// try {
//
// BufferedReader br = new BufferedReader(new FileReader(manifPath));
// line = br.readLine(); /* got the <nb_segs> */
// line = br.readLine(); /* got the <lab1;lab2;...> */
//
// line = br.readLine(); /* got the list of alphas */
// lineElems = line.split(";");
// boolean found = false;
// int i = 0;
// while(!found && i < lineElems.length){
//
// if(Double.parseDouble(lineElems[i]) == alpha){
// found = true;
// }
// i++;
//
// }
//
// br.close();
//
// if(!found){ /* compute an new mu map if the specified alpha is not found */
//
// for(Map.Entry<Integer, SegReference> entry : listOfSegs.entrySet()){
//
// SegReference s = entry.getValue();
// s.muMap = DistanceMap.compute(s, alpha, false, path);
// s.margin = (int)(Math.log((1 / 0.001) - 1) / alpha); /* en px */
//
// }
//
// /* add the current alpha in the manifest file */
// try(FileWriter fw = new FileWriter(manifPath, true);
// BufferedWriter bw = new BufferedWriter(fw);
// PrintWriter out = new PrintWriter(bw))
// {
// out.print(";"+ alpha); /* save alpha in the manifest file */
// out.close();
// bw.close();
// fw.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// }
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
//
// return listOfSegs;
// }
}
| 30.471055 | 188 | 0.617401 |
1e76d3629051c22a2099db90d2f37b4e39010c10 | 3,432 | package com.restaurant.dinner.admin.controller.base;
import com.restaurant.dinner.admin.ProjectProperties;
import com.restaurant.dinner.api.pojo.po.admin.TbSysUser;
import com.restaurant.dinner.api.pojo.vo.JsonObjectVo;
import com.restaurant.dinner.api.recipe.admin.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* 登录接口
*
* @date 2016-11-06
* @author 赵梓彧 - [email protected]
*/
@Controller
@RequestMapping(value = "/")
public class LoginController {
private final static String LOGIN_MODE_NAME_OR_PHONE = "1";//登录方式:用户名或手机号(默认)
private final static String LOGIN_MODE_PHONE_IDENTIFYING_CODE = "2";//登录方式:手机验证码
private final static String LOGIN_MODE_QR_CODE = "3";//登录方式:二维码扫描
@Autowired
private SysUserService sysUserService;
@RequestMapping("/doLogin")
@ResponseBody
public JsonObjectVo<Object> doLogin(HttpServletRequest request, HttpSession httpSession) {
JsonObjectVo<Object> jsonObjectVo = new JsonObjectVo<>();
String loginMode = request.getParameter("mode");//登录方式(根据登录方式判断所需的请求参数)
TbSysUser user = null;
if (loginMode == null || LOGIN_MODE_NAME_OR_PHONE.equals(loginMode)) {
// 登录方式:用户名或手机号(默认)
String logincode = request.getParameter("code");
if (logincode == null) {
jsonObjectVo.setSuccess(false);
jsonObjectVo.setMsg("未输入用户名");
return jsonObjectVo;
}
String password = request.getParameter("password");
if (password == null) {
jsonObjectVo.setSuccess(false);
jsonObjectVo.setMsg("未输入密码");
return jsonObjectVo;
}
try {
user = sysUserService.loginByNameOrPhone(logincode, password);
} catch (Exception e) {
e.printStackTrace();
jsonObjectVo.setSuccess(false);
jsonObjectVo.setMsg(e.getMessage());
return jsonObjectVo;
}
} else if (LOGIN_MODE_PHONE_IDENTIFYING_CODE.equals(loginMode)) {
// 登录方式:手机验证码
} else if (LOGIN_MODE_QR_CODE.equals(loginMode)) {
// 登录方式:二维码扫描
} else {
jsonObjectVo.setSuccess(false);
jsonObjectVo.setMsg("登录方式不存在");
return jsonObjectVo;
}
if (user != null) {
httpSession.setAttribute(ProjectProperties.SESSION_USER_FULL_NAME, user.getFullName());
httpSession.setAttribute(ProjectProperties.SESSION_USER_ID, user.getId());
jsonObjectVo.setSuccess(true);
return jsonObjectVo;
} else {
jsonObjectVo.setSuccess(false);
jsonObjectVo.setMsg("用户名或密码错误");
return jsonObjectVo;
}
}
@RequestMapping("/doLogout")
public String doLogout(ModelMap map, HttpSession httpSession) {
httpSession.removeAttribute(ProjectProperties.SESSION_USER_FULL_NAME);
httpSession.removeAttribute(ProjectProperties.SESSION_USER_ID);
return "redirect:/login";// 跳转到[/login]处理器
}
}
| 36.903226 | 99 | 0.6588 |
4fca8674a11c67a60335e3c94a1e72a4e202335a | 4,908 | /*
* #%L
* AbstractSaslAuthenticator.java - mongodb-async-driver - Allanbank Consulting, Inc.
* %%
* Copyright (C) 2011 - 2014 Allanbank Consulting, 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.
* #L%
*/
package com.allanbank.mongodb.client.connection.auth;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
import com.allanbank.mongodb.Credential;
import com.allanbank.mongodb.bson.builder.BuilderFactory;
import com.allanbank.mongodb.bson.builder.DocumentBuilder;
import com.allanbank.mongodb.client.callback.ReplyCallback;
import com.allanbank.mongodb.client.connection.Connection;
import com.allanbank.mongodb.client.message.Command;
import com.allanbank.mongodb.error.MongoDbAuthenticationException;
/**
* AbstractSaslAuthenticator provides the basic logic for a SASL based
* authenticator.
*
* @api.no This class is <b>NOT</b> part of the drivers API. This class may be
* mutated in incompatible ways between any two releases of the
* extensions.
* @copyright 2014, Allanbank Consulting, Inc., All Rights Reserved
*/
public abstract class AbstractSaslAuthenticator
extends AbstractAuthenticator {
/** An empty set of bytes. */
public static final byte[] EMPTY_BYTES = SaslResponseCallback.EMPTY_BYTES;
/** The database to authenticate against. */
public static final String EXTERNAL = SaslResponseCallback.EXTERNAL;
/**
* Creates a new AbstractSaslAuthenticator.
*/
public AbstractSaslAuthenticator() {
super();
}
/**
* Starts to authenticate the user with the specified credentials.
*
* @param credentials
* The credentials to use to login to the database.
* @param connection
* The connection to authenticate the user with.
* @throws MongoDbAuthenticationException
* On a failure in the protocol to authenticate the user on the
* connection.
*/
public void startAuthentication(final Credential credentials,
final Connection connection) throws MongoDbAuthenticationException {
try {
final SaslClient client = createSaslClient(credentials, connection);
if (client != null) {
byte[] payload = EMPTY_BYTES;
if (client.hasInitialResponse()) {
payload = client.evaluateChallenge(payload);
}
sendStart(payload, connection, new SaslResponseCallback(client,
connection, myResults));
}
else {
throw new MongoDbAuthenticationException(
"Could not locate a SASL provider.");
}
}
catch (final SaslException e) {
throw new MongoDbAuthenticationException(e);
}
}
/**
* Creates the SASL Client.
*
* @param credentials
* The credentials to use in creating the client.
* @param connection
* The connection we are authenticating against.
* @return The {@link SaslClient} for the authentication.
* @throws MongoDbAuthenticationException
* On an authentication error.
* @throws SaslException
* On a SASL error.
*/
protected abstract SaslClient createSaslClient(
final Credential credentials, final Connection connection)
throws MongoDbAuthenticationException, SaslException;
/**
* The SASL mechanism name.
*
* @return The SASL mechanism name.
*/
protected abstract String getMechanism();
/**
* Sends an initial request to authenticate with the server.
*
* @param payload
* The payload for the request.
* @param connection
* The connection to authenticate.
* @param callback
* The callback to handle the reply.
*/
protected void sendStart(final byte[] payload, final Connection connection,
final ReplyCallback callback) {
final DocumentBuilder cmd = BuilderFactory.start();
cmd.add("saslStart", 1);
cmd.add("mechanism", getMechanism());
cmd.add("payload", payload);
connection.send(
new Command(EXTERNAL, Command.COMMAND_COLLECTION, cmd.build()),
callback);
}
} | 35.565217 | 85 | 0.650774 |
f45f2d1a7c077db9d6f15d548441f25b3a2bbc0d | 7,039 | package com.wavefront.agent.handlers;
import com.wavefront.agent.data.EntityPropertiesFactory;
import com.wavefront.common.SamplingLogger;
import com.wavefront.api.agent.ValidationConfiguration;
import com.wavefront.data.ReportableEntityType;
import org.apache.commons.lang.math.NumberUtils;
import wavefront.report.Histogram;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Caching factory for {@link ReportableEntityHandler} objects. Makes sure there's only one handler
* for each {@link HandlerKey}, which makes it possible to spin up handlers on demand at runtime,
* as well as redirecting traffic to a different pipeline.
*
* @author [email protected]
*/
public class ReportableEntityHandlerFactoryImpl implements ReportableEntityHandlerFactory {
private static final Logger logger = Logger.getLogger("sampling");
public static final Logger VALID_POINTS_LOGGER = new SamplingLogger(
ReportableEntityType.POINT, Logger.getLogger("RawValidPoints"),
getSystemPropertyAsDouble("wavefront.proxy.logpoints.sample-rate"),
"true".equalsIgnoreCase(System.getProperty("wavefront.proxy.logpoints")), logger::info);
public static final Logger VALID_HISTOGRAMS_LOGGER = new SamplingLogger(
ReportableEntityType.HISTOGRAM, Logger.getLogger("RawValidHistograms"),
getSystemPropertyAsDouble("wavefront.proxy.logpoints.sample-rate"),
"true".equalsIgnoreCase(System.getProperty("wavefront.proxy.logpoints")), logger::info);
private static final Logger VALID_SPANS_LOGGER = new SamplingLogger(
ReportableEntityType.TRACE, Logger.getLogger("RawValidSpans"),
getSystemPropertyAsDouble("wavefront.proxy.logspans.sample-rate"), false, logger::info);
private static final Logger VALID_SPAN_LOGS_LOGGER = new SamplingLogger(
ReportableEntityType.TRACE_SPAN_LOGS, Logger.getLogger("RawValidSpanLogs"),
getSystemPropertyAsDouble("wavefront.proxy.logspans.sample-rate"), false, logger::info);
private static final Logger VALID_EVENTS_LOGGER = new SamplingLogger(
ReportableEntityType.EVENT, Logger.getLogger("RawValidEvents"),
getSystemPropertyAsDouble("wavefront.proxy.logevents.sample-rate"), false, logger::info);
protected final Map<String, Map<ReportableEntityType, ReportableEntityHandler<?, ?>>> handlers =
new ConcurrentHashMap<>();
private final SenderTaskFactory senderTaskFactory;
private final int blockedItemsPerBatch;
private final ValidationConfiguration validationConfig;
private final Logger blockedPointsLogger;
private final Logger blockedHistogramsLogger;
private final Logger blockedSpansLogger;
private final Function<Histogram, Histogram> histogramRecompressor;
private final EntityPropertiesFactory entityPropertiesFactory;
/**
* Create new instance.
*
* @param senderTaskFactory SenderTaskFactory instance used to create SenderTasks
* for new handlers.
* @param blockedItemsPerBatch controls sample rate of how many blocked points are written
* into the main log file.
* @param validationConfig validation configuration.
*/
public ReportableEntityHandlerFactoryImpl(
final SenderTaskFactory senderTaskFactory, final int blockedItemsPerBatch,
@Nonnull final ValidationConfiguration validationConfig, final Logger blockedPointsLogger,
final Logger blockedHistogramsLogger, final Logger blockedSpansLogger,
@Nullable Function<Histogram, Histogram> histogramRecompressor,
EntityPropertiesFactory entityPropertiesFactory) {
this.senderTaskFactory = senderTaskFactory;
this.blockedItemsPerBatch = blockedItemsPerBatch;
this.validationConfig = validationConfig;
this.blockedPointsLogger = blockedPointsLogger;
this.blockedHistogramsLogger = blockedHistogramsLogger;
this.blockedSpansLogger = blockedSpansLogger;
this.histogramRecompressor = histogramRecompressor;
this.entityPropertiesFactory = entityPropertiesFactory;
}
@SuppressWarnings("unchecked")
@Override
public <T, U> ReportableEntityHandler<T, U> getHandler(HandlerKey handlerKey) {
Consumer<Long> receivedRateSink = rate ->
entityPropertiesFactory.get(handlerKey.getEntityType()).
reportReceivedRate(handlerKey.getHandle(), rate);
return (ReportableEntityHandler<T, U>) handlers.computeIfAbsent(handlerKey.getHandle(),
h -> new ConcurrentHashMap<>()).computeIfAbsent(handlerKey.getEntityType(), k -> {
switch (handlerKey.getEntityType()) {
case POINT:
return new ReportPointHandlerImpl(handlerKey, blockedItemsPerBatch,
senderTaskFactory.createSenderTasks(handlerKey), validationConfig, true,
receivedRateSink, blockedPointsLogger, VALID_POINTS_LOGGER, null);
case HISTOGRAM:
return new ReportPointHandlerImpl(handlerKey, blockedItemsPerBatch,
senderTaskFactory.createSenderTasks(handlerKey), validationConfig, true,
receivedRateSink, blockedHistogramsLogger, VALID_HISTOGRAMS_LOGGER,
histogramRecompressor);
case SOURCE_TAG:
return new ReportSourceTagHandlerImpl(handlerKey, blockedItemsPerBatch,
senderTaskFactory.createSenderTasks(handlerKey), receivedRateSink,
blockedPointsLogger);
case TRACE:
return new SpanHandlerImpl(handlerKey, blockedItemsPerBatch,
senderTaskFactory.createSenderTasks(handlerKey),
validationConfig, receivedRateSink, blockedSpansLogger, VALID_SPANS_LOGGER,
() -> entityPropertiesFactory.getGlobalProperties().getDropSpansDelayedMinutes());
case TRACE_SPAN_LOGS:
return new SpanLogsHandlerImpl(handlerKey, blockedItemsPerBatch,
senderTaskFactory.createSenderTasks(handlerKey), receivedRateSink,
blockedSpansLogger, VALID_SPAN_LOGS_LOGGER);
case EVENT:
return new EventHandlerImpl(handlerKey, blockedItemsPerBatch,
senderTaskFactory.createSenderTasks(handlerKey), receivedRateSink,
blockedPointsLogger, VALID_EVENTS_LOGGER);
default:
throw new IllegalArgumentException("Unexpected entity type " +
handlerKey.getEntityType().name() + " for " + handlerKey.getHandle());
}
});
}
@Override
public void shutdown(@Nonnull String handle) {
if (handlers.containsKey(handle)) {
handlers.get(handle).values().forEach(ReportableEntityHandler::shutdown);
}
}
private static double getSystemPropertyAsDouble(String propertyName) {
String sampleRateProperty = propertyName == null ? null : System.getProperty(propertyName);
return NumberUtils.isNumber(sampleRateProperty) ? Double.parseDouble(sampleRateProperty) : 1.0d;
}
}
| 50.640288 | 100 | 0.756926 |
216c9bf8e19623bdb9ab0f1918f9abd7802c76e1 | 359 | package dev.cheerfun.pixivic.biz.web.collection.dto;
import lombok.Data;
/**
* @author OysterQAQ
* @version 1.0
* @date 2020/5/2 8:01 下午
* @description UpdateIllustrationOrderDTO
*/
@Data
public class UpdateIllustrationOrderDTO {
private Integer upIllustrationId;
private Integer lowIllustrationId;
private Integer reOrderIllustrationId;
}
| 21.117647 | 52 | 0.760446 |
6bb8b6bc60cc560363a82acec40dceaa048537e8 | 2,540 | package minevalley.core.api.corporations;
import minevalley.core.api.Registered;
import minevalley.core.api.economy.BankAccount;
import java.util.List;
public interface Group extends Registered {
/**
* Gets the id of this group.
*
* @return id of group
*/
int getId();
/**
* Gets the name of this group.
*
* @return name of group
*/
String getName();
/**
* Sets the name of this group.
*
* @return Result of the rename
*/
RenameFeedback changeName(String name);
/**
* Gets this group's description
*
* @return description as string
*/
String getDescription();
/**
* Sets the description of this group.
*
* @param description description as string
*/
void setDescription(String description);
/**
* Changes the description of this group. Max. length = 150 chars; Min. length = 15 chars
*
* @param description description as string
* @return result of the description change
*/
RenameFeedback changeDescription(String description);
/**
* Gets whether this group is a company (otherwise: organization).
*
* @return true, if group is company
*/
boolean isCompany();
/**
* Gets this group's owner.
*
* @return unique id of owner as string
*/
String getOwner();
/**
* Gets a list of all operators.
*
* @return list of all operators' unique ids
*/
List<String> getOperators();
/**
* Gets the department, which is markes as default.
*
* @return group's default department
*/
Department getDefaultDepartment();
/**
* Gets a list of all departments.
*
* @return departments as list
*/
List<Department> getDepartments();
/**
* Removes the member with the specific unique id from this group.
*
* @param uniqueId member to remove
*/
void removeMember(String uniqueId);
/**
* Adds a member with the specific unique id to this group.
*
* @param uniqueId member to add
*/
void addMember(String uniqueId);
/**
* Gets the bank account of this group.
*
* @return bank account of group
*/
BankAccount getBankAccount();
/**
* Deletes this group.
*/
void delete();
enum RenameFeedback {
FORBIDDEN_CHARACTERS,
FORBIDDEN_WORDS,
ALREADY_USED,
TOO_LONG,
TOO_SHORT,
SUCCESS
}
}
| 20.650407 | 93 | 0.588583 |
df83c1cdb9a5218283b667719526cbba89902e85 | 849 | package uk.co.stikman.utils;
import java.util.HashMap;
import java.util.Map;
public class MimeTypes {
public static final Map<String, String> MIME_TYPES = new HashMap<>();
static {
MIME_TYPES.put(".css", "text/css");
MIME_TYPES.put(".js", "text/javascript");
MIME_TYPES.put(".html", "text/html");
MIME_TYPES.put(".htm", "text/html");
MIME_TYPES.put(".jpg", "image/jpeg");
MIME_TYPES.put(".jpeg", "image/jpeg");
MIME_TYPES.put(".png", "image/png");
MIME_TYPES.put(".gif", "image/gif");
}
public static String find(String filename) {
return find(filename, "application/octet-stream");
}
public static String find(String filename, String def) {
String s = filename;
int pos = s.lastIndexOf('.');
if (pos != -1)
s = s.substring(pos);
String x = MIME_TYPES.get(s);
if (x == null)
return def;
return x;
}
}
| 24.257143 | 70 | 0.656066 |
64d6cea235efbf895987581afc82f14882b24458 | 2,701 | package com.mooc.ppjoke.utils;
import android.content.ComponentName;
import androidx.fragment.app.FragmentActivity;
import androidx.navigation.ActivityNavigator;
import androidx.navigation.NavController;
import androidx.navigation.NavGraph;
import androidx.navigation.NavGraphNavigator;
import androidx.navigation.NavigatorProvider;
import androidx.navigation.fragment.FragmentNavigator;
import com.mooc.libcommon.global.AppGlobals;
import com.mooc.ppjoke.FixFragmentNavigator;
import com.mooc.ppjoke.model.Destination;
import java.util.HashMap;
public class NavGraphBuilder {
//需要和NavController相关联,所以该方法的参数就为此
//需要外部传入activity和containId
public static void build(NavController controller,FragmentActivity activity,int containerId){
//通过响应的Navigate创建相应的页面节点
NavigatorProvider provider = controller.getNavigatorProvider();
//分别获取FragmentNavigator和ActivityNavigator对象
// FragmentNavigator fragmentNavigator = provider.getNavigator(FragmentNavigator.class);
//使用自建的导航器FixFragmentNavigator
FixFragmentNavigator fragmentNavigator=new FixFragmentNavigator(activity,activity.getSupportFragmentManager(),containerId);
//创建完成之后需要添加到NavigatorProvider的hashMap中去
provider.addNavigator(fragmentNavigator);
ActivityNavigator activityNavigator=provider.getNavigator(ActivityNavigator.class);
//后面的数据要添加到改NavGraph中
NavGraph navGraph=new NavGraph(new NavGraphNavigator(provider));
HashMap<String, Destination> destConfig=AppConfig.getDestConfig();
for (Destination value : destConfig.values()) {
if (value.isFragment){
FragmentNavigator.Destination destination=fragmentNavigator.createDestination();
//向destination中填相应的字段
destination.setClassName(value.className);
destination.setId(value.id);
destination.addDeepLink(value.pageUrl);
navGraph.addDestination(destination);
}else {
ActivityNavigator.Destination destination=activityNavigator.createDestination();
destination.setId(value.id);
destination.addDeepLink(value.pageUrl);
destination.setComponentName(new ComponentName(AppGlobals.getApplication().getPackageName(),value.className));
navGraph.addDestination(destination);
}
//如果value是默认启动页
if (value.asStarter){
navGraph.setStartDestination(value.id);
}
}
//将navGraph赋值给controller
controller.setGraph(navGraph);
}
}
| 37.513889 | 132 | 0.701222 |
36c7bc3b7a72f7ec88f3f33b05e4aced3c9155b8 | 950 | package org.nautilus.plugin.factory;
import java.util.ArrayList;
import java.util.List;
import org.nautilus.plugin.extension.SelectionExtension;
import org.nautilus.plugin.extension.selection.BinaryTournamentWithRankingAndCrowdingDistanceSelectionExtension;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.solution.Solution;
public class SelectionFactory {
private List<SelectionExtension> extensions = new ArrayList<>();
public SelectionFactory() {
extensions.add(new BinaryTournamentWithRankingAndCrowdingDistanceSelectionExtension());
}
public List<SelectionExtension> getExtensions() {
return extensions;
}
public SelectionOperator<List<? extends Solution<?>>, ? extends Solution<?>> getSelection(String selectionId) {
for (SelectionExtension extension : getExtensions()) {
if (selectionId.equalsIgnoreCase(extension.getId())) {
return extension.getSelection();
}
}
return null;
}
}
| 27.142857 | 112 | 0.789474 |
4e569df2f27f53b3523e1b1d15cf2c199a1be9b2 | 370 | package com.cn.luckymorning.study.optional;
/**
* Main
*
* @author lucky_morning
* @group com.cn.luckymorning.study.optional
* @date 2020/8/21 13:51
*/
public class Main {
public static void main(String[] args) {
System.out.println(OptionalDemo.testOptionalOrElse(null));
System.out.println(OptionalDemo.testOptionalOrElseGet(null));
}
}
| 21.764706 | 69 | 0.697297 |
d221688fc2520ac3e473f3706bbbe41614008cc4 | 1,355 | package cyclops.data;
import cyclops.reactive.ReactiveSeq;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
public class HashSet2Test {
@Test
public void duplicates(){
assertThat(HashSet.of(1,2,1,2,1,2).size(),equalTo(2));
}
@Test
public void nines(){
/** HashSet<Integer> hs = HashSet.<Integer>empty().plus(9).plus(-10).plus(8)
.plus(-9);
System.out.println("-9?"+hs.containsValue(-9));
**/
System.out.println(HashSet.<Long>empty().plus(9l).plus(-10l)
.plus(8l));
// .plus(-9l));
}
@Test
public void reversedRangeLongWithReverse(){
HashSet<Long> s = HashSet.rangeLong(10, -10);
// HashSet<Long> s = (HashSet)HashSet.rangeLong(10, -10).reverse();
//System.out.println(HashSet.fromStream(ReactiveSeq.rangeLong(10,-10).reverse()));
System.out.println("******************");
System.out.println("******************");
System.out.println(s.reverse());
/** System.out.println(((HashSet)s.reverse()).getMap());
assertThat(HashSet.rangeLong(10, -10).reverse().count(),equalTo(20L));
**/
}
}
//[0,-1,1,-2,2,-3,3,-4,4,-5,5,-6,6,-7,7,-8,-9,8,9,-10,9,-10]
//[-1,0,-2,1,-3,2,-4,3,-5,4,-6,5,-7,6,-8,7,-9,8,-10,9] | 32.261905 | 89 | 0.564576 |
553ebc82d7353a6489a0ab1c388b19bd4d851907 | 3,410 | package edu.uw.covidsafe.ble;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.os.ParcelUuid;
import android.util.Log;
import edu.uw.covidsafe.utils.ByteUtils;
import edu.uw.covidsafe.utils.Constants;
import edu.uw.covidsafe.utils.Utils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class BluetoothScanHelper implements Runnable {
public static AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
Log.e("ble", "BLE advertisement added successfully "+settingsInEffect.toString());
}
@Override
public void onStartFailure(int errorCode) {
Log.e("ble", "Failed to add BLE advertisement, reason: " + errorCode);
}
};
static Context cxt;
public BluetoothScanHelper(Context cxt) {
this.cxt = cxt;
}
@Override
public void run() {
Log.e("ble","mytask-run ");
ScanSettings.Builder builder = new ScanSettings.Builder();
builder.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER);
ScanFilter filter = new ScanFilter.Builder()
.setServiceUuid(new ParcelUuid(Constants.BEACON_SERVICE_UUID))
.build();
List<ScanFilter> filters = new LinkedList<ScanFilter>();
filters.add(filter);
Constants.scannedUUIDs = new HashSet<String>();
Constants.scannedUUIDsRSSIs = new HashMap<String,Integer>();
Constants.blueAdapter.getBluetoothLeScanner().startScan(filters, builder.build(), mLeScanCallback);
}
public static ScanCallback mLeScanCallback =
new ScanCallback() {
@Override
public void onScanResult(int callbackType, final ScanResult result) {
super.onScanResult(callbackType, result);
Map<ParcelUuid, byte[]> map = result.getScanRecord().getServiceData();
byte[] data = map.get(new ParcelUuid(Constants.BEACON_SERVICE_UUID));
Log.e("ble","onscanresult "+(data==null));
if (data != null && data.length == 16) {
String contactUuid = ByteUtils.byte2UUIDstring(data);
// Log.e("uuid","CONTACT "+contactUuid);
int rssi = result.getRssi();
if (Constants.scannedUUIDs != null &&
!Constants.scannedUUIDs.contains(contactUuid) &&
rssi >= Constants.rssiCutoff) {
// String[] elts = contactUuid.split("-");
Constants.scannedUUIDs.add(contactUuid);
Constants.scannedUUIDsRSSIs.put(contactUuid, rssi);
}
}
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.e("ble", "error onscanfailed "+errorCode);
}
};
}
| 37.472527 | 107 | 0.607918 |
6e3258dc9af5ca5eb061c8d96a1e87bc0fb03b71 | 3,057 | package com.manoelcampos.exportador;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Classe abstrata que fornece uma implementação base para as subclasses
* que definem formatos específicos de exportação de dados.
*
* @author Manoel Campos da Silva Filho
*/
public abstract class AbstractExportadorListaProduto implements ExportadorListaProduto {
/**
* Colunas a serem exibidas na tabela gerada no processo de exportação.
*/
protected static final List<String> TITULOS_COLUNAS = Arrays.asList("ID", "Descrição", "Marca", "Modelo", "Estoque");
private List<Coluna> colunas;
public AbstractExportadorListaProduto() {
colunas = new ArrayList<>();
addNewColuna(Produto::getId, "Código");
addNewColuna(Produto::getDescricao, "Descrição");
}
protected void addCOluna(Coluna coluna) {
getColunas().add(coluna);
}
@Override
public final String exportar(List<Produto> listaProdutos) {
final StringBuilder sb = new StringBuilder();
sb.append(abrirTabela());
sb.append(abrirLinha());
for (Coluna coluna : getColunas()) {
sb.append(coluna.exportarCabecalho());
}
sb.append(fecharLinha());
sb.append("\n");
sb.append(fecharLinhaTitulos());
gerarLinhasProdutos(sb, listaProdutos);
sb.append(fecharTabela());
return sb.toString();
}
/**
* Gera o texto representando todas as linhas de uma tabela (em um formato definido pelas subclasses)
* contendo os dados dos produtos na lista de produtos.
*
* @param sb {@link StringBuilder} onde o texto gerado será adicionado
* @param listaProdutos
*/
private void gerarLinhasProdutos(StringBuilder sb, List<Produto> listaProdutos) {
for (Produto produto : listaProdutos) {
sb.append(gerarColunasLinha(produto));
}
}
/**
* Gera o texto representando uma única linha de uma tabela (em um formato definido pelas subclasses).
*
* @param produto valores a serem exibidos nas colunas, que podem ser:
* (i) os títulos das colunas (caso esteja sendo gerada a linha de cabeçalho da tabela) ou
* (ii) os valores de uma linha da tabela (caso esteja sendo gerado uma linha de conteúdo da tabela).
* Neste último caso, tal parâmetro deve conter os valores dos atributos de um objeto da lista de produtos.
* @return uma String representando a linha gerada com os valores
*/
protected String gerarColunasLinha(Produto produto) {
StringBuilder sb = new StringBuilder();
sb.append(abrirLinha());
for (Coluna coluna : getColunas()) {
sb.append(coluna.exportarDados(produto));
}
sb.append(fecharLinha());
sb.append("\n");
return sb.toString();
}
/**
* @return the colunas
*/
protected List<Coluna> getColunas() {
return colunas;
}
}
| 33.228261 | 126 | 0.643114 |
9e3157f15ba2990d331d4dc4cc5a3d6221586e5b | 458 | package lightsearch.server.initialization;
import org.springframework.stereotype.Service;
@Service("serverInitializer")
public class ServerInitializerImpl implements ServerInitializer {
private final BlacklistCreator blacklistCreator;
public ServerInitializerImpl(BlacklistCreator blacklistCreator) {
this.blacklistCreator = blacklistCreator;
}
@Override
public void initialize() {
blacklistCreator.create();
}
}
| 24.105263 | 69 | 0.766376 |
b07da2f2d7634a6c118664023480065eb091ebcb | 1,071 | package roundone.helper;
import roundone.helper.graph.Graph;
import roundone.helper.graph.Vertex;
import java.util.*;
public class TopologicalSort<T> {
private final Graph<T> graph;
private Stack<Vertex<T>> stack;
private Set<Vertex<T>> visited;
public TopologicalSort(Graph<T> graph) {
this.graph = graph;
this.stack = new Stack<>();
this.visited = new HashSet<>();
}
public List<Vertex<T>> sort() {
for (Vertex<T> tVertex : graph.getAllVertex()) {
if (!visited.contains(tVertex)) {
sortUtil(tVertex);
}
}
List<Vertex<T>> sortedElement = new ArrayList<>();
while (!stack.empty()) {
sortedElement.add(stack.pop());
}
return sortedElement;
}
private void sortUtil(Vertex<T> vertex) {
visited.add(vertex);
for (Vertex<T> vrtx : vertex.getAdjacentVertex()) {
if (!visited.contains(vrtx)) {
sortUtil(vrtx);
}
}
stack.add(vertex);
}
}
| 23.8 | 59 | 0.558357 |
4dcc5c21cfa9b816cf11a5ac3bc8b925be834eff | 1,765 | package com.mcml.space.patches;
import com.mcml.space.config.Patches;
import com.mcml.space.core.DataManager;
import com.mcml.space.core.EscapeLag;
import com.mcml.space.util.AzureAPI;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class AntiCrashOP implements Listener {
public static List<String> TheOps = new ArrayList();
public static void init() {
if (Patches.AntiCrashOPenable) {
AzureAPI.log("子模块 - 反崩溃OP 已启动");
if (!DataManager.data.isList("OpList")) {
Iterator var0 = Bukkit.getOperators().iterator();
while (var0.hasNext()) {
OfflinePlayer offplayer = (OfflinePlayer) var0.next();
TheOps.add(offplayer.getName());
}
AzureAPI.log("第一次运行模块,正在导入现有OP: " + TheOps);
save();
DataManager.save();
}
TheOps = DataManager.data.getStringList("OpList");
Bukkit.getPluginManager().registerEvents(new AntiCrashOP(), EscapeLag.plugin);
}
}
public static void save() {
DataManager.data.set("OpList", TheOps);
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
if (Bukkit.getOperators().contains(player) && !TheOps.contains(player.getName())) {
player.setOp(false);
AzureAPI.log(player, Patches.AntiCrashOPWarnMessage);
}
}
}
| 30.431034 | 91 | 0.639093 |
929a24b4627cc14a954307b9ec0a98eb34316983 | 7,319 | package cellsociety.simulation;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import javafx.util.Pair;
/**
* Purpose: This class is used to make and manage grid for the WaTorWorld/Predation+Play simulation.
* Assumptions:
* Dependencies: Grid and Cell
* Use it in the same way as described in the general grid class except with a extra parameters for
* how long it takes fish to breed, sharks to breed, and sharks to die.
*
*/
public class WatorGrid extends Grid {
public static final int SHARK = 2;
public static final int FISH = 1;
public static final int EMPTY = 0;
public static final int ENERGY_FROM_FISH = 3;
private int fishTimeToBreed;
private int sharkTimeToBreed;
private int sharkDeathTime;
private Set<Integer> myFish = new HashSet();
private Set<Integer> mySharks= new HashSet();
private Set<Integer> emptyCells = new HashSet<>();
private Set<Integer> fishToRemove = new HashSet<>();
private Set<Integer> myFishToAdd = new HashSet<>();
private List<Point> neighborLocs;
/**
*
* @param cols
* @param rows
* @param sharkBreed time it takes for a shark to breed (produce a new shark)
* @param fishBreed time it takes for a fish to breed (produce a new fish)
* @param sharkDie amount of time it takes for a shark to die, food increases this by decreasing the
* time since the shark last ate.
* @param neighbors
* @param edges
*/
public WatorGrid(int cols, int rows, int sharkBreed, int fishBreed, int sharkDie, List<Point> neighbors, edgeType edges) {
super(cols, rows, neighbors, edges);
fishTimeToBreed = fishBreed;
sharkDeathTime = sharkDie;
sharkTimeToBreed = sharkBreed;
neighborLocs = neighbors;
}
@Override
public void updateCells(List<Cell> updateList) {
for (Cell cell : updateList) {
if (cell.getType() == SHARK) {
mySharks.add(cell.getX()*numColumns+ cell.getY());
}
else if (cell.getType() == FISH){
myFish.add(cell.getX() * numColumns + cell.getY());
}
}
for (Pair pair:findEmptyCells()){
emptyCells.add(calcLocation((int)pair.getKey(),(int)pair.getValue()));
emptyCells.removeAll(myFish);
emptyCells.removeAll(mySharks);
}
super.updateCells(updateList);
}
@Override
public List<Cell> checkForUpdates() {
ArrayList<Cell> updateList = new ArrayList<>();
updateList.addAll(updateSharks());
updateList.addAll(updateFish());
myFish.removeAll(fishToRemove);
myFish.addAll(myFishToAdd);
fishToRemove.clear();
myFishToAdd.clear();
return updateList;
}
private Collection<Cell> updateFish() {
ArrayList<Cell> updateList = new ArrayList<>();
for(Integer location: myFish){
int x = location/numColumns ;
int y = location % numColumns;
Cell curCell = myCellGrid[x][y];
List<Pair> emptySpots;
emptySpots = checkForNeighbors(x,y,emptyCells);
if (emptySpots.isEmpty()){
continue;
}
updateList.add(moveFish(emptySpots, x,y,curCell,updateList));
curCell.increaseAge();
}
return updateList;
}
private Cell moveFish(List<Pair> emptySpots, int x, int y, Cell curCell, List updateList) {
int randIndex = (int) (Math.random()*emptySpots.size());
Pair newCoordinates = emptySpots.get(randIndex);
int newx =(int) newCoordinates.getKey();
int newy = (int) newCoordinates.getValue();
curCell.setX(newx);
curCell.setY(newy);
myFishToAdd.add(calcLocation(newx,newy));
if (curCell.getAge() > fishTimeToBreed){
curCell.resetAge();
updateList.add(new Cell(FISH,x,y));
emptyCells.remove(calcLocation(x,y));
}
else{
updateList.add(new Cell(EMPTY,x,y));
fishToRemove.add(calcLocation(x,y));
emptyCells.add(calcLocation(x,y));
}
return curCell;
}
private Collection<Cell> updateSharks() {
ArrayList<Cell> updateList = new ArrayList<>();
List<Pair> fish;
List<Pair> emptySpots;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numColumns; j++) {
Cell curCell = myCellGrid[i][j];
if (curCell.getType() == SHARK){
if (curCell.getTimeSinceEat() > sharkDeathTime){
updateList.add(new Cell(EMPTY,i,j));
emptyCells.add(calcLocation(i,j));
mySharks.remove(curCell);
continue;
}
fish = checkForNeighbors(i,j,myFish);
if (fish.isEmpty()){
emptySpots = checkForNeighbors(i,j,emptyCells);
if (!emptySpots.isEmpty()){
updateList.add(moveShark(emptySpots,i,j,curCell,false));
addNewSharkOrEmpty(updateList, i, j, curCell);
}
else{
curCell.increaseAge();
curCell.setTimeSinceEat(1);
}
}
else {
updateList.add(moveShark(fish, i, j, curCell, true));
addNewSharkOrEmpty(updateList, i, j, curCell);
}
}
}
}
return updateList;
}
private Integer calcLocation(int i, int j) {
return i * numColumns + j;
}
private void addNewSharkOrEmpty(ArrayList<Cell> updateList, int i, int j, Cell curCell) {
if (curCell.getAge() > sharkTimeToBreed) {
updateList.add(new Cell(SHARK, i, j));
mySharks.add(i*numColumns + j);
emptyCells.remove(calcLocation(i,j));
curCell.resetAge();
} else {
updateList.add(new Cell(EMPTY, i, j));
emptyCells.add(calcLocation(i,j));
}
}
private Cell moveShark(List<Pair> placesToMove, int i, int j, Cell curCell, boolean killFish) {
int randIndex = (int) (Math.random()*placesToMove.size());
Pair newCoordinates = placesToMove.get(randIndex);
int newx =(int) newCoordinates.getKey();
int newy = (int) newCoordinates.getValue();
if(killFish) {
myFish.remove(newx * numColumns + newy);
curCell.setTimeSinceEat(-ENERGY_FROM_FISH);
}
else {
emptyCells.remove(newx * numColumns + newy);
curCell.setTimeSinceEat(1);
}
mySharks.remove(i*numColumns + j);
mySharks.add(newx*numColumns + newy);
curCell.setX(newx);
curCell.setY(newy);
curCell.increaseAge();
return curCell;
}
private List<Pair> checkForNeighbors(int i, int j, Set lookingFor) {
List<Pair> neighbors = new ArrayList<>();
Integer sharkCoordinate = calcLocation(i,j);
Queue<Integer> neighborsToCheck = findNeighbors(sharkCoordinate);
while (neighborsToCheck.peek() != null) {
Integer currentCell = neighborsToCheck.remove();
if (lookingFor.contains(currentCell)) {
neighbors.add(new Pair(currentCell / numColumns, currentCell % numColumns));
}
}
return neighbors;
}
protected Queue<Integer> findNeighbors(int location) {
LinkedList<Integer> neighbors = new LinkedList<>();
for (Point p : neighborLocs) {
Integer validNeighbor = legalNeighbor(location/numColumns + p.x,location%numColumns + p.y);
if(validNeighbor != null) {
neighbors.add(validNeighbor);
}
}
return neighbors;
}
}
| 31.960699 | 124 | 0.643804 |
7a51fed45bb8975ef1cf3497cebc72d9fd222b59 | 701 | package com.prefecture.gestionlocale.model.dao;
import com.prefecture.gestionlocale.bean.Rue;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RueDao extends JpaRepository<Rue, Long> {
Page<Rue> findByNomContainingOrQuartierNomContaining(String nom, String quartier, Pageable pageable);
Long countByNomAndQuartierId(String nom, Long quartierId);
Long countByNomAndIdNotAndQuartierId(String nom, Long id, Long quartierId);
List<Rue> findByQuartierIdOrderByNom(Long id);
}
| 35.05 | 105 | 0.820257 |
bac876c0e1a77fca82a4f0b966635e5b255dcb9f | 16,956 | package org.mockserver.socket;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.asn1.*;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.*;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.bc.BcX509ExtensionUtils;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.util.IPAddress;
import org.mockserver.configuration.ConfigurationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
/**
* @author jamesdbloom, ganskef
*/
public class KeyStoreFactory {
private static final Logger logger = LoggerFactory.getLogger(SSLFactory.class);
private static final String PROVIDER_NAME = BouncyCastleProvider.PROVIDER_NAME;
static {
Security.addProvider(new BouncyCastleProvider());
}
private static final String SIGNATURE_ALGORITHM = "SHA256WithRSAEncryption";
private static final String KEY_GENERATION_ALGORITHM = "RSA";
private static final boolean REGENERATE_FRESH_CA_CERTIFICATE = false;
/**
* Generates an 2048 bit RSA key pair using SHA1PRNG for the Certificate Authority.
*/
private static final int ROOT_KEYSIZE = 2048;
/**
* Generates an 1024 bit RSA key pair using SHA1PRNG for the server
* certificates. Thoughts: 2048 takes much longer time on older CPUs. And
* for almost every client, 1024 is sufficient.
*/
private static final int FAKE_KEYSIZE = 1024;
/**
* Current time minus 1 year, just in case software clock goes back due to
* time synchronization
*/
private static final Date NOT_BEFORE = new Date(System.currentTimeMillis() - 86400000L * 365);
/**
* The maximum possible value in X.509 specification: 9999-12-31 23:59:59,
* new Date(253402300799000L), but Apple iOS 8 fails with a certificate
* expiration date grater than Mon, 24 Jan 6084 02:07:59 GMT (issue #6).
*
* Hundred years in the future from starting the proxy should be enough.
*/
private static final Date NOT_AFTER = new Date(System.currentTimeMillis() + 86400000L * 365 * 100);
/**
* Create a random 2048 bit RSA key pair with the given length
*/
public static KeyPair generateKeyPair(int keySize) throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_GENERATION_ALGORITHM, PROVIDER_NAME);
generator.initialize(keySize, new SecureRandom());
return generator.generateKeyPair();
}
private static SubjectKeyIdentifier createSubjectKeyIdentifier(Key key) throws IOException {
ASN1InputStream is = null;
try {
is = new ASN1InputStream(new ByteArrayInputStream(key.getEncoded()));
ASN1Sequence seq = (ASN1Sequence) is.readObject();
SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(seq);
return new BcX509ExtensionUtils().createSubjectKeyIdentifier(info);
} finally {
IOUtils.closeQuietly(is);
}
}
private static X509Certificate signCertificate(X509v3CertificateBuilder certificateBuilder, PrivateKey signedWithPrivateKey) throws OperatorCreationException, CertificateException {
ContentSigner signer = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER_NAME).build(signedWithPrivateKey);
return new JcaX509CertificateConverter().setProvider(PROVIDER_NAME).getCertificate(certificateBuilder.build(signer));
}
/**
* Create a certificate to use by a Certificate Authority, signed by a self signed certificate.
*/
public X509Certificate createCACert(PublicKey publicKey, PrivateKey privateKey) throws Exception {
//
// signers name
//
X500Name issuerName = new X500Name("CN=www.mockserver.com, O=MockServer, L=London, ST=England, C=UK");
//
// subjects name - the same as we are self signed.
//
X500Name subjectName = issuerName;
//
// serial
//
BigInteger serial = BigInteger.valueOf(new Random().nextInt(Integer.MAX_VALUE));
//
// create the certificate - version 3
//
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, NOT_BEFORE, NOT_AFTER, subjectName, publicKey);
builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
builder.addExtension(Extension.keyUsage, false, usage);
ASN1EncodableVector purposes = new ASN1EncodableVector();
purposes.add(KeyPurposeId.id_kp_serverAuth);
purposes.add(KeyPurposeId.id_kp_clientAuth);
purposes.add(KeyPurposeId.anyExtendedKeyUsage);
builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));
X509Certificate cert = signCertificate(builder, privateKey);
cert.checkValidity(new Date());
cert.verify(publicKey);
return cert;
}
/**
* Create a server certificate for the given domain and subject alternative names, signed by the given Certificate Authority.
*/
public X509Certificate createClientCert(PublicKey publicKey, X509Certificate certificateAuthorityCert, PrivateKey certificateAuthorityPrivateKey, PublicKey certificateAuthorityPublicKey, String domain, String[] subjectAlternativeNameDomains, String[] subjectAlternativeNameIps) throws Exception {
//
// signers name
//
X500Name issuer = new X509CertificateHolder(certificateAuthorityCert.getEncoded()).getSubject();
//
// subjects name - the same as we are self signed.
//
X500Name subject = new X500Name("CN=" + domain + ", O=MockServer, L=London, ST=England, C=UK");
//
// serial
//
BigInteger serial = BigInteger.valueOf(new Random().nextInt(Integer.MAX_VALUE));
//
// create the certificate - version 3
//
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER, subject, publicKey);
builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
//
// subject alternative name
//
List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
if (subjectAlternativeNameDomains != null) {
subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, domain));
for (String subjectAlternativeNameDomain : subjectAlternativeNameDomains) {
subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, subjectAlternativeNameDomain));
}
}
if (subjectAlternativeNameIps != null) {
for (String subjectAlternativeNameIp : subjectAlternativeNameIps) {
if (IPAddress.isValidIPv6WithNetmask(subjectAlternativeNameIp)
|| IPAddress.isValidIPv6(subjectAlternativeNameIp)
|| IPAddress.isValidIPv4WithNetmask(subjectAlternativeNameIp)
|| IPAddress.isValidIPv4(subjectAlternativeNameIp)) {
subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, subjectAlternativeNameIp));
}
}
}
if (subjectAlternativeNames.size() > 0) {
DERSequence subjectAlternativeNamesExtension = new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[subjectAlternativeNames.size()]));
builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNamesExtension);
}
X509Certificate cert = signCertificate(builder, certificateAuthorityPrivateKey);
cert.checkValidity(new Date());
cert.verify(certificateAuthorityPublicKey);
return cert;
}
/**
* Create a KeyStore with a server certificate for the given domain and subject alternative names.
*/
KeyStore generateCertificate(KeyStore keyStore, String certificationAlias, String certificateAuthorityAlias, char[] keyStorePassword, String domain, String[] subjectAlternativeNameDomains, String[] subjectAlternativeNameIps) throws Exception {
//
// personal keys
//
KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE);
PrivateKey clientPrivateKey = keyPair.getPrivate();
PublicKey clientPublicKey = keyPair.getPublic();
//
// ca keys
//
PrivateKey caPrivateKey = loadPrivateKeyFromPEMFile("org/mockserver/socket/CertificateAuthorityPrivateKey.pem");
X509Certificate caCert = (X509Certificate) loadCertificateFromKeyStore("org/mockserver/socket/CertificateAuthorityKeyStore.jks", certificateAuthorityAlias, keyStorePassword);
//
// regenerate ca private key and ca certificate (for development / debugging only)
//
if (REGENERATE_FRESH_CA_CERTIFICATE) {
KeyPair caKeyPair = generateKeyPair(ROOT_KEYSIZE);
PublicKey caPublicKey = caKeyPair.getPublic();
caPrivateKey = caKeyPair.getPrivate();
caCert = createCACert(caPublicKey, caPrivateKey);
KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
caKeyStore.load(readFileFromClassPathOrPath("org/mockserver/socket/CertificateAuthorityKeyStore.jks"), ConfigurationProperties.javaKeyStorePassword().toCharArray());
saveCertificateAsKeyStore(
caKeyStore,
false,
"CertificateAuthorityKeyStore.jks",
certificateAuthorityAlias,
clientPrivateKey,
keyStorePassword,
new X509Certificate[]{caCert},
caCert
);
saveCertificateAsPEMFile(caCert, "CertificateAuthorityCertificate.pem", false);
saveCertificateAsPEMFile(caPublicKey, "CertificateAuthorityPublicKey.pem", false);
saveCertificateAsPEMFile(caPrivateKey, "CertificateAuthorityPrivateKey.pem", false);
}
//
// generate client certificate
//
X509Certificate clientCert = createClientCert(clientPublicKey, caCert, caPrivateKey, caCert.getPublicKey(), domain, subjectAlternativeNameDomains, subjectAlternativeNameIps);
saveCertificateAsPEMFile(clientCert, "ClientCertificate.pem", true);
saveCertificateAsPEMFile(clientPublicKey, "ClientPublicKey.pem", true);
saveCertificateAsPEMFile(clientPrivateKey, "ClientPrivateKey.pem", true);
return saveCertificateAsKeyStore(
keyStore,
ConfigurationProperties.deleteGeneratedKeyStoreOnExit(),
ConfigurationProperties.javaKeyStoreFilePath(),
certificationAlias,
clientPrivateKey,
keyStorePassword,
new X509Certificate[]{clientCert, caCert},
caCert
);
}
/**
* Saves X509Certificate as Base-64 encoded PEM file.
*/
public void saveCertificateAsPEMFile(Object x509Certificate, String filename, boolean deleteOnExit) throws IOException {
File pemFile = new File(filename);
FileWriter pemfileWriter = new FileWriter(pemFile);
JcaPEMWriter jcaPEMWriter = null;
try {
jcaPEMWriter = new JcaPEMWriter(pemfileWriter);
jcaPEMWriter.writeObject(x509Certificate);
} finally {
IOUtils.closeQuietly(jcaPEMWriter);
IOUtils.closeQuietly(pemfileWriter);
}
if (deleteOnExit) {
pemFile.deleteOnExit();
}
}
/**
* Save X509Certificate in KeyStore file.
*/
private KeyStore saveCertificateAsKeyStore(KeyStore existingKeyStore, boolean deleteOnExit, String keyStoreFileName, String certificationAlias, Key privateKey, char[] keyStorePassword, Certificate[] chain, X509Certificate caCert) {
try {
KeyStore keyStore = existingKeyStore;
if (keyStore == null) {
// create new key store
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, keyStorePassword);
}
// add certificate
try {
keyStore.deleteEntry(certificationAlias);
} catch (KeyStoreException kse) {
// ignore as may not exist in keystore yet
}
keyStore.setKeyEntry(certificationAlias, privateKey, keyStorePassword, chain);
// add CA certificate
try {
keyStore.deleteEntry(SSLFactory.KEY_STORE_CA_ALIAS);
} catch (KeyStoreException kse) {
// ignore as may not exist in keystore yet
}
keyStore.setCertificateEntry(SSLFactory.KEY_STORE_CA_ALIAS, caCert);
// save as JKS file
File keyStoreFile = new File(keyStoreFileName);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(keyStoreFile);
keyStore.store(fileOutputStream, keyStorePassword);
logger.trace("Saving key store to file [" + keyStoreFileName + "]");
} finally {
IOUtils.closeQuietly(fileOutputStream);
}
if (deleteOnExit) {
keyStoreFile.deleteOnExit();
}
return keyStore;
} catch (Exception e) {
throw new RuntimeException("Exception while saving KeyStore", e);
}
}
/**
* Load PrivateKey from PEM file.
*/
private RSAPrivateKey loadPrivateKeyFromPEMFile(String privateKeyFileName) {
try {
String publicKeyFile = IOUtils.toString(new InputStreamReader(KeyStoreFactory.class.getClassLoader().getResourceAsStream(privateKeyFileName)));
byte[] publicKeyBytes = DatatypeConverter.parseBase64Binary(publicKeyFile.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", ""));
return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(publicKeyBytes));
} catch (Exception e) {
throw new RuntimeException("Exception reading private key from PEM file", e);
}
}
/**
* Load X509Certificate from KeyStore file.
*/
private Certificate loadCertificateFromKeyStore(String keyStoreFileName, String certificationAlias, char[] keyStorePassword) {
try {
InputStream inputStream = readFileFromClassPathOrPath(keyStoreFileName);
try {
logger.trace("Loading key store from file [" + keyStoreFileName + "]");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(inputStream, keyStorePassword);
return keystore.getCertificate(certificationAlias);
} finally {
IOUtils.closeQuietly(inputStream);
}
} catch (Exception e) {
throw new RuntimeException("Exception while loading KeyStore from " + keyStoreFileName, e);
}
}
/**
* Load file from classpath and if not found then try file path
*/
private InputStream readFileFromClassPathOrPath(String keyStoreFileName) throws FileNotFoundException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(keyStoreFileName);
if (inputStream == null) {
// load from path if not found in classpath
inputStream = new FileInputStream(keyStoreFileName);
}
return inputStream;
}
}
| 43.813953 | 300 | 0.681883 |
02463087f8121b8d8a824509b5d700f0eaa089a7 | 461 | package com.levelup.java.junit;
import static org.junit.Assert.assertFalse;
import org.junit.Ignore;
import org.junit.Test;
/**
* This java example will demonstrate ignoring
* a test with junit.
*
* @author Justin Musgrove
* @see <a href='http://www.leveluplunch.com/java/examples/junit-ignore-test/'>Ignore Test</a>
*
*/
public class IgnoreTest {
@Ignore("Ignore this test")
@Test
public void ignore_test_junit () {
assertFalse(true);
}
}
| 18.44 | 94 | 0.711497 |
5ceb301aeca344cde8cc7c10a25b33fa0a71a032 | 1,435 | package org.jboss.resteasy.util;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.spi.StringConverter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.RuntimeDelegate;
import java.util.Set;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class HeaderHelper
{
public static void setAllow(MultivaluedMap headers, String[] methods)
{
if (methods == null)
{
headers.remove("Allow");
return;
}
StringBuilder builder = new StringBuilder();
boolean isFirst = true;
for (String l : methods)
{
if (isFirst)
{
isFirst = false;
}
else
{
builder.append(", ");
}
builder.append(l);
}
headers.putSingle("Allow", builder.toString());
}
public static void setAllow(MultivaluedMap headers, Set<String> methods)
{
if (methods == null)
{
headers.remove("Allow");
return;
}
StringBuilder builder = new StringBuilder();
boolean isFirst = true;
for (String l : methods)
{
if (isFirst)
{
isFirst = false;
}
else
{
builder.append(", ");
}
builder.append(l);
}
headers.putSingle("Allow", builder.toString());
}
}
| 22.076923 | 75 | 0.55331 |
2d39f1b46f6a24f24abe792f2d7541e7d219804d | 1,510 | package com.jakubpetriska.gameengine.api;
import com.jakubpetriska.gameengine.api.components.Camera;
import com.jakubpetriska.gameengine.api.math.Matrix44;
/**
* Provides rendering functionality.
*/
public interface Renderer {
/**
* Gets called by the engine before the rendering of a frame starts (calls to render(Model)).
* <p/>
* This ensures that all updates to game objects are applied for given frame.
*/
void onStartRenderingFrame();
/**
* Renders model.
*
* @param mesh Mesh to render.
* @param transformation Transformation of the rendered object.
*/
void render(MeshData mesh, Color color, Matrix44 transformation);
/**
* Renders wireframe of the given mesh. Use
*
* @param mesh Mesh to render.
* @param color Color of the rendered wireframe.
* @param transformation Transformation of the rendered object.
*/
void renderWireframe(MeshData mesh, Color color, Matrix44 transformation);
/**
* Creates instance of MeshData with supplied data.
* Implementation can return a subclass of MeshData to which it can store it's specific
* data to use during rendering.
* <p/>
* Input parameters are similar to {@link MeshData}'s fields.
*/
MeshData createMeshData(
float[] vertices, float[] normals,
int[] trianglesVertices, int[] trianglesNormals);
void setCamera(Camera camera);
Camera getCamera();
}
| 30.2 | 97 | 0.660927 |
ba477017e66fb930f5fc7de7edf689cdf3d56fab | 986 | package javacore.Xnio.test;
import java.nio.file.Path;
import java.nio.file.Paths;
public class RelativizarTest {
public static void main(String[] args) {
Path dir = Paths.get("/home/caio");
Path classe = Paths.get("/home/caio/java/Pessoa.java");
Path pathToClasse = dir.relativize(classe);
System.out.println(pathToClasse);
Path absoluto1 = Paths.get("/home/caio");
Path absoluto2 = Paths.get("/usr/local");
Path absoluto3 = Paths.get("/home/caio/java/Pessoa.java");
Path relativo1 = Paths.get("temp");
Path relativo2 = Paths.get("temp/Funcionario.java");
System.out.println("1: " +absoluto1.relativize(absoluto3));
System.out.println("2: " +absoluto3.relativize(absoluto1));
System.out.println("3: " +absoluto1.relativize(absoluto2));
System.out.println("4: " +relativo1.relativize(relativo2));
System.out.println("5: " +absoluto1.relativize(relativo1));
}
}
| 36.518519 | 67 | 0.648073 |
16e9d5dd07a03e301a36ad92fffb15e5434226de | 1,393 | package net.elmosoft.splendid.browser;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
* @author Aleksei_Mordas
*
*/
public class FirefoxFactory extends BrowserFactory {
private static final Logger LOGGER = LogManager.getLogger(FirefoxFactory.class);
@Override
public WebDriver createBrowser(boolean acceptUntrustedCerts,
boolean assumeUntrustedIssuer) {
FirefoxProfile profile = new FirefoxProfile();
LOGGER.info("Firefox profile was created");
profile.setAcceptUntrustedCertificates(acceptUntrustedCerts);
profile.setAssumeUntrustedCertificateIssuer(assumeUntrustedIssuer);
new DesiredCapabilities();
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(FirefoxDriver.PROFILE, profile);
capabilities.setCapability("fake", "true");
capabilities.setCapability("media.navigator.permission.disabled", "true");
LOGGER.info("Firefox profile was set as capability");
WebDriverManager.firefoxdriver().setup();
return new FirefoxDriver(capabilities);
}
@Override
public WebDriver createBrowser() {
return new FirefoxDriver();
}
}
| 32.395349 | 81 | 0.806174 |
cd14a8741f41ac6aa78fadd298ca0fa98129049e | 3,041 | package com.anvil.adsama.nsaw.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AlphaVantage implements Parcelable {
public static final Parcelable.Creator<AlphaVantage> CREATOR = new Creator<AlphaVantage>() {
@Override
public AlphaVantage createFromParcel(Parcel source) {
AlphaVantage alphaVantage = new AlphaVantage();
alphaVantage.mCompanyName = ((String) source.readValue((String.class.getClassLoader())));
alphaVantage.mLastRefreshTime = ((String) source.readValue((String.class.getClassLoader())));
alphaVantage.mOpen = ((float) source.readValue((float.class.getClassLoader())));
alphaVantage.mHigh = ((float) source.readValue((float.class.getClassLoader())));
alphaVantage.mLow = ((float) source.readValue((float.class.getClassLoader())));
alphaVantage.mClose = ((float) source.readValue((float.class.getClassLoader())));
alphaVantage.mVolume = ((float) source.readValue((float.class.getClassLoader())));
return alphaVantage;
}
@Override
public AlphaVantage[] newArray(int size) {
return new AlphaVantage[size];
}
};
@SerializedName("2. Symbol")
@Expose
private String mCompanyName;
@SerializedName("3. Last Refreshed")
@Expose
private String mLastRefreshTime;
@SerializedName("1. open")
@Expose
private float mOpen;
@SerializedName("2. high")
@Expose
private float mHigh;
@SerializedName("2. low")
@Expose
private float mLow;
@SerializedName("2. close")
@Expose
private float mClose;
@SerializedName("5. volume")
@Expose
private float mVolume;
private AlphaVantage() {
}
public AlphaVantage(String companyName, String refreshTime, float open, float high, float low, float close, float volume) {
mCompanyName = companyName;
mLastRefreshTime = refreshTime;
mOpen = open;
mHigh = high;
mLow = low;
mClose = close;
mVolume = volume;
}
public String getCompanyName() {
return mCompanyName;
}
public String getRefreshTime() {
return mLastRefreshTime;
}
public float getOpen() {
return mOpen;
}
public float getHigh() {
return mHigh;
}
public float getLow() {
return mLow;
}
public float getClose() {
return mClose;
}
public float getVolume() {
return mVolume;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(mCompanyName);
dest.writeValue(mLastRefreshTime);
dest.writeValue(mOpen);
dest.writeValue(mHigh);
dest.writeValue(mLow);
dest.writeValue(mClose);
dest.writeValue(mVolume);
}
} | 27.899083 | 127 | 0.634988 |
28ddafd877021e55db1d151a60799581d727ed80 | 4,796 | package com.cy.core.role.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.cy.core.resource.dao.ResourceMapper;
import com.cy.core.resource.entity.Resource;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cy.base.entity.DataGrid;
import com.cy.core.role.dao.RoleMapper;
import com.cy.core.role.entity.Role;
import com.cy.core.user.entity.UserRole;
import com.cy.system.GetDictionaryInfo;
@Service("roleService")
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Autowired
private ResourceMapper resourceMapper;
public DataGrid<Role> dataGrid(Map<String, Object> map) {
DataGrid<Role> dataGrid = new DataGrid<Role>();
long total = roleMapper.countRole(map);
dataGrid.setTotal(total);
int start = ((Integer) map.get("page") - 1) * (Integer) map.get("rows");
map.put("start", start);
List<Role> list = roleMapper.selectRole(map);
dataGrid.setRows(list);
return dataGrid;
}
public Role getById(long roleId) {
return roleMapper.getById(roleId);
}
public void save(Role role) {
role.setSystemAdmin(0);
roleMapper.add(role);
}
public void update(Role role) {
roleMapper.update(role);
}
public void delete(long id) {
try {
roleMapper.deleteRoleAndResource(id);
roleMapper.delete(id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Role selectResource(long roleId) {
return roleMapper.selectResource(roleId);
}
/**
* 创建人:Kent
* 创建时间:2016-07-26
* 描述:授权菜单和功能
* @param ids 授权菜单IDs
* @param actionIds 授权功能IDs
* @param id 角色ID
*/
public void updateGrant(String ids, String actionIds, long id) {
try {
roleMapper.deleteRoleAndResource(id);
if(!StringUtils.isBlank(ids)) {
List<Resource> menus = resourceMapper.selectMenuByIds(ids);
if(!StringUtils.isBlank(actionIds)){
List<Resource> actions = resourceMapper.selectActionByIds(actionIds);
menus.addAll(actions);
}
List<Map<String,Long>> roleResources = Lists.newArrayList();
for(Resource r : menus){
Map<String,Long> map = Maps.newHashMap();
map.put("roleId",id);
map.put("id",r.getId());
roleResources.add(map);
}
if(roleResources.size()>0) {
roleMapper.insertRoleAndResource1(roleResources);
}
}else if(!StringUtils.isBlank(actionIds)){
List<Resource> actions = resourceMapper.selectActionByIds(actionIds);
List<Map<String,Long>> roleResources = Lists.newArrayList();
for(Resource r : actions){
Map<String,Long> map = Maps.newHashMap();
map.put("roleId",id);
map.put("id",r.getId());
roleResources.add(map);
}
if(roleResources.size()>0) {
roleMapper.insertRoleAndResource1(roleResources);
}
}
/*String[] idAttr = ids.split(",");
for (String idStr : idAttr) {
if (idStr != null && !"".equals(idStr)) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("roleId", id);
map.put("id", Long.parseLong(idStr));
roleMapper.insertRoleAndResource(map);
}
}
// 刷新内存
GetDictionaryInfo.getInstance().reloadDictionaryInfoMap();*/
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public List<Role> selectAll() {
return roleMapper.selectAll();
}
public List<Role> getMenu(long roleId) {
return roleMapper.getMenu(roleId);
}
@Override
public List<Role> selectAllNoAdmin() {
return roleMapper.selectAllNoAdmin();
}
@Override
public List<Role> selectxAllNoAdmin() {
return roleMapper.selectxAllNoAdmin();
}
public List<Role> getMenuByUserRole(List<UserRole> userRoles) {
return roleMapper.getMenuByUserRole(userRoles);
}
@Override
public List<Role> getUserRoleByUserId(long userId) {
return roleMapper.getUserRoleByUserId(userId);
}
/**
* 创建人:Kent
* 创建时间:2016-07-25
* 描述:查询角色授权菜单
*
* @param roleId 角色ID
* @return 角色
*/
@Override
public Role selectMenu(long roleId) {
return roleMapper.selectMenu(roleId);
}
/**
* 创建人:Kent
* 创建时间:2016-07-25
* 描述:查询角色授权功能
*
* @param roleId
* @return 角色
*/
@Override
public Role selectAction(long roleId) {
return roleMapper.selectAction(roleId);
}
/**
* 创建人:kent
* 创建时间:2016-07-26
* 描述:通过功能查询该功能拥有的角色
*
* @param actionName
* @return
*/
@Override
public List<Role> getRolesByAction(String actionName) {
return roleMapper.selectRolesByAction(actionName);
}
/**
* 创建人:jiangling
* 创建时间:2016-08-03
* 描述:通过id查询删除标志位
* @param
* @return 删除标志位 Can_Del_Flag
*/
@Override
public int getDelFlag(long id) {
return roleMapper.getDelFlag(id);
}
}
| 23.742574 | 74 | 0.696622 |
cdcbc9cc582d53f53b24af9cd5f3840d7c225921 | 1,382 | package cn.yinjiahui.group_purchase.po;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("address")
public class Address
{
@TableId(type= IdType.AUTO)
private Integer id;
private String name;
private float x;
private float y;
private String address_detailed;
public Address(String name, float x, float y,String address_detailed)
{
this.name = name;
this.x = x;
this.y = y;
this.address_detailed=address_detailed;
}
public Address()
{
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public float getX()
{
return x;
}
public void setX(float x)
{
this.x = x;
}
public float getY()
{
return y;
}
public void setY(float y)
{
this.y = y;
}
public String getAddress_detailed()
{
return address_detailed;
}
public void setAddress_detailed(String address_detailed)
{
this.address_detailed = address_detailed;
}
}
| 16.452381 | 73 | 0.596961 |
ad9a4d9c1c29da704f4cd735accf5601bade35e8 | 7,923 | /*
* Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved.
*
* This software is open source.
* See the bottom of this file for the licence.
*
* $Id: Visdom.java,v 1.1.1.1 2001/05/22 08:12:37 jstrachan Exp $
*/
/*
* Dom4jGUI.java
*
* Created on 11. april 2001, 22:02
*/
package org.dom4j.visdom;
import org.dom4j.swing.TreeModelBuilder;
import org.dom4j.examples.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.net.*;
/**
*
* @author Pipo
* @version
*/
public class Visdom extends JFrame {
/** Creates new Dom4jGUI */
public Visdom() {
initComponents();
}
private void exitForm(java.awt.event.WindowEvent p_evt){
Action l_exit = Actions.get(Actions.EXIT);
l_exit.actionPerformed(null);
}
private void addWindowCloseListener(){
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
}
);
}
private TreeModel createTreeModelFromDocument(){
return TreeModelBuilder.build(
ExampleDocumentBuilder.buildDocument());
}
private TreeModel createTreeModelFromFile(){
return TreeModelBuilder.build((org.dom4j.Document) Components.get(Components.CONFIG_DOC));
}
private JTree createTree(){
//JTree l_tree = new JTree(createTreeModelFromDocument());
JTree l_tree = new JTree(createTreeModelFromFile());
l_tree.setEditable(true);
return l_tree;
}
private void setSplitPane(){
JSplitPane l_split = new JSplitPane();
l_split.setLeftComponent(new JScrollPane(createTree()));
l_split.setRightComponent(new JLabel("VisDOM v0.01a"));
getContentPane().add(l_split);
}
public void initComponents(){
addWindowCloseListener();
setJMenuBar(MenuBuilder.buildMenuBar());
setSplitPane();
setSize(800, 600);
}
//******************************
// STATIC INITIALZATION METHODS
//******************************
private static void init(String args[]) throws MalformedURLException{
setConfigFile(args[0]);
setConfigDoc();
openToolBarWindow();
openFileSystemWindow();
openDomTreeWindow();
openXPathWindow();
openEditorWindow();
createConfigWindow();
}
private static void setConfigFile(String p_file){
Components.put(Components.CONFIG_FILE, p_file);
Components.lockKey(Components.CONFIG_FILE);
}
private static void setConfigDoc() throws MalformedURLException{
Components.put(Components.CONFIG_DOC, ExampleDocumentBuilder.readDocument(
(String) Components.get(Components.CONFIG_FILE) ));
}
private static void openToolBarWindow(){
JFrame l_toolBarWindow = WindowBuilder.buildToolBarWindow();
l_toolBarWindow.pack();
l_toolBarWindow.setSize(1000, 75);
l_toolBarWindow.setLocation(0,0);
l_toolBarWindow.show();
Components.put(Components.TOOLBAR_WINDOW, l_toolBarWindow);
Components.lockKey(Components.TOOLBAR_WINDOW);
}
private static void openFileSystemWindow(){
JFrame l_fileSystemWindow = WindowBuilder.buildFileSystemWindow();
l_fileSystemWindow.pack();
l_fileSystemWindow.setSize(300, 600);
l_fileSystemWindow.setLocation(0, 75);
l_fileSystemWindow.show();
Components.put(Components.FILESYSTEM_WINDOW, l_fileSystemWindow);
Components.lockKey(Components.FILESYSTEM_WINDOW);
}
private static void openDomTreeWindow(){
JFrame l_domTreeWindow = WindowBuilder.buildDomTreeWindow();
l_domTreeWindow.pack();
l_domTreeWindow.setSize(300, 600);
l_domTreeWindow.setLocation(300, 75);
l_domTreeWindow.show();
Components.put(Components.DOMTREE_WINDOW, l_domTreeWindow);
Components.lockKey(Components.DOMTREE_WINDOW);
}
private static void openXPathWindow(){
JFrame l_xpathWindow = WindowBuilder.buildXPathWindow();
l_xpathWindow.pack();
l_xpathWindow.setSize(300, 200);
l_xpathWindow.setLocation(300, 675);
l_xpathWindow.show();
Components.put(Components.XPATH_WINDOW, l_xpathWindow);
Components.lockKey(Components.XPATH_WINDOW);
}
private static void openEditorWindow(){
JFrame l_editorWindow = WindowBuilder.buildEditorWindow();
l_editorWindow.pack();
l_editorWindow.setSize(400,600);
l_editorWindow.setLocation(600, 75);
l_editorWindow.show();
Components.put(Components.EDITOR_WINDOW, l_editorWindow);
Components.lockKey(Components.EDITOR_WINDOW);
}
private static void createConfigWindow(){
}
/**
* Starts the Dom4jGui. Takes a configuration file path as argument.
* @param args the command line arguments
*/
public static void main (String args[]) {
try{
if(args.length == 1){
init(args);
}
printWelcomeText();
//Dom4jGUI l_frame = new Dom4jGUI();
//l_frame.pack();
//l_frame.setSize(800,600);
//l_frame.show();
}catch(Exception e){
System.out.println("Error starting FreeDOM: " + e.toString());
}
}
private static void printWelcomeText(){
System.out.println("*****************");
System.out.println(" VisDOM 1.00a ");
System.out.println("*****************");
}
}
/*
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 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. The name "DOM4J" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of MetaStuff, Ltd. For written permission,
* please contact [email protected].
*
* 4. Products derived from this Software may not be called "DOM4J"
* nor may "DOM4J" appear in their names without prior written
* permission of MetaStuff, Ltd. DOM4J is a registered
* trademark of MetaStuff, Ltd.
*
* 5. Due credit should be given to the DOM4J Project
* (http://dom4j.org/).
*
* THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED 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
* METASTUFF, LTD. OR ITS 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.
*
* Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved.
*
* $Id: Visdom.java,v 1.1.1.1 2001/05/22 08:12:37 jstrachan Exp $
*/
| 32.875519 | 99 | 0.64256 |
90d4c3bbc5912f51143c5f928a5d9959f42acef0 | 618 | package com.dojogrouppty.account;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class UserAuthenticationIntegrationTest {
private static final Logger logger
= LoggerFactory.getLogger(UserAuthenticationIntegrationTest.class);
@Test
public void testSimple() {
String p = "XXX";
BCryptPasswordEncoder pe = new BCryptPasswordEncoder();
String encPassword = pe.encode(p);
logger.debug("HELLB ---->[" + encPassword+"]");
}
}
| 29.428571 | 80 | 0.690939 |
99f9a992e548cf3c9225850db1f529e6d55ab96b | 11,543 | /*
* $Id$
*/
/*
Copyright (c) 2000-2008 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.config;
import org.lockss.util.*;
import org.lockss.test.*;
import org.lockss.config.Tdb.TdbException;
import java.util.*;
/**
* Test class for <code>org.lockss.config.TdbPublisher</code>
*
* @author Philip Gust
* @version $Id$
*/
public class TestTdbPublisher extends LockssTestCase {
public void setUp() throws Exception {
super.setUp();
}
public void tearDown() throws Exception {
super.tearDown();
}
static Logger log = Logger.getLogger("TestTdbPublisher");
/**
* Test creating valid TdbPublisher.
*/
public void testValidPublisher() {
TdbPublisher publisher = null;
try {
publisher = new TdbPublisher("Test Publisher");
} catch (IllegalArgumentException ex) {
}
assertEquals("Test Publisher", publisher.getName());
}
/**
* Test creating TdbPublisher with null name.
*/
public void testNullPublisherName() {
TdbPublisher publisher = null;
try {
publisher = new TdbPublisher(null);
fail("TdbPublisher did not throw IllegalArgumentException for null constructor argument.");
} catch (IllegalArgumentException ex) {
}
assertNull(publisher);
}
/**
* Test equals() method for publisher.
* @throws TdbException for invalid Tdb operations
*/
public void testEquals() throws TdbException {
TdbPublisher publisher1 = new TdbPublisher("Test Publisher");
TdbTitle title1 = new TdbTitle("Test Title 1", "0000-0001");
publisher1.addTdbTitle(title1);
assertEquals(publisher1, publisher1);
// same as publisher1
TdbPublisher publisher2 = new TdbPublisher("Test Publisher");
TdbTitle title2 = new TdbTitle("Test Title 1", "0000-0002");
publisher2.addTdbTitle(title2);
assertEquals(publisher2, publisher2);
// differs from publisher1 by title name
TdbPublisher publisher3 = new TdbPublisher("Test Publisher");
TdbTitle title3 = new TdbTitle("Test Title 3", "0000-0003");
publisher3.addTdbTitle(title3);
assertNotEquals(publisher1, publisher3);
// differs from publisher3 by publisher name
TdbPublisher publisher4 = new TdbPublisher("Test Publisher 4");
TdbTitle title4 = new TdbTitle("Test Title 3", "0000-0004");
publisher4.addTdbTitle(title4);
assertNotEquals(publisher3, publisher4);
}
/**
* Test ISBNs and ISBNs
* @throws TdbException for invalid Tdb operations
*/
public void testIssns() throws TdbException {
TdbPublisher publisher = new TdbPublisher("Test Publisher");
TdbTitle title1 = new TdbTitle("Test Title 1", "TestTitle1");
publisher.addTdbTitle(title1);
TdbAu au1 = new TdbAu("Test AU 1", "pluginA");
title1.addTdbAu(au1);
au1.setPropertyByName("issn", "1234-5678");
au1.setPropertyByName("eissn", "2468-1357");
au1.setPropertyByName("issnl", "8765-4321");
au1.setAttr("isbn", "1234567890");
assertEquals(title1, publisher.getTdbTitleByIssn("1234-5678"));
assertEquals(title1, publisher.getTdbTitleByIssn("2468-1357"));
assertEquals(title1, publisher.getTdbTitleByIssn("8765-4321"));
assertSameElements(new TdbAu[] {au1},
publisher.getTdbAusByIsbn("1234567890"));
assertSameElements(new TdbTitle[] {title1},
publisher.getTdbTitlesByIssn("1234-5678"));
// add second title with same elements
TdbTitle title2 = new TdbTitle("Test Title 2", "TestTitle2");
publisher.addTdbTitle(title2);
TdbAu au2 = new TdbAu("Test AU 2", "pluginB");
title2.addTdbAu(au2);
au2.setPropertyByName("issn", "1234-5678");
au2.setPropertyByName("eissn", "2468-1357");
au2.setPropertyByName("issnl", "8765-4321");
au2.setAttr("isbn", "1234567890");
assertSameElements(new TdbAu[] {au1, au2},
publisher.getTdbAusByIsbn("1234567890"));
assertSameElements(new TdbTitle[] {title1, title2},
publisher.getTdbTitlesByIssn("1234-5678"));
}
/**
* Test addTitle() method.
* @throws TdbException for invalid Tdb operations
*/
public void testAddTitle() throws TdbException {
TdbPublisher publisher = new TdbPublisher("Test Publisher");
Collection<TdbTitle> titles = publisher.getTdbTitles();
assertEmpty(titles);
// add title
TdbTitle title = new TdbTitle("Test Title 1", "0000-0001");
publisher.addTdbTitle(title);
titles = publisher.getTdbTitles();
assertNotNull(titles);
assertEquals(1, titles.size());
// can't add null title
try {
publisher.addTdbTitle(null);
fail("TdbPublisher did not throw IllegalArgumentException adding null title.");
} catch (IllegalArgumentException ex) {
}
titles = publisher.getTdbTitles();
assertEquals(1, titles.size());
TdbTitle title2 = new TdbTitle("Test Title 2", title.getId());
try {
publisher.addTdbTitle(title2);
fail("TdbPublisher did not throw TdbException adding duplicate title");
} catch (TdbException ex) {
}
}
/**
* Test getTitlesByName() and getTitleById() methods.
* @throws TdbException for invalid Tdb operations
*/
public void testGetTitle() throws TdbException {
TdbPublisher publisher = new TdbPublisher("Test Publisher");
Collection<TdbTitle> titles = publisher.getTdbTitles();
assertEmpty(titles);
assertFalse(publisher.tdbTitleIterator().hasNext());
// add two titles
TdbTitle title1 = new TdbTitle("Journal Title", "1234-5678");
publisher.addTdbTitle(title1);
TdbTitle title2 = new TdbTitle("Book Title", "978-0521807678");
publisher.addTdbTitle(title2);
TdbTitle title3 = new TdbTitle("Book Title", "978-0345303066");
publisher.addTdbTitle(title3);
titles = publisher.getTdbTitles();
assertEquals(3, titles.size());
assertSameElements(ListUtil.list(title1, title2, title3),
ListUtil.fromIterator(publisher.tdbTitleIterator()));
assertEmpty(ListUtil.fromIterator(publisher.tdbAuIterator()));
TdbAu au1 = new TdbAu("Test AU1", "pluginA");
TdbAu au2 = new TdbAu("Test AU2", "pluginB");
TdbAu au3 = new TdbAu("Test AU3", "pluginC");
title1.addTdbAu(au1);
title1.addTdbAu(au2);
title3.addTdbAu(au3);
assertSameElements(ListUtil.list(au1, au2, au3),
ListUtil.fromIterator(publisher.tdbAuIterator()));
// get two titles by name
Collection<TdbTitle> getTitle1 = publisher.getTdbTitlesByName("Journal Title");
assertEquals(1, getTitle1.size());
assertEquals(title1, getTitle1.iterator().next());
Collection<TdbTitle> getTitle2 = publisher.getTdbTitlesByName("Book Title");
assertEquals(2, getTitle2.size());
assertTrue(getTitle2.contains(title2));
assertTrue(getTitle2.contains(title3));
// get title by ID
TdbTitle getTitleId2 = publisher.getTdbTitleById("978-0521807678");
assertEquals(title2, getTitleId2);
// get unknown title by name
Collection<TdbTitle> getTitleUnknown = publisher.getTdbTitlesByName("unknown");
assertEmpty(getTitleUnknown);
// get unknown title by ID
TdbTitle getTitleIdUnknown = publisher.getTdbTitleById("unknown");
assertNull(getTitleIdUnknown);
}
/**
* Test getTdbProviderCount() method.
* @throws TdbException for invalid Tdb operations
*/
public void testGetProvider() throws TdbException {
TdbPublisher publisher = new TdbPublisher("Test Publisher");
Collection<TdbTitle> titles = publisher.getTdbTitles();
assertEmpty(titles);
assertFalse(publisher.tdbTitleIterator().hasNext());
// add two titles
TdbTitle title1 = new TdbTitle("Journal Title", "1234-5678");
publisher.addTdbTitle(title1);
TdbTitle title2 = new TdbTitle("Book Title", "978-0521807678");
publisher.addTdbTitle(title2);
TdbTitle title3 = new TdbTitle("Book Title", "978-0345303066");
publisher.addTdbTitle(title3);
TdbAu au1 = new TdbAu("Test AU1", "pluginA");
new TdbProvider("provider1").addTdbAu(au1);
TdbAu au2 = new TdbAu("Test AU2", "pluginB");
new TdbProvider("provider2").addTdbAu(au2);
TdbAu au3 = new TdbAu("Test AU3", "pluginC");
new TdbProvider("provider3").addTdbAu(au3);
title1.addTdbAu(au1);
title1.addTdbAu(au2);
title3.addTdbAu(au3);
// ensure there are two providers: one that was
// explicitly added for au2, and one that was
// implicitly added for au1 and au3
assertEquals(3, publisher.getTdbProviderCount());
}
/**
* Test TdbAu.addPluginIdsForDifferences() method.
* @throws TdbException for invalid Tdb operations
*/
public void testAddPluginIdsForDifferences() throws TdbException {
TdbPublisher pub1 = new TdbPublisher("Test Publisher");
TdbTitle title1 = new TdbTitle("Test Title", "0000-0001");
TdbAu au1 = new TdbAu("Test AU1", "pluginA");
au1.setAttr("a", "A");
au1.setAttr("b", "A");
au1.setParam("x", "X");
au1.setPluginVersion("3");
title1.addTdbAu(au1);
pub1.addTdbTitle(title1);
// duplicate of pub1
TdbPublisher pub2 = new TdbPublisher("Test Publisher");
TdbTitle title2 = new TdbTitle("Test Title", "0000-0001");
TdbAu au2 = new TdbAu("Test AU1", "pluginA");
au2.setAttr("a", "A");
au2.setAttr("b", "A");
au2.setParam("x", "X");
au2.setPluginVersion("3");
title2.addTdbAu(au2);
pub2.addTdbTitle(title2);
TdbPublisher pub3 = new TdbPublisher("Test Publisher");
TdbTitle title3 = new TdbTitle("Test Title", "0000-0003");
TdbAu au3 = new TdbAu("Test AU1", "pluginB");
au3.setAttr("a", "A");
au3.setAttr("b", "A");
au3.setParam("x", "X");
au3.setPluginVersion("3");
title3.addTdbAu(au3);
pub3.addTdbTitle(title3);
// no differences becuase pub1 and pub2 are duplicates
Tdb.Differences diffs12 = new Tdb.Differences();
pub1.addDifferences(diffs12, pub2);
assertEquals(0, diffs12.getPluginIdsForDifferences().size());
// differences are 'pluginA' and 'pluginB'
Tdb.Differences diffs13 = new Tdb.Differences();
pub1.addDifferences(diffs13, pub3);
assertEquals(2, diffs13.getPluginIdsForDifferences().size());
}
}
| 34.663664 | 97 | 0.692974 |
3f9953fa32e0c35a8ee37d63034062628ec632bd | 2,715 | package com.landoop.avro.codec;
import org.apache.avro.file.Codec;
import org.apache.avro.file.DataFileConstants;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Implements bzip2 compression and decompression.
*/
public class BZip2Codec extends Codec {
public static final int DEFAULT_BUFFER_SIZE = 64 * 1024;
private ByteArrayOutputStream outputBuffer;
@Override
public String getName() {
return DataFileConstants.BZIP2_CODEC;
}
@Override
public ByteBuffer compress(ByteBuffer uncompressedData) throws IOException {
ByteArrayOutputStream baos = getOutputBuffer(uncompressedData.remaining());
BZip2CompressorOutputStream outputStream = new BZip2CompressorOutputStream(baos);
try {
outputStream.write(uncompressedData.array(),
uncompressedData.position(),
uncompressedData.remaining());
} finally {
outputStream.close();
}
ByteBuffer result = ByteBuffer.wrap(baos.toByteArray());
return result;
}
@Override
public ByteBuffer decompress(ByteBuffer compressedData) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(compressedData.array());
BZip2CompressorInputStream inputStream = new BZip2CompressorInputStream(bais);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int readCount = -1;
while ((readCount = inputStream.read(buffer, compressedData.position(), buffer.length)) > 0) {
baos.write(buffer, 0, readCount);
}
ByteBuffer result = ByteBuffer.wrap(baos.toByteArray());
return result;
} finally {
inputStream.close();
}
}
@Override
public int hashCode() {
return getName().hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || obj.getClass() != getClass())
return false;
return true;
}
//get and initialize the output buffer for use.
private ByteArrayOutputStream getOutputBuffer(int suggestedLength) {
if (null == outputBuffer) {
outputBuffer = new ByteArrayOutputStream(suggestedLength);
}
outputBuffer.reset();
return outputBuffer;
}
} | 30.166667 | 106 | 0.660773 |
40f0a03868d512ba6e27b02d951265eede31c452 | 3,821 | package com.valarao.wordlesolver.controller;
import com.valarao.wordlesolver.cache.CacheManager;
import com.valarao.wordlesolver.calculator.ScoreCalculator;
import com.valarao.wordlesolver.loader.WordDatasetLoader;
import com.valarao.wordlesolver.model.CalculateInformationScoresRequest;
import com.valarao.wordlesolver.model.CalculateInformationScoresResponse;
import com.valarao.wordlesolver.model.PastGuess;
import com.valarao.wordlesolver.model.PredictiveScore;
import com.valarao.wordlesolver.model.RetrospectiveScore;
import com.valarao.wordlesolver.model.ValidationResult;
import com.valarao.wordlesolver.validation.InputValidationException;
import com.valarao.wordlesolver.validation.GuessValidator;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
/**
* Controller managing the endpoint to calculate information scores for candidate guesses.
*/
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class ScoreController {
@Autowired
@NonNull
@Qualifier("reducedWordDatasetLoader")
private final WordDatasetLoader wordDatasetLoader;
@Autowired
@NonNull
private final ScoreCalculator<PredictiveScore> predictiveScoreCalculator;
@Autowired
@NonNull
private final ScoreCalculator<RetrospectiveScore> retrospectiveScoreCalculator;
@Autowired
@NonNull
private final CacheManager cacheManager;
@Autowired
@NonNull
@Qualifier("compositeGuessValidator")
private final GuessValidator guessValidator;
/***
*
* @param request Request with past guesses made.
* @return Response with calculated scores for candidate guesses.
*/
@PostMapping("/scores")
public CalculateInformationScoresResponse calculateInformationScores(
@RequestBody CalculateInformationScoresRequest request) {
validateGuesses(request.getGuesses());
List<String> allWords = wordDatasetLoader.load();
List<PastGuess> guesses = convertGuessWordsToUpperCase(request.getGuesses());
if (guesses.isEmpty()) {
return cacheManager.getScores();
}
List<PredictiveScore> predictiveScores = predictiveScoreCalculator.calculate(allWords, guesses);
return CalculateInformationScoresResponse.builder()
.topWord(predictiveScores.isEmpty() ? "" : predictiveScores.get(predictiveScores.size() - 1).getGuessWord())
.predictiveScores(predictiveScores)
.retrospectiveScores(retrospectiveScoreCalculator.calculate(allWords, guesses))
.build();
}
private List<PastGuess> convertGuessWordsToUpperCase(List<PastGuess> guesses) {
return guesses.stream()
.map(pastGuess -> pastGuess.toBuilder()
.guessWord(pastGuess.getGuessWord().toUpperCase(Locale.ROOT))
.build())
.collect(Collectors.toList());
}
private void validateGuesses(List<PastGuess> guesses) throws InputValidationException {
ValidationResult validationResult = guessValidator.validateAll(guesses);
if (!validationResult.isValid()) {
log.error(validationResult.getMessage());
throw new InputValidationException(validationResult.getMessage());
}
}
}
| 37.831683 | 124 | 0.750589 |
4c8f4c96e3dadd61c2939f86a6d97b036b8c3e73 | 1,846 | package com.youngadessi.demo.auth.controller;
import com.youngadessi.demo.auth.service.AuthenticationService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/auth")
public class AuthenticationController {
private final AuthenticationService authService;
private final PasswordEncoder passwordEncoder;
// private static final UserMapper USER_MAPPER = Mappers.getMapper(UserMapper.class);
@PostMapping("/signin")
public ResponseEntity<String> signin(@Valid @RequestBody LoginRequest loginRequest) {
return new ResponseEntity<>(authService.signin(loginRequest), HttpStatus.CREATED);
}
@PostMapping("/secure")
public ResponseEntity<String> secure() {
return new ResponseEntity<>("success", HttpStatus.CREATED);
}
// @PostMapping("/signup")
// public String signup(@RequestBody @Valid UserDTO userDTO) {
// return authService.signup(USER_MAPPER.toEntity(userDTO));
// }
//
// @DeleteMapping(value = "/{username}")
// public String delete(@PathVariable String username) {
// authService.delete(username);
// return username;
// }
//
// @GetMapping(value = "/me")
// public UserDTO whoami(HttpServletRequest req) {
// return USER_MAPPER.toDto(authService.whoami(req));
// }
}
| 32.385965 | 90 | 0.755688 |
a939bd24a3915d0cfcfb877ff812cc6027864d15 | 8,705 | /*
* (C) Copyright 2021 Radix DLT Ltd
*
* Radix DLT Ltd 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 com.radixdlt.api.service;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.inject.Inject;
import com.radixdlt.api.data.ActionType;
import com.radixdlt.api.data.action.TransactionAction;
import com.radixdlt.crypto.ECPublicKey;
import com.radixdlt.identifiers.REAddr;
import com.radixdlt.networks.Addressing;
import com.radixdlt.utils.UInt256;
import com.radixdlt.utils.functional.Failure;
import com.radixdlt.utils.functional.Result;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import static com.radixdlt.api.data.ApiErrors.INVALID_ACTION_DATA;
import static com.radixdlt.api.data.ApiErrors.MISSING_FIELD;
import static com.radixdlt.api.data.ApiErrors.UNSUPPORTED_ACTION;
import static com.radixdlt.application.validators.scrypt.ValidatorUpdateRakeConstraintScrypt.RAKE_MAX;
import static com.radixdlt.application.validators.scrypt.ValidatorUpdateRakeConstraintScrypt.RAKE_MIN;
import static com.radixdlt.application.validators.scrypt.ValidatorUpdateRakeConstraintScrypt.RAKE_PERCENTAGE_GRANULARITY;
import static com.radixdlt.identifiers.CommonErrors.UNABLE_TO_DECODE;
import static com.radixdlt.identifiers.CommonErrors.VALUE_OUT_OF_RANGE;
import static com.radixdlt.utils.functional.Result.allOf;
import static com.radixdlt.utils.functional.Result.wrap;
import static java.util.Optional.ofNullable;
public final class ActionParserService {
private final Addressing addressing;
@Inject
public ActionParserService(Addressing addressing) {
this.addressing = addressing;
}
public Result<List<TransactionAction>> parse(JSONArray actions) {
var list = new ArrayList<TransactionAction>();
for (var o : actions) {
if (!(o instanceof JSONObject)) {
return INVALID_ACTION_DATA.with(o).result();
}
var element = (JSONObject) o;
var result = param(element, "type")
.flatMap(ActionType::fromString)
.flatMap(type -> parseByType(type, element))
.onSuccess(list::add);
if (!result.isSuccess()) {
return result.map(List::of);
}
}
return Result.ok(list);
}
private Result<TransactionAction> parseByType(ActionType type, JSONObject element) {
switch (type) {
case UNKNOWN:
case MSG:
default:
return UNSUPPORTED_ACTION.with(type).result();
case TRANSFER:
return allOf(
from(element),
to(element),
amount(element),
rri(element)
).map(TransactionAction::transfer);
case UNSTAKE:
return allOf(
from(element),
validator(element),
amount(element)
).map(TransactionAction::unstake);
case STAKE:
return allOf(
from(element),
validator(element),
amount(element)
).map(TransactionAction::stake);
case BURN:
return allOf(
from(element),
rri(element),
amount(element)
).map(TransactionAction::burn);
case MINT:
return allOf(
to(element),
rri(element),
amount(element)
).map(TransactionAction::mint);
case REGISTER_VALIDATOR:
return allOf(
validator(element)
).map(TransactionAction::register);
case UNREGISTER_VALIDATOR:
return allOf(
validator(element)
).map(TransactionAction::unregister);
case UPDATE_VALIDATOR_METADATA:
return allOf(
validator(element),
optionalName(element),
optionalUrl(element)
).map(TransactionAction::updateMetadata);
case UPDATE_VALIDATOR_FEE:
return allOf(
validator(element),
fee(element)
).map(TransactionAction::updateValidatorFee);
case UPDATE_DELEGATION:
return allOf(
validator(element),
allowDelegation(element)
).map(TransactionAction::updateAllowDelegation);
case UPDATE_OWNER:
return allOf(
validator(element),
owner(element)
).map(TransactionAction::updateOwnerAddress);
case CREATE_FIXED:
return allOf(
to(element),
pubKey(element),
symbol(element),
name(element),
description(element),
iconUrl(element),
tokenUrl(element),
supply(element)
).map(TransactionAction::createFixed);
case CREATE_MUTABLE:
return allOf(
pubKey(element),
symbol(element),
name(element),
optionalDescription(element),
optionalIconUrl(element),
optionalTokenUrl(element)
).map(TransactionAction::createMutable);
}
}
private Result<ECPublicKey> pubKey(JSONObject element) {
return param(element, "publicKeyOfSigner")
.flatMap(ECPublicKey::fromHexString);
}
private Result<REAddr> rri(JSONObject element) {
// TODO: Need to verify symbol matches
return param(element, "rri")
.flatMap(p -> addressing.forResources().parseFunctional(p).map(t -> t.map((__, addr) -> addr)));
}
private static final Failure FEE_BOUNDS_FAILURE = VALUE_OUT_OF_RANGE.with(
(double) RAKE_MIN / (double) RAKE_PERCENTAGE_GRANULARITY + "",
(double) RAKE_MAX / (double) RAKE_PERCENTAGE_GRANULARITY + ""
);
private Result<Integer> fee(JSONObject element) {
return param(element, "validatorFee")
.flatMap(parameter -> wrap(UNABLE_TO_DECODE, () -> Double.parseDouble(parameter)))
.map(doublePercentage -> (int) (doublePercentage * RAKE_PERCENTAGE_GRANULARITY))
.filter(percentage -> percentage >= RAKE_MIN && percentage <= RAKE_MAX, FEE_BOUNDS_FAILURE);
}
private Result<Boolean> allowDelegation(JSONObject element) {
return param(element, "allowDelegation")
.flatMap(parameter ->
Stream.of("true", "false")
.filter(parameter::equals)
.findAny()
.map(Boolean::parseBoolean)
.map(Result::ok)
.orElseGet(() -> UNABLE_TO_DECODE.with(parameter).result())
);
}
private Result<REAddr> from(JSONObject element) {
return address(element, "from");
}
private Result<REAddr> owner(JSONObject element) {
return address(element, "owner");
}
private Result<REAddr> to(JSONObject element) {
return address(element, "to");
}
private Result<ECPublicKey> validator(JSONObject element) {
return param(element, "validator")
.flatMap(addressing.forValidators()::fromString);
}
private static Result<UInt256> amount(JSONObject element) {
return param(element, "amount")
.flatMap(UInt256::fromString);
}
private static Result<UInt256> supply(JSONObject element) {
return param(element, "supply")
.flatMap(UInt256::fromString);
}
private static Result<String> name(JSONObject element) {
return param(element, "name");
}
private static Result<Optional<String>> optionalName(JSONObject element) {
return optionalParam(element, "name");
}
private static Result<String> symbol(JSONObject element) {
return param(element, "symbol");
}
private static Result<Optional<String>> optionalUrl(JSONObject element) {
return optionalParam(element, "url");
}
private static Result<String> iconUrl(JSONObject element) {
return param(element, "iconUrl");
}
private static Result<Optional<String>> optionalIconUrl(JSONObject element) {
return optionalParam(element, "iconUrl");
}
private static Result<String> tokenUrl(JSONObject element) {
return param(element, "tokenUrl");
}
private static Result<Optional<String>> optionalTokenUrl(JSONObject element) {
return optionalParam(element, "tokenUrl");
}
private static Result<String> description(JSONObject element) {
return param(element, "description");
}
private static Result<Optional<String>> optionalDescription(JSONObject element) {
return optionalParam(element, "description");
}
private static Result<Optional<String>> optionalParam(JSONObject element, String name) {
return Result.ok(
ofNullable(element.opt(name))
.filter(String.class::isInstance)
.map(String.class::cast)
);
}
private Result<REAddr> address(JSONObject element, String name) {
return param(element, name)
.flatMap(addressing.forAccounts()::parseFunctional);
}
private static Result<String> param(JSONObject params, String name) {
return ofNullable(params.opt(name))
.map(Object::toString)
.map(Result::ok)
.orElseGet(() -> MISSING_FIELD.with(name).result());
}
}
| 28.540984 | 121 | 0.727972 |
b30c4a2ea15f0a794667e6952b46156ba645ee92 | 1,561 | /*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* 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 org.teiid.metadata;
import static org.junit.Assert.*;
import org.junit.Test;
public class TestTable {
@Test public void testCardinality() {
Table t = new Table();
assertEquals(-1, t.getCardinalityAsFloat(), 0);
t.setCardinality(1000);
assertEquals(1000, t.getCardinalityAsFloat(), 0);
t.setCardinality(100000111000111100L);
assertEquals(100000111000111100L/t.getCardinalityAsFloat(), 1, .01);
}
@Test public void testColumnPrecisionScale() {
Column c = new Column();
Datatype datatype = new Datatype();
datatype.setName("bigdecimal");
c.setDatatype(datatype);
c.setPrecision(0);
c.setScale(2);
assertEquals(2, c.getScale());
assertEquals(BaseColumn.DEFAULT_PRECISION, c.getPrecision());
}
}
| 32.520833 | 76 | 0.692505 |
8b8460733f5f2e826b4330521bde6fd7f6e0c7c1 | 3,410 | package org.gama.lang;
import java.io.Serializable;
import java.util.Iterator;
/**
* Kind of StringBuilder aimed at being simpler by its API.
*
* @author Guillaume Mary
*/
public class StringAppender implements Serializable, CharSequence {
private StringBuilder appender;
public StringAppender() {
appender = new StringBuilder();
}
public StringAppender(int capacity) {
appender = new StringBuilder(capacity);
}
public StringAppender(Object... s) {
this();
cat(s);
}
public StringAppender cat(Object s) {
appender.append(s);
return this;
}
public StringAppender cat(Object s1, Object s2) {
// we skip an array creation by calling cat() multiple times
return cat(s1).cat(s2);
}
public StringAppender cat(Object s1, Object s2, Object s3) {
// we skip an array creation by calling cat() multiple times
return cat(s1).cat(s2).cat(s3);
}
public StringAppender cat(Object... ss) {
for (Object s : ss) {
cat(s);
}
return this;
}
public StringAppender cat(Iterable ss) {
for (Object s : ss) {
cat(s);
}
return this;
}
public StringAppender catAt(int index, Object... ss) {
// We make this method uses cat() to ensure that any override of cat() is also used by this method
// otherwise we could simply use appender.insert(..)
// So, we swap this.appender with a new StringBuilder to make cat(..) fill it
StringBuilder previous = this.appender;
StringBuilder target = new StringBuilder();
this.appender = target;
// cat() will append to the temporary StringBuilder
cat(ss);
this.appender = previous;
// finally inserting at index
this.appender.insert(index, target);
return this;
}
public StringAppender catIf(boolean condition, Object... ss) {
if (condition) {
cat(ss);
}
return this;
}
public StringAppender ccat(Object... s) {
return ccat(s, s[s.length - 1], s.length - 1);
}
public StringAppender ccat(Iterable ss, Object sep) {
Iterator iterator = ss.iterator();
while (iterator.hasNext()) {
Object s = iterator.next();
cat(s).catIf(iterator.hasNext(), sep);
}
return this;
}
public StringAppender ccat(Object[] s, Object sep) {
return ccat(s, sep, s.length);
}
public StringAppender ccat(Object[] s, Object sep, int objectCount) {
if (s.length > 0) {
int lastIndex = objectCount < 1 ? 0 : objectCount - 1;
for (int i = 0; i < objectCount; i++) {
cat(s[i]).catIf(i != lastIndex, sep);
}
}
return this;
}
public StringAppender wrap(Object open, Object close) {
catAt(0, open).cat(close);
return this;
}
@Override
public String toString() {
return appender.toString();
}
public StringAppender cutTail(int nbChar) {
int newLength = length() - nbChar;
if (newLength > -1) {
appender.setLength(newLength);
}
return this;
}
public StringAppender cutHead(int nbChar) {
appender.delete(0, nbChar);
return this;
}
/**
* Gives access to delegate appender, because it can be usefull to append directly to the standard API StringBuilder
*
* @return the underlying appender
*/
public StringBuilder getAppender() {
return appender;
}
@Override
public int length() {
return appender.length();
}
@Override
public char charAt(int index) {
return appender.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return appender.subSequence(start, end);
}
}
| 22.142857 | 117 | 0.677126 |
253472e2b2b8afcb77e326f40b01d801afa1f5ac | 4,113 | package ca.corefacility.bioinformatics.irida.ria.unit.web.services;
import java.util.List;
import java.util.Locale;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.MessageSource;
import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException;
import ca.corefacility.bioinformatics.irida.model.joins.impl.RelatedProjectJoin;
import ca.corefacility.bioinformatics.irida.model.project.Project;
import ca.corefacility.bioinformatics.irida.ria.web.exceptions.UIAddAssociatedProjectException;
import ca.corefacility.bioinformatics.irida.ria.web.exceptions.UIRemoveAssociatedProjectException;
import ca.corefacility.bioinformatics.irida.ria.web.projects.settings.dto.AssociatedProject;
import ca.corefacility.bioinformatics.irida.ria.web.services.UIAssociatedProjectsService;
import ca.corefacility.bioinformatics.irida.security.permissions.project.ProjectOwnerPermission;
import ca.corefacility.bioinformatics.irida.service.ProjectService;
import com.google.common.collect.ImmutableList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;
public class UIAssociatedProjectsServiceTest {
private UIAssociatedProjectsService service;
private ProjectService projectService;
// DATA
private final Long PROJECT_1_ID = 1L;
private final Long PROJECT_2_ID = 2L;
private final Long PROJECT_4_ID = 4L;
private final Project PROJECT_1 = new Project("PROJECT_1");
private final Project PROJECT_2 = new Project("PROJECT_2");
private final Project PROJECT_3 = new Project("PROJECT_3");
private final Project PROJECT_4 = new Project("PROJECT_4");
@BeforeEach
public void setUp() {
projectService = mock(ProjectService.class);
ProjectOwnerPermission projectOwnerPermission = mock(ProjectOwnerPermission.class);
MessageSource messageSource = mock(MessageSource.class);
service = new UIAssociatedProjectsService(projectService, projectOwnerPermission, messageSource);
PROJECT_1.setId(PROJECT_1_ID);
PROJECT_2.setId(PROJECT_2_ID);
PROJECT_4.setId(PROJECT_4_ID);
when(projectService.read(PROJECT_1_ID)).thenReturn(PROJECT_1);
when(projectService.read(PROJECT_2_ID)).thenReturn(PROJECT_2);
when(projectService.read(PROJECT_4_ID)).thenReturn(PROJECT_4);
List<RelatedProjectJoin> relatedProjectJoins = ImmutableList.of(new RelatedProjectJoin(PROJECT_1, PROJECT_2),
new RelatedProjectJoin(PROJECT_1, PROJECT_3), new RelatedProjectJoin(PROJECT_1, PROJECT_4));
when(projectService.getRelatedProjects(PROJECT_1)).thenReturn(relatedProjectJoins);
}
@Test
public void testGetAssociatedProjectsForProject() {
List<AssociatedProject> relatedProjectJoins = service.getAssociatedProjectsForProject(PROJECT_1_ID);
assertEquals(3, relatedProjectJoins.size());
verify(projectService, times(1)).read(PROJECT_1_ID);
verify(projectService, times(1)).getRelatedProjects(PROJECT_1);
}
@Test
public void testAddAssociatedProject() throws UIAddAssociatedProjectException {
service.addAssociatedProject(PROJECT_1_ID, PROJECT_2_ID, Locale.ENGLISH);
verify(projectService, times(1)).addRelatedProject(PROJECT_1, PROJECT_2);
when(projectService.read(PROJECT_4_ID)).thenThrow(new EntityNotFoundException("Cannot find project"));
assertThrows(UIAddAssociatedProjectException.class, () -> {
service.addAssociatedProject(PROJECT_1_ID, PROJECT_4_ID, Locale.ENGLISH);
});
}
@Test
public void testRemoveAssociatedProject() throws UIRemoveAssociatedProjectException {
service.removeAssociatedProject(PROJECT_1_ID, PROJECT_2_ID, Locale.ENGLISH);
verify(projectService, times(1)).read(PROJECT_1_ID);
verify(projectService, times(1)).read(PROJECT_2_ID);
verify(projectService, times(1)).removeRelatedProject(PROJECT_1, PROJECT_2);
when(projectService.read(PROJECT_4_ID)).thenThrow(new EntityNotFoundException("Cannot find project"));
assertThrows(UIRemoveAssociatedProjectException.class, () -> {
service.removeAssociatedProject(PROJECT_1_ID, PROJECT_4_ID, Locale.ENGLISH);
});
}
}
| 43.294737 | 111 | 0.822514 |
2fb5d9448a72fee7aa4e656f2b5a67b0cbc17e0c | 4,052 | package com.stackroute.userregistration.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stackroute.userregistration.domain.User;
import com.stackroute.userregistration.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.mockito.Mockito.*;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class UserControllerTest {
//Creating the object for the mockmvc to mock the service
@Autowired
MockMvc mockMvc;
//Mocking the user service
@Mock
UserService userService;
@InjectMocks
UserController userController;
@Before
public void setup()
{
MockitoAnnotations.initMocks(this);
//Building the usercontroller
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}}
//Creating the testcase for the saving the user in the database
// @Test
// public void saveUserTest() throws Exception
// {
// //Sample user details
// User user = new User("1","Sahithi","[email protected]","pwd");
// //When the saveUser is called it has to return the saved user
// when(userService.saveUser(user)).thenReturn(user);
// //It has to perform the action whenever the user url template is called using the post method
// mockMvc.perform(post("/user")
// .contentType(MediaType.APPLICATION_JSON)
// .content(asJsonString(user)))
// .andExpect(status().isCreated());
// //It has to call the user only once
// verify(userService, times(1)).saveUser(Mockito.any(User.class));
// verifyNoMoreInteractions(userService);
// }
/* @Test
public void getAllUsersTest() throws Exception
{
//Sample user details
List<User> users = new ArrayList<>();
User user = new User("1","Sahithi","[email protected]","pwd");
User user1 = new User("1","premika","[email protected]","pwd");
users.add(user);
users.add(user1);
//Call the getuser method
when(userService.getUsers()).thenReturn(users);
mockMvc.perform(get("/user")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)));
//It has to call the getUsers only once
verify(userService, times(1)).getUsers();
verifyNoMoreInteractions(userService);
}
@Test
public void deleteUserTest() throws Exception
{
//Sample user details
User user = new User("1","Sahithi","[email protected]","pwd");
//When the deleteUser is called it has to return the deleted user
when(userService.deleteUser("1")).thenReturn(user);
mockMvc.perform(delete("/user/1")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
verify(userService, times(1)).deleteUser("1");
verifyNoMoreInteractions(userService);
}
//This method is used to change the object to the string
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}*/
| 40.118812 | 103 | 0.682626 |
8f371c80db3fb6a968e09cd9e08e4db5900586d7 | 14,520 | package com.navismart.navismart.view;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelProviders;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.navismart.navismart.BuildConfig;
import com.navismart.navismart.R;
import com.navismart.navismart.adapters.ChatAdapter;
import com.navismart.navismart.model.ChatModel;
import com.navismart.navismart.utils.PreferencesHelper;
import com.navismart.navismart.viewmodelfactory.ContactAdminViewModelFactory;
import com.navismart.navismart.viewmodels.ContactAdminViewModel;
import org.json.JSONObject;
import java.util.ArrayList;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static com.navismart.navismart.MainActivity.USER_TYPE;
import static com.navismart.navismart.MainActivity.getCurrentStringDate;
import static com.navismart.navismart.MainActivity.getCurrentStringTime;
import static com.navismart.navismart.adapters.ChatAdapter.SENDER_BOATER;
import static com.navismart.navismart.adapters.ChatAdapter.SENDER_MARINA;
public class ContactUsFragment extends Fragment {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private RecyclerView chatRecyclerView;
private FloatingActionButton sendButton;
private EditText msgEditText;
private TextView marinaChatName;
private ImageView moreIcon;
private Button deleteButton, cancelButton;
private FirebaseAuth auth;
private DatabaseReference databaseReference;
private String userID, userName, adminID;
private String receiverToken, senderToken, userToken, adminToken;
private PreferencesHelper preferencesHelper;
public ContactUsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chat, container, false);
preferencesHelper = new PreferencesHelper(getActivity());
chatRecyclerView = view.findViewById(R.id.chat_recycler_view);
sendButton = view.findViewById(R.id.send_button);
msgEditText = view.findViewById(R.id.msg_edit_text);
marinaChatName = view.findViewById(R.id.marinaChatName);
moreIcon = view.findViewById(R.id.more_icon);
msgEditText.setEnabled(false);
sendButton.setEnabled(false);
userName = getArguments().getString("userName");
userID = getArguments().getString("userID");
adminID = getArguments().getString("adminID");
if (USER_TYPE == SENDER_BOATER || USER_TYPE == SENDER_MARINA) {
marinaChatName.setText("Navismart");
} else {
marinaChatName.setText(userName);
}
auth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("users").child(userID).child("profile").child("fcm_token").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
userToken = dataSnapshot.getValue().toString();
databaseReference.child("users").child(adminID).child("profile").child("fcm_token").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
adminToken = dataSnapshot.getValue().toString();
if (USER_TYPE == SENDER_BOATER || USER_TYPE == SENDER_MARINA) {
receiverToken = adminToken;
senderToken = userToken;
} else {
receiverToken = userToken;
senderToken = adminToken;
}
msgEditText.setEnabled(true);
sendButton.setEnabled(true);
Log.d("ADMIN_TOKEN", adminToken);
Log.d("USER_TOKEN", userToken);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Dialog deleteDialog = new Dialog(getContext());
deleteDialog.setContentView(R.layout.delete_chat_dialog);
deleteButton = deleteDialog.findViewById(R.id.delete_button);
cancelButton = deleteDialog.findViewById(R.id.cancel_delete);
cancelButton.setOnClickListener((View v) -> deleteDialog.dismiss());
deleteButton.setOnClickListener((View v) -> {
deleteAllChats();
deleteDialog.dismiss();
});
moreIcon.setOnClickListener((View v) -> {
PopupMenu popupMenu = new PopupMenu(getContext(), moreIcon);
popupMenu.getMenuInflater().inflate(R.menu.chat_options, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(item -> {
if (item.getItemId() == R.id.delete_chats) {
deleteDialog.show();
}
return true;
});
popupMenu.show();
});
sendButton.setOnClickListener((View v) -> {
if (!msgEditText.getText().toString().trim().isEmpty()) {
ChatModel chatModel = new ChatModel();
chatModel.setSENDER_TYPE(USER_TYPE);
chatModel.setMsg(msgEditText.getText().toString());
chatModel.setMsgTime(getCurrentStringTime());
chatModel.setMsgDate(getCurrentStringDate());
uploadMessage(chatModel);
}
});
if (USER_TYPE == SENDER_BOATER || USER_TYPE == SENDER_MARINA) {
ContactAdminViewModel contactAdminViewModel = ViewModelProviders.of(this, new ContactAdminViewModelFactory(adminID, userID)).get(ContactAdminViewModel.class);
LiveData<DataSnapshot> liveData = contactAdminViewModel.getDataSnapshotLiveData();
liveData.observe(this, dataSnapshot -> {
ArrayList<ChatModel> chatModelArrayList = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.child("messages").getChildren()) {
ChatModel chatModel = snapshot.getValue(ChatModel.class);
if (chatModel.getSENDER_TYPE() == SENDER_BOATER) {
chatModel.setMsgName(userName);
} else {
chatModel.setMsgName("Navismart");
}
chatModelArrayList.add(chatModel);
}
ChatAdapter reviewListAdapter = new ChatAdapter(chatModelArrayList, getContext());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
((LinearLayoutManager) mLayoutManager).setStackFromEnd(true);
chatRecyclerView.setLayoutManager(mLayoutManager);
chatRecyclerView.setItemAnimator(new DefaultItemAnimator());
chatRecyclerView.setAdapter(reviewListAdapter);
});
} else {
ContactAdminViewModel contactAdminViewModel = ViewModelProviders.of(this, new ContactAdminViewModelFactory(userID, adminID)).get(ContactAdminViewModel.class);
LiveData<DataSnapshot> liveData = contactAdminViewModel.getDataSnapshotLiveData();
liveData.observe(this, dataSnapshot -> {
ArrayList<ChatModel> chatModelArrayList = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.child("messages").getChildren()) {
ChatModel chatModel = snapshot.getValue(ChatModel.class);
if (chatModel.getSENDER_TYPE() == SENDER_BOATER) {
chatModel.setMsgName("Navismart");
} else {
chatModel.setMsgName(userName);
}
chatModelArrayList.add(chatModel);
}
ChatAdapter reviewListAdapter = new ChatAdapter(chatModelArrayList, getContext());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
((LinearLayoutManager) mLayoutManager).setStackFromEnd(true);
chatRecyclerView.setLayoutManager(mLayoutManager);
chatRecyclerView.setItemAnimator(new DefaultItemAnimator());
chatRecyclerView.setAdapter(reviewListAdapter);
});
}
return view;
}
private void deleteAllChats() {
DatabaseReference chatReference;
String id = "";
if (USER_TYPE == SENDER_BOATER || USER_TYPE == SENDER_MARINA)
id = adminID;
else
id = userID;
chatReference = databaseReference.child("users").child(auth.getCurrentUser().getUid()).child("contactAdmin").child(id).child("messages");
chatReference.setValue(null)
.addOnSuccessListener(aVoid -> Toast.makeText(getContext(), "Chats deleted successfully", Toast.LENGTH_SHORT).show()).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getContext(), "Unable to delete chats", Toast.LENGTH_SHORT).show();
}
});
}
private void uploadMessage(ChatModel chatModel) {
DatabaseReference chatReference;
chatReference = databaseReference.child("users").child(userID).child("contactAdmin").child(adminID).child("messages");
chatReference.push().setValue(chatModel).addOnSuccessListener(aVoid -> msgEditText.setText(null));
chatReference = databaseReference.child("users").child(userID).child("contactAdmin").child(adminID).child("userName");
chatReference.setValue(userName);
chatReference = databaseReference.child("users").child(userID).child("contactAdmin").child(adminID).child("adminName");
chatReference.setValue("Navismart");
chatReference = databaseReference.child("users").child(adminID).child("contactAdmin").child(userID).child("messages");
chatReference.push().setValue(chatModel).addOnSuccessListener(aVoid -> msgEditText.setText(null));
chatReference = databaseReference.child("users").child(adminID).child("contactAdmin").child(userID).child("userName");
chatReference.setValue(userName);
chatReference = databaseReference.child("users").child(adminID).child("contactAdmin").child(userID).child("adminName");
chatReference.setValue("Navismart");
String userToken = "", adminToken = "";
if (USER_TYPE == SENDER_BOATER || USER_TYPE == SENDER_MARINA) {
adminToken = receiverToken;
userToken = preferencesHelper.getToken();
} else {
adminToken = preferencesHelper.getToken();
userToken = receiverToken;
}
chatReference = databaseReference.child("users").child(userID).child("contactAdmin").child(adminID).child("userToken");
chatReference.setValue(userToken);
chatReference = databaseReference.child("users").child(userID).child("contactAdmin").child(adminID).child("adminToken");
chatReference.setValue(adminToken);
chatReference = databaseReference.child("users").child(adminID).child("contactAdmin").child(userID).child("userToken");
chatReference.setValue(userToken);
chatReference = databaseReference.child("users").child(adminID).child("contactAdmin").child(userID).child("adminToken");
chatReference.setValue(adminToken);
sendNotification(receiverToken, chatModel.getMsg());
}
private void sendNotification(String regToken, String msg) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
JSONObject dataJson = new JSONObject();
dataJson.put("body", msg);
dataJson.put("title", auth.getCurrentUser().getDisplayName());
json.put("notification", dataJson);
json.put("to", regToken);
RequestBody body = RequestBody.create(JSON, json.toString());
Request request = new Request.Builder()
.header("Authorization", "key=" + BuildConfig.LEGACY_SERVER_KEY)
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.build();
Response response = client.newCall(request).execute();
String finalResponse = response.body().string();
} catch (Exception e) {
Log.d("Notification Error: ", e.toString());
}
return null;
}
}.execute();
}
}
| 43.603604 | 180 | 0.646901 |
593abbfde8628c9f6dff1a1219f7df2ffabfbdef | 789 | package com.imyc.SBAP.Base.valid.combinedNotNull.annotation;
import com.imyc.SBAP.Base.valid.combinedNotNull.utils.CombinedNotNullValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Constraint(validatedBy = CombinedNotNullValidator.class)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CombinedNotNull {
String message() default "{dto.combined.not.null.error}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
// Fields to validate against null.
String[] fields() default {};
} | 34.304348 | 79 | 0.780735 |
c92b751375f46c9eba094c309f0b71e0481baba8 | 1,338 | package org.cybersapien.watercollection.processors;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.cybersapien.watercollection.service.v1.model.WaterCollection;
import javax.cache.Cache;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;
/**
* Processor to read the water collection cache.
*/
@Named
@RequiredArgsConstructor
public class WaterCollectionsCacheBulkReader implements Processor {
/**
* Water Collection cache
*/
private final Cache<String, WaterCollection> waterCollectionCache;
@Override
public void process(@NonNull Exchange exchange) throws Exception {
if (exchange.isFailed()) {
return;
}
if (null == exchange.getIn()) {
exchange.setException(new InvalidProcessorStateException("incoming message is null"));
return;
}
// TODO honor paging in the request. Right now the default page size (1024?) is used.
List<WaterCollection> waterCollections = new ArrayList<>();
for (Cache.Entry<String, WaterCollection> entry : waterCollectionCache) {
waterCollections.add(entry.getValue());
}
exchange.getOut().setBody(waterCollections, List.class);
}
}
| 30.409091 | 98 | 0.704783 |
809b5329f16601db5d57bda0cb8818fb2019cac3 | 3,254 | package com.github.stormbit.sdk.utils.vkapi.executors;
import com.github.stormbit.sdk.utils.Utils;
import com.github.stormbit.sdk.utils.vkapi.Auth;
import com.github.stormbit.sdk.utils.vkapi.Executor;
import com.github.stormbit.sdk.utils.vkapi.calls.CallAsync;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
import java.util.stream.IntStream;
/**
* Created by Storm-bit
* Executor for users
*/
public class ExecutorUser extends Executor {
public ExecutorUser(Auth auth) {
super(auth);
}
@Override
protected void executing() {
List<CallAsync> tmpQueue = new ArrayList<>();
int count = 0;
for (Iterator<CallAsync> iterator = queue.iterator(); iterator.hasNext() && count < 25; count++) {
tmpQueue.add(iterator.next());
}
if (!tmpQueue.isEmpty()) {
for (CallAsync item : tmpQueue) {
String method = item.getMethodName();
JSONObject params = item.getParams();
if (!Utils._hashes.has(method)) {
Utils.get_hash(_auth, method);
}
queue.removeAll(tmpQueue);
JSONObject data = new JSONObject();
data.put("act", "a_run_method");
data.put("al", 1);
data.put("hash", Utils._hashes.get(method));
data.put("method", method);
data.put("param_v", Utils.version);
for (String key : params.keySet()) {
data.put("param_" + key, params.get(key));
}
Map<String, Object> prms = new HashMap<>();
for (String key : data.keySet()) {
prms.put(key, data.get(key));
}
// Execute
if (count > 0) {
String responseString = _auth.session.post(Utils.URL)
.body(prms)
.send().readToText().replaceAll("[<!>]", "").substring(2);
if (LOG_REQUESTS) {
LOG.error("New executing request response: {}", responseString);
}
JSONObject response;
try {
response = new JSONObject(new JSONObject(responseString).getJSONArray("payload").getJSONArray(1).getString(0));
} catch (JSONException e) {
tmpQueue.forEach(call -> call.getCallback().onResult("false"));
LOG.error("Bad response from executing: {}, params: {}", responseString, data.toString());
return;
}
if (!response.has("response")) {
LOG.error("No 'response' object when executing code, VK response: {}", response);
tmpQueue.forEach(call -> call.getCallback().onResult("false"));
return;
}
Object responses = response.get("response");
IntStream.range(0, count).forEachOrdered(i -> tmpQueue.get(i).getCallback().onResult(responses));
}
}
}
}
}
| 34.252632 | 135 | 0.509219 |
338f1a382b960b99b8e7891b6cd55537fed8b0c7 | 305 | package com.zscat.mallplus.build.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zscat.mallplus.build.entity.BuildingFloor;
/**
* <p>
* 服务类
* </p>
*
* @author zscat
* @since 2019-11-27
*/
public interface IBuildingFloorService extends IService<BuildingFloor> {
}
| 17.941176 | 72 | 0.740984 |
385d0e84282ab8a441d75457fec3ab02db65e740 | 368 | package io.crowdcode.cloudbay.auction.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
public class AuctionExpiredException extends InvalidAuctionStateException {
public AuctionExpiredException() {
super("Product already expired");
}
}
| 28.307692 | 75 | 0.809783 |
4c1838fe09e759aeaa8d33e9b457345bc64c9166 | 2,273 | package order.model.service;
import static common.JDBCTemplate.*;
import java.sql.Connection;
import java.util.ArrayList;
import member.model.dao.MemberDao;
import member.model.vo.Member;
import notice.model.dao.NoticeDao;
import notice.model.vo.Notice;
import order.model.dao.OrderDao;
import order.model.vo.Order;
import order.model.vo.OrderDetail;
public class OrderService {
public ArrayList<Order> selectOrderList(String mNo) {
Connection conn = getConnection();
ArrayList<Order> list = new OrderDao().selectOrderList(conn, mNo);
close(conn);
return list;
}
// Shopping_Order 테이블 접근 -> 주문 추가하기
public int insertOrder(String mNo, String rName, String rPhone, String addr, String rPlease, int chong) {
Connection conn = getConnection();
int r1 = new OrderDao().insertOrder(conn, mNo, rName, rPhone, addr, rPlease, chong);
if(r1>0) {
commit(conn);
}else {
rollback(conn);
}
close(conn);
return r1;
}
// order_detail 테이블 접근 -> 주문 상세 추가하기
public int insertDetailOrder(String orderId, String pId, int quantity, int total) {
Connection conn = getConnection();
int result = new OrderDao().insertDetailOrder(conn, orderId, pId, quantity, total);
if(result>0) {
commit(conn);
}else {
rollback(conn);
}
close(conn);
return result;
}
// 최근 주문 번호 1개 조회하기
public String selectOrderId(String mNo) {
Connection conn = getConnection();
String orderId = new OrderDao().selectOrderId(conn, mNo);
close(conn);
return orderId;
}
// 마이페이지에서 주문 조회 시
public ArrayList<OrderDetail> selectMyOrder(String mNo) {
Connection conn = getConnection();
ArrayList<OrderDetail> oList = new OrderDao().selectMyOrder(conn, mNo);
close(conn);
return oList;
}
//어드민페이지 - 회원관리용 주문액리스트
public ArrayList<Order> SelectOrderList(int currentPage, int boardLimit) {
Connection conn = getConnection();
ArrayList<Order> list = new OrderDao().selectOrderList(conn, currentPage, boardLimit);
close(conn);
return list;
}
//오더 하나 셀렉
public Order selectOrder(String oId) {
Connection conn = getConnection();
Order order = new OrderDao().selectOrder(conn, oId);
close(conn);
return order;
}
}
| 24.706522 | 107 | 0.683238 |
03aba8181d53f085465de67107c18de21e12e483 | 4,998 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.buck.core.rules.providers.lib;
import com.facebook.buck.core.artifact.Artifact;
import com.facebook.buck.core.artifact.OutputArtifact;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rules.actions.lib.args.CommandLineArgs;
import com.facebook.buck.core.rules.actions.lib.args.CommandLineArgsFactory;
import com.facebook.buck.core.rules.providers.annotations.ImmutableInfo;
import com.facebook.buck.core.rules.providers.impl.BuiltInProvider;
import com.facebook.buck.core.rules.providers.impl.BuiltInProviderInfo;
import com.facebook.buck.core.starlark.compatible.BuckSkylarkTypes;
import com.facebook.buck.core.starlark.rule.args.CommandLineArgsBuilder;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Stream;
import net.starlark.java.eval.Dict;
import net.starlark.java.eval.EvalException;
import net.starlark.java.eval.Printer;
import net.starlark.java.eval.StarlarkList;
/**
* The standard {@link com.facebook.buck.core.rules.providers.Provider} that describes how to run a
* given build rule's outputs.
*/
@ImmutableInfo(
args = {"env", "args"},
defaultSkylarkValues = {"{}", "[]"})
public abstract class RunInfo extends BuiltInProviderInfo<RunInfo> implements CommandLineArgs {
public static final BuiltInProvider<RunInfo> PROVIDER =
BuiltInProvider.of(ImmutableRunInfo.class);
@Override
public void repr(Printer printer) {
printer.append("<command line arguments>");
}
@Override
public boolean isImmutable() {
/**
* We already validate that the types added here are Immutable in {@link CommandLineArgsFactory}
* there is no need to do further validation.
*
* <p>See also {@link AggregateCommandLineArgs}, {@link ListCommandLineArgs}, {@link
* com.facebook.buck.core.rules.providers.lib.RunInfo}
*/
return true;
}
/** @return any additional environment variables that should be used when executing */
@AddToRuleKey
public abstract ImmutableMap<String, String> env();
/** @return the command line arguments to use when executing */
@AddToRuleKey
public abstract CommandLineArgs args();
/**
* Create an instance of RunInfo from skylark arguments.
*
* @param env environment variables to use when executing
* @param args arguments used to execute this program. Must be one of {@link
* CommandLineArgsBuilder}, {@link CommandLineArgs} or {@link StarlarkList}.
* @return An instance of {@link RunInfo} with immutable {@link #env()} and {@link #args()}
* @throws EvalException the type passed in was incorrect
*/
public static RunInfo instantiateFromSkylark(Dict<String, String> env, Object args)
throws EvalException {
Map<String, String> validatedEnv = Dict.cast(env, String.class, String.class, "environment");
CommandLineArgs commandLineArgs;
if (args instanceof CommandLineArgsBuilder) {
commandLineArgs = ((CommandLineArgsBuilder) args).build();
} else if (args instanceof CommandLineArgs) {
commandLineArgs = (CommandLineArgs) args;
} else if (args instanceof StarlarkList) {
ImmutableList<Object> validatedArgs =
BuckSkylarkTypes.toJavaList((StarlarkList<?>) args, Object.class, "args");
commandLineArgs = CommandLineArgsFactory.from(validatedArgs);
} else {
throw new HumanReadableException(
"%s must either be a list of arguments, or an args() object");
}
return new ImmutableRunInfo(validatedEnv, commandLineArgs);
}
@Override
public ImmutableSortedMap<String, String> getEnvironmentVariables() {
return ImmutableSortedMap.<String, String>naturalOrder()
.putAll(env())
.putAll(args().getEnvironmentVariables())
.build();
}
@Override
public Stream<ArgAndFormatString> getArgsAndFormatStrings() {
return args().getArgsAndFormatStrings();
}
@Override
public int getEstimatedArgsCount() {
return args().getEstimatedArgsCount();
}
@Override
public void visitInputsAndOutputs(Consumer<Artifact> inputs, Consumer<OutputArtifact> outputs) {
args().visitInputsAndOutputs(inputs, outputs);
}
}
| 38.446154 | 100 | 0.744098 |
c7885b7019230f1a016ba6f085a1dde377210189 | 227 | package org.patientview.api.model;
public class RequeueReport {
private final int count;
public RequeueReport(int count) {
this.count = count;
}
public int getCount() {
return count;
}
}
| 15.133333 | 37 | 0.625551 |
414e5c006d4fd2635d3908d9dc3645f06cd93d44 | 1,791 | /*
* Copyright (C) 2014 Naver Corp.
*
* 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.navercorp.volleyextensions.cache.universalimageloader.memory.impl;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.shadows.ShadowBitmap;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.navercorp.volleyextensions.cache.universalimageloader.memory.impl.UniversalFifoLimitedMemoryCache;
@RunWith(RobolectricTestRunner.class)
@org.robolectric.annotation.Config(manifest=org.robolectric.annotation.Config.NONE)
public class UniversalFifoLimitedMemoryCacheTest {
@Test
public void bitmapShouldBeCached(){
// Given
String url = "http://me.do/test1.jpg";
Bitmap image = ShadowBitmap.createBitmap(100, 100, Config.ALPHA_8);
ImageCache cache = new UniversalFifoLimitedMemoryCache(10);
// When
cache.putBitmap(url, image);
// Then
Bitmap hit = cache.getBitmap(url);
assertThat("Bitmap should be cached by WeakReference event if it exceeds size limit of UniversalFifoLimitedMemoryCache",
hit, is(image));
}
}
| 36.55102 | 123 | 0.778336 |
f8fb2d6bbb8cc241f91ded8c8796ceff7b8b1167 | 5,018 | /**
* Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite 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
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.symbolic.solver.cvc4;
import org.evosuite.symbolic.expr.Comparator;
import org.evosuite.symbolic.expr.ConstraintVisitor;
import org.evosuite.symbolic.expr.Expression;
import org.evosuite.symbolic.expr.IntegerConstraint;
import org.evosuite.symbolic.expr.Operator;
import org.evosuite.symbolic.expr.RealConstraint;
import org.evosuite.symbolic.expr.StringConstraint;
import org.evosuite.symbolic.expr.bv.IntegerConstant;
import org.evosuite.symbolic.expr.bv.StringBinaryToIntegerExpression;
import org.evosuite.symbolic.solver.SmtExprBuilder;
import org.evosuite.symbolic.solver.smt.SmtExpr;
final class ConstraintToCVC4Visitor implements ConstraintVisitor<SmtExpr, Void> {
private final ExprToCVC4Visitor exprVisitor;
public ConstraintToCVC4Visitor() {
this(false);
}
private static SmtExpr translateCompareTo(Expression<?> left, Comparator cmp, Expression<?> right) {
if (!(left instanceof StringBinaryToIntegerExpression)) {
return null;
}
if (!(right instanceof IntegerConstant)) {
return null;
}
if (cmp != Comparator.NE && cmp!=Comparator.EQ) {
return null;
}
StringBinaryToIntegerExpression leftExpr = (StringBinaryToIntegerExpression)left;
if (leftExpr.getOperator()!=Operator.COMPARETO) {
return null;
}
IntegerConstant rightExpr = (IntegerConstant)right;
if (rightExpr.getConcreteValue()!=0) {
return null;
}
ExprToCVC4Visitor v = new ExprToCVC4Visitor();
SmtExpr leftEquals = leftExpr.getLeftOperand().accept(v, null);
SmtExpr rightEquals = leftExpr.getRightOperand().accept(v, null);
if (leftEquals==null || rightEquals==null) {
return null;
}
SmtExpr eqExpr = SmtExprBuilder.mkEq(leftEquals, rightEquals);
if (cmp==Comparator.EQ) {
return eqExpr;
} else {
return SmtExprBuilder.mkNot(eqExpr);
}
}
public ConstraintToCVC4Visitor(boolean rewriteNonLinearConstraints) {
this.exprVisitor = new ExprToCVC4Visitor(rewriteNonLinearConstraints);
}
@Override
public SmtExpr visit(IntegerConstraint c, Void arg) {
Expression<?> leftOperand = c.getLeftOperand();
Expression<?> rightOperand = c.getRightOperand();
Comparator cmp = c.getComparator();
SmtExpr expr = translateCompareTo(leftOperand, cmp, rightOperand);
if (expr != null) {
return expr;
} else {
return visit(leftOperand, cmp, rightOperand);
}
}
private SmtExpr visit(Expression<?> leftOperand, Comparator cmp, Expression<?> rightOperand) {
SmtExpr left = leftOperand.accept(exprVisitor, null);
SmtExpr right = rightOperand.accept(exprVisitor, null);
if (left == null || right == null) {
return null;
}
return mkComparison(left, cmp, right);
}
@Override
public SmtExpr visit(RealConstraint c, Void arg) {
Expression<?> leftOperand = c.getLeftOperand();
Expression<?> rightOperand = c.getRightOperand();
Comparator cmp = c.getComparator();
return visit(leftOperand, cmp, rightOperand);
}
@Override
public SmtExpr visit(StringConstraint c, Void arg) {
Expression<?> leftOperand = c.getLeftOperand();
Expression<?> rightOperand = c.getRightOperand();
Comparator cmp = c.getComparator();
SmtExpr equalsExpr = translateCompareTo(leftOperand , cmp, rightOperand);
if (equalsExpr != null) {
return equalsExpr;
} else {
return visit(leftOperand, cmp, rightOperand);
}
}
private static SmtExpr mkComparison(SmtExpr left, Comparator cmp, SmtExpr right) {
switch (cmp) {
case LT: {
SmtExpr lt = SmtExprBuilder.mkLt(left, right);
return lt;
}
case LE: {
SmtExpr le = SmtExprBuilder.mkLe(left, right);
return le;
}
case GT: {
SmtExpr gt = SmtExprBuilder.mkGt(left, right);
return gt;
}
case GE: {
SmtExpr ge = SmtExprBuilder.mkGe(left, right);
return ge;
}
case EQ: {
SmtExpr ge = SmtExprBuilder.mkEq(left, right);
return ge;
}
case NE: {
SmtExpr ge = SmtExprBuilder.mkEq(left, right);
SmtExpr ne = SmtExprBuilder.mkNot(ge);
return ne;
}
default: {
throw new RuntimeException("Unknown comparator for constraint " + cmp.toString());
}
}
}
}
| 30.412121 | 102 | 0.705261 |
b7d908179e8bff8db9bdb68ba3fa33beb0c08559 | 2,119 | package sf.example.spring.mockmvc;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.Mockito.when;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(controllers = StarshipBookingController.class)
class StarshipBookingControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private StarshipBookingService bookingService;
@Test
void callsServiceWithParameter_noResults() throws Exception {
when(bookingService.findBookableStarships(200)).thenReturn(new ArrayList<>());
mockMvc.perform(
get("/bookable-starships")
.header("capacity", "200")
.accept(APPLICATION_JSON))
.andExpect(status().is2xxSuccessful())
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
}
@Test
void callsServiceWithParameter_twoResults() throws Exception {
List<Starship> twoStarships = Arrays.asList(new Starship(), new Starship());
when(bookingService.findBookableStarships(42)).thenReturn(twoStarships);
mockMvc.perform(
get("/bookable-starships")
.header("capacity", "42")
.accept(APPLICATION_JSON))
.andExpect(status().is2xxSuccessful())
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").value(hasSize(2)));
}
}
| 36.534483 | 89 | 0.694195 |
e64261a6e9b93e189d4044de198ba59fa1749cbc | 6,561 | package com.lothrazar.dimstack.transit;
import com.lothrazar.dimstack.DimstackMod;
import javax.annotation.Nullable;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.NBTUtil;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
/**
* A transit object. A transit represents a connection between vertical dimensions.
*/
public class Transit {
protected ResourceLocation itemId;
protected ResourceLocation from;
protected ResourceLocation to;
protected boolean goesUpwards;
protected int yLimit;
protected BlockPos pos;
protected boolean relative;
protected float ratio;
protected int landing;
public Transit(ResourceLocation itemId, ResourceLocation from, ResourceLocation to, boolean top, int yLimit, BlockPos pos, boolean relative, float ratio, int landing) {
this.itemId = itemId;
this.from = from;
this.to = to;
this.goesUpwards = top;
this.yLimit = yLimit;
this.pos = pos;
this.relative = relative;
this.ratio = ratio;
this.landing = landing;
}
public Transit(CompoundNBT tag) {
read(tag);
}
public Transit() {}
public void read(CompoundNBT tag) {
if (tag.contains("item")) {
itemId = ResourceLocation.tryCreate(tag.getString("item"));
}
from = ResourceLocation.tryCreate(tag.getString("from"));
to = ResourceLocation.tryCreate(tag.getString("to"));
goesUpwards = tag.getBoolean("up");
yLimit = tag.getInt("ylimit");
landing = tag.getInt("landing");
ratio = tag.getFloat("ratio");
if (tag.contains("pos")) {
pos = NBTUtil.readBlockPos(tag.getCompound("pos"));
}
}
public CompoundNBT write() {
CompoundNBT tag = new CompoundNBT();
if (itemId != null) {
tag.putString("item", itemId.toString());
}
tag.putString("from", from.toString());
tag.putString("to", to.toString());
tag.putBoolean("up", goesUpwards);
tag.putInt("ylimit", yLimit);
tag.putInt("landing", landing);
tag.putFloat("ratio", ratio);
if (pos != null) {
tag.put("pos", NBTUtil.writeBlockPos(pos));
}
return tag;
}
/**
* The id of the dimension this transit comes from.
*/
public ResourceLocation getSourceDim() {
return from;
}
/**
* The id of the dimension this transit leads to.
*/
public ResourceLocation getTargetDim() {
return to;
}
/**
* If this transit goes upwards into the connected dimension If this returns true, the portal is expected to be near the ceiling of the dim, whatever that may be.
*/
public boolean goesUpwards() {
return goesUpwards;
}
/**
* The limit of how close the player must be to the top (or bottom) of the world to utilize this transit. This number is a y-value. If {@link Transit#goesUpwards()} returns true, the player must be
* above this value, otherwise they must be below it.
*/
public int getLimit() {
return yLimit;
}
/**
* If this transit does a relative transition or not. If it does, then {@link Transit#getTargetPos()} will be null. In the event that it does not, the target pos will always be where the transit
* sends the player, and a return portal will not be created.
*/
public boolean isRelative() {
return relative;
}
/**
* If {@link Transit#isRelative()} is false, returns the destination of this transit. Otherwise, this returns null.
*/
@Nullable
public BlockPos getTargetPos() {
return pos;
}
/**
* The factor that will be applied to the source coordinates when travelling to a dimension, before looking for a destination. Only used if {@link Transit#isRelative()} is true.
*/
public float getRatio() {
return ratio;
}
/**
* Returns the y-level that the destination portal will spawn at, if {@link Transit#isRelative()} is true. Otherwise this is not relevant.
*/
public int getLanding() {
return landing;
}
public static Transit.Builder builder() {
return new Builder();
}
public static Transit fromString(String layer, boolean relative) {
String[] lrs = layer.split(",");
Transit.Builder builder = Transit.builder();
try {
builder.item(ResourceLocation.tryCreate(lrs[0]));
builder.from(ResourceLocation.tryCreate(lrs[1]));
builder.to(ResourceLocation.tryCreate(lrs[2]));
builder.goesUpwards(">".equalsIgnoreCase(lrs[3]));
builder.limit(Integer.parseInt(lrs[4]));
if (!relative) {
int x = Integer.parseInt(lrs[5]), y = Integer.parseInt(lrs[6]), z = Integer.parseInt(lrs[7]);
builder.pos(new BlockPos(x, y, z));
}
else {
builder.ratio(Float.parseFloat(lrs[5]));
builder.landing(Integer.parseInt(lrs[6]));
}
return builder.build();
}
catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
DimstackMod.LOGGER.error("Rift problem " + layer + " || " + builder.build(), e);
return null;
}
}
@Override
public String toString() {
return "Transit [from=" + from + ", to=" + to + ", goesUpwards=" + goesUpwards + ", yLimit=" + yLimit +
", pos=" + pos + ", relative=" + relative + ", ratio=" + ratio + ", landing=" + landing + "]";
}
public static class Builder {
protected ResourceLocation itemId;
protected ResourceLocation from;
protected ResourceLocation to;
protected boolean goesUpwards;
protected int yLimit;
protected BlockPos pos;
protected boolean relative = true; //assumed true until pos is set
protected float ratio;
protected int landing;
public Builder() {}
public Builder item(ResourceLocation dim) {
this.itemId = dim;
return this;
}
public Builder from(ResourceLocation dim) {
this.from = dim;
return this;
}
public Builder to(ResourceLocation dim) {
this.to = dim;
return this;
}
public Builder goesUpwards(boolean goesUpwards) {
this.goesUpwards = goesUpwards;
return this;
}
public Builder limit(int limit) {
this.yLimit = limit;
return this;
}
public Builder pos(BlockPos pos) {
this.pos = pos;
this.relative = false;
return this;
}
public Builder ratio(float ratio) {
this.ratio = ratio;
this.relative = true;
return this;
}
public Builder landing(int landing) {
this.landing = landing;
return this;
}
public Transit build() {
return new Transit(itemId, from, to, goesUpwards, yLimit, pos, relative, ratio, landing);
}
}
}
| 28.526087 | 199 | 0.656912 |
110d15cfbcb3f325d48c5264e4d6e25f4bf7e267 | 2,043 | /*
* 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 org.apache.tools.ant.taskdefs;
import java.io.File;
import org.apache.tools.ant.BuildFileTest;
/**
*/
public class AbstractCvsTaskTest extends BuildFileTest {
public AbstractCvsTaskTest() {
this( "AbstractCvsTaskTest" );
}
public AbstractCvsTaskTest(String name) {
super(name);
}
public void setUp() {
configureProject("src/etc/testcases/taskdefs/abstractcvstask.xml");
}
public void tearDown() {
executeTarget("cleanup");
}
public void testAbstractCvsTask() {
executeTarget( "all" );
}
public void testPackageAttribute() {
File f = getProject().resolveFile("tmpdir/ant/build.xml");
assertTrue("starting empty", !f.exists());
expectLogContaining("package-attribute", "U ant/build.xml");
assertTrue("now it is there", f.exists());
}
public void testTagAttribute() {
File f = getProject().resolveFile("tmpdir/ant/build.xml");
assertTrue("starting empty", !f.exists());
expectLogContaining("tag-attribute", "ANT_141 (revision: 1.175.2.13)");
assertTrue("now it is there", f.exists());
}
}
| 32.951613 | 80 | 0.659814 |
45ae73665be244d68a033be1e68ab888995530a4 | 1,357 | package com.example.subhasis.spy;
/**
* Created by Subhasis on 26-09-2017.
*/
import android.app.Service;
import android.content.*;
import android.os.*;
import android.widget.Toast;
public class BackgroundService extends Service {
public Context context = this;
public Handler handler = null;
public static Runnable runnable = null;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
handler = new Handler();
runnable = new Runnable() {
public void run() {
Toast.makeText(context, "Service is still running", Toast.LENGTH_LONG).show();
handler.postDelayed(runnable, 10000);
}
};
handler.postDelayed(runnable, 15000);
}
@Override
public void onDestroy() {
/* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */
//handler.removeCallbacks(runnable);
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
}
} | 27.693878 | 95 | 0.614591 |
d5f3795b0765cd866a2c48f3800d2e19725da6d1 | 249 | package com.flagship.design.pattern.structural.decorator.v2;
/**
* @Author Flagship
* @Date 2020/11/13 12:32
* @Description
*/
public abstract class ABatterCake {
protected abstract String getDesc();
protected abstract int cost();
}
| 16.6 | 60 | 0.710843 |
885d51aec2044bd1d931a729bde9b9cf623ad0f9 | 9,384 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.google.android.gms.wearable;
public final class R {
public static final class attr {
public static final int ambientEnabled = 0x7f010013;
public static final int cameraBearing = 0x7f010004;
public static final int cameraTargetLat = 0x7f010005;
public static final int cameraTargetLng = 0x7f010006;
public static final int cameraTilt = 0x7f010007;
public static final int cameraZoom = 0x7f010008;
public static final int circleCrop = 0x7f010002;
public static final int imageAspectRatio = 0x7f010001;
public static final int imageAspectRatioAdjust = 0x7f010000;
public static final int liteMode = 0x7f010009;
public static final int mapType = 0x7f010003;
public static final int uiCompass = 0x7f01000a;
public static final int uiMapToolbar = 0x7f010012;
public static final int uiRotateGestures = 0x7f01000b;
public static final int uiScrollGestures = 0x7f01000c;
public static final int uiTiltGestures = 0x7f01000d;
public static final int uiZoomControls = 0x7f01000e;
public static final int uiZoomGestures = 0x7f01000f;
public static final int useViewLifecycle = 0x7f010010;
public static final int zOrderOnTop = 0x7f010011;
}
public static final class color {
public static final int common_action_bar_splitter = 0x7f050004;
public static final int common_signin_btn_dark_text_default = 0x7f050005;
public static final int common_signin_btn_dark_text_disabled = 0x7f050006;
public static final int common_signin_btn_dark_text_focused = 0x7f050007;
public static final int common_signin_btn_dark_text_pressed = 0x7f050008;
public static final int common_signin_btn_default_background = 0x7f050009;
public static final int common_signin_btn_light_text_default = 0x7f05000a;
public static final int common_signin_btn_light_text_disabled = 0x7f05000b;
public static final int common_signin_btn_light_text_focused = 0x7f05000c;
public static final int common_signin_btn_light_text_pressed = 0x7f05000d;
public static final int common_signin_btn_text_dark = 0x7f05000e;
public static final int common_signin_btn_text_light = 0x7f05000f;
}
public static final class drawable {
public static final int common_full_open_on_phone = 0x7f020002;
public static final int common_ic_googleplayservices = 0x7f020003;
public static final int common_signin_btn_icon_dark = 0x7f020004;
public static final int common_signin_btn_icon_disabled_dark = 0x7f020005;
public static final int common_signin_btn_icon_disabled_focus_dark = 0x7f020006;
public static final int common_signin_btn_icon_disabled_focus_light = 0x7f020007;
public static final int common_signin_btn_icon_disabled_light = 0x7f020008;
public static final int common_signin_btn_icon_focus_dark = 0x7f020009;
public static final int common_signin_btn_icon_focus_light = 0x7f02000a;
public static final int common_signin_btn_icon_light = 0x7f02000b;
public static final int common_signin_btn_icon_normal_dark = 0x7f02000c;
public static final int common_signin_btn_icon_normal_light = 0x7f02000d;
public static final int common_signin_btn_icon_pressed_dark = 0x7f02000e;
public static final int common_signin_btn_icon_pressed_light = 0x7f02000f;
public static final int common_signin_btn_text_dark = 0x7f020010;
public static final int common_signin_btn_text_disabled_dark = 0x7f020011;
public static final int common_signin_btn_text_disabled_focus_dark = 0x7f020012;
public static final int common_signin_btn_text_disabled_focus_light = 0x7f020013;
public static final int common_signin_btn_text_disabled_light = 0x7f020014;
public static final int common_signin_btn_text_focus_dark = 0x7f020015;
public static final int common_signin_btn_text_focus_light = 0x7f020016;
public static final int common_signin_btn_text_light = 0x7f020017;
public static final int common_signin_btn_text_normal_dark = 0x7f020018;
public static final int common_signin_btn_text_normal_light = 0x7f020019;
public static final int common_signin_btn_text_pressed_dark = 0x7f02001a;
public static final int common_signin_btn_text_pressed_light = 0x7f02001b;
public static final int powered_by_google_dark = 0x7f02001c;
public static final int powered_by_google_light = 0x7f02001d;
}
public static final class id {
public static final int adjust_height = 0x7f060001;
public static final int adjust_width = 0x7f060002;
public static final int hybrid = 0x7f060004;
public static final int none = 0x7f060003;
public static final int normal = 0x7f060005;
public static final int satellite = 0x7f060006;
public static final int terrain = 0x7f060007;
}
public static final class integer {
public static final int google_play_services_version = 0x7f070000;
}
public static final class raw {
}
public static final class string {
public static final int auth_google_play_services_client_facebook_display_name = 0x7f04001e;
public static final int auth_google_play_services_client_google_display_name = 0x7f04001f;
public static final int common_android_wear_notification_needs_update_text = 0x7f040000;
public static final int common_android_wear_update_text = 0x7f040001;
public static final int common_android_wear_update_title = 0x7f040002;
public static final int common_google_play_services_api_unavailable_text = 0x7f040003;
public static final int common_google_play_services_enable_button = 0x7f040004;
public static final int common_google_play_services_enable_text = 0x7f040005;
public static final int common_google_play_services_enable_title = 0x7f040006;
public static final int common_google_play_services_error_notification_requested_by_msg = 0x7f040007;
public static final int common_google_play_services_install_button = 0x7f040008;
public static final int common_google_play_services_install_text_phone = 0x7f040009;
public static final int common_google_play_services_install_text_tablet = 0x7f04000a;
public static final int common_google_play_services_install_title = 0x7f04000b;
public static final int common_google_play_services_invalid_account_text = 0x7f04000c;
public static final int common_google_play_services_invalid_account_title = 0x7f04000d;
public static final int common_google_play_services_needs_enabling_title = 0x7f04000e;
public static final int common_google_play_services_network_error_text = 0x7f04000f;
public static final int common_google_play_services_network_error_title = 0x7f040010;
public static final int common_google_play_services_notification_needs_update_title = 0x7f040011;
public static final int common_google_play_services_notification_ticker = 0x7f040012;
public static final int common_google_play_services_sign_in_failed_text = 0x7f040013;
public static final int common_google_play_services_sign_in_failed_title = 0x7f040014;
public static final int common_google_play_services_unknown_issue = 0x7f040015;
public static final int common_google_play_services_unsupported_text = 0x7f040016;
public static final int common_google_play_services_unsupported_title = 0x7f040017;
public static final int common_google_play_services_update_button = 0x7f040018;
public static final int common_google_play_services_update_text = 0x7f040019;
public static final int common_google_play_services_update_title = 0x7f04001a;
public static final int common_google_play_services_updating_text = 0x7f04001b;
public static final int common_google_play_services_updating_title = 0x7f04001c;
public static final int common_open_on_phone = 0x7f04001d;
public static final int common_signin_button_text = 0x7f040020;
public static final int common_signin_button_text_long = 0x7f040021;
}
public static final class style {
}
public static final class styleable {
public static final int[] LoadingImageView = { 0x7f010000, 0x7f010001, 0x7f010002 };
public static final int LoadingImageView_circleCrop = 2;
public static final int LoadingImageView_imageAspectRatio = 1;
public static final int LoadingImageView_imageAspectRatioAdjust = 0;
public static final int[] MapAttrs = { 0x7f010003, 0x7f010004, 0x7f010005, 0x7f010006, 0x7f010007, 0x7f010008, 0x7f010009, 0x7f01000a, 0x7f01000b, 0x7f01000c, 0x7f01000d, 0x7f01000e, 0x7f01000f, 0x7f010010, 0x7f010011, 0x7f010012, 0x7f010013 };
public static final int MapAttrs_ambientEnabled = 16;
public static final int MapAttrs_cameraBearing = 1;
public static final int MapAttrs_cameraTargetLat = 2;
public static final int MapAttrs_cameraTargetLng = 3;
public static final int MapAttrs_cameraTilt = 4;
public static final int MapAttrs_cameraZoom = 5;
public static final int MapAttrs_liteMode = 6;
public static final int MapAttrs_mapType = 0;
public static final int MapAttrs_uiCompass = 7;
public static final int MapAttrs_uiMapToolbar = 15;
public static final int MapAttrs_uiRotateGestures = 8;
public static final int MapAttrs_uiScrollGestures = 9;
public static final int MapAttrs_uiTiltGestures = 10;
public static final int MapAttrs_uiZoomControls = 11;
public static final int MapAttrs_uiZoomGestures = 12;
public static final int MapAttrs_useViewLifecycle = 13;
public static final int MapAttrs_zOrderOnTop = 14;
}
}
| 61.333333 | 246 | 0.831628 |
e10927b5e890df8ac18da0193b69725bba7abb80 | 1,260 | package net.bytebuddy.implementation.bytecode.assign.reference;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
/**
* A simple assigner that is capable of handling the casting of reference types. Primitives can only be assigned to
* each other if they represent the same type.
*/
public enum ReferenceTypeAwareAssigner implements Assigner {
/**
* The singleton instance.
*/
INSTANCE;
@Override
public StackManipulation assign(TypeDescription.Generic source, TypeDescription.Generic target, Typing typing) {
if (source.isPrimitive() || target.isPrimitive()) {
return source.equals(target)
? StackManipulation.Trivial.INSTANCE
: StackManipulation.Illegal.INSTANCE;
} else if (source.asErasure().isAssignableTo(target.asErasure())) {
return StackManipulation.Trivial.INSTANCE;
} else if (typing.isDynamic()) {
return TypeCasting.to(target);
} else {
return StackManipulation.Illegal.INSTANCE;
}
}
}
| 36 | 116 | 0.703968 |
cd350deb2a28a0a0e655f53b0f8982db444d27df | 1,319 | package cn.javava.weixin.oauth2;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.web.util.UriComponentsBuilder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class OAuth2ClientAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
if (authException != null) {
authException.printStackTrace();
}
UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
builder.scheme("https").host("open.weixin.qq.com").port(443).path("/connect/oauth2/authorize");
builder.queryParam("appid", "wxfe19480979014ade");
builder.queryParam("redirect_uri", "http://zhifu.javava.cn/zhifu/login");
builder.queryParam("response_type", "code");
builder.queryParam("scope", "snsapi_userinfo");
builder.queryParam("state", "");
builder.fragment("wechat_redirect");
response.sendRedirect(builder.toUriString());
}
}
| 43.966667 | 160 | 0.753601 |
3b6e64a814330e4ddac59192a7eb638e17461ad6 | 233 | package com.mmx.myshop.admin.dao;
import com.mmx.myshop.domain.TbUser;
import org.springframework.stereotype.Repository;
@Repository
public interface TbUserDao extends BaseDao<TbUser>{
TbUser getAdminByemail(String email);
}
| 19.416667 | 51 | 0.802575 |
98ff31980ad98adc3f1c19170b6194c5c4279357 | 2,102 | package httpfaultinjectorclient;
import java.net.URI;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;
import reactor.netty.http.client.HttpClientResponse;
public class App {
private static String _scheme = "http";
private static String _host = "localhost";
private static int _port = 7777;
public static void main(String[] args) throws Exception {
HttpClient httpClient = HttpClient.create();
// When using HTTPS to the fault injector, you must either add the .NET developer certificate to the Java cacerts keystore,
// or uncomment the following lines to disable SSL validation.
//
// io.netty.handler.ssl.SslContext sslContext = io.netty.handler.ssl.SslContextBuilder
// .forClient().trustManager(io.netty.handler.ssl.util.InsecureTrustManagerFactory.INSTANCE).build();
// httpClient = httpClient.secure(sslContextBuilder -> sslContextBuilder.sslContext(sslContext));
System.out.println("Sending request...");
HttpClientResponse response = get(httpClient, "https://www.example.org").block();
System.out.println(response.status());
}
private static Mono<HttpClientResponse> get(HttpClient httpClient, String uri) throws Exception {
URI upstream = new URI(uri);
URI upstreamBase = new URI(
upstream.getScheme(),
upstream.getUserInfo(),
upstream.getHost(),
upstream.getPort(),
null,
null,
null);
URI faultInjector = new URI(
_scheme,
upstream.getUserInfo(),
_host,
_port,
upstream.getPath(),
upstream.getQuery(),
upstream.getFragment());
return httpClient
// Set "X-Upstream-Base-Uri" header to upstream host
.headers(headers -> headers.add("X-Upstream-Base-Uri", upstreamBase.toString()))
.get()
// Set URI to fault injector
.uri(faultInjector.toString())
.response();
}
}
| 34.459016 | 131 | 0.630828 |
85fa504b1148ae7012b91ce2404e8481c89b7f17 | 3,060 | package org.junit.platform.console.options;
import eu.cqse.teamscale.client.CommitDescriptor;
import org.junit.platform.console.shadow.joptsimple.OptionParser;
import org.junit.platform.console.shadow.joptsimple.OptionSet;
import org.junit.platform.console.shadow.joptsimple.OptionSpec;
import static java.util.Arrays.asList;
/** Helper class to parse command line options. */
public class AvailableImpactedTestsExecutorCommandLineOptions {
/** Available options from jUnit */
private AvailableOptions jUnitOptions;
/** Holds the command line parser with the standard jUnit options and ours. */
private final OptionParser parser;
/** Teamscale server options */
private final OptionSpec<String> url;
private final OptionSpec<String> project;
private final OptionSpec<String> userName;
private final OptionSpec<String> userAccessToken;
private final OptionSpec<String> partition;
private final OptionSpec<String> baseline;
private final OptionSpec<String> end;
private final OptionSpec<Void> runAllTests;
/** Constructor. */
AvailableImpactedTestsExecutorCommandLineOptions() {
jUnitOptions = new AvailableOptions();
parser = jUnitOptions.getParser();
url = parser.accepts("url",
"Url of the teamscale server")
.withRequiredArg();
project = parser.accepts("project",
"Project ID of the teamscale project")
.withRequiredArg();
userName = parser.accepts("user",
"The user name in teamscale")
.withRequiredArg();
userAccessToken = parser.accepts("access-token",
"The users access token for Teamscale")
.withRequiredArg();
partition = parser.accepts("partition",
"Partition of the tests")
.withRequiredArg();
baseline = parser.accepts("baseline",
"The baseline commit")
.withRequiredArg();
end = parser.accepts("end",
"The end commit")
.withRequiredArg();
runAllTests = parser.acceptsAll(asList("all", "run-all-tests"),
"Partition of the tests");
}
/** Returns an options parser with the available options set. */
public OptionParser getParser() {
return parser;
}
/** Converts the parsed parameters into a {@link ImpactedTestsExecutorCommandLineOptions} object. */
public ImpactedTestsExecutorCommandLineOptions toCommandLineOptions(OptionSet detectedOptions) {
CommandLineOptions jUnitResult = jUnitOptions.toCommandLineOptions(detectedOptions);
ImpactedTestsExecutorCommandLineOptions result = new ImpactedTestsExecutorCommandLineOptions(jUnitResult);
result.server.url = detectedOptions.valueOf(this.url);
result.server.project = detectedOptions.valueOf(this.project);
result.server.userName = detectedOptions.valueOf(this.userName);
result.server.userAccessToken = detectedOptions.valueOf(this.userAccessToken);
result.partition = detectedOptions.valueOf(this.partition);
result.runAllTests = detectedOptions.has(this.runAllTests);
result.baseline = CommitDescriptor.parse(detectedOptions.valueOf(this.baseline));
result.endCommit = CommitDescriptor.parse(detectedOptions.valueOf(this.end));
return result;
}
}
| 33.26087 | 108 | 0.769935 |
9fddb7d247aae54067b12bc00b8d6ff22200bf19 | 1,241 | /*
* Copyright (c) 2019 Bixbit - Krzysztof Benedyczak. All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.types.authn;
import java.util.Objects;
/**
* Describes authenticator configuration.
*
* @author P.Piernik
*
*/
public class AuthenticatorDefinition
{
public final String id;
public final String type;
public final String configuration;
public final String localCredentialName;
public AuthenticatorDefinition(String id, String type, String configuration, String localCredentialName)
{
this.id = id;
this.type = type;
this.configuration = configuration;
this.localCredentialName = localCredentialName;
}
@Override
public int hashCode()
{
return Objects.hash(id, localCredentialName, type, configuration);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AuthenticatorDefinition other = (AuthenticatorDefinition) obj;
return Objects.equals(id, other.id) && Objects.equals(localCredentialName, other.localCredentialName)
&& Objects.equals(type, other.type)
&& Objects.equals(configuration, other.configuration);
}
}
| 23.865385 | 105 | 0.736503 |
c5c4349f7b784e7ea1a5c7a34961d0dc9ba07efd | 3,206 | /**
* Copyright (C) 2018 Jeebiz (http://jeebiz.net).
* All Rights Reserved.
*/
package net.jeebiz.admin.authz.rbac0.web.dto;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@ApiModel(value = "AuthzUserProfileDTO", description = "用户描述信息DTO")
@Getter
@Setter
@ToString
public class AuthzUserProfileDTO {
/**
* 用户详情Id
*/
@ApiModelProperty(name = "id", dataType = "String", value = "用户详情Id")
private String id;
/**
* 用户别名(昵称)
*/
@ApiModelProperty(name = "nickname", dataType = "String", value = "用户昵称")
private String nickname;
/**
* 用户头像:图片路径或图标样式
*/
@ApiModelProperty(name = "avatar", dataType = "String", value = "用户头像:图片路径或图标样式")
private String avatar;
/**
* 手机号码国家码
*/
@ApiModelProperty(name = "countryCode", dataType = "String", value = "手机号码国家码")
private String countryCode;
/**
* 手机号码
*/
@ApiModelProperty(name = "phone", dataType = "String", value = "手机号码")
private String phone;
/**
* 性别:(M:男,F:女)
*/
@ApiModelProperty(name = "gender", dataType = "String", value = "性别:(M:男,F:女)")
private String gender;
/**
* 电子邮箱
*/
@ApiModelProperty(name = "email", dataType = "String", value = "电子邮箱")
private String email;
/**
* 出生日期
*/
@ApiModelProperty(name = "birthday", dataType = "String", value = "出生日期")
private String birthday;
/**
* 身份证号码
*/
@ApiModelProperty(name = "idcard", dataType = "String", value = "身份证号码")
private String idcard;
/**
* 用户年龄
*/
@ApiModelProperty(name = "age", dataType = "Integer", value = "用户年龄")
private int age;
/**
*用户身高
*/
@ApiModelProperty(name = "height", dataType = "String", value = "用户身高")
protected String height;
/**
*用户体重
*/
@ApiModelProperty(name = "weight", dataType = "String", value = "用户体重")
protected String weight;
/**
* 官方语言
*/
@ApiModelProperty(name = "language", dataType = "String", value = "官方语言")
private String language;
/**
* 用户简介
*/
@ApiModelProperty(name = "intro", dataType = "String", value = "用户简介")
private String intro;
/**
* 个人照片(包含是否封面标记、序号、地址的JSON对象)
*/
@ApiModelProperty(name = "photos", dataType = "com.alibaba.fastjson.JSONArray", value = "个人照片(包含是否封面标记、序号、地址的JSON对象)")
private JSONArray photos;
/**
* 用户位置:常驻省份
*/
@ApiModelProperty(name = "province", dataType = "String", value = "用户位置:常驻省份")
private String province;
/**
* 用户位置:常驻城市
*/
@ApiModelProperty(name = "city", dataType = "String", value = "用户位置:常驻城市")
private String city;
/**
* 用户位置:常驻区域
*/
@ApiModelProperty(name = "area", dataType = "String", value = "用户位置:常驻区域")
private String area;
/**
* 用户位置:常驻地经度
*/
@ApiModelProperty(name = "longitude", dataType = "Double", value = "用户位置:常驻地经度")
private double longitude;
/**
* 用户位置:常驻地纬度
*/
@ApiModelProperty(name = "latitude", dataType = "Double", value = "用户位置:常驻地纬度")
private double latitude;
/**
*用户信息完成度
*/
@ApiModelProperty(name = "degree", dataType = "Integer", value = "用户信息完成度")
private int degree;
/**
* 初始化时间
*/
@ApiModelProperty(name = "time24", dataType = "String", value = "初始化时间")
private String time24;
}
| 24.105263 | 119 | 0.653774 |
967b44387c365414ed800044c8701f1d7f6bb8ce | 1,517 | package com.sequenceiq.cloudbreak.converter.v4.connectors;
import java.util.HashSet;
import java.util.Set;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.api.endpoint.v4.connector.responses.EncryptionKeyConfigV4Response;
import com.sequenceiq.cloudbreak.api.endpoint.v4.connector.responses.PlatformEncryptionKeysV4Response;
import com.sequenceiq.cloudbreak.cloud.model.CloudEncryptionKey;
import com.sequenceiq.cloudbreak.cloud.model.CloudEncryptionKeys;
import com.sequenceiq.cloudbreak.converter.AbstractConversionServiceAwareConverter;
@Component
public class CloudEncryptionKeysToPlatformEncryptionKeysV4ResponseConverter
extends AbstractConversionServiceAwareConverter<CloudEncryptionKeys, PlatformEncryptionKeysV4Response> {
@Override
public PlatformEncryptionKeysV4Response convert(CloudEncryptionKeys source) {
PlatformEncryptionKeysV4Response platformEncryptionKeysV4Response = new PlatformEncryptionKeysV4Response();
Set<EncryptionKeyConfigV4Response> result = new HashSet<>();
for (CloudEncryptionKey entry : source.getCloudEncryptionKeys()) {
EncryptionKeyConfigV4Response actual =
new EncryptionKeyConfigV4Response(entry.getName(), entry.getId(), entry.getDescription(), entry.getDisplayName(), entry.getProperties());
result.add(actual);
}
platformEncryptionKeysV4Response.setEncryptionKeyConfigs(result);
return platformEncryptionKeysV4Response;
}
}
| 48.935484 | 157 | 0.805537 |
97d5058092e81ed2c4a7dd760afb99c5183a55d5 | 1,846 | /*
* 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 org.tomato.study.rpc.core.data;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* 注册中心配置
* @author Tomato
* Created on 2021.09.27
*/
@Getter
@AllArgsConstructor
public class NameServerConfig {
/**
* 注册中心的地址
*/
private final String connString;
/**
* 注册中心编解码
*/
private final Charset charset;
/**
* 当前RPC node的环境,name server会订阅同环境的其余provider
*/
private final String stage;
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String connString;
private Charset charset = StandardCharsets.UTF_8;
private String stage = "default";
public Builder connString(String connString) {
this.connString = connString;
return this;
}
public Builder charset(Charset charset) {
this.charset = charset;
return this;
}
public Builder stage(String stage) {
this.stage = stage;
return this;
}
public NameServerConfig build() {
return new NameServerConfig(connString, charset, stage);
}
}
}
| 24.289474 | 76 | 0.646262 |
e315c6bf7963bf56676311a4accace68fe21c3ac | 2,820 | package com.pg85.otg.customobjects.bofunctions;
import com.pg85.otg.configuration.customobjects.CustomObjectConfigFile;
import com.pg85.otg.configuration.customobjects.CustomObjectConfigFunction;
import com.pg85.otg.exception.InvalidConfigException;
import java.util.List;
/**
* Represents a block in a BO3.
*/
public abstract class ParticleFunction<T extends CustomObjectConfigFile> extends CustomObjectConfigFunction<T>
{
public int y;
public Boolean firstSpawn = true;
public String particleName = "";
public double interval = 1;
public double intervalOffset = 0;
public double velocityX = 0;
public double velocityY = 0;
public double velocityZ = 0;
public boolean velocityXSet = false;
public boolean velocityYSet = false;
public boolean velocityZSet = false;
@Override
public void load(List<String> args) throws InvalidConfigException
{
assureSize(5, args);
// Those limits are arbitrary, LocalWorld.setBlock will limit it
// correctly based on what chunks can be accessed
x = readInt(args.get(0), -100, 100);
y = readInt(args.get(1), -1000, 1000);
z = readInt(args.get(2), -100, 100);
particleName = args.get(3);
interval = readDouble(args.get(4), 0, Integer.MAX_VALUE);
if(args.size() > 5)
{
velocityX = readDouble(args.get(5), Integer.MIN_VALUE, Integer.MAX_VALUE);
velocityXSet = true;
}
if(args.size() > 6)
{
velocityY = readDouble(args.get(6), Integer.MIN_VALUE, Integer.MAX_VALUE);
velocityYSet = true;
}
if(args.size() > 7)
{
velocityZ = readDouble(args.get(7), Integer.MIN_VALUE, Integer.MAX_VALUE);
velocityZSet = true;
}
}
@Override
public String makeString()
{
return "Particle(" + x + ',' + y + ',' + z + ',' + particleName + ',' + interval + ',' + velocityX + ',' + velocityY + ',' + velocityZ + ')';
}
public String makeStringForPacket()
{
return "Particle(" + x + ',' + y + ',' + z + ',' + particleName + ',' + interval + ',' + velocityX + ',' + velocityY + ',' + velocityZ + ',' + velocityXSet + ',' + velocityYSet + ',' + velocityZSet + ')';
}
@Override
public boolean isAnalogousTo(CustomObjectConfigFunction<T> other)
{
if(!getClass().equals(other.getClass()))
{
return false;
}
ParticleFunction<T> block = (ParticleFunction<T>) other;
return block.x == x && block.y == y && block.z == z && block.particleName.equalsIgnoreCase(particleName) && block.interval == interval && block.velocityX == velocityX && block.velocityY == velocityY && block.velocityZ == velocityZ;
}
public abstract ParticleFunction<T> getNewInstance();
}
| 33.571429 | 239 | 0.625887 |
4387e389bf3ed194334795bcde5169c6b261206a | 3,648 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.iflytek.skintest;
public final class R {
public static final class attr {
}
public static final class color {
public static final int background=0x7f040001;
public static final int background_dark=0x7f040002;
public static final int btn_color=0x7f040003;
public static final int btn_color_dark=0x7f040004;
public static final int window_background=0x7f040000;
}
public static final class dimen {
public static final int font_size=0x7f050000;
public static final int font_size_dark=0x7f050001;
public static final int font_size_large=0x7f050002;
public static final int font_size_large_dark=0x7f050003;
}
public static final class drawable {
public static final int btn_background=0x7f020000;
public static final int btn_background_dark=0x7f020001;
public static final int btn_normal=0x7f020002;
public static final int btn_normal_dark=0x7f020003;
public static final int btn_pressed=0x7f020004;
public static final int btn_pressed_dark=0x7f020005;
public static final int ic_launcher=0x7f020006;
}
public static final class id {
public static final int button_num_edit=0x7f090007;
public static final int button_num_setting=0x7f090008;
public static final int enable_async_load_skin=0x7f090005;
public static final int feature_area=0x7f090006;
public static final int load_dark_skin=0x7f090002;
public static final int load_plugin_skin=0x7f090003;
public static final int load_white_skin=0x7f090001;
public static final int root=0x7f090000;
public static final int start_new_activity=0x7f090004;
}
public static final class integer {
public static final int brightness_dark=0x7f060000;
}
public static final class layout {
public static final int activity_home=0x7f030000;
public static final int activity_setting=0x7f030001;
}
public static final class string {
public static final int app_name=0x7f070000;
public static final int button_num_setting=0x7f07000d;
public static final int changing_skin=0x7f07000e;
public static final int disable_async_load_skin=0x7f07000b;
public static final int disabled_feature=0x7f070013;
public static final int dynamic_button=0x7f07000f;
public static final int enable_async_load_skin=0x7f07000a;
public static final int enabled_feature=0x7f070012;
public static final int feature_hint=0x7f070010;
public static final int load_dark_skin=0x7f070004;
public static final int load_dark_skin_dark=0x7f070005;
public static final int load_default_skin=0x7f070006;
public static final int load_plugin_skin=0x7f070007;
public static final int load_plugin_skin_dark=0x7f070008;
public static final int load_white_skin=0x7f070002;
public static final int load_white_skin_dark=0x7f070003;
public static final int performance_test_hint=0x7f070011;
public static final int skin_configuration=0x7f070009;
public static final int time_usage=0x7f070014;
public static final int title_activity_home=0x7f070001;
public static final int title_activity_setting=0x7f07000c;
}
public static final class style {
public static final int CustomTheme=0x7f080000;
}
}
| 45.6 | 67 | 0.733827 |
e33bdb2730dd7efbf477a6e1a4e56102ea402f28 | 3,400 | /*
*************************************************************************
* The contents of this file are subject to the Openbravo Public License
* Version 1.1 (the "License"), being the Mozilla Public License
* Version 1.1 with a permitted attribution clause; you may not use this
* file except in compliance with the License. You may obtain a copy of
* the License at http://www.openbravo.com/legal/license.html
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
* The Original Code is Openbravo ERP.
* The Initial Developer of the Original Code is Openbravo SLU
* All portions are Copyright (C) 2016 Openbravo SLU
* All Rights Reserved.
* Contributor(s): ______________________________________.
************************************************************************
*/
package org.openbravo.client.application.attachment;
import javax.servlet.ServletException;
import org.apache.axis.utils.StringUtils;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.openbravo.base.filter.IsIDFilter;
import org.openbravo.base.weld.WeldUtils;
import org.openbravo.client.application.Parameter;
import org.openbravo.client.application.window.ApplicationDictionaryCachedStructures;
import org.openbravo.dal.service.OBCriteria;
import org.openbravo.dal.service.OBDal;
import org.openbravo.erpCommon.ad_callouts.SimpleCallout;
import org.openbravo.model.ad.ui.Tab;
import org.openbravo.model.ad.utility.AttachmentMethod;
/**
* Callout executed only on Metadata Tab of "Windows, Tabs and Fields" window. It calculates the
* Sequence Number to set on the new metadata when the Attachment Method is selected.
*/
public class MetadataOnTab extends SimpleCallout {
private static final String WINDOWTABSFIELDS_WINDOW_ID = "102";
@Override
protected void execute(CalloutInfo info) throws ServletException {
final String windowId = info.getWindowId();
if (!WINDOWTABSFIELDS_WINDOW_ID.equals(windowId)) {
return;
}
final String methodId = info.getStringParameter("inpcAttachmentMethodId", IsIDFilter.instance);
final String tabId = info.getStringParameter("inpadTabId", IsIDFilter.instance);
if (StringUtils.isEmpty(methodId)) {
info.addResult("inpseqno", "");
} else {
int seqNo = getNextSeqNo(methodId, tabId);
info.addResult("inpseqno", seqNo);
}
}
private int getNextSeqNo(String methodId, String tabId) {
ApplicationDictionaryCachedStructures adcs = WeldUtils
.getInstanceFromStaticBeanManager(ApplicationDictionaryCachedStructures.class);
AttachmentMethod attMethod = OBDal.getInstance().get(AttachmentMethod.class, methodId);
Tab tab = adcs.getTab(tabId);
OBCriteria<Parameter> critParam = OBDal.getInstance().createCriteria(Parameter.class);
critParam.add(Restrictions.eq(Parameter.PROPERTY_ATTACHMENTMETHOD, attMethod));
critParam.add(Restrictions.eq(Parameter.PROPERTY_TAB, tab));
critParam.setProjection(Projections.max(Parameter.PROPERTY_SEQUENCENUMBER));
if (critParam.uniqueResult() == null) {
return 10;
}
long maxSeqNo = (Long) critParam.uniqueResult();
return (int) (maxSeqNo + 10);
}
}
| 43.589744 | 99 | 0.73 |
6b96f86c195a9ba6d27263d27215dd7b60884636 | 5,554 | package org.elasticsearch.plugin.analysis.hanlp;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.utility.Predefine;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.elasticsearch.common.io.FileSystemUtils;
import org.elasticsearch.core.PathUtils;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.analysis.AnalyzerProvider;
import org.elasticsearch.index.analysis.HanLPAnalyzerProvider;
import org.elasticsearch.index.analysis.HanLPTokenizerFactory;
import org.elasticsearch.index.analysis.TokenizerFactory;
import org.elasticsearch.indices.analysis.AnalysisModule;
import org.elasticsearch.plugins.AnalysisPlugin;
import org.elasticsearch.plugins.Plugin;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
/**
* Project: elasticsearch-analysis-hanlp
* Description: Hanlp分词插件
* Author: Kenn
* Create: 2018-12-14 15:10
*/
public class AnalysisHanLPPlugin extends Plugin implements AnalysisPlugin {
public static String PLUGIN_NAME = "analysis-hanlp";
private static final Logger logger = LogManager.getLogger(AnalysisHanLPPlugin.class);
/**
* Hanlp配置文件名
*/
private static final String CONFIG_FILE_NAME = "hanlp.properties";
public AnalysisHanLPPlugin(Settings settings) {
String home = null;
if (Environment.PATH_HOME_SETTING.exists(settings)) {
home = Environment.PATH_HOME_SETTING.get(settings);
}
if (home == null) {
throw new IllegalStateException(Environment.PATH_HOME_SETTING.getKey() + " is not configured");
} else {
Path configDir = PathUtils.get(home, "config", AnalysisHanLPPlugin.PLUGIN_NAME);
Predefine.HANLP_PROPERTIES_PATH = configDir.resolve(CONFIG_FILE_NAME).toString();
logger.debug("hanlp properties path: {}", Predefine.HANLP_PROPERTIES_PATH);
}
}
@Override
public Map<String, AnalysisModule.AnalysisProvider<TokenizerFactory>> getTokenizers() {
Map<String, AnalysisModule.AnalysisProvider<TokenizerFactory>> extra = new HashMap<>();
extra.put("hanlp", HanLPTokenizerFactory::getHanLPTokenizerFactory);
extra.put("hanlp_standard", HanLPTokenizerFactory::getHanLPStandardTokenizerFactory);
extra.put("hanlp_index", HanLPTokenizerFactory::getHanLPIndexTokenizerFactory);
if (FileSystemUtils.exists(Paths.get(
AccessController.doPrivileged((PrivilegedAction<String>) () -> HanLP.Config.PerceptronCWSModelPath)
).toAbsolutePath())) {
extra.put("hanlp_nlp", HanLPTokenizerFactory::getHanLPNLPTokenizerFactory);
} else {
logger.warn("can not find perceptron cws model from [{}], you can not use tokenizer [hanlp_nlp]",
HanLP.Config.PerceptronCWSModelPath);
}
if (FileSystemUtils.exists(Paths.get(
AccessController.doPrivileged((PrivilegedAction<String>) () -> HanLP.Config.CRFCWSModelPath)
).toAbsolutePath())) {
extra.put("hanlp_crf", HanLPTokenizerFactory::getHanLPCRFTokenizerFactory);
} else {
logger.warn("can not find crf cws model from [{}], you can not use tokenizer [hanlp_crf]",
HanLP.Config.CRFCWSModelPath);
}
extra.put("hanlp_n_short", HanLPTokenizerFactory::getHanLPNShortTokenizerFactory);
extra.put("hanlp_dijkstra", HanLPTokenizerFactory::getHanLPDijkstraTokenizerFactory);
extra.put("hanlp_speed", HanLPTokenizerFactory::getHanLPSpeedTokenizerFactory);
return extra;
}
@Override
public Map<String, AnalysisModule.AnalysisProvider<AnalyzerProvider<? extends Analyzer>>> getAnalyzers() {
Map<String, AnalysisModule.AnalysisProvider<AnalyzerProvider<? extends Analyzer>>> extra = new HashMap<>();
extra.put("hanlp", HanLPAnalyzerProvider::getHanLPAnalyzerProvider);
extra.put("hanlp_standard", HanLPAnalyzerProvider::getHanLPStandardAnalyzerProvider);
extra.put("hanlp_index", HanLPAnalyzerProvider::getHanLPIndexAnalyzerProvider);
if (FileSystemUtils.exists(Paths.get(
AccessController.doPrivileged((PrivilegedAction<String>) () -> HanLP.Config.PerceptronCWSModelPath)
).toAbsolutePath())) {
extra.put("hanlp_nlp", HanLPAnalyzerProvider::getHanLPNLPAnalyzerProvider);
} else {
logger.warn("can not find perceptron cws model from [{}], you can not use analyzer [hanlp_nlp]",
HanLP.Config.PerceptronCWSModelPath);
}
if (FileSystemUtils.exists(Paths.get(
AccessController.doPrivileged((PrivilegedAction<String>) () -> HanLP.Config.CRFCWSModelPath)
).toAbsolutePath())) {
extra.put("hanlp_crf", HanLPAnalyzerProvider::getHanLPCRFAnalyzerProvider);
} else {
logger.warn("can not find crf cws model from [{}], you can not use analyzer [hanlp_crf]",
HanLP.Config.CRFCWSModelPath);
}
extra.put("hanlp_n_short", HanLPAnalyzerProvider::getHanLPNShortAnalyzerProvider);
extra.put("hanlp_dijkstra", HanLPAnalyzerProvider::getHanLPDijkstraAnalyzerProvider);
extra.put("hanlp_speed", HanLPAnalyzerProvider::getHanLPSpeedAnalyzerProvider);
return extra;
}
}
| 46.672269 | 115 | 0.71552 |
74b52d3aa13ab77980ccac473a7cffb8895653ab | 20,477 | /*
* ***** BEGIN LICENSE BLOCK *****
*
* Zimbra Collaboration Suite Server
* Copyright (C) 2011 VMware, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
*
* ***** END LICENSE BLOCK *****
*/
/**
* Log.java --
* <p>
* JVM will look for a log config property file, which is used to setup
* log handlers (console, files, etc..), log levels, and log format..
* It will look first at the command line
*
* -Djava.util.logging.config.file=myConfigFile
*
* if not found then at its default location
*
* JDK_HOME/jre/lib/logging.properties
*
* A very short config file that outputs only to the console would contain
* the following:
*
* handlers=java.util.logging.ConsoleHandler
* java.util.logging.ConsoleHandler.level=FINEST
* java.util.logging.ConsoleHandler.formatter=com.vmware.qalib.LogFormatter
*
* Debug usage:
* - Debug messages -> Level.FINE
* - Exception trace -> Level.FINER
* - Tracing messages -> Level.FINEST
* <p>
*
* @author nguyenc
*/
package com.zimbra.qa.selenium.framework.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.logging.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.ITestResult;
import org.testng.Reporter;
public class Log {
private static IRacetrack racetrack;
private static boolean racetrackWarningLogged;
private static ThreadLocal<String> threadTestCaseId = new InheritableThreadLocal<String>();
private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";
// Flag indicating whether logging should go to the TestNG logger or not.
private static boolean logToTestNg = false;
/**
* Initialize Racetrack functionality
*
* @param url The URL of the Racetrack web service
* @param id The test case id of the test run.
* @deprecated use {@link Log#initRacetrack()} instead.
*/
@Deprecated
public static synchronized void
initializeRacetrack(String url,
String id)
{
racetrack = RacetrackWebservice.getInstance(url, id);
}
/**
* Initialize Racetrack functionality
*
*/
public static synchronized void
initRacetrack()
{
racetrack = RacetrackWebservice.getInstance();
}
/**
* Initialize Racetrack functionality
*
* @param testCaseId
*/
public static synchronized void
initRacetrack(String testCaseId)
{
threadTestCaseId.set(testCaseId);
initRacetrack();
}
/**
* Initialize TestNG logging
*
*/
public static synchronized void
initializeTestNG()
{
logToTestNg = true;
}
/**
* Print a label to the log
*
* * Ex: INFO : [ 1] [:::] ##################
* INFO : [ 1] [:::] # #
* INFO : [ 1] [:::] # Test Cleanup #
* INFO : [ 1] [:::] # #
* INFO : [ 1] [:::] ##################
*
* @param s A label
* @param symbol A symbol to use as border
*/
public static synchronized void
label( String s,
String symbol )
{
label(s, symbol, Integer.MIN_VALUE);
}
/**
* Print a label to the log
*
* * Ex: INFO : [ 1] [:::] ##################
* INFO : [ 1] [:::] # #
* INFO : [ 1] [:::] # Test Cleanup #
* INFO : [ 1] [:::] # #
* INFO : [ 1] [:::] ##################
*
* @param s A label
* @param width Max width
*/
public static synchronized void
label( String s,
int width )
{
label(s, null, width);
}
/**
* Print a label to the log
*
* * Ex: INFO : [ 1] [:::] ##################
* INFO : [ 1] [:::] # #
* INFO : [ 1] [:::] # Test Cleanup #
* INFO : [ 1] [:::] # #
* INFO : [ 1] [:::] ##################
*
* @param s A label
*/
public static synchronized void
label( String s )
{
label(s, null, Integer.MIN_VALUE);
}
/**
* Print a label to the log
*
* * Ex: INFO : [ 1] [:::] ##################
* INFO : [ 1] [:::] # #
* INFO : [ 1] [:::] # Test Cleanup #
* INFO : [ 1] [:::] # #
* INFO : [ 1] [:::] ##################
*
* @param s A label
* @param symbol A symbol to use as border
* @param width Max width
*/
public static synchronized void
label( String s,
String symbol,
int width)
{
final int labelPadding = 6;
final int spacePadding = 4;
final int defaultWidth = 80;
final String _symbol = null == symbol ? "#" : symbol;
final int _width = Integer.MIN_VALUE == width ? defaultWidth : width;
final String colon = ":";
List<String> lines = splitStringByLength(s, _width);
StringBuffer symbols = new StringBuffer();
int i = 0;
int labelLength = s.length() > _width ? _width : s.length();
while(i++ < labelLength + labelPadding){
symbols.append(_symbol);
}
StringBuffer spaces = new StringBuffer(_symbol);
i = 0;
while(i++ < labelLength + spacePadding){
spaces.append(" ");
}
spaces.append(_symbol);
logger.logp(Level.INFO, colon, colon, symbols.toString());
logger.logp(Level.INFO, colon, colon, spaces.toString());
for(String line : lines) {
if(line.length() < labelLength){
int j = line.length();
while (j++ < labelLength){
line += " ";
}
}
logger.logp(Level.INFO, colon, colon, _symbol + " " + line + " "
+ _symbol);
}
logger.logp(Level.INFO, colon, colon, spaces.toString());
logger.logp(Level.INFO, colon, colon, symbols.toString());
}
/**
* Split a string using a max length
*
* @param s A string
* @param len A max length
*
* @return List of strings
*/
public static List<String>
splitStringByLength(String s,
int len)
{
List<String> r = new ArrayList<String>();
int start = 0;
int remain = s.length();
while(remain > len){
String t = s.substring(start, start + len);
r.add(t);
remain -= len;
start += len;
}
r.add(s.substring(start, s.length()));
return r;
}
/**
* Print error messages to the log
*
* @param message
*/
public static synchronized void error( String message )
{
p(Level.SEVERE, message);
}
/**
* Print warning messages to the log
*
* @param message
*/
public static synchronized void warning( String message )
{
p(Level.WARNING, message);
}
/**
* Print info messages to the log
*
* @param message
*/
public static synchronized void info( String message )
{
p(Level.INFO, message);
}
/**
* Print config messages to the log
*
* @param message
*/
public static synchronized void config( String message )
{
p(Level.CONFIG, message);
}
/**
* Print debug messages to the log at FINE level
*
* @param message
*/
public static synchronized void fineDebug( String message )
{
p(Level.FINE, message);
}
/**
* Print debug messages to the log at FINER level
*
* @param message
*/
public static synchronized void finerDebug( String message )
{
p(Level.FINER, message);
}
/**
* Print debug messages to the log at FINEST level
*
* @param message
*/
public static synchronized void finestDebug( String message )
{
p(Level.FINEST, message);
}
/**
* Print exceptions to the log at SEVERE level
*
* @param e
*/
public static synchronized void exception( Exception e )
{
px(Level.SEVERE, e.getMessage(), e);
}
/**
* Get the logger and set log level to ALL, which means listening to
* all log messages
*/
private static final Logger logger =
Logger.getLogger(Log.class.toString());
static
{
logger.setLevel(Level.ALL);
System.setErr(System.out);
if(!System.getProperties().containsKey("java.util.logging.config.file")){
String msg = "No log config file is specified. Setting log level to "
+ "FINEST and log formatter to com.vmware.qalib.LogFormatter";
System.out.println(msg);
for(Handler h : logger.getHandlers()) {
if(h instanceof ConsoleHandler){
h.setLevel(Level.FINEST);
h.setFormatter(new LogFormatter());
}
}
}
// set level of apache httpclient logs to 'error'
System.setProperty("org.apache.commons.logging.Log",
"org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache."
+ "commons.httpclient", "error");
}
/**
* Common wrapper for logp()
* @param level - Log levels
* @param message - Log message
* @param thrown - Caught exception
*/
private static void pc( Level level,
String message,
Throwable thrown )
{
/**
* Figure out the class and method that call logger
*/
Throwable callStack = new Throwable();
StackTraceElement[] locations = callStack.getStackTrace();
String className = "Unknown";
String methodName = "Unknown";
if (null != locations && locations.length >= 3) {
StackTraceElement caller = locations[3];
className = caller.getClassName();
methodName = caller.getMethodName();
}
if (null == thrown) {
logger.logp(level, className, methodName, message);
} else {
logger.logp(level, className, methodName, message, thrown);
}
if (logToTestNg) {
logToTestNg(level.toString(), className, methodName, message);
}
}
/**
* Log message to TestNG reporter
*
* Formats the log information and prints it out.
*
* @param level
* one of the "java.util.logging.Level"s
* @param className
* name of the class printing the message.
* @param methodName
* name of the method printing the message.
* @param message
* message to be printed.
*/
private static void logToTestNg(String level,
String className,
String methodName,
String message)
{
SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateTimeInstance();
df.applyPattern(TIMESTAMP_FORMAT);
String msg = "["
+ df.format(Calendar.getInstance().getTime())
+ " "
+ level.toUpperCase()
+ " "
+ className
+ "."
+ methodName
+ " "
+ Thread.currentThread().getId()
+"] "
+ message;
try {
TestNGLogFileReporter.log(msg);
} catch (IOException e) {
logger.logp(Level.SEVERE, "Log", "logToTestNg",
"Error writing to temporary testng logs: " + e.getMessage());
}
}
/**
* Common wrapper for normal logs
* @param level - Log level
* @param message - Log message
*/
private static void p( Level level,
String message )
{
pc(level, message, null);
}
/**
* Common wrapper that can take exceptions and display their attributes
* @param level - Log level
* @param message - Log message
* @param thrown - exception thrown
*/
private static void px( Level level,
String message,
Throwable thrown )
{
/**
* Print the message and brief description of the exception.
*/
pc(level, message, thrown);
/**
* Redirect printStackTrace to string.
*/
Writer sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
thrown.printStackTrace(pw);
/**
* Print stack trace at SEVERE level.
*/
pc(Level.SEVERE, sw.toString(), null);
}
/**
* Log a comment in Racetrack
*
* @param msg a string to be logged in racetrack.
* @deprecated use {@link Log#racetrackComment(String)} instead.
*/
@Deprecated
public static void
commentToRacetrack(String msg)
{
if (null != racetrack) {
try {
racetrack.testCaseComment(msg);
} catch (HarnessException e) {
Log.warning("Failed to log to racetrack.");
Log.warning(e.getMessage());
}
} else {
logRacetrackUnavailableWarning();
}
}
/**
* Log a comment in Racetrack
*
* @param testCaseId
* @param msg a string to be logged in racetrack.
*/
public static void
racetrackComment(String testCaseId, String msg)
{
if (null != racetrack) {
try {
racetrack.testCaseComment(testCaseId, msg);
} catch (HarnessException e) {
Log.warning("Failed to log to racetrack.");
Log.warning(e.getMessage());
}
} else {
logRacetrackUnavailableWarning();
}
}
/**
* Log a racetrack comment to this thread's test result.
*
* @param msg a message string
*/
public static void
racetrackComment(String msg) {
racetrackComment(threadTestCaseId.get(), msg);
}
/**
* Log a verification in Racetrack
*
* @param description a string description.
* @param expected A string representing the expected result of the verification
* @param actual A string representing the actual result of the verification
* @param result "true" if the verification passed.
*/
@Deprecated
public static void
verificationToRacetrack(String description,
String expected,
String actual,
boolean result)
{
if (null != racetrack) {
try {
racetrack.testCaseVerification(description,
actual,
expected,
result);
} catch (HarnessException e) {
Log.warning("Failed to log to racetrack.");
Log.warning(e.getMessage());
}
} else {
logRacetrackUnavailableWarning();
}
}
/**
* Log a verification in Racetrack
*
* @param description a string description.
* @param expected A string representing the expected result of the verification
* @param actual A string representing the actual result of the verification
* @param result "true" if the verification passed.
*/
public static void
racetrackVerification(String testCaseId,
String description,
String expected,
String actual,
boolean result)
{
if (null != racetrack) {
try {
racetrack.testCaseVerification(testCaseId,
description,
actual,
expected,
result);
} catch (HarnessException e) {
Log.warning("Failed to log to racetrack.");
Log.warning(e.getMessage());
}
} else {
logRacetrackUnavailableWarning();
}
}
/**
* Log a verification in Racetrack
*
* @param description a string description.
* @param expected A string representing the expected result of the verification
* @param actual A string representing the actual result of the verification
* @param result "true" if the verification passed.
*/
public static void
racetrackVerification(String description,
String expected,
String actual,
boolean result)
{
racetrackVerification(threadTestCaseId.get(), description, expected, actual, result);
}
/**
* Log a warning to console stating that racetrack reporting is unavailable
*
*/
private static synchronized void
logRacetrackUnavailableWarning()
{
if(!racetrackWarningLogged) {
Log.warning("Racetrack is not initialized. Racetrack logging "+
"will fail.");
racetrackWarningLogged = true;
}
}
public static class LogFormatter extends java.util.logging.Formatter {
/**
* Set the actual format using LOG_TIME_FORMAT from SviConstants.
* @param record - a line of log.
* @return the format.
*/
@Override
public synchronized String
format( LogRecord record )
{
// get a 4 digit thread ID as StringBuilder
StringBuilder sb = new StringBuilder();
java.util.Formatter f = new java.util.Formatter(sb);
f.format("[%4d]", Thread.currentThread().getId());
return " " + record.getLevel()
+ " : "
+ sb.toString()
+ " ["
+ record.getSourceClassName()
+ ":"
+ record.getSourceMethodName()
+ "] "
+ record.getMessage()
+ "\n";
}
}
public static class TestNGLogFileReporter {
private static Map<ITestResult, File> fileMap = Collections.synchronizedMap(new HashMap<ITestResult, File>());
private static Map<ITestResult, Writer> writerMap = Collections.synchronizedMap(new HashMap<ITestResult, Writer>());
/**
* Start logging to a file for the test
*
* This method can be called multiple times for the same test. Subsequent calls
* will be no-ops. This allows for multiple listeners to subscribe to the
* log file.
*
* @param result ITestResult corresponding to the test to log for
* @throws IOException
*/
public static void startLogging(ITestResult result) throws IOException {
if(!fileMap.containsKey(result)) {
File tempLogFile = File.createTempFile("vum-temp-log", ".log");
tempLogFile.deleteOnExit();
fileMap.put(result, tempLogFile);
writerMap.put(result, new BufferedWriter(new FileWriter(tempLogFile)));
}
}
/**
* Log a message for the current thread
*
* @param s Message to be logged
* @throws IOException
*/
public static void log(String s) throws IOException {
ITestResult currentResult = Reporter.getCurrentTestResult();
if(fileMap.containsKey(currentResult) && writerMap.containsKey(currentResult)) {
writerMap.get(currentResult).write(s + "\n");
}
}
/**
* Close the log file at the end of the test
*
* @param result ITestResult for the test that has finished
* @throws IOException
*/
public static void endLogging(ITestResult result) throws IOException {
if(fileMap.containsKey(result) && writerMap.containsKey(result)) {
writerMap.get(result).close();
writerMap.remove(result);
}
}
/**
* Get the log file associated with the given test.
*
* @param result ITestResult for the test to get the log file from
* @return temporary log file
*/
public static File getOutput(ITestResult result) {
return fileMap.get(result);
}
}
}
| 28.519499 | 121 | 0.554036 |
080217c13aeebc8dcfa9b26899837b5f5057e082 | 19,877 | package edu.sc.snacktrack.login;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseRole;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.parse.SignUpCallback;
import edu.sc.snacktrack.main.MainActivity;
import edu.sc.snacktrack.R;
import edu.sc.snacktrack.utils.Utils;
public class NewAccountFragment extends Fragment {
private static final String TAG = "NewAccountDebug";
private static final String STATE_LOGGING_IN = "stateLoggingIn";
private View rootView;
private EditText usernameET;
private EditText passwordET;
private EditText passwordConfirmET;
private TextView usernameErrorStatus;
private TextView passwordMatchStatus;
private TextView passwordRequirementStatus;
private RadioGroup rGroup;
private Button signUpButton;
private Button existingAccountButton;
private Toast toast;
private UsernameErrorStatusUpdater usernameErrorStatusUpdater;
private Context context;
private boolean loggingIn;
private static final PasswordChecker passwordChecker = new PasswordChecker();
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
loggingIn = false;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_new_account, container, false);
// Initialize view fields
rootView = view.findViewById(R.id.newAccountRootView);
usernameET = (EditText) view.findViewById(R.id.usernameEditText);
passwordET = (EditText) view.findViewById(R.id.passwordEditText);
passwordConfirmET = (EditText) view.findViewById(R.id.passwordConfirmEditText);
usernameErrorStatus = (TextView) view.findViewById(R.id.usernameErrorStatus);
passwordMatchStatus = (TextView) view.findViewById(R.id.passwordMatchStatus);
passwordRequirementStatus = (TextView) view.findViewById(R.id.passwordReqTextView);
signUpButton = (Button) view.findViewById(R.id.signUpButton);
rGroup = (RadioGroup) view.findViewById(R.id.signUpRadioGroup);
existingAccountButton = (Button) view.findViewById(R.id.existingAccountButton);
// When the root view gains focus, we should hide the soft keyboard.
rootView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
Utils.closeSoftKeyboard(getContext(), v);
}
}
});
// Set the text watchers
setTextWatchers();
// The existing account link should start the login activity.
existingAccountButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((LoginActivity) getActivity()).existingAccountMode();
}
});
// Attempt to sign the user up when the sign up button is pressed
signUpButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Utils.closeSoftKeyboard(getContext(), v);
attemptSignup();
}
});
setWidgetsEnabled(!loggingIn);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_LOGGING_IN, loggingIn);
}
/**
* Attempts to sign up the new user. If unable to, displays an error message to the user.
* If successful, sets the result to RESULT_OK and finishes this activity.
*/
private void attemptSignup(){
setWidgetsEnabled(false);
loggingIn = true;
final ParseUser newUser = new ParseUser();
String username = usernameET.getText().toString();
String password = passwordET.getText().toString();
String passwordConfirm = passwordConfirmET.getText().toString();
StringBuilder usernameInvalidReason = new StringBuilder();
StringBuilder passwordMatchReason = new StringBuilder();
StringBuilder selectionInvalidReason = new StringBuilder();
if(!isUsernameValid(username, usernameInvalidReason)){
updateToast(usernameInvalidReason.toString(), Toast.LENGTH_LONG);
setWidgetsEnabled(true);
loggingIn = false;
return;
}
if(!doPasswordsMatch(password, passwordConfirm, passwordMatchReason)){
updateToast(passwordMatchReason.toString(), Toast.LENGTH_LONG);
setWidgetsEnabled(true);
loggingIn = false;
return;
}
if(!passwordChecker.meetsRequirements(password)){
updateToast("Password does not meet requirements", Toast.LENGTH_LONG);
setWidgetsEnabled(true);
loggingIn = false;
return;
}
if(!isSelected(selectionInvalidReason)){
updateToast(selectionInvalidReason.toString(), Toast.LENGTH_LONG);
setWidgetsEnabled(true);
loggingIn = false;
return;
}
// If this line is reached, the provided credentials are valid, so we attempt sign up.
newUser.setUsername(username);
newUser.setPassword(password);
String sel = isDietitian();
if(sel.equals("true"))
newUser.put("isDietitian", true);
else
newUser.put("isDietitian", false);
newUser.signUpInBackground(new SignUpCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
// Sign up was successful
ParseRole role = new ParseRole("role_" + newUser.getObjectId());
role.setACL(new ParseACL(newUser));
role.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if(e == null){
startMainActivity();
} else{
updateToast(Utils.getErrorMessage(e), Toast.LENGTH_SHORT);
}
}
});
} else {
updateToast(Utils.getErrorMessage(e), Toast.LENGTH_SHORT);
}
setWidgetsEnabled(true);
loggingIn = false;
}
});
}
/**
* Enables or disables all user input widgets.
*
* @param enabled true to enable; false to disable
*/
private void setWidgetsEnabled(boolean enabled){
usernameET.setEnabled(enabled);
passwordET.setEnabled(enabled);
passwordConfirmET.setEnabled(enabled);
signUpButton.setEnabled(enabled);
//existingAccountLink.setEnabled(enabled);
existingAccountButton.setEnabled(enabled);
}
/**
* Sets the text watchers for each of the EditText views.
*/
private void setTextWatchers(){
// When the contents of the username EditText changes, we check the username.
usernameET.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (usernameErrorStatusUpdater != null) {
usernameErrorStatusUpdater.cancel(true);
}
usernameErrorStatusUpdater = new UsernameErrorStatusUpdater();
usernameErrorStatusUpdater.execute(s.toString());
}
});
// When the contents of the password or passwordConfirm EditText changes, we check the passwords.
passwordET.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String password = passwordET.getText().toString();
String passwordConfirm = passwordConfirmET.getText().toString();
updatePasswordErrorStatus(password, passwordConfirm);
}
});
passwordConfirmET.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String password = passwordET.getText().toString();
String passwordConfirm = passwordConfirmET.getText().toString();
updatePasswordErrorStatus(password, passwordConfirm);
}
});
}
/**
* Checks if a username is valid.
*
* For now, this method applies the following constraints on usernames:
*
* 1. The username cannot be blank
* 2. The username must be alphanumeric (only numbers and letters, no spaces)
*
* This method *does not* check if the username is taken.
*
* @param username The username to check
* @param reason When not null, this method will append the reason the username is invalid
* (or "OK" if the username is valid).
*
* @return true if the username is valid. false otherwise.
*/
private boolean isUsernameValid(String username, @Nullable StringBuilder reason){
if(username.length() == 0){
if(reason != null){
reason.append("Username is blank");
}
return false;
}
// Usernames must be alphanumeric
for(char c : username.toCharArray()){
if(!Character.isLetterOrDigit(c)){
if(reason != null){
reason.append("Username must be alphanumeric");
}
return false;
}
}
if(reason != null){
reason.append("OK");
}
return true;
}
/**
* Checks if a password and its confirmation match
*
* @param password The password
* @param passwordConfirm The confirmed password
* @param reason When not null, this method will append the reason the passwords do not match
* (or "OK" if they do).
* @return true if the passwords match. false otherwise.
*/
private boolean doPasswordsMatch(String password, String passwordConfirm,
@Nullable StringBuilder reason){
if(password.equals("")){
if(reason != null){
reason.append("Password is blank");
}
return false;
}
else if(passwordConfirm.equals("")){
if(reason != null){
reason.append("Password confirm is blank");
}
return false;
}
else if(!password.equals(passwordConfirm)){
if(reason != null){
reason.append("Passwords do not match");
}
return false;
}
else{
if(reason != null){
reason.append("OK");
}
return true;
}
}
private boolean isSelected(@Nullable StringBuilder reason) {
if(rGroup.getCheckedRadioButtonId() == -1) {
if(reason != null)
reason.append("Please pick your user type");
return false;
}
else {
if(reason != null)
reason.append("OK");
return true;
}
}
private String isDietitian() {
RadioButton rb = (RadioButton) rGroup.findViewById(rGroup.getCheckedRadioButtonId());
String selection = (String) rb.getText();
if(selection.equals("Dietitian")) {
Log.i("Testing", "isDietitian = true");
return "true";
}
else {
Log.i("Testing", "isDietitian = false");
return "false";
}
}
/**
* Updates the password error status. That is, displays to the user whether or not the passwords
* match and if the password meets the strength requirements.
*/
private void updatePasswordErrorStatus(String password, String passwordConfirm){
StringBuilder matchProblem = new StringBuilder();
if(doPasswordsMatch(password, passwordConfirm, matchProblem)){
passwordMatchStatus.setTextColor(Color.parseColor("#006600"));
passwordMatchStatus.setText("Passwords match");
} else{
passwordMatchStatus.setTextColor(Color.RED);
passwordMatchStatus.setText(matchProblem.toString());
}
PasswordChecker.CheckResult checkResult = PasswordChecker.checkPassword(password);
// Color each of the requirements red (requirement not satisfied) or green (requirement
// satisfied).
passwordRequirementStatus.setText(Html.fromHtml(new StringBuilder()
.append(checkResult.hasMixedCase() && checkResult.hasNumbers()
&& checkResult.length() >= passwordChecker.getMinimumLength() ?
"<font color='#006600'>Your password must: </font>" :
"<font color='#ff0000'>Your password must: </font>"
)
.append(checkResult.hasMixedCase() && checkResult.hasNumbers() ?
"<font color='#006600'>use </font>" :
"<font color='#ff0000'>use </font>"
)
.append(checkResult.hasLowerCase() ?
"<font color='#006600'>a lowercase letter, </font>" :
"<font color='#ff0000'>a lowercase letter, </font>"
)
.append(checkResult.hasUpperCase() ?
"<font color='#006600'>an uppercase letter, </font>" :
"<font color='#ff0000'>an uppercase letter, </font>"
)
.append(checkResult.hasNumbers() ?
"<font color='#006600'>a number, </font>" :
"<font color='#ff0000'>a number, </font>"
)
.append(checkResult.length() >= passwordChecker.getMinimumLength() ?
"<font color='#006600'>and have at least 8 characters." :
"<font color='#ff0000'>and have at least 8 characters."
)
.toString()
));
}
/**
* Cancels the current toast and displays a new toast.
*
* @param text The text to display
* @param length The length to display the toast
*/
private void updateToast(String text, int length){
if(toast != null){
toast.cancel();
}
if(context != null){
toast = Toast.makeText(
context,
text,
length
);
toast.show();
}
}
private void startMainActivity(){
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
getActivity().finish();
}
/**
* This class checks if a username is valid and then checks if the username is taken.
* Once complete, updates usernameErrorStatus.
*
* The username should be passed to the execute() method.
*
* This process must be done in an AsyncTask because querying for a username may take a long
* time and will interfere the UI thread.
*/
private class UsernameErrorStatusUpdater extends AsyncTask<String, Void, String> {
private TextView usernameErrorStatus;
private ParseQuery<ParseUser> query;
private boolean queryCanceled;
public UsernameErrorStatusUpdater(){
super();
this.queryCanceled = false;
}
@Override
protected void onPreExecute(){
usernameErrorStatus = NewAccountFragment.this.usernameErrorStatus;
usernameErrorStatus.setText("Checking username...");
usernameErrorStatus.setTextColor(Color.BLACK);
}
@Override
protected String doInBackground(String... params) {
String username = params[0];
return checkUsername(username);
}
@Override
protected void onPostExecute(String result){
usernameErrorStatus.setText(result);
if(result.equalsIgnoreCase("OK")){
usernameErrorStatus.setTextColor(Color.BLACK);
} else{
usernameErrorStatus.setTextColor(Color.RED);
}
}
@Override
protected void onCancelled(String result){
queryCanceled = true;
if(query != null){
query.cancel();
}
}
/**
* First, this method calls isUsernameValid(). If the username is valid, we then check if
* it is already taken.
*
* @param username The username to check
*
* @return "OK" if the username checks out. Error message otherwise.
*/
private String checkUsername(String username){
// First, check constraints in isUserNameValid()
StringBuilder temp = new StringBuilder();
if(!isUsernameValid(username, temp)){
return temp.toString();
}
// If the query hasn't already been canceled, start the query.
if(!queryCanceled){
// Next, check if the username is taken
query = ParseUser.getQuery();
query.whereEqualTo("username", username);
try {
if (query.find().size() > 0) {
// Username is taken.
return "Username is taken";
} else{
// User name is not taken
return "OK";
}
} catch(ParseException e){
return "Unable to check username";
}
} else{
return "Unable to check username";
}
// This line is unreachable.
}
}
} | 34.508681 | 105 | 0.583589 |
c36dcc1b1563d5be1eed43c0ec948bf19c08888f | 1,945 | package appUtils.settings;
import music.Rhythm;
import settings.SettingDouble;
import settings.SettingRhythm;
import settings.Settings;
/**
* A {@link Settings} object which contains all of the information about tabs
* in general without direct respect to any input or output interface
* @author zrona
*/
public class TabSettings extends Settings{
/** Default for {@link #quantizeDivisor} */
public static final double QUANTIZE_DIVISOR = 16.0;
/** @return Default for {@link #rhythmConversionEndValue} */
public static Rhythm RHYTHM_CONVERSION_END_VALUE = new Rhythm(1, 4);
/**
* The divisor used for quantizing notes for creation, placement, and selection, based on note duration.
* If this value is 8, it uses eighth notes, if it is 4, it uses quarter notes, if it is 1.23 it uses notes 1/1.23 the length of a whole note
*/
private SettingDouble quantizeDivisor;
/**
* The value for the {@link Rhythm} used for the last note when a rhythmicless tab is converted to use rhythm, and the last note cannot be guessed
* because it has no note after it
*/
private SettingRhythm rhythmConversionEndValue;
/**
* Create a new set of {@link TabSettings} with all default values loaded
*/
public TabSettings(){
super();
this.quantizeDivisor = this.addDouble(QUANTIZE_DIVISOR);
this.rhythmConversionEndValue = this.add(new SettingRhythm(RHYTHM_CONVERSION_END_VALUE));
}
/** @return See {@link #quantizeDivisor} */
public SettingDouble getQuantizeDivisor(){ return this.quantizeDivisor; }
/** @return See {@link #rhythmConversionEndValue} */
public SettingRhythm getRhythmConversionEndValue(){ return this.rhythmConversionEndValue; }
/** @return See {@link #quantizeDivisor} */
public Double quantizeDivisor(){ return this.getQuantizeDivisor().get(); }
/** @return See {@link #rhythmConversionEndValue} */
public Rhythm rhythmConversionEndValue(){ return this.getRhythmConversionEndValue().get(); }
}
| 38.9 | 147 | 0.751671 |
9ff9349a51b472350acde791b87f090650b1759b | 936 | package emlkoks.entitybrowser.query;
import emlkoks.entitybrowser.query.comparator.ComparationType;
import emlkoks.entitybrowser.session.entity.FieldProperty;
import java.util.Objects;
import lombok.Getter;
import lombok.NonNull;
/**
* Created by EmlKoks on 19.06.19.
*/
@Getter
public class FieldFilter {
private ComparationType comparationType;
private FieldProperty fieldProperty;
private Object[] values;
public FieldFilter(@NonNull ComparationType comparationType, @NonNull FieldProperty fieldProperty, Object... values) {
this.comparationType = comparationType;
this.fieldProperty = fieldProperty;
this.values = values;
}
public Object getValue() {
return getValue(0);
}
public Object getValue(int valueIndex) {
if (Objects.isNull(values) || valueIndex >= values.length) {
return null;
}
return values[valueIndex];
}
}
| 26.742857 | 122 | 0.706197 |
62f5d58b5c503b47492bcb2c6076372855b6a8ed | 1,143 | package com.fluxtream.domain;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import com.fluxtream.Configuration;
@Entity(name = "ApiKeyAttribute")
@NamedQueries({
@NamedQuery(name = "apiKeyAttribute.byKeyAndConnector", query = "SELECT att FROM ApiKeyAttribute att WHERE att.apiKey=? AND att.attributeKey=?"),
@NamedQuery(name = "apiKeyAttribute.delete", query = "DELETE FROM ApiKeyAttribute att WHERE att.apiKey=? AND att.attributeKey=?") })
public class ApiKeyAttribute extends AbstractEntity {
@ManyToOne
public ApiKey apiKey;
public String attributeKey;
@Lob
String attributeValue;
public int hashcode() {
return HashCodeBuilder.reflectionHashCode(this, false);
}
public void setAttributeValue(String value, Configuration env) {
this.attributeValue = env.encrypt(value);
}
public boolean equals(Object o1, Object o2) {
return EqualsBuilder.reflectionEquals(o1, o2);
}
}
| 27.878049 | 147 | 0.785652 |
c484511f0754679befb601cdc9ead071ec57db82 | 1,000 | /* *
* Authors: Hyunwoo Lee <[email protected]>
* Released under the MIT license.
* */
package com.bot.api.conversation;
import com.bot.api.model.conversation.ConversationRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/bot")
public class ConversationController {
@Autowired
private ConversationBO conversationBO;
@RequestMapping(value="/message", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity receive(@RequestBody ConversationRequest conversationRequest) throws Exception {
return new ResponseEntity(conversationBO.response(conversationRequest), HttpStatus.OK);
}
@ExceptionHandler(Exception.class)
public void globalExceptionHandler(Exception e){
e.printStackTrace();
}
}
| 30.30303 | 106 | 0.781 |
76666846e7e86d59c092b38e4bae086f81f87dc9 | 7,472 | package com.abatra.android.wheelie.mayI;
import android.content.pm.PackageManager;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Lifecycle;
import com.abatra.android.wheelie.lifecycle.owner.ILifecycleOwner;
import com.google.common.collect.ImmutableMap;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ManifestMultiplePermissionsRequestorTest {
@InjectMocks
private ManifestMultiplePermissionsRequestor permissionRequestor;
@Mock
private ILifecycleOwner mockedLifecycleOwner;
@Mock
private Lifecycle mockedLifecycle;
@Mock
private ActivityResultLauncher<String[]> mockedMultiplePermissionsActivityResultLauncher;
@Captor
private ArgumentCaptor<ActivityResultCallback<Map<String, Boolean>>> multiplePermissionsActivityResultCallbackArgumentCaptor;
@Captor
private ArgumentCaptor<MultiplePermissionsGrantResult> multiplePermissionsGrantResultArgumentCaptor;
@Mock
private MultiplePermissionsRequestor.Callback mockedCallback;
private MockedStatic<ContextCompat> mockedContextCompat;
private MockedStatic<ActivityCompat> mockedActivityCompat;
@Before
public void setup() {
when(mockedLifecycleOwner.getLifecycle()).thenReturn(mockedLifecycle);
//noinspection unchecked
when(mockedLifecycleOwner.registerForActivityResult(
ArgumentMatchers.any(ActivityResultContracts.RequestMultiplePermissions.class),
ArgumentMatchers.any(ActivityResultCallback.class)))
.thenReturn(mockedMultiplePermissionsActivityResultLauncher);
mockedContextCompat = mockStatic(ContextCompat.class);
mockedContextCompat.when(() -> ContextCompat.checkSelfPermission(ArgumentMatchers.any(), anyString()))
.thenReturn(PackageManager.PERMISSION_DENIED);
mockedActivityCompat = mockStatic(ActivityCompat.class);
mockedActivityCompat.when(() -> ActivityCompat.shouldShowRequestPermissionRationale(ArgumentMatchers.any(), anyString())).thenReturn(true);
permissionRequestor.observeLifecycle(mockedLifecycleOwner);
assertTrue(permissionRequestor.getLifecycleOwner().isPresent());
assertThat(permissionRequestor.getLifecycleOwner().get(), sameInstance(mockedLifecycleOwner));
verify(mockedLifecycle, times(1)).addObserver(permissionRequestor);
assertNotNull(permissionRequestor.getMultiplePermissionsActivityResultLauncher());
verify(mockedLifecycleOwner, times(1)).registerForActivityResult(
ArgumentMatchers.any(ActivityResultContracts.RequestMultiplePermissions.class),
multiplePermissionsActivityResultCallbackArgumentCaptor.capture());
assertThat(multiplePermissionsActivityResultCallbackArgumentCaptor.getAllValues(), hasSize(1));
}
@After
public void tearDown() {
mockedContextCompat.close();
mockedActivityCompat.close();
}
@Test
public void testOnDestroy() {
assertTrue(permissionRequestor.getLifecycleOwner().isPresent());
permissionRequestor.requestSystemPermissions(new String[]{"a", "b"}, mockedCallback);
assertTrue(permissionRequestor.getCallbackDelegator().isPresent());
assertThat(permissionRequestor.getMultiplePermissionsActivityResultLauncher(), notNullValue());
permissionRequestor.onDestroy();
assertFalse(permissionRequestor.getLifecycleOwner().isPresent());
assertFalse(permissionRequestor.getCallbackDelegator().isPresent());
assertThat(permissionRequestor.getMultiplePermissionsActivityResultLauncher(), nullValue());
}
@Test
public void testRequestSystemPermissions_allGranted() {
mockedContextCompat.when(() -> ContextCompat.checkSelfPermission(ArgumentMatchers.any(), anyString()))
.thenReturn(PackageManager.PERMISSION_GRANTED);
permissionRequestor.requestSystemPermissions(new String[]{"pa", "pb"}, mockedCallback);
verify(mockedCallback, times(1)).onPermissionResult(multiplePermissionsGrantResultArgumentCaptor.capture());
verifyNoMoreInteractions(mockedCallback);
assertTrue(multiplePermissionsGrantResultArgumentCaptor.getValue().getSinglePermissionGrantResult("pa").isPermissionGranted());
assertTrue(multiplePermissionsGrantResultArgumentCaptor.getValue().getSinglePermissionGrantResult("pb").isPermissionGranted());
verifyNoInteractions(mockedMultiplePermissionsActivityResultLauncher);
}
@Test
public void testRequestSystemPermissions_notAllGranted() {
String[] permissions = {"pa", "pb", "pc"};
mockedActivityCompat.when(() -> ActivityCompat.shouldShowRequestPermissionRationale(ArgumentMatchers.any(), eq("pc"))).thenReturn(false);
permissionRequestor.requestSystemPermissions(permissions, mockedCallback);
verify(mockedMultiplePermissionsActivityResultLauncher, times(1)).launch(permissions);
multiplePermissionsActivityResultCallbackArgumentCaptor.getValue().onActivityResult(ImmutableMap.of("pa", true, "pb", false));
verify(mockedCallback, times(1)).onPermissionResult(multiplePermissionsGrantResultArgumentCaptor.capture());
assertTrue(multiplePermissionsGrantResultArgumentCaptor.getValue().getSinglePermissionGrantResult("pa").isPermissionGranted());
assertFalse(multiplePermissionsGrantResultArgumentCaptor.getValue().getSinglePermissionGrantResult("pa").isPermissionPermanentlyDeniedBeforeRequest());
assertFalse(multiplePermissionsGrantResultArgumentCaptor.getValue().getSinglePermissionGrantResult("pb").isPermissionGranted());
assertFalse(multiplePermissionsGrantResultArgumentCaptor.getValue().getSinglePermissionGrantResult("pb").isPermissionPermanentlyDeniedBeforeRequest());
assertFalse(multiplePermissionsGrantResultArgumentCaptor.getValue().getSinglePermissionGrantResult("pc").isPermissionGranted());
assertTrue(multiplePermissionsGrantResultArgumentCaptor.getValue().getSinglePermissionGrantResult("pc").isPermissionPermanentlyDeniedBeforeRequest());
}
}
| 43.695906 | 159 | 0.790418 |
1c4f8686d7c35c818b4bc4bea263ac8f6dc3b21c | 2,706 | /*
* Copyright (c) 2014, 2015, OpenMapFX and LodgON
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of LodgON, OpenMapFX, any associated website, 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 LODGON 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.
*/
package org.lodgon.openmapfx.core;
import java.util.List;
/**
*
* Interface used to describe a source of tiles, to allow for switching
* between both providers and the types of tiles that are displayed.
*
* @author Geoff Capper
*/
public interface TileProvider {
/** Get the display name of the tile provider, for use in the UI.
*
* @return The display name of the tile provider, e.g. "Map Quest"
*/
public String getProviderName();
/** Get an array of {@link TileType}s that this provider can supply.
*
* @return the list of tyletypes
*/
public List<TileType> getTileTypes();
/** Gets the default tile type for this provider, typically the map tile.
*
* @return the default tiletype
*/
public TileType getDefaultType();
/** The attribution notice that is required by the tile provider to be
* displayed.
*
* @return Any legally required attribution notice that must be displayed.
*/
public String getAttributionNotice();
}
| 40.38806 | 83 | 0.702513 |
6b581f43939accadfe51fe21aa5f106eb4d7af52 | 1,093 | // SPDX-License-Identifier: MIT
package mealplaner.plugins.comment.mealextension;
import java.util.Objects;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import mealplaner.plugins.api.MealFact;
import mealplaner.plugins.api.MealFactXml;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class CommentFact implements MealFact, MealFactXml {
private final String comment;
public CommentFact() {
this.comment = "";
}
public CommentFact(String comment) {
this.comment = comment;
}
public String getComment() {
return comment;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CommentFact that = (CommentFact) o;
return comment.equals(that.comment);
}
@Override
public int hashCode() {
return Objects.hash(comment);
}
@Override
public String toString() {
return "[comment='" + comment + "']";
}
}
| 21.019231 | 59 | 0.695334 |
086a6d075be3b2fa8e8f1a5eee5e949d5cd59e24 | 2,319 | /* Copyright 2016 Google 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.google.api.codegen.viewmodel;
import com.google.api.gax.core.RetrySettings.Builder;
import com.google.auto.value.AutoValue;
import javax.annotation.Nullable;
import org.joda.time.Duration;
@AutoValue
public abstract class RetryParamsDefinitionView {
public abstract String key();
@Nullable // Used in C#
public abstract String name();
public abstract String retryBackoffMethodName();
public abstract String timeoutBackoffMethodName();
public abstract Duration totalTimeout();
public abstract Duration initialRetryDelay();
public abstract double retryDelayMultiplier();
public abstract Duration maxRetryDelay();
public abstract Duration initialRpcTimeout();
public abstract double rpcTimeoutMultiplier();
public abstract Duration maxRpcTimeout();
public static Builder newBuilder() {
return new AutoValue_RetryParamsDefinitionView.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder key(String val);
public abstract Builder name(String val);
public abstract Builder retryBackoffMethodName(String val);
public abstract Builder timeoutBackoffMethodName(String val);
public abstract Builder initialRetryDelay(Duration initialDelay);
public abstract Builder retryDelayMultiplier(double multiplier);
public abstract Builder maxRetryDelay(Duration maxDelay);
public abstract Builder initialRpcTimeout(Duration initialTimeout);
public abstract Builder rpcTimeoutMultiplier(double multiplier);
public abstract Builder maxRpcTimeout(Duration maxTimeout);
public abstract Builder totalTimeout(Duration totalTimeout);
public abstract RetryParamsDefinitionView build();
}
}
| 29.730769 | 75 | 0.776197 |
22b1c4f90bb2b97891d7260e84472df6f074d9c2 | 11,116 | package com.box.sdk;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
/**
* The Metadata class represents one type instance of Box metadata.
*
* Learn more about Box metadata:
* https://developers.box.com/metadata-api/
*/
public class Metadata {
/**
* Specifies the name of the default "properties" metadata template.
*/
public static final String DEFAULT_METADATA_TYPE = "properties";
/**
* Specifies the "global" metadata scope.
*/
public static final String GLOBAL_METADATA_SCOPE = "global";
/**
* Specifies the "enterprise" metadata scope.
*/
public static final String ENTERPRISE_METADATA_SCOPE = "enterprise";
/**
* The default limit of entries per response.
*/
public static final int DEFAULT_LIMIT = 100;
/**
* URL template for all metadata associated with item.
*/
public static final URLTemplate GET_ALL_METADATA_URL_TEMPLATE = new URLTemplate("/metadata");
/**
* Values contained by the metadata object.
*/
private final JsonObject values;
/**
* Operations to be applied to the metadata object.
*/
private JsonArray operations;
/**
* Creates an empty metadata.
*/
public Metadata() {
this.values = new JsonObject();
}
/**
* Creates a new metadata.
* @param values the initial metadata values.
*/
public Metadata(JsonObject values) {
this.values = values;
}
/**
* Creates a copy of another metadata.
* @param other the other metadata object to copy.
*/
public Metadata(Metadata other) {
this.values = new JsonObject(other.values);
}
/**
* Used to retrieve all metadata associated with the item.
* @param item item to get metadata for.
* @param fields the optional fields to retrieve.
* @return An iterable of metadata instances associated with the item.
*/
public static Iterable<Metadata> getAllMetadata(BoxItem item, String ... fields) {
QueryStringBuilder builder = new QueryStringBuilder();
if (fields.length > 0) {
builder.appendParam("fields", fields);
}
return new BoxResourceIterable<Metadata>(
item.getAPI(),
GET_ALL_METADATA_URL_TEMPLATE.buildWithQuery(item.getItemURL().toString(), builder.toString()),
DEFAULT_LIMIT) {
@Override
protected Metadata factory(JsonObject jsonObject) {
return new Metadata(jsonObject);
}
};
}
/**
* Returns the 36 character UUID to identify the metadata object.
* @return the metadata ID.
*/
public String getID() {
return this.get("/$id");
}
/**
* Returns the metadata type.
* @return the metadata type.
*/
public String getTypeName() {
return this.get("/$type");
}
/**
* Returns the parent object ID (typically the file ID).
* @return the parent object ID.
*/
public String getParentID() {
return this.get("/$parent");
}
/**
* Returns the scope.
* @return the scope.
*/
public String getScope() {
return this.get("/$scope");
}
/**
* Returns the template name.
* @return the template name.
*/
public String getTemplateName() {
return this.get("/$template");
}
/**
* Adds a new metadata value.
* @param path the path that designates the key. Must be prefixed with a "/".
* @param value the value.
* @return this metadata object.
*/
public Metadata add(String path, String value) {
this.values.add(this.pathToProperty(path), value);
this.addOp("add", path, value);
return this;
}
/**
* Adds a new metadata value.
* @param path the path that designates the key. Must be prefixed with a "/".
* @param value the value.
* @return this metadata object.
*/
public Metadata add(String path, float value) {
this.values.add(this.pathToProperty(path), value);
this.addOp("add", path, value);
return this;
}
/**
* Replaces an existing metadata value.
* @param path the path that designates the key. Must be prefixed with a "/".
* @param value the value.
* @return this metadata object.
*/
public Metadata replace(String path, String value) {
this.values.set(this.pathToProperty(path), value);
this.addOp("replace", path, value);
return this;
}
/**
* Replaces an existing metadata value.
* @param path the path that designates the key. Must be prefixed with a "/".
* @param value the value.
* @return this metadata object.
*/
public Metadata replace(String path, float value) {
this.values.set(this.pathToProperty(path), value);
this.addOp("replace", path, value);
return this;
}
/**
* Removes an existing metadata value.
* @param path the path that designates the key. Must be prefixed with a "/".
* @return this metadata object.
*/
public Metadata remove(String path) {
this.values.remove(this.pathToProperty(path));
this.addOp("remove", path, null);
return this;
}
/**
* Tests that a property has the expected value.
* @param path the path that designates the key. Must be prefixed with a "/".
* @param value the expected value.
* @return this metadata object.
*/
public Metadata test(String path, String value) {
this.addOp("test", path, value);
return this;
}
/**
* Returns a value.
* @param path the path that designates the key. Must be prefixed with a "/".
* @return the metadata property value.
* @deprecated Metadata#get() does not handle all possible metadata types; use Metadata#getValue() instead
*/
@Deprecated
public String get(String path) {
final JsonValue value = this.values.get(this.pathToProperty(path));
if (value == null) {
return null;
}
if (!value.isString()) {
return value.toString();
}
return value.asString();
}
/**
* Returns a value, regardless of type.
* @param path the path that designates the key. Must be prefixed with a "/".
* @return the metadata property value as an indeterminate JSON type.
*/
public JsonValue getValue(String path) {
return this.values.get(this.pathToProperty(path));
}
/**
* Get a value from a string or enum metadata field.
* @param path the key path in the metadata object. Must be prefixed with a "/".
* @return the metadata value as a string.
*/
public String getString(String path) {
return this.getValue(path).asString();
}
/**
* Get a value from a float metadata field.
* @param path the key path in the metadata object. Must be prefixed with a "/".
* @return the metadata value as a floating point number.
*/
public double getFloat(String path) {
// @NOTE(mwiller) 2018-02-05: JS number are all 64-bit floating point, so double is the correct type to use here
return this.getValue(path).asDouble();
}
/**
* Get a value from a date metadata field.
* @param path the key path in the metadata object. Must be prefixed with a "/".
* @return the metadata value as a Date.
* @throws ParseException when the value cannot be parsed as a valid date
*/
public Date getDate(String path) throws ParseException {
return BoxDateFormat.parse(this.getValue(path).asString());
}
/**
* Returns a list of metadata property paths.
* @return the list of metdata property paths.
*/
public List<String> getPropertyPaths() {
List<String> result = new ArrayList<String>();
for (String property : this.values.names()) {
if (!property.startsWith("$")) {
result.add(this.propertyToPath(property));
}
}
return result;
}
/**
* Returns the JSON patch string with all operations.
* @return the JSON patch string.
*/
public String getPatch() {
if (this.operations == null) {
return "[]";
}
return this.operations.toString();
}
/**
* Returns the JSON representation of this metadata.
* @return the JSON representation of this metadata.
*/
@Override
public String toString() {
return this.values.toString();
}
/**
* Converts a JSON patch path to a JSON property name.
* Currently the metadata API only supports flat maps.
* @param path the path that designates the key. Must be prefixed with a "/".
* @return the JSON property name.
*/
private String pathToProperty(String path) {
if (path == null || !path.startsWith("/")) {
throw new IllegalArgumentException("Path must be prefixed with a \"/\".");
}
return path.substring(1);
}
/**
* Converts a JSON property name to a JSON patch path.
* @param property the JSON property name.
* @return the path that designates the key.
*/
private String propertyToPath(String property) {
if (property == null) {
throw new IllegalArgumentException("Property must not be null.");
}
return "/" + property;
}
/**
* Adds a patch operation.
* @param op the operation type. Must be add, replace, remove, or test.
* @param path the path that designates the key. Must be prefixed with a "/".
* @param value the value to be set.
*/
private void addOp(String op, String path, String value) {
if (this.operations == null) {
this.operations = new JsonArray();
}
this.operations.add(new JsonObject()
.add("op", op)
.add("path", path)
.add("value", value));
}
/**
* Adds a patch operation.
* @param op the operation type. Must be add, replace, remove, or test.
* @param path the path that designates the key. Must be prefixed with a "/".
* @param value the value to be set.
*/
private void addOp(String op, String path, float value) {
if (this.operations == null) {
this.operations = new JsonArray();
}
this.operations.add(new JsonObject()
.add("op", op)
.add("path", path)
.add("value", value));
}
static String scopeBasedOnType(String typeName) {
String scope;
if (typeName.equals(DEFAULT_METADATA_TYPE)) {
scope = GLOBAL_METADATA_SCOPE;
} else {
scope = ENTERPRISE_METADATA_SCOPE;
}
return scope;
}
}
| 29.801609 | 120 | 0.601205 |
388f840bae2390c85d16fc9abffe5c3f5d44de5a | 1,755 | package de.adorsys.keycloack.custom.auth;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.keycloak.OAuth2Constants;
import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import de.adorsys.keycloack.secret.adapter.common.UserSecretAdapter;
public class AuthenticatorUtil {
public static Optional<String> readScope(AuthenticationFlowContext context) {
Object scope = context.getAuthenticationSession().getClientNote(OAuth2Constants.SCOPE);
return Optional.ofNullable(scope)
.map(Object::toString);
}
public static void addMainSecretToUserSession(UserSecretAdapter userSecretStorage, AuthenticationFlowContext context, UserModel user, UserCredentialModel credentialModel ){
String userSecret = userSecretStorage.retrieveMainSecret(context.getRealm(), user, credentialModel);
// copy notes into the user session
// Hint: it might have been interesting to distinguish between the different type of notes
// that can be returned by a user storage provider like:
// - UserSesionNote
// - AuthNote
// - ClientNote
// Hint: even roles could be transported using these notes.
Object scope = credentialModel.getNote(Constants.CUSTOM_SCOPE_NOTE_KEY);
if (userSecret != null) {
context.getAuthenticationSession().setUserSessionNote(UserSecretAdapter.USER_MAIN_SECRET_NOTE_KEY,userSecret);
}
if(scope!=null){
context.getAuthenticationSession().setUserSessionNote(UserSecretAdapter.AUTH_SESSION_SCOPE_NOTE_KEY,scope.toString());
}
}
}
| 40.813953 | 176 | 0.765812 |
2f3653e8163c851da5b4f6d2267e850830dccef5 | 337 | package com.example.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories
@EnableTransactionManagement
public class Config {
}
| 25.923077 | 78 | 0.869436 |
76a631794966766247958350ec0af7c84224c013 | 287 | package io.whz.synapse.pojo.neural;
import android.support.annotation.NonNull;
public class Digit {
public final double[] colors;
public final int label;
public Digit(int label, @NonNull double[] colors) {
this.colors = colors;
this.label = label;
}
}
| 20.5 | 55 | 0.66899 |
d18adf64b69e85134c68ce811ab3e8d224310e84 | 200 | package io.axway.iron.core.model.validation;
import io.axway.iron.description.Entity;
import io.axway.iron.description.Unique;
@Entity
public interface TargetEntity {
@Unique
String id();
}
| 18.181818 | 44 | 0.76 |
03800c7698c19b62a864ecc9aa4004514195750a | 1,764 | package me.lake.librestreaming.tools;
/**
* Created by lake on 16-3-16.
*/
import android.util.Log;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.UnknownHostException;
public class LogTools {
protected static final String TAG = "RESLog";
private static boolean enableLog = true;
public static boolean isEnableLog() {
return enableLog;
}
public static void setEnableLog(boolean enableLog) {
LogTools.enableLog = enableLog;
}
public static void e(String content) {
if (!enableLog) {
return;
}
Log.e(TAG, content);
}
public static void d(String content) {
if (!enableLog) {
return;
}
Log.d(TAG, content);
}
public static void trace(String msg) {
if (!enableLog) {
return;
}
trace(msg, new Throwable());
}
public static void trace(Throwable e) {
if (!enableLog) {
return;
}
trace(null, e);
}
public static void trace(String msg, Throwable e) {
if (!enableLog) {
return;
}
if (null == e || e instanceof UnknownHostException) {
return;
}
final Writer writer = new StringWriter();
final PrintWriter pWriter = new PrintWriter(writer);
e.printStackTrace(pWriter);
String stackTrace = writer.toString();
if (null == msg || msg.equals("")) {
msg = "================error!==================";
}
Log.e(TAG, "==================================");
Log.e(TAG, msg);
Log.e(TAG, stackTrace);
Log.e(TAG, "-----------------------------------");
}
} | 23.837838 | 61 | 0.518707 |
cbaf455982e3e0cda69e72c961c34e84a197b46f | 2,101 | /* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019 Datadog, Inc.
*/
package com.datadoghq.sketch.gk;
import static org.junit.jupiter.api.Assertions.fail;
import com.datadoghq.sketch.QuantileSketchTest;
import java.util.Arrays;
abstract class GKArrayTest extends QuantileSketchTest<GKArray> {
abstract double rankAccuracy();
@Override
public GKArray newSketch() {
return new GKArray(rankAccuracy());
}
@Override
protected void assertAccurate(boolean merged, double[] sortedValues, double quantile, double actualQuantileValue) {
final double rankAccuracy = (merged ? 2 : 1) * rankAccuracy();
// Check the rank accuracy.
final int minExpectedRank = (int) Math.floor(Math.max(quantile - rankAccuracy, 0) * sortedValues.length);
final int maxExpectedRank = (int) Math.ceil(Math.min(quantile + rankAccuracy, 1) * sortedValues.length);
int searchIndex = Arrays.binarySearch(sortedValues, actualQuantileValue);
if (searchIndex < 0) {
searchIndex = -searchIndex - 1;
}
int index = searchIndex;
while (index > 0 && sortedValues[index - 1] >= actualQuantileValue) {
index--;
}
int minRank = index;
while (index < sortedValues.length && sortedValues[index] <= actualQuantileValue) {
index++;
}
int maxRank = index;
if (maxRank < minExpectedRank || minRank > maxExpectedRank) {
fail();
}
}
static class GKArrayTest1 extends GKArrayTest {
@Override
double rankAccuracy() {
return 1e-1;
}
}
static class GKArrayTest2 extends GKArrayTest {
@Override
double rankAccuracy() {
return 1e-2;
}
}
static class GKArrayTest3 extends GKArrayTest {
@Override
double rankAccuracy() {
return 1e-3;
}
}
}
| 28.013333 | 119 | 0.63208 |
ddf07b00f10cae9bc69d6e40b3c0122eef6726f6 | 1,633 | package br.com.casadocodigo.listadelivros;
import br.com.casadocodigo.novolivro.LivroEntity;
import java.math.BigDecimal;
import java.time.LocalDate;
public class DetalhesLivroDto {
private Long id;
private String titulo;
private String resumo;
private String sumario;
private BigDecimal precoLivro;
private Integer qtdPaginas;
private String isbn;
private LocalDate dataLancamento;
private Long idCategoria;
private Long idAutor;
public DetalhesLivroDto(LivroEntity livro) {
this.id = livro.getId();
this.titulo = livro.getTitulo();
this.resumo = livro.getResumo();
this.sumario = livro.getSumario();
this.precoLivro = livro.getPrecoLivro();
this.qtdPaginas = livro.getQtdPaginas();
this.isbn = livro.getIsbn();
this.dataLancamento = livro.getDataLancamento();
this.idCategoria = livro.getIdCategoria();
this.idAutor = livro.getIdAutor();
}
public Long getId() {
return id;
}
public String getTitulo() {
return titulo;
}
public String getResumo() {
return resumo;
}
public String getSumario() {
return sumario;
}
public BigDecimal getPrecoLivro() {
return precoLivro;
}
public Integer getQtdPaginas() {
return qtdPaginas;
}
public String getIsbn() {
return isbn;
}
public LocalDate getDataLancamento() {
return dataLancamento;
}
public Long getIdCategoria() {
return idCategoria;
}
public Long getIdAutor() {
return idAutor;
}
}
| 22.067568 | 56 | 0.637477 |
350b64d2aad513bddc32f2cb8cffe2a95e848ceb | 378 | package com.itjing.designpatterns.factorymethod;
/**
* @author: lijing
* @Date: 2021年05月27日 16:28
* @Description: 具体产品 ConcreteProduct
*/
public class BusImpl2 implements Bus {
@Override
public void run() {
System.out.println("BusImpl2 is running");
}
@Override
public void stop() {
System.out.println("BusImpl2 stop running");
}
}
| 19.894737 | 52 | 0.653439 |
faf90f8db2c1a82a22015b6c224184f892af13c1 | 2,469 | package eu.coatrack.admin.service;
/*-
* #%L
* coatrack-api
* %%
* Copyright (C) 2013 - 2020 Corizon | Institut für angewandte Systemtechnik Bremen GmbH (ATB)
* %%
* 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.
* #L%
*/
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import eu.coatrack.api.Proxy;
import eu.coatrack.api.ServiceApi;
import eu.coatrack.api.User;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* @author perezdf
*/
public class GitServiceTest {
public GitServiceTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Autowired
GitService gitService;
// TODO add test methods here.
// The methods must be annotated with annotation @Test. For example:
//
//Test
public void testBasic() throws IOException, GitAPIException, URISyntaxException {
Proxy proxy = new Proxy();
proxy.setId(UUID.randomUUID().toString());
User owner = new User();
owner.setInitialized(Boolean.FALSE);
ServiceApi service = new ServiceApi();
service.setOwner(owner);
service.setId(Calendar.getInstance().getTimeInMillis());
service.setLocalUrl(" http://localhost:8083/crate-tracking2");
Set<ServiceApi> services = new HashSet<ServiceApi>();
services.add(service);
proxy.setServiceApis(services);
gitService.init();
gitService.addProxy(proxy);
gitService.commit("Add new Proxy");
}
}
| 25.989474 | 94 | 0.684488 |
31cc4b18cfc2b17ed17f2e689fadc9ac47302989 | 227 | package com.example.mystudyzone;
import java.util.List;
import retrofit.Callback;
import retrofit.http.GET;
public interface MyJsonService {
@GET("/1kpjf")
void listEvents(Callback<List<Event>> eventsCallback);
}
| 15.133333 | 58 | 0.748899 |
e1ffb0d214192078cd89940c255919b68a21f684 | 6,035 | package com.sample.eventstreams.builders;
import java.util.Map;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.Message;
import com.sample.eventstreams.MQSourceConnector;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaAndValue;
import org.apache.kafka.connect.errors.ConnectException;
import org.apache.kafka.connect.source.SourceRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Builds Kafka Connect SourceRecords from messages.
*/
public abstract class BaseRecordBuilder implements RecordBuilder {
private static final Logger log = LoggerFactory.getLogger(BaseRecordBuilder.class);
public enum KeyHeader {NONE, MESSAGE_ID, CORRELATION_ID, CORRELATION_ID_AS_BYTES, DESTINATION};
protected KeyHeader keyheader = KeyHeader.NONE;
/**
* Configure this class.
*
* @param props initial configuration
*
* @throws ConnectException Operation failed and connector should stop.
*/
@Override public void configure(Map<String, String> props) {
log.trace("[{}] Entry {}.configure, props={}", Thread.currentThread().getId(), this.getClass().getName(), props);
String kh = props.get(MQSourceConnector.CONFIG_NAME_MQ_RECORD_BUILDER_KEY_HEADER);
if (kh != null) {
if (kh.equals(MQSourceConnector.CONFIG_VALUE_MQ_RECORD_BUILDER_KEY_HEADER_JMSMESSAGEID)) {
keyheader = KeyHeader.MESSAGE_ID;
log.debug("Setting Kafka record key from JMSMessageID header field");
}
else if (kh.equals(MQSourceConnector.CONFIG_VALUE_MQ_RECORD_BUILDER_KEY_HEADER_JMSCORRELATIONID)) {
keyheader = KeyHeader.CORRELATION_ID;
log.debug("Setting Kafka record key from JMSCorrelationID header field");
}
else if (kh.equals(MQSourceConnector.CONFIG_VALUE_MQ_RECORD_BUILDER_KEY_HEADER_JMSCORRELATIONIDASBYTES)) {
keyheader = KeyHeader.CORRELATION_ID_AS_BYTES;
log.debug("Setting Kafka record key from JMSCorrelationIDAsBytes header field");
}
else if (kh.equals(MQSourceConnector.CONFIG_VALUE_MQ_RECORD_BUILDER_KEY_HEADER_JMSDESTINATION)) {
keyheader = KeyHeader.DESTINATION;
log.debug("Setting Kafka record key from JMSDestination header field");
}
else {
log.error("Unsupported MQ record builder key header value {}", kh);
throw new ConnectException("Unsupported MQ record builder key header value");
}
}
log.trace("[{}] Exit {}.configure", Thread.currentThread().getId(), this.getClass().getName());
}
/**
* Gets the key to use for the Kafka Connect SourceRecord.
*
* @param context the JMS context to use for building messages
* @param topic the Kafka topic
* @param message the message
*
* @return the Kafka Connect SourceRecord's key
*
* @throws JMSException Message could not be converted
*/
public SchemaAndValue getKey(JMSContext context, String topic, Message message) throws JMSException {
Schema keySchema = null;
Object key = null;
String keystr;
switch (keyheader) {
case MESSAGE_ID:
keySchema = Schema.OPTIONAL_STRING_SCHEMA;
keystr = message.getJMSMessageID();
if (keystr.startsWith("ID:", 0)) {
key = keystr.substring(3);
}
else {
key = keystr;
}
break;
case CORRELATION_ID:
keySchema = Schema.OPTIONAL_STRING_SCHEMA;
keystr = message.getJMSCorrelationID();
if (keystr.startsWith("ID:", 0)) {
key = keystr.substring(3);
}
else {
key = keystr;
}
break;
case CORRELATION_ID_AS_BYTES:
keySchema = Schema.OPTIONAL_BYTES_SCHEMA;
key = message.getJMSCorrelationIDAsBytes();
break;
case DESTINATION:
keySchema = Schema.OPTIONAL_STRING_SCHEMA;
key = message.getJMSDestination().toString();
break;
default:
break;
}
return new SchemaAndValue(keySchema, key);
}
/**
* Gets the value to use for the Kafka Connect SourceRecord.
*
* @param context the JMS context to use for building messages
* @param topic the Kafka topic
* @param messageBodyJms whether to interpret MQ messages as JMS messages
* @param message the message
*
* @return the Kafka Connect SourceRecord's value
*
* @throws JMSException Message could not be converted
*/
public abstract SchemaAndValue getValue(JMSContext context, String topic, boolean messageBodyJms, Message message) throws JMSException;
/**
* Convert a message into a Kafka Connect SourceRecord.
*
* @param context the JMS context to use for building messages
* @param topic the Kafka topic
* @param messageBodyJms whether to interpret MQ messages as JMS messages
* @param message the message
*
* @return the Kafka Connect SourceRecord
*
* @throws JMSException Message could not be converted
*/
@Override public SourceRecord toSourceRecord(JMSContext context, String topic, boolean messageBodyJms, Message message) throws JMSException {
SchemaAndValue key = this.getKey(context, topic, message);
SchemaAndValue value = this.getValue(context, topic, messageBodyJms, message);
return new SourceRecord(null, null, topic, key.schema(), key.value(), value.schema(), value.value());
}
}
| 40.233333 | 145 | 0.624689 |
c8f92bea43454da114d7391eeb6da377081aafb1 | 5,513 | /*
* Seldon -- open source prediction engine
* =======================================
*
* Copyright 2011-2015 Seldon Technologies Ltd and Rummble Ltd (http://www.seldon.io/)
*
* ********************************************************************************************
*
* 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.seldon.topics;
import io.seldon.clustering.recommender.ItemRecommendationAlgorithm;
import io.seldon.clustering.recommender.ItemRecommendationResultSet;
import io.seldon.clustering.recommender.RecommendationContext;
import io.seldon.items.RecentItemsWithTagsManager;
import io.seldon.recommendation.RecommendationUtils;
import io.seldon.topics.TopicFeaturesManager.TopicFeaturesStore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TopicModelRecommender implements ItemRecommendationAlgorithm {
private static Logger logger = Logger.getLogger(TopicModelRecommender.class.getSimpleName());
private static final String name = TopicModelRecommender.class.getSimpleName();
private static final String ATTR_ID_PROPERTY_NAME ="io.seldon.algorithm.tags.attrid";
private static final String TABLE_PROPERTY_NAME = "io.seldon.algorithm.tags.table";
private static final String MIN_NUM_WEIGHTS_PROPERTY_NAME = "io.seldon.algorithm.tags.minnumtagsfortopicweights";
TopicFeaturesManager featuresManager;
RecentItemsWithTagsManager tagsManager;
@Autowired
public TopicModelRecommender(TopicFeaturesManager featuresManager,RecentItemsWithTagsManager tagsManager)
{
this.featuresManager = featuresManager;
this.tagsManager = tagsManager;
}
@Override
public ItemRecommendationResultSet recommend(String client,
Long user, Set<Integer> dimensions, int maxRecsCount, RecommendationContext ctxt, List<Long> recentitemInteractions) {
RecommendationContext.OptionsHolder options = ctxt.getOptsHolder();
Integer tagAttrId = options.getIntegerOption(ATTR_ID_PROPERTY_NAME);
String tagTable = options.getStringOption(TABLE_PROPERTY_NAME);
Integer minNumTagsForWeights = options.getIntegerOption(MIN_NUM_WEIGHTS_PROPERTY_NAME);
TopicFeaturesStore store = featuresManager.getClientStore(client,options);
if (store == null)
{
if (logger.isDebugEnabled())
logger.debug("Failed to find topic features for client "+client);
return new ItemRecommendationResultSet(Collections.<ItemRecommendationResultSet.ItemRecommendationResult>emptyList(), name);
}
if (ctxt == null || ctxt.getContextItems() == null || ctxt.getContextItems().size() == 0)
{
logger.warn("Not items passed in to recommend from. For client "+client);
return new ItemRecommendationResultSet(Collections.<ItemRecommendationResultSet.ItemRecommendationResult>emptyList(), name);
}
Map<Long,List<String>> itemTags = tagsManager.retrieveRecentItems(client, ctxt.getContextItems(), tagAttrId, tagTable);
if (itemTags == null || itemTags.size() == 0)
{
if (logger.isDebugEnabled())
logger.debug("Failed to find recent tag items for client "+client);
return new ItemRecommendationResultSet(Collections.<ItemRecommendationResultSet.ItemRecommendationResult>emptyList(), name);
}
else if (logger.isDebugEnabled())
logger.debug("Got "+itemTags.size()+" recent item tags");
float[] userTopicWeight = store.getUserWeightVector(user);
if (userTopicWeight == null)
{
return new ItemRecommendationResultSet(Collections.<ItemRecommendationResultSet.ItemRecommendationResult>emptyList(), name);
}
Map<Long,Double> scores = new HashMap<>();
for(Map.Entry<Long, List<String>> e : itemTags.entrySet()) // for all items
{
if (e.getValue().size() >= minNumTagsForWeights && !recentitemInteractions.contains(e.getKey()))
{
float[] itemTopicWeight = store.getTopicWeights(e.getKey(), e.getValue());
Double score = new Double(dot(userTopicWeight,itemTopicWeight));
if (logger.isDebugEnabled())
logger.debug("Score for "+e.getKey()+"->"+score);
scores.put(e.getKey(), score);
}
}
Map<Long,Double> scaledScores = RecommendationUtils.rescaleScoresToOne(scores, maxRecsCount);
List<ItemRecommendationResultSet.ItemRecommendationResult> results = new ArrayList<>();
for(Map.Entry<Long, Double> e : scaledScores.entrySet())
{
results.add(new ItemRecommendationResultSet.ItemRecommendationResult(e.getKey(), e.getValue().floatValue()));
}
return new ItemRecommendationResultSet(results, name);
}
private static float dot(float[] vec1, float[] vec2)
{
float sum = 0;
for (int i = 0; i < vec1.length; i++){
sum += vec1[i] * vec2[i];
}
return sum;
}
@Override
public String name() {
return name;
}
}
| 40.536765 | 127 | 0.73626 |
3c115eddc2729723b68532fc481872303f340448 | 215 | package org.saiku.service.util.security.authorisation;
import org.springframework.security.core.Authentication;
public interface AuthorisationPredicate
{
boolean isAuthorised(Authentication authentication);
}
| 23.888889 | 56 | 0.84186 |
0fdf7177fd96ca00084d7815017f94919821860a | 921 | // Copyright (C) 2017 The Android Open Source Project
//
// 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.googlesource.gerrit.owners.common;
import com.google.gerrit.reviewdb.client.Account;
import com.google.inject.ImplementedBy;
import java.util.Set;
@ImplementedBy(AccountsImpl.class)
public interface Accounts {
public String GROUP_PREFIX = "group/";
Set<Account.Id> find(String nameOrEmail);
}
| 34.111111 | 75 | 0.765472 |
07af6c387ed0b270b1781f52293e93f213399552 | 1,270 | package com.github.wesleyegberto.jaxrsspecificationtest.aop;
import com.github.wesleyegberto.jaxrsspecificationtest.business.boundary.PersonResources;
import javax.annotation.Priority;
import javax.ws.rs.DELETE;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.DynamicFeature;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;
/**
* Will add a filter if the request is a DELETE.
* It is executed when the server is started and the endpoints are being registered.
*
* @author Wesley Egberto
*/
@Provider
@Priority(Priorities.AUTHENTICATION)
public class DynamicBinder implements DynamicFeature {
@Override
public void configure(ResourceInfo resInf, FeatureContext featureCtx) {
System.out.println("[DynamicBinder] verifying: " + resInf.getResourceMethod().getName());
if(PersonResources.class.equals(resInf.getResourceClass()) &&
resInf.getResourceMethod().isAnnotationPresent(DELETE.class)) {
System.out.println("[DynamicBinder] registered for " + resInf.getResourceMethod().getName());
// Use new object if the class isn't annotated
featureCtx.register(new HeaderAdminValidatorFilter());
}
}
}
| 36.285714 | 105 | 0.744882 |
a4f3ba988d16d6d6c74438c33e6889c0c310b044 | 3,790 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.bedit.gaming.wormstats.math;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import de.bedit.gaming.wormstats.constants.Constants;
import de.bedit.gaming.wormstats.dao.ConfigurationDao;
import de.bedit.gaming.wormstats.model.CompetitorMatchStatistic;
import de.bedit.gaming.wormstats.model.Leage;
import de.bedit.gaming.wormstats.model.MatchGame;
import de.bedit.gaming.wormstats.model.SimpleTableEntry;
/**
*
* @author benjamin
*/
@Stateless(name = "tableCalculator")
public class TableCalculatorImpl implements TableCalculator {
@EJB
ConfigurationDao configurationDao;
@Override
public List<SimpleTableEntry> createSimpleTableList(Leage leage) {
List<SimpleTableEntry> list = new ArrayList<SimpleTableEntry>();
Map<Long, SimpleTableEntry> entries = new HashMap<Long, SimpleTableEntry>();
List<MatchGame> matches = leage.getMatches();
for (MatchGame match : matches) {
for (CompetitorMatchStatistic stat : match
.getCompetitorMatchStatistics()) {
if (entries.containsKey(stat.getCompetitor().getId())) {
SimpleTableEntry entry = entries.get(stat.getCompetitor()
.getId());
entry.setKills(entry.getKills() + stat.getKills());
if (stat.getCompetitor().getId() == match.getWinner()
.getId()) {
entry.setWins(entry.getWins() + 1);
}
entry.setMatches(entry.getMatches() + 1);
entry.setSkill(calculateSimpleSkill(entry));
entry.setSelfKills(entry.getSelfKills()
+ stat.getSelfKills());
entries.put(stat.getCompetitor().getId(), entry);
} else {
SimpleTableEntry entry = new SimpleTableEntry();
entry.setMatches(1);
entry.setCompetitor(stat.getCompetitor());
entry.setKills(stat.getKills());
entry.setSelfKills(stat.getSelfKills());
if (stat.getCompetitor().getId() == match.getWinner()
.getId()) {
entry.setWins(1);
}
// Hack zur Übernahme der Altdaten
if (leage.getName().equals("5014 #1")) {
String cName = stat.getCompetitor().getName();
if (cName.equals("Benjamin")) {
entry.setKills(entry.getKills() + 163);
entry.setMatches(entry.getMatches() + 31);
entry.setWins(entry.getWins() + 15);
} else if (cName.equals("Thomas")) {
entry.setKills(entry.getKills() + 129);
entry.setMatches(entry.getMatches() + 25);
entry.setWins(entry.getWins() + 10);
} else if (cName.equals("Tom")) {
entry.setKills(entry.getKills() + 139);
entry.setMatches(entry.getMatches() + 26);
entry.setWins(entry.getWins() + 10);
} else if (cName.equals("Frank")) {
entry.setKills(entry.getKills() + 142);
entry.setMatches(entry.getMatches() + 29);
entry.setWins(entry.getWins() + 7);
} else if (cName.equals("Tilo")) {
entry.setKills(entry.getKills() + 14);
entry.setMatches(entry.getMatches() + 5);
entry.setWins(entry.getWins() + 0);
}
}
entry.setSkill(calculateSimpleSkill(entry));
entries.put(stat.getCompetitor().getId(), entry);
}
}
}
for (SimpleTableEntry entry : entries.values()) {
list.add(entry);
}
return list;
}
@Override
public double calculateSimpleSkill(SimpleTableEntry entry) {
Expression exp = new Expression(configurationDao.getConfiguration()
.getSkillFormula());
exp.setVariable(Constants.KILLS, entry.getKills());
exp.setVariable(Constants.SELFKILLS, entry.getSelfKills());
exp.setVariable(Constants.MATCHES, entry.getMatches());
exp.setVariable(Constants.WINS, entry.getWins());
return exp.resolve();
}
}
| 30.32 | 78 | 0.681003 |
af8300fbd0759a669467d5ba694ecf23ab8a6a02 | 4,054 | // Code generated by Wire protocol buffer compiler, do not edit.
// Source file: ./src/protobufs/services/media/actions/complete_image_upload.proto
package com.rhlabs.protobufs.services.media.actions.complete_image_upload;
import com.rhlabs.protobufs.services.media.containers.media.MediaTypeV1;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoField;
import static com.squareup.wire.Message.Datatype.ENUM;
import static com.squareup.wire.Message.Datatype.STRING;
import static com.squareup.wire.Message.Datatype.UINT32;
public final class CompleteImageUploadRequestV1 extends Message {
private static final long serialVersionUID = 0L;
public static final Integer DEFAULT_VERSION = 1;
public static final MediaTypeV1 DEFAULT_MEDIA_TYPE = MediaTypeV1.PROFILE;
public static final String DEFAULT_MEDIA_KEY = "";
public static final String DEFAULT_UPLOAD_KEY = "";
public static final String DEFAULT_UPLOAD_ID = "";
@ProtoField(tag = 1, type = UINT32)
public final Integer version;
@ProtoField(tag = 2, type = ENUM)
public final MediaTypeV1 media_type;
@ProtoField(tag = 3, type = STRING)
public final String media_key;
@ProtoField(tag = 4, type = STRING)
public final String upload_key;
@ProtoField(tag = 5, type = STRING)
public final String upload_id;
public CompleteImageUploadRequestV1(Integer version, MediaTypeV1 media_type, String media_key, String upload_key, String upload_id) {
this.version = version;
this.media_type = media_type;
this.media_key = media_key;
this.upload_key = upload_key;
this.upload_id = upload_id;
}
private CompleteImageUploadRequestV1(Builder builder) {
this(builder.version, builder.media_type, builder.media_key, builder.upload_key, builder.upload_id);
setBuilder(builder);
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof CompleteImageUploadRequestV1)) return false;
CompleteImageUploadRequestV1 o = (CompleteImageUploadRequestV1) other;
return equals(version, o.version)
&& equals(media_type, o.media_type)
&& equals(media_key, o.media_key)
&& equals(upload_key, o.upload_key)
&& equals(upload_id, o.upload_id);
}
@Override
public int hashCode() {
int result = hashCode;
if (result == 0) {
result = version != null ? version.hashCode() : 0;
result = result * 37 + (media_type != null ? media_type.hashCode() : 0);
result = result * 37 + (media_key != null ? media_key.hashCode() : 0);
result = result * 37 + (upload_key != null ? upload_key.hashCode() : 0);
result = result * 37 + (upload_id != null ? upload_id.hashCode() : 0);
hashCode = result;
}
return result;
}
public static final class Builder extends Message.Builder<CompleteImageUploadRequestV1> {
public Integer version;
public MediaTypeV1 media_type;
public String media_key;
public String upload_key;
public String upload_id;
public Builder() {
}
public Builder(CompleteImageUploadRequestV1 message) {
super(message);
if (message == null) return;
this.version = message.version;
this.media_type = message.media_type;
this.media_key = message.media_key;
this.upload_key = message.upload_key;
this.upload_id = message.upload_id;
}
public Builder version(Integer version) {
this.version = version;
return this;
}
public Builder media_type(MediaTypeV1 media_type) {
this.media_type = media_type;
return this;
}
public Builder media_key(String media_key) {
this.media_key = media_key;
return this;
}
public Builder upload_key(String upload_key) {
this.upload_key = upload_key;
return this;
}
public Builder upload_id(String upload_id) {
this.upload_id = upload_id;
return this;
}
@Override
public CompleteImageUploadRequestV1 build() {
return new CompleteImageUploadRequestV1(this);
}
}
}
| 31.671875 | 135 | 0.707203 |
aa41aa363db4d1d53aef6cda29f547bdbda538a2 | 1,790 | package com.google.android.gms.internal.ads;
import android.os.SystemClock;
public final class zzsw implements zzso {
/* renamed from: a */
private boolean f29341a;
/* renamed from: b */
private long f29342b;
/* renamed from: c */
private long f29343c;
/* renamed from: d */
private zzln f29344d = zzln.f28809a;
/* renamed from: b */
public final void mo32224b() {
if (!this.f29341a) {
this.f29343c = SystemClock.elapsedRealtime();
this.f29341a = true;
}
}
/* renamed from: c */
public final void mo32225c() {
if (this.f29341a) {
mo32222a(mo31998a());
this.f29341a = false;
}
}
/* renamed from: a */
public final void mo32222a(long j) {
this.f29342b = j;
if (this.f29341a) {
this.f29343c = SystemClock.elapsedRealtime();
}
}
/* renamed from: a */
public final void mo32223a(zzso zzso) {
mo32222a(zzso.mo31998a());
this.f29344d = zzso.mo32006i();
}
/* renamed from: a */
public final long mo31998a() {
long j = this.f29342b;
if (!this.f29341a) {
return j;
}
long elapsedRealtime = SystemClock.elapsedRealtime() - this.f29343c;
zzln zzln = this.f29344d;
if (zzln.f28810b == 1.0f) {
return j + zzkt.m30597b(elapsedRealtime);
}
return j + zzln.mo31949a(elapsedRealtime);
}
/* renamed from: a */
public final zzln mo31999a(zzln zzln) {
if (this.f29341a) {
mo32222a(mo31998a());
}
this.f29344d = zzln;
return zzln;
}
/* renamed from: i */
public final zzln mo32006i() {
return this.f29344d;
}
}
| 23.246753 | 76 | 0.54581 |
7a16a5708ad48d5f673cf78968e310994c741055 | 1,404 | package uk.co.bitcat.helpers;
import edu.stanford.nlp.ie.util.RelationTriple;
import java.util.List;
import java.util.Map;
public class Loggers {
public static void logEntities(Map<String, String> entitiesToTypes) {
System.out.println("----------ENTITIES----------");
for (Map.Entry<String, String> entry : entitiesToTypes.entrySet()) {
System.out.println(entry);
}
}
public static void logTriples(List<RelationTriple> triples) {
System.out.println("----------UNFILTERED----------");
for (RelationTriple triple : triples) {
System.out.println(triple.confidence + "," +
triple.subjectLemmaGloss() + "," +
triple.relationLemmaGloss() + "," +
triple.objectLemmaGloss());
}
}
public static void logTriplesWithEntityTypes(List<RelationTriple> triples, Map<String, String> entitiesToTypes) {
System.out.println("----------FILTERED----------");
for (RelationTriple triple : triples) {
System.out.println(triple.confidence + "," +
triple.subjectLemmaGloss() + "(" + entitiesToTypes.get(triple.subjectLemmaGloss()) + ")," +
triple.relationLemmaGloss() + "," +
triple.objectLemmaGloss() + "(" + entitiesToTypes.get(triple.objectLemmaGloss()) + ")");
}
}
}
| 37.945946 | 117 | 0.576923 |
b503bc04ddba28b2af8d21597ce1b63c1c3a0e6f | 1,718 | package com.xtoon.boot.sys.domain.model.log;
import com.xtoon.boot.common.domain.Entity;
import com.xtoon.boot.sys.domain.model.tenant.TenantId;
import com.xtoon.boot.sys.domain.model.user.UserName;
/**
* 日志实体
*
* @author haoxin
* @date 2021-02-02
**/
public class Log implements Entity<Log> {
/**
* logId
*/
private LogId logId;
/**
* 用户名
*/
private UserName userName;
/**
* 用户操作
*/
private String operation;
/**
* 请求方法
*/
private String method;
/**
* 请求参数
*/
private String params;
/**
* 执行时长(毫秒)
*/
private Long time;
/**
* IP地址
*/
private String ip;
/**
* 租户ID
*/
private TenantId tenantId;
public Log(LogId logId, UserName userName, String operation, String method, String params, Long time, String ip) {
this.logId = logId;
this.userName = userName;
this.operation = operation;
this.method = method;
this.params = params;
this.time = time;
this.ip = ip;
}
@Override
public boolean sameIdentityAs(Log other) {
return other != null && logId.sameValueAs(other.logId);
}
public LogId getLogId() {
return logId;
}
public String getOperation() {
return operation;
}
public String getMethod() {
return method;
}
public String getParams() {
return params;
}
public Long getTime() {
return time;
}
public String getIp() {
return ip;
}
public UserName getUserName() {
return userName;
}
public TenantId getTenantId() {
return tenantId;
}
}
| 16.679612 | 118 | 0.557043 |
346807165d5a0f6539d7f3cb05c07e9c5bf1b2a5 | 3,350 | package org.bougainvillea.java.basejava.codequality.chapter09;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**
* 129.适当设置阻塞队列长度
*
* 注意:阻塞队列的长度是固定的
*
* 阻塞队列BlockingQueue扩展了Queue、Collection接口,
* 对元素的插入和提取使用了“阻塞”处理,
* Collection下的实现类一般都采用了长度自行管理方式(也就是变长)
*
* 阻塞队列和非阻塞队列一个重要区别:
* 1)阻塞队列的容量是固定的,
* 2)非阻塞队列则是变长的。
* 3)阻塞队列可以在声明时指定队列的容量,
* 若指定的容量,则元素的数量不可超过该容量,
* 若不指定,队列的容量为Integer的最大值
* 原因:
* 1)阻塞队列是为了容纳(或排序)多线程任务而存在的,
* 其服务的对象是多线程应用,
* 2)而非阻塞队列容纳的则是普通的数据元素
*
* 阻塞队列的这种机制对异步计算是非常有帮助的,
* 例如我们定义深度为100的阻塞队列容纳100个任务,
* 多个线程从该队列中获取任务并处理,
* 当所有的线程都在繁忙,
* 并且队列中任务数量已经为100时,也预示着系统运算压力非常巨大,
* 而且处理结果的时间也会比较长,
* 于是在第101个任务期望加入时,队列拒绝加入,而且返回异常,
* 由系统自行处理,避免了异步运算的不可知性
* 注意阅读下方的源码
*
*/
public class Ey {
public static void main(String[] args) {
//列表的初始长度为5,在实际使用时,
// 当加入的元素超过初始容量时,ArrayList会自行扩容,确保能够正常加入元素
List<String> list=new ArrayList<>(5);
for (int i = 0; i < 10; i++) {
list.add("");
}
System.err.println(list.size());
//BlockingQueue不能自行扩容,报下面的异常
//Exception in thread "main" java.lang.IllegalStateException: Queue full
BlockingQueue<String> bq=new ArrayBlockingQueue<>(5);
for (int i = 0; i < 10; i++) {
bq.add("");
}
System.err.println(bq.size());
}
}
//源码
//AbstractQueue.add(e)
/*public boolean add(E e) {
//调用offer方法尝试写入
if (offer(e))
return true;
else
//写入失败,抛出队列已满异常
throw new IllegalStateException("Queue full");
}*/
//ArrayBlockingQueue.offer(e)
/*public boolean offer(E e) {
checkNotNull(e);
final ReentrantLock lock = this.lock;
//申请锁,只允许同时一个线程操作
lock.lock();
try {
//元素计数器的计数与数组长度相同,标识队列已满
if (count == items.length)
return false;
else {
//队列未满,插入元素
enqueue(e);
return true;
}
} finally {
//释放锁
lock.unlock();
}
}*/
//ArrayBlockingQueue.put(e)
// 如果应用期望无论等待多长时间都要运行该任务,不希望返回异常
// 需要用BlockingQueue接口定义的put方法,
// 它的作用也是把元素加入到队列中,
// 但它与add、offer方法不同,
// 它会等待队列空出元素,再让自己加入进去,
// 通俗地讲,put方法提供的是一种“无赖”式的插入,
// 无论等待多长时间都要把该元素插入到队列中
// put方法的目的就是确保元素肯定会加入到队列中,
// 问题是此种等待是一个循环,会不停地消耗系统资源,
// 当等待加入的元素数量较多时势必会对系统性能产生影响
// JDK已经想到了这个问题,它提供了带有超时时间的offer方法,
// 其实现方法与put比较类似,
// 只是使用Condition的awaitNanos方法来判断当前线程已经等待了多少纳秒,
// 超时则返回false
/*
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
//可中断锁
lock.lockInterruptibly();
try {
//队列满,等待其他线程移除元素
while (count == items.length)
notFull.await();
//插入元素
enqueue(e);
} finally {
//是否锁
lock.unlock();
}
}*/
/*超时时间
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
checkNotNull(e);
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length) {
if (nanos <= 0)
return false;
nanos = notFull.awaitNanos(nanos);
}
enqueue(e);
return true;
} finally {
lock.unlock();
}
}*/ | 23.103448 | 80 | 0.616418 |