text
stringlengths 10
2.72M
|
|---|
/*
* OKRoughCast.java
*
* Created on August 20, 2004, 11:03 AM
*/
package RoughCast;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.imageio.*;
import OKUtils.CmdLineHandler;
import OKUtils.ImageFileUtil;
import java.util.Arrays;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Hashtable;
import java.awt.Image;
import java.awt.image.ImageConsumer;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.IOException;
// See JDC Tech Tips October 21, 1999 for description of these classes
//(deprecated) import com.sun.image.codec.jpeg.JPEGCodec;
//(deprecated) import com.sun.image.codec.jpeg.JPEGEncodeParam;
//(deprecated) import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.io.OutputStream;
import java.util.StringTokenizer;
import java.awt.Toolkit;
// Metrics used for color statistics
enum MetricsType {
MEDIAN,
AVERAGE
}
/**
* This class hosts a little utility to provide a post-camera
* white balance. It can work out the median values of the red,
* green, and blue pixels, and it can scale all the pixels of an
* image so as to restore a previous ratio of red:green:blue to
* 1:1:1. So you can take a shot (perhaps at lowest resolution)
* of a card with a reasonably large area of white or uniform grey,
* and use the values from this image to restore the white balance of
* other shots taken under the same conditions. More realistically,
* the result may not be perfect, but it may provide a more
* convenient starting point for correction with a GUI image editing
* tool than the original.
* <br>
* If you don't have a grey card you trust, you can use a card that
* you don't trust, calibrating it by a third shot, taken under
* better lighting conditions. Both calibration shots and the image
* you wish to corect should be taken with a manual white balance
* setting (e.g. cloudy). Work out the median values as the
* values from the card under the conditions you wish to correct
* from, divided by the values from this card under the conditions
* for which your camera's manual white balance setting was intended.
* I find that a photographic 18% grey card is cheap, and that cheap
* photocopier paper is slightly blue.
* <br>
* It is not obvious that it makes sense to scale pixel values that
* may not be linear functions of light intensity, due to gamma
* correction. However, gamma correction can be at least approximated
* by assuming that the pixel value is the light intensity raised to
* some unknown power. This means that converting down to light
* intensity, scaling, and then converting back up amounts to scaling
* by some power of the original scaling factor. Since our scaling
* factor is determined by the median of a calibration image this all
* comes out in the wash. However, after I have scaled the pixel values
* to adjust the colour, I may have values outside the range 0..255.
* I scale the result (scaling all colours the same) so that the
* highest pixel value in the image is 255. Here I am merely trying
* to preserve as much information as possible, but the choice of
* the best possible quantisation to use here probably does depend on
* gamma. Hopefully this pragmatic choice won't be to bad.
* <br>
* My main reason to use the median as the basis
* of compensation is that it would be unaffected if your calibration
* image (typically of a grey card) was not quite properly framed, or
* contained a little specular reflection, but it also has the advantage
* that (unlike the mean) it gives the same result no matter whether you
* apply it to gamma-corrected values and transform the result back
* to the original scale, or just apply it to the original values and
* ignore gamma-correction.
* <br>
* This program will also apply gamma-correction, just before the
* final scaling step. I do this just because
* it is easy and saves you one step going in and out of JPEG. I
* don't attempt to work out a gamma correction or even advise this
* particularly - it just seemed too easy to leave out.
*/
public class OKRoughCast
{
/** width of subimage to scan */
private static final int SAMPLE_WIDTH = 4;
/** height of subimage to scan */
private static final int SAMPLE_HEIGHT = 4;
private static MetricsType _metrics = MetricsType.MEDIAN;
/** Creates a new instance of OKRoughCast */
public OKRoughCast()
{
}
public static void SetMetricsType(MetricsType m) { _metrics = m; }
public static MetricsType GetMetricsType() { return _metrics; }
/*************** Main API functions ******************************/
/** This reads in an image and returns the chosen-metrics values of RGB
* or null, on error.
*/
public static double[] analyze_image_colors(String imageName, boolean verbose)
{
return Counter.analyse(_metrics, imageName, verbose);
}
/** This reads in an image and returns the chosen-metrics values of RGB
* of subimage around {x, y}
* or null, on error.
*/
public static double[] analyze_image_colors(String imageName,
int x, int y,
boolean verbose)
{
BufferedImage im = Counter.loadImage(imageName);
return Counter.analyse_subImage(_metrics, im,
x-SAMPLE_WIDTH/2, y-SAMPLE_HEIGHT/2,
SAMPLE_WIDTH, SAMPLE_HEIGHT, verbose);
}
/** @return the chosen-metrics values of RGB or null, on error.
*/
public static double[] analyze_image_colors(BufferedImage img, boolean verbose)
{
return Counter.analyse(_metrics, img, verbose);
}
/** @return the chosen-metrics values of RGB of subimage around {x, y}
* or null, on error.
*/
public static double[] analyze_image_colors(BufferedImage img,
int x, int y,
boolean verbose)
{
return Counter.analyse_subImage(_metrics, img,
x-SAMPLE_WIDTH/2, y-SAMPLE_HEIGHT/2,
SAMPLE_WIDTH, SAMPLE_HEIGHT, verbose);
}
public static double[] get_inverse_relation_colors(double[] rgb)
{
double r1=rgb[0], g1=rgb[1], b1=rgb[2]; //orig colors
double r2, g2, b2; // inverse-relation colors
if ( r1 == 0 ) r1 = 0.1;
if ( g1 == 0 ) g1 = 0.1;
if ( b1 == 0 ) b1 = 0.1;
r2 = 100.0;
g2 = r1*r2/g1;
b2 = r1*r2/b1;
return new double[] {r2, g2, b2};
}
/**
* Convert a file according to the arguments here. Don't overwrite -
* it's just too easy to slip up and destroy an image with this
* command-line interface otherwise.
* 'scaleEachChannel'=true - scale to make source R,G,B independently equal target's
= false; // scale source-image colors independently
*/
public static boolean convertFile(String inFileName, String outFileName,
double[] targetMetrics, boolean scaleEachChannel,
double quality, double gamma, boolean verbose)
throws IOException, InterruptedException
{
if (verbose)
{
System.out.println("Will convert " + inFileName + " to " + outFileName +
"; purpose: " + (scaleEachChannel? "color-match to median "
: "white-balance from median ") +
targetMetrics + "; gamma " + (scaleEachChannel? "(ignored)" : gamma));
}
if (new File(outFileName).exists())
{
System.out.println("Stopping conversion as output file " +
outFileName + " exists");
return false;
}
File inpFile = new File(inFileName);
if ( !inpFile.exists() )
{
System.out.println("Stopping conversion as input file " +
inFileName + " doesn't exist");
return false;
}
BufferedImage im = OKUtils.ImageFileUtil.readAsBufferedImage(inpFile);
BufferedImage bi = convertImage(im, targetMetrics, scaleEachChannel,
gamma, verbose);
if ( bi == null )
{
if ( verbose )
System.out.println("Trouble converting image " + inFileName);
return false;
}
return OKUtils.ImageFileUtil.saveImageAsJPEG(bi, 1.0f, outFileName);
}
/**
* Convert an image according to the arguments here.
* @return the new converted image or null on failure.
*/
public static BufferedImage convertImage(BufferedImage im,
double[] targetMetrics, boolean scaleEachChannel, double gamma, boolean verbose)
{
if ( verbose && (im == null) )
{ System.out.println("* convertImage(null) !");
return null;
}
// First time we fetch the image we want to know its size
// and the maximum values of each colour to scale the result
// of conversion
Counter cwb = new OKRoughCast.Counter();
cwb.setVerbose(verbose);
boolean imageAnalysisOK = cwb.countImage(im);
int width = im.getWidth();
int height = im.getHeight();
if ( verbose )
{
if ( !imageAnalysisOK )
{ System.out.println("* convertImage(): Trouble analysing image!");
return null;
}
System.out.println("Image is " + width + " by " + height);
}
int[][] counts = new int[3][];
counts[0] = cwb.getRedCount();
counts[1] = cwb.getGreenCount();
counts[2] = cwb.getBlueCount();
byte[][] tables = null; // for per-channel lookup tables
double[] sourceMetrics = null; // for source median in direct-color-scale
if ( !scaleEachChannel ) // white-balancing
tables = Converter.create_lookup_tables__white_balance(
counts, gamma, targetMetrics);
else
{ // matching colors to another image
sourceMetrics = analyze_image_colors(im, false);
tables = Converter.create_lookup_tables__direct_scale(
counts, sourceMetrics, targetMetrics);
}
// Now we can convert the image
Converter c = new Converter();
c.setVerbose(verbose);
BufferedImage bi = c.process(im, tables);
if ( bi == null )
{
if ( verbose )
System.out.println("* convertImage(): Trouble converting image!");
return null;
}
if ( scaleEachChannel )
{
double[] resultMetrics = analyze_image_colors(bi, false);
System.out.println("Source metrics (R G B): " +
sourceMetrics[0] + " " + sourceMetrics[1] + " " + sourceMetrics[2]);
System.out.println("Target metrics (R G B): " +
targetMetrics[0] + " " + targetMetrics[1] + " " + targetMetrics[2]);
System.out.println("Result metrics (R G B): " +
resultMetrics[0] + " " + resultMetrics[1] + " " + resultMetrics[2]);
}
return bi;
}
/** This class reads in images, keeping the size of the image
* and frequency counts of RGB values.
*/
public static class Counter
{
private final static int MAX_BLOCK_SIZE = 1024 * 1024; // =1Mpix
/** slot x holds the number of pixels seen with value x for red */
private int[] redCounts;
/** slot x holds the number of pixels seen with value x for green */
private int[] greenCounts;
/** slot x holds the number of pixels seen with value x for blue */
private int[] blueCounts;
/** The width of the image */
private int imageWidth;
/** The height of the image */
private int imageHeight;
/** Image to look at */
private BufferedImage inpImage = null;
/** Set true to provide more info */
private boolean verbose;
public Counter()
{
inpImage = null;
redCounts = null; greenCounts = null; blueCounts = null;
}
/** Reads in an image and returns the specified-metrics values of RGB
* or null, on error.
*/
protected static double[] analyse(MetricsType mt, String imageName,
boolean verbose)
{
BufferedImage im = loadImage(imageName);
if ( im == null )
{ // trouble reading in data
System.out.println("Trouble loading image " + imageName);
return null;
}
return analyse(mt, im, verbose);
}
/** @return the specified-metrics values of RGB or null on error.
*/
protected static double[] analyse_subImage(MetricsType mt, BufferedImage im,
int x, int y, int w, int h, boolean verbose)
{
BufferedImage subIm = null;
if ( im == null )
{ if ( verbose )
System.out.println("* analyse_subImage(null)!");
return null;
}
if ( (x < im.getMinX()) || ((x+w) > (im.getMinX()+im.getWidth())) ||
(y < im.getMinY()) || ((y+h) > (im.getMinY()+im.getHeight())) )
{ if ( verbose )
System.out.println("* analyse_subImage(image, x,y,w,h): " +
"out of boundaries!");
return null;
}
try
{
subIm = im.getSubimage(x, y, w, h);
} catch (RasterFormatException e)
{ if ( verbose )
System.out.println("* analyse_subImage(image, x,y,w,h): " +
"out of boundaries!");
return null;
}
return analyse(mt, subIm, verbose);
}
/** @return the specified-metrics values of RGB or null on error.
*/
protected static double[] analyse(MetricsType mt, BufferedImage im,
boolean verbose)
{
Counter cwb = new Counter();
cwb.setVerbose(verbose);
if ( !cwb.countImage(im) )
{
System.out.println("* analyse(image): Trouble analyzing image!");
return null;
}
int[] redCount = cwb.getRedCount();
int[] greenCount = cwb.getGreenCount();
int[] blueCount = cwb.getBlueCount();
double[] metrics = null;
switch (mt) {
case MEDIAN:
metrics = new double[] {
getMedian(redCount), getMedian(greenCount), getMedian(blueCount) };
break;
case AVERAGE:
metrics = new double[] {
getAverage(redCount), getAverage(greenCount), getAverage(blueCount) };
break;
}
if ( verbose )
{
System.out.println("Image is " + cwb.getWidth() + " by " +
cwb.getHeight());
//~ System.out.println("Red, Green, and Blue counts");
//~ for (int i = 0; i < 256; i++)
//~ {
//~ System.out.println(i + ": " + redCount[i] + ", " +
//~ greenCount[i] + ", " + blueCount[i]);
//~ }
System.out.println("Image metrics (R G B): " +
metrics[0] + " " + metrics[1] + " " + metrics[2]);
}
return metrics;
}
/**
* Work out median from frequency counts
* @param counts array of per-pixel-value frequences for one channel
* @return the value of median
*/
protected static double getMedian(int[] counts)
{
// First work out the total number of samples
int sum = 0;
for (int i = 0; i < counts.length; i++)
{
sum += counts[i];
}
// A value is a median if <= half of the values
// lie to its left and also <= half of the values
// lie to its right. We may have many such values. For instance
// in the counts {1, 0, 0, 1} ALL of the data points are medians.
// In such a case we take the middle value of the range of
// medians.
int toLeft = 0;
int toRight = sum;
// This truncation is safe even if there are an odd number of
// values - there will still be a median: e.g. in {1, 0, 0, 1, 0, 1}
// the central 1 is a median.
int half = sum / 2;
int firstMedian = -1;
int lastMedian = -1;
for (int i = 0; i < counts.length; i++)
{
toRight -= counts[i];
if ((toLeft <= half) && (toRight <= half))
{
if (firstMedian < 0)
{ firstMedian = i;
}
lastMedian = i;
}
toLeft += counts[i];
}
return (firstMedian + lastMedian) * 0.5;
}
/**
* Work out average from frequency counts
* @param counts array of per-pixel-value frequences for one channel
* @return the value of average
*/
protected static double getAverage(int[] counts)
{
// average == SUM( val * counts[val] / total_count
int total_count = 0; // ultimately the number of pixels in the sample
int i;
for ( i = counts.length -1; i >= 0; i-- )
total_count += counts[i];
double average = 0.0, sum = 0.0;
for ( i = counts.length -1; i >= 0; i-- )
sum += 1.0 * i * counts[i];
average = sum / total_count;
return average;
}
/** sets verbose flag to get more info printed out */
public void setVerbose(boolean x)
{
verbose = x;
}
/** return the width of the image */
public int getWidth()
{
return (inpImage != null)? inpImage.getWidth() : -1;
}
/** return the height of the image */
public int getHeight()
{
return (inpImage != null)? inpImage.getHeight() : -1;
}
/** return a copy of the array of counts of red pixels. Slot x
* holds the number of such pixels with value x.
*/
public int[] getRedCount()
{
return (int[])redCounts.clone();
}
/** return a copy of the array of counts of green pixels. Slot x
* holds the number of such pixels with value x.
*/
public int[] getGreenCount()
{
return (int[])greenCounts.clone();
}
/** return a copy of the array of counts of blue pixels. Slot x
* holds the number of such pixels with value x.
*/
public int[] getBlueCount()
{
return (int[])blueCounts.clone();
}
/**
* return the image
*/
public BufferedImage getImage()
{
return inpImage;
}
/** Return the largest pixel value seen */
private static int getMax(int[] counts)
{
for (int i = counts.length - 1; i >= 0; i--)
{
if (counts[i] != 0)
{
return i;
}
}
return 0;
}
protected boolean image_load_failed()
{
return (inpImage == null);
}
/**
* Loads in an image and makes frequency counts.
*/
protected boolean countImage(String name)
{
if ( (inpImage =loadImage(name)) != null )
return countImage(inpImage);
else
return false;
}
/**
* Loads in an image.
* @return the loaded image on success, null on failure
*/
protected static BufferedImage loadImage(String name)
{
File imgFile = new File(name);
// read the image file
BufferedImage im = ImageFileUtil.readAsBufferedImage(imgFile);
if ( im == null )
return null;
System.out.println("Source image " + im.getWidth() + "*"
+ im.getHeight() + "\tread from "
+ imgFile.getAbsolutePath());
return im;
}
/**
* Makes frequency counts on image 'im'.
*/
protected boolean countImage(BufferedImage im)
{
if ( im == null )
return false;
inpImage = im;
// obtain and analyze the pixel data in chunks
redCounts = new int[256];
greenCounts = new int[256];
blueCounts = new int[256];
int imgWidth = inpImage.getWidth();
int maxChunkStep = detect_max_width_of_horz_chunk(inpImage,
MAX_BLOCK_SIZE);
boolean cntResult = true;
for ( int chunkLeftBound = 0; chunkLeftBound < imgWidth;
chunkLeftBound += maxChunkStep )
{
int chunkRightBound = chunkLeftBound + maxChunkStep - 1;
if ( chunkRightBound > (imgWidth-1) )
chunkRightBound = imgWidth - 1;
int pixels[] = ImageDataReader.getImagePixels(inpImage,
chunkLeftBound, 0,
chunkRightBound, inpImage.getHeight()-1);
if ( pixels == null )
return false;
cntResult &= countPixels(chunkRightBound-chunkLeftBound+1,
inpImage.getHeight(),
inpImage.getColorModel(), pixels);
}
return cntResult;
}
/**
* @return size of horizontal part to split image into blocks,
* so that each block is no more than maxBlockSize. This size holds
* for all but the last chunk
**/
protected static int detect_max_width_of_horz_chunk(BufferedImage bimage,
int maxBlockSize)
{
int imgWidth = bimage.getWidth();
int nChunks = detect_numer_of_horz_chunks(bimage, maxBlockSize);
// chunk width is maxChunkStep for all but the last chunk
int maxChunkStep = (int)Math.ceil((double)imgWidth / nChunks);
return maxChunkStep;
}
/**
* @return numer of horizontal parts to split image into,
* so that each block is no more than maxBlockSize
**/
protected static int detect_numer_of_horz_chunks(BufferedImage bimage,
int maxBlockSize)
{
int imgWidth = bimage.getWidth();
int imgHeight = bimage.getHeight();
double totalPixels = imgWidth * imgHeight;
int nChunks = (int)Math.ceil(totalPixels / maxBlockSize);
return nChunks;
}
protected boolean countPixels(int w, int h, ColorModel cm, int[] pixels)
{
if ( w*h*cm.getNumComponents() != pixels.length )
{
System.out.println("* countPixels() got incompatible parameters!");
return false;
}
int pixelStep = cm.getNumComponents();
for ( int i = 0; i < pixels.length; i+=pixelStep )
{
int pix = pixels[i];
redCounts[pixels[i+0]/*cm.getRed(pix)*/]++;
greenCounts[pixels[i+1]/*cm.getGreen(pix)*/]++;
blueCounts[pixels[i+2]/*cm.getBlue(pix)*/]++;
}
return true;
}
}//END_OF__class_Counter
public void read_cmd_line(String[] args) throws Exception
{
CmdLineHandler cmdLine = new CmdLineHandler(args);
System.out.println(cmdLine);
// TODO: set "defaults" - as if no arguments
/* workDir = new File(".");
String[] workDirA = cmdLine.params_of_switch("-workdir");
if ( workDirA != null )
workDir = new File(workDirA[0]);
*/
/*
String[] paramArr =null;
if ( (paramArr =cmdLine.params_of_switch("-image_file")) != null )
imgFile = new File(paramArr[0]);
**/
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
}
/**
* This class converts the image, writing to a BufferedImage.
*/
public static class Converter
{
/** Three 256-entry lookup tables for red, green, and blue */
private byte[][] lookup;
/** BufferedImage to write converted results to */
private BufferedImage ourTarget;
/** Set to true when ImageProducer says complete */
private boolean complete = false;
/** ImageProducer with the data */
private ImageProducer producer;
/** status provided by ImageProducer */
private int imageStatus;
/** Set to true to get more info printed out */
private boolean verbose;
/** set verbose flag */
public void setVerbose(boolean x)
{
verbose = x;
}
/**
* Call this to process an image, scaling the values according
* to the lookup table in scale.
* @param source image to be processed
* @param scale 3 per-band arrays for lookup table
* @return the resulting image
*/
public BufferedImage process(BufferedImage source, byte[][] scale)
{
//BufferedImage bi = null;
BufferedImage bi = new BufferedImage(
source.getWidth(), source.getHeight(), source.getType());
int compNum = source.getColorModel().getNumComponents();
//TODO: provide RenderingHints instead of null
LookupOp lookupop = new LookupOp(new ByteLookupTable(0, scale), null);
try
{
bi = lookupop.filter(source, bi);
} catch (IllegalArgumentException e)
{ System.out.println("process(): number of arrays in the LookupTable"
+ " does not meet the restrictions.");
return null;
}
ourTarget = bi;
return ourTarget;
}
/**
* Creates lookup tables doing both color balancing and gamma correction.
* @param counts 3 per-band arrays of pixel value frequences - counts[0]=array-of-red-frequences.
*/
protected static byte[][] create_lookup_tables__white_balance(
int[][] counts, double gamma, double[] median)
{
final double ZERO_SUBSTITUTE = 0.5;
// Want to divide by respective medians, add optional
// gamma correction, and then scale
// result so that the maximum pixel value produced is 255
double max = 0.0;
for (int i = 0; i < counts.length; i++)
{
double v = median[i];
if (v <= 0.0)
{ // Shouldn't be here, but if we are avoid division by zero
v = ZERO_SUBSTITUTE;
}
double x = getMax(counts[i]) / v;
if (gamma != 1.0)
{
x = Math.pow(x, gamma);
}
// x is what the corrected value would be without scaling to
// fit everything into the range 0..255
if (x > max)
{
max = x;
}
}
// Now create lookup tables for conversion
byte[][] tables = new byte[3][];
for (int i = 0; i < tables.length; i++)
{
double v = median[i];
if (v <= 0.0)
{
v = ZERO_SUBSTITUTE;
}
byte[] lookup = new byte[256];
tables[i] = lookup;
for (int j = 0; j < lookup.length; j++)
{
double x = j / v;
if (gamma != 1.0)
{
x = Math.pow(x, gamma);
}
// Apply scaling to fit in range 0..255
lookup[j] = (byte)Math.round(x * 255.0 / max);
}
}
return tables;
}
/**
* Creates lookup tables doing direct color scaling.
* Basically: vNew = vOld * targetMetrics / sourceMetrics
* @param counts 3 per-band arrays of pixel value frequences - counts[0]=array-of-red-frequences.
*/
protected static byte[][] create_lookup_tables__direct_scale(
int[][] counts, double[] sourceMetrics, double[] targetMetrics)
{
final double ZERO_SUBSTITUTE = 0.5;
//~ // Want to divide by respective targetMetricss, add optional
//~ // gamma correction, and then scale
//~ // result so that the maximum pixel value produced is 255
//~ double max = 0.0;
//~ for (int i = 0; i < counts.length; i++)
//~ {
//~ double sm = sourceMetrics[i], tm = targetMetrics[i];
//~ if (sm <= 0.0)
//~ { // Shouldn't be here, but if we are avoid division by zero
//~ sm = ZERO_SUBSTITUTE;
//~ }
//~ double x = getMax(counts[i]) * tm / sm;
//~ // x is what the corrected value would be without scaling to
//~ // fit everything into the range 0..255
//~ if (x > max)
//~ {
//~ max = x;
//~ }
//~ }
// Now create lookup tables for conversion
byte[][] tables = new byte[3][];
for (int i = 0; i < tables.length; i++)
{
double sm = sourceMetrics[i], tm = targetMetrics[i];
if (sm <= 0.0)
{ // Shouldn't be here, but if we are avoid division by zero
sm = ZERO_SUBSTITUTE;
}
byte[] lookup = new byte[256];
tables[i] = lookup;
for (int j = 0; j < lookup.length; j++)
{
// Apply scaling to match target color
double x = j * tm / sm;
//~ // Apply scaling to fit in range 0..255
//~ lookup[j] = (byte)Math.round(x * 255.0 / max);
// Apply restriction to the max of 255
lookup[j] = (byte)( (x <= 255)? x : 255 );
}
}
return tables;
}
/** @return the largest pixel value seen */
private static int getMax(int[] counts)
{
for (int i = counts.length - 1; i >= 0; i--)
{
if (counts[i] != 0)
{
return i;
}
}
return 0;
}
}//END_OF__class_Converter
}//END_OF__class_OKRoughCast
|
package com.saaolheart.mumbai.store.stock;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StockHistoryRepo extends JpaRepository<StockHistoryDetailsDomain, Long> {
}
|
// Sun Certified Java Programmer
// Chapter 8; P676_2
// Inner Classes
class Food {
Popcorn p = new Popcorn() {
public void sizzle() {
System.out.println("anonymous sizzling popcorn");
}
public void pop() {
System.out.println("anonymous popcorn");
}
};
public void popIt() {
p.pop(); // OK, Popcorn has a pop() method
p.sizzle(); // Not Legal! Popcorn does not have sizzle()
}
}
|
package ashman;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Observable;
import javafx.scene.canvas.Canvas;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.media.AudioClip;
public class Game extends Observable implements Serializable{
private static final Image
GAME_OVER = new Image("images/game_over.png", 400, 160, false, false),
YOU_WON = new Image("images/you_won.png", 400, 180, false, false),
PAUSED = new Image("images/paused.png", 400, 210, false, false),
LEVEL_TWO = new Image("images/level_two.png", 400, 180, false, false);
private transient Canvas metaLayer;
private final AshLayer ashLayer;
private transient StackPane stackPane;
private ArrayList<GhostLayer> ghosts;
private transient AudioClip intro, game_over, you_won;
private KeyCode lastKey;
private int ghostSpeed;
public transient BorderPane borderPane;
public boolean introMutex, paused;
public int state, numOfGhosts;
public final Maze maze;
public Game(int level, int ashStartX, int ashStartY, int numOfGhosts, int ghostSpeed){
lastKey = KeyCode.R;
this.ghostSpeed = ghostSpeed;
borderPane = new BorderPane();
introMutex = true;
maze = new Maze(level, this);
ashLayer = new AshLayer(maze, ashStartX, ashStartY);
this.numOfGhosts = numOfGhosts;
initiateGhosts();
metaLayer = new Canvas(400, 400);
stackPane = new StackPane();
initiateStackPane();
borderPane.setCenter(stackPane);
state = 0;
paused = false;
}
public void initiateAudio(){
intro = new AudioClip(getClass().getResource("/resources/intro.aiff").toExternalForm());
game_over = new AudioClip(getClass().getResource("/resources/game_over.aiff").toExternalForm());
you_won = new AudioClip(getClass().getResource("/resources/you_won.aiff").toExternalForm());
Thread audioThread = new Thread(){
@Override
public void run(){
if(introMutex){
intro.play();
while(intro.isPlaying()){
introMutex = true;
}
introMutex = false;
}
}
};
audioThread.start();
}
public void levelTwo(int level, int ashStartX, int ashStartY, int numOfGhosts, int ghostSpeed ){
refresh(level, ashStartX, ashStartY, numOfGhosts, ghostSpeed);
lastKey = KeyCode.R;
ashLayer.stop();
ghosts.stream().forEach((ghost) -> {
ghost.stop();
});
metaLayer.getGraphicsContext2D().clearRect(0, 0, 400, 400);
metaLayer.getGraphicsContext2D().drawImage(LEVEL_TWO, 0, 68);
paused = true;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException{
ois.defaultReadObject();
metaLayer = new Canvas(400, 400);
stackPane = new StackPane();
borderPane = new BorderPane();
initiateStackPane();
borderPane.setCenter(stackPane);
initiateAudio();
lastKey = KeyCode.R;
pause();
}
public void refresh(int level, int ashStartX, int ashStartY, int numOfGhosts, int ghostSpeed){
introMutex = true;
lastKey = KeyCode.R;
maze.refresh(level);
ashLayer.refresh(ashStartX, ashStartY);
stackPane.getChildren().clear();
this.numOfGhosts = numOfGhosts;
this.ghostSpeed = ghostSpeed;
initiateGhosts();
metaLayer.getGraphicsContext2D().clearRect(0, 0, 400, 400);
initiateStackPane();
borderPane.setCenter(stackPane);
state = 0;
resume();
initiateAudio();
}
private void initiateGhosts(){
ghosts = new ArrayList<>();
for(int color = 0; color < numOfGhosts; color++){
ghosts.add(new GhostLayer(maze, ashLayer, 10, 9, color%4, color%3, this, ghostSpeed));
}
}
public void onKeyPress(KeyEvent event){
KeyCode code = event.getCode();
if(!lastKey.equals(code)){
if(!introMutex && !paused){
if(null != code)
switch (code) {
case UP:
ashLayer.move(AshLayer.UP);
break;
case RIGHT:
ashLayer.move(AshLayer.RIGHT);
break;
case DOWN:
ashLayer.move(AshLayer.DOWN);
break;
case LEFT:
ashLayer.move(AshLayer.LEFT);
break;
case HOME:
maze.cheat();
break;
case P:
pause();
}
lastKey = code;
}
}
if(code == KeyCode.R || code == KeyCode.ENTER){
resume();
lastKey = code;
}
}
private void initiateStackPane(){
stackPane.getChildren().add(maze.canvas);
stackPane.getChildren().add(ashLayer.canvas);
ghosts.stream().forEach((ghost) -> {
stackPane.getChildren().add(ghost.canvas);
});
stackPane.getChildren().add(metaLayer);
}
public void gameOver(){
ashLayer.stop();
ghosts.stream().forEach((ghost) -> {
ghost.stop();
});
metaLayer.getGraphicsContext2D().drawImage(GAME_OVER, 0, 68);
game_over.play();
state = -1;
setChanged();
notifyObservers();
}
public void scoreChange(){
setChanged();
notifyObservers();
}
public void onWin(){
ashLayer.stop();
ghosts.stream().forEach((ghost) -> {
ghost.stop();
});
metaLayer.getGraphicsContext2D().drawImage(YOU_WON, 0, 68);
you_won.play();
state = 1;
setChanged();
notifyObservers();
}
@Override
public boolean hasChanged(){
return state == 0;
}
public void refresh() {
maze.refresh();
ashLayer.refresh();
initiateAudio();
}
public void pause() {
lastKey = KeyCode.R;
ashLayer.stop();
ghosts.stream().forEach((ghost) -> {
ghost.stop();
});
metaLayer.getGraphicsContext2D().clearRect(0, 0, 400, 400);
metaLayer.getGraphicsContext2D().drawImage(PAUSED, 0, 68);
paused = true;
}
private void resume() {
paused = false;
ashLayer.pausedMutex = false;
metaLayer.getGraphicsContext2D().clearRect(0, 0, 400, 400);
ghosts.stream().forEach((ghost) -> {
ghost.resume();
});
}
}
|
package com.oumar.learn.application;
public final class PageMap {
private PageMap(){
}
public static final String ADMIN = "admin";
public static final String REGISTER_PRE = "register";
public static final String LOGIN = "login";
public static final String HOME = "home";
}
|
package com.allen.lightstreamdemo.callback;
import com.orhanobut.logger.Logger;
import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;
/**
* Created by: allen on 16/8/11.
*/
public class SubscriberCallback<T > extends Subscriber<T> {
private final static String TAG = "SubscriberCallback";
private NetCallback<T> mNetCallback;
public SubscriberCallback(NetCallback<T> netCallback) {
this.mNetCallback = netCallback;
}
@Override
public void onCompleted() {
mNetCallback.onCompleted();
}
@Override
public void onError(Throwable e) {
Logger.d("onError: " + e.getLocalizedMessage());
int code = 404;
String msg = "未知错误";
if (e instanceof HttpException) {
code = 500;
msg = "世界最遥远的距离就是没网";
}
mNetCallback.onFailer(code, msg);
mNetCallback.onCompleted();
}
@Override
public void onNext(T t) {
mNetCallback.onSuccess(t);
}
}
|
package adsaufgabe1;
public class Shellsort_tsosedow implements IShellsort {
/* Der Konstruktor hat kein Argument
*/
public Shellsort_tsosedow() {
}
/* Rueckgabewert: Anzahl der Schluesselvergleiche
*/
public int shellsort(IPermutation[] feld) {
int vgl = 1;
int schrittweite = 1;
for(int i = 0; i < feld.length; i++) {
System.out.print(i + ": ");
feld[i].print();
}
while (3*schrittweite+1 < feld.length) {
schrittweite = (schrittweite*3)+1;
vgl++;
}
System.out.println("Schrittweite berechnet");
vgl++;
while (schrittweite > 0) {
System.out.println("Führe Insertionsort mit Schreitweite " + schrittweite + " aus");
vgl += insertionsortMitSchrittweite(feld, schrittweite);
schrittweite /= 3;
}
return vgl;
}
/* Rueckgabewert: Anzahl der Schluesselvergleiche
*/
public int insertionsortMitSchrittweite(IPermutation[] feld, int schrittweite) {
int vgl = 1;
int nichtTauschen = 0;
for (int i = schrittweite; i < feld.length; i++) {
int perm1Betrag = Math.abs(feld[i].wert(1)-feld[i].wert(feld[i].laenge()));
IPermutation perm1 = feld[i];
System.out.println("\nHauptpermutation ist " + i + ": " + perm1);
System.out.println("");
int k = i;
System.out.println("Vergleich der Beträge von Hauptpermutation "+ i + ": " + perm1 + " mit " + (k-schrittweite) + ": " + feld[k-schrittweite]);
while (k > schrittweite-1 && Math.abs(feld[k-schrittweite].wert(1)-feld[k-schrittweite].wert(feld[0].laenge())) >= perm1Betrag && nichtTauschen == 0) {
if(Math.abs(feld[k-schrittweite].wert(1)-feld[k-schrittweite].wert(feld[k-schrittweite].laenge())) > perm1Betrag) {
feld[k] = feld[k-schrittweite];
System.out.println("Feldstelle " + k + " überschrieben mit Vorgängerstelle "+ (k-schrittweite) + " da es größer war");
System.out.print("xAltes k: " + k);
k = k - schrittweite;
System.out.println(", wird zu " + k);
}
else {
int stelle = -1;
for(int j = 1; j <= feld[0].laenge(); j++) {
if ((perm1.wert(j) != feld[k-schrittweite].wert(j)) && stelle == -1) {
stelle = j;
System.out.println("Ungleiche Stelle " + j + " in Permutationen gefunden");
}
}
if(stelle != -1 && (perm1.wert(stelle) < feld[k-schrittweite].wert(stelle))) {
feld[k] = feld[k-schrittweite];
System.out.println("Feld " + k + " überschrieben mit Vorgänger "+ (k-schrittweite) + " da Stelle größer war");
}
else {
System.out.println("Vorgänger ist kleiner, kein Tausch erforderlich");
nichtTauschen = 1;
}
System.out.print("yAltes k: " + k);
k = k - schrittweite;
System.out.println(", wird zu " + k);
}
if(k > schrittweite-1) {
System.out.println("Vergleich der Beträge von Hauptpermutation "+ i + ": " + perm1 + " mit " + (k-schrittweite) + ": " + feld[k-schrittweite]);
}
vgl++;
}
if (nichtTauschen == 0) {
feld[k] = perm1;
System.out.println("Feldstelle " + k + ": " + feld[k] + " ersetzt mit Hauptpermutation "+ perm1);
}
else { //das später entfernen
feld[k+ schrittweite] = perm1;
System.out.println("Feldstelle " + (k+schrittweite) + ": " + feld[k+schrittweite] + " ersetzt mit Hauptpermutation "+ perm1);
nichtTauschen = 0;
}
for(int x = 0; x < feld.length; x++) {
System.out.print(x + ": " + feld[x] + "\n");
}
}
return vgl;
}
}
/*
*
*
* Was macht der Konstruktor? Was muss da rein?
*
* HTWKLOGIN == Nutzername zum einloggen?
*
*
*
*/
|
package com.company.ch01_Array;
public class Student {
private String name;
private int score;
public Student(String name,int score){
this.name=name;
this.score=score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString(){
return (String.format("name:%s score:%d",name,score));
}
public static void main(String[] args) {
Student Tom =new Student("Tom",55);
Student Jack = new Student("Jack",66);
Student Luce = new Student("Luce",99);
Array<Student> arr=new Array<>();
arr.addLast(Tom);
arr.addLast(Jack);
arr.addLast(Luce);
System.out.println(arr);
}
}
|
//模仿判断valid parenthesis的方法,记录已经使用的‘(’ 和‘)’,以及抵消的‘(’
//用dfs
class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<>();
if(n == 0){
return ans;
}
StringBuilder sol = new StringBuilder();
dfs(ans, sol, n, 0, 0, 0);
return ans;
}
private void dfs(List<String> ans, StringBuilder sol, int n,
int leftCnt, int curLeft, int rightCnt){
if(leftCnt == n && rightCnt == n){
ans.add(sol.toString());
return;
}
//是否允许sol中添加'('字符
if(leftCnt < n){
sol.append('(');
dfs(ans, sol, n, leftCnt + 1, curLeft + 1, rightCnt);
sol.deleteCharAt(sol.length() - 1);
}
//是否允许sol中添加‘)’字符
if(rightCnt < n && curLeft > 0){
sol.append(')');
dfs(ans, sol, n, leftCnt, curLeft - 1, rightCnt + 1);
sol.deleteCharAt(sol.length() - 1);
}
}
}
|
package zajaczkowski.adrian;
import zajaczkowski.adrian.simulation.Simulation;
import zajaczkowski.adrian.tools.Item;
import zajaczkowski.adrian.tools.Rocket;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class App {
public static void main(String[] args) throws IOException {
final Path phase1Path = Paths.get("./src/main/resources/Phase-1.txt");
final Path phase2Path = Paths.get("./src/main/resources/Phase-2.txt");
Simulation simulation = new Simulation();
ArrayList<Item> itemsForPhase1 = simulation.loadItems(phase1Path);
ArrayList<Item> itemsForPhase2 = simulation.loadItems(phase2Path);
System.out.println("Loading U1 fleet...");
ArrayList<Rocket> fleetU1 = new ArrayList<>();
fleetU1.addAll(simulation.loadU1(itemsForPhase1));
fleetU1.addAll(simulation.loadU1(itemsForPhase2));
System.out.println("Total budget for U1 fleet is: " + simulation.runSimulation(fleetU1) + " millions $");
System.out.println("Loading U2 fleet...");
ArrayList<Rocket> fleetU2 = new ArrayList<>();
fleetU2.addAll(simulation.loadU2(itemsForPhase1));
fleetU2.addAll(simulation.loadU2(itemsForPhase2));
System.out.println("Total budget for U2 fleet is: " + simulation.runSimulation(fleetU2) + " millions $");
}
}
|
package com.ubs.opsit.interviews;
import org.junit.Assert;
import org.junit.Test;
public class ClockValidatorTest {
@Test
public void testHourValidation() {
Assert.assertFalse(BerlinClockValidator.validateTimeFormat("72:00:00"));
Assert.assertTrue(BerlinClockValidator.validateTimeFormat("23:00:00"));
}
@Test
public void testMinuteValidation() {
Assert.assertFalse(BerlinClockValidator.validateTimeFormat("00:72:00"));
Assert.assertTrue(BerlinClockValidator.validateTimeFormat("00:28:00"));
}
@Test
public void testSecondValidation() {
Assert.assertFalse(BerlinClockValidator.validateTimeFormat("00:00:70"));
Assert.assertTrue(BerlinClockValidator.validateTimeFormat("00:00:06"));
}
@Test
public void testFormatValidation() {
Assert.assertFalse(BerlinClockValidator.validateTimeFormat("72-00-00"));
Assert.assertTrue(BerlinClockValidator.validateTimeFormat("22:34:20"));
}
}
|
package com.mobiledev.shapedprogressview;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button squareButton, circleButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
squareButton = (Button)findViewById(R.id.SquareProgress);
circleButton = (Button)findViewById(R.id.CircleProgress);
squareButton.setOnClickListener(this);
circleButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId() == R.id.SquareProgress)
{
Intent intentSquare = new Intent(MainActivity.this, SquareProgressActivity.class);
startActivity(intentSquare);
}
else if(view.getId() == R.id.CircleProgress)
{
}
}
}
|
package com.penzias.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.penzias.core.BasicServiceImpl;
import com.penzias.core.interfaces.BasicMapper;
import com.penzias.dao.SmDepartmentMapper;
import com.penzias.entity.SmDepartment;
import com.penzias.entity.SmDepartmentExample;
import com.penzias.service.SmDepartmentService;
@Service("smDepartmentService")
public class SmDepartmentServiceImpl extends BasicServiceImpl<SmDepartmentExample, SmDepartment> implements SmDepartmentService {
@Resource
private SmDepartmentMapper smDepartmentMapper;
@Override
public BasicMapper<SmDepartmentExample, SmDepartment> getMapper(){
return smDepartmentMapper;
}
}
|
package com.campus.controller;
import com.campus.entity.Exam;
import com.campus.utils.PoiImportExcel;
import com.campus.common.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 文件上传控制层
*/
@Controller
@RequestMapping("/file")
public class FileController {
/**
* 上传文件
* @param filename
* @return
*/
@RequestMapping("/fileUpload")
@ResponseBody
public Result fileUpload(@RequestBody MultipartFile filename, HttpServletRequest request){
/**
* 应该返回上传成功还是失败,失败了,需要把原因返回出去,
* 成功了,需要把总分返回出去
*/
//创建Result对象
Result result1 = new Result();
if(filename==null || filename.equals("") || filename.toString()==""){
result1.setSuccess("fail");
result1.setMessage("您还没有上传文件哦!");
return result1;
}
//获取导入的Excel表格的所有信息
Result result = PoiImportExcel.fileupload(filename);
//获取Excel表格的信息
List<Exam> data1 = (List<Exam>) result.getData1();
request.getSession().setAttribute("exam",data1);
//判断结果是否为success
if(result.getSuccess()=="success"){
//求出总分
Double efenzhi = 0.0;
for(Exam exam:data1){
efenzhi += exam.getEfenzhi();
}
//把得到的总分进行赋值
result.setData2(efenzhi+"");
}
//返回结果
return result;
}
}
|
package ro.Stellrow.HarderMinecraftMobs.utils;
import org.bukkit.configuration.file.FileConfiguration;
public class ConfigurationManager {
public void updateValues(FileConfiguration configuration){
updateAffectValues(configuration);
updateMobStats(configuration);
updateMobStatsAffect(configuration);
updateMobGear(configuration);
updateChance(configuration);
}
public boolean affectZombies;
public boolean affectSkeletons;
public boolean affectSpiders;
public boolean affectCreepers;
public boolean affectSpawners;
private void updateAffectValues(FileConfiguration configuration){
affectZombies = configuration.getBoolean("General.MobConfig.affectZombies",true);
affectSkeletons = configuration.getBoolean("General.MobConfig.affectSkeletons",true);
affectSpiders = configuration.getBoolean("General.MobConfig.affectSpiders",true);
affectCreepers = configuration.getBoolean("General.MobConfig.affectCreeper",true);
affectSpawners = configuration.getBoolean("General.AffectSpawnerMobs",true);
}
public boolean affectZombieHealth;
public boolean affectZombieSpeed;
public boolean affectZombieAttack;
public boolean affectSkeletonHealth;
public boolean affectSkeletonSpeed;
public boolean affectSkeletonAttack;
public boolean affectSpiderHealth;
public boolean affectSpiderSpeed;
public boolean affectSpiderAttack;
public boolean affectCreeperHealth;
public boolean affectCreeperSpeed;
private void updateMobStatsAffect(FileConfiguration configuration){
affectZombieHealth = affectEntityHealth("Zombie",configuration);
affectSkeletonHealth = affectEntityHealth("Skeleton",configuration);
affectSpiderHealth = affectEntityHealth("Spider",configuration);
affectCreeperHealth = affectEntityHealth("Creeper",configuration);
affectZombieSpeed = affectEntitySpeed("Zombie",configuration);
affectSkeletonSpeed = affectEntitySpeed("Skeleton",configuration);
affectSpiderSpeed = affectEntitySpeed("Spider",configuration);
affectCreeperSpeed = affectEntitySpeed("Creeper",configuration);
affectZombieAttack = affectEntityAttack("Zombie",configuration);
affectSkeletonAttack = affectEntityAttack("Skeleton",configuration);
affectSpiderAttack = affectEntityAttack("Spider",configuration);
}
public int zombieHealth;
public int skeletonHealth;
public int spiderHealth;
public int creeperHealth;
public double zombieSpeed;
public double skeletonSpeed;
public double spiderSpeed;
public double creeperSpeed;
public double zombieAttack;
public double skeletonAttack;
public double spiderAttack;
private void updateMobStats(FileConfiguration configuration){
zombieHealth = configuration.getInt("Stats.Zombie.Health",20);
skeletonHealth = configuration.getInt("Stats.Skeleton.Health",20);
spiderHealth = configuration.getInt("Stats.Spider.Health",20);
creeperHealth = configuration.getInt("Stats.Creeper.Health",20);
zombieSpeed = configuration.getDouble("Stats.Zombie.Speed",0.23);
skeletonSpeed = configuration.getDouble("Stats.Skeleton.Speed",0.25);
spiderSpeed = configuration.getDouble("Stats.Spider.Speed",0.3);
creeperSpeed = configuration.getDouble("Stats.Creeper.Speed",0.25);
zombieAttack = configuration.getDouble("Stats.Zombie.Attack",4);
skeletonAttack = configuration.getDouble("Stats.Skeleton.Attack",4);
spiderAttack = configuration.getDouble("Stats.Spider.Attack",4);
}
public boolean zombieRandomGear;
public boolean skeletonRandomGear;
private void updateMobGear(FileConfiguration configuration){
zombieRandomGear = configuration.getBoolean("General.MobConfig.MobStrength.Zombie.randomGear",true);
skeletonRandomGear = configuration.getBoolean("General.MobConfig.MobStrength.Skeleton.randomGear",true);
}
public int randomGearChance;
private void updateChance(FileConfiguration configuration){
randomGearChance = configuration.getInt("General.ChanceConfig.spawnWithRandomGearChance",30);
}
private boolean affectEntityHealth(String type,FileConfiguration configuration){
return configuration.getBoolean("General.MobConfig.MobStrength."+type+".higherHealth",true);
}
private boolean affectEntitySpeed(String type,FileConfiguration configuration){
return configuration.getBoolean("General.MobConfig.MobStrength."+type+".higherSpeed",true);
}
private boolean affectEntityAttack(String type,FileConfiguration configuration){
return configuration.getBoolean("General.MobConfig.MobStrength."+type+".higherAttack",true);
}
}
|
package com.example.android_essential_07_hw2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
int pos = 0;
int[] ringtones = {R.raw.aleksandr_vikto, R.raw.billie_eilish, R.raw.billie_eilish_b, R.raw.furkan_soysal, R.raw.na_zvonochek, R.raw.suprafive_latel};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickButton(View view) {
switch (view.getId()) {
case R.id.buttonStart:
startService(
new Intent(MainActivity.this, PlayService.class));
break;
case R.id.buttonStop:
stopService(
new Intent(MainActivity.this, PlayService.class));
break;
case R.id.buttonBack:
back();
break;
case R.id.buttonNext:
next();
break;
}
}
private void back() {
if (pos != 0) {
pos--;
}
setRingtone();
}
private void next() {
if (pos != ringtones.length - 1) {
pos++;
}
setRingtone();
}
private void setRingtone() {
PlayService.setRingtone(pos);
stopService(
new Intent(MainActivity.this, PlayService.class));
startService(
new Intent(MainActivity.this, PlayService.class));
}
}
|
package org.bashemera.openfarm.form;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.springframework.data.annotation.Id;
public class AccountForm {
@Id
private String id;
@Size(min=1, max=32, message="The account name must be between 1 and 32 characters")
private String name;
@NotNull(message="Please enter unique code")
@Size(min=3, max=30, message="The code must be between 3 and 32 characters")
private String code;
@NotNull
@Pattern(regexp = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$", message="Email address is invalid")
private String email;
@Size(min=1, max=32, message="The first name must be between 1 and 32 characters")
private String firstName;
@Size(min=1, max=32, message="The last name must be between 1 and 32 characters")
private String lastName;
@Size(min=8, max=32, message="The password must be between 8 and 32 characters")
private String password;
@NotNull(message="Password and confirm password not a match")
private String confirmPassword;
private boolean status = false;
private String token;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code.replaceAll("\\s+", "_").toLowerCase();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
checkPassword();
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
//checkPassword();
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
private void checkPassword() {
if (this.password == null || this.confirmPassword == null)
return;
else if(!this.password.equals(this.confirmPassword)) {
System.out.println("Checking this just");
this.confirmPassword = null;
}
}
}
|
package com.shopify.mapper;
import org.apache.ibatis.annotations.Mapper;
import com.shopify.seller.SellerData;
@Mapper
public interface SellerMapper {
public int insertSeller(SellerData seller);
public int updateSeller(SellerData seller);
public int updateSellerPasswd(SellerData seller);
public int selectSellerCount (SellerData seller);
public SellerData selectSeller (SellerData seller);
}
|
package ga.selection;
import ga.Population;
public class SelectionRandomBasedElitist extends Selection {
private int numElitist = 1;// keeps n best individuals
@Override
public void select(Population population) {
super.select(population);
// keep 'n' best individuals for next generation
for (int rank = 0; rank < numElitist; rank++) {
plan.reserve(population.getIndividuals().get(rank));
}
// select parents until target MatingPlan size is reached
while (plan.size() < returnSize) {
// select two individuals at random for breeding
plan.add(population.getRandomIndividual(), population.getRandomIndividual());
}
}
}
|
/*(Financial application: find the sales amount) You have just started a sales job in a department store.
* Your pay consists of a base salary and a commission. The base salary is $5,000.
* Write a program that finds the minimum sales you have to generate in order to make $30,000.
*/
import java.util.Scanner;
public class Problem5_39 {
public static void main(String[] args) {
final double COMMISSION_SOUGHT = 30000;
double salesAmount, commission, balance;
salesAmount = 0;
do {
balance = commission = 0;// set balance and commission to 0
salesAmount += 0.01;// Increase sales amount by $0.01
//If sales amount is $10,000.01 and above commission rate is 12%
if(salesAmount > 10000)
commission += (balance = salesAmount - 10000) * 0.12;
if(salesAmount > 5000)
commission += (balance-= balance - 5000) * 0.10;
if(salesAmount > 0)
commission += balance * 0.08;
}while(commission < COMMISSION_SOUGHT);
System.out.printf("Minimum sales to earn $30,000: $%.0f\n ", salesAmount);
}
}
|
package com.sunny.token.response;
import lombok.Getter;
public class Response<T>{
@Getter
private String code;
@Getter
private String message;
@Getter
private T result;
public Response(){}
public Response(T result){
this.result = result;
this.code = ResponseCode.SUCCESS.getCode();
this.message = ResponseCode.SUCCESS.getMessage();
}
public Response(ResponseCode code){
this.code = code.getCode();
this.message = code.getMessage();
}
public T get(){
return result;
}
public boolean success(){
return ResponseCode.SUCCESS.equals(code);
}
}
|
package br.com.alura.core;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistenceUtil {
private static final String PERSISTENCE_UNIT_NAME = "conta-db";
private PersistenceUtil() {
super();
}
public static EntityManager entityManager(){
EntityManagerFactory emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
return emf.createEntityManager();
}
}
|
package com.jawspeak.unifier.changes;
import java.util.Arrays;
import java.util.List;
public class NewClass implements Change {
private int version;
private int access;
private String name;
private String signature;
private String superName;
private String[] interfaces;
private List<NewMethod> newMethods;
private List<NewField> newFields;
public NewClass(int version, int access, String name, String signature, String superName,
String[] interfaces, List<NewMethod> newMethods, List<NewField> newFields) {
this.version = version;
this.access = access;
this.name = name;
this.signature = signature;
this.superName = superName;
this.interfaces = interfaces;
this.newMethods = newMethods;
this.newFields = newFields;
}
public void run() {
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + access;
result = prime * result + Arrays.hashCode(interfaces);
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((newFields == null) ? 0 : newFields.hashCode());
result = prime * result + ((newMethods == null) ? 0 : newMethods.hashCode());
result = prime * result + ((signature == null) ? 0 : signature.hashCode());
result = prime * result + ((superName == null) ? 0 : superName.hashCode());
result = prime * result + version;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NewClass other = (NewClass) obj;
if (access != other.access)
return false;
if (!Arrays.equals(interfaces, other.interfaces))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (newFields == null) {
if (other.newFields != null)
return false;
} else if (!newFields.equals(other.newFields))
return false;
if (newMethods == null) {
if (other.newMethods != null)
return false;
} else if (!newMethods.equals(other.newMethods))
return false;
if (signature == null) {
if (other.signature != null)
return false;
} else if (!signature.equals(other.signature))
return false;
if (superName == null) {
if (other.superName != null)
return false;
} else if (!superName.equals(other.superName))
return false;
if (version != other.version)
return false;
return true;
}
}
|
package valatava.lab.warehouse.controller;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import valatava.lab.warehouse.exeption.CreatedEntityIdException;
import valatava.lab.warehouse.exeption.UpdatedEntityIdException;
import valatava.lab.warehouse.service.CategoryService;
import valatava.lab.warehouse.service.dto.CategoryDTO;
import valatava.lab.warehouse.service.mapper.CategoryMapper;
/**
* REST controller for managing the categories.
*
* @author Yuriy Govorushkin
*/
@RestController
@RequestMapping("/api/categories")
public class CategoryController {
private final CategoryService categoryService;
private final CategoryMapper categoryMapper;
public CategoryController(CategoryService categoryService, CategoryMapper categoryMapper) {
this.categoryService = categoryService;
this.categoryMapper = categoryMapper;
}
@GetMapping
public List<CategoryDTO> getAllCategory() {
return categoryMapper.toDTOs(categoryService.findAll());
}
@GetMapping("{id}")
public CategoryDTO getCategory(@PathVariable Long id) {
return categoryMapper.toDTO(categoryService.findCategory(id));
}
@PostMapping
public void saveCategory(@RequestBody CategoryDTO categoryDTO) {
if (categoryDTO.getId() != null) {
throw new CreatedEntityIdException();
}
categoryService.save(categoryMapper.toEntity(categoryDTO));
}
@PutMapping
public void updateCategory(@RequestBody CategoryDTO categoryDTO) {
if (categoryDTO.getId() == null) {
throw new UpdatedEntityIdException();
}
categoryService.save(categoryMapper.toEntity(categoryDTO));
}
}
|
package com.gg.example.springExample.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
/**
* User: adurmaz
* Date: 5/12/13
* Time: 1:44 PM
*/
@Aspect
public class PetClinicTrackerAspect {
//@Around("execution(* com.gg.example.springExample..*.*(..))")
@Around("bean(*Service)")
public Object trace(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
try {
System.out.println("Before : " + proceedingJoinPoint.getSignature());
return proceedingJoinPoint.proceed();
} finally {
System.out.println("After :" + proceedingJoinPoint.getSignature());
}
}
}
|
package net.minecraft.init;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemArmorStand;
import net.minecraft.item.ItemBow;
import net.minecraft.item.ItemEmptyMap;
import net.minecraft.item.ItemFishingRod;
import net.minecraft.item.ItemMap;
import net.minecraft.item.ItemPotion;
import net.minecraft.item.ItemShears;
import net.minecraft.util.ResourceLocation;
public class Items {
private static Item getRegisteredItem(String name) {
Item item = (Item)Item.REGISTRY.getObject(new ResourceLocation(name));
if (item == null)
throw new IllegalStateException("Invalid Item requested: " + name);
return item;
}
static {
if (!Bootstrap.isRegistered())
throw new RuntimeException("Accessed Items before Bootstrap!");
}
public static final Item field_190931_a = getRegisteredItem("air");
public static final Item IRON_SHOVEL = getRegisteredItem("iron_shovel");
public static final Item IRON_PICKAXE = getRegisteredItem("iron_pickaxe");
public static final Item IRON_AXE = getRegisteredItem("iron_axe");
public static final Item FLINT_AND_STEEL = getRegisteredItem("flint_and_steel");
public static final Item APPLE = getRegisteredItem("apple");
public static final ItemBow BOW = (ItemBow)getRegisteredItem("bow");
public static final Item ARROW = getRegisteredItem("arrow");
public static final Item SPECTRAL_ARROW = getRegisteredItem("spectral_arrow");
public static final Item TIPPED_ARROW = getRegisteredItem("tipped_arrow");
public static final Item COAL = getRegisteredItem("coal");
public static final Item DIAMOND = getRegisteredItem("diamond");
public static final Item IRON_INGOT = getRegisteredItem("iron_ingot");
public static final Item GOLD_INGOT = getRegisteredItem("gold_ingot");
public static final Item IRON_SWORD = getRegisteredItem("iron_sword");
public static final Item WOODEN_SWORD = getRegisteredItem("wooden_sword");
public static final Item WOODEN_SHOVEL = getRegisteredItem("wooden_shovel");
public static final Item WOODEN_PICKAXE = getRegisteredItem("wooden_pickaxe");
public static final Item WOODEN_AXE = getRegisteredItem("wooden_axe");
public static final Item STONE_SWORD = getRegisteredItem("stone_sword");
public static final Item STONE_SHOVEL = getRegisteredItem("stone_shovel");
public static final Item STONE_PICKAXE = getRegisteredItem("stone_pickaxe");
public static final Item STONE_AXE = getRegisteredItem("stone_axe");
public static final Item DIAMOND_SWORD = getRegisteredItem("diamond_sword");
public static final Item DIAMOND_SHOVEL = getRegisteredItem("diamond_shovel");
public static final Item DIAMOND_PICKAXE = getRegisteredItem("diamond_pickaxe");
public static final Item DIAMOND_AXE = getRegisteredItem("diamond_axe");
public static final Item STICK = getRegisteredItem("stick");
public static final Item BOWL = getRegisteredItem("bowl");
public static final Item MUSHROOM_STEW = getRegisteredItem("mushroom_stew");
public static final Item GOLDEN_SWORD = getRegisteredItem("golden_sword");
public static final Item GOLDEN_SHOVEL = getRegisteredItem("golden_shovel");
public static final Item GOLDEN_PICKAXE = getRegisteredItem("golden_pickaxe");
public static final Item GOLDEN_AXE = getRegisteredItem("golden_axe");
public static final Item STRING = getRegisteredItem("string");
public static final Item FEATHER = getRegisteredItem("feather");
public static final Item GUNPOWDER = getRegisteredItem("gunpowder");
public static final Item WOODEN_HOE = getRegisteredItem("wooden_hoe");
public static final Item STONE_HOE = getRegisteredItem("stone_hoe");
public static final Item IRON_HOE = getRegisteredItem("iron_hoe");
public static final Item DIAMOND_HOE = getRegisteredItem("diamond_hoe");
public static final Item GOLDEN_HOE = getRegisteredItem("golden_hoe");
public static final Item WHEAT_SEEDS = getRegisteredItem("wheat_seeds");
public static final Item WHEAT = getRegisteredItem("wheat");
public static final Item BREAD = getRegisteredItem("bread");
public static final ItemArmor LEATHER_HELMET = (ItemArmor)getRegisteredItem("leather_helmet");
public static final ItemArmor LEATHER_CHESTPLATE = (ItemArmor)getRegisteredItem("leather_chestplate");
public static final ItemArmor LEATHER_LEGGINGS = (ItemArmor)getRegisteredItem("leather_leggings");
public static final ItemArmor LEATHER_BOOTS = (ItemArmor)getRegisteredItem("leather_boots");
public static final ItemArmor CHAINMAIL_HELMET = (ItemArmor)getRegisteredItem("chainmail_helmet");
public static final ItemArmor CHAINMAIL_CHESTPLATE = (ItemArmor)getRegisteredItem("chainmail_chestplate");
public static final ItemArmor CHAINMAIL_LEGGINGS = (ItemArmor)getRegisteredItem("chainmail_leggings");
public static final ItemArmor CHAINMAIL_BOOTS = (ItemArmor)getRegisteredItem("chainmail_boots");
public static final ItemArmor IRON_HELMET = (ItemArmor)getRegisteredItem("iron_helmet");
public static final ItemArmor IRON_CHESTPLATE = (ItemArmor)getRegisteredItem("iron_chestplate");
public static final ItemArmor IRON_LEGGINGS = (ItemArmor)getRegisteredItem("iron_leggings");
public static final ItemArmor IRON_BOOTS = (ItemArmor)getRegisteredItem("iron_boots");
public static final ItemArmor DIAMOND_HELMET = (ItemArmor)getRegisteredItem("diamond_helmet");
public static final ItemArmor DIAMOND_CHESTPLATE = (ItemArmor)getRegisteredItem("diamond_chestplate");
public static final ItemArmor DIAMOND_LEGGINGS = (ItemArmor)getRegisteredItem("diamond_leggings");
public static final ItemArmor DIAMOND_BOOTS = (ItemArmor)getRegisteredItem("diamond_boots");
public static final ItemArmor GOLDEN_HELMET = (ItemArmor)getRegisteredItem("golden_helmet");
public static final ItemArmor GOLDEN_CHESTPLATE = (ItemArmor)getRegisteredItem("golden_chestplate");
public static final ItemArmor GOLDEN_LEGGINGS = (ItemArmor)getRegisteredItem("golden_leggings");
public static final ItemArmor GOLDEN_BOOTS = (ItemArmor)getRegisteredItem("golden_boots");
public static final Item FLINT = getRegisteredItem("flint");
public static final Item PORKCHOP = getRegisteredItem("porkchop");
public static final Item COOKED_PORKCHOP = getRegisteredItem("cooked_porkchop");
public static final Item PAINTING = getRegisteredItem("painting");
public static final Item GOLDEN_APPLE = getRegisteredItem("golden_apple");
public static final Item SIGN = getRegisteredItem("sign");
public static final Item OAK_DOOR = getRegisteredItem("wooden_door");
public static final Item SPRUCE_DOOR = getRegisteredItem("spruce_door");
public static final Item BIRCH_DOOR = getRegisteredItem("birch_door");
public static final Item JUNGLE_DOOR = getRegisteredItem("jungle_door");
public static final Item ACACIA_DOOR = getRegisteredItem("acacia_door");
public static final Item DARK_OAK_DOOR = getRegisteredItem("dark_oak_door");
public static final Item BUCKET = getRegisteredItem("bucket");
public static final Item WATER_BUCKET = getRegisteredItem("water_bucket");
public static final Item LAVA_BUCKET = getRegisteredItem("lava_bucket");
public static final Item MINECART = getRegisteredItem("minecart");
public static final Item SADDLE = getRegisteredItem("saddle");
public static final Item IRON_DOOR = getRegisteredItem("iron_door");
public static final Item REDSTONE = getRegisteredItem("redstone");
public static final Item SNOWBALL = getRegisteredItem("snowball");
public static final Item BOAT = getRegisteredItem("boat");
public static final Item SPRUCE_BOAT = getRegisteredItem("spruce_boat");
public static final Item BIRCH_BOAT = getRegisteredItem("birch_boat");
public static final Item JUNGLE_BOAT = getRegisteredItem("jungle_boat");
public static final Item ACACIA_BOAT = getRegisteredItem("acacia_boat");
public static final Item DARK_OAK_BOAT = getRegisteredItem("dark_oak_boat");
public static final Item LEATHER = getRegisteredItem("leather");
public static final Item MILK_BUCKET = getRegisteredItem("milk_bucket");
public static final Item BRICK = getRegisteredItem("brick");
public static final Item CLAY_BALL = getRegisteredItem("clay_ball");
public static final Item REEDS = getRegisteredItem("reeds");
public static final Item PAPER = getRegisteredItem("paper");
public static final Item BOOK = getRegisteredItem("book");
public static final Item SLIME_BALL = getRegisteredItem("slime_ball");
public static final Item CHEST_MINECART = getRegisteredItem("chest_minecart");
public static final Item FURNACE_MINECART = getRegisteredItem("furnace_minecart");
public static final Item EGG = getRegisteredItem("egg");
public static final Item COMPASS = getRegisteredItem("compass");
public static final ItemFishingRod FISHING_ROD = (ItemFishingRod)getRegisteredItem("fishing_rod");
public static final Item CLOCK = getRegisteredItem("clock");
public static final Item GLOWSTONE_DUST = getRegisteredItem("glowstone_dust");
public static final Item FISH = getRegisteredItem("fish");
public static final Item COOKED_FISH = getRegisteredItem("cooked_fish");
public static final Item DYE = getRegisteredItem("dye");
public static final Item BONE = getRegisteredItem("bone");
public static final Item SUGAR = getRegisteredItem("sugar");
public static final Item CAKE = getRegisteredItem("cake");
public static final Item BED = getRegisteredItem("bed");
public static final Item REPEATER = getRegisteredItem("repeater");
public static final Item COOKIE = getRegisteredItem("cookie");
public static final ItemMap FILLED_MAP = (ItemMap)getRegisteredItem("filled_map");
public static final ItemShears SHEARS = (ItemShears)getRegisteredItem("shears");
public static final Item MELON = getRegisteredItem("melon");
public static final Item PUMPKIN_SEEDS = getRegisteredItem("pumpkin_seeds");
public static final Item MELON_SEEDS = getRegisteredItem("melon_seeds");
public static final Item BEEF = getRegisteredItem("beef");
public static final Item COOKED_BEEF = getRegisteredItem("cooked_beef");
public static final Item CHICKEN = getRegisteredItem("chicken");
public static final Item COOKED_CHICKEN = getRegisteredItem("cooked_chicken");
public static final Item MUTTON = getRegisteredItem("mutton");
public static final Item COOKED_MUTTON = getRegisteredItem("cooked_mutton");
public static final Item RABBIT = getRegisteredItem("rabbit");
public static final Item COOKED_RABBIT = getRegisteredItem("cooked_rabbit");
public static final Item RABBIT_STEW = getRegisteredItem("rabbit_stew");
public static final Item RABBIT_FOOT = getRegisteredItem("rabbit_foot");
public static final Item RABBIT_HIDE = getRegisteredItem("rabbit_hide");
public static final Item ROTTEN_FLESH = getRegisteredItem("rotten_flesh");
public static final Item ENDER_PEARL = getRegisteredItem("ender_pearl");
public static final Item BLAZE_ROD = getRegisteredItem("blaze_rod");
public static final Item GHAST_TEAR = getRegisteredItem("ghast_tear");
public static final Item GOLD_NUGGET = getRegisteredItem("gold_nugget");
public static final Item NETHER_WART = getRegisteredItem("nether_wart");
public static final ItemPotion POTIONITEM = (ItemPotion)getRegisteredItem("potion");
public static final ItemPotion SPLASH_POTION = (ItemPotion)getRegisteredItem("splash_potion");
public static final ItemPotion LINGERING_POTION = (ItemPotion)getRegisteredItem("lingering_potion");
public static final Item GLASS_BOTTLE = getRegisteredItem("glass_bottle");
public static final Item DRAGON_BREATH = getRegisteredItem("dragon_breath");
public static final Item SPIDER_EYE = getRegisteredItem("spider_eye");
public static final Item FERMENTED_SPIDER_EYE = getRegisteredItem("fermented_spider_eye");
public static final Item BLAZE_POWDER = getRegisteredItem("blaze_powder");
public static final Item MAGMA_CREAM = getRegisteredItem("magma_cream");
public static final Item BREWING_STAND = getRegisteredItem("brewing_stand");
public static final Item CAULDRON = getRegisteredItem("cauldron");
public static final Item ENDER_EYE = getRegisteredItem("ender_eye");
public static final Item SPECKLED_MELON = getRegisteredItem("speckled_melon");
public static final Item SPAWN_EGG = getRegisteredItem("spawn_egg");
public static final Item EXPERIENCE_BOTTLE = getRegisteredItem("experience_bottle");
public static final Item FIRE_CHARGE = getRegisteredItem("fire_charge");
public static final Item WRITABLE_BOOK = getRegisteredItem("writable_book");
public static final Item WRITTEN_BOOK = getRegisteredItem("written_book");
public static final Item EMERALD = getRegisteredItem("emerald");
public static final Item ITEM_FRAME = getRegisteredItem("item_frame");
public static final Item FLOWER_POT = getRegisteredItem("flower_pot");
public static final Item CARROT = getRegisteredItem("carrot");
public static final Item POTATO = getRegisteredItem("potato");
public static final Item BAKED_POTATO = getRegisteredItem("baked_potato");
public static final Item POISONOUS_POTATO = getRegisteredItem("poisonous_potato");
public static final ItemEmptyMap MAP = (ItemEmptyMap)getRegisteredItem("map");
public static final Item GOLDEN_CARROT = getRegisteredItem("golden_carrot");
public static final Item SKULL = getRegisteredItem("skull");
public static final Item CARROT_ON_A_STICK = getRegisteredItem("carrot_on_a_stick");
public static final Item NETHER_STAR = getRegisteredItem("nether_star");
public static final Item PUMPKIN_PIE = getRegisteredItem("pumpkin_pie");
public static final Item FIREWORKS = getRegisteredItem("fireworks");
public static final Item FIREWORK_CHARGE = getRegisteredItem("firework_charge");
public static final Item ENCHANTED_BOOK = getRegisteredItem("enchanted_book");
public static final Item COMPARATOR = getRegisteredItem("comparator");
public static final Item NETHERBRICK = getRegisteredItem("netherbrick");
public static final Item QUARTZ = getRegisteredItem("quartz");
public static final Item TNT_MINECART = getRegisteredItem("tnt_minecart");
public static final Item HOPPER_MINECART = getRegisteredItem("hopper_minecart");
public static final ItemArmorStand ARMOR_STAND = (ItemArmorStand)getRegisteredItem("armor_stand");
public static final Item IRON_HORSE_ARMOR = getRegisteredItem("iron_horse_armor");
public static final Item GOLDEN_HORSE_ARMOR = getRegisteredItem("golden_horse_armor");
public static final Item DIAMOND_HORSE_ARMOR = getRegisteredItem("diamond_horse_armor");
public static final Item LEAD = getRegisteredItem("lead");
public static final Item NAME_TAG = getRegisteredItem("name_tag");
public static final Item COMMAND_BLOCK_MINECART = getRegisteredItem("command_block_minecart");
public static final Item RECORD_13 = getRegisteredItem("record_13");
public static final Item RECORD_CAT = getRegisteredItem("record_cat");
public static final Item RECORD_BLOCKS = getRegisteredItem("record_blocks");
public static final Item RECORD_CHIRP = getRegisteredItem("record_chirp");
public static final Item RECORD_FAR = getRegisteredItem("record_far");
public static final Item RECORD_MALL = getRegisteredItem("record_mall");
public static final Item RECORD_MELLOHI = getRegisteredItem("record_mellohi");
public static final Item RECORD_STAL = getRegisteredItem("record_stal");
public static final Item RECORD_STRAD = getRegisteredItem("record_strad");
public static final Item RECORD_WARD = getRegisteredItem("record_ward");
public static final Item RECORD_11 = getRegisteredItem("record_11");
public static final Item RECORD_WAIT = getRegisteredItem("record_wait");
public static final Item PRISMARINE_SHARD = getRegisteredItem("prismarine_shard");
public static final Item PRISMARINE_CRYSTALS = getRegisteredItem("prismarine_crystals");
public static final Item BANNER = getRegisteredItem("banner");
public static final Item END_CRYSTAL = getRegisteredItem("end_crystal");
public static final Item SHIELD = getRegisteredItem("shield");
public static final Item ELYTRA = getRegisteredItem("elytra");
public static final Item CHORUS_FRUIT = getRegisteredItem("chorus_fruit");
public static final Item CHORUS_FRUIT_POPPED = getRegisteredItem("chorus_fruit_popped");
public static final Item BEETROOT_SEEDS = getRegisteredItem("beetroot_seeds");
public static final Item BEETROOT = getRegisteredItem("beetroot");
public static final Item BEETROOT_SOUP = getRegisteredItem("beetroot_soup");
public static final Item field_190929_cY = getRegisteredItem("totem_of_undying");
public static final Item field_190930_cZ = getRegisteredItem("shulker_shell");
public static final Item field_191525_da = getRegisteredItem("iron_nugget");
public static final Item field_192397_db = getRegisteredItem("knowledge_book");
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\init\Items.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
// Sun Certified Java Programmer
// Chapter 3, P226
// Assignments
class Tester226 {
public static void main(String[] args) {
Dog[] myDogs = new Dog[6]; // creates an array of 6
// Dog references
for (int x = 0; x < myDogs.length; x++) {
myDogs[x] = new Dog(); // assign a new Dog to the
// index position x
System.out.println(myDogs[x]);
}
}
}
|
package swm11.jdk.jobtreaming.back.app.lecture.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import swm11.jdk.jobtreaming.back.app.lecture.model.Lecture;
import swm11.jdk.jobtreaming.back.app.user.model.User;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
@Repository
public interface LectureRepository extends JpaRepository <Lecture, Long> {
List<Lecture> findAllByTitleContaining(String query);
Optional<Lecture> findByIdAndStudentsContaining(Long lectureId, User user);
List<Lecture> findAllByStudentsContainingAndStartedAtAfter(User user, LocalDateTime now);
}
|
package com;
import java.nio.charset.Charset;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
/**
* @author xuxinbin
* @version $$Id: nettyJoin, v 0.1 2017/8/17 12:58 xuxinbin Exp $$
*/
public class ByteBufTest {
public static void main(String[] args) {
test1();
System.out.println("=================================");
test2();
}
/**
* 复制一个ByteBuf
*/
private static void test4() {
Charset utf8 = Charset.forName("UTF-8");
ByteBuf buf = Unpooled.copiedBuffer("Netty in action rocks!", utf8);
ByteBuf copy = buf.copy(0, 15);
System.out.println(copy.toString(utf8)); //Netty in action
buf.setByte(0, 'J');
System.out.println(buf.toString(utf8)); //Jetty in action rocks!
System.out.println(copy.toString(utf8)); //Netty in action
}
/**
* 对ByteBuf进行切片
*/
private static void test3() {
Charset utf8 = Charset.forName("UTF-8");
ByteBuf buf = Unpooled.copiedBuffer("Netty in action rocks!", utf8);
System.out.println(buf);
ByteBuf sliced = buf.slice(0, 15);
System.out.println(sliced.toString(utf8)); //Netty in action
buf.setByte(0, 'J');
System.out.println("buf.getByte(0) == " + buf.getByte(0)); //buf.getByte(0) == 74
System.out.println("sliced.getByte(0) == " + sliced.getByte(0)); //sliced.getByte(0) == 74
System.out.println(buf.toString(utf8));//Jetty in action rocks!
System.out.println(sliced.toString(utf8)); //Jetty in action
}
/**
* ByteBuf的get和set方法不会移动索引值
*/
private static void test2() {
Charset utf8 = Charset.forName("UTF-8");
ByteBuf buf = Unpooled.copiedBuffer("Netty in Action rocks!", utf8);
System.out.println((char)buf.getByte(0)); //N
int readerIndex = buf.readerIndex();
int writerIndex = buf.writerIndex();
buf.setByte(0, 'B');
System.out.println(buf.toString(utf8)); //Betty in Action rocks!
System.out.println(readerIndex); //0
System.out.println(writerIndex); //22
System.out.println(buf.readerIndex()); //0
System.out.println(buf.writerIndex()); //22
}
/**
* ByteBuf的writeXXX方法会移动索引值
*/
private static void test1() {
Charset utf8 = Charset.forName("UTF-8");
ByteBuf buf = Unpooled.copiedBuffer("Netty in Action rocks!", utf8);
System.out.println((char)buf.readByte()); //N
int readerIndex = buf.readerIndex();
int writerIndex = buf.writerIndex();
System.out.println((char)buf.getByte(buf.readerIndex())); //e
buf.writeByte('?');
System.out.println(readerIndex); //1
System.out.println(writerIndex); //22
System.out.println(buf.readerIndex()); //1
System.out.println(buf.writerIndex()); //23
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.widget;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.openkm.frontend.client.Main;
import com.openkm.frontend.client.bean.GWTProcessDefinition;
import com.openkm.frontend.client.service.OKMWorkflowService;
import com.openkm.frontend.client.service.OKMWorkflowServiceAsync;
import com.openkm.frontend.client.widget.wizard.WorkflowWidget;
import com.openkm.frontend.client.widget.wizard.WorkflowWidgetToFire;
/**
* WorkflowPopup popup
* s
* @author jllort
*
*/
public class WorkflowPopup extends DialogBox implements WorkflowWidgetToFire {
private final OKMWorkflowServiceAsync workflowService = (OKMWorkflowServiceAsync) GWT.create(OKMWorkflowService.class);
private VerticalPanel vPanel;
private HorizontalPanel hPanel;
private Button closeButton;
private Button addButton;
private ListBox listBox;
private SimplePanel sp;
private WorkflowWidget workflowWidget= null;
private String uuid = "";
/**
* WorkflowPopup popup
*/
public WorkflowPopup() {
// Establishes auto-close when click outside
super(false,true);
vPanel = new VerticalPanel();
hPanel = new HorizontalPanel();
sp = new SimplePanel();
closeButton = new Button(Main.i18n("button.close"), new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hide();
}
});
addButton = new Button(Main.i18n("button.start"), new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
addButton.setEnabled(false);
runProcessDefinition();
}
});
listBox = new ListBox();
listBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
if (listBox.getSelectedIndex() > 0) {
addButton.setEnabled(true);
} else {
addButton.setEnabled(false);
}
sp.setVisible(false);
sp.clear();
}
});
listBox.setStyleName("okm-Select");
vPanel.setWidth("300px");
vPanel.setHeight("50px");
closeButton.setStyleName("okm-NoButton");
addButton.setStyleName("okm-YesButton");
addButton.setEnabled(false);
hPanel.add(closeButton);
hPanel.add(new HTML(" "));
hPanel.add(addButton);
hPanel.setCellHorizontalAlignment(closeButton,VerticalPanel.ALIGN_CENTER);
hPanel.setCellHorizontalAlignment(addButton,VerticalPanel.ALIGN_CENTER);
vPanel.add(new HTML("<br>"));
vPanel.add(listBox);
vPanel.add(sp);
vPanel.add(new HTML("<br>"));
vPanel.add(hPanel);
vPanel.add(new HTML("<br>"));
vPanel.setCellHorizontalAlignment(listBox, VerticalPanel.ALIGN_CENTER);
vPanel.setCellHorizontalAlignment(hPanel, VerticalPanel.ALIGN_CENTER);
super.hide();
setWidget(vPanel);
}
/**
* Gets asynchronous to get all process definitions
*/
final AsyncCallback<List<GWTProcessDefinition>> callbackFindLatestProcessDefinitions = new AsyncCallback<List<GWTProcessDefinition>>() {
public void onSuccess(List<GWTProcessDefinition> result){
listBox.clear();
listBox.addItem("",""); // Adds empty value
for (Iterator<GWTProcessDefinition> it = result.iterator(); it.hasNext();) {
GWTProcessDefinition processDefinition = it.next();
if (Main.get().workspaceUserProperties.getWorkspace().getMiscWorkflowList().contains(processDefinition.getName())) {
listBox.addItem(processDefinition.getName(), processDefinition.getName());
}
}
}
public void onFailure(Throwable caught) {
Main.get().showError("callbackFindLatestProcessDefinitions", caught);
}
};
/**
* Gets asynchronous to run process definition
*/
final AsyncCallback<Object> callbackRunProcessDefinition = new AsyncCallback<Object>() {
public void onSuccess(Object result){
Main.get().mainPanel.dashboard.workflowDashboard.findUserTaskInstances();
}
public void onFailure(Throwable caught) {
Main.get().showError("callbackRunProcessDefinition", caught);
}
};
/**
* Enables close button
*/
public void enableClose() {
closeButton.setEnabled(true);
Main.get().mainPanel.setVisible(true); // Shows main panel when all widgets are loaded
}
/**
* Language refresh
*/
public void langRefresh() {
setText(Main.i18n("workflow.label"));
closeButton.setText(Main.i18n("button.close"));
addButton.setText(Main.i18n("button.start"));
}
/**
* Show the popup error
*
* @param msg Error message
*/
public void show() {
setText(Main.i18n("workflow.label"));
findLatestProcessDefinitions(); // Gets all groups
listBox.setVisible(true);
addButton.setEnabled(false);
workflowWidget = null;
listBox.setVisible(true);
sp.setVisible(false);
sp.clear();
int left = (Window.getClientWidth()-300)/2;
int top = (Window.getClientHeight()-100)/2;
setPopupPosition(left,top);
super.show();
}
/**
* Gets all process definitions
*/
private void findLatestProcessDefinitions() {
workflowService.findLatestProcessDefinitions(callbackFindLatestProcessDefinitions);
}
/**
* Run process definition
*/
private void runProcessDefinition() {
if (workflowWidget!=null) {
workflowWidget.runProcessDefinition(); // Here has some forms to be filled
} else if (listBox.getSelectedIndex()>0) {
if (Main.get().activeFolderTree.isPanelSelected()) {
uuid = Main.get().activeFolderTree.getFolder().getUuid();
} else {
if (Main.get().mainPanel.desktop.browser.fileBrowser.isDocumentSelected()) {
uuid = Main.get().mainPanel.desktop.browser.fileBrowser.getDocument().getUuid();
} else if(Main.get().mainPanel.desktop.browser.fileBrowser.isFolderSelected()) {
uuid = Main.get().mainPanel.desktop.browser.fileBrowser.getFolder().getUuid();
} else if(Main.get().mainPanel.desktop.browser.fileBrowser.isMailSelected()) {
uuid = Main.get().mainPanel.desktop.browser.fileBrowser.getMail().getUuid();
}
}
workflowWidget = new WorkflowWidget(listBox.getValue(listBox.getSelectedIndex()), uuid, this, new HashMap<String, Object>());
listBox.setVisible(false);
sp.add(workflowWidget);
workflowWidget.runProcessDefinition();
}
}
@Override
public void finishedRunProcessDefinition() {
workflowWidget = null;
hide();
}
@Override
public void hasPendingProcessDefinitionForms() {
sp.setVisible(true);
addButton.setEnabled(true);
}
}
|
package pms.dto;
public class pms_projectSch {
// 1. 검색 속성
private String project_name; // 프로젝트 제목
// 2. 페이징 처리
private int count; // 총데이터 건수
private int pageSize; // 한페이지 보여줄 데이터 건수
private int pageCount; // 총 페이지 수 count/pageSize
private int curPage; // 클릭한 현재 페이지 번호
private int start; // 페이지의 시작 번호
private int end; // 페이지의 마지막 번호
// 3. block 처리
private int blockSize; // 한번에 보여줄 block의 크기
private int startBlock; // block의 시작번호
private int endBlock; // block의 마지막번호
private String name; // PM_pno를 PM이름으로
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProject_name() {
return project_name;
}
public void setProject_name(String project_name) {
this.project_name = project_name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public int getCurPage() {
return curPage;
}
public void setCurPage(int curPage) {
this.curPage = curPage;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int getBlockSize() {
return blockSize;
}
public void setBlockSize(int blockSize) {
this.blockSize = blockSize;
}
public int getStartBlock() {
return startBlock;
}
public void setStartBlock(int startBlock) {
this.startBlock = startBlock;
}
public int getEndBlock() {
return endBlock;
}
public void setEndBlock(int endBlock) {
this.endBlock = endBlock;
}
}
|
package com.kunsoftware.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.kunsoftware.bean.HeadIconTitleRequestBean;
import com.kunsoftware.entity.HeadIconTitle;
import com.kunsoftware.exception.KunSoftwareException;
import com.kunsoftware.mapper.HeadIconTitleMapper;
import com.kunsoftware.util.FileUtil;
@Service
public class HeadIconTitleService {
private static Logger logger = LoggerFactory.getLogger(HeadIconTitleService.class);
@Autowired
private HeadIconTitleMapper mapper;
public List<HeadIconTitle> getHeadIconTitleListAll(String type) {
logger.info("query");
return mapper.getHeadIconTitleListAll(type);
}
@Transactional
public HeadIconTitle insert(HeadIconTitleRequestBean requestBean) throws KunSoftwareException {
HeadIconTitle record = new HeadIconTitle();
BeanUtils.copyProperties(requestBean, record);
if(requestBean.getImageFile() != null) {
String imagePath = FileUtil.uploadFile(requestBean.getImageFile());
record.setName(imagePath);
}
mapper.insert(record);
return record;
}
public HeadIconTitle selectByPrimaryKey(Integer id) throws KunSoftwareException {
return mapper.selectByPrimaryKey(id);
}
public HeadIconTitle selectMemberInfo() throws KunSoftwareException {
return mapper.selectMemberInfo();
}
@Transactional
public int updateByPrimaryKey(HeadIconTitleRequestBean requestBean,Integer id) throws KunSoftwareException {
HeadIconTitle record = mapper.selectByPrimaryKey(id);
BeanUtils.copyProperties(requestBean, record);
if(requestBean.getImageFile() != null) {
String imagePath = FileUtil.uploadFile(requestBean.getImageFile());
record.setName(imagePath);
}
return mapper.updateByPrimaryKeySelective(record);
}
@Transactional
public void updateEnableByIds(Integer[] id,String enable) throws KunSoftwareException {
for(int i = 0;i < id.length;i++) {
HeadIconTitle record = mapper.selectByPrimaryKey(id[i]);
record.setEnable(enable);
mapper.updateByPrimaryKeySelective(record);
}
}
@Transactional
public int deleteByPrimaryKey(Integer id) throws KunSoftwareException {
return mapper.deleteByPrimaryKey(id);
}
@Transactional
public void deleteByPrimaryKey(Integer[] id) throws KunSoftwareException {
for(int i = 0;i < id.length;i++) {
mapper.deleteByPrimaryKey(id[i]);
}
}
}
|
/**
* Alipay.com Inc.
* Copyright (c) 2004-2012 All Rights Reserved.
*/
package com.github.obullxl.lang.xml;
import java.util.ArrayList;
import java.util.List;
import com.github.obullxl.lang.MapExt;
import com.github.obullxl.lang.ToString;
/**
* XML节点模型
*
* @author shizihu
* @version $Id: XMLNode.java, v 0.1 2012-9-13 上午09:50:04 shizihu Exp $
*/
public class XMLNode extends ToString {
private static final long serialVersionUID = 2545193236502133681L;
/** 名称(小写) */
private String name;
/** 文本内容,可能为空 */
private String text;
/** 节点属性(Key为小写) */
private MapExt extMap;
/** 子节点 */
private List<XMLNode> children;
// ~~~~~~~~~~~ 公用方法 ~~~~~~~~~~~ //
// ~~~~~~~~~~~ getters and setters ~~~~~~~~~~~~~~ //
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public void setChildren(List<XMLNode> children) {
this.children = children;
}
public List<XMLNode> getChildren() {
if (this.children == null) {
this.children = new ArrayList<XMLNode>();
}
return children;
}
public MapExt getExtMap() {
if (this.extMap == null) {
this.extMap = new MapExt();
}
return extMap;
}
public void setExtMap(MapExt extMap) {
this.extMap = extMap;
}
}
|
package java2.businesslogic;
import java2.database.AnnouncementRepository;
import java2.domain.Announcement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class AnnouncementFieldValidator {
@Autowired private AnnouncementRepository announcementRepository;
public Optional<ValidationError> validateId(int id) {
if(id == 0) {
return Optional.of(new ValidationError("id", "Must not be empty!"));
} else {
return Optional.empty();
}
}
public Optional<ValidationError> validateTitle(String title) {
if(title == null || title.isEmpty()) {
return Optional.of(new ValidationError("title", "Must not be empty!"));
} else {
return Optional.empty();
}
}
public Optional<ValidationError> validateDescription(String description) {
if(description == null || description.isEmpty()) {
return Optional.of(new ValidationError("description", "Must not be empty!"));
} else {
return Optional.empty();
}
}
public Optional<ValidationError> validateLogin(String login) {
if(login == null || login.isEmpty()) {
return Optional.of(new ValidationError("login", "Must not be empty!"));
} else {
return Optional.empty();
}
}
public Optional<ValidationError> validateAnnouncementPresence(int id) {
Optional<Announcement> announcementFound = announcementRepository.findById(id);
if(!announcementFound.isPresent()) {
return Optional.of(new ValidationError("id", "Announcement not found!"));
} else {
return Optional.empty();
}
}
public Optional<ValidationError> validateAnnouncementAlreadyBanned(int id) {
Optional<Announcement> foundAnnouncement = announcementRepository.findById(id);
if(foundAnnouncement.isPresent()) {
if(foundAnnouncement.get().getState().getId().equals("BANNED")) {
return Optional.of(new ValidationError("id", "Announcement already banned!"));
} else {
return Optional.empty();
}
} else {
return Optional.empty();
}
}
public Optional<ValidationError> validateLoginOfCreator(String login, int id) {
Optional<Announcement> foundAnnouncement = announcementRepository.findById(id);
Announcement announcement = foundAnnouncement.get();
if(!announcement.getCreator().getLogin().equals(login)) {
return Optional.of(new ValidationError("login", "Incorrect login of creator of announcement!"));
} else {
return Optional.empty();
}
}
}
|
package org.proyectofinal.gestorpacientes.modelo.entidades;
public class Estadistica {
private Object id;
private Object total;
public Estadistica(Object id, Object total) {
super();
this.setId(id);
this.setTotal(total);
}
public Object getMedicoId() {
return id;
}
public Object getTotal() {
return total;
}
public void setId(Object medicoId) {
this.id = medicoId;
}
public void setTotal(Object total) {
this.total = total;
}
}
|
package rjm.romek.awscourse.repository;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import rjm.romek.awscourse.model.Chapter;
import rjm.romek.awscourse.model.Task;
import rjm.romek.awscourse.verifier.s3.KeyExistsVerifier;
@RunWith(SpringRunner.class)
@DataJpaTest
public class TaskRepositoryTest {
@Autowired
private TaskRepository taskRepository;
@Autowired
private ChapterRepository chapterRepository;
@Test
public void testSaveAndDelete() {
Chapter chapter = new Chapter("Chapter");
chapterRepository.save(chapter);
Task task = new Task(chapter, "Description", KeyExistsVerifier.class);
task = taskRepository.save(task);
assertTrue(taskRepository.findById(task.getTaskId()).isPresent());
}
@Test
public void testFindByChapter() {
Chapter chapter = new Chapter("Chapter");
chapterRepository.save(chapter);
Task task1 = new Task(chapter, "Description", KeyExistsVerifier.class);
Task task2 = new Task(chapter, "Description", KeyExistsVerifier.class);
taskRepository.save(task1);
taskRepository.save(task2);
List<Task> tasks = taskRepository.findByChapter(chapter);
assertTrue(tasks.stream().anyMatch(x -> x.getTaskId() == task1.getTaskId()));
assertTrue(tasks.stream().anyMatch(x -> x.getTaskId() == task1.getTaskId()));
}
}
|
package Controllers;
import backend.model.Person;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.time.Period;
import java.util.ResourceBundle;
public class AddPerson implements Initializable {
private static final Logger logger = LogManager.getLogger(ListViewController.class);
static ActionEvent event1;
int idNum, ageNum;
boolean validAge, validName, validLastName, validId;
String Age, ID, lastname, firstname;
String FirstName, LastName;
int iD, AGE;
@FXML
public Button closeButton;
@FXML
private TextField firstName;
@FXML
private TextField lastName;
@FXML
private TextField age;
@FXML
private TextField id;
@FXML
private DatePicker DOB;
/**
* stores the data from the user.
**/
@FXML
public void addition(ActionEvent event) throws IOException {
FirstName = firstName.getText();
LastName = lastName.getText();
LocalDate dob = DOB.getValue();
iD = Person.NEW_PERSON;
Period period = Period.between(dob, LocalDate.now());
AGE = period.getYears();
System.out.println("_____________________> MY AGEEEEEEE " + AGE );
Person person = new Person( iD,FirstName,LastName, AGE, dob);
ViewSwitcher.globalAction = event;
validId = isValid(id.getText(), 1);
validName = isValid(firstName.getText(), 2);
validLastName = isValid(lastName.getText(), 3);
validAge = isValid(age.getText(), 0);
if( !validName || !validLastName || dob.isAfter(LocalDate.now()) ) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Invalid input (check first name, last name, and DOB).\n Please try again.");
alert.showAndWait();
}
else {
ListViewController.setAddition(person);
logger.info("CREATING <" + firstname +" "+ lastname + idNum + ">");
ViewSwitcher.getInstance().switchView(ViewType.ListViewController);
}
}
/**
* lets the user know that there was an error
* **/
private boolean isValid(String message, int num)
{
try{
//makes sure the id is an int and not a string
if(num ==1) {
ID = id.getText();
idNum = Integer.parseInt(ID);
// System.out.println("valid input");
}if(num==0) {
//makes sure the age is an int and not a string
Age = age.getText();
ageNum = Integer.parseInt(Age);
// System.out.println("this number is " + ageNum);
if(ageNum < 0 || ageNum > 150)
{
throw new IllegalArgumentException("Non readable file");
}
}
if(num==2){
// spaces for strings
int lastNameLen = lastName.getLength();
int firstNameLen = firstName.getLength();
if(firstNameLen < 1 || firstNameLen > 100 || lastNameLen <1 || lastNameLen > 100)
return false;
lastname = lastName.getText();
firstname = firstName.getText();
boolean testerz1 = isStringOnlyAlphabet(firstname);
boolean testerz = isStringOnlyAlphabet(lastname);
if(!testerz || !testerz1)
throw new IllegalArgumentException("Non readable file");
return (firstname != null && !firstname.trim().isEmpty()) && (lastname != null && !lastname.trim().isEmpty());
}
return true;
}catch (IllegalArgumentException err){
if(num ==0)
// logger.error("ERROR - invalid Age entered, please enter a number between 1-150.");
if(num ==1)
// logger.error("ERROR - id number out of range, please enter an id within the range -2147483648 to 2147483647.");
if(num ==2)
logger.error("ERROR - invaid name entered, please ensure your first/last name field contains only characters.");
return false;
}
}
public boolean isStringOnlyAlphabet(String str)
{
return ((str != null)
&& (!str.equals(""))
&& (str.matches("^[a-zA-Z]*$")));
}
/**
* can delete
**/
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
id.setDisable(true);
age.setDisable(true);
firstName.setText("Lou");
lastName.setText("Smith");
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.sql.ResultSet;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Derek
*/
public class DataAccessTest {
public DataAccessTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp()
{
try
{
DataAccess.Connect();
}
catch(Exception ex)
{
fail("Failed to setup." + ex);
}
}
@After
public void tearDown(){
try
{
DataAccess.disconnect();
}
catch(Exception ex)
{
fail("Failed to teardown." + ex);
}
}
/**
* Test of Connect method, of class DataAccess.
*/
// @Test
public void Connect() {
System.out.println("Connect");
DataAccess.Connect();
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of disconnect method, of class DataAccess.
*/
// @Test
public void disconnect() throws Exception {
System.out.println("disconnect");
DataAccess.disconnect();
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of init method, of class DataAccess.
*/
//@Test
public void init() {
System.out.println("init");
DataAccess.init();
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of execute method, of class DataAccess.
*/
@Test
public void execute() throws Exception {
System.out.println("execute");
String email ="chenjinlin@hotmail.com";
String query = "select * from useraccount where email LIKE '%chenjinlin%'";
int count=0;
ResultSet result = DataAccess.execute(query);
if(result == null)
fail("no record is returned.");
while(result.next())
{
assertEquals(email,result.getString("email"));
count++;
}
assertEquals(1, count);
}
/**
* Test of Case_GetByID method, of class DataAccess.
*/
@Test
public void Case_GetByID() throws Exception {
System.out.println("Case_GetByID");
int count=0;
int ID = 2;
//ResultSet expResult = null;
ResultSet result = DataAccess.Case_GetByID(ID);
if(result == null)
fail("no record is returned.");
while(result.next())
{
assertEquals(ID,result.getInt("caseid"));
count++;
}
assertEquals(1,count);
}
@Test
public void Case_GetByExactName() {
System.out.println("Case_GetByExactName");
int count=0;
//int ID = 2;
String cname="vancouver ring";
//ResultSet expResult = null;
try
{
ResultSet result = DataAccess.Case_GetByExactName(cname);
if(result == null)
fail("no record is returned.");
while(result.next())
{
//assertEquals(0,cname.compareToIgnoreCase(result.getString("casename")));
assertEquals(cname,result.getString("casename"));
//assertEquals();
count++;
}
assertEquals(1,count);
}
catch(Exception ex)
{
fail("Case_GetByExactName test failed." + ex.getMessage());
}
}
@Test
public void Case_GetByNameSubString() {
System.out.println("Case_GetByNameSubString");
int count=0;
//int ID = 2;
String cname="vancouver";
//ResultSet expResult = null;
try
{
ResultSet result = DataAccess.Case_GetByNameSubString(cname);
if(result == null)
fail("no record is returned.");
while(result.next())
{
//assertEquals(0,cname.compareToIgnoreCase(result.getString("casename")));
if(result.getString("casename").indexOf(cname, 0)==-1)
{
fail("Case_GetByExactName test failed. Found a case doesn't contain '" + cname +"'");
}
//assertEquals();
count++;
}
assertEquals(3,count);
}
catch(Exception ex)
{
fail("Case_GetByExactName test failed." + ex.getMessage());
}
}
@Test
public void Offender_GetAllByCaseID() {
System.out.println("Offender_GetByName");
int count=0;
//String name="paul";
int caseid=1;
try
{
ResultSet result = DataAccess.Offender_GetAllByCaseID(caseid);
if(result == null)
fail("no record is returned.");
while(result.next())
{
if(result.getInt("caseid")!=1)
{
fail("Offender_GetByName test failed. Found a case doesn't contain '" + caseid +"'");
}
//assertEquals();
count++;
}
assertEquals(2,count);
}
catch(Exception ex)
{
fail("Offender_GetByName test failed." + ex.getMessage());
}
}
@Test
public void Offender_GetByName() {
System.out.println("Offender_GetByName");
int count=0;
String name="paul";
try
{
ResultSet result = DataAccess.Offender_GetByName(name);
if(result == null)
fail("no record is returned.");
while(result.next())
{
if(result.getString("name").indexOf(name, 0)==-1)
{
fail("Offender_GetByName test failed. Found a case doesn't contain '" + name +"'");
}
//assertEquals();
count++;
}
assertEquals(3,count);
}
catch(Exception ex)
{
fail("Offender_GetByName test failed." + ex.getMessage());
}
}
@Test
public void DemoInfo_GetByID() {
System.out.println("DemoInfo_GetByID");
int count=0;
int ID = 1;
try
{
ResultSet result = DataAccess.DemoInfo_GetByID(ID);
if(result == null)
fail("no record is returned.");
while(result.next())
{
assertEquals(ID,result.getInt("demoid"));
count++;
}
assertEquals(1,count);
}
catch(Exception ex)
{
fail("DemoInfo_GetByID test failed." + ex.getMessage());
}
}
@Test
public void Means_GetByID() {
System.out.println("Means_GetByID");
int count=0;
int ID = 1;
try
{
ResultSet result = DataAccess.Means_GetByID(ID);
if(result == null)
fail("no record is returned.");
while(result.next())
{
assertEquals(ID,result.getInt("meansid"));
count++;
}
assertEquals(1,count);
}
catch(Exception ex)
{
fail("Means_GetByID test failed." + ex.getMessage());
}
}
@Test
public void Means_GetAll() {
System.out.println("Means_GetAll");
int count=0;
try
{
ResultSet result = DataAccess.Means_GetAll();
if(result == null)
fail("no record is returned.");
while(result.next())
{
count++;
}
assertEquals(7,count);
}
catch(Exception ex)
{
fail("Means_GetAll test failed." + ex.getMessage());
}
}
@Test
public void Role_GetByID() {
System.out.println("Role_GetByID");
int count=0;
int ID = 1;
try
{
ResultSet result = DataAccess.Role_GetByID(ID);
if(result == null)
fail("no record is returned.");
while(result.next())
{
assertEquals(ID,result.getInt("roleid"));
count++;
}
assertEquals(1,count);
}
catch(Exception ex)
{
fail("Role_GetByID test failed." + ex.getMessage());
}
}
@Test
public void Role_GetAll() {
System.out.println("Role_GetAll");
int count=0;
try
{
ResultSet result = DataAccess.Role_GetAll();
if(result == null)
fail("no record is returned.");
while(result.next())
{
count++;
}
assertEquals(3,count);
}
catch(Exception ex)
{
fail("Role_GetAll test failed." + ex.getMessage());
}
}
@Test
public void Victim_GetByID() {
System.out.println("Victim_GetByID");
int count=0;
try
{
ResultSet result = DataAccess.Victim_GetByID(1,1);
if(result == null)
fail("no record is returned.");
while(result.next())
{
count++;
}
assertEquals(1,count);
}
catch(Exception ex)
{
fail("Role_GetAll test failed." + ex.getMessage());
}
}
}
|
package com.ccxia.cbcraft.item;
import com.ccxia.cbcraft.CbCraft;
import com.ccxia.cbcraft.creativetab.CreativeTabsCbCraft;
import net.minecraft.item.Item;
public class ItemCocoaCream extends Item {
public ItemCocoaCream() {
this.setUnlocalizedName(CbCraft.MODID + ".cocoaCream");
this.setRegistryName("cocoa_cream");
this.setCreativeTab(CreativeTabsCbCraft.tabCbCraft);
}
}
|
package edu.upc.adapterviews;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Auth_Activity extends Activity implements View.OnClickListener {
private EditText labelServer;
private EditText labelUser;
private EditText labelPort;
private String server;
private String username;
private String port;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.auth);
((Button) findViewById(R.id.mainButton)).setOnClickListener(this);
}
public void onClick(View arg0) {
if (arg0 == findViewById(R.id.mainButton)) {
labelServer = (EditText) findViewById(R.id.serverET);
labelPort = (EditText) findViewById(R.id.portET);
labelUser = (EditText) findViewById(R.id.usernameET);
server = labelServer.getText().toString();
port = labelPort.getText().toString();
username = labelUser.getText().toString();
if (!server.isEmpty()) {
if (!port.isEmpty()) {
if (!username.isEmpty()) {
Intent intent = new Intent(this, Chat_Activity.class);
intent.putExtra("Server", server);
intent.putExtra("Port", port);
intent.putExtra("Username", username);
startActivity(intent);
} else {
Toast.makeText(this, "You cannot leave Username blank!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "You cannot leave Port blank!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "You cannot leave Server blank!", Toast.LENGTH_SHORT).show();
}
}
}
}
|
package com.tencent.mm.plugin.subapp.ui.voicereminder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.plugin.subapp.c.d;
class RemindDialog$3 implements OnClickListener {
final /* synthetic */ RemindDialog otT;
RemindDialog$3(RemindDialog remindDialog) {
this.otT = remindDialog;
}
public final void onClick(DialogInterface dialogInterface, int i) {
d bGs = d.bGs();
if (bGs != null) {
bGs.ix(RemindDialog.c(this.otT));
}
this.otT.finish();
}
}
|
package questions.GroupAnagrams_0049;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* @lc app=leetcode.cn id=49 lang=java
*
* [49] 字母异位词分组
*
* https://leetcode-cn.com/problems/group-anagrams/description/
*
* algorithms
* Medium (59.30%)
* Likes: 230
* Dislikes: 0
* Total Accepted: 42.4K
* Total Submissions: 70.7K
* Testcase Example: '["eat","tea","tan","ate","nat","bat"]'
*
* 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
*
* 示例:
*
* 输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
* 输出:
* [
* ["ate","eat","tea"],
* ["nat","tan"],
* ["bat"]
* ]
*
* 说明:
*
*
* 所有输入均为小写字母。
* 不考虑答案输出的顺序。
*
*
*/
// @lc code=start
class Solution {
private Map<String, List<String>> map = new HashMap<>();
// 方法一:排序数组分类
public List<List<String>> groupAnagrams(String[] strs) {
for (int i = 0; i < strs.length; i++) {
String str = strs[i];
String key = this.sortByAlphabet(str);
List<String> list;
if(map.containsKey(key))
list = map.get(key);
else {
list = new ArrayList<>();
map.put(key, list);
}
list.add(str);
}
List<List<String>> res = new ArrayList<>();
map.forEach((key, list) -> {
res.add(list);
});
return res;
}
public String sortByAlphabet(String str){
char[] chars = str.toCharArray();
Arrays.sort(chars);
return String.valueOf(chars);
}
}
// @lc code=end
|
package com.junye.rest.controller;
import java.security.Provider.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.junye.service.LunboService;
import com.junye.service.impl.LunboServiceImpl;
import com.junye.vo.ImgVo;
/**
* @author 作者 junye E-mail: 1105128664@qq.com
* @version 创建时间:2018年9月3日
* 类说明 :
*/
@RestController("LunboController")
@RequestMapping("/api")
public class LunboController {
@Autowired
private LunboService lunboService;
@RequestMapping("/getlunbo")
public Map<String,Object> getLunbo(HttpServletRequest req,HttpServletResponse rsq){
Map<String,Object> map = new HashMap<String, Object>();
List<ImgVo> lunbo = lunboService.getLunbo();
Map<String,Object> map2 = new HashMap<String, Object>();
map.put("status", 0);
map.put("message", lunbo);
rsq.setHeader("Access-Control-Allow-Origin", "*");
return map;
}
@RequestMapping("/getthumimages/{imgid}")
public Map<String,Object> getthumimagesById(@PathVariable("imgid") String imgid,HttpServletRequest req,HttpServletResponse rsq){
Map<String,Object> map = new HashMap<String, Object>();
List<ImgVo> images = lunboService.getthumimagesById(imgid);
Map<String,Object> map2 = new HashMap<String, Object>();
map.put("status", 0);
map.put("message", images);
rsq.setHeader("Access-Control-Allow-Origin", "*");
return map;
}
}
|
package com.kunsoftware.controller.manager;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.kunsoftware.bean.JsonBean;
import com.kunsoftware.bean.OrdersAttachmentRequestBean;
import com.kunsoftware.controller.BaseController;
import com.kunsoftware.entity.Orders;
import com.kunsoftware.entity.OrdersAttachment;
import com.kunsoftware.exception.KunSoftwareException;
import com.kunsoftware.service.OrdersAttachmentService;
import com.kunsoftware.service.OrdersService;
@Controller
@RequestMapping("/manager/ordersattachment")
public class OrdersAttachmentController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(OrdersAttachmentController.class);
@Autowired
private OrdersAttachmentService service;
@Autowired
private OrdersService ordersService;
@RequestMapping("/list")
public String listOrdersAttachment(ModelMap model,Integer ordersId) throws KunSoftwareException {
logger.info("订单附件列表");
Orders orders = ordersService.selectByPrimaryKey(ordersId);
List<OrdersAttachment> list = service.getOrdersAttachmentListAll(ordersId);
model.addAttribute("retList", list);
model.addAttribute("orders", orders);
return "manager/ordersattachment/ordersattachment-list";
}
@RequestMapping("/add")
public String addOrdersAttachment(ModelMap model) throws KunSoftwareException {
logger.info("添加订单附件");
return "manager/ordersattachment/ordersattachment-add";
}
@RequestMapping(value="/add.json")
@ResponseBody
public JsonBean addOrdersAttachment(@RequestParam(value = "ordersattachmentFile", required = false) MultipartFile file,OrdersAttachmentRequestBean requestBean) throws KunSoftwareException {
logger.info("保存订单附件");
requestBean.setFile(file);
OrdersAttachment entity = service.insert(requestBean);
JsonBean jsonBean = new JsonBean();
jsonBean.put("id", entity.getId());
jsonBean.setMessage("操作成功");
return jsonBean;
}
@RequestMapping("/edit")
public String editOrdersAttachment(ModelMap model,Integer id) throws KunSoftwareException {
logger.info("编辑订单附件");
OrdersAttachment entity = service.selectByPrimaryKey(id);
model.addAttribute("entity", entity);
return "manager/ordersattachment/ordersattachment-edit";
}
@RequestMapping(value="/edit.json")
@ResponseBody
public JsonBean editOrdersAttachment(@RequestParam(value = "ordersattachmentImageFile", required = false) MultipartFile file,OrdersAttachmentRequestBean requestBean,Integer id) throws KunSoftwareException {
logger.info("编辑保存订单附件");
requestBean.setFile(file);
service.updateByPrimaryKey(requestBean,id);
JsonBean jsonBean = new JsonBean();
jsonBean.setMessage("操作成功");
return jsonBean;
}
@RequestMapping(value="/del.json")
@ResponseBody
public JsonBean delOrdersAttachment(Integer[] id) throws KunSoftwareException {
logger.info("删除订单附件");
service.deleteByPrimaryKey(id);
JsonBean jsonBean = new JsonBean();
jsonBean.setMessage("操作成功");
return jsonBean;
}
}
|
package mygame.gameplay;
import com.jme3.bullet.control.CharacterControl;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import mygame.StageManager;
import mygame.stage.GamePlayManager;
public class Player {
private Node modelNode;
private GamePlayManager gamePlayManager;
// Player properties
private String name;
private PlayerAvatar playerAvatar;
private PlayerProfile playerProfile;
private GameCharacter playerMainCharacter;
private final StageManager stageManager;
RPGCharacterControl characterControl;
public Player(StageManager stageManager, GamePlayManager gamePlayManager, String name) {
this.stageManager = stageManager;
this.gamePlayManager = gamePlayManager;
this.name = name;
}
public void initPlayer(Node modelNode, RPGCharacterControl characterControl) {
this.modelNode = modelNode;
this.playerMainCharacter = new GameCharacter("Character " + name, modelNode);
this.characterControl = characterControl;
modelNode.addControl(characterControl);
}
public void simpleUpdate(float tpf) {
}
public Spatial getPlayerModel() {
return modelNode;
}
public Node getModelNode() {
return modelNode;
}
public void setModelNode(Node modelNode) {
this.modelNode = modelNode;
}
public PlayerAvatar getPlayerAvatar() {
return playerAvatar;
}
public void setPlayerAvatar(PlayerAvatar playerAvatar) {
this.playerAvatar = playerAvatar;
}
public GameCharacter getPlayerMainCharacter() {
return playerMainCharacter;
}
public void setPlayerMainCharacter(GameCharacter playerMainCharacter) {
this.playerMainCharacter = playerMainCharacter;
}
public PlayerProfile getPlayerProfile() {
return playerProfile;
}
public void setPlayerProfile(PlayerProfile playerProfile) {
this.playerProfile = playerProfile;
}
public RPGCharacterControl getCharacterControl() {
return characterControl;
}
}
|
package com.tencent.mm.plugin.freewifi.e;
import com.tencent.mm.plugin.freewifi.a.a.a;
import com.tencent.mm.plugin.freewifi.e.i.1;
import com.tencent.mm.plugin.freewifi.k.b;
import com.tencent.mm.plugin.freewifi.m;
import com.tencent.mm.plugin.freewifi.ui.FreeWifiFrontPageUI;
import com.tencent.mm.plugin.freewifi.ui.FreeWifiFrontPageUI.d;
import com.tencent.mm.sdk.platformtools.x;
import java.net.HttpURLConnection;
class i$1$1 implements a {
final /* synthetic */ 1 jlc;
i$1$1(1 1) {
this.jlc = 1;
}
public final void g(HttpURLConnection httpURLConnection) {
int responseCode = httpURLConnection.getResponseCode();
x.i("MicroMsg.FreeWifi.Protocol33", "sessionKey=%s, step=%d, method=Protocol33.HttpAuthentication.onSuccess, desc=it receives http response for authentication. http response status code=%d", new Object[]{m.E(this.jlc.jlb.intent), Integer.valueOf(m.F(this.jlc.jlb.intent)), Integer.valueOf(responseCode)});
if (responseCode == 200) {
this.jlc.jlb.aPk();
} else if (responseCode == 302) {
i.a(this.jlc.jlb, httpURLConnection.getHeaderField("Location"));
} else {
x.i("MicroMsg.FreeWifi.Protocol33", "sessionKey=%s, step=%d, method=Protocol33.httpAuthentication, desc=http response status code is neither 200 nor 302, so it fails to connect wifi. ", new Object[]{m.E(this.jlc.jlb.intent), Integer.valueOf(m.F(this.jlc.jlb.intent))});
FreeWifiFrontPageUI freeWifiFrontPageUI = this.jlc.jlb.jkG;
d dVar = d.jnj;
FreeWifiFrontPageUI.a aVar = new FreeWifiFrontPageUI.a();
aVar.jmI = m.a(this.jlc.jlb.jkI, b.jiJ, 32);
freeWifiFrontPageUI.a(dVar, aVar);
}
}
public final void j(Exception exception) {
x.i("MicroMsg.FreeWifi.Protocol33", "sessionKey=%s, step=%d, method=Protocol33.httpAuthentication, desc=exception happens during http, so it fails to connect wifi. e.getMessage()=%s, stacktrace=%s", new Object[]{m.E(this.jlc.jlb.intent), Integer.valueOf(m.F(this.jlc.jlb.intent)), exception.getMessage(), m.h(exception)});
FreeWifiFrontPageUI freeWifiFrontPageUI = this.jlc.jlb.jkG;
d dVar = d.jnj;
FreeWifiFrontPageUI.a aVar = new FreeWifiFrontPageUI.a();
aVar.jmI = m.a(this.jlc.jlb.jkI, b.jiJ, m.i(exception));
freeWifiFrontPageUI.a(dVar, aVar);
}
}
|
/**
* Data Transfer Objects.
*/
package projet.jee.gi.ensa.service.dto;
|
package jp.smartcompany.job.enums;
/**
* @author xiao wenpeng
*/
public interface ResponseMessage {
/**
* 返回状态码
* @return int
*/
int code();
/**
* 返回提示信息
* @return String
*/
String msg();
}
|
/*
* Copyright (C) 2019-2023 Hedera Hashgraph, LLC
*
* 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.hedera.mirror.common.domain.contract;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.hedera.mirror.common.converter.ListToStringSerializer;
import com.hedera.mirror.common.domain.entity.EntityId;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import java.util.Collections;
import java.util.List;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.SuperBuilder;
import org.springframework.data.domain.Persistable;
@Data
@Entity
@NoArgsConstructor
@SuperBuilder
public class ContractResult implements Persistable<Long> {
private Long amount;
@ToString.Exclude
private byte[] bloom;
@ToString.Exclude
private byte[] callResult;
@Id
private Long consensusTimestamp;
private long contractId;
@Builder.Default
@JsonSerialize(using = ListToStringSerializer.class)
private List<Long> createdContractIds = Collections.emptyList();
private String errorMessage;
@ToString.Exclude
private byte[] failedInitcode;
@ToString.Exclude
private byte[] functionParameters;
private byte[] functionResult; // Temporary field until we can confirm the migration captured everything
private Long gasLimit;
private Long gasUsed;
private EntityId payerAccountId;
private EntityId senderId;
private byte[] transactionHash;
private Integer transactionIndex;
private int transactionNonce;
private Integer transactionResult;
@JsonIgnore
@Override
public Long getId() {
return consensusTimestamp;
}
@JsonIgnore
@Override
public boolean isNew() {
return true; // Since we never update and use a natural ID, avoid Hibernate querying before insert
}
}
|
package minimal;
import static org.junit.Assert.*;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class Market {
private FirefoxDriver driver;
String URL = "https://market.yandex.ru/";
@Before
public void setUp() throws Exception {
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("version", "latest");
capabilities.setCapability("platform", Platform.WINDOWS);
capabilities.setCapability("name", "Testing Selenium");
System.setProperty("webdriver.gecko.driver", "/Applications/Firefox.app/Contents/MacOS/firefox-bin");
this.driver = new FirefoxDriver(capabilities);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
@Test
public void testYaMarket() throws Exception {
driver.get(URL);
assertEquals(URL, this.driver.getCurrentUrl());
// Нажать по ссылке "Каталог"
// Открыт "Каталог", представлены блоки: основные категории товаров, "Популярные товары",
// "Вас также могут заинтересовать", "Статьи и подборки"
WebElement catalogLink = driver.findElement(By.xpath("//span[contains(.,'Каталог')]"));
catalogLink.click();
assertEquals(this.driver.getCurrentUrl(), URL + "?tab=catalog");
String mainCategory = "//div[@class='catalog-simple__item']";
int mainCategoriesCount = 12;
List<WebElement> mainCategories = driver.findElementsByXPath(mainCategory);
assertEquals(mainCategories.size(), mainCategoriesCount);
mainCategories.get(mainCategoriesCount - 1).sendKeys(Keys.PAGE_DOWN);
String articlesSection = "//div[@class='snippet-list snippet-list_type_grid snippet-list_size_4']";
String interestSection = "//div[@class='snippet-list snippet-list_size_4 flex-grid__list']";
String popularSection = "//div[@class='snippet-list snippet-list_type_grid snippet-list_size_4 metrika i-bem metrika_js_inited']";
List<String> sections = Arrays.asList(articlesSection, interestSection, popularSection);
for (String x : sections) checkXpathElement(x);
// Перейти в раздел "Электроника" -> "Мобильные телефоны"
// Открыт раздел "Мобильные телефоны", в категории "Популярные" и "Новинки" представлены 3 девайса
String electronic = "Электроника";
String mobilePhones = "Мобильные телефоны";
driver.findElementByLinkText(electronic).click();
driver.findElementByLinkText(mobilePhones).click();
assertTrue(driver.getTitle().contains(mobilePhones));
List<String> categories = Arrays.asList("Популярные", "Новинки");
for (String name : categories) {
String query = "//div[@class='top-3-models'][contains(.,'" + name + "')]";
checkXpathElement(query);
int devicesCount = 3;
String partPath = "/ul/li";
assertEquals(driver.findElementsByXPath(query + partPath).size(), devicesCount);
}
// Нажать по "расширенный поиск" блока выбора по параметрам
driver.findElementByLinkText("Расширенный поиск →").click();
assertTrue(driver.getTitle().contains(mobilePhones));
String paramsBlock = "//div[@class='layout__col layout__col_search-filters_visible i-bem']";
assertTrue(driver.findElementByXPath(paramsBlock).isDisplayed());
// Ввести Цену, руб. "от" значение 5125
// Ввести Цену, руб. "до" значение 10123
HashMap<String, String> prices = new HashMap<String, String>();
prices.put("glf-pricefrom-var", "5125");
prices.put("glf-priceto-var", "10123");
for (Map.Entry<String, String> x : prices.entrySet()) {
driver.findElementById(x.getKey()).sendKeys(x.getValue());
assertEquals(driver.findElementById(x.getKey()).getAttribute("value"), x.getValue());
}
WebElement checkBoxOnStock = driver.findElementById("glf-onstock-select");
if (!checkBoxOnStock.isSelected()) {
checkBoxOnStock.click();
}
assertTrue(checkBoxOnStock.isSelected());
// Раскрыть блок "Тип"
String typePhone = "//span[@class='title__content'][contains(.,'Тип')]";
String itemSmartphone = "//label[@class='checkbox__label'][contains(.,'смартфон')]";
if (!driver.findElementByXPath(itemSmartphone).isDisplayed()) {
driver.findElement(By.xpath(typePhone)).click();
}
driver.findElementByXPath(itemSmartphone).click();
checkSelected(itemSmartphone);
// Кликнуть на селектбокс "Android"
String itemAndroid = "//label[@class='checkbox__label'][contains(.,'Android')]";
WebElement checkboxAndroid = driver.findElementByXPath(itemAndroid);
checkboxAndroid.click();
checkSelected(itemAndroid);
// Случано выбрать 3 устройства из представленных на странице, имеющих рейтинг от "3,5" до "4,5",
// и вывести в лог информацию в формате
// "номер девайса на странице - наименование девайса - стоимость девайса (от-до)"
String itemDevice = "//div[@class='n-snippet-card snippet-card clearfix i-bem n-snippet-card_js_inited']";
List<WebElement> list = driver.findElementsByXPath(itemDevice);
List<String> result = new ArrayList<String>();
for (int i = 0; i < list.size() - 1; i++) {
String[] args = list.get(i).getText().split("\n");
Double rate = Double.valueOf(args[0]);
if ((rate <= 4.5) && (rate >= 3.5)) {
String name = args[3];
String wordForDelete = "Новинка";
if (name.toString().contains(wordForDelete)) {
name = name.replace(wordForDelete, "");
}
String separator = " - ";
result.add("Номер на странице " + (++i) + separator + name + separator + args[1] + separator + args[2]);
}
}
// оставить только 3 элемента в списке для вывода
while (result.size() > 3) {
Random rand = new Random();
int n = rand.nextInt(result.size());
result.remove(n);
}
for (String x : result) {
System.out.println(x);
}
}
private void checkSelected(String queryCheckbox) {
assertEquals(driver.findElementsByXPath(queryCheckbox + "/parent::*").size(), 1);
assertTrue(driver.findElementsByXPath(queryCheckbox + "/parent::*").get(0).
getAttribute("class").contains("checkbox_checked_yes"));
}
private void checkXpathElement(String xpath) {
assertTrue(driver.findElement(By.xpath(xpath)).isDisplayed());
}
@After
public void tearDown() throws Exception {
this.driver.quit();
}
}
|
package com.study.demo.security.handlers;
import java.util.List;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import com.study.demo.vo.Member;
import lombok.Data;
//현재 로그인한 사용자 객체 저장 DTO
@Data
public class MyAuthentication extends UsernamePasswordAuthenticationToken{
private static final long serialVersionUID = 1L;
Member member;
public MyAuthentication(String id, String password, List<GrantedAuthority> grantedAuthorityList, Member member) {
super(id, password, grantedAuthorityList);
this.member = member;
}
}
|
package com.company.crackingthecode.stringsandarrays;
import java.util.ArrayList;
import java.util.List;
public class Anagram {
public static void main(String[] args) {
System.out.println(numOfDeletions("fcrxzwscanmligyxyvym", "jxwtrhvujlmrpdoqbisbwhmgpmeoke"));
}
static int wrongAnswerDoesntAlwaysWork(String s1, String s2) {
List<Character> charSet = new ArrayList<>();
String longer = s1.length() >= s2.length() ? s1 : s2;
String shortest = s1.length() >= s2.length() ? s2 : s1;
int index = 0;
for (int i = 0; i < longer.length(); i++) {
char c = longer.charAt(i);
if (charSet.contains(c)) {
continue;
}
for (int j = 0; j < shortest.length(); j++) {
if (c == shortest.charAt(j)) {
charSet.add(index, c);
index++;
}
}
}
return (s1.length() - charSet.size()) + (s2.length() - charSet.size());
}
static int numOfDeletions(String s1, String s2) {
return 0;
}
}
|
package com.freak.printtool.hardware.utils;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;
/**
* 时间的工具类
*
* @author Freak
* @date 2019/8/13.
*/
public class DateUtil {
private final static SimpleDateFormat SDF_YEAR = new SimpleDateFormat("yyyy");
private final static SimpleDateFormat SDF_DAY = new SimpleDateFormat("yyyy-MM-dd");
private final static SimpleDateFormat SDF_DAYS = new SimpleDateFormat("yyyyMMdd");
private final static SimpleDateFormat SDF_TIMES = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final static SimpleDateFormat SDF_TIME = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private final static SimpleDateFormat SDF_MONTH = new SimpleDateFormat("yyyy-MM");
private final static SimpleDateFormat SN_TIMES = new SimpleDateFormat("yyyyMMddHHmmss");
/**
* 精确到毫秒的完整时间 如:yyyy-MM-dd HH:mm:ss.S
*/
public static final String FORMAT_FULL = "yyyy-MM-dd HH:mm:ss.S";
/**
* 这是sn生成的方法 具体到秒 加二位随机数
*
* @return
*/
public static Long createSn() {
int i = new Random().nextInt(10000);
DecimalFormat localDecimalFormat = new DecimalFormat("0000");
return Long.parseLong(getSn() + "" + localDecimalFormat.format(i));
}
/**
* 2017 06 02 18 26 50> yyyy-MM-dd HH:mm:ss
*
* @param sn
* @return
*/
public static String setStandardDate(String sn) {
StringBuilder date = new StringBuilder(sn);
date.insert(4, "-");
date.insert(7, "-");
date.insert(10, " ");
date.insert(13, ":");
date.insert(16, ":");
return date.toString();
}
/**
* 获取YYYY格式
*
* @return
*/
public static String getYear() {
return SDF_YEAR.format(new Date());
}
/**
* 获取YYYY-MM-DD格式
*
* @return
*/
public static String getDay() {
return SDF_DAY.format(new Date());
}
/**
* 获取YYYYMMDD格式
*
* @return
*/
public static String getDays() {
return SDF_DAYS.format(new Date());
}
/**
* 获取YYYY-MM-DD hh:mm:ss格式
*
* @return
*/
public static String getTimes() {
return SDF_TIMES.format(new Date());
}
/**
* 获取YYYY-MM-DD hh:mm:ss格式
*
* @return
*/
public static String getSn() {
return SN_TIMES.format(new Date());
}
/**
* 获取YYYY-MM-DD hh:mm格式
*
* @return
*/
public static String getTime() {
return SDF_TIME.format(new Date());
}
/**
* @param s
* @param e
* @return boolean
* @throws
* @Title: compareDate
* @Description: 日期比较,如果s>=e 返回true 否则返回false
* @author luguosui
*/
public static boolean compareDate(String s, String e) {
if (fomatDate(s) == null || fomatDate(e) == null) {
return false;
}
return fomatDate(s).getTime() >= fomatDate(e).getTime();
}
/**
* 格式化日期
*
* @return
*/
public static Date fomatDate(String date) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
return fmt.parse(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 格式化日期
*
* @return
*/
public static Date fomatTime(String date) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return fmt.parse(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 校验日期是否合法
*
* @return
*/
public static boolean isValidDate(String s) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
fmt.parse(s);
return true;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
return false;
}
}
/**
* 将时间戳转为字符串
*
* @param ccTime
* @return
*/
public static String getStrTime(String ccTime) {
String reStrTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
long lccTime = Long.valueOf(ccTime);
reStrTime = sdf.format(new Date(lccTime));
return reStrTime;
}
/**
* 将字符串转为时间戳
*
* @param userTime
* @return
*/
public static String getTime(String userTime) {
String reTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date d;
try {
d = sdf.parse(userTime);
long l = d.getTime();
String str = String.valueOf(l);
reTime = str.substring(0, 10);
} catch (ParseException e) {
e.printStackTrace();
}
return reTime;
}
/**
* 将字符串转为时间戳
*
* @param userTime
* @return
*/
public static String getDate(String userTime) {
String reTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d;
try {
d = sdf.parse(userTime);
long l = d.getTime();
String str = String.valueOf(l);
reTime = str.substring(0, 10);
} catch (ParseException e) {
e.printStackTrace();
}
return reTime;
}
/**
* 获取时间戳
*
* @return 获取时间戳
*/
public static String getTimeString() {
SimpleDateFormat df = new SimpleDateFormat(FORMAT_FULL);
Calendar calendar = Calendar.getInstance();
return df.format(calendar.getTime());
}
public static int getDiffYear(String startTime, String endTime) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
long aa = 0;
int years = (int) (((fmt.parse(endTime).getTime() - fmt.parse(
startTime).getTime()) / (1000 * 60 * 60 * 24)) / 365);
return years;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
return 0;
}
}
/**
* <li>功能描述:时间相减得到天数
*
* @param beginDateStr
* @param endDateStr
* @return long
* @author Administrator
*/
public static long getDaySub(String beginDateStr, String endDateStr) {
long day = 0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = null;
Date endDate = null;
try {
beginDate = format.parse(beginDateStr);
endDate = format.parse(endDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
return day;
}
/**
* 得到n天之后的日期
*
* @param days
* @return
*/
public static String getAfterDayDate(String days) {
int daysInt = Integer.parseInt(days);
// java.util包
Calendar canlendar = Calendar.getInstance();
// 日期减 如果不够减会将月变动
canlendar.add(Calendar.DATE, daysInt);
Date date = canlendar.getTime();
// SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdfd.format(date);
return dateStr;
}
/**
* 得到n天之后是周几
*
* @param days
* @return
*/
public static String getAfterDayWeek(String days) {
int daysInt = Integer.parseInt(days);
// java.util包
Calendar canlendar = Calendar.getInstance();
// 日期减 如果不够减会将月变动
canlendar.add(Calendar.DATE, daysInt);
Date date = canlendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("E");
String dateStr = sdf.format(date);
return dateStr;
}
/**
* 获取每月的天数
*
* @param month
*/
public static int getMonthDays(String month) {
// String month = "2015-05";
try {
Date date = SDF_MONTH.parse(month);
// java.util包
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
} catch (ParseException e) {
e.printStackTrace();
}
//默认返回最大值每月的最大值31
return 31;
}
/**
* 入口测试方法
*
* @param args
*/
// public static void main(String[] args) {
//
// int days = getMonthDays("2015-02");
// System.out.println(days);
// System.out.println(DateUtil.SDF_TIME);
// }
}
|
package com.bytedance.ies.bullet.kit.rn;
import com.bytedance.ies.bullet.b.e.aa;
import com.bytedance.ies.bullet.b.e.h;
import com.bytedance.ies.bullet.b.e.i;
import com.bytedance.ies.bullet.b.e.l;
import com.bytedance.ies.bullet.b.e.m;
import com.bytedance.ies.bullet.b.e.s;
import com.bytedance.ies.bullet.b.e.w;
import com.bytedance.ies.bullet.kit.rn.a.b;
import com.bytedance.ies.bullet.kit.rn.a.c;
import com.facebook.react.bridge.INativeLibraryLoader;
import com.facebook.react.bridge.OnRNLoadExceptionListener;
import com.facebook.react.bridge.ReactBridge;
import d.f.b.l;
import java.util.List;
import org.json.JSONObject;
public final class RnKitApi implements IRnKitApi<j> {
public static final a Companion = new a(null);
public static final String SCHEME_RN = "react-native";
private com.bytedance.ies.bullet.b.g.a.b contextProviderFactory;
private h globalSettingsProvider;
private boolean hasInitialized;
private final Class<j> instanceType = j.class;
public static IRnKitApi createIRnKitApibyMonsterPlugin() {
Object object = com.ss.android.ugc.b.a(IRnKitApi.class);
return (object != null) ? (IRnKitApi)object : new RnKitApi();
}
public final h<h> convertToGlobalSettingsProvider(Object paramObject) {
l.b(paramObject, "delegate");
return (paramObject instanceof b) ? new b(paramObject) : null;
}
public final l<i, g> convertToPackageProviderFactory(Object paramObject) {
l.b(paramObject, "delegate");
return (paramObject instanceof c) ? new c(paramObject) : null;
}
public final void ensureKitInitialized() {
if (!this.hasInitialized) {
e e;
h h1 = this.globalSettingsProvider;
h h2 = null;
if (h1 != null) {
d d = h1.a();
} else {
h1 = null;
}
f f = new f((d)h1);
com.bytedance.ies.bullet.b.g.a.b b1 = this.contextProviderFactory;
h1 = h2;
if (b1 != null) {
com.bytedance.ies.bullet.b.f.d d = (com.bytedance.ies.bullet.b.f.d)b1.c(com.bytedance.ies.bullet.b.f.d.class);
h1 = h2;
if (d != null)
e = new e(d);
}
if (e == null) {
ReactBridge.staticInit(f);
} else {
ReactBridge.staticInit(f, e);
}
ReactBridge.setJSExceptionListener(d.a);
this.hasInitialized = true;
}
}
public final Class<j> getInstanceType() {
return this.instanceType;
}
public final String getKitSDKVersion() {
return "0.55.4-LYNX-1.3.0.39";
}
public final com.bytedance.ies.bullet.b.e.a getKitType() {
return com.bytedance.ies.bullet.b.e.a.RN;
}
public final void onApiMounted(j paramj) {
l.b(paramj, "kitInstanceApi");
}
public final void onInitialized(h paramh, com.bytedance.ies.bullet.b.g.a.b paramb) {
l.b(paramb, "contextProviderFactory");
this.globalSettingsProvider = paramh;
this.contextProviderFactory = paramb;
}
public final j provideInstanceApi(aa paramaa, List<String> paramList, com.bytedance.ies.bullet.b.d paramd, com.bytedance.ies.bullet.b.g.a.b paramb) {
l.b(paramaa, "sessionInfo");
l.b(paramList, "packageNames");
l.b(paramd, "kitPackageRegistryBundle");
l.b(paramb, "providerFactory");
ensureKitInitialized();
return new j(this, paramaa, paramList, paramd, paramb);
}
public final com.bytedance.ies.bullet.b.g.c.d<w> provideProcessor() {
return new g(this);
}
public final boolean useNewInstance() {
return true;
}
public static final class a {
private a() {}
}
public static final class b implements h<h> {
b(Object param1Object) {}
}
public static final class c implements l<i, g> {
c(Object param1Object) {}
}
static final class d implements ReactBridge.JSExceptionListener {
public static final d a = new d();
public final void upLoad(JSONObject param1JSONObject) {}
}
public static final class e implements INativeLibraryLoader {
e(com.bytedance.ies.bullet.b.f.d param1d) {}
public final void loadLibrary(String param1String) {}
}
public static final class f implements OnRNLoadExceptionListener {
f(d param1d) {}
public final void onLoadError(String param1String) {}
}
public static final class g implements com.bytedance.ies.bullet.b.g.c.d<w> {
g(RnKitApi param1RnKitApi) {}
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\bytedance\ies\bullet\kit\rn\RnKitApi.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package me.solidev.library.ui.activity;
import me.solidev.library.utils.ToastUtil;
/**
* Created by _SOLID
* Date:2016/6/2
* Time:16:58
* Desc:
*/
public abstract class BaseMainActivity extends BaseActivity {
private long lastBackKeyDownTick = 0;
private static final long MAX_DOUBLE_BACK_DURATION = 1500;
@Override
public void onBackPressed() {
beforeOnBackPressed();
long currentTick = System.currentTimeMillis();
if (currentTick - lastBackKeyDownTick > MAX_DOUBLE_BACK_DURATION) {
ToastUtil.getInstance().showShortToast("再按一次退出");
lastBackKeyDownTick = currentTick;
} else {
finish();
System.exit(0);
}
}
protected void beforeOnBackPressed() {
}
}
|
package pl.finsys.setterExample;
public class OutputHelper {
private IOutputGenerator outputGenerator;
public void generateOutput() {
outputGenerator.generateOutput();
}
//wstrzykniecie przez metode setter'a
public void setOutputGenerator(IOutputGenerator outputGenerator) {
this.outputGenerator = outputGenerator;
}
}
|
package com.sarf.dao;
import java.util.List;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.sarf.vo.ReplyVO;
@Repository
public class R_ReplyDAOImpl implements ReplyDAO{
@Inject
private SqlSession sql;
String mapper = "r_replyMapper";
// 댓글 조회
@Override
public List<ReplyVO> readReply(int bno) throws Exception {
return sql.selectList(mapper + ".readReply", bno);
}
//댓글 작성
@Override
public void writeReply(ReplyVO r_vo) throws Exception {
sql.insert(mapper + ".writeReply", r_vo);
}
// 댓글 수정
@Override
public void updateReply(ReplyVO r_vo) throws Exception {
sql.update(mapper + ".updateReply", r_vo);
}
// 선택된 댓글 조회
@Override
public ReplyVO selectReply(int rno) throws Exception {
return sql.selectOne(mapper + ".selectReply", rno);
}
// 댓글 삭제
@Override
public void deleteReply(ReplyVO r_vo) throws Exception {
sql.delete(mapper + ".deleteReply", r_vo);
}
}
|
package com.yt.factory;
public class WhiteHumanWomen extends WhiteHumanMan {
@Override
public void sex() {
System.out.println("白种人性别为女");
}
}
|
package listaJava2;
import java.util.Scanner;
public class ListaJavaExercicio2 {
public static void main(String[] args) {
// Ler 10 números e imprimir quantos são pares e quantos são ímpares. (FOR)
int x =0, par =0, impar =0, numero =0;
Scanner leia = new Scanner(System.in);
for(x = 1; x<= 10; x++)
{
System.out.print("Digite um número");
numero = leia.nextInt();
if(numero % 2 !=0)
{
impar++;
}else
{
par++;
}
}
System.out.printf("Foram lidos %d números pares e %d número ímpares", par, impar);
leia.close();
}
}
|
package com.codegym.checkinhotel.repository;
import com.codegym.checkinhotel.model.AppRole;
import org.springframework.data.repository.CrudRepository;
import javax.management.relation.Role;
public interface IRoleRepository extends CrudRepository<AppRole,Long> {
}
|
package com.acculytixs.wayuparty.entity.vendor;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "special_package")
public class SpecialPackage implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "vendor_uuid")
private String vendorUUID;
@Column(name = "service_type",columnDefinition = "TEXT default NULL")
private String serviceType;
@Column(name = "start_date")
private Date startDate;
@Column(name = "end_date")
private Date endDate;
@Column(name = "event_banner_image",columnDefinition = "TEXT default NULL")
private String eventBannerImage;
// @Column(name = "event_mobile_banner_image",columnDefinition = "TEXT default NULL")
// private String eventMobileBannerImage;
@Column(name = "event_mobile_banner_image",columnDefinition = "TEXT default NULL")
private String eventDisplayImage;
//
// @Column(name = "event_banner_image",columnDefinition = "TEXT default NULL")
// private String eventBannerImage;
//
@Column(name = "created_date")
private Date createdDate;
public String getEventDisplayImage() {
return eventDisplayImage;
}
public void setEventDisplayImage(String eventDisplayImage) {
this.eventDisplayImage = eventDisplayImage;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getVendorUUID() {
return vendorUUID;
}
public void setVendorUUID(String vendorUUID) {
this.vendorUUID = vendorUUID;
}
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getEventBannerImage() {
return eventBannerImage;
}
public void setEventBannerImage(String eventBannerImage) {
this.eventBannerImage = eventBannerImage;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "SpecialPackage [id=" + id + ", vendorUUID=" + vendorUUID + ", serviceType=" + serviceType
+ ", startDate=" + startDate + ", endDate=" + endDate + ", eventBannerImage=" + eventBannerImage
+ ", eventDisplayImage=" + eventDisplayImage + ", createdDate=" + createdDate + "]";
}
}
|
package cn.xyz.repository;
import java.util.List;
import org.mongodb.morphia.query.UpdateResults;
import cn.xyz.mianshi.vo.PublicNum;
public interface PublicNumRepository {
Integer addPublicNum(PublicNum publicNum);
PublicNum getPublicNum(Integer publicId);
List<Integer> getServiceIds(Integer publicId);
List<PublicNum> getPublcNumListForCS(Integer csUserId);
PublicNum removePublicNum(Integer publicId, Integer csUserId);
UpdateResults deletePublicNum(Integer publicId);
}
|
public abstract class Box {
int height;
int weight;
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setHeight(int height) {
this.height = height;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getName(int a, int b) {
return name;
}
public abstract Integer getHeight();
public abstract Integer getWeight();
}
|
package todos;
import java.util.Scanner;
public class TodoApplication {
/*
TO DO
1. dodaj
2. Wczytaj
0. Koniec
Tablica [10] - 10-elementowa
MENU(1,2,0)
Kliknij 1 - prosisz użytkownika o dodanie " to do ": Dodaj "to do ", naciśnij enter i powróć do menu
Kliknij 2 - Wczytaj wszystkie elementy, które użytkownik dodał : 1. ble ble ble, 2. cos cos cos itd ... [ Scanner.nextline(); ]
kliknij 0 - KONIEC
1 i 2 pętla for !!!
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] todos = new String[10];
int index = 0;
int decision;
do {
TodoViews.menu();
decision = scanner.nextInt();
scanner.nextLine();
switch (decision) {
case 1:
if ( index == todos.length) {
TodoViews.noSpaceWarningMessage();
TodoViews.waitForUser(scanner);
}else{
addTodo(scanner, todos, index);
index++;
}
addTodo(scanner, todos, index);
index++;
break;
case 2:
listTodos(todos, index);
TodoViews.waitForUser(scanner);
break;
}
} while (decision != 0);
}
private static void addTodo(Scanner scanner, String[] todos, int index) {
TodoViews.newTodoMessage();
String newTodo = scanner.nextLine();
todos[index] = newTodo;
}
private static void listTodos( String[] todos, int todosToDisplay) {
//wyświetlanie tablicy
//wyznaczenie zmiennej
if (todosToDisplay == 0) {
TodoViews.noTOdosToDisplayMessage();
}
for (int i = 0; i <todos.length ; i++) {
System.out.println(i + ". " + todos[i]);
}
}
}
|
package com.tencent.mm.plugin.mmsight.model.a;
import com.tencent.mm.plugin.mmsight.model.a.c.a;
import com.tencent.mm.plugin.mmsight.model.a.d.c;
import com.tencent.mm.sdk.platformtools.x;
class n$3 implements a {
final /* synthetic */ n ljp;
n$3(n nVar) {
this.ljp = nVar;
}
public final void beh() {
x.i("MicroMsg.MMSightMediaCodecMP4MuxRecorder", "onPcmReady");
if (this.ljp.lis.ljK != c.lhJ) {
x.w("MicroMsg.MMSightMediaCodecMP4MuxRecorder", "not MediaStatus.Initialized, maybe canceled by user");
return;
}
q qVar = this.ljp.ljg;
x.i("MicroMsg.MMSightYUVMediaCodecBufIdRecorder", "Start");
qVar.bTv = true;
qVar.startTime = System.currentTimeMillis();
this.ljp.lis.a(c.lhC);
}
}
|
package Tests;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import javax.imageio.ImageIO;
import IO.SpriteLoader;
import Utils.Images;
public class ImageBorder {
public static void main(String[] args) {
BufferedImage img = SpriteLoader.loadSprite("front1.png");
int colour = img.getRGB(img.getWidth() / 2, img.getHeight() / 2);
int r = (colour)&0xFF;
int g = (colour>>8)&0xFF;
int b = (colour>>16)&0xFF;
int a = (colour>>24)&0xFF;
System.out.println(r + " " + g + " " + b + " " + a);
LinkedList<int[]> borderPositions = Images.getBorder(img, 1);
for(int[] pos : borderPositions) {
//int colour = img.getRGB(pos[0], pos[1]);
//System.out.println((colour>>24) & 0xff);
//System.out.println((255 << 24));
img.setRGB(pos[0], pos[1], -1689547);
}
System.out.println(Integer.toBinaryString(-1689547));
System.out.println(Integer.parseInt("1111111111001100011100000110101", 2));
System.out.println(-Integer.parseInt("1111111111001100011100000110101", 2));
System.out.println(0xFF);
try {
ImageIO.write(img, "png", new File("test.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.Collections_PriorityQueue_HashMap_TreeMap;
//7. Write a Java program to compare two priority queues.
import java.util.PriorityQueue;
public class PriorityQueue_Comparision {
public static void main(String[] args) {
// Create a empty Priority Queue
PriorityQueue<String> pq1 = new PriorityQueue<String>();
// use add() method to add values in the Priority Queue
pq1.add("Rohit");
pq1.add("Sohan");
pq1.add("Shyamu");
pq1.add("Rahul");
System.out.println("First Priority Queue: "+pq1);
PriorityQueue<String> pq2 = new PriorityQueue<String>();
pq2.add("Rohit");
pq2.add("Rohan");
pq2.add("Shyamu");
pq2.add("KL Rahul");
System.out.println("Second Priority Queue: "+pq2);
//comparison output in Priority Queue
for (String element : pq1){
System.out.println(pq2.contains(element) ? "Yes" : "No");
}
}
}
|
package gdut.ff.generator.util;
/**
*
* @author liuffei
* @date 2018-04-03 update
* @description
*/
public class StringUtil {
/**
* 表名转成类名
* @param tableName
* @return
*/
public static String tableNameToClassName(String tableName) {
StringBuffer className = new StringBuffer("");
String names[] = tableName.split("_");
if(null != names && names.length > 0) {
for(int i = 0;i < names.length;i++) {
className.append(names[i].substring(0,1).toUpperCase()+names[i].substring(1));
}
}
return className.toString();
}
/**
* 查找表的字段
* @param tableColumn
* @return
*/
public static String tableColumnToClassProperty(String columnName) {
StringBuffer propertyName = new StringBuffer("");
String names[] = columnName.split("_");
if(null != names && names.length > 0) {
for(int i = 0;i < names.length;i++) {
if(i == 0) {
propertyName.append(names[i]);
}else {
propertyName.append(names[i].substring(0,1).toUpperCase()+names[i].substring(1));
}
}
}
return propertyName.toString();
}
/**
* 将gdut.ff.domain 转换成gdut/ff/domain
* @param packageName
* @return
*/
public static String formatPathName(String packageName) {
return packageName.replace(".", "/");
}
}
|
package ru.lischenko_dev.fastmessenger.util;
import android.content.*;
import android.preference.*;
public class PrefsManager
{
private static Context context;
public static PrefsManager getInstance(Context c) {
return new PrefsManager(c);
}
public PrefsManager(Context c) {
this.context = c;
}
public static void put(String key, String value) {
if (context == null)
throw new NullPointerException("Context == null! I cant work (black_moon)");
PrefsManager.getPrefs().edit().putString(key, value);
}
public static Object get(String key, String defValue) {
if(context == null)
throw new NullPointerException("Context == null");
return PrefsManager.getPrefs().getString(key, defValue);
}
public static SharedPreferences getPrefs() {
if(context == null)
throw new NullPointerException("Context == null");
return PreferenceManager.getDefaultSharedPreferences(context);
}
}
|
/*
* Robot Explorer
*
* Stefan-Dobrin Cosmin
* 342C4
*/
package explorer.gui;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import explorer.Cell.Direction;
import explorer.Cell.Type;
import explorer.Cell.Visibility;
/**
* The Class LegendCanvas that show the cell legend to the user.
*/
@SuppressWarnings("serial")
public class LegendCanvas extends Canvas {
/**
* Instantiates a new map canvas.
*/
public LegendCanvas() {
setBackground (Color.DARK_GRAY);
setFont(new Font("Dialog", Font.BOLD, 14));
}
/* (non-Javadoc)
* @see java.awt.Canvas#paint(java.awt.Graphics)
*/
public void paint(Graphics g) {
Graphics2D g2;
g2 = (Graphics2D) g;
CellGraphics cell;
//Desenam celula
cell=new CellGraphics(0, 0, Type.Empty);
cell.drawAt(g2, 5, 10);
//Scriem hintul
g2.setColor(Color.WHITE);
g2.drawString("Free", 45, 33);
//Desenam celula
cell=new CellGraphics(0, 0, Type.Goal);
cell.drawAt(g2, 90, 10);
//Scriem hintul
g2.setColor(Color.WHITE);
g2.drawString("Goal", 125, 33);
//Desenam celula
cell=new CellGraphics(0, 0, Type.Clue);
cell.hint=Direction.NE;
cell.drawAt(g2, 180, 10);
//Scriem hintul
g2.setColor(Color.WHITE);
g2.drawString("Hint", 215, 33);
//Desenam celula
cell=new CellGraphics(0, 0, Type.Trap);
cell.probability=0.7f;
cell.drawAt(g2, 260, 10);
//Scriem hintul
g2.setColor(Color.WHITE);
g2.drawString("Trap", 295, 33);
//Desenam celula
cell=new CellGraphics(0, 0, Type.Wall);
cell.drawAt(g2, 340, 10);
//Scriem hintul
g2.setColor(Color.WHITE);
g2.drawString("Wall", 375, 33);
//Desenam celula
cell=new CellGraphics(0, 0, Type.Empty);
cell.enemy=1;
cell.drawAt(g2, 420, 10);
//Scriem hintul
g2.setColor(Color.WHITE);
g2.drawString("Enemy", 455, 33);
//Desenam celula
cell=new CellGraphics(0, 0, Type.Exit);
cell.drawAt(g2, 515, 10);
//Scriem hintul
g2.setColor(Color.WHITE);
g2.drawString("Exit | ", 550, 33);
//Desenam celula
cell=new CellGraphics(0, 0, Type.Empty);
cell.visible=Visibility.Known;
cell.drawAt(g2, 600, 10);
//Scriem hintul
g2.setColor(Color.WHITE);
g2.drawString("Known", 635, 33);
//Desenam celula
cell=new CellGraphics(0, 0, Type.Empty);
cell.visible=Visibility.Hidden;
cell.drawAt(g2, 690, 10);
//Scriem hintul
g2.setColor(Color.WHITE);
g2.drawString("Hidden", 725, 33);
//Desenam celula
cell=new CellGraphics(0, 0, Type.Empty);
cell.visible=Visibility.Visible;
cell.drawAt(g2, 780, 10);
//Scriem hintul
g2.setColor(Color.WHITE);
g2.drawString("Visible", 815, 33);
//Desenam celula
cell=new CellGraphics(0, 0, Type.Empty);
cell.visible=Visibility.Current;
cell.drawAt(g2, 870, 10);
//Scriem hintul
g2.setColor(Color.WHITE);
g2.drawString("Current", 905, 33);
}
}
|
package main;
import java.awt.Color;
public class ColorStyle {
public static final ColorStyle ORIGINAL = new ColorStyle(Color.GREEN, Color.RED, Color.BLUE);
public static final ColorStyle PAPER = new ColorStyle(Color.decode("#91bfdb"), Color.decode("#fc8d59"),
Color.decode("#ffffbf"));
private Color reachable, unreachable, buffer;
private Color[] weights;
public ColorStyle(Color reachable, Color unreachable, Color buffer) {
this(reachable, unreachable, buffer, new Color[] { Color.decode("#1a9641"), Color.decode("#a6d96a"),
Color.decode("#fdae61"), Color.decode("#d7191c") });
}
public ColorStyle(Color reachable, Color unreachable, Color buffer, Color[] weights) {
this.reachable = reachable;
this.unreachable = unreachable;
this.buffer = buffer;
this.weights = weights;
}
public Color reachable() {
return reachable;
}
public Color unreachable() {
return unreachable;
}
public Color buffer() {
return buffer;
}
public Color weight(int i) {
return weights[i];
}
}
|
package com.facemelt.spitter.service;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.facemelt.spitter.dao.SpitterDAO;
import com.facemelt.spitter.domain.Spitter;
import com.facemelt.spitter.domain.Spittle;
@Service("spitterService")
public class SpitterServiceImpl implements SpitterService {
private SpitterDAO spitterDAO;
@Autowired
public SpitterServiceImpl(SpitterDAO spitterDAO) {
super();
this.spitterDAO = spitterDAO;
}
@Override
@Transactional(propagation=Propagation.REQUIRED)
public List<Spittle> getRecentSpittles(int count) {
List<Spittle> recentSpittles = spitterDAO.getRecentSpittles(count);
return recentSpittles;
}
@Override
public void saveSpittle(Spittle spittle) {
spittle.setPostDate(new Date());
}
@Override
public void saveSpitter(Spitter spitter) {
// TODO Auto-generated method stub
}
@Override
public Spitter getSpitter(long id) {
// TODO Auto-generated method stub
return null;
}
@Override
public void startFollowing(SpitterService follower, SpitterService followee) {
// TODO Auto-generated method stub
}
@Override
public List<Spittle> getSpittlesForSpitter(Spitter spitter) {
return null;
}
@Override
public List<Spittle> getSpittlesForSpitter(String username) {
// TODO Auto-generated method stub
return null;
}
@Override
public Spitter getSpitter(String username) {
return spitterDAO.getSpitterByUsername(username);
}
@Override
public Spittle getSpittleById(long id) {
// TODO Auto-generated method stub
return null;
}
@Override
public void deleteSpittle(long id) {
// TODO Auto-generated method stub
}
@Override
public List<Spitter> getAllSpitters() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.btsandjjiao.controller;
import com.btsandjjiao.domain.Employee;
import com.btsandjjiao.domain.Msg;
import com.btsandjjiao.service.EmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
/*
* 删除员工信息
* 批量删除和单个删除合二为一
* 批量删除:1-2-3
* 单个删除:1
* */
@RequestMapping(value = "/emp/{ids}", method = RequestMethod.DELETE)
@ResponseBody
public Msg deleteEmp(@PathVariable("ids")String ids){
if(ids.contains("-")){
List<Integer> del_ids = new ArrayList<>();
String[] str_ids = ids.split("-");
for(String string : str_ids){
del_ids.add(Integer.parseInt(string));
}
employeeService.deleteBatch(del_ids);
}else {
Integer id = Integer.parseInt(ids);
employeeService.deleteEmp(id);
}
return Msg.success();
}
/*
* 更新员工信息
* */
@RequestMapping(value = "/emp/{empId}", method = RequestMethod.PUT)
@ResponseBody
public Msg saveEmp(Employee employee) {
employeeService.updateEmp(employee);
return Msg.success();
}
/*
* 按照员工id查找员工
*
* PathVariable:来自请求地址中的变量
* */
@RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
@ResponseBody
public Msg getEmp(@PathVariable("id") Integer id) {
Employee employee = employeeService.getEmp(id);
return Msg.success().add("emp", employee);
}
/*
* 检查用户名是否可用
* */
@ResponseBody
@RequestMapping("/checkuser")
public Msg checkuser(@RequestParam("empName") String empName) {
//先判断用户名是否是合法的表达式
String regex = "(^[A-Za-z0-9]{3,16}$)|(^[\\u2E80-\\u9FFF]{2,5}$)";
if (!empName.matches(regex)) {
return Msg.fail().add("va_msg", "名字必须是2-5个中文或者3-16位英文数字组合");
}
//数据库用户校验
boolean b = employeeService.checkUser(empName);
if (b) {
return Msg.success();
} else {
return Msg.fail().add("va_msg", "用户名被占用");
}
}
/*
* 员工保存 要进行校验---jquery前端校验,ajax用户名重复校验,重要的数据都要进行后端校验(JSR303)
*
* 要支持JSR303校验,导入依赖hibernate-validator
* */
@RequestMapping(value = "/emp", method = RequestMethod.POST)
@ResponseBody
public Msg saveEmp(@Valid Employee employee, BindingResult result) {
if (result.hasErrors()) {
//校验失败,应该返回失败,还是在模态框中显示错误的信息
Map<String, Object> map = new HashMap<>();
//提取错误信息
List<FieldError> errors = result.getFieldErrors();
for (FieldError fieldError : errors) {
System.out.println("错误的字段名:"+fieldError.getField());
System.out.println("错误的信息:"+fieldError.getDefaultMessage());
map.put(fieldError.getField(), fieldError.getDefaultMessage());
}
return Msg.fail().add("errorFields", map);
} else {
employeeService.saveEmp(employee);
return Msg.success();
}
}
//直接返回的是json数据格式的数据
@RequestMapping("/emps")
@ResponseBody
public Msg getEmpsWithJson(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model){
PageHelper.startPage(pn,5);
List<Employee> employeeList=employeeService.getAll();
PageInfo pageInfo = new PageInfo(employeeList, 5);
//add的是用户携带的数据
return Msg.success().add("pageInfo",pageInfo);
}
/*
* 查询员工数据(分页查询)
*
* */
//
//@RequestMapping("/emps")
public String getEmps(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model){
//引入pageHelper分页插件
//在查询之前,只需要调用页码,以及每页的大小
PageHelper.startPage(pn,5);
//紧跟着这个查询就是分页查询
List<Employee> employeeList=employeeService.getAll();
//使用PageInfo包装查询过的结果,只需要将PageInfo交给页面就行,5代表连续显示的页数
PageInfo pageInfo = new PageInfo(employeeList, 5);
model.addAttribute("pageInfo",pageInfo);
return "list";
}
}
|
package fall2018.csc2017.slidingtiles;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import fall2018.csc2017.R;
import fall2018.csc2017.common.CustomAdapter;
import fall2018.csc2017.common.GestureDetectGridView;
import fall2018.csc2017.common.SaveAndLoadFiles;
import fall2018.csc2017.common.SaveAndLoadGames;
import fall2018.csc2017.gamelauncher.SlidingFragment;
import fall2018.csc2017.scoring.Score;
import fall2018.csc2017.users.User;
/**
* The game activity.
*/
public class SlidingGameActivity extends AppCompatActivity implements Observer, SaveAndLoadFiles,
SaveAndLoadGames {
/**
* The board manager.
*/
private SlidingBoardManager slidingBoardManager;
/**
* The buttons to display.
*/
private List<Button> tileButtons;
/**
* The HashMap of all the fall2018.csc2017.users by name.
*/
private Map<String, User> userAccounts;
/**
* The name of the current user.
*/
private User currentUser;
/**
* The number of tiles per side of the board.
*/
private int difficulty;
/**
* Request Code for gallery activity
*/
public static final int IMAGE_REQUEST_CODE = 100;
/**
* EditText of the number of moves to undo.
*/
private EditText movesToUndo;
/**
* Image uploaded by user
*/
private Bitmap userImage;
/**
* A boolean tracking whether the game has been won.
*/
private boolean gameWon;
/**
* The score of this Sliding tiles game.
*/
private int score;
/**
* The grid for the game activity.
*/
private GestureDetectGridView gridView;
/**
* Width of each tile.
*/
private static int columnWidth;
/**
* Height of each tile.
*/
private static int columnHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slidingtilesgame);
slidingBoardManager =
(SlidingBoardManager) loadGameFromFile(SlidingFragment.TEMP_SAVE_FILENAME);
updateScore();
initializeUsers();
difficulty = slidingBoardManager.getDifficulty();
initializeGrid();
createTileButtons();
addUserButtonListener();
addUndoButtonListener();
}
/**
* A helper method to initialize the user information.
*/
private void initializeUsers() {
userAccounts = loadUserAccounts();
currentUser = userAccounts.get(loadCurrentUsername());
}
/**
* A helper method to initialize the view grid.
*/
private void initializeGrid() {
gridView = findViewById(R.id.grid);
gridView.setNumColumns(difficulty);
gridView.setBoardManager(slidingBoardManager);
slidingBoardManager.getBoard().addObserver(this);
gridView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
gridView.getViewTreeObserver().removeOnGlobalLayoutListener(
this);
int displayWidth = gridView.getMeasuredWidth();
int displayHeight = gridView.getMeasuredHeight();
columnWidth = displayWidth / difficulty;
columnHeight = displayHeight / difficulty;
display();
}
});
}
/**
* Create the buttons for displaying the tiles.
*/
private void createTileButtons() {
SlidingBoard slidingBoard = slidingBoardManager.getBoard();
tileButtons = new ArrayList<>();
for (int row = 0; row < difficulty; row++) {
for (int col = 0; col < difficulty; col++) {
Button tmp = new Button(getApplicationContext());
if (!slidingBoardManager.userTiles) {
tmp.setBackgroundResource(slidingBoard.getTile(row, col).getBackground());
} else {
tmp.setBackground(new BitmapDrawable(getResources(),
slidingBoard.getTile(row, col).getUserImage()));
}
this.tileButtons.add(tmp);
}
}
}
/**
* Update the backgrounds on the buttons to match the tiles.
*/
private void updateTileButtons() {
SlidingBoard slidingBoard = slidingBoardManager.getBoard();
int nextPos = 0;
for (Button b : tileButtons) {
int row = nextPos / difficulty;
int col = nextPos % difficulty;
if (!slidingBoardManager.userTiles) {
b.setBackgroundResource(slidingBoard.getTile(row, col).getBackground());
} else {
if (!gameWon && slidingBoard.getTile(row, col).getId() == difficulty * difficulty) {
b.setBackgroundResource(R.drawable.whitespace);
} else {
b.setBackground(new BitmapDrawable(getResources(),
slidingBoard.getTile(row, col).getUserImage()));
}
}
nextPos++;
}
}
/**
* The listener for the undo button.
*/
private void addUndoButtonListener() {
final Button undoButton = findViewById(R.id.undoButton);
undoButton.setOnClickListener(view -> {
movesToUndo = findViewById(R.id.inputUndo);
try {
int moves = Integer.valueOf(movesToUndo.getText().toString());
slidingBoardManager.undoMove(moves);
} catch (NumberFormatException e) {
slidingBoardManager.undoMove(1);
}
});
}
/**
* The listener for the add user images button.
*/
private void addUserButtonListener() {
final Button userButton = findViewById(R.id.user);
// Try to get a ternary working here
if (!slidingBoardManager.userTiles)
userButton.setText(R.string.user_image_button_unpressed);
else
userButton.setText(R.string.user_image_button_pressed);
userButton.setOnClickListener(view -> {
if (!slidingBoardManager.userTiles) {
pickImageFromGallery();
} else {
userButton.setText(R.string.user_image_button_unpressed);
slidingBoardManager.userTiles = false;
display();
}
});
}
/**
* Start activity to pick image from user gallery.
*/
private void pickImageFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, IMAGE_REQUEST_CODE);
}
/**
* continuation of gallery pick activity
*
* @param requestCode Request code for activity
* @param resultCode Resulting code from Android
* @param i intent of activity
*/
@Override
protected final void onActivityResult(final int requestCode,
final int resultCode, final Intent i) {
super.onActivityResult(requestCode, resultCode, i);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case IMAGE_REQUEST_CODE:
createBitmapFromUri(i.getData());
break;
}
}
if (userImage != null) {
final Button userButton = findViewById(R.id.user);
userButton.setText(R.string.user_image_button_pressed);
SlidingBoard slidingBoard = slidingBoardManager.getBoard();
slidingBoardManager.userTiles = true;
for (int nextPos = 0; nextPos < slidingBoard.numTiles(); nextPos++) {
int row = nextPos / difficulty;
int col = nextPos % difficulty;
slidingBoard.getTile(row, col).createUserTiles(userImage, difficulty);
display();
}
}
}
/**
* Converts uri from gallery to bitmap
*
* @param imageUri uri of selected image.
*/
private void createBitmapFromUri(Uri imageUri) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
Log.e("GalleryAccessActivity", "Image select error", e);
}
if (bitmap != null) {
userImage = Bitmap.createScaledBitmap(
bitmap, 247 * difficulty, 391 * difficulty, true);
}
}
@Override
public void update(Observable o, Object arg) {
updateScore();
int moves = slidingBoardManager.getNumMoves() % 10;
if (moves == 0 && !gameWon) {
currentUser.getSaves().put(SlidingFragment.GAME_TITLE, slidingBoardManager);
saveUserAccounts(userAccounts);
}
if (slidingBoardManager.gameFinished()) {
gameWon = true;
createToast("You Win!");
updateLeaderBoard("Sliding Tiles", new Score(currentUser.getName(),
score));
}
display();
}
/**
* Display the score as you play the game.
*/
private void updateScore() {
score = slidingBoardManager.generateScore();
TextView curScore = findViewById(R.id.curScore);
curScore.setText(String.valueOf(score));
}
/**
* Set up the background image for each button based on the master list
* of positions, and then call the adapter to set the view.
*/
public void display() {
updateTileButtons();
gridView.setAdapter(new CustomAdapter(tileButtons, columnWidth, columnHeight));
}
@Override
public void onBackPressed() {
switchToSlidingTilesActivity();
}
/**
* Switch to the title screen. Only to be called when back pressed.
*/
private void switchToSlidingTilesActivity() {
writeNewValues(currentUser, SlidingFragment.GAME_TITLE, slidingBoardManager);
saveUserAccounts(userAccounts);
if (!gameWon) {
createToast("Saved");
} else {
createToast("Your score is " + slidingBoardManager.generateScore());
}
finish();
}
/**
* @param msg The message to be displayed in the Toast.
*/
private void createToast(String msg) {
Toast.makeText(
this, msg, Toast.LENGTH_LONG).show();
}
/**
* Passes context of the activity to utility interface
*
* @return Context of current activity
*/
public Context getActivity() {
return this;
}
}
|
package eu.senla;
public class Main {
static byte a;
static short b;
static int c;
static long d;
static float e;
static double f;
static char g;
static boolean h;
static Byte aByte;
static Short bShort;
static Integer cInteger;
static Long dLong;
static Float eFloat;
static Double fDouble;
static Character gCharacter;
static Boolean hBoolean;
public static void main(String[] args) {
byte a1 = 33;
short b1 = 26;
int c1 = 456;
long d1 = 567;
float e1=74;
double f1 = 753;
char g1 = 75;
boolean h1 = true;
Byte a2=94;
Short b2 = 45;
Integer c2= 83;
Long d2= 93L;
Float e2 = 843F;
Double f2 = 832D;
Character g2 = 54;
Boolean h2 = false;
Number number = new Number();
number.setA((byte) 12);
byte a = number.getA();
System.out.println(a);
number.setB((short) 2);
short b = number.getB();
System.out.println(b);
number.setC((int)33);
int c = number.getC();
number.setD((long)55);
long d = number.getD();
number.setE((float)124);
float e = number.getE();
number.setF((double)12);
double f = number.getF();
number.setG((char)77);
char g = number.getG();
number.setH((boolean)false);
boolean h = number.getH();
byte x = (byte) a2;
System.out.println(x);
byte x1 = (byte) b1;
System.out.println(x1);
byte x2 = (byte) d1; // (long d1 = 567), result: x2 = 55
System.out.println(x2);
byte x3 = (byte) f1; // double f1 = 753; result: x2 = -15
System.out.println(x3);
byte x4 = (byte) g1;
System.out.println(x4);
//Long x5 = (Long) a2;// cannot cast from Byte to Long
//System.out.println(x5);
Long x5 = (Long) d1;
System.out.println(x5);
//Long x6 = (Long) f2;// cannot cast from Double to Long
//System.out.println(x6);
boolean x7 = (boolean) h2;
System.out.println(x7);
Boolean x8 = (Boolean) h1;
System.out.println(x8);
char x9 = (char) g2;//Character g2 = 54; result: x9 = 6
System.out.println(x9);
String q = "s";
//char x10 = (char) q;// cannot cast from String to char
//Character x10 = (Character) q;// cannot cast from String to Character
Character r = 'w';
char r1 = 'r';
//String q1 = (String) r1;//cannot cast from char to String
}
}
|
package com.example.a.projectcompanyhdexpertiser.APIConnection;
public class APIConnection {
public static String LINK="http://192.168.1.53:8181/api/8.0/system/";
public static String HOST="http://192.168.1.53:8181/";
public static String PATH="api/8.0/system/";
public static String getHOST() {
return HOST;
}
public static void setHOST(String HOST) {
APIConnection.HOST = HOST;
}
public static String getPATH() {
return PATH;
}
public static void setPATH(String PATH) {
APIConnection.PATH = PATH;
}
}
|
package hrishi.gad.repository;
import hrishi.gad.entity.Alerts;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface AlertsRepository extends CrudRepository<Alerts, String> {
List<Alerts> findByVin(String vin);
}
|
package com.website.views.pages;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.mindrot.jbcrypt.BCrypt;
import com.website.models.entities.Author;
import com.website.persistence.AuthorService;
import com.website.tools.navigation.Redirector;
import com.website.tools.navigation.SessionManager;
import com.website.views.WebPages;
/**
* The registration web page view.</br>
* This {@link Named} class is bound with the same named xhtml file.
*
* @author Jérémy Pansier
*/
@Named
@RequestScoped
public class Registration {
/** The service managing the author persistence. */
@Inject
private AuthorService authorService;
/** The web page. */
public static final WebPages WEB_PAGE = WebPages.REGISTRATION;
/** The author name used to register. */
private String authorName;
/** The password. */
private String password;
/** The confirmation password. */
private String confirmationPassword;
/**
* @return the web page
*/
public WebPages getWebPage() {
return WEB_PAGE;
}
/**
* Gets the author name used to register.
*
* @return the author name used to register
*/
public String getAuthorName() {
return authorName;
}
/**
* Sets the author name used to register.
*
* @param authorName the new author name used to register
*/
public void setAuthorName(final String authorName) {
this.authorName = authorName;
}
/**
* Gets the password.
*
* @return the password
*/
public String getPassword() {
return password;
}
/**
* Sets the password.
*
* @param password the new password
*/
public void setPassword(final String password) {
this.password = password;
}
/**
* Gets the confirmation password.
*
* @return the confirmation password
*/
public String getConfirmationPassword() {
return confirmationPassword;
}
/**
* Sets the confirmation password.
*
* @param confirmationPassword the new confirmation password
*/
public void setConfirmationPassword(final String confirmationPassword) {
this.confirmationPassword = confirmationPassword;
}
/**
* Registers the new author with the name and password he specified.
*/
public void signin() {
SessionManager.trackUser(authorName);
if (0 != password.compareTo(confirmationPassword)) {
Redirector.redirect(WEB_PAGE.createJsfUrl(), true, "Les mots de passes ne sont pas identiques");
return;
}
if (0 == "".compareTo(authorName) || authorService.isAuthor(authorName)) {
Redirector.redirect(WEB_PAGE.createJsfUrl(), true, "Ce nom d'utilisateur n'est pas valide");
return;
}
final String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt(12));
final Author author = new Author();
author.setname(authorName);
author.setPassword(hashedPassword);
authorService.persistAuthor(author);
Redirector.redirect(WebPages.PROFILE_EDITION.createJsfUrl(), false, "Inscription réussie");
}
}
|
package com.joy.http.volley.toolbox;
import android.util.Log;
import com.joy.http.Progress;
import com.joy.http.volley.Response;
import com.joy.http.volley.Result;
import com.joy.http.volley.ServerError;
import com.joy.http.volley.VolleyLog;
import java.io.File;
import java.io.IOException;
/**
* Created by Daisw on 2017/6/6.
*/
public class ByteArrayRequest extends ByteRequest<byte[]> {
public ByteArrayRequest(Method method, String url, boolean isProgress) {
super(method, url, isProgress);
}
public ByteArrayRequest(String url, boolean isProgress) {
this(Method.GET, url, isProgress);
}
@Override
public File getStorageFile() {
return null;
}
@Override
protected Result<Progress<byte[]>> parseNetworkResponse(Response response) {
if (VolleyLog.DEBUG) {
Log.i(VolleyLog.TAG, "ByteArrayRequest ## contentLength: " + response.contentLength);
}
byte[] dataByteArray;
long startTime = System.currentTimeMillis();
try {
dataByteArray = toByteArray(response);
} catch (IOException e) {
e.printStackTrace();
return Result.error(e);
} catch (ServerError e) {
e.printStackTrace();
return Result.error(e);
}
if (VolleyLog.DEBUG) {
Log.i(VolleyLog.TAG, "ByteArrayRequest ## spent time: " + (System.currentTimeMillis() - startTime) + "ms");
}
if (dataByteArray == null) {
return Result.error(new NullPointerException("the byte array of image data is null."));
}
if (VolleyLog.DEBUG) {
Log.i(VolleyLog.TAG, "ByteArrayRequest ## size: " + dataByteArray.length);
}
return Result.success(new Progress<>(dataByteArray));
}
}
|
package hackathon.viasat.marksdankburgers;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import static android.Manifest.permission.READ_CONTACTS;
import android.content.Intent;
import android.view.View.OnTouchListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, View.OnTouchListener{
//firebase authenticator
private FirebaseAuth authenticator;
private FirebaseAuth.AuthStateListener authListener;
//text entry fields
private EditText passwordField;
private EditText emailField;
private TextView registerLink;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);//must be called
setContentView(R.layout.activity_login);
//views
emailField = (AutoCompleteTextView) findViewById(R.id.email);
passwordField = (EditText) findViewById(R.id.password);
registerLink = (TextView) findViewById(R.id.registser_link);
registerLink.setOnTouchListener(this);
//login btn
findViewById(R.id.sign_in_button).setOnClickListener(this);
//set up authentication state listener
authListener = new FirebaseAuth.AuthStateListener(){
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth){
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
//user is signed in
//Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
//launchAccount();
}
else{
//user is sigend out
//Log.d(TAG, "onAuthStateChanged:signed_out");
}
//updateUI(user);
}
};
//end set up auth state listener
authenticator = FirebaseAuth.getInstance();
}
@Override
public void onStart(){
super.onStart();
authenticator.addAuthStateListener(authListener);
}
@Override
public void onStop(){
super.onStop();
//clean up listener
if(authListener != null){
authenticator.removeAuthStateListener(authListener);
}
}
private void signIn(String email, String password){
//start signin
authenticator.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(LoginActivity.this, "Autnetication failed", Toast.LENGTH_SHORT).show();
}
}
});
}
//open up the registration form
private void goToRegisterActivity(){
Intent intent = new Intent(this, RegistrationActivity.class);
startActivity(intent);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.sign_in_button:
signIn(emailField.getText().toString(), passwordField.getText().toString());
break;
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(v.getId()){
case R.id.registser_link:
goToRegisterActivity();
break;
}
return false;
}
}
|
package org.codeshifts.spring.db;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* Created by werner.diwischek on 12.05.17.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( locations= {"/spring/db/hsql.xml"})
public class HSQLDbConfigurationXmlTest {
@Autowired
DataSource dataSource;
@Autowired
DataSourceTransactionManager transactionManager;
@Test
public void createSimpleOperator() throws Exception {
Assert.assertNotNull(dataSource);
Assert.assertNotNull(transactionManager);
Connection connection = dataSource.getConnection();
Assert.assertNotNull(transactionManager);
String query = "select * from person";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
stmt.close();
connection.close();
Assert.assertTrue(connection.isClosed());
}
}
|
package com.xiaodao.core.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
/**
* Entity基类
*
* @author ruoyi
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 统计字段
*/
@ApiModelProperty("页数")
private int pageIndex;
/**
* 统计字段
*/
@ApiModelProperty("每页数量")
private int pageSie;
/**
* 统计字段
*/
@ApiModelProperty("统计字段")
private String statisticalProperty;
/**
* 统计方式
*/
@ApiModelProperty("统计方式(count()、max()、avg()、min()、max()、sum())")
private String statisticalMethod;
/**
* 搜索值
*/
@ApiModelProperty("搜索值")
private String searchValue;
/**
* 搜索条件
*/
@ApiModelProperty("搜索条件 eq,ne,gt,ge,lt,le,like,notLike,in,notIn,isNull,isNotNull")
private String searchCondition;
/**
* 排序字段
*/
@ApiModelProperty("排序字段")
private String orderBy = "create_time";
/**
* 是否升序
*/
@ApiModelProperty("是否升序(0:升序,1:降序)")
private int isAsc;
/**
* 创建者
*/
@ApiModelProperty("创建者")
private Long createBy;
/**
* 创建时间
*/
@ApiModelProperty("创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 更新者
*/
@ApiModelProperty("更新者")
private Long updateBy;
/**
* 更新时间
*/
@ApiModelProperty("更新时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/**
* 备注
*/
@ApiModelProperty("备注")
private String remark;
@ApiModelProperty("搜索开始时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date beginTime;
@ApiModelProperty("搜获结束时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endTime;
}
|
package com.tencent.mm.g.a;
import com.tencent.mm.sdk.b.b;
public final class pe extends b {
public a caa;
public b cab;
public pe() {
this((byte) 0);
}
private pe(byte b) {
this.caa = new a();
this.cab = new b();
this.sFm = false;
this.bJX = null;
}
}
|
package com.jp.photo.biz;
import java.util.List;
import com.jp.photo.po.AlbumPo;
public interface AlbumBiz {
public int addAlbumPo(AlbumPo po);
public int deleteAlbumPoById(AlbumPo po);
public List<AlbumPo> getAlbumPoList(AlbumPo po);
public int updateAlbumPoById(AlbumPo po);
public AlbumPo getAlbumPoById(AlbumPo po);
}
|
package fun.witt.stream;
import java.util.Random;
import java.util.stream.Stream;
/**
* @author witt
* @fileName StreamPrincipleDemo
* @date 2018/8/19 02:51
* @description 流运行原理
* @history <author> <time> <version> <desc>
*/
public class StreamPrincipleDemo {
public static void main(String[] args) {
Stream<Integer> integerStream = Stream.generate(() -> new Random().nextInt(100))
.limit(100)
.parallel()
.peek(integer -> println(" peek 1 " + integer))
.filter(integer -> {
println(" filter 1 " + integer);
return integer > 0;
})
.sorted((o1, o2) -> {
println(" sort");
return o1.compareTo(o2);
})
.peek(integer -> println(" peek 2 " + integer));
integerStream.count();
}
private static void println(String s) {
System.out.println(Thread.currentThread().getName() + " " + s);
}
}
|
package com.pangpang6.books.pattern.iteratormode;
/**
* 迭代器模式
* 封装遍历,迭代器接口
* 数据组的返回对象就是迭代器模式
* 提供一种方法顺序访问一个聚合对象中的各个对象
*
* 首先定义个迭代器接口,然后类中添加内部类实现迭代器接口
*
*
*/
public class Test {
}
|
package com.philippe.app.service.kafka;
import com.philippe.app.domain.SparkPocNotification;
import com.philippe.app.domain.User;
import com.philippe.app.service.avro.AvroCodecService;
import com.philippe.app.service.mapper.CustomMapperService;
import example.avro.sparkpoc.Notification;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class PublisherImpl implements Publisher {
// TODO The Orika mapper would not map correctly the String id from app.domain.User to the UUID id of example.avro.User avroUser
// TODO So we went for a CustomMapperService.
// @Qualifier("beanMapper")
// @Autowired
// private MapperFacade mapperFacade;
@Autowired
private CustomMapperService customMapperService;
@Autowired
private AvroCodecService<example.avro.User> avroCodecServiceForUsers;
@Autowired
private AvroCodecService<example.avro.sparkpoc.Notification> avroCodecServiceForNotifications;
@Override
public boolean send(final User user) {
final example.avro.User avroUser = customMapperService.convert(user);
boolean isEncoded = false;
byte[] byteArray = null;
try {
byteArray = avroCodecServiceForUsers.encode(avroUser);
isEncoded = true;
} catch (Exception ex) {
log.debug("exception is {}", ex);
}
log.debug("byteArray is {}", byteArray);
// TODO Publish the byteArray to Kafka
return isEncoded;
}
@Override
public boolean send(SparkPocNotification sparkPocNotification) {
final Notification notification = customMapperService.convert(sparkPocNotification);
boolean isEncoded = false;
byte[] byteArray = null;
try {
byteArray = avroCodecServiceForNotifications.encode(notification);
isEncoded = true;
} catch (Exception ex) {
log.debug("exception is {}", ex);
}
log.debug("byteArray is {}", byteArray);
// TODO Publish the byteArray to Kafka. Choose between:
// TODO https://www.baeldung.com/spring-cloud-stream-kafka-avro-confluent
// TODO https://www.baeldung.com/spring-kafka
// TODO https://codenotfound.com/spring-kafka-apache-avro-serializer-deserializer-example.html
return isEncoded;
}
}
|
package day21multidimensionalarray;
import java.util.Arrays;
public class MultiDimensionalArrray02 {
public static void main(String[] args) {
// Multi Dimensional Array olusturup deger atama
int arr[][] = { {1,2}, {3}, {4,5,6} };
System.out.println(Arrays.deepToString(arr));
System.out.println(arr[0][1] + arr[1][0] + arr[2][2]);
//arr arrayndeki tum elelmanlarin toplamin veren prog yaziniz.
// int sum =0;
// for(int i=arr[0][0]; i<=arr[arr.length-1][arr.length-1]; i++) {
// sum = sum + i;
// }
// System.out.println(sum);
int sum = 0;
for(int i=0; i<arr.length; i++) {
for(int j=0; j<arr[i].length; j++) {
sum = sum +arr[i][j];
}
}
System.out.println("Tum elemanlarin tooplami: " + sum);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package co.tweetbuy.servlet;
import co.tweetbuy.bean.CardBean;
import co.tweetbuy.bean.ErrorBean;
import co.tweetbuy.bean.UserBean;
import co.tweetbuy.db.DBUtil;
import co.tweetbuy.util.AppUtil;
import co.tweetbuy.util.Constants;
import co.tweetbuy.util.Errors;
import co.tweetbuy.util.LogIt;
import co.tweetbuy.util.Util;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author emrah
*/
@WebServlet(name = "CardUpdateAmount", urlPatterns = {"/CardUpdateAmount"})
public class CardUpdateAmount extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
UserBean sessionUser = (UserBean) request.getSession().getAttribute(Constants.AUTHENTICATION_SESSION_USER_VARIABLE);
String cardJson = request.getParameter("card");
CardBean cb = AppUtil.jsonToBean(CardBean.class, cardJson);
cb.setUserId(sessionUser.getId());
if (Util.checkPermission(Util.getPermission(sessionUser, cb), Constants.PERMISSION_CARD_AMOUNT_CHANGE)) {
int cardId = DBUtil.updateCard(cb);
CardBean resultCb = new CardBean();
resultCb.setId(cardId);
out.println(AppUtil.beanToJson(resultCb));
} else {
ErrorBean error = new ErrorBean();
error.setErrorCode(Errors.ERROR_PERMISSION_CARD_AMOUNT_CHANGE);
out.println(AppUtil.beanToJson(error));
LogIt.logger.error(CardUpdateDraft.class + ">" + Thread.currentThread().getStackTrace()[1].getMethodName() + "> Permission Error:" + Errors.ERROR_PERMISSION_CARD_AMOUNT_CHANGE);
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.example.libroapp.ui;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.example.libroapp.R;
import com.example.libroapp.librosColecciones;
import com.example.libroapp.resultadosBusqueda;
/**
* A simple {@link Fragment} subclass.
* Use the {@link Busqueda#newInstance} factory method to
* create an instance of this fragment.
*/
public class Busqueda extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public Busqueda() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Busqueda.
*/
// TODO: Rename and change types and number of parameters
public static Busqueda newInstance(String param1, String param2) {
Busqueda fragment = new Busqueda();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_busqueda, container, false);
final EditText busqueda = (EditText) view.findViewById(R.id.busqueda_editText);
final EditText filtro = (EditText) view.findViewById(R.id.filtro_editText);
Button buscar=(Button) view.findViewById(R.id.buscar_button);
buscar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
System.out.println(busqueda.getText());
FragmentManager manager = getFragmentManager();
resultadosBusqueda nuevo=new resultadosBusqueda(busqueda.getText().toString(),filtro.getText().toString());
manager.beginTransaction().replace(R.id.nav_host_fragment, nuevo).commit();
}
});
// Inflate the layout for this fragment
return view;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cz.mutabene.controller.admin;
import cz.mutabene.model.entity.FileEntity;
import cz.mutabene.model.form.admin.FileAddForm;
import cz.mutabene.model.form.admin.FileEditForm;
import cz.mutabene.model.form.admin.FileShowForm;
import cz.mutabene.service.info.InfoMessages;
import cz.mutabene.service.manager.FileManager;
import cz.mutabene.service.pager.Pager;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
*
* @author novakst6
*/
@Controller
@RequestMapping(value={"admin/file"})
@Secured(value={"ROLE_ADMIN"})
public class FileControllerAdmin {
private InfoMessages infoMessages;
private Pager pager;
private FileManager fileManager;
@RequestMapping(value={"show.htm"},method={RequestMethod.GET})
public String showGET(
ModelMap m,
@ModelAttribute(value="showFormModel")
FileShowForm formModel,
@RequestParam(value="page",required=false)
Integer page
) throws Exception
{
if(page == null){page = new Integer(1);}
try {
pager.setMax(fileManager.getCount());
pager.setPage(page);
m.addAttribute("files", fileManager.findPage(pager.getResult()[0], pager.getResult()[1]));
} catch (Exception e) {
infoMessages.setErrorMessage("ERROR "+e.getMessage());
return "redirect:/admin/index.htm";
}
return "admin/file/show";
}
@RequestMapping(value={"show.htm"},method={RequestMethod.POST})
public String showPOST(
@ModelAttribute("showFormModel")
FileShowForm formModel,
BindingResult errors,
ModelMap m
) throws Exception
{
try {
List<Long> ids = formModel.getIds();
List<FileEntity> files = fileManager.findByListId(ids);
String message = "";
String error = "";
for(FileEntity f: files)
{
if(fileManager.delete(f)){
message += f.getName()+" ";
} else {
error += f.getName();
}
}
if(!message.equals("")){
infoMessages.setInfoMessage("Soubory "+message+" byly smazány.");
}
if(!error.equals("")){
infoMessages.setWarnMessage("Soubory "+error+" nebyly smazány, protože jsou na nich závislé jiné objekty.");
}
} catch (Exception e) {
infoMessages.setErrorMessage("ERROR "+e.getMessage());
}
return "redirect:show.htm";
}
@RequestMapping(value={"add.htm"},method={RequestMethod.GET})
public String addGET(
@ModelAttribute(value="addFormModel")
FileAddForm formModel,
ModelMap m
) throws Exception
{
return "admin/file/add";
}
@RequestMapping(value={"add.htm"},method={RequestMethod.POST})
public String addPOST(
@ModelAttribute(value="addFormModel")
@Valid FileAddForm formModel,
BindingResult errors,
ModelMap m
) throws Exception
{
try {
if(!errors.hasErrors())
{
FileEntity file = new FileEntity();
file.setName(formModel.getFile().getOriginalFilename());
file.setContentType(formModel.getFile().getContentType());
file.setFileSize(formModel.getFile().getSize());
file.setStream(formModel.getFile().getBytes());
file.setDescription(formModel.getDescription());
fileManager.add(file);
infoMessages.setInfoMessage("Soubor "+file.getName()+" byl úspěšně uložen.");
return "redirect:show.htm";
} else {
return "admin/file/add";
}
} catch (Exception e) {
infoMessages.setErrorMessage("ERROR "+e.getMessage());
return "redirect:show.htm";
}
}
@RequestMapping(value={"edit.htm"},method= RequestMethod.GET)
public String editGET(
@RequestParam(value="id",required=true)
Long id,
@ModelAttribute(value="editFormModel")
FileEditForm formModel,
ModelMap m
) throws Exception
{
try {
if(id == null)
{
infoMessages.setWarnMessage("Parametr id musí být zadaný.");
return "redirect:show.htm";
}
FileEntity file = fileManager.findById(id);
if(file == null)
{
infoMessages.setWarnMessage("Objekt se zadaným id se nepodařilo najít.");
return "redirect:show.htm";
}
formModel.setId(id);
formModel.setDescription(file.getDescription());
String content = file.getContentType();
if(content.contains("image"))
{
formModel.setImage(Boolean.TRUE);
} else {
formModel.setImage(Boolean.FALSE);
}
} catch (Exception e) {
infoMessages.setErrorMessage("ERROR "+e.getMessage());
}
return "admin/file/edit";
}
@RequestMapping(value={"edit.htm"},method={RequestMethod.POST})
public String editPOST(
@ModelAttribute(value="editFormModel")
@Valid FileEditForm formModel,
BindingResult errors,
ModelMap m
) throws Exception
{
try {
if(!errors.hasErrors()){
FileEntity file = fileManager.findById(formModel.getId());
if(file == null)
{
infoMessages.setWarnMessage("Editovaný objekt se nepodařilo najít.");
return "redirect:show.htm";
}
if(!formModel.getKeepFile()){
file.setName(formModel.getFile().getOriginalFilename());
file.setContentType(formModel.getFile().getContentType());
file.setFileSize(formModel.getFile().getSize());
file.setStream(formModel.getFile().getBytes());
}
file.setDescription(formModel.getDescription());
fileManager.edit(file);
infoMessages.setInfoMessage("Záznamy byly úspěšně uloženy.");
return "redirect:show.htm";
} else {
FileEntity file = fileManager.findById(formModel.getId());
if(file == null)
{
infoMessages.setWarnMessage("Editovaný objekt se nepodařilo najít.");
return "redirect:show.htm";
}
String content = file.getContentType();
if(content.contains("image"))
{
formModel.setImage(Boolean.TRUE);
} else {
formModel.setImage(Boolean.FALSE);
}
return "admin/file/edit";
}
} catch (Exception e) {
infoMessages.setErrorMessage("ERROR "+e.getMessage());
return "redirect:show.htm";
}
}
@RequestMapping(value={"delete.htm"},method={RequestMethod.GET})
public String delete(
@RequestParam(value="id",required=true)
Long id
) throws Exception
{
try {
if(id == null)
{
infoMessages.setWarnMessage("Parametr id je povinný.");
return "redirect:show.htm";
}
FileEntity file = fileManager.findById(id);
if(file == null)
{
infoMessages.setWarnMessage("Objekt se zadaným id se nepodařilo nelézt.");
return "redirect:show.htm";
}
if(fileManager.delete(file))
{
infoMessages.setInfoMessage("Objekt byl smazán.");
} else {
infoMessages.setWarnMessage("Objekt se nepodařilo smazat, protože jsou na něm závislé jiné objekty.");
}
} catch (Exception e) {
infoMessages.setErrorMessage("ERROR "+e.getMessage());
return "redirect:show.htm";
}
return "redirect:show.htm";
}
public @Autowired void setFileManager(FileManager fileManager) {
this.fileManager = fileManager;
}
public @Autowired void setInfoMessages(InfoMessages infoMessages) {
this.infoMessages = infoMessages;
}
public @Autowired void setPager(Pager pager) {
this.pager = pager;
}
}
|
package com.ibeiliao.account.test.provider;
import com.ibeiliao.pay.pub.api.provider.UploadProvider;
import com.ibeiliao.pay.account.impl.utils.QiniuUtils;
import com.ibeiliao.pay.common.utils.JsonUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by jingyesi on 16/7/26.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring-context.xml")
public class UploadPorviderTest {
@Autowired
UploadProvider uploadProvider;
@Test
public void getSpaceInfoTest(){
System.out.println(JsonUtil.toJSONString(uploadProvider.getSpaceInfo()));
System.out.println(QiniuUtils.privateDownloadUrl("http://paycert.ibeiliao.com//test/20160726/1.jpg"));
}
}
|
package com.hedong.hedongwx.web.controller.webpc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.hedong.hedongwx.config.CommonConfig;
import com.hedong.hedongwx.entity.Area;
import com.hedong.hedongwx.entity.Equipment;
import com.hedong.hedongwx.entity.TemplateParent;
import com.hedong.hedongwx.entity.TemplateSon;
import com.hedong.hedongwx.entity.User;
import com.hedong.hedongwx.service.AreaService;
import com.hedong.hedongwx.service.BasicsService;
import com.hedong.hedongwx.service.EquipmentService;
import com.hedong.hedongwx.service.TemplateService;
import com.hedong.hedongwx.utils.CommUtil;
/**
* @Description: 小区信息控制类
* @author origin 创建时间: 2019年11月7日 上午11:29:22
*/
@Controller
@RequestMapping(value = "/areaData")
public class AreaDataController {
@Autowired
private AreaService areaService;
@Autowired
private TemplateService templateService;
@Autowired
private EquipmentService equipmentService;
@Autowired
private BasicsService basicsService;
@Autowired
private HttpServletRequest request;
/**
* separate
* @Description:小区管理信息
* @author: origin
*/
@RequestMapping(value="/areaManageData")
@ResponseBody
public Object areaManageData(HttpServletRequest request, HttpServletResponse response) {
Object result = null;
if(CommonConfig.isExistSessionUser(request)){
result = CommUtil.responseBuild(901, "session缓存失效", "");
}else{
result = areaService.areaManageData(request);
}
return JSON.toJSON(result);
}
/**
* @Description:
* @param request
* @param response
* @author: origin 2020年5月15日上午11:11:53
*/
@RequestMapping(value="/areaDetails")
@ResponseBody
public Object areaDetails(HttpServletRequest request, HttpServletResponse response) {
if(CommonConfig.isExistSessionUser(request)){
return CommUtil.responseBuild(901, "session缓存失效", "");
}else{
Map<String, Object> datamap = new HashMap<String, Object>();
try {
Map<String, Object> maparam = CommUtil.getRequestParam(request);
if(maparam.isEmpty()){
return CommUtil.responseBuildInfo(102, "参数传递不正确或为空", datamap);
}
Integer aid = CommUtil.toInteger(maparam.get("aid"));
if(aid.equals(0)){
return CommUtil.responseBuildInfo(102, "请指定某个小区", datamap);
}
//根据小区id查询单个小区相关信息
Map<String, Object> resultarea = areaService.inquireSingleAreaInfo(aid);
Integer merid = CommUtil.toInteger(resultarea.get("merid"));
Integer tempcardid = CommUtil.toInteger(resultarea.get("tempid2"));
Integer tempwallid = CommUtil.toInteger(resultarea.get("tempid"));
Map<String, Object> DirectTempCard = basicsService.inquireDirectTempData(tempcardid, merid, null, "在线卡");
Integer nowcartempid = CommUtil.toInteger(DirectTempCard.get("id"));
List<TemplateSon> tempcardson = templateService.getSonTemplateLists(nowcartempid);
tempcardson = tempcardson == null ? new ArrayList<>() : tempcardson;
DirectTempCard.put("gather", tempcardson);
Map<String, Object> DirectTempWall = basicsService.inquireDirectTempData(tempwallid, merid, null, "钱包");
Integer nowwaltempid = CommUtil.toInteger(DirectTempWall.get("id"));
List<TemplateSon> tempwallson = templateService.getSonTemplateLists(nowwaltempid);
tempwallson = tempwallson == null ? new ArrayList<>() : tempwallson;
DirectTempWall.put("gather", tempwallson);
Map<String, Object> areaonline = areaService.inquireAreaOnlineCard(aid);
Integer devicenum = areaService.inquireAreaDevicenum(aid);
Map<String, Object> areauser = areaService.inquireAreaUser(aid);
Integer onlinenum = CommUtil.toInteger(areaonline.get("count"));
Double ctopupbalance = CommUtil.toDouble(areaonline.get("topupbalance"));
Double csendmoney = CommUtil.toDouble(areaonline.get("sendmoney"));
Integer areausernum = CommUtil.toInteger(areauser.get("count"));
Double utopupbalance = CommUtil.toDouble(areauser.get("topupbalance"));
Double usendmoney = CommUtil.toDouble(areauser.get("sendmoney"));
datamap.put("ctopupbalance", ctopupbalance);
datamap.put("csendmoney", csendmoney);
datamap.put("utopupbalance", utopupbalance);
datamap.put("usendmoney", usendmoney);
resultarea.put("onlinenum", onlinenum);
resultarea.put("devicenum", devicenum);
resultarea.put("areausernum", areausernum);
List<Map<String, Object>> devicenumlist = equipmentService.inquireAreaDeaviceInfo(aid);
List<Map<String, Object>> touarealist = areaService.inquirePartnerInfo(aid, 2);
datamap.put("resultarea", resultarea);
datamap.put("tempWallet", DirectTempWall);
datamap.put("tempOnCard", DirectTempCard);
datamap.put("partnerInfo", touarealist);
datamap.put("devicenumlist", devicenumlist);
return JSON.toJSON(CommUtil.responseBuildInfo(200, "成功", datamap));
} catch (Exception e) {
e.printStackTrace();
return CommUtil.responseBuildInfo(301, "异常错误", datamap);
}
}
}
@RequestMapping(value="/editAreaInfo")
@ResponseBody
public Object editAreaInfo(Integer aid, String name, String address) {
Map<String, Object> datamap = new HashMap<String, Object>();
if(CommUtil.toInteger(aid).equals(0)){
return CommUtil.responseBuild(102, "参数传递不正确或为空", "");
}
try {
Object resultedit = areaService.editAreaInfo(aid, name, address);
// Map<String, Object> resultedit = (Map<String, Object>) areaService.editAreaInfo(aid, name, address);
return JSON.toJSON(resultedit);
} catch (Exception e) {
e.printStackTrace();
return CommUtil.responseBuildInfo(301, "异常错误", datamap);
}
}
/**
* @Description:修改合伙人分成比
* @author: origin 2020年5月15日上午11:11:53
*/
@RequestMapping(value="/editBindAreaPartner")
@ResponseBody
// public Object editBindAreaPartner(HttpServletRequest request, HttpServletResponse response) {
public Object editBindAreaPartner(Integer id, Integer aid, Double percent) {
Map<String, Object> datamap = new HashMap<String, Object>();
if(CommUtil.toInteger(id).equals(0) || percent==null){
return CommUtil.responseBuild(102, "参数传递不正确或为空", "");
}
try {
//修改小区合伙人分成比
Map<String, Object> resultedit = areaService.editBindAreaPartner(id, percent*100);
Integer coden = CommUtil.toInteger(resultedit.get("code"));
if(coden==200){
// AreaRelevance partner = (AreaRelevance) resultedit.get("result");
List<Map<String, Object>> partnerInfo = areaService.inquirePartnerInfo(aid, 2);
datamap.put("partnerInfo", partnerInfo);
return JSON.toJSON(CommUtil.responseBuildInfo(200, "成功", datamap));
}else{
return JSON.toJSON(CommUtil.responseBuildInfo(201, "修改失败", datamap));
}
} catch (Exception e) {
e.printStackTrace();
return CommUtil.responseBuildInfo(301, "异常错误", datamap);
}
}
/**
* @Description:删除合伙人
* @author: origin 2020年5月15日上午11:11:53
*/
@RequestMapping(value="/removeAreaPartner")
@ResponseBody
public Object removeAreaPartner(Integer id, Integer aid) {
Map<String, Object> datamap = new HashMap<String, Object>();
if(CommUtil.toInteger(id).equals(0)){
return CommUtil.responseBuild(102, "参数传递不正确或为空", "");
}
try {
Map<String, Object> resultedit = areaService.removeAreaPartner(id);
Integer coden = CommUtil.toInteger(resultedit.get("code"));
if(coden==200){
// AreaRelevance partner = (AreaRelevance) resultedit.get("result");
List<Map<String, Object>> partnerInfo = areaService.inquirePartnerInfo(aid, 2);
datamap.put("partnerInfo", partnerInfo);
return JSON.toJSON(CommUtil.responseBuildInfo(200, "成功", datamap));
}else{
return JSON.toJSON(resultedit);
}
} catch (Exception e) {
e.printStackTrace();
return CommUtil.responseBuildInfo(301, "异常错误", datamap);
}
}
/**
* @Description:绑定合伙人
* @author: origin 2020年5月15日上午11:11:53
*/
@RequestMapping(value="/bindAreaPartner")
@ResponseBody
public Object bindAreaPartner(Integer aid, Integer type, String phone, Double percent) {
Map<String, Object> datamap = new HashMap<String, Object>();
if(CommUtil.toInteger(aid).equals(0) || percent==null){
return CommUtil.responseBuild(102, "参数传递不正确或为空", "");
}
try {
Map<String, Object> resultedit = areaService.bindAreaPartner(aid, type, phone, percent*100);
Integer coden = CommUtil.toInteger(resultedit.get("code"));
if(coden==200){
List<Map<String, Object>> partnerInfo = areaService.inquirePartnerInfo(aid, 2);
datamap.put("partnerInfo", partnerInfo);
return JSON.toJSON(CommUtil.responseBuildInfo(200, "成功", datamap));
}else{
return JSON.toJSON(CommUtil.responseBuildInfo(201, "修改失败", datamap));
}
} catch (Exception e) {
e.printStackTrace();
return CommUtil.responseBuildInfo(301, "异常错误", datamap);
}
}
@RequestMapping(value="/delAreaCode")
@ResponseBody
public Object delAreaCode( Integer aid, Integer merid, String code) {
Map<String, Object> datamap = new HashMap<String, Object>();
if(code==null){
return CommUtil.responseBuild(102, "参数传递不正确或为空", "");
}
try {
User user = (User) request.getSession().getAttribute("admin");
Integer opeid = user == null ? 0 : user.getId();
equipmentService.insertCodeoperatelog(code, 4, 2, merid, opeid, aid + "");
Equipment equipment = new Equipment();
equipment.setCode(code);
equipment.setAid(0);
equipmentService.updateEquipment(equipment);
List<Map<String, Object>> devicenumlist = equipmentService.inquireAreaDeaviceInfo(aid);
datamap.put("devicenum", devicenumlist.size());
datamap.put("devicenumlist", devicenumlist);
return JSON.toJSON(CommUtil.responseBuildInfo(200, "成功", datamap));
} catch (Exception e) {
e.printStackTrace();
return CommUtil.responseBuildInfo(301, "异常错误", datamap);
}
}
@RequestMapping("/addAreaCode")
@ResponseBody
public Map<String, Object> addAreaCode( String code, Integer aid) {
Map<String, Object> datamap = new HashMap<String, Object>();
if(code==null || aid==null){
return CommUtil.responseBuild(102, "参数传递不正确或为空", datamap);
}
Area area = areaService.selectByIdArea(CommUtil.toInteger(aid));
if (area == null) {
return CommUtil.responseBuild(102, "小区不存在", datamap);
}
Integer merid = CommUtil.toInteger(area.getMerid());
Map<String, Object> deviceinfo = CommUtil.isMapEmpty(equipmentService.selectEquipAreaInfo(code));
Integer dealid = CommUtil.toInteger(deviceinfo.get("dealid"));
Integer aidcode = CommUtil.toInteger(deviceinfo.get("aid"));
if(!merid.equals(dealid)){
return CommUtil.responseBuild(102, "小区所属商户与设备所属商户不一致", datamap);
}
if(!aidcode.equals(0)){
return CommUtil.responseBuild(102, "该设备已被绑定到小区中", datamap);
}
User user = (User) request.getSession().getAttribute("user");
Integer opeid = user == null ? 0 : user.getId();
equipmentService.insertCodeoperatelog(code, 4, 1, dealid, opeid, aid + "");
Equipment equipment = new Equipment();
equipment.setCode(code);
equipment.setAid(aid);
equipmentService.updateEquipment(equipment);
deviceinfo.put("aid", aid);
List<Map<String, Object>> devicenumlist = equipmentService.inquireAreaDeaviceInfo(aid);
datamap.put("deviceinfo", deviceinfo);
datamap.put("devicenum", devicenumlist.size());
datamap.put("devicenumlist", devicenumlist);
return CommUtil.responseBuild(200, "成功", datamap);
}
//type: 1 钱包 2在线卡
@SuppressWarnings("unchecked")
@RequestMapping({ "/dealAllTemp" })
@ResponseBody
public Object copyDirectTemp(Integer aid, Integer merid, Integer type) {
Map<String, Object> datamap = new HashMap<String, Object>();
try {
Area area = areaService.selectByIdArea(CommUtil.toInteger(aid));
if (area == null || type == null) {
return CommUtil.responseBuild(102, "小区不存在或未指定对象", datamap);
}
List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
List<Map<String, Object>> listinfo = new ArrayList<Map<String, Object>>();
//3 钱包 4在线卡
Integer tempid = 0;
Integer tempstatus = 3;
if(type.equals(1)){
tempstatus = 3;
tempid = CommUtil.toInteger(area.getTempid());
} else if(type.equals(2)){
tempstatus = 4;
tempid = CommUtil.toInteger(area.getTempid2());
}
List<TemplateParent> tempinfo = templateService.inquireTempByStatus(CommUtil.toInteger(merid), tempstatus);
Map<String, Object> tempchoose = new HashMap<String, Object>();
for(TemplateParent item : tempinfo){
Integer nowtempid = CommUtil.toInteger(item.getId());
Map<String, Object> mapinfo = JSON.parseObject(JSON.toJSONString(item), Map.class);
List<TemplateSon> tempcardson = templateService.getSonTemplateLists(nowtempid);
tempcardson = tempcardson == null ? new ArrayList<>() : tempcardson;
mapinfo.put("gather", tempcardson);
if(CommUtil.toInteger(tempid).equals(nowtempid)){
mapinfo.put("pitchon", 1);
tempchoose = mapinfo;
}else{
listmap.add(mapinfo);
}
}
listinfo.add(tempchoose);
listinfo.addAll(listmap);
datamap.put("listdata", listinfo);
datamap.put("tempchoose", tempchoose);
return CommUtil.responseBuildInfo(200, "成功", datamap);
} catch (Exception e) {
e.printStackTrace();
return CommUtil.responseBuildInfo(301, "异常错误", datamap);
}
}
//type: 1 钱包 2在线卡
@RequestMapping({ "/areaTempChoose"})
@ResponseBody
public Object areaTempChoose(Integer aid, Integer tempid, Integer type) {
Map<String, Object> datamap = new HashMap<String, Object>();
try {
//3 钱包 4在线卡
aid = CommUtil.toInteger(aid);
tempid = CommUtil.toInteger(tempid);
Map<String, Object> result = areaService.areaTempDirectUpdate( aid, tempid, type);
return result;
} catch (Exception e) {
e.printStackTrace();
return CommUtil.responseBuildInfo(301, "异常错误", datamap);
}
}
}
|
package com.zjw.myapplication.utils;
public interface OnFinishListener {
Void onSuccess(Object obj);
Void onError();
}
|
package io.ygg.common;
/*
* Copyright (c) 2015
* Christian Tucker. All rights reserved.
*
* The use of OGServer is free of charge for personal and commercial use. *
*
* THIS SOFTWARE IS PROVIDED 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR 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.
*
* * Policy subject to change.
*/
/**
* This class is used as a helper class to print various message types
* to the console.
*
* @author Christian Tucker
*/
public class Log {
/**
* Prints a message to the console with the <strong>[INFO]:</strong> prefix.
*
* @param info The message
*/
public static void info(String info) {
System.out.println("[INFO]: " + info);
}
/**
* Prints a message to the console with the <strong>[ERROR]:</strong> prefix.
*
* @param error The message
*/
public static void error(String error) {
System.err.println("[ERROR]: " + error);
}
/**
* Prints a message to the console with the <strong>[WARNING]:</strong> prefix.
*
* @param warning The message
*/
public static void warning(String warning) {
System.out.println("[WARNING]: " + warning);
}
/**
* Prints a message to the console with the <strong>[DEBUG]:</strong> prefix.
*
* @param message The message
*/
public static void debug(String message) {
if (Config.debugging) {
System.out.println("[DEBUG]: " + message);
}
}
}
|
package test;
public class Main1 {
public static void main(String[] args) {
String s = " I like you ";
String[] arr = s.split(" ");
System.out.println(arr.length);
for(String val:arr) {
System.out.println(val);
}
}
}
|
package com.github.jvogit.springreact.response;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import lombok.Data;
@Data
public class ApiResponse {
private final HttpStatus status;
private final String message;
public ResponseEntity<Object> toResponseEntity() {
return ResponseEntity.status(status).body(this);
}
}
|
package visitor;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Vector;
public class Arginfo {
public String str,toprint;
public int where,ans,delay,flag,iscall,val,labelprint;
public Vector vec;
public LinkedList<String> list;
public Arginfo(String str){
this.str=str;
this.where=-1;
this.labelprint=1;
this.ans=-1;
this.flag=-1;
this.delay=0;
this.iscall=0;
this.toprint="";
this.val=-1;
this.vec=new Vector();
}
}
//1 CJUMP,HSTORE,HLOAD TEMP
//2 PRINT SIMPLEEXP
|
1.class Student2{
2.int rollno;
3.String name;
4.
5.void insertRecord(int r,String n){//method
6.rollno=r;
7.name=n;
8.}
9.
10.void displayInformation(){System.out.println(rollno+" "+name);}//method
11.
12.public static void main(String args[]){
13.Student2 s1=new Student2();
14.Student2 s2=new Student2();
15.
16.s1.insertRecord(111,"Karan");
17.s2.insertRecord(222,"Aryan");
18.
19.s1.displayInformation();
s2.displayInformation();
|
package pl.edu.ur.polab4.obiekty;
public class Szescian {
private String nazwa;
private String kolor;
private double bok;
public Szescian(String nazwa, String kolor, double bok) {
this.nazwa = nazwa;
this.kolor = kolor;
this.bok = bok;
}
private double pole(double bok) {
return 6.0D * bok * bok;
}
private double objetosc(double bok) {
return bok * bok * bok;
}
public String wyswietl(String nazwa, String kolor, double bok) {
System.out.println("Sześcian: " + nazwa + "\tKolor: " + kolor + "\tKrawędź= " + bok + "\tPole= " + this.pole(bok) + "\tObjętość= " + this.objetosc(bok));
return "";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.