text stringlengths 10 2.72M |
|---|
package org.newdawn.slick.tests;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Game;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.particles.ParticleEmitter;
import org.newdawn.slick.particles.ParticleSystem;
import org.newdawn.slick.particles.effects.FireEmitter;
public class ParticleTest extends BasicGame {
private ParticleSystem system;
private int mode = 2;
public ParticleTest() {
super("Particle Test");
}
public void init(GameContainer container) throws SlickException {
Image image = new Image("testdata/particle.tga", true);
this.system = new ParticleSystem(image);
this.system.addEmitter((ParticleEmitter)new FireEmitter(400, 300, 45.0F));
this.system.addEmitter((ParticleEmitter)new FireEmitter(200, 300, 60.0F));
this.system.addEmitter((ParticleEmitter)new FireEmitter(600, 300, 30.0F));
}
public void render(GameContainer container, Graphics g) {
for (int i = 0; i < 100; i++) {
g.translate(1.0F, 1.0F);
this.system.render();
}
g.resetTransform();
g.drawString("Press space to toggle blending mode", 200.0F, 500.0F);
g.drawString("Particle Count: " + (this.system.getParticleCount() * 100), 200.0F, 520.0F);
}
public void update(GameContainer container, int delta) {
this.system.update(delta);
}
public void keyPressed(int key, char c) {
if (key == 1)
System.exit(0);
if (key == 57) {
this.mode = (1 == this.mode) ? 2 : 1;
this.system.setBlendingMode(this.mode);
}
}
public static void main(String[] argv) {
try {
AppGameContainer container = new AppGameContainer((Game)new ParticleTest());
container.setDisplayMode(800, 600, false);
container.start();
} catch (SlickException e) {
e.printStackTrace();
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\tests\ParticleTest.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package org.arthur.review.service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.arthur.review.model.User;
import org.arthur.review.database.DataConnection;
import org.arthur.review.model.SecurityQuestion;
public class LoginService {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
/** User authentication while logging in
* to the system
* @param username
* @param password
* @return
*/
public boolean authenticate(String username, String password){
Boolean result = true;
try{
con = DataConnection.getConnection();
String query = "SELECT * FROM users where username = ? and passwd = ?";
ps = con.prepareStatement(query);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
if(!rs.next()){
System.out.println("This user does not exist");
result = false;
}
}catch (Exception ex) {
} finally {
DataConnection.closeConnection(ps, con);
}
return result;
}
/** Retrieve all user details
* @param username
* @return
*/
public User getUserInformation(String username) {
User user = null;
try {
con = DataConnection.getConnection();
String query = "SELECT * FROM users where username = ?";
ps = con.prepareStatement(query);
ps.setString(1, username);
rs = ps.executeQuery();
if (rs.next()) {
user = new User();
user.setUser_oid(rs.getInt(1));
user.setUserName(rs.getString(2));
user.setAdmin(rs.getBoolean(4));
user.setUpi(rs.getString(5));
user.setEmail(rs.getString(6));
user.setSecurity_question_id(rs.getInt(7));
user.setSecurity_answer(rs.getString(8));
}
} catch (Exception ex) {
} finally {
DataConnection.closeConnection(ps, con);
}
return user;
}
/** Maps security question's oid to
* the security question's actual description
* @param questionOID
* @return
*/
public String mapQuestionOIDToDescription(int questionOID){
String questionDescription = null;
try{
con = DataConnection.getConnection();
String query = "select ques_description from Security_question "
+ "where ques_oid = ?" ;
ps = con.prepareStatement(query);
ps.setInt(1, questionOID);
rs = ps.executeQuery();
while(rs.next()){
SecurityQuestion sq = new SecurityQuestion();
sq.setQues_description(rs.getString(1));
questionDescription = sq.getQues_description();
}
}catch (Exception ex) {
} finally {
DataConnection.closeConnection(ps, con);
}
return questionDescription;
}
/** Maps a security question to it's
* corresponding oid
* @param quesDescription
* @return
*/
public int mapQuestionDescriptionToOID(String quesDescription) {
int quesOID = 0;
try{
con = DataConnection.getConnection();
String query = "select ques_oid from Security_question "
+ "where ques_description = ?" ;
ps = con.prepareStatement(query);
ps.setString(1, quesDescription);
rs = ps.executeQuery();
while(rs.next()){
SecurityQuestion sq = new SecurityQuestion();
sq.setQues_oid(rs.getInt(1));
quesOID = sq.getQues_oid();
}
}catch (Exception ex) {
} finally {
DataConnection.closeConnection(ps, con);
}
return quesOID;
}
/** Retrieves list of all available security questions
*
* @return
*/
public List<SecurityQuestion> getAllSecurityQuestions(){
List<SecurityQuestion> sqList = new ArrayList<>();
try {
con = DataConnection.getConnection();
String query = "SELECT * FROM Security_Question ORDER BY ques_oid";
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while(rs.next()) {
SecurityQuestion sq = new SecurityQuestion();
sq.setQues_oid(rs.getInt(1));
sq.setQues_description(rs.getString(2));
sqList.add(sq);
}
} catch (Exception ex) {
} finally {
DataConnection.closeConnection(ps, con);
}
return sqList;
}
/** Creates a new user in the system
*
* @param userName
* @param password
* @param upi
* @param email
* @param quesDescription
* @param answer
*/
public void addNewUser(String userName, String password, String upi, String email, int quesOID,
String answer) {
try{
con = DataConnection.getConnection();
String query = "INSERT into users (username, passwd, upi, email, Security_Question, Security_Answer)"
+ "VALUES (?,?,?,?,?,?)";
ps = con.prepareStatement(query);
ps.setString(1, userName);
ps.setString(2, password);
ps.setString(3, upi);
ps.setString(4, email);
ps.setInt(5, quesOID);
ps.setString(6, answer);
rs = ps.executeQuery();
}catch (Exception ex) {
} finally {
DataConnection.closeConnection(ps, con);
}
}
/**Retrieves list of all users
* existing in the system
* @return
*/
public List<User> getAllUsers(){
List<User> usersList = new ArrayList<>();
try {
con = DataConnection.getConnection();
String query = "SELECT username, isAdmin, upi, email FROM Users";
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while(rs.next()) {
User user = new User();
user.setUserName(rs.getString(1));
user.setAdmin(rs.getBoolean(2));
user.setUpi(rs.getString(3));
user.setEmail(rs.getString(4));
usersList.add(user);
}
} catch (Exception ex) {
} finally {
DataConnection.closeConnection(ps, con);
}
return usersList;
}
}
|
package JavaSE.OO.IO;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/*
* java.io.Reader;
* java.io.InputStreamReader;转换流(字节输入流-->字符输入流)
* java.io.FileReader;文件字符输入流
*/
public class FileReaderTest {
public static void main(String[] args) {
//创建文件字符输入流
FileReader fr=null;
try {
fr=new FileReader("E:\\test02.txt");
//开始读
char[] chars=new char[512];//1kb
int temp=0;
while((temp=fr.read(chars))!=-1) {
//将char数组有效部分转换成字符串
System.out.println(new String(chars,0,temp));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(fr!=null) {
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
|
package edu.stuy.starlorn.upgrades;
public class RapidFireUpgrade extends GunUpgrade {
public RapidFireUpgrade() {
super();
_name = "Rapid Fire";
_description = "pew pew -> pew pew pew pew";
}
@Override
public double getCooldown(double cooldown) {
return cooldown/2;
}
@Override
public String getSpriteName() {
return "upgrade/rapidfire";
}
@Override
public Upgrade clone() {
return new RapidFireUpgrade();
}
}
|
package com.piistech.gratecrm.Utils.Adapter;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.stepstone.stepper.Step;
import com.stepstone.stepper.adapter.AbstractFragmentStepAdapter;
import com.stepstone.stepper.viewmodel.StepViewModel;
import java.util.ArrayList;
public class AddBasementStepperAdapter extends AbstractFragmentStepAdapter {
private ArrayList<Fragment> arrayList;
private Context context;
private FragmentManager manager;
public AddBasementStepperAdapter(Context context, ArrayList<Fragment> arrayList, FragmentManager manager) {
super(manager, context);
this.arrayList = arrayList;
this.context = context;
this.manager = manager;
}
@Override
public Step createStep(int position) {
Bundle b = new Bundle();
b.putInt("key", position);
arrayList.get(position).setArguments(b);
return (Step) arrayList.get(position);
}
@Override
public int getCount() {
return arrayList.size();
}
@NonNull
@Override
public StepViewModel getViewModel(@IntRange(from = 0) int position) {
StepViewModel.Builder builder = new StepViewModel.Builder(context)
.setTitle(arrayList.get(position).toString());
switch (position) {
case 0:
builder
.setEndButtonLabel("Next")
.setBackButtonVisible(false);
break;
case 1:
builder
.setEndButtonLabel("Proceed")
.setBackButtonLabel("Back");
break;
case 2:
builder
.setBackButtonLabel("Back")
.setEndButtonLabel("Proceed");
break;
case 3:
builder
.setBackButtonVisible(false)
.setEndButtonLabel("Finish");
break;
default:
throw new IllegalArgumentException("Unsupported position: " + position);
}
return builder.create();
}
} |
package com.youthchina.dto.community.discuss;
import com.youthchina.domain.jinhao.Discuss;
import com.youthchina.dto.RequestDTO;
public class DiscussRequestDTO implements RequestDTO<Discuss> {
private String body;
private boolean is_anonymous;
public DiscussRequestDTO() {}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public boolean isIs_anonymous() {
return is_anonymous;
}
public void setIs_anonymous(boolean is_anonymous) {
this.is_anonymous = is_anonymous;
}
@Override
public Discuss convertToDomain() {
return null;
}
}
|
public class K2SO extends Droid{
public K2SO(){
super("K2SO","Light Side","Rebel",false);
}
} |
package reconstructwithpreandin;
import java.util.HashMap;
import java.util.Map;
public class Solution {
public TreeNode reconstruct(int[] in, int[] pre) {
// Write your solution here.
Map<Integer, Integer> inIndex = indexMap(in);
return helper(pre, inIndex,0,in.length-1,0,in.length-1);
}
private Map<Integer, Integer> indexMap(int [] in){
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < in.length; i++){
map.put(in[i],i);
}
return map;
}
private TreeNode helper(int [] pre, Map<Integer, Integer> inIndex, int inleft, int inright, int preleft, int preright){
if(inleft > inright){
return null;
}
TreeNode root = new TreeNode(pre[preleft]);
int inmid = inIndex.get(root.key);
root.left = helper(pre, inIndex, inleft, inmid-1, preleft+1, preleft - inleft + inmid);
root.right = helper(pre, inIndex, inmid + 1, inright, preright - inright + inmid + 1, preright);
return root;
}
} |
package org.lvzr.fast.test.unitils.service.impl;
import java.util.List;
import org.lvzr.fast.test.unitils.dao.EmployeeDao;
import org.lvzr.fast.test.unitils.model.Employee;
import org.lvzr.fast.test.unitils.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EmployeeServiceImpl implements EmployeeService{
private EmployeeDao employeeDao;
@Autowired
public void setEmployeeDao(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
}
public List<Employee> findAll(){
return employeeDao.findAll();
}
public boolean save(Employee employee){
return employeeDao.save(employee);
}
public boolean delete(String id){
return employeeDao.delete(id);
}
public Employee get(String id){
return employeeDao.get(id);
}
} |
package com.dragon.system.quartz.config;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragon.system.quartz.model.QuartzJobModel;
import com.dragon.system.quartz.service.QuartzJobService;
import com.dragon.system.quartz.utils.QuartzManage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 在容器启动的时候需要初始化一些内容。比如读取配置文件,数据库连接之类的。
* SpringBoot给我们提供了两个接口来帮助我们实现这种需求。
* 这两个接口分别为CommandLineRunner和ApplicationRunner。
* 他们的执行时机为容器启动完成的时候
*/
@Component
public class JobRunner implements ApplicationRunner {
private static Logger log = LoggerFactory.getLogger(JobRunner.class);
@Autowired
private QuartzJobService quartzJobService;
@Autowired
private QuartzManage quartzManage;
@Override
public void run(ApplicationArguments args) throws Exception {
log.debug("--------------------注入定时任务---------------------");
QueryWrapper<QuartzJobModel> query = new QueryWrapper<>();
query.lambda().eq(QuartzJobModel::getIsPause, false);
List<QuartzJobModel> quartzJobs = quartzJobService.list(query);
quartzJobs.forEach(quartzJob -> {
quartzManage.addJob(quartzJob);
});
log.debug("--------------------定时任务注入完成---------------------");
}
}
|
/* */ package datechooser.beans.editor.dimension;
/* */
/* */ import datechooser.beans.locale.LocaleUtils;
/* */ import java.awt.BorderLayout;
/* */ import java.awt.Color;
/* */ import java.awt.Dimension;
/* */ import java.awt.FlowLayout;
/* */ import java.awt.Graphics;
/* */ import java.awt.GridLayout;
/* */ import java.awt.Point;
/* */ import java.awt.Rectangle;
/* */ import java.beans.PropertyEditorSupport;
/* */ import javax.swing.JLabel;
/* */ import javax.swing.JPanel;
/* */ import javax.swing.JSpinner;
/* */ import javax.swing.SpinnerNumberModel;
/* */ import javax.swing.event.ChangeEvent;
/* */ import javax.swing.event.ChangeListener;
/* */
/* */
/* */
/* */ class SimpleDimensionEditorPane
/* */ extends JPanel
/* */ {
/* */ private PropertyEditorSupport editor;
/* */ private Preview preview;
/* */ private JPanel controls;
/* */
/* */ public SimpleDimensionEditorPane(PropertyEditorSupport editor)
/* */ {
/* 31 */ this.editor = editor;
/* */
/* 33 */ final Dimension dim = getValue();
/* 34 */ final SpinnerNumberModel width = new SpinnerNumberModel(dim.width, 10, 20000, 1);
/* 35 */ final SpinnerNumberModel height = new SpinnerNumberModel(dim.height, 10, 20000, 1);
/* */
/* 37 */ this.controls = new JPanel(new GridLayout(1, 2));
/* 38 */ JPanel widthPane = new JPanel(new FlowLayout(1));
/* 39 */ JPanel heightPane = new JPanel(new FlowLayout(1));
/* 40 */ widthPane.add(new JLabel(LocaleUtils.getEditorLocaleString("Width")));
/* 41 */ widthPane.add(new JSpinner(width));
/* 42 */ heightPane.add(new JLabel(LocaleUtils.getEditorLocaleString("Height")));
/* 43 */ heightPane.add(new JSpinner(height));
/* 44 */ this.controls.add(widthPane);
/* 45 */ this.controls.add(heightPane);
/* 46 */ this.controls.revalidate();
/* */
/* 48 */ this.preview = new Preview(null);
/* */
/* 50 */ setLayout(new BorderLayout());
/* 51 */ add(this.preview, "Center");
/* 52 */ add(this.controls, "South");
/* 53 */ revalidate();
/* 54 */ ChangeListener onChange = new ChangeListener() {
/* */ public void stateChanged(ChangeEvent e) {
/* 56 */ dim.setSize(width.getNumber().intValue(), height.getNumber().intValue());
/* */
/* 58 */ SimpleDimensionEditorPane.this.setValue(dim);
/* 59 */ SimpleDimensionEditorPane.this.repaint();
/* */ }
/* */
/* 62 */ };
/* 63 */ width.addChangeListener(onChange);
/* 64 */ height.addChangeListener(onChange);
/* */ }
/* */
/* */ private Dimension getValue() {
/* 68 */ return (Dimension)this.editor.getValue();
/* */ }
/* */
/* */
/* 72 */ private void setValue(Dimension value) { this.editor.setValue(value); }
/* */
/* */ private class Preview extends JPanel {
/* */ private Preview() {}
/* */
/* 77 */ private Point startRec = new Point();
/* */
/* */ protected void paintComponent(Graphics g) {
/* 80 */ Rectangle rec = getBounds();
/* 81 */ Dimension dim = SimpleDimensionEditorPane.this.getValue();
/* 82 */ if (dim.width < rec.width) {
/* 83 */ this.startRec.x = ((rec.width - dim.width) / 2);
/* */ } else {
/* 85 */ this.startRec.x = 0;
/* */ }
/* 87 */ if (dim.height < rec.height) {
/* 88 */ this.startRec.y = ((rec.height - dim.height) / 2);
/* */ } else {
/* 90 */ this.startRec.y = 0;
/* */ }
/* 92 */ g.setColor(Color.BLUE);
/* 93 */ g.fillRect(this.startRec.x, this.startRec.y, dim.width, dim.height);
/* */ }
/* */
/* */ public Dimension getPreferredSize() {
/* 97 */ return new Dimension(100, 200);
/* */ }
/* */ }
/* */ }
/* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/beans/editor/dimension/SimpleDimensionEditorPane.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 0.7.1
*/ |
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.function.Consumer;
//import GUIServerExample.Client; import your game Client Class here
import java.util.ArrayList;
import java.util.Iterator;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextField;
import javafx.scene.control.ChoiceBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class GUIClient extends Application{
int playerNum = -1; //Tracks what player number this client is
GameCommunicator info= new GameCommunicator(1);//Here default client number is 1
Client clientConnection;
String[] categories = new String[]{"Super_heroes","Desserts","Transportation"};
//Variables in GUI client
Stage stage;
//Variables in first scene
BorderPane pane1 = new BorderPane();
Label helloLabel = new Label("Hello,Player.Connect to Server First.");
Label ipLabel = new Label("Please enter an IP Address:");
Label portLabel = new Label("Please enter a port number:");
TextField port = new TextField("5555");
TextField ip = new TextField("127.0.0.1");
Button powerClient = new Button("Enter");
//Variables in second scene
BorderPane pane2 = new BorderPane();
Label attemptLabel = new Label("Attemp #: "); // Give the hint that which attempt that client are current on
Label attNumberLabel = new Label("");// Show the number of attempt that client are current on
Label guesswordLabel= new Label("Let's guess words!!!");
Label pickCategoryLabel = new Label("Pick a category!");
Label choiceCate = new Label(""); // Store the category that player picked.
Label NumhintLabel = new Label("You are player #: "); // Give a message to show player number
Label playerNumberLabel = new Label("");
ChoiceBox<String> cb = new ChoiceBox<String>(FXCollections.observableArrayList("Super_heroes","Desserts","Transportation"));
Button nextButton = new Button("Next");//For Scene 2 Next button;
//Variables in third scene
BorderPane pane3 = new BorderPane();
Label categoryLabel = new Label("Category: ");//Show a hint to Category
Label cateLabel = new Label("");//Show exact category that client picked such like: Transportation
Label wordLabel = new Label("Word:"); //Show hint of Word
ArrayList<Button> letters = new ArrayList<Button>(); // Store the word letters with button ArrayList
Label guessLeftLabel = new Label("Number of guesses left: ");
Label numGuessLeft = new Label("");
Label EnterLetterLabel = new Label("Enter letter guess: ");
TextField guessField = new TextField("");// Input a letter the client want to guess
Button guessButton = new Button("Guess");
//Variables in Four scene
BorderPane pane4= new BorderPane();
Label successLabel = new Label("Congratulation. You guessed correctly word now!");
public static void main(String[] args) {
// TODO Auto-generated method stub
launch(args);
}
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
primaryStage.setTitle("(Client) Starting Word Guess!!!");
this.stage = primaryStage;
powerClient.setOnAction(e-> {primaryStage.setScene(clientTwo());
primaryStage.setTitle("Playing Game...");
clientConnection = new Client(data->{
Platform.runLater(()->{ info = (GameCommunicator) data; });
});
clientConnection.start();
});
//for category choiceBox listen event
cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
public void changed(@SuppressWarnings("rawtypes") ObservableValue observable, Number oldValue, Number newValue) {
// TODO Auto-generated method stub
choiceCate.setText(categories[newValue.intValue()]);
String cate = choiceCate.getText();
int i=-1;
if(cate.equals("Super_heroes")) {
i=0;
}
else if(cate.equals("Desserts")) {
i=1;
}
else if (cate.equals("Transportation")) {
i=2;
}
else {
choiceCate.setText(""); // No category picked
}
// info.setCategory(i);//if you use number for category.
// info,setCategory(cate);//if you use string for category.
cb.setDisable(false);
}
});
//Next button listening to events on scene 2
nextButton.setOnAction(e->{
if(choiceCate.getText() =="") {
return;
}
primaryStage.setScene(clientThree());
}
);
//Guess Button listening to events on scene 3 --the main play scene
guessButton.setOnAction(e->{
String guessletter = guessField.getText(); //Get the guess letter
//If guess letter is a letter a-z or A-Z then find letter in word
//success to find the letter in word
if(isLetter(guessletter)) {
//info.guess = guessletter.charAt(0); // Set the guess letter
//Find the index of the letter client guess at word in specific category,for example index =3 mean the fourth letter
letters.get(info.numGuesses-1).setText(guessletter);
guessField.clear();
--info.numGuesses;
//Check the statue of game, if game guess over 6 times or if the word is filled full and correct,then go to scene 4
primaryStage.setScene(clientFour());
//if the attempt life used up, go scene five
//primaryStage.setScene(clientFive());
}
else {
return;
}
//fail to find the letter in word
});
primaryStage.setScene(clientOne());
primaryStage.show();
}
//This is where the port/IP input scene
public Scene clientOne() {
helloLabel.setStyle("-fx-font-size: 25");
portLabel.setStyle("-fx-font-size: 25");
ipLabel.setStyle("-fx-font-size: 25");
HBox portBox = new HBox(25, portLabel, port);
HBox ipBox = new HBox(25, ipLabel, ip);
HBox enterBox = new HBox(50,powerClient);
helloLabel.setAlignment(Pos.CENTER);
portBox.setAlignment(Pos.CENTER);
ipBox.setAlignment(Pos.CENTER);
enterBox.setAlignment(Pos.CENTER);
powerClient.setStyle("-fx-pref-width: 150px");
powerClient.setAlignment(Pos.CENTER);
VBox setupBox = new VBox(50,helloLabel, ipBox, portBox,enterBox);
pane1.setCenter(setupBox);
Scene scene = new Scene(pane1,600,600);
return scene;
}
public Scene clientTwo() {
attemptLabel.setTextFill(Color.web("white"));
guesswordLabel.setTextFill(Color.web("white"));
pickCategoryLabel.setTextFill(Color.web("white"));
nextButton.setTextFill(Color.web("Black"));
HBox setCatBox = new HBox(20,pickCategoryLabel,cb);
setCatBox.setAlignment(Pos.CENTER);
VBox setup2Box = new VBox(20,attemptLabel,guesswordLabel,setCatBox);
setup2Box.setStyle("-fx-font-size: 25");
setup2Box.setAlignment(Pos.TOP_CENTER);
HBox nextBox = new HBox(200,nextButton);
nextBox.setStyle("-fx-font-size: 25");
nextBox.setAlignment(Pos.BASELINE_CENTER);
HBox setPnumBox = new HBox(20,NumhintLabel,playerNumberLabel);
setPnumBox.setStyle("-fx-font-size: 25");
setPnumBox.setAlignment(Pos.BOTTOM_RIGHT);
VBox setallBox = new VBox(300,setup2Box,nextButton);
setallBox.setAlignment(Pos.CENTER);
setallBox.setStyle("-fx-font-size: 25");
pane2.setCenter(setallBox);
pane2.setBottom(setPnumBox);
pane2.setStyle("-fx-background-image:url(./wordguess.jpg);-fx-background-repeat:no-repeat");
Scene scene = new Scene(pane2,600,600);
scene.setFill(Color.TRANSPARENT);
return scene;
}
public Scene clientThree() {
attemptLabel.setStyle("-fx-font-size: 20");
attemptLabel.setTextFill(Color.web("black"));
attNumberLabel.setStyle("-fx-font-size: 20");
attNumberLabel.setTextFill(Color.web("black"));
categoryLabel.setStyle("-fx-font-size: 20");
categoryLabel.setTextFill(Color.web("black"));
cateLabel.setText(choiceCate.getText());
cateLabel.setStyle("-fx-font-size: 20");
cateLabel.setTextFill(Color.web("black"));
HBox attBox = new HBox(20,attemptLabel,attNumberLabel,categoryLabel,cateLabel);
HBox.setMargin(attemptLabel, new Insets(10,20,20,20));
HBox.setMargin(attNumberLabel, new Insets(10,20,20,20));
HBox.setMargin(categoryLabel, new Insets(10,20,20,20));
HBox.setMargin(cateLabel, new Insets(10,20,20,20));
wordLabel.setStyle("-fx-font-size: 25");
wordLabel.setTextFill(Color.web("black"));
HBox setlettersBox = new HBox();//This Hbox store all letters that need to guess
//change loop length with numletter;
for(int i=0;i< 6;i++) {
letters.add(new Button(""));
letters.get(i).setStyle("-fx-font-size: 30");
letters.get(i).setTextFill(Color.web("black"));
letters.get(i).setStyle("-fx-background-image:url(./underline.png)");
letters.get(i).setVisible(true);
letters.get(i).setDisable(false);
setlettersBox.getChildren().add(letters.get(i));
}//Enf for loop
setlettersBox.setPadding(new Insets(20));
HBox lettersBox = new HBox(20,wordLabel,setlettersBox);
HBox.setMargin(wordLabel,new Insets(20,20,50,50) );
guessLeftLabel.setStyle("-fx-font-size: 25");
guessLeftLabel.setTextFill(Color.web("black"));
numGuessLeft.setStyle("-fx-font-size: 25");
numGuessLeft.setTextFill(Color.web("black"));
HBox setGuessNumBox = new HBox(20,guessLeftLabel,numGuessLeft);
HBox.setMargin(guessLeftLabel, new Insets(30,20,20,50));
EnterLetterLabel.setStyle("-fx-font-size: 25");
EnterLetterLabel.setTextFill(Color.web("black"));
guessField.setStyle("-fx-font-size: 25");
guessButton.setStyle("-fx-font-size: 25");
HBox guessBox = new HBox(10,EnterLetterLabel,guessField,guessButton);
HBox.setMargin(EnterLetterLabel, new Insets(10,20,20,20));
NumhintLabel.setStyle("-fx-font-size: 25");
NumhintLabel.setTextFill(Color.web("black"));
playerNumberLabel.setStyle("-fx-font-size: 25");//Show the player number
playerNumberLabel.setTextFill(Color.web("black"));
HBox setPlayerNumBox = new HBox(20,NumhintLabel,playerNumberLabel);
setPlayerNumBox.setAlignment(Pos.BOTTOM_RIGHT);
VBox setWordBox = new VBox(30,attBox,lettersBox,setGuessNumBox,guessBox);
pane3.setCenter(setWordBox);
pane3.setBottom(setPlayerNumBox);
Scene scene = new Scene(pane3,600,600);
return scene;
}
public Scene clientFour() {
attemptLabel.setStyle("-fx-font-size:25");
attemptLabel.setTextFill(Color.web("black"));
attNumberLabel.setStyle("-fx-font-size:25");
attNumberLabel.setTextFill(Color.web("Black"));
//if(info.attemptCat1>0 || info.attemptCat2>0||info.attemptCat3>0)
HBox setAttemptBox = new HBox(20,attemptLabel,attNumberLabel);
pickCategoryLabel.setStyle("-fx-font-size:25");
pickCategoryLabel.setTextFill(Color.web("Black"));
Scene scene = new Scene(pane4,600,600);
pane4.setTop(setAttemptBox);
return scene;
}
public static boolean isLetter(String str){
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^[a-zA-Z]$");
java.util.regex.Matcher m = pattern.matcher(str);
return m.matches();
}
}
|
/*
* Sonar JavaScript Plugin
* Copyright (C) 2011 Eriks Nukis
* dev@sonar.codehaus.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.javascript.complexity;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.antlr.runtime.tree.CommonTree;
import org.junit.Test;
public class JavaScriptComplexityAnalyzerTest {
public static void printTree(CommonTree t, int indent) {
if (t != null) {
StringBuffer sb = new StringBuffer(indent);
for (int i = 0; i < indent; i++)
sb = sb.append(" ");
for (int i = 0; i < t.getChildCount(); i++) {
System.out.println(sb.toString() + t.getChild(i).toString() + "[line:" + t.getChild(i).getLine() + "] " + t.getChild(i).getType());
printTree((CommonTree) t.getChild(i), indent + 1);
}
}
}
@Test
public void functionNameRecognitionTest() throws JavaScriptPluginException, IOException {
String fileName = "/org/sonar/plugins/javascript/complexity/FunctionNames.js";
JavaScriptComplexityAnalyzer analyzer = new JavaScriptComplexityAnalyzer();
List<JavaScriptFunction> functions = analyzer.analyzeComplexity(JavaScriptComplexityAnalyzerTest.class
.getResourceAsStream(fileName));
//CommonTree tree = analyzer.getJavaScriptAst(JavaScriptComplexityAnalyzerTest.class.getResourceAsStream(fileName));
//printTree(tree, 0);
assertEquals(11, functions.size());
assertEquals("name1", functions.get(0).getName());
assertEquals("name2", functions.get(1).getName());
assertEquals("someMethodSimple", functions.get(2).getName());
assertEquals("someMethodDeep", functions.get(3).getName());
assertEquals("anonymousFunction0", functions.get(4).getName());
assertEquals("name3", functions.get(5).getName());
assertEquals("anonymousFunction1", functions.get(6).getName());
assertEquals("anonymousFunction2", functions.get(7).getName());
assertEquals("anonymousFunction3", functions.get(8).getName());
assertEquals("anonymousFunction4", functions.get(9).getName());
}
@Test
public void complexityTest() throws JavaScriptPluginException {
String fileName = "/org/sonar/plugins/javascript/complexity/Complexity.js";
JavaScriptComplexityAnalyzer analyzer = new JavaScriptComplexityAnalyzer();
//CommonTree tree = analyzer.getJavaScriptAst(JavaScriptComplexityAnalyzerTest.class.getResourceAsStream(fileName));
//printTree(tree, 0);
List<JavaScriptFunction> functions = analyzer.analyzeComplexity(JavaScriptComplexityAnalyzerTest.class
.getResourceAsStream(fileName));
assertEquals("name1", functions.get(0).getName());
assertEquals(3, functions.get(0).getComplexity());
assertEquals("name2", functions.get(1).getName());
assertEquals(5, functions.get(1).getComplexity());
assertEquals("innerFunction", functions.get(2).getName());
assertEquals(3, functions.get(2).getComplexity());
assertEquals("name3", functions.get(3).getName());
assertEquals(2, functions.get(3).getComplexity());
assertEquals("name4", functions.get(4).getName());
assertEquals(12, functions.get(4).getComplexity());
assertEquals("name5", functions.get(5).getName());
assertEquals(2, functions.get(5).getComplexity());
assertEquals("name6", functions.get(6).getName());
assertEquals(6, functions.get(6).getComplexity());
}
}
|
package com.incuube.bot.services.outcome;
import com.incuube.bot.model.common.users.TelegramUser;
import com.incuube.bot.model.common.users.User;
import com.incuube.bot.model.exceptions.BotConfigException;
import com.incuube.bot.model.outcome.OutcomeMessage;
import com.incuube.bot.model.outcome.OutcomeSuggestionMessage;
import com.incuube.bot.model.outcome.OutcomeTextMessage;
import com.incuube.bot.util.JsonConverter;
import com.incuube.bot.util.ParamsExtractor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
@Log4j2
public class OutcomeMessageSender {
private TelegramMessageSender telegramMessageSender;
@Value("${bot.telegram.serviceChat}")
private String serviceChatId;
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private final Pattern placeHolderPattern = Pattern.compile("\\$\\{(.+?)\\}");
@Autowired
public OutcomeMessageSender(TelegramMessageSender telegramMessageSender) {
this.telegramMessageSender = telegramMessageSender;
}
public String sendOutcomeMessage(OutcomeMessage outcomeMessage, User user) {
switch (user.getMessenger()) {
case TELEGRAM:
TelegramUser telegramUser = (TelegramUser) user;
sendTelegramOutcomeMessage(outcomeMessage, telegramUser);
return telegramUser.getId();
default:
throw new BotConfigException("Unsupported Messenger! " + user.getMessenger());
}
}
private void sendTelegramOutcomeMessage(OutcomeMessage outcomeMessage, TelegramUser telegramUser) {
if (outcomeMessage.getParams().get("special_action") != null) {
sendSpecialAction(telegramUser);
}
Optional<OutcomeMessage> message = prepareMessage(outcomeMessage, telegramUser);
if (!message.isPresent()) {
throw new BotConfigException("Params not found!!");
}
outcomeMessage = message.get();
if (outcomeMessage instanceof OutcomeTextMessage) {
telegramMessageSender.sendOutcomeMessage((OutcomeTextMessage) outcomeMessage, telegramUser);
}
if (outcomeMessage instanceof OutcomeSuggestionMessage) {
telegramMessageSender.sendOutcomeMessage((OutcomeSuggestionMessage) outcomeMessage, telegramUser);
}
}
private void sendSpecialAction(TelegramUser telegramUser) {
StringBuilder sb = new StringBuilder("Request:\n");
sb.append("User id (technical) - ").append(telegramUser.getId()).append("\n")
.append("User first name - ").append(telegramUser.getFirst_name()).append("\n");
if (telegramUser.getLast_name() != null) {
sb.append("User last name - ").append(telegramUser.getLast_name()).append("\n");
}
if (telegramUser.getUsername() != null) {
sb.append("Username - ").append(telegramUser.getUsername()).append("\n");
}
sb.append("City - \"").append(telegramUser.getParams().get("city")).append("\"\n");
sb.append("Days - \"").append(telegramUser.getParams().get("days")).append("\"\n");
sb.append("Month - \"").append(telegramUser.getParams().get("month")).append("\"\n");
sb.append("Persons - \"").append(telegramUser.getParams().get("persons")).append("\"\n");
sb.append("Time -\"").append(telegramUser.getLastActionTime().plusHours(2).format(formatter)).append("\"\n");
sb.append("Connection message -\"").append((String) telegramUser.getParams().get("contact_info")).append("\"");
OutcomeTextMessage textMessage = new OutcomeTextMessage();
textMessage.setText(sb.toString());
Optional<OutcomeMessage> outcomeMessage = prepareMessage(textMessage, telegramUser);
if (!outcomeMessage.isPresent()) {
throw new BotConfigException("Params setting for special action is invalid!!");
}
telegramMessageSender.sendOutcomeMessage((OutcomeTextMessage) outcomeMessage.get(), serviceChatId);
}
private Optional<OutcomeMessage> prepareMessage(OutcomeMessage outcomeMessage, User user) {
// log.info("Params sender for message - {}", outcomeMessage);
Optional<String> jsonRepresentation = JsonConverter.convertObject(outcomeMessage);
if (jsonRepresentation.isPresent()) {
String json = jsonRepresentation.get();
Matcher matcher = placeHolderPattern.matcher(json);
while (matcher.find()) {
String paramName = matcher.group(1);
if (paramName != null) {
Optional<String> paramFromMap = ParamsExtractor.getParamFromMap(user.getParams(), paramName);
if (paramFromMap.isPresent()) {
json = json.replace(String.format("${%s}", paramName), paramFromMap.get());
} else {
log.error("Param wasn't found! Param name - '{}'!", paramFromMap);
return Optional.empty();
}
}
}
return JsonConverter.convertJson(json, OutcomeMessage.class);
}
return Optional.of(outcomeMessage);
}
}
|
package com.sinelnikov.competetive.week1;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class AdditionAndSubtraction {
/*
Given two integers x and y, construct an infinite sequence of integers A = {a0,a1,a2,...}
as follows: a0 =0andforeveryi≥1,a2i−1 =a2i−2 +xanda2i =a2i−1 −y.
Given three integers x, y and z, find the index of the first occurrence of z in A
or report that z does not appear in A.
Forexample,ifx=2,y=1andz=3,thenA=(0,2,1,3,2,4,3,...)andtheansweris3(a3 =3 and
this is the first occurrence of 3 in A). If x = 2, y = 0 and z = 3, then A = (0,2,2,4,4,6,6,...)
and the answer is −1 (there is no occurrence of 3 in A).
*/
public static void main(String[] arg) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int x, y, z;
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
int result = -1;
result = exists(x, y, z);
out.println(result);
in.close();
out.close();
}
public static int exists(int x, int y, int z) {
if (z == 0) {
return 0;
}
if (x == y) {
if (x == z) return 1;
else return -1;
}
int aprev = 0;
for (int i = 1;;i++) {
int a;
if (i % 2 == 1) {
a = aprev + x;
if (x < y && a < z) { // x < y means function is increasing
return -1;
}
} else {
a = aprev - y;
if (x > y && a > z) { // x > y means function is decreasing
return -1;
}
}
if (z == a) {
return i;
}
aprev = a;
}
}
} |
package com.lbsp.promotion.core.service.task;
import com.lbsp.promotion.core.service.BaseServiceImpl;
import com.lbsp.promotion.entity.constants.GenericConstants;
import com.lbsp.promotion.entity.model.Task;
import com.lbsp.promotion.entity.query.GenericQueryParam;
import com.lbsp.promotion.entity.query.QueryKey;
import com.lbsp.promotion.util.Security;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
@Service
public class TaskServiceImpl extends BaseServiceImpl<Task> implements
TaskService<Task> {
/**
* 保存任务
*
* @param className
* @param name
* @return
*/
@Transactional
public boolean saveTask(String className,String name){
Date date = new Date();
Task task = new Task();
task.setId(Security.generateUUIDStr());
task.setClass_name(className);
task.setName(name);
task.setCreate_user(GenericConstants.LBSP_ADMINISTRATOR_ID);
task.setUpdate_user(GenericConstants.LBSP_ADMINISTRATOR_ID);
task.setCreate_date(date);
task.setLast_update_date(date);
return this.insert(task) > 0;
}
/**
* 删除任务
*
* @param task
* @return
*/
@Transactional
public boolean deleteTask(Task task){
if(task == null)
return false;
GenericQueryParam param = new GenericQueryParam();
if(StringUtils.isNotBlank(task.getId())){
param.put(new QueryKey("id", QueryKey.Operators.EQ),task.getId());
}else{
if(StringUtils.isNotBlank(task.getName())){
param.put(new QueryKey("name", QueryKey.Operators.EQ),task.getName());
}
if(StringUtils.isNotBlank(task.getClass_name())){
param.put(new QueryKey("class_name", QueryKey.Operators.EQ),task.getClass_name());
}
}
return this.delete(param) > 0;
}
}
|
package tw.org.iii.java;
public class Brad27 {
public static void main(String[] args) {
//int[] a = new int[] {1,2,3,4};
int[] a = {1,2,3,4};
// int[] a;
// a = new int[] {1,2,3,4};
// int[] a;
// a = {1,2,3,4}; => xxx
for ( int i=0; i<a.length; i++) {
System.out.println(a[i]);
}
System.out.println("---");
// for-each
for (int v : a) {
System.out.println(v);
}
}
}
|
package com.kakaopay.payments.api.util;
import com.kakaopay.payments.api.dto.CardInfo;
public class DataConvertor {
/**
* 부가가치세 계산
* @param amount
* @return
*/
public static int calVAT(int amount){
double div = ((double)amount / 11);
int round = (int)Math.round(div);
return round;
}
/**
* 카드정보를 암호화하기 위하여 문자합치기
* @param cardInfo
* @return
*/
public static String concatCardInfo(CardInfo cardInfo) {
return cardInfo.getCardNumber()
+ Constants.CARDINFO_SPLIT
+ cardInfo.getExpirationDate()
+ Constants.CARDINFO_SPLIT
+ cardInfo.getCvc()
+ Constants.CARDINFO_SPLIT;
}
/**
* 카드정보를 복호화하여 객체화 하기
* @param str
* @return
*/
public static CardInfo objectCardInfo(String str) {
int index1 = str.indexOf(Constants.CARDINFO_SPLIT);
int index2 = str.indexOf(Constants.CARDINFO_SPLIT, index1+1);
int index3 = str.indexOf(Constants.CARDINFO_SPLIT, index2+1);
String cardNumber = str.substring(0, index1);
String expDate = str.substring(index1+1, index2);
String cvc = str.substring(index2+1, index3);
CardInfo cardInfo = CardInfo.builder()
.cardNumber(cardNumber)
.expirationDate(expDate)
.cvc(cvc)
.build();
return cardInfo;
}
/**
* string 데이터 명세에 맞게 String 변경
* @param str
* @param length
* @param type
* @return
*/
public static String formatPayStr(String str, int length, int type){
if(str.length() >= length){
return str;
}
char c = ' ';
if(type == Constants.DATA_TYPE_NUM_ZERO){
c = '0';
}
StringBuilder sb = new StringBuilder();
if((type == Constants.DATA_TYPE_NUM_LEFT)
|| (type == Constants.DATA_TYPE_STRING)){
sb.append(str);
}
int size = length - str.length();
while (size > 0) {
sb.append(c);
size--;
}
if((type == Constants.DATA_TYPE_NUM)
|| (type == Constants.DATA_TYPE_NUM_ZERO)){
sb.append(str);
}
return sb.toString();
}
}
|
package com.greenglobal.eoffice.infrastructure.broker;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import com.greenglobal.eoffice.domain.core.events.DomainEvent;
import com.greenglobal.eoffice.infrastructure.configs.IKafkaConstants;
import com.greenglobal.eoffice.infrastructure.event.EventHandler;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.errors.WakeupException;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.Duration;
import java.util.Collections;
public class KafkaEventConsumer implements EventConsumer {
private final KafkaConsumer<String, DomainEvent> consumer;
private final AtomicBoolean closed = new AtomicBoolean();
@Autowired
private EventHandler eventHandler;
public KafkaEventConsumer() {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, IKafkaConstants.KAFKA_BROKERS);
props.put(ConsumerConfig.GROUP_ID_CONFIG, IKafkaConstants.GROUP_ID);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, EventDeserializer.class.getName());
props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, IKafkaConstants.MAX_POLL_RECORDS);
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, IKafkaConstants.OFFSET_RESET_EARLIER);
consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList(IKafkaConstants.TOPIC_CONGVANDI));
}
@Override
public void run() {
try {
while (!closed.get()) {
consume();
}
} catch (WakeupException e) {
// will wakeup for closing
} finally {
consumer.close();
}
}
private void consume() {
ConsumerRecords<String, DomainEvent> records = consumer.poll(Duration.ZERO);
for (ConsumerRecord<String, DomainEvent> record : records) {
eventHandler.onEvent(record.value());
}
consumer.commitSync();
}
public void stop() {
closed.set(true);
consumer.wakeup();
}
} |
package common.instamsg.driver;
public class MessageData {
String topicName;
String payload;
public MessageData(String topicName, String payload) {
super();
this.topicName = topicName;
this.payload = payload;
}
public String getTopicName() {
return topicName;
}
public String getPayload() {
return payload;
}
}
|
/*
* Copyright 2016 Johns Hopkins University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dataconservancy.cos.osf.client.model;
import org.dataconservancy.cos.osf.client.retrofit.OsfService;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Tests mapping between the JSON of a 'logs' document and the Java model for the Log class
*
* @author Elliot Metsger (emetsger@jhu.edu)
*/
public class LogTest extends AbstractMockServerTest {
@Rule
public TestName TEST_NAME = new TestName();
private OsfService osfService;
@Before
public void setUp() throws Exception {
factory.interceptors().add(new RecursiveInterceptor(TEST_NAME, LogTest.class));
osfService = factory.getOsfService(OsfService.class);
}
@Test
public void testLogMapping() throws Exception {
final String registrationId = "eq7a4";
final Registration registration = osfService.registrationById(registrationId).execute().body();
assertNotNull(registration);
assertNotNull(registration.getLogs());
final List<Log> logs = osfService.logs(registration.getLogs()).execute().body();
final String eventId = "57570a06c7950c0045ac803e";
final Log log = logs.stream()
.filter(e -> e.getId().equals(eventId))
.findFirst()
.orElseThrow(
() -> new RuntimeException("Expected log stream to contain log id " + eventId));
// additional assertions
final String expectedAction = "node_removed";
final String expectedDate = "2016-06-07T17:52:19.617Z";
final String expectedNode = "eq7a4/";
final String expectedOrigNode = "5w8q7/";
final String expectedUser = "qmdz6/";
assertEquals(expectedAction, log.getAction());
assertEquals(expectedDate, log.getDate());
assertTrue(log.getNode().endsWith(expectedNode));
assertTrue(log.getOriginal_node().endsWith(expectedOrigNode));
assertTrue(log.getUser().endsWith(expectedUser));
assertTrue(log.getParams().containsKey("params_node"));
assertTrue(log.getParams().containsKey("params_project"));
assertTrue(((Map) log.getParams().get("params_node")).get("id").equals("5w8q7"));
assertTrue(((Map) log.getParams().get("params_node")).get("title").equals("Workflow Execution"));
}
}
|
package id.ac.ub.ptiik.papps.parsers;
import java.util.ArrayList;
import id.ac.ub.ptiik.papps.base.Agenda;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class AgendaParser {
public static ArrayList<Agenda> Parse(String JSONString){
try {
JSONObject object = new JSONObject(JSONString);
ArrayList<Agenda> agendaList = new ArrayList<Agenda>();
JSONArray newsArray = object.getJSONArray("agenda");
for(int i=0; i<newsArray.length(); i++) {
Agenda a = new Agenda();
JSONObject aJSON = (JSONObject) newsArray.get(i);
a.agenda_id = aJSON.getString("jenis_kegiatan_id");
a.jenis_kegiatan_id = aJSON.getString("jenis_kegiatan_id");
a.lokasi = aJSON.getString("lokasi");
a.ruang = aJSON.getString("ruang");
a.judul = aJSON.getString("judul");
a.keterangan = aJSON.getString("keterangan");
a.penyelenggara = aJSON.getString("penyelenggara");
a.tgl_mulai = aJSON.getString("tgl_mulai");
a.tgl_selesai = aJSON.getString("tgl_selesai");
a.is_publish = aJSON.getString("is_publish");
a.is_private = aJSON.getString("is_private");
agendaList.add(a);
}
return agendaList;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
|
package sarong;
import sarong.discouraged.ThrustAlt32RNG;
import sarong.util.StringKit;
import java.io.Serializable;
/**
* A 32-bit generator that needs no math on 64-bit values to calculate high-quality pseudo-random numbers, and has been
* adapted to meet the needs of GWT while maintaining compatibility with other JDK platforms. It won't ever multiply an
* int by a number with more than 20 bits, and along with bitwise operations used frequently, this prevents precision
* loss on GWT from when an int fails to overflow and exceeds 2 to the 53. The only other generators in this library
* that avoid precision loss like that are {@link Zig32RNG}, which precedes this generator and is slightly slower, and
* {@link ThrustAlt32RNG}, but that generator isn't capable of producing all int results and has a small bias toward
* some other results.
* <br>
* Zag32RNG has extremely good performance on GWT, though how good depends on the browser being used and whether 32-bit
* or 64-bit results are needed. In Opera 51 on a Windows 7 laptop (64-bit), it takes roughly 43 microseconds to
* generate 10,000 int values with Zag32RNG; ThrustAlt32RNG takes roughly 37 microseconds, and LightRNG takes roughly
* 1929 microseconds (yes, math on long values does have a speed penalty to make up for its better accuracy). The total
* period of Zag32RNG is 0xFFFFFFFF00000000 (18446744069414584320). Quality is very good here, and this passes PractRand
* without failures and with 3 minor anomalies (classified as "unusual" and all different kinds) on 32TB of testing;
* this is probably enough to confirm a generator as high-quality. It's still possible that tests not present in
* PractRand can detect errors in Zag32RNG.
* <br>
* For the specific structure of Zag32RNG, it is a combination of a Marsaglia-style XorShift generator with an "XLCG"
* generator (like a linear congruential generator but using XOR instead of addition). It has 2 ints for state, stateA
* and stateB, where stateA is modified by the XorShift and cannot be given 0, and stateB is modified by the XLCG and
* can be assigned any int. stateA will never be 0, but will be every non-0 int with equal frequency; it repeats every
* {@code Math.pow(2, 32) - 1} generated numbers. stateB goes through every int over the course of the XLCG's period; it
* naturally has a period of {@code Math.pow(2, 32)}. Just adding an XLCG to a XorShift generator isn't enough to ensure
* quality; the XLCG's result (not the actual stateB) is xorshifted right twice, as in {@code tempB ^= tempB >>> 13},
* before adding the XorShift result of stateA and then xorshifting right once more to get the final value. The XorShift
* that stateA uses is a normal kind that involves two rightward shifts and one leftward shift, but because stateB is
* updated by an XLCG (which has a higher period on its more-significant bits and a very low period on its
* least-significant bits), the numbers using stateB's value need only rightward shifts by varying amounts. This
* generator is not reversible given the output of {@link #nextInt()}, though the update steps for stateA and stateB are
* both individually reversible.
* <br>
* Although Zag32RNG has a {@link #determine(int, int)} method, calling it is considerably more complex than other
* RandomnessSources that provide determine() methods. It also doesn't allow skipping through the state, and a moderate
* amount of the possible values that can be provided with {@link #setState(long)} will be changed before this can use
* them (there are fewer than 2 to the 64 possible states, but only somewhat).
* <br>
* Created by Tommy Ettinger on 3/13/2018.
*/
public final class Zag32RNG implements StatefulRandomness, Serializable {
private int a, b;
private static final long serialVersionUID = 178316585712476930L;
/**
* Constructs a Zag32RNG with a random state, using two calls to Math.random().
*/
public Zag32RNG()
{
this((int)((Math.random() * 2.0 - 1.0) * 0x80000000), (int)((Math.random() * 2.0 - 1.0) * 0x80000000));
}
/**
* Constructs a Zag32RNG with a stateA equal to the given stateA unless 0 was given, in which case stateA will be 1,
* and a stateB exactly equal to the given stateB.
* @param stateA any int except 0 (0 will be treated as 1 instead)
* @param stateB any int
*/
public Zag32RNG(int stateA, int stateB)
{
a = stateA == 0 ? 1 : stateA;
b = stateB;
}
/**
* Takes 32 bits of state and uses it to randomly fill the 64 bits of state this uses.
* @param statePart any int
*/
public Zag32RNG(int statePart)
{
b = statePart;
a = ~statePart;
a ^= a >>> 5;
a ^= a << 17;
a ^= a >>> 13;
a ^= statePart;
if(a == 0) a = 1; // not sure if this is possible
}
/**
* Constructs a Zag32RNG using a long that combines the two parts of state, as from {@link #getState()}.
* @param stateCombined a long that combines state A and state B, with state A in the less significant 32 bits
*/
public Zag32RNG(long stateCombined)
{
this((int)stateCombined, (int)(stateCombined >>> 32));
}
public final int nextInt() {
int z = (b = (b ^ 0xC74EAD55) * 0xA5CB3);
a ^= a >>> 14;
z ^= z >>> 13;
a ^= a >>> 15;
z = (z ^ z >>> 11) + (a ^= a << 13);
return (z ^ z >>> 7);
}
/**
* Using this method, any algorithm that might use the built-in Java Random
* can interface with this randomness source.
*
* @param bits the number of bits to be returned
* @return the integer containing the appropriate number of bits
*/
@Override
public final int next(int bits) {
int z = (b = (b ^ 0xC74EAD55) * 0xA5CB3);
a ^= a >>> 14;
z ^= z >>> 13;
a ^= a >>> 15;
z = (z ^ z >>> 11) + (a ^= a << 13);
return (z ^ z >>> 7) >>> (32 - bits);
}
/**
* Using this method, any algorithm that needs to efficiently generate more
* than 32 bits of random data can interface with this randomness source.
* <p>
* Get a random long between Long.MIN_VALUE and Long.MAX_VALUE (both inclusive).
*
* @return a random long between Long.MIN_VALUE and Long.MAX_VALUE (both inclusive)
*/
@Override
public final long nextLong() {
int z = (b ^ 0xC74EAD55) * 0xA5CB3, y = (b = (z ^ 0xC74EAD55) * 0xA5CB3);
a ^= a >>> 14;
z ^= z >>> 13;
a ^= a >>> 15;
z = (z ^ z >>> 11) + (a ^= a << 13);
a ^= a >>> 14;
y ^= y >>> 13;
a ^= a >>> 15;
y = (y ^ y >>> 11) + (a ^= a << 13);
return (long)(y ^ y >>> 7) << 32 ^ (z ^ z >>> 7);
}
/**
* Produces a copy of this RandomnessSource that, if next() and/or nextLong() are called on this object and the
* copy, both will generate the same sequence of random numbers from the point copy() was called. This just need to
* copy the state so it isn't shared, usually, and produce a new value with the same exact state.
*
* @return a copy of this RandomnessSource
*/
@Override
public Zag32RNG copy() {
return new Zag32RNG(a, b);
}
public int getStateA()
{
return a;
}
public void setStateA(int stateA)
{
a = stateA == 0 ? 1 : stateA;
}
public int getStateB()
{
return b;
}
public void setStateB(int stateB)
{
b = stateB;
}
/**
* Get the current internal state of the StatefulRandomness as a long.
*
* @return the current internal state of this object.
*/
@Override
public long getState() {
return (long) b << 32 | (a & 0xFFFFFFFFL);
}
/**
* Set the current internal state of this StatefulRandomness with a long.
* If the bottom 32 bits of the given state are all 0, then this will set stateA to 1, otherwise it sets stateA to
* those bottom 32 bits. This always sets stateB to the upper 32 bits of the given state.
* @param state a 64-bit long; the bottom 32 bits should not be all 0, but this is tolerated
*/
@Override
public void setState(long state) {
a = (int)(state & 0xFFFFFFFFL);
if(a == 0) a = 1;
b = (int) (state >>> 32);
}
/**
* Sets the current internal state of this Zag32RNG with two ints, where stateA can be any int except 0, and stateB
* can be any int.
* @param stateA any int except 0 (0 will be treated as 1 instead)
* @param stateB any int
*/
public void setState(int stateA, int stateB)
{
a = stateA == 0 ? 1 : stateA;
b = stateB;
}
@Override
public String toString() {
return "Zag32RNG with stateA 0x" + StringKit.hex(a) + " and stateB 0x" + StringKit.hex(b);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Zag32RNG that = (Zag32RNG) o;
return a == that.a && b == that.b;
}
@Override
public int hashCode() {
return 31 * a + b;
}
/**
* Gets a pseudo-random int determined wholly by the given state variables a and b, which should change every call.
* Call with {@code determine((a = (a = (a ^= a >>> 14) ^ a >>> 15) ^ a << 13), b = (b ^ 0xC74EAD55) * 0xA5CB3 | 0)},
* where a and b are int variables used as state. The complex call to this method allows it to remain static. In the
* update for b, the bitwise OR with 0 is only needed for GWT in order to force overflow to wrap instead of losing
* precision (a quirk of the JS numbers GWT uses). If you know you won't target GWT you can use
* {@code b = (b ^ 0xC74EAD55) * 0xA5CB3}. This should be fairly fast on GWT because most PRNGs (that can pass any
* decent statistical quality tests) use either 64-bit long values or many int variables for state, while this can
* get by with just two int variables. Using long on GWT is usually the only reasonable option if you expect
* arithmetic overflow (because long is emulated by GWT to imitate the behavior of a JDK, but is considerably slower
* as a result), but by some careful development for this generator, it should have identical results on GWT and on
* desktop/Android JVMs with only int math.
* <br>
* You may find it more convenient to just instantiate a Zag32RNG object rather than using the complex state update;
* using the methods on a Zag32RNG object may also be more efficient because some operations can be performed with
* bit-parallel optimizations on the same (modern) processor.
* @param a must be non-zero and updated with each call, using {@code a = (a = (a ^= a >>> 14) ^ a >>> 15) ^ a << 13}
* @param b must be updated with each call, using {@code b = (b ^ 0xC74EAD55) * 0xA5CB3 | 0}, with {@code | 0} needed for GWT
* @return a pseudo-random int, equidistributed over a period of 0xFFFFFFFF00000000; can be any int
*/
public static int determine(int a, int b) {
return ((b = ((b ^= b >>> 13) ^ b >>> 11) + a) ^ b >>> 7);
}
/**
* Gets a pseudo-random int between 0 and the given bound, using the given ints a and b as the state; these state
* variables a and b should change with each call. The exclusive bound can be negative or positive, and can be
* between -32768 and 32767 (both inclusive); the small limits allow using just 32-bit math. Call with
* {@code determineBounded((a = (a = (a ^= a >>> 14) ^ a >>> 15) ^ a << 13), b = (b ^ 0xC74EAD55) * 0xA5CB3 | 0), bound},
* where a and b are int variables used as state and bound is the exclusive outer bound. The complex call to this
* method allows it to remain static. In the update for b, the bitwise OR with 0 is only needed for GWT in order to
* force overflow to wrap instead of losing precision (a quirk of the JS numbers GWT uses). If you know you won't
* target GWT you can use {@code b = (b ^ 0xC74EAD55) * 0xA5CB3}.
* @param a must be non-zero and updated with each call, using {@code a = (a = (a ^= a >>> 14) ^ a >>> 15) ^ a << 13}
* @param b must be updated with each call, using {@code b = (b ^ 0xC74EAD55) * 0xA5CB3 | 0}, with {@code | 0} needed for GWT
* @param bound the outer exclusive limit on the random number; should be between -32768 and 32767 (both inclusive)
* @return a pseudo-random int, between 0 (inclusive) and bound (exclusive)
*/
public static int determineBounded(int a, int b, int bound)
{
return ((bound * (((b = ((b ^= b >>> 13) ^ b >>> 11) + a) ^ b >>> 7) & 0x7FFF)) >> 15);
}
}
|
package fr.projetcookie.boussole.providers;
import android.location.Location;
public class BaloonPositionFromSettings extends BaloonPositionProvider {
Location mFakeLocation = new Location("baloon");
public BaloonPositionFromSettings(int t) {
super(t);
}
public BaloonPositionFromSettings(double lat, double lon) {
super(0);
setLocation(lat, lon);
}
public void setLocation(double lat, double lon) {
mFakeLocation.setLongitude(lon);
mFakeLocation.setLatitude(lat);
}
public void run() {} // Who needs Threads when you have swag?
@Override
public float stahp() {
return 0;
}
@Override
public Location getLocation() {
return mFakeLocation;
}
}
|
/**
*
*/
package com.trs.om.rbac.dao;
import java.util.AbstractList;
import java.util.List;
/**
* @author Administrator
*
*/
public class PagedList extends AbstractList {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 当前页记录列表
*/
private List pageItems;
/**
* 当前页码
*/
private int pageIndex;
/**
* 每页记录数
*/
private int pageSize;
/**
* 总记录数
*/
private int totalItemCount;
/**
* @param pageItems
* @param pageNumber
* @param itemsPerPage
* @param totalItemCount
*/
public PagedList(List pageItems, int pageIndex, int pageSize, int totalItemCount) {
this.pageItems = pageItems;
this.pageIndex = pageIndex;
this.pageSize = pageSize;
this.totalItemCount = totalItemCount;
}
/**
* @see java.util.AbstractList#get(int)
*/
public Object get(int index) {
return this.pageItems.get(index);
}
/**
* @see java.util.AbstractCollection#size()
*/
public int size() {
return this.pageItems.size();
}
/**
* @return the list of items for this page
*/
public List getPageItems() {
return pageItems;
}
/**
* @return total count of items
*/
public int getTotalItemCount() {
return totalItemCount;
}
/**
* @return total count of pages
*/
public int getTotalPageCount() {
return (int) Math.ceil((double) getTotalItemCount() / getPageSize());
}
/**
* @return true if this is the first page
*/
public boolean isFirstPage() {
return isFirstPage(getPageIndex());
}
/**
* @return true if this is the last page
*/
public boolean isLastPage() {
return isLastPage(getPageIndex());
}
/**
* @param page
* @return true if the page is the first page
*/
public boolean isFirstPage(int page) {
return page <= 1;
}
/**
* @param page
* @return true if the page is the last page
*/
public boolean isLastPage(int page) {
return page >= getTotalPageCount();
}
/**
* @see java.util.AbstractCollection#toString()
*/
public String toString() {
return new StringBuffer(256).append(this).append(getPageItems()).append(getPageIndex()).append(getPageSize()).append(getTotalItemCount()).toString();
}
/**
* @return the pageIndex
*/
public int getPageIndex() {
return pageIndex;
}
/**
* @return the pageSize
*/
public int getPageSize() {
return pageSize;
}
}
|
/*
* Copyright (c) 2012, Oskar Veerhoek
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
*/
package org.oskar;
import org.apache.log4j.Logger;
import org.oskar.application.file.FileSystem;
import org.oskar.application.input.InputSystem;
import org.oskar.logic.LogicSystem;
import org.oskar.view.RenderingSystem;
import org.oskar.application.resources.ResourceSystem;
import org.oskar.application.window.WindowingSystem;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Oskar Veerhoek
*/
public class GameWorld {
private WindowingSystem windowingSystem = new WindowingSystem();
private RenderingSystem renderingSystem = new RenderingSystem();
private FileSystem fileSystem = new FileSystem();
private ResourceSystem resourceSystem = new ResourceSystem();
private LogicSystem logicSystem = new LogicSystem();
private InputSystem inputSystem = new InputSystem();
private Map<String, String> stringProperties = new HashMap<String, String>();
private Map<String, Integer> integerProperties = new HashMap<String, Integer>();
private boolean isCreated = false;
private AtomicBoolean flaggedForDestruction = new AtomicBoolean(false);
public void setFlaggedForDestruction(boolean value) {
this.flaggedForDestruction.set(value);
}
public boolean isFlaggedForDestruction() {
return flaggedForDestruction.get();
}
/**
* Sets the "created" state to true.
*/
public GameWorld() {
isCreated = true;
}
/**
* Destroys all the modules that the game world uses.
*/
public void destroy() {
info(GameWorld.class, "Destroying game world");
inputSystem.destroy();
logicSystem.destroy();
renderingSystem.destroy();
windowingSystem.destroy();
resourceSystem.destroy();
fileSystem.destroy();
isCreated = false;
info(GameWorld.class, "Done destroying game world");
}
/**
* Prints out a debug log.
* @param sender the class from which the log is sent
* @param log the contents of the log
*/
public void debug(Class sender, String log) {
Logger.getLogger(sender).debug(log);
}
/**
* Prints out an info log.
* @param sender the class from which the log is sent
* @param log the contents of the log
*/
public void info(Class sender, String log) {
Logger.getLogger(sender).info(log);
}
/**
* Prints out a warning log.
* @param sender the class from which the log is sent
* @param log the contents of the log
*/
public void warn(Class sender, String log) {
Logger.getLogger(sender).warn(log);
}
/**
* Prints out a fatal exception and destroys the game world.
* @param sender the class from which the log is sent
* @param e the exception that occurred
*/
public void fatal(Class sender, Exception e) {
Logger.getLogger(sender).fatal("", e);
setFlaggedForDestruction(true);
}
/**
* Prints out a fatal exception with a log and destroys the game world.
* @param sender the class from which the log was sent
* @param log the contents of the log
* @param e the exception that occurred
*/
public void fatal(Class sender, String log, Exception e) {
Logger.getLogger(sender).fatal(log, e);
setFlaggedForDestruction(true);
}
/**
* Prints out a fatal log and destroys the game world.
* @param sender the class from which the log was sent
* @param log the contents of the log
*/
public void fatal(Class sender, String log) {
Logger.getLogger(sender).fatal(log);
setFlaggedForDestruction(true);
}
/**
* Prints out an exception.
* @param sender the class from which the log is sent
* @param e the exception that occurred
*/
public void error(Class sender, Exception e) {
Logger.getLogger(sender).error("", e);
}
/**
* Prints out an exception with a log.
* @param sender the class from which the log is sent
* @param log the contents of the log
* @param e the exception that occurred
*/
public void error(Class sender, String log, Exception e) {
Logger.getLogger(sender).error(log, e);
}
/**
* Prints out an error log.
* @param sender the class from which the log is sent
* @param log the contents of the log
*/
public void error(Class sender, String log) {
Logger.getLogger(sender).error(log);
}
/**
* Sets the appropriate properties and initialises the following modules:
* - File System
* - Resource System
* - Windowing System
* - Rendering System
*/
public void create() {
info(GameWorld.class, "Creating game world");
debug(GameWorld.class, "Setting properties");
setProperty("WINDOW_TITLE", "Core OpenGL - Java w/ LWJGL");
setProperty("WINDOW_WIDTH", 640);
setProperty("WINDOW_HEIGHT", 480);
setProperty("RESOURCE_VERTEX_SHADER", "res/shader.vs");
setProperty("RESOURCE_FRAGMENT_SHADER", "res/shader.fs");
fileSystem.create(this);
resourceSystem.create(this);
windowingSystem.create(this);
renderingSystem.create(this);
logicSystem.create(this);
inputSystem.create(this);
info(GameWorld.class, "Done creating game world");
}
public void setProperty(String key, String value) {
debug(GameWorld.class, "Setting " + key + " to \"" + value + "\"");
stringProperties.put(key, value);
}
public void setProperty(String key, Integer value) {
debug(GameWorld.class, "Setting " + key + " to " + value);
integerProperties.put(key, value);
}
public Integer getIntegerProperty(String key) {
if (!integerProperties.containsKey(key)) {
error(GameWorld.class, "Key " + key + " does not exist.");
return null;
} else {
return integerProperties.get(key);
}
}
public String getStringProperty(String key) {
if (!stringProperties.containsKey(key)) {
error(GameWorld.class, "Key " + key + " does not exist.");
return null;
} else {
return stringProperties.get(key);
}
}
public boolean isCreated() {
return isCreated;
}
public RenderingSystem getRenderingSystem() {
return renderingSystem;
}
public LogicSystem getLogicSystem() {
return logicSystem;
}
public InputSystem getInputSystem() {
return inputSystem;
}
public FileSystem getFileSystem() {
return fileSystem;
}
public ResourceSystem getResourceSystem() {
return resourceSystem;
}
public void run() {
while (!flaggedForDestruction.get()) {
inputSystem.update();
logicSystem.update();
renderingSystem.update();
windowingSystem.update();
}
}
}
|
package com.krx.websocket.message;
/**
* Created by benjamin on 9/28/14.
*/
public class TextMessage implements WebSocketMessage<String> {
private CharSequence charSequence;
public TextMessage(){
}
public TextMessage(CharSequence charSequence){
this.charSequence = charSequence;
}
public CharSequence getCharSequence() {
return charSequence;
}
public void setCharSequence(CharSequence charSequence) {
this.charSequence = charSequence;
}
@Override
public String getPayload() {
return charSequence.toString();
}
@Override
public int getPayloadLength() {
return charSequence.length();
}
}
|
package com.kush.lib.expressions.functions;
public interface FunctionSpec {
String getFunctionName();
Class<?> getReturnType();
FunctionExecutor getFunctionExecutor();
}
|
package com.xiaodao.admin.client;
import com.github.pagehelper.PageInfo;
import com.xiaodao.feign.config.MultipartSupportConfig;
import com.xiaodao.core.result.RespDataVO;
import com.xiaodao.core.result.RespVO;
import com.xiaodao.core.result.RespVOBuilder;
import com.xiaodao.admin.entity.SysDictData;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@FeignClient(value = "system-service", path = "/sysDictData", fallbackFactory = SysDictDataClientFallback.class, configuration = MultipartSupportConfig.class)
public interface SysDictDataClient {
/**
* 新增
*
* @param sysDictData
* @return
*/
@PostMapping("/insert")
RespVO insert(@RequestBody SysDictData sysDictData);
/**
* 带有空值判断的新增
*
* @param sysDictData
* @return
*/
@PostMapping("/insertSelective")
RespVO insertSelective(@RequestBody SysDictData sysDictData);
/**
* 批量新增
*
* @param list
* @return
*/
@PostMapping("/batchInsert")
RespVO batchInsert(@RequestBody List<SysDictData> list);
/**
* 带有空值判断的新增
*
* @param list
* @return
*/
@PostMapping("/batchInsertSelective")
RespVO batchInsertSelective(@RequestBody List<SysDictData> list);
/**
* 根据主键更新
*
* @param sysDictData
* @return
*/
@PutMapping("/updateByPrimaryKey")
RespVO updateByPrimaryKey(@RequestBody SysDictData sysDictData);
/**
* 根据空值判断的主键更新
*
* @param sysDictData
* @return
*/
@PutMapping("/updateSelectiveByPrimaryKey")
RespVO updateSelectiveByPrimaryKey(@RequestBody SysDictData sysDictData);
/**
* 批量更新
*
* @param list
* @return
*/
@PutMapping("/batchUpdate")
RespVO batchUpdate(@RequestBody List<SysDictData> list);
/**
* 带有空值判断的批量更新
*
* @param list
* @return
*/
@PutMapping("/batchUpdateSelective")
RespVO batchUpdateSelective(@RequestBody List<SysDictData> list);
/**
* 更新插入
*
* @param sysDictData
* @return
*/
@PostMapping("/upsert")
RespVO upsert(@RequestBody SysDictData sysDictData);
/**
* 带有空值判断的更新插入
*
* @param sysDictData
* @return
*/
@PostMapping("/upsertSelective")
RespVO upsertSelective(@RequestBody SysDictData sysDictData);
/**
* 批量更新插入
*
* @param list
* @return
*/
@PostMapping("/batchUpsert")
RespVO batchUpsert(@RequestBody List<SysDictData> list);
/**
* 带有空值判断的批量更新插入
*
* @param list
* @return
*/
@PostMapping("/batchUpsertSelective")
RespVO batchUpsertSelective(@RequestBody List<SysDictData> list);
/**
* 通过主键删除
*
* @param dictCode
* @return
*/
@DeleteMapping("/{dictCode}")
RespVO deleteByPrimaryKey(@PathVariable(value = "dictCode") Integer dictCode);
/**
* 通过主键批量删除
*
* @param list
* @return
*/
@DeleteMapping("/deleteBatchByPrimaryKeys")
RespVO deleteBatchByPrimaryKeys(@RequestBody List<Long> list);
/**
* 条件删除
*
* @param sysDictData
* @return
*/
@DeleteMapping("/delete")
RespVO delete(@RequestBody SysDictData sysDictData);
/**
* 通过主键查询
*
* @param dictCode
* @return
*/
@GetMapping("/{dictCode}")
RespVO<SysDictData> queryByPrimaryKey(@PathVariable(value = "dictCode") Integer dictCode);
/**
* 通过主键批量查询
*
* @param list
* @return
*/
@PostMapping("/queryBatchPrimaryKeys")
RespVO<RespDataVO<SysDictData>> queryBatchPrimaryKeys(@RequestBody List<Long> list);
/**
* 条件查询一个
*
* @param sysDictData
* @return
*/
@PostMapping("/queryOne")
RespVO<SysDictData> queryOne(@RequestBody SysDictData sysDictData);
/**
* 条件查询
*
* @param sysDictData
* @return
*/
@PostMapping("/queryByCondition")
RespVO<RespDataVO<SysDictData>> queryByCondition(@RequestBody SysDictData sysDictData);
/**
* 条件分页查询
*
* @param sysDictData
* @return
*/
@PostMapping("/queryPageByCondition")
RespVO<PageInfo<SysDictData>> queryPageByCondition(@RequestBody SysDictData sysDictData);
/**
* 模糊查询
*
* @param sysDictData
* @return
*/
@PostMapping("/queryFuzzy")
RespVO<RespDataVO<SysDictData>> queryFuzzy(@RequestBody SysDictData sysDictData);
/**
* 模糊分页查询
*
* @param sysDictData
* @return
*/
@PostMapping("/queryPageFuzzy")
RespVO<PageInfo<SysDictData>> queryPageFuzzy(@RequestBody SysDictData sysDictData);
/**
* 模糊条件查询
*
* @param sysDictData
* @return
*/
@PostMapping("/queryByLikeCondition")
RespVO<RespDataVO<SysDictData>> queryByLikeCondition(@RequestBody SysDictData sysDictData);
/**
* 模糊分页条件查询
*
* @param sysDictData
* @return
*/
@PostMapping("/queryPageByLikeCondition")
RespVO<PageInfo<SysDictData>> queryPageByLikeCondition(@RequestBody SysDictData sysDictData);
/**
* 条件查询数量
*
* @param sysDictData
* @return
*/
@PostMapping("/queryCount")
RespVO<Long> queryCount(@RequestBody SysDictData sysDictData);
/**
* 分组统计
*
* @param sysDictData
* @return
*/
@PostMapping("/statisticsGroup")
RespVO<RespDataVO<Map<String, Object>>> statisticsGroup(@RequestBody SysDictData sysDictData);
/**
* 日统计
*
* @param sysDictData
* @return
*/
@PostMapping("/statisticsGroupByDay")
RespVO<RespDataVO<Map<String, Object>>> statisticsGroupByDay(@RequestBody SysDictData sysDictData);
/**
* 月统计
*
* @param sysDictData
* @return
*/
@PostMapping("/statisticsGroupByMonth")
RespVO<RespDataVO<Map<String, Object>>> statisticsGroupByMonth(@RequestBody SysDictData sysDictData);
/**
* 年统计
*
* @param sysDictData
* @return
*/
@PostMapping("/statisticsGroupByYear")
RespVO<RespDataVO<Map<String, Object>>> statisticsGroupByYear(@RequestBody SysDictData sysDictData);
}
class SysDictDataClientFallback implements SysDictDataClient {
@Override
public RespVO insert(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO insertSelective(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO batchInsert(List<SysDictData> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO batchInsertSelective(List<SysDictData> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO updateByPrimaryKey(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO updateSelectiveByPrimaryKey(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO batchUpdate(List<SysDictData> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO batchUpdateSelective(List<SysDictData> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO upsert(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO upsertSelective(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO batchUpsert(List<SysDictData> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO batchUpsertSelective(List<SysDictData> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO deleteByPrimaryKey(Integer dictCode) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO deleteBatchByPrimaryKeys(List<Long> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO delete(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<SysDictData> queryByPrimaryKey(Integer dictCode) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<SysDictData>> queryBatchPrimaryKeys(List<Long> list) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<SysDictData> queryOne(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<SysDictData>> queryByCondition(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<PageInfo<SysDictData>> queryPageByCondition(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<SysDictData>> queryFuzzy(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<PageInfo<SysDictData>> queryPageFuzzy(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<SysDictData>> queryByLikeCondition(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<PageInfo<SysDictData>> queryPageByLikeCondition(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<Long> queryCount(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<Map<String, Object>>> statisticsGroup(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<Map<String, Object>>> statisticsGroupByDay(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<Map<String, Object>>> statisticsGroupByMonth(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
@Override
public RespVO<RespDataVO<Map<String, Object>>> statisticsGroupByYear(SysDictData sysDictData) {
return RespVOBuilder.failure("system-service服务不可用");
}
} |
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.sites;
import de.hybris.platform.cmsfacades.data.SiteData;
import java.util.List;
/**
* simplification of site related interactions.
*/
public interface SiteFacade
{
/**
* Lists all sites for which user has at-least read access to one of the non-active catalog versions.
*
* @return All sites that are configured; never <tt>null</tt>
*/
List<SiteData> getAllSiteData();
/**
* Lists all sites that are configured for the given list of catalogIds where the catalog id represents the lowest
* level catalog in the hierarchy for a site.
*
* @param catalogIds
* - the catalog identifiers
* @return All sites where the catalog ids are the lowest catalog in the catalog hierarchy; never <tt>null</tt>
*/
List<SiteData> getSitesForCatalogs(final List<String> catalogIds);
}
|
package com.mango.leo.zsproject.industrialservice.createrequirements.carditems.bean;
import com.luck.picture.lib.entity.LocalMedia;
import java.util.List;
/**
* Created by admin on 2018/5/16.
*/
public class CardFourthItemBean {
//private String projectId;
private String name;
private String company;
private String phoneNumber;
private String position;
private String email;
public CardFourthItemBean() {
}
public CardFourthItemBean(String name, String company, String phoneNumber, String position, String email/*,String projectId*/) {
//this.projectId = projectId;
this.name = name;
this.company = company;
this.phoneNumber = phoneNumber;
this.position = position;
this.email = email;
}
/* public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
package com.hobson.assesment.steps;
import com.hobson.assesment.pages.HomePage;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.junit.Assert;
public class ScorllStepdefs extends BaseStepDef {
private HomePage homePage;
public ScorllStepdefs(){
super();
homePage = new HomePage(Hooks.driver);
}
@Then("^I should get tiles in the ([^\"]*)$")
public void iShouldGetTilesInTheExpectedOrder(String expectedTileName) throws Throwable {
String actualTileName = homePage.getFirstTileName();
Assert.assertEquals(expectedTileName,actualTileName);
}
@When("^I click on right arrow ([^\"]*) times$")
public void iClickOnRightArrow(int n) throws Throwable {
for(int i = 0; i < n; i++) {
homePage.clickRightArrow();
}
homePage.waitForTileToBeVisble();
}
@When("^I click on left arrow ([^\"]*) times$")
public void iClickOnLeftArrowNTimes(int n) throws Throwable {
for(int i = 0; i < n; i++) {
homePage.clickLeftArrow();
}
homePage.waitForTileToBeVisble();
}
}
|
/*
*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*
*/
package com.cnk.travelogix.common.core.payment.criterias;
import de.hybris.platform.core.enums.PaymentStatus;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.cnk.travelogix.common.core.model.PaymentPlanEntryModel;
/**
* @author i323727
*
*/
public abstract class AbstractPaymentPlanEntryCriteria implements PaymentPlanEntryCriteria
{
/*
* (non-Javadoc)
*
* @see com.cnk.travelogix.common.core.payment.criterias.PaymentPlanEntryCriteria#meetCriteria(java.util.List)
*/
@Override
public List<PaymentPlanEntryModel> meetCriteria(final List<PaymentPlanEntryModel> list)
{
final ArrayList<PaymentPlanEntryModel> result = new ArrayList<PaymentPlanEntryModel>();
Optional.ofNullable(list).ifPresent(elist -> {
elist.forEach(entry -> {
if (entry.getPaymentPlan().getPaymentStatus() == getPaymentStatus())
{
result.add(entry);
}
});
});
return result;
}
public abstract PaymentStatus getPaymentStatus();
}
|
package com.semantyca.nb.ui.action.constants;
public enum ActionType {
CUSTOM_ACTION, DELETE_DOCUMENT, SAVE_AND_CLOSE, CLOSE, GET_DOCUMENT_ACCESSLIST, BACK, LINK, RELOAD, API_ACTION
}
|
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestDBConnection {
private static final boolean DEBUG = true;
private String ip;
private int port;
private String dbName;
private String userName;
private String userPwd;
@Before
public void beforeDbConnectTest() {
if (DEBUG) {
// Dev
ip = "hyonga.iptime.org";
port = 15433;
dbName = "UCIOS";
userName = "uci_dba";
userPwd = "rhdro2015#";
} else {
// Real
ip = "hyonga.iptime.org";
port = 154383;
dbName = "UCIOS";
userName = "uci_dba";
userPwd = "rhdro2015#";
}
}
@Test
public void dbConnection() {
String connectionUrl = "jdbc:sqlserver://" + ip + ":" + port + ";" + "databaseName=" + dbName + ";";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver okay");
con = DriverManager.getConnection(connectionUrl, userName, userPwd);
System.out.println("Connection Made");
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
}
}
|
package ca.antonious.habittracker;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.View;
import ca.antonious.habittracker.addhabit.AddHabitActivity;
import ca.antonious.habittracker.habitlist.HabitListFragment;
import ca.antonious.habittracker.todayshabitlist.TodaysHabitsFragment;
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private TabLayout tabLayout;
private FloatingActionButton floatingActionButton;
private SectionsPagerAdapter sectionsPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindViews();
setUpViewPager();
handleAddButtonClicks();
}
private void bindViews() {
viewPager = (ViewPager) findViewById(R.id.container);
tabLayout = (TabLayout) findViewById(R.id.tabs);
floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
}
private void setUpViewPager() {
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(sectionsPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
private void handleAddButtonClicks() {
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, AddHabitActivity.class));
}
});
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: return TodaysHabitsFragment.newInstance();
case 1: return HabitListFragment.newInstance();
default: return null;
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: return getString(R.string.todays_habits_tab_name);
case 1: return getString(R.string.all_habits_tab_name);
default: return null;
}
}
}
}
|
package com.znamenacek.jakub.spring_boot_security_test.controllers;
import com.znamenacek.jakub.spring_boot_security_test.exceptions.StudentNotFoundException;
import com.znamenacek.jakub.spring_boot_security_test.models.Student;
import com.znamenacek.jakub.spring_boot_security_test.services.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(path = "api")
public class StudentController {
private final StudentService studentService;
@Autowired
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
@GetMapping
public ResponseEntity<List<Student>> getAllStudents(){
return new ResponseEntity<>(studentService.getAllStudents(), HttpStatus.OK);
}
@GetMapping(path = "/{id}")
public ResponseEntity<Student> getStudentById(@PathVariable Integer id){
return studentService.getStudentById(id)
.map(student -> new ResponseEntity<>(student,HttpStatus.OK))
.orElseThrow(() -> new StudentNotFoundException(id));
}
@PostMapping
public ResponseEntity<Student> createStudent(@RequestBody Student student){
return new ResponseEntity<>(studentService.createStudent(student), HttpStatus.OK);
}
}
|
package com.flutterwave.raveandroid;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.constraintlayout.widget.Guideline;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.FragmentTransaction;
import androidx.transition.AutoTransition;
import androidx.transition.TransitionManager;
import com.flutterwave.raveandroid.account.AccountFragment;
import com.flutterwave.raveandroid.ach.AchFragment;
import com.flutterwave.raveandroid.banktransfer.BankTransferFragment;
import com.flutterwave.raveandroid.barter.BarterFragment;
import com.flutterwave.raveandroid.card.CardFragment;
import com.flutterwave.raveandroid.data.DeviceIdGetter;
import com.flutterwave.raveandroid.data.events.SessionFinishedEvent;
import com.flutterwave.raveandroid.di.components.DaggerRaveUiComponent;
import com.flutterwave.raveandroid.di.components.RaveUiComponent;
import com.flutterwave.raveandroid.di.modules.AndroidModule;
import com.flutterwave.raveandroid.francMobileMoney.FrancMobileMoneyFragment;
import com.flutterwave.raveandroid.ghmobilemoney.GhMobileMoneyFragment;
import com.flutterwave.raveandroid.mpesa.MpesaFragment;
import com.flutterwave.raveandroid.rave_cache.SharedPrefsRepo;
import com.flutterwave.raveandroid.rave_core.di.DeviceIdGetterModule;
import com.flutterwave.raveandroid.rave_java_commons.RaveConstants;
import com.flutterwave.raveandroid.rave_logger.Event;
import com.flutterwave.raveandroid.rave_logger.EventLogger;
import com.flutterwave.raveandroid.rave_logger.di.EventLoggerModule;
import com.flutterwave.raveandroid.rave_logger.events.ScreenLaunchEvent;
import com.flutterwave.raveandroid.rave_logger.events.ScreenMinimizeEvent;
import com.flutterwave.raveandroid.rave_presentation.di.DaggerRaveComponent;
import com.flutterwave.raveandroid.rave_presentation.di.RaveComponent;
import com.flutterwave.raveandroid.rave_remote.di.RemoteModule;
import com.flutterwave.raveandroid.rwfmobilemoney.RwfMobileMoneyFragment;
import com.flutterwave.raveandroid.sabankaccount.SaBankAccountFragment;
import com.flutterwave.raveandroid.ugmobilemoney.UgMobileMoneyFragment;
import com.flutterwave.raveandroid.uk.UkFragment;
import com.flutterwave.raveandroid.ussd.UssdFragment;
import com.flutterwave.raveandroid.zmmobilemoney.ZmMobileMoneyFragment;
import org.parceler.Parcels;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import javax.inject.Inject;
import static androidx.constraintlayout.widget.ConstraintLayout.LayoutParams.HORIZONTAL;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.LIVE_URL;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_ACCOUNT;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_ACH;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_BANK_TRANSFER;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_BARTER;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_FRANCO_MOBILE_MONEY;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_GH_MOBILE_MONEY;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_MPESA;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_RW_MOBILE_MONEY;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_SA_BANK_ACCOUNT;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_UG_MOBILE_MONEY;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_UK;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_USSD;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PAYMENT_TYPE_ZM_MOBILE_MONEY;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.RAVEPAY;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.RAVE_PARAMS;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.STAGING_URL;
public class RavePayActivity extends AppCompatActivity {
public static String BASE_URL;
View.OnClickListener onClickListener;
private HashMap<Integer, Guideline> guidelineMap = new HashMap<>();
private ArrayList<PaymentTile> paymentTiles = new ArrayList<>();
private HashMap<Integer, PaymentTile> tileMap = new HashMap<>();
private Guideline topGuide;
RavePayInitializer ravePayInitializer;
private Guideline bottomGuide;
private ConstraintLayout root;
public static int RESULT_SUCCESS = RaveConstants.RESULT_SUCCESS;
public static int RESULT_ERROR = RaveConstants.RESULT_ERROR;
public static int RESULT_CANCELLED = RaveConstants.RESULT_CANCELLED;
private int tileCount = 0;
int theme;
private float paymentTilesTextSize;
private long transitionDuration = 350;
RaveUiComponent raveUiComponent;
@Inject
EventLogger eventLogger;
@Inject
SharedPrefsRepo sharedManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
ravePayInitializer = Parcels.unwrap(getIntent().getParcelableExtra(RAVE_PARAMS));
} catch (Exception e) {
e.printStackTrace();
Log.d(RAVEPAY, "Error retrieving initializer");
}
buildGraph();
theme = ravePayInitializer.getTheme();
if (theme != 0) {
try {
setTheme(theme);
} catch (Exception e) {
e.printStackTrace();
}
}
setContentView(R.layout.rave_sdk_activity_rave_pay);
root = findViewById(R.id.rave_pay_activity_rootview);
Event event = new ScreenLaunchEvent("Payment Activity").getEvent();
event.setPublicKey(ravePayInitializer.getPublicKey());
eventLogger.logEvent(event);
setupMainContent();
}
private void setupMainContent() {
onClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
handleClick(view);
}
};
topGuide = createGuideline(this, HORIZONTAL);
root.addView(topGuide);
topGuide.setGuidelinePercent(0.08f);
bottomGuide = createGuideline(this, HORIZONTAL);
root.addView(bottomGuide);
bottomGuide.setGuidelinePercent(0.92f);
generatePaymentTiles();
generateGuides(tileCount);
render();
}
private void render() {
render(false);
}
private void render(boolean animated) {
if (tileCount == 1) {
View singlePaymentTileView = paymentTiles.get(0).view;
singlePaymentTileView.callOnClick(); // Show payment fragment
singlePaymentTileView.findViewById(R.id.arrowIv2).setVisibility(View.GONE);
((TextView) singlePaymentTileView.findViewById(R.id.rave_payment_type_title_textView)).setGravity(Gravity.CENTER);
singlePaymentTileView.setOnClickListener(null);
} else {
View fragmentContainerLayout = root.getViewById(R.id.payment_fragment_container_layout);
if (fragmentContainerLayout != null) {
renderAsHidden(fragmentContainerLayout, animated);
}
ConstraintSet set = new ConstraintSet();
set.clone(root);
for (int i = 0; i < paymentTiles.size(); i++) {
View tv2 = paymentTiles.get(i).view;
int upIndex = 10 - (i + 1);
Guideline upGuide = guidelineMap.get(upIndex);
Guideline downGuide = guidelineMap.get(upIndex + 1);
if (upGuide != null && downGuide != null) {
set.connect(tv2.getId(), ConstraintSet.TOP, upGuide.getId(), ConstraintSet.BOTTOM);
set.connect(tv2.getId(), ConstraintSet.BOTTOM, downGuide.getId(), ConstraintSet.TOP);
set.connect(tv2.getId(), ConstraintSet.LEFT, root.getId(), ConstraintSet.LEFT);
set.connect(tv2.getId(), ConstraintSet.RIGHT, root.getId(), ConstraintSet.RIGHT);
set.constrainWidth(tv2.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
set.constrainHeight(tv2.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
set.setVisibility(tv2.getId(), ConstraintSet.VISIBLE);
View arrowIv = tv2.findViewById(R.id.arrowIv2);
if (arrowIv != null)
arrowIv.animate().rotation(0f).setDuration(transitionDuration);
}
}
// Set title view
View titleView = root.findViewById(R.id.title_container);
if (titleView == null) {
titleView = getLayoutInflater().inflate(R.layout.rave_sdk_payment_title_layout, root, false);
root.addView(titleView);
}
set.connect(titleView.getId(), ConstraintSet.TOP, root.getId(), ConstraintSet.TOP);
set.connect(titleView.getId(), ConstraintSet.BOTTOM, guidelineMap.get(10 - paymentTiles.size() + 1).getId(), ConstraintSet.BOTTOM);
set.connect(titleView.getId(), ConstraintSet.LEFT, root.getId(), ConstraintSet.LEFT);
set.connect(titleView.getId(), ConstraintSet.RIGHT, root.getId(), ConstraintSet.RIGHT);
set.constrainWidth(titleView.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
set.constrainHeight(titleView.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
set.setVisibility(titleView.getId(), ConstraintSet.VISIBLE);
if (animated) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
AutoTransition transition = new AutoTransition();
transition.setDuration(transitionDuration);
TransitionManager.beginDelayedTransition(root, transition);
set.applyTo(root);
}
} else {
set.applyTo(root);
}
}
}
private void handleClick(View clickedView) {
PaymentTile paymentTile = tileMap.get(clickedView.getId());
if (paymentTile.isTop) {
Event event = new ScreenMinimizeEvent("payment methods").getEvent();
event.setPublicKey(ravePayInitializer.getPublicKey());
eventLogger.logEvent(event);
showAllPaymentTypes();
} else {
showSelectedPaymentType(clickedView);
}
}
private void showAllPaymentTypes() {
render(true);
for (int i = 0; i < paymentTiles.size(); i++) {
PaymentTile t = paymentTiles.get(i);
t.isTop = false;
tileMap.put(t.view.getId(), t);
}
}
private void showSelectedPaymentType(View clickedView) {
for (int i = 0; i < paymentTiles.size(); i++) {
PaymentTile t = paymentTiles.get(i);
t.isTop = t.view.getId() == clickedView.getId();
tileMap.put(t.view.getId(), t);
}
Integer tileId = null;
PaymentTile foundPaymentTile = null;
Integer foundIndex = null;
for (int i = 0; i < paymentTiles.size(); i++) {
PaymentTile current = paymentTiles.get(i);
if (current.view.getId() == clickedView.getId()) {
tileId = current.view.getId();
foundPaymentTile = current;
foundIndex = i;
break;
}
}
// If view was found
if (tileId != null && paymentTiles.size() != 0) {
renderAsHidden(root.getViewById(R.id.title_container));
renderToTop(foundPaymentTile.view);
displayPaymentFragment(foundPaymentTile);
if (tileCount > 1) {
if (tileId == paymentTiles.get(paymentTiles.size() - 1).view.getId()) {
//pick first as bottom
int bottomId = paymentTiles.get(0).view.getId();
renderToBottom(paymentTiles.get(0).view);
//hide other(s)
for (int i = 0; i < paymentTiles.size(); i++) {
PaymentTile t = paymentTiles.get(i);
if (clickedView.getId() != t.view.getId() && bottomId != t.view.getId()) {
renderAsHidden(t.view);
}
}
} else {
int bottomId = paymentTiles.get(foundIndex + 1).view.getId();
//pick next as bottom
renderToBottom(paymentTiles.get(foundIndex + 1).view);
//hide other(S)
for (int i = 0; i < paymentTiles.size(); i++) {
PaymentTile t = paymentTiles.get(i);
if (clickedView.getId() != t.view.getId() && bottomId != t.view.getId()) {
renderAsHidden(t.view);
}
}
}
}
}
}
private void displayPaymentFragment(final PaymentTile foundPaymentTile) {
View fragmentContainerLayout = root.getViewById(R.id.payment_fragment_container_layout);
if (fragmentContainerLayout == null) {
fragmentContainerLayout
= getLayoutInflater()
.inflate(R.layout.rave_sdk_payment_fragment_container_layout, root, false);
root.addView(fragmentContainerLayout);
fragmentContainerLayout
.findViewById(R.id.choose_another_payment_method_tv)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Event event = new ScreenMinimizeEvent("Payment Methods").getEvent();
event.setPublicKey(ravePayInitializer.getPublicKey());
eventLogger.logEvent(event);
showAllPaymentTypes();
}
});
}
if (ravePayInitializer.isStaging() && ravePayInitializer.getShowStagingLabel()) {
findViewById(R.id.stagingModeBannerLay).setVisibility(View.VISIBLE);
}
int topToBottomConstraint = ((ConstraintLayout.LayoutParams)
fragmentContainerLayout.getLayoutParams()).topToBottom;
int topToTopConstraint = ((ConstraintLayout.LayoutParams)
fragmentContainerLayout.getLayoutParams()).topToTop;
if (topToBottomConstraint != topGuide.getId() && topToTopConstraint != topGuide.getId()) {
setPaymentFragmentInPlace(fragmentContainerLayout, foundPaymentTile);
} else hideThenShowFragment(fragmentContainerLayout, foundPaymentTile);
}
private void hideThenShowFragment(final View fragmentContainerLayout, final PaymentTile paymentTile) {
fragmentContainerLayout.animate()
.setDuration(transitionDuration / 3)
.alpha(0.0f)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
addFragmentToLayout(paymentTile);
fragmentContainerLayout
.animate()
.setListener(null)
.setDuration(transitionDuration * 2 / 3)
.alpha(1.0f);
}
});
}
private void setPaymentFragmentInPlace(View fragmentContainerLayout, PaymentTile foundPaymentTile) {
ConstraintSet set = new ConstraintSet();
set.clone(root);
set.connect(fragmentContainerLayout.getId(), ConstraintSet.TOP, topGuide.getId(), ConstraintSet.TOP);
if (tileCount > 1)
set.connect(fragmentContainerLayout.getId(), ConstraintSet.BOTTOM, bottomGuide.getId(), ConstraintSet.BOTTOM);
else
set.connect(fragmentContainerLayout.getId(), ConstraintSet.BOTTOM, root.getId(), ConstraintSet.BOTTOM);
set.connect(fragmentContainerLayout.getId(), ConstraintSet.LEFT, root.getId(), ConstraintSet.LEFT);
set.connect(fragmentContainerLayout.getId(), ConstraintSet.RIGHT, root.getId(), ConstraintSet.RIGHT);
set.constrainWidth(fragmentContainerLayout.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
set.constrainHeight(fragmentContainerLayout.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
set.setVisibility(fragmentContainerLayout.getId(), ConstraintSet.VISIBLE);
addFragmentToLayout(foundPaymentTile);
if (tileCount == 1)
fragmentContainerLayout.findViewById(R.id.choose_another_payment_method_tv).setVisibility(View.GONE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
AutoTransition transition = new AutoTransition();
transition.setDuration(transitionDuration);
TransitionManager.beginDelayedTransition(root, transition);
set.applyTo(root);
} else {
set.applyTo(root);
}
}
private void addFragmentToLayout(PaymentTile foundPaymentTile) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
switch (foundPaymentTile.paymentType) {
case PAYMENT_TYPE_ACCOUNT:
transaction.replace(R.id.payment_fragment_container, new AccountFragment());
break;
case PAYMENT_TYPE_ACH:
transaction.replace(R.id.payment_fragment_container, new AchFragment());
break;
case PAYMENT_TYPE_BANK_TRANSFER:
transaction.replace(R.id.payment_fragment_container, new BankTransferFragment());
break;
case RaveConstants.PAYMENT_TYPE_CARD:
transaction.replace(R.id.payment_fragment_container, new CardFragment());
break;
case PAYMENT_TYPE_FRANCO_MOBILE_MONEY:
transaction.replace(R.id.payment_fragment_container, new FrancMobileMoneyFragment());
break;
case PAYMENT_TYPE_GH_MOBILE_MONEY:
transaction.replace(R.id.payment_fragment_container, new GhMobileMoneyFragment());
break;
case PAYMENT_TYPE_MPESA:
transaction.replace(R.id.payment_fragment_container, new MpesaFragment());
break;
case PAYMENT_TYPE_RW_MOBILE_MONEY:
transaction.replace(R.id.payment_fragment_container, new RwfMobileMoneyFragment());
break;
case PAYMENT_TYPE_UG_MOBILE_MONEY:
transaction.replace(R.id.payment_fragment_container, new UgMobileMoneyFragment());
break;
case PAYMENT_TYPE_UK:
transaction.replace(R.id.payment_fragment_container, new UkFragment());
break;
case PAYMENT_TYPE_BARTER:
transaction.replace(R.id.payment_fragment_container, new BarterFragment());
break;
case PAYMENT_TYPE_USSD:
transaction.replace(R.id.payment_fragment_container, new UssdFragment());
break;
case PAYMENT_TYPE_ZM_MOBILE_MONEY:
transaction.replace(R.id.payment_fragment_container, new ZmMobileMoneyFragment());
break;
case PAYMENT_TYPE_SA_BANK_ACCOUNT:
transaction.replace(R.id.payment_fragment_container, new SaBankAccountFragment());
break;
default:
Log.d("Adding Payment Fragment", "Payment type does not exist in payment types list");
render();// Show default view
return;
}
try {
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void renderToTop(View tv) {
ConstraintSet set = new ConstraintSet();
set.clone(root);
set.connect(tv.getId(), ConstraintSet.TOP, root.getId(), ConstraintSet.TOP);
set.connect(tv.getId(), ConstraintSet.BOTTOM, topGuide.getId(), ConstraintSet.TOP);
set.connect(tv.getId(), ConstraintSet.LEFT, root.getId(), ConstraintSet.LEFT);
set.connect(tv.getId(), ConstraintSet.RIGHT, root.getId(), ConstraintSet.RIGHT);
set.constrainWidth(tv.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
set.constrainHeight(tv.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
set.setVisibility(tv.getId(), ConstraintSet.VISIBLE);
View arrowIv = tv.findViewById(R.id.arrowIv2);
if (arrowIv != null)
arrowIv.animate().rotation(180f).setDuration(transitionDuration);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
AutoTransition transition = new AutoTransition();
transition.setDuration(transitionDuration);
TransitionManager.beginDelayedTransition(root, transition);
set.applyTo(root);
} else set.applyTo(root);
}
private void renderToBottom(View tv) {
ConstraintSet set = new ConstraintSet();
set.clone(root);
set.connect(tv.getId(), ConstraintSet.TOP, bottomGuide.getId(), ConstraintSet.BOTTOM);
set.connect(tv.getId(), ConstraintSet.BOTTOM, root.getId(), ConstraintSet.BOTTOM);
set.connect(tv.getId(), ConstraintSet.LEFT, root.getId(), ConstraintSet.LEFT);
set.connect(tv.getId(), ConstraintSet.RIGHT, root.getId(), ConstraintSet.RIGHT);
set.constrainWidth(tv.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
set.constrainHeight(tv.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
set.setVisibility(tv.getId(), ConstraintSet.VISIBLE);
View arrowIv = tv.findViewById(R.id.arrowIv2);
if (arrowIv != null) arrowIv.animate().rotation(0f).setDuration(transitionDuration);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
AutoTransition transition = new AutoTransition();
transition.setDuration(transitionDuration);
TransitionManager.beginDelayedTransition(root, transition);
set.applyTo(root);
} else
set.applyTo(root);
}
private void renderAsHidden(View view) {
renderAsHidden(view, false);
}
private void renderAsHidden(View view, Boolean fadeOut) {
if (view != null) {
ConstraintSet set = new ConstraintSet();
set.clone(root);
set.connect(view.getId(), ConstraintSet.TOP, root.getId(), ConstraintSet.TOP);
set.connect(view.getId(), ConstraintSet.BOTTOM, root.getId(), ConstraintSet.TOP);
set.connect(view.getId(), ConstraintSet.LEFT, root.getId(), ConstraintSet.LEFT);
set.connect(view.getId(), ConstraintSet.RIGHT, root.getId(), ConstraintSet.RIGHT);
set.constrainWidth(view.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
set.constrainHeight(view.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
if (fadeOut) set.setVisibility(view.getId(), ConstraintSet.GONE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
AutoTransition transition = new AutoTransition();
transition.setDuration(transitionDuration);
TransitionManager.beginDelayedTransition(root, transition);
set.applyTo(root);
} else {
set.applyTo(root);
}
}
}
private void generatePaymentTiles() {
ArrayList<Integer> orderedPaymentTypesList = ravePayInitializer.getOrderedPaymentTypesList();
// Reverse payment types order since payment types are added from the bottom
Collections.reverse(orderedPaymentTypesList);
tileCount = orderedPaymentTypesList.size();
if (tileCount > 8) paymentTilesTextSize = 18f;
else paymentTilesTextSize = 20f;
for (int index = 0; index < orderedPaymentTypesList.size(); index++)
addPaymentType(orderedPaymentTypesList.get(index));
}
private void addPaymentType(int paymentType) {
View tileView;
try {
tileView = createPaymentTileView(RaveConstants.paymentTypesNamesList.get(paymentType) + "");
} catch (Exception e) {
e.printStackTrace();
Log.d("Add payment type error", "Payment type doesn't exist.");
return;
}
PaymentTile paymentTile = new PaymentTile(tileView, paymentType, false);
paymentTiles.add(paymentTile);
tileView.setOnClickListener(onClickListener);
tileMap.put(tileView.getId(), paymentTile);
}
private View createPaymentTileView(String title) {
View tileView = getLayoutInflater().inflate(R.layout.rave_sdk_payment_type_tile_layout, root, false);
TextView tv2 = tileView.findViewById(R.id.rave_payment_type_title_textView);
tileView.setId(ViewCompat.generateViewId());
String fullTitle = "Pay with " + title;
SpannableStringBuilder sb = new SpannableStringBuilder(fullTitle);
sb.setSpan(new StyleSpan(Typeface.BOLD), 9, fullTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
tv2.setText(sb);
tv2.setTextSize(paymentTilesTextSize);
root.addView(tileView);
return tileView;
}
private void generateGuides(int count) {
for (int i = 0; i <= count; i++) {
Guideline guideline = createGuideline(this, HORIZONTAL);
root.addView(guideline);
double percent;
if (count > 8) percent = (1 - (0.07 * i));
else percent = (1 - (0.08 * i));
guideline.setGuidelinePercent((float) percent);
guideline.setTag(10 - i);
guidelineMap.put(10 - i, guideline);
}
}
private Guideline createGuideline(Context context, int orientation) {
Guideline guideline = new Guideline(context);
guideline.setId(ViewCompat.generateViewId());
ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(
ConstraintLayout.LayoutParams.WRAP_CONTENT,
ConstraintLayout.LayoutParams.WRAP_CONTENT
);
lp.orientation = orientation;
guideline.setLayoutParams(lp);
return guideline;
}
private void buildGraph() {
if (ravePayInitializer.isStaging()) {
BASE_URL = STAGING_URL;
} else {
BASE_URL = LIVE_URL;
}
RaveComponent raveComponent = DaggerRaveComponent.builder()
.deviceIdGetterModule(new DeviceIdGetterModule(new DeviceIdGetter(this).getDeviceId()))
.remoteModule(new RemoteModule(BASE_URL))
.eventLoggerModule(new EventLoggerModule())
.build();
raveUiComponent = DaggerRaveUiComponent.builder()
.androidModule(new AndroidModule(this))
.raveComponent(raveComponent).build();
raveUiComponent.inject(this);
}
@Override
public void onBackPressed() {
setRavePayResult(RavePayActivity.RESULT_CANCELLED, new Intent());
super.onBackPressed();
}
public void setRavePayResult(int result, Intent intent) {
if (result == RESULT_CANCELLED) {
Event event = new SessionFinishedEvent("Payment cancelled").getEvent();
event.setPublicKey(ravePayInitializer.getPublicKey());
eventLogger.logEvent(event);
} else if (result == RESULT_ERROR) {
Event event = new SessionFinishedEvent("Payment error").getEvent();
event.setPublicKey(ravePayInitializer.getPublicKey());
eventLogger.logEvent(event);
} else if (result == RESULT_SUCCESS) {
Event event = new SessionFinishedEvent("Payment successful").getEvent();
event.setPublicKey(ravePayInitializer.getPublicKey());
eventLogger.logEvent(event);
}
setResult(result, intent);
}
public RaveUiComponent getRaveUiComponent() {
return raveUiComponent;
}
public RavePayInitializer getRavePayInitializer() {
return ravePayInitializer;
}
public EventLogger getEventLogger() {
return eventLogger;
}
} |
package com.fastjavaframework.interceptor;
import java.lang.reflect.Method;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.fastjavaframework.UserSession;
import com.fastjavaframework.annotation.Approve;
import com.fastjavaframework.annotation.Create;
import com.fastjavaframework.annotation.Delete;
import com.fastjavaframework.annotation.Read;
import com.fastjavaframework.annotation.Update;
import com.fastjavaframework.annotation.Upload;
import com.fastjavaframework.util.CommonUtil;
/**
* 权限拦截器
* 方法上包含'@Create' '@Update' '@Delete' '@Read' '@Upload' '@Approve' 注解
* api路径包含库中open_id
* 满足以上条件则有权限
*/
public class AuthorityInterceptor extends HandlerInterceptorAdapter {
@Override
@Create
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
UserSession userSession = (UserSession)request.getSession().getAttribute("userSession");
if(null != userSession) {
//权限
Map<String,String> menuAuthority = userSession.getMenuAuthority();
//获取方法
HandlerMethod handlerMethod = (HandlerMethod)handler;
Method method = handlerMethod.getMethod();
//库中open_id(key)与api路径对比,并判断方法是否与相应的权限注解
for(String key : menuAuthority.keySet()) {
String value = menuAuthority.get(key);
if(request.getRequestURI().indexOf(key) != -1 && ("all".equals(value)
|| ("read".equals(value) && null != method.getAnnotation(Read.class))
|| ("create".equals(value) && null != method.getAnnotation(Create.class))
|| ("update".equals(value) && null != method.getAnnotation(Update.class))
|| ("delete".equals(value) && null != method.getAnnotation(Delete.class))
|| ("upload".equals(value) && null != method.getAnnotation(Upload.class))
|| ("Approve".equals(value) && null != method.getAnnotation(Approve.class)) )) {
return true;
}
}
}
CommonUtil.setResponseReturnValue(response, HttpServletResponse.SC_UNAUTHORIZED, "无权限进行此操作!");
return false;
}
}
|
package com.zzidc.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @ClassName BrowserSecurityConfig
* @Author chenxue
* @Description TODO
* @Date 2019/4/2 10:50
**/
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{
private UserAuthenticationSuccessHandler userAuthenticationSuccessHandler;
private UserFailureHander userFailureHander;
/*
* @Author chenxue
* @Description //配置了这个Bean以后,从前端传递过来的密码将被加密
* @Date 2019/4/2 17:16
* @Param []
* @return org.springframework.security.crypto.password.PasswordEncoder
**/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/index")
/*.successHandler(userAuthenticationSuccessHandler)
.failureHandler(userFailureHander)*/
.and()
.authorizeRequests()
.antMatchers("/login.html")
.permitAll()
.and().csrf().disable();
}
}
|
package com.thanhviet.userlistarchvm;
import android.app.Application;
import com.thanhviet.userlistarchvm.db.UserRoomDB;
public class BaseApp extends Application {
private static BaseApp self;
private AppExecutors mAppExecutors;
public static BaseApp getInstance() {
return self;
}
@Override
public void onCreate() {
super.onCreate();
self = this;
mAppExecutors = new AppExecutors();
}
public UserRoomDB getDatabase() {
return UserRoomDB.getInstance(this, mAppExecutors);
}
public UserRepository getRepository() {
return UserRepository.getInstance(getDatabase());
}
}
|
package com.perfectorial.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;
/**
* @author Reza Safarpour (rsafarpour1991@gmail.com) on 11/22/2015
*/
@Document
public class Product implements Entity{
@Id
private String id;
private String name;
private String publisher;
private String auther;
private List<String> tags;
@DBRef
private Category category;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getAuther() {
return auther;
}
public void setAuther(String auther) {
this.auther = auther;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controle;
import gui.InterfaceSoletrando;
import modelo.Contador;
import modelo.Partida;
import rede.AtorNetGames;
import rede.JogadaSoletrando;
/**
*
* @author Bisnaguete
*/
public class AtorJogador {
private InterfaceSoletrando janela;
private AtorNetGames netGames;
private Partida partida;
private Contador contador;
public static void main(String[] args) {
new AtorJogador();
}
public boolean conectar() {
boolean exito = false;
String idUsuario = janela.obterUsuario();
String servidor = janela.obterServidor();
exito = netGames.conectar(servidor, idUsuario);
if (exito) {
partida.setConectado(true);
netGames.solicitarInicio();
}
if (exito) {
janela.desabilitarConectar();
janela.habilitarDesistir();
janela.notificar("Conexão estabelecida com sucesso!");
return true;
} else {
janela.notificar("Conexão falhou!");
return false;
}
}
public void atualizarContador(int tempo) {
janela.atualizarContador(tempo);
}
public void confirmarPalavra() {
contador.interromper();
partida.setConfirmouPalavra();
boolean acertou = partida.verificarGrafia();
if (acertou) {
janela.notificar("Você acertou a palavra!");
} else {
janela.notificar("Você errou a palavra!");
}
partida.setAcerteiPalavra(acertou);
boolean primeiro = partida.isPrimeiroDaRodada();
if (!primeiro) {
partida.verificaVencedor();
}
enviarJogada();
janela.iniciarInterfaceEspera();
janela.limparTela();
janela.notificar("Sua vez de esperar!");
if (!primeiro) {
int venci = partida.getVencedor();
if (venci != 0) {
if (venci == -1) {
janela.notificar("Você venceu!");
} else {
janela.notificar("Você perdeu!");
}
finalizarJogo();
}
}
}
public AtorJogador() {
janela = new InterfaceSoletrando(this);
netGames = new AtorNetGames(this);
partida = new Partida();
janela.setVisible(true);
}
public void ouvirPalavra() {
boolean podeOuvir = partida.ouvirPalavra();
if (podeOuvir) {
janela.decrementaQuantVezesOuvir();
} else {
janela.notificar("Você já ouviu a palavra 3 vezes!");
}
}
public void receberSolicitacaoDeInicio(int posicao) {
partida.setPrimeiroDaRodada(posicao);
String nome = netGames.obterNomeAdversario(posicao);
partida.setNome(nome);
if (posicao == 1) {
nome = netGames.obterNomeAdversario(2);
} else {
nome = netGames.obterNomeAdversario(1);
}
partida.setNomeAdversario(nome);
janela.setNomeAdversario(nome);
if (posicao == 1) {
partida.setContadorRodada(-1);
iniciarVez();
contador = new Contador(this);
contador.start();
janela.notificar("Sua vez começou!");
} else {
partida.setContadorRodada(0);
janela.iniciarInterfaceEspera();
janela.notificar("Sua vez de esperar!");
}
}
private void iniciarVez() {
partida.iniciarVez();
String sinonimo = partida.getSinonimo();
String significado = partida.getSignificado();
String frase = partida.getFrase();
String nivelAtual = partida.getNivelAtual();
String rodadaAtual = partida.getRodadaAtual();
janela.iniciarInterfaceJogador(sinonimo, significado, frase, nivelAtual, rodadaAtual);
}
public void finalizarJogo() {
desconectar();
boolean conectado = partida.getConectado();
if (!conectado) {
janela.desabilitarControles();
janela.limparTela();
} else {
janela.notificar("Não foi possível finalizar o jogo!");
}
}
public void digitarLetra(char letra) {
partida.adicionarLetra(letra);
enviarJogada();
}
private void enviarJogada() {
JogadaSoletrando jogada = instanciarJogada();
netGames.enviarJogada(jogada);
}
private JogadaSoletrando instanciarJogada() {
return partida.instanciarJogada();
}
public void desistir() {
finalizarJogo();
}
public void receberJogada(JogadaSoletrando jogada) {
boolean confirmou = jogada.isConfirmouPalavra();
if (!confirmou) {
char caractere = jogada.getCaractere();
janela.addCaractereOponente(caractere);
} else {
if (partida.isPrimeiroDaRodada()) { //primeiro da rodada
int vencedor = jogada.getVencedor();
if (vencedor == 0) {
iniciarVez();
contador = new Contador(this);
contador.start();
janela.notificar("Sua vez começou!");
} else {
if (vencedor == 1) {
janela.notificar("Voce venceu!");
} else {
janela.notificar("Você perdeu!");
}
finalizarJogo();
}
} else { //segundo da rodada
partida.setAcertouOponente(jogada.isAcertou());
iniciarVez();
contador = new Contador(this);
contador.start();
janela.notificar("Sua vez começou!");
}
}
}
public void receberDesistencia() {
janela.notificar("Oponente desistiu!");
contador.interromper();
finalizarJogo();
}
public void desconectar() {
boolean exito = netGames.desconectar();
if(exito) {
partida.setConectado(false);
}
}
}
|
import edu.duke.*;
import org.apache.commons.csv.*;
/**
* Write a description of ParsingExportData here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class ParsingExportData {
public void countryInfo(CSVParser parser, String country){
for(CSVRecord record : parser){
String countryRecord = record.get("Country");
if(countryRecord.equals(country)) {
System.out.print(record.get("Country") + ": ");
System.out.print(record.get("Exports") + ": ");
System.out.println(record.get("Value (dollars)"));
}
}
}
public void listExportersTwoProducts(CSVParser parser, String exportItem1, String exportItem2){
for(CSVRecord record : parser){
String exports = record.get("Exports");
if(exports.contains(exportItem1)&&exports.contains(exportItem2)){
System.out.println(record.get("Country"));
}
}
}
public int numberOfExporters(CSVParser parser, String exportItem){
int count = 0;
for(CSVRecord record : parser){
String exports = record.get("Exports");
if(exports.contains(exportItem)){
count++;
}
}
return count;
}
public void bigExporters(CSVParser parser, String amount){
for(CSVRecord record : parser){
String value = record.get("Value (dollars)");
if(value.length() > amount.length()){
System.out.print(record.get("Country")+" ");
System.out.println(value);
}
}
}
public void tester(){
FileResource fr = new FileResource();
CSVParser parser = fr.getCSVParser();
String find ="Nauru";
System.out.println("1.");
countryInfo(parser, find);
parser = fr.getCSVParser();
System.out.println("2. list Exporter two products");
listExportersTwoProducts(parser,"cotton","flowers");
parser = fr.getCSVParser();
System.out.println("3. NumberOfExporter");
System.out.println(numberOfExporters(parser,"cocoa"));
parser = fr.getCSVParser();
System.out.println("4. big exporter");
bigExporters(parser,"$999,999,999,999");
}
}
|
package com.tencent.mm.plugin.sns.ui;
class SnsUploadUI$13 implements Runnable {
final /* synthetic */ SnsUploadUI ogU;
SnsUploadUI$13(SnsUploadUI snsUploadUI) {
this.ogU = snsUploadUI;
}
public final void run() {
1 1 = new 1(this);
if (SnsUploadUI.g(this.ogU) != null) {
SnsUploadUI.g(this.ogU).setOnDragListener(1);
}
}
}
|
package com.google.android.gms.c;
import java.util.Arrays;
public final class av$a$a extends ay<av$a$a> {
private static volatile av$a$a[] aZy;
public a aZz;
public int type;
public static final class a extends ay<a> {
public byte[] aZA;
public String aZB;
public double aZC;
public float aZD;
public long aZE;
public int aZF;
public int aZG;
public boolean aZH;
public com.google.android.gms.c.av.a[] aZI;
public av$a$a[] aZJ;
public String[] aZK;
public long[] aZL;
public float[] aZM;
public long aZN;
public a() {
this.aZA = bh.bas;
this.aZB = "";
this.aZC = 0.0d;
this.aZD = 0.0f;
this.aZE = 0;
this.aZF = 0;
this.aZG = 0;
this.aZH = false;
this.aZI = com.google.android.gms.c.av.a.qu();
this.aZJ = av$a$a.qv();
this.aZK = bh.baq;
this.aZL = bh.bam;
this.aZM = bh.ban;
this.aZN = 0;
this.aZY = null;
this.baj = -1;
}
public final void a(ax axVar) {
int i;
int i2 = 0;
if (!Arrays.equals(this.aZA, bh.bas)) {
byte[] bArr = this.aZA;
axVar.aB(1, 2);
axVar.dJ(bArr.length);
axVar.m(bArr);
}
if (!this.aZB.equals("")) {
axVar.e(2, this.aZB);
}
if (Double.doubleToLongBits(this.aZC) != Double.doubleToLongBits(0.0d)) {
double d = this.aZC;
axVar.aB(3, 1);
long doubleToLongBits = Double.doubleToLongBits(d);
axVar.dH(((int) doubleToLongBits) & 255);
axVar.dH(((int) (doubleToLongBits >> 8)) & 255);
axVar.dH(((int) (doubleToLongBits >> 16)) & 255);
axVar.dH(((int) (doubleToLongBits >> 24)) & 255);
axVar.dH(((int) (doubleToLongBits >> 32)) & 255);
axVar.dH(((int) (doubleToLongBits >> 40)) & 255);
axVar.dH(((int) (doubleToLongBits >> 48)) & 255);
axVar.dH(((int) (doubleToLongBits >> 56)) & 255);
}
if (Float.floatToIntBits(this.aZD) != Float.floatToIntBits(0.0f)) {
axVar.d(4, this.aZD);
}
if (this.aZE != 0) {
axVar.g(5, this.aZE);
}
if (this.aZF != 0) {
axVar.az(6, this.aZF);
}
if (this.aZG != 0) {
i = this.aZG;
axVar.aB(7, 0);
axVar.dJ(ax.dL(i));
}
if (this.aZH) {
axVar.s(8, this.aZH);
}
if (this.aZI != null && this.aZI.length > 0) {
for (be beVar : this.aZI) {
if (beVar != null) {
axVar.a(9, beVar);
}
}
}
if (this.aZJ != null && this.aZJ.length > 0) {
for (be beVar2 : this.aZJ) {
if (beVar2 != null) {
axVar.a(10, beVar2);
}
}
}
if (this.aZK != null && this.aZK.length > 0) {
for (String str : this.aZK) {
if (str != null) {
axVar.e(11, str);
}
}
}
if (this.aZL != null && this.aZL.length > 0) {
for (long g : this.aZL) {
axVar.g(12, g);
}
}
if (this.aZN != 0) {
axVar.g(13, this.aZN);
}
if (this.aZM != null && this.aZM.length > 0) {
while (i2 < this.aZM.length) {
axVar.d(14, this.aZM[i2]);
i2++;
}
}
super.a(axVar);
}
public final boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof a)) {
return false;
}
a aVar = (a) obj;
if (!Arrays.equals(this.aZA, aVar.aZA)) {
return false;
}
if (this.aZB == null) {
if (aVar.aZB != null) {
return false;
}
} else if (!this.aZB.equals(aVar.aZB)) {
return false;
}
return (Double.doubleToLongBits(this.aZC) == Double.doubleToLongBits(aVar.aZC) && Float.floatToIntBits(this.aZD) == Float.floatToIntBits(aVar.aZD) && this.aZE == aVar.aZE && this.aZF == aVar.aZF && this.aZG == aVar.aZG && this.aZH == aVar.aZH && bc.equals(this.aZI, aVar.aZI) && bc.equals(this.aZJ, aVar.aZJ) && bc.equals(this.aZK, aVar.aZK) && bc.equals(this.aZL, aVar.aZL) && bc.equals(this.aZM, aVar.aZM) && this.aZN == aVar.aZN) ? a(aVar) : false;
}
public final int hashCode() {
int hashCode = (this.aZB == null ? 0 : this.aZB.hashCode()) + ((Arrays.hashCode(this.aZA) + 527) * 31);
long doubleToLongBits = Double.doubleToLongBits(this.aZC);
return (((((((((((((((this.aZH ? 1231 : 1237) + (((((((((((hashCode * 31) + ((int) (doubleToLongBits ^ (doubleToLongBits >>> 32)))) * 31) + Float.floatToIntBits(this.aZD)) * 31) + ((int) (this.aZE ^ (this.aZE >>> 32)))) * 31) + this.aZF) * 31) + this.aZG) * 31)) * 31) + bc.hashCode(this.aZI)) * 31) + bc.hashCode(this.aZJ)) * 31) + bc.hashCode(this.aZK)) * 31) + bc.hashCode(this.aZL)) * 31) + bc.hashCode(this.aZM)) * 31) + ((int) (this.aZN ^ (this.aZN >>> 32)))) * 31) + qF();
}
protected final int pU() {
int i;
int i2;
be beVar;
int i3 = 0;
int pU = super.pU();
if (!Arrays.equals(this.aZA, bh.bas)) {
byte[] bArr = this.aZA;
pU += (bArr.length + ax.dK(bArr.length)) + ax.dI(1);
}
if (!this.aZB.equals("")) {
pU += ax.f(2, this.aZB);
}
if (Double.doubleToLongBits(this.aZC) != Double.doubleToLongBits(0.0d)) {
pU += ax.dI(3) + 8;
}
if (Float.floatToIntBits(this.aZD) != Float.floatToIntBits(0.0f)) {
pU += ax.dI(4) + 4;
}
if (this.aZE != 0) {
pU += ax.h(5, this.aZE);
}
if (this.aZF != 0) {
pU += ax.aA(6, this.aZF);
}
if (this.aZG != 0) {
pU += ax.dK(ax.dL(this.aZG)) + ax.dI(7);
}
if (this.aZH) {
pU += ax.dI(8) + 1;
}
if (this.aZI != null && this.aZI.length > 0) {
i = 0;
while (true) {
i2 = pU;
if (i >= this.aZI.length) {
break;
}
beVar = this.aZI[i];
if (beVar != null) {
i2 += ax.b(9, beVar);
}
pU = i + 1;
}
pU = i2;
}
if (this.aZJ != null && this.aZJ.length > 0) {
i = 0;
while (true) {
i2 = pU;
if (i >= this.aZJ.length) {
break;
}
beVar = this.aZJ[i];
if (beVar != null) {
i2 += ax.b(10, beVar);
}
pU = i + 1;
}
pU = i2;
}
if (this.aZK != null && this.aZK.length > 0) {
i2 = 0;
int i4 = 0;
for (String str : this.aZK) {
if (str != null) {
i4++;
i2 += ax.bu(str);
}
}
pU = (pU + i2) + (i4 * 1);
}
if (this.aZL != null && this.aZL.length > 0) {
i = 0;
while (true) {
i2 = i3;
if (i >= this.aZL.length) {
break;
}
i2 += ax.ad(this.aZL[i]);
i3 = i + 1;
}
pU = (pU + i2) + (this.aZL.length * 1);
}
if (this.aZN != 0) {
pU += ax.h(13, this.aZN);
}
return (this.aZM == null || this.aZM.length <= 0) ? pU : (pU + (this.aZM.length * 4)) + (this.aZM.length * 1);
}
}
public av$a$a() {
this.type = 1;
this.aZz = null;
this.aZY = null;
this.baj = -1;
}
public static av$a$a[] qv() {
if (aZy == null) {
synchronized (bc.bai) {
if (aZy == null) {
aZy = new av$a$a[0];
}
}
}
return aZy;
}
public final void a(ax axVar) {
axVar.az(1, this.type);
if (this.aZz != null) {
axVar.a(2, this.aZz);
}
super.a(axVar);
}
public final boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof av$a$a)) {
return false;
}
av$a$a av_a_a = (av$a$a) obj;
if (this.type != av_a_a.type) {
return false;
}
if (this.aZz == null) {
if (av_a_a.aZz != null) {
return false;
}
} else if (!this.aZz.equals(av_a_a.aZz)) {
return false;
}
return a(av_a_a);
}
public final int hashCode() {
return (((this.aZz == null ? 0 : this.aZz.hashCode()) + ((this.type + 527) * 31)) * 31) + qF();
}
protected final int pU() {
int pU = super.pU() + ax.aA(1, this.type);
return this.aZz != null ? pU + ax.b(2, this.aZz) : pU;
}
}
|
/**
* Provides useful methods for manipulating a phrase.
*
* @author Ben Godfrey
* @version 08 DEC 2017
*/
public class Phrase {
/** The phrase to be manipulated */
private String currentPhrase;
/** Constructs a new Phrase object. */
public Phrase(String p) {
this.currentPhrase = p;
}
/**
* Returns the index of the nth occurrence of str in the current phrase.
*
* @param str The string to search for.
* @param n Which occurrence to search for.
* @return The index of the occurrence, -1 if nonexistant.
*/
public int findNthOccurrence(String str, int n) {
int index = 0;
int counter = 0;
do {
index = currentPhrase.indexOf(str, index);
if (index == -1) {
return -1;
}
counter++;
index++;
} while(counter < n);
return index - 1;
}
/**
* Replaces the Nth occurrence of a string with something else.
*
* @param str The string to be replaced.
* @param n Which occurrence to replace.
* @param repl The string to replace with.
*/
public void replaceNthOccurrence(String str, int n, String repl) {
int nthIndex = findNthOccurrence(str, n);
if (nthIndex != -1) {
String prefix = currentPhrase.substring(0, nthIndex);
String suffix = currentPhrase.substring(nthIndex + str.length(), currentPhrase.length());
currentPhrase = prefix + repl + suffix;
}
}
/**
* Finds the last occurrence of a string in the phrase.
*
* @param str The string to search for.
* @return The index of the last occurrence.
*/
public int findLastOccurrence(String str) {
int index = -1;
int counter = 1;
boolean foundLast = false;
do {
int currentIndex = findNthOccurrence(str, counter);
if (currentIndex == -1 || counter > 10) {
foundLast = true;
} else {
counter++;
index = currentIndex;
}
} while (!foundLast);
return index;
}
/**
* This object, as a String!
*
* @return A String representation of this object.
*/
public String toString() {
return currentPhrase;
}
} |
package ua.addicted.assetwand.models;
/**
* Created by addicted on 12.03.16.
*/
public class ReceiptEntry {
private Receipt receipt;
private String entryString;
private String originalTitle;
private String title;
private int quantity;
private double price;
public ReceiptEntry(Receipt receipt, String entryString) {
this.receipt = receipt;
this.entryString = entryString;
}
public Receipt getReceipt() {
return receipt;
}
public void setReceipt(Receipt receipt) {
this.receipt = receipt;
}
public String getEntryString() {
return entryString;
}
public void setEntryString(String entryString) {
this.entryString = entryString;
}
public String getOriginalTitle() {
return originalTitle;
}
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ReceiptEntry that = (ReceiptEntry) o;
if (!receipt.equals(that.receipt)) return false;
return entryString.equals(that.entryString);
}
@Override
public int hashCode() {
int result = receipt.hashCode();
result = 31 * result + entryString.hashCode();
return result;
}
}
|
package com.tencent.mm.network;
import com.tencent.mars.mm.MMLogic;
import com.tencent.mm.sdk.platformtools.bd;
class t$11 extends bd<Object> {
final /* synthetic */ String esM;
final /* synthetic */ String esN;
final /* synthetic */ t esu;
t$11(t tVar, String str, String str2) {
this.esu = tVar;
this.esM = str;
this.esN = str2;
super(1000, null, (byte) 0);
}
protected final Object run() {
MMLogic.setNewDnsDebugHost(this.esM, this.esN);
return null;
}
}
|
package edu.nju.logic.impl;
import edu.nju.data.dao.DocumentDAO;
import edu.nju.data.dao.WikiDAO;
import edu.nju.logic.service.RelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Created by cuihao on 2016/7/20.
*/
@Component
public class RelationImpl implements RelationService {
@Autowired
private WikiDAO wikiDAO;
@Autowired
private DocumentDAO documentDAO;
@Override
public List getRelatedDocByWiki(long wikiId) {
return wikiDAO.getRelatedDocuments(wikiId);
}
@Override
public List getRelatedQuestionByWiki(long wikiId) {
return wikiDAO.getRelatedQuestions(wikiId);
}
@Override
public List getRelatedWikiByDoc(long docId) {
return documentDAO.getRelatedWikis(docId);
}
@Override
public List getRelatedQuestionByDoc(long docId) {
return documentDAO.getRelatedQuestions(docId);
}
}
|
package com.stayready.assessment.week2.part01;
public class BasicStringUtils {
/**
* @param string1 - Base string to be added to
* @param string2 - String to add to `string1`
* @return concatenation of `string1` and `string2`
*/
public static String concatentate(String string1, String string2)
{
String newString = string1+ string2;
return newString;
}
/**
* @param string1 - String to be reversed
* @return an identical string with characters in reverse order
*/
public static String reverse(String string1) {
StringBuilder input1 = new StringBuilder();
input1.append(string1);
input1 = input1.reverse();
return input1.toString();
}
/**
* @param string1 - first string to be reversed
* @param string2 - second string to be reversed
* @return concatenation of the reverse of `string1` and reverse of `string2`
*/
public static String reverseThenConcatenate(String string1, String string2) {
StringBuilder input1 = new StringBuilder();
input1.append(string1);
input1 = input1.reverse();
StringBuilder input2 = new StringBuilder();
input2.append(string2);
input2 = input2.reverse();
return input1.append(input2).toString();
}
/**
* @param string - the string to be manipulated
* @param charactersToRemove - Characters that should be removed from `string`
* @return `string` with `charactersToRemove` removed
*/
public static String removeCharacters(String string, String charactersToRemove) {
String newString = "";
String newerString = "";
for(int i = 0; i < charactersToRemove.length(); i++){
newString = charactersToRemove.substring(i, i+1);
string = string.replaceAll(newString, "");
newString = "";
}
return string;
}
/**
* @param string - the string to be manipulated
* @param charactersToRemove - characters to be removed from the string
* @return reverse of `string` with `charactersToRemove` removed
*/
public static String removeCharactersThenReverse(String string, String charactersToRemove) {
String newString = "";
String newerString = "";
for(int i = 0; i < charactersToRemove.length(); i++){
newString = charactersToRemove.substring(i, i+1);
string = string.replaceAll(newString, "");
newString = "";
}
StringBuilder input1 = new StringBuilder();
input1.append(string);
input1 = input1.reverse();
return input1.toString();
}
}
|
package models;
import javafx.animation.TranslateTransition;
import javafx.scene.shape.Rectangle;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.util.Duration;
public class Element extends Rectangle {
private final Color color = Color.valueOf("#ADD8E6");
private final double width=40;
private int CurrentPosition;
private int value;
public int getCurrentPosition() {
return CurrentPosition;
}
public void setCurrentPosition(int currentPosition) {
CurrentPosition = currentPosition;
}
public Element(int value,int position) {
setValue(value);
setCurrentPosition(position);
this.setFill(color);
this.setWidth(width);
this.setHeight(value/100+50);
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
|
package cs5387;
/* <<author name redacted >>
purpose of this program is to provide sort functions for Tables
Version 1.0
*/
public class tableSorter{
public boolean isSorted(Table t){
int range = t.getSize();
int prevVal=t.getTableValue(0,0); //prevVal is to compare to the previous element as follows
for(int i=0; i<range; i++) //For each row
for(int j=1;j<range;j++) //for each column
if(prevVal > t.getTableValue(i,j)) //if previous value is greater than current, Not sorted
return false;
else
prevVal=t.getTableValue(i,j); //else, lets update prevVal!
return true; //Made it this far, table is sorted!
}
public static int totalOps;
public int getTotalOps(){
return totalOps;
}
public static void sortable(Table t){
int range = t.getSize();
int[] tempArr = new int[range*range]; //Make an array with elements of the table for better sorting
int k=0;
totalOps=7; //7 assignments including this one and setting i=0 next line!
for(int i=0; i<range; i++){
totalOps+=3; //3 operations to compare and increment and j=0 below line
for(int j=0;j<range;j++){
totalOps+=2; //2 operations to compare and increment
tempArr[k++]=t.getTableValue(i,j); //Populate our temporary array
totalOps+=3; //3 operations to increment k, index into tempArr, and to index into table(i,j)
}
}
tempArr=bubbleSort(tempArr); //Bubble sort our temporary array!
k=0;
totalOps+=3; //3 lines above the call and assignment, and i=0 below
for(int i=0; i<range; i++){
totalOps+=3; //Compare and increment i, and j=0 below
for(int j=0;j<range;j++){
totalOps+=2; //Compare and increment
t.setTableValue(i,j,tempArr[k++]); //Update the table with sorted values
totalOps+=3; //increment k, index into tempArr, index into table (i,j) to set the value
}
}
return;
}
private static int[] bubbleSort(int[] inArr){ //Bubble sort algorithm
int n = inArr.length;
totalOps+=2; //Assign n above, and assign i to 0 below
for (int i = 0; i < n-1; i++){
totalOps+=3; //compare i, increment i above, j=0 below
for (int j = 0; j < n-i-1; j++){
totalOps+=2; //compare j, increment j above
if (inArr[j] > inArr[j+1]){
totalOps+=1; //Compare above
int temp = inArr[j];
inArr[j] = inArr[j+1];
inArr[j+1] = temp;
totalOps+=3; //3 assignments above
}
}
}
return inArr;
}
}
|
package com.zcc.contactapp.server.db.mybatis.controller;
import com.zcc.contactapp.server.dao.ContactInfo;
import com.zcc.contactapp.server.db.mybatis.service.MybatisService;
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.RestController;
/**
* Created by cc on 2019/9/3.
*/
@RestController
@RequestMapping("/mybatis")
public class MybatisController {
@Autowired
MybatisService mybatisService;
@RequestMapping("/getinfo")
public ContactInfo getInfo(Long id) {
return mybatisService.getInfo(id);
}
}
|
package com.jim.multipos.ui.reports.summary_report;
import com.jim.multipos.config.scope.PerFragment;
import dagger.Binds;
import dagger.Module;
@Module
public abstract class SummaryReportPresenterModule {
@Binds
@PerFragment
abstract SummaryReportPresenter provideSummaryReportPresenter(SummaryReportPresenterImpl salesReportPresenter);
}
|
package com.youthchina.util.permission;
import com.youthchina.domain.zhongyang.User;
/**
* Created by zhongyangwu on 5/24/19.
*/
public interface HasOwner {
default User getOwner() {
User user = new User();
user.setId(this.getOwnerId());
return user;
}
Integer getOwnerId();
}
|
package com.zilker.taxi.bean;
/*
* Personal details of customer.
*/
public class Customer {
private String firstName;
private String lastName;
private String mailId;
public Customer() {}
public Customer(String firstName, String lastName, String mailId) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.mailId = mailId;
}
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 getMailId() {
return mailId;
}
public void setMailId(String mailId) {
this.mailId = mailId;
}
}
|
package example;
import org.springframework.data.repository.CrudRepository;
public interface ExportLogRepository extends CrudRepository<ExportLog, Integer> {
}
|
package com.epam.restaurant.service;
import com.epam.restaurant.dao.exception.DaoException;
import com.epam.restaurant.dao.factory.SqlDaoFactory;
import com.epam.restaurant.dao.impl.CategorySqlDao;
import com.epam.restaurant.dao.impl.DishSqlDao;
import com.epam.restaurant.entity.Category;
import com.epam.restaurant.entity.Dish;
import com.epam.restaurant.service.exception.ServiceException;
import com.epam.restaurant.util.ValidationUtil;
import java.util.List;
/**
* Perform service operations with category object.
*/
public class CategoryService {
/**
* Dao for category dao objects
*/
private static final CategorySqlDao categoryDao = (CategorySqlDao) SqlDaoFactory.getInstance().getDao(SqlDaoFactory.DaoType.CATEGORY);
/**
* Dao for dish dao objects
*/
private static final DishSqlDao dishDao = (DishSqlDao) SqlDaoFactory.getInstance().getDao(SqlDaoFactory.DaoType.DISH);
private static CategoryService instance = new CategoryService();
private CategoryService() {
}
public static CategoryService getInstance() {
return instance;
}
/**
* Get all categories from data source
*
* @return list of all categories from data source
* @throws ServiceException
*/
public List<Category> getAllCategories() throws ServiceException {
try {
return categoryDao.getAll();
} catch (DaoException e) {
throw new ServiceException("CategoryServiceException", e);
}
}
/**
* Get category from data source with specific id
*
* @param id category id
* @return category with this id
* @throws ServiceException
*/
public Category getById(Long id) throws ServiceException {
try {
return categoryDao.getByPK(id);
} catch (DaoException e) {
throw new ServiceException("CategoryService Exception", e);
}
}
/**
* Get all dishes from current category
*
* @param categoryId category id
* @return dishes from with category
* @throws ServiceException
*/
public List<Dish> getAllFromCategory(long categoryId) throws ServiceException {
try {
return dishDao.getAllFromCategory(categoryId);
} catch (DaoException e) {
throw new ServiceException("CategoryService Exception", e);
}
}
/**
* Get category from data source with specific name
*
* @param name category name
* @return category
* @throws ServiceException
*/
public Category getByName(String name) throws ServiceException {
try {
return categoryDao.getByName(name);
} catch (DaoException e) {
throw new ServiceException("CategoryService Exception", e);
}
}
/**
* Create new record in data source with specific params
*
* @param name category name
* @param description category description
* @return created category object
* @throws ServiceException
*/
public Category create(String name, String description) throws ServiceException {
Category category = new Category(name, description);
try {
if (ValidationUtil.categoryValid(category)) {
return categoryDao.persist(category);
} else {
throw new ServiceException("CategoryService Exception");
}
} catch (DaoException e) {
throw new ServiceException("CategoryService Exception", e);
}
}
/**
* Update record in data source for specific category
*
* @param category category to update
* @throws ServiceException
*/
public void update(Category category) throws ServiceException {
try {
if (ValidationUtil.categoryValid(category)) {
categoryDao.update(category);
} else {
throw new ServiceException("CategoryService Exception");
}
} catch (DaoException e) {
throw new ServiceException("CategoryService Exception", e);
}
}
/**
* Remove record from data source for specific category
*
* @param category category to remove
* @throws ServiceException
*/
public void delete(Category category) throws ServiceException {
try {
categoryDao.delete(category);
} catch (DaoException e) {
throw new ServiceException("CategoryService Exception", e);
}
}
}
|
package twilight.bgfx.buffers;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
/**
*
* @author tmccrary
*
*/
public class TransientIndexBuffer {
long data;
long size;
int handleId;
long startIndex;
public long pointer;
/**
*
* @return
*/
public ByteBuffer getData() {
ByteBuffer buffer = nGetData();
buffer = buffer.order(ByteOrder.nativeOrder());
return buffer;
}
public ShortBuffer getShortData() {
return getData().asShortBuffer();
}
public native ByteBuffer nGetData();
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.Closeable;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.Socket;
import org.apache.commons.net.io.CopyStreamEvent;
import org.apache.commons.net.io.CopyStreamListener;
import org.apache.commons.net.io.Util;
import org.junit.Assert;
import org.junit.Test;
public class UtilTest {
static class CSL implements CopyStreamListener {
final long expectedTotal;
final int expectedBytes;
final long expectedSize;
CSL(final long totalBytesTransferred, final int bytesTransferred, final long streamSize) {
this.expectedTotal = totalBytesTransferred;
this.expectedBytes = bytesTransferred;
this.expectedSize = streamSize;
}
@Override
public void bytesTransferred(final CopyStreamEvent event) {
}
@Override
public void bytesTransferred(final long totalBytesTransferred, final int bytesTransferred, final long streamSize) {
Assert.assertEquals("Wrong total", expectedTotal, totalBytesTransferred);
Assert.assertEquals("Wrong streamSize", expectedSize, streamSize);
Assert.assertEquals("Wrong bytes", expectedBytes, bytesTransferred);
}
}
// Class to check overall counts as well as batch size
static class CSLtotal implements CopyStreamListener {
final long expectedTotal;
final long expectedBytes;
volatile long totalBytesTransferredTotal;
volatile long bytesTransferredTotal;
CSLtotal(final long totalBytesTransferred, final long bytesTransferred) {
this.expectedTotal = totalBytesTransferred;
this.expectedBytes = bytesTransferred;
}
@Override
public void bytesTransferred(final CopyStreamEvent event) {
}
@Override
public void bytesTransferred(final long totalBytesTransferred, final int bytesTransferred, final long streamSize) {
Assert.assertEquals("Wrong bytes", expectedBytes, bytesTransferred);
this.totalBytesTransferredTotal = totalBytesTransferred;
this.bytesTransferredTotal += bytesTransferred;
}
void checkExpected() {
Assert.assertEquals("Wrong totalBytesTransferred total", expectedTotal, totalBytesTransferredTotal);
Assert.assertEquals("Total should equal sum of parts", totalBytesTransferredTotal, bytesTransferredTotal);
}
}
private final Writer dest = new CharArrayWriter();
private final Reader source = new CharArrayReader(new char[] { 'a' });
private final InputStream src = new ByteArrayInputStream(new byte[] { 'z' });
private final OutputStream dst = new ByteArrayOutputStream();
@Test
public void testcloseQuietly() {
Util.closeQuietly((Closeable) null);
Util.closeQuietly((Socket) null);
}
@Test
public void testNET550_Reader() throws Exception {
final char[] buff = { 'a', 'b', 'c', 'd' }; // must be multiple of 2
final int bufflen = buff.length;
{ // Check buffer size 1 processes in chunks of 1
final Reader rdr = new CharArrayReader(buff);
final CSLtotal listener = new CSLtotal(bufflen, 1);
Util.copyReader(rdr, dest, 1, 0, listener); // buffer size 1
listener.checkExpected();
}
{ // Check bufsize 2 uses chunks of 2
final Reader rdr = new CharArrayReader(buff);
final CSLtotal listener = new CSLtotal(bufflen, 2);
Util.copyReader(rdr, dest, 2, 0, listener); // buffer size 2
listener.checkExpected();
}
{ // Check bigger size reads the lot
final Reader rdr = new CharArrayReader(buff);
final CSLtotal listener = new CSLtotal(bufflen, bufflen);
Util.copyReader(rdr, dest, 20, 0, listener); // buffer size 20
listener.checkExpected();
}
{ // Check negative size reads reads full amount
final Reader rdr = new CharArrayReader(buff);
final CSLtotal listener = new CSLtotal(bufflen, bufflen);
Util.copyReader(rdr, dest, -1, 0, listener); // buffer size -1
listener.checkExpected();
}
{ // Check zero size reads reads full amount
final Reader rdr = new CharArrayReader(buff);
final CSLtotal listener = new CSLtotal(bufflen, bufflen);
Util.copyReader(rdr, dest, 0, 0, listener); // buffer size -1
listener.checkExpected();
}
}
@Test
public void testNET550_Stream() throws Exception {
final byte[] buff = { 'a', 'b', 'c', 'd' }; // must be multiple of 2
final int bufflen = buff.length;
{ // Check buffer size 1 processes in chunks of 1
final InputStream is = new ByteArrayInputStream(buff);
final CSLtotal listener = new CSLtotal(bufflen, 1);
Util.copyStream(is, dst, 1, 0, listener); // buffer size 1
listener.checkExpected();
}
{ // Check bufsize 2 uses chunks of 2
final InputStream is = new ByteArrayInputStream(buff);
final CSLtotal listener = new CSLtotal(bufflen, 2);
Util.copyStream(is, dst, 2, 0, listener); // buffer size 2
listener.checkExpected();
}
{ // Check bigger size reads the lot
final InputStream is = new ByteArrayInputStream(buff);
final CSLtotal listener = new CSLtotal(bufflen, bufflen);
Util.copyStream(is, dst, 20, 0, listener); // buffer size 20
listener.checkExpected();
}
{ // Check negative size reads reads full amount
final InputStream is = new ByteArrayInputStream(buff);
final CSLtotal listener = new CSLtotal(bufflen, bufflen);
Util.copyStream(is, dst, -1, 0, listener); // buffer size -1
listener.checkExpected();
}
{ // Check zero size reads reads full amount
final InputStream is = new ByteArrayInputStream(buff);
final CSLtotal listener = new CSLtotal(bufflen, bufflen);
Util.copyStream(is, dst, 0, 0, listener); // buffer size -1
listener.checkExpected();
}
}
@Test
public void testReader_1() throws Exception {
final long streamSize = 0;
final int bufferSize = -1;
Util.copyReader(source, dest, bufferSize, streamSize, new CSL(1, 1, streamSize));
}
@Test
public void testReader0() throws Exception {
final long streamSize = 0;
final int bufferSize = 0;
Util.copyReader(source, dest, bufferSize, streamSize, new CSL(1, 1, streamSize));
}
@Test
public void testReader1() throws Exception {
final long streamSize = 0;
final int bufferSize = 1;
Util.copyReader(source, dest, bufferSize, streamSize, new CSL(1, 1, streamSize));
}
@Test
public void testStream_1() throws Exception {
final long streamSize = 0;
final int bufferSize = -1;
Util.copyStream(src, dst, bufferSize, streamSize, new CSL(1, 1, streamSize));
}
@Test
public void testStream0() throws Exception {
final long streamSize = 0;
final int bufferSize = 0;
Util.copyStream(src, dst, bufferSize, streamSize, new CSL(1, 1, streamSize));
}
@Test
public void testStream1() throws Exception {
final long streamSize = 0;
final int bufferSize = 1;
Util.copyStream(src, dst, bufferSize, streamSize, new CSL(1, 1, streamSize));
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package subsystems;
import commands.NetDisable;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.command.Subsystem;
import robot.RobotMap;
/**
* NOT USED
* @author Ben
*/
// NOT USED
public class Net extends Subsystem
{
DigitalInput _netDeployed;
DigitalInput _netStowed;
double _deploySpeed;
double _stowSpeed;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand()
{
setDefaultCommand(new NetDisable());
}
public Net()
{
super("Net");
_netDeployed = new DigitalInput(RobotMap.Digital.Input.netDeployed);
_netStowed = new DigitalInput(RobotMap.Digital.Input.netStowed);
}
public void deploy()
{
if(deployed())
{
setOutputs(0.0);
}
else
{
setOutputs(_deploySpeed);
}
}
public void stow()
{
if(stowed())
{
setOutputs(0.0);
}
else
{
setOutputs(_stowSpeed);
}
}
private boolean stowed()
{
return _netStowed.get();
}
private boolean deployed()
{
return _netDeployed.get();
}
private void setOutputs(double value)
{
}
}
|
package com.ev.q3;
import java.util.HashSet;
public class ScatterPalindrome {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1="abaaa";
HashSet<String> hs= scatterPalindromes(s1);
System.out.println(hs);
}
private static HashSet<String> scatterPalindromes(String s1) {
HashSet<String> result = new HashSet<>();
for (int i = 0; i < s1.length(); i++) {
for (int j = i + 1; j <= s1.length(); j++) {
if (truePalindrome(s1.substring(i, j))) {
result.add(s1.substring(i, j));
}
}
}
return result;
}
private static boolean truePalindrome(String substring) {
StringBuffer str1 = new StringBuffer(substring);
StringBuffer str2 = str1.reverse();
return (str2.toString()).equals(substring);
}
}
|
package com.acme.paymentserver.dto;
import lombok.*;
import java.io.Serializable;
import java.util.List;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ResponseErrorDTO implements Serializable {
private List<String> erros;
} |
package servlets.Admin;
import entities.Asset;
import entities.Results;
import persistence.AssetDao;
import servlets.BaseServlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Alex
* 6/26/2016
*/
@WebServlet(
name = "grainForm",
urlPatterns = {"/admin/grain/*", "/admin/grain", "/admin/grain/"}
)
public class GrainFormServlet extends BaseServlet {
/**
* Handles HTTP GET requests.
*
* @param request the HttpServletRequest object
* @param response the HttpServletResponse object
* @throws ServletException if there is a Servlet failure
* @throws IOException if there is an IO failure
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String assetId = request.getPathInfo();
String content = "/admin/assetForm.jsp";
String title = "";
String button = "";
if (assetId == null) {
title = "New Grain Form";
button = "Submit";
} else if (!assetId.equals("")) {
AssetDao dao = (AssetDao) getServletContext().getAttribute("assetDao");
Asset asset = dao.getRecordById(Integer.parseInt(assetId.substring(1)));
if (asset == null) {
Results results = new Results();
results.setType("Error");
results.addMessage("Grain with id of " + assetId.substring(1) + " does not exist.");
title = "New Grain Form";
button = "Submit";
content = "error.jsp";
request.setAttribute("results", results);
} else if (asset.getType().toLowerCase().equals("grain")) {
request.setAttribute("asset", asset);
title = asset.getName() + "Grain Update Form";
button = "Update";
} else {
Results results = new Results();
results.setType("Error");
results.addMessage("Asset with id of " + assetId.substring(1) + " is not a grain.");
title = "New Grain Form";
button = "Submit";
content = "error.jsp";
request.setAttribute("results", results);
}
}
request.setAttribute("type", "grain");
request.setAttribute("button", button);
servletResponse(request, response, title, content);
}
/**
* Handles HTTP POST requests.
*
* @param request the HttpServletRequest object
* @param response the HttpServletResponse object
* @throws ServletException if there is a Servlet failure
* @throws IOException if there is an IO failure
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("assetName");
String currentStock = request.getParameter("currentStock");
String description = request.getParameter("description");
String assetId = request.getPathInfo();
Results results = new Results();
AssetDao dao = (AssetDao) getServletContext().getAttribute("assetDao");
Asset asset = new Asset();
if (assetId != null) {
if (!assetId.equals("")) {
asset = dao.getRecordById(Integer.parseInt(assetId.substring(1)));
}
} else {
assetId = "";
}
asset.setName(name);
asset.setDescription(description);
asset.setCurrentStock(Float.parseFloat(currentStock));
asset.setType("grain");
if (dao.addOrUpdateRecord(asset)) {
results.setSuccess(true);
if (assetId.equals("")) {
results.setType("Grain was added");
} else {
results.setType("Grain was updated");
}
} else {
if (assetId.equals("")) {
results.setType("Failed to add Grain");
} else {
results.setType("Failed to update Grain");
}
}
request.setAttribute("results", results);
doGet(request, response);
}
}
|
package de.hso.sem.rw;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.document.Document;
import org.apache.lucene.store.MMapDirectory;
import org.apache.tika.exception.TikaException;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.language.detect.LanguageHandler;
import org.apache.tika.language.detect.LanguageResult;
import org.apache.tika.metadata.DublinCore;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.TeeContentHandler;
import org.apache.tika.sax.ToTextContentHandler;
import org.xml.sax.SAXException;
import javax.enterprise.context.ApplicationScoped;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApplicationScoped
public class FullTextIndex {
private Analyzer analyzer = new StandardAnalyzer();
private Directory directory;
private static final String DOCUMENT_BLOB_ID = "id";
private static final String DOCUMENT_MIME = "mime";
private static final String DOCUMENT_TITLE = "title";
private static final String DOCUMENT_AUTHOR = "author";
private static final String DOCUMENT_DATE = "date";
private static final String DOCUMENT_LANGUAGE = "lang";
private static final String DOCUMENT_CONTENT = "content";
public FullTextIndex() {
try {
directory = new MMapDirectory(Path.of("luceneIndex"));
} catch (IOException e) {
e.printStackTrace();
}
}
private IndexWriterConfig createIndexWriterConfig() {
return new IndexWriterConfig(analyzer);
}
public void add(Path path, Long id) throws IOException, TikaException, SAXException {
System.out.println("adding "+path+" id="+id+" to repo.");
AutoDetectParser parser = new AutoDetectParser();
ToTextContentHandler toTextContentHandler = new ToTextContentHandler();
LanguageHandler languageHandler = new LanguageHandler();
Metadata metadata = new Metadata();
// Analyze using Tika
InputStream is = TikaInputStream.get(path);
parser.parse(is, new TeeContentHandler(toTextContentHandler, languageHandler), metadata, new ParseContext());
is.close();
LanguageResult languageResult = languageHandler.getLanguage();
// Write to Lucene
IndexWriter indexWriter = new IndexWriter(directory, createIndexWriterConfig());
Document document = new Document();
document.add(new StringField(DOCUMENT_BLOB_ID, id.toString(), Field.Store.YES));
document.add(new TextField(DOCUMENT_CONTENT, toTextContentHandler.toString(), Field.Store.YES));
if(languageResult.isReasonablyCertain()) {
document.add(new StringField(DOCUMENT_LANGUAGE, languageResult.getLanguage(), Field.Store.YES));
}
Map<String, String> map = new HashMap<>();
map.put(Metadata.CONTENT_TYPE, DOCUMENT_MIME);
map.put(DublinCore.TITLE.getName(), DOCUMENT_TITLE);
map.put(DublinCore.CREATOR.getName(), DOCUMENT_AUTHOR);
map.put(DublinCore.DATE.getName(), DOCUMENT_DATE);
for(Map.Entry<String, String> e : map.entrySet()) {
String value = metadata.get(e.getKey());
if(value != null) {
document.add(new StringField(e.getValue(),value, Field.Store.YES));
}
}
indexWriter.addDocument(document);
indexWriter.close();
}
public IndexDocument get(int id) throws IOException {
IndexWriter indexWriter = new IndexWriter(directory, createIndexWriterConfig());
IndexReader reader = DirectoryReader.open(indexWriter);
IndexSearcher searcher = new IndexSearcher(reader);
Document doc = searcher.doc(id);
IndexDocument indexDocument = new IndexDocument(id, doc);
indexWriter.close();
return indexDocument;
}
public List<QueryResult> query(String query) throws ParseException, IOException, InvalidTokenOffsetsException {
Query q;
if(query.trim().length() > 0) {
q = new QueryParser(DOCUMENT_CONTENT, analyzer).parse(query);
} else {
q = new MatchAllDocsQuery();
}
return query(q);
}
public List<QueryResult> query(Query q) throws IOException, InvalidTokenOffsetsException {
IndexWriter indexWriter = new IndexWriter(directory, createIndexWriterConfig());
IndexReader reader = DirectoryReader.open(indexWriter);
IndexSearcher searcher = new IndexSearcher(reader);
TopDocs docs = searcher.search(q, 25);
SimpleHTMLFormatter htmlFormatter = new SimpleHTMLFormatter();
Highlighter highlighter = new Highlighter(htmlFormatter, new QueryScorer(q));
ArrayList<QueryResult> results = new ArrayList<>();
for(ScoreDoc doc : docs.scoreDocs) {
Document d = searcher.doc(doc.doc);
String content = d.get(DOCUMENT_CONTENT);
TokenStream tokenStream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), doc.doc, DOCUMENT_CONTENT, analyzer);
TextFragment[] frag = highlighter.getBestTextFragments(tokenStream, content, true, 3);
String snippedHtml = Stream.of(frag)
.map(TextFragment::toString)
.collect(Collectors.joining(" ... "));
results.add(new QueryResult(
new IndexDocument(doc.doc, d),
snippedHtml
));
}
indexWriter.close();
return results;
}
public static class IndexDocument {
private final int id;
private final Long blobId;
private final String mime;
private final String title;
private final String author;
private final String date;
private final String lang;
public IndexDocument(int id, Document document) {
this.id = id;
this.blobId = Long.valueOf(document.get(DOCUMENT_BLOB_ID));
this.mime = document.get(DOCUMENT_MIME);
this.title = document.get(DOCUMENT_TITLE);
this.author = document.get(DOCUMENT_AUTHOR);
this.date = document.get(DOCUMENT_DATE);
this.lang = document.get(DOCUMENT_LANGUAGE);
}
public int getId() {
return id;
}
public Long getBlobId() {
return blobId;
}
public String getMime() {
return mime;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getDate() {
return date;
}
public String getLang() {
return lang;
}
}
public static class QueryResult {
private final IndexDocument document;
private final String snippedHtml;
public QueryResult(IndexDocument document, String snippedHtml) {
this.document = document;
this.snippedHtml = snippedHtml;
}
public IndexDocument getDocument() {
return document;
}
public String getSnippedHtml() {
return snippedHtml;
}
}
}
|
package ru.javabegin.training.webservices.testservice;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
@WebService(serviceName = "TestWS")
public class TestWS {
@WebMethod(operationName = "correctName")
public String correctName(@WebParam(name = "name") String name) {
return "My name is "+name;
}
}
|
package kr.co.sist.mgr.room.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import kr.co.sist.mgr.room.vo.MgrRoomInfoVO;
import kr.co.sist.mgr.room.vo.MgrRoomListVO;
import kr.co.sist.mgr.room.vo.MgrRoomModifyVO;
import kr.co.sist.mgr.room.vo.MgrRoomVO;
public class MgrRoomDAO {
private static MgrRoomDAO mgrRoomDAO;
public MgrRoomDAO() {
}
public static MgrRoomDAO getInstance() {
if(mgrRoomDAO == null) {
mgrRoomDAO = new MgrRoomDAO();
}//end if
return mgrRoomDAO;
}//getInstance
private Connection getConn() throws SQLException{
Connection con=null;
//1. JNDI 사용객체 생성
try {
Context ctx = new InitialContext();
//2. DBCP에서 DB연결 객체 얻기.
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/luna_dbcp");
//3. Connection 얻기
con=ds.getConnection();
} catch (NamingException e) {
e.printStackTrace();
}//end catch
return con;
}//getConn
/**
* 룸 정보 넣기
* @param mrVO
* @throws SQLException
*/
public void insertRoomInfo(MgrRoomVO mrVO) throws SQLException {
Connection con=null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con=getConn();
StringBuilder insertRoomInfo= new StringBuilder();
insertRoomInfo
.append(" insert into room_info( room_name, room_num ) ")
.append(" values(?,?) ");
pstmt=con.prepareStatement(insertRoomInfo.toString());
pstmt.setString(1, mrVO.getRoomName());
pstmt.setInt(2, mrVO.getRoomNum());
rs=pstmt.executeQuery();
pstmt.close();
StringBuilder insertRoomType = new StringBuilder();
insertRoomType
.append(" insert into room_type( room_num, room_name, room_size, price, max_guest, amenity, room_intro, img1, img2, img3, img4, img5) ")
.append(" values(?,?,?,?,?,?,?,?,?,?,?,?) ");
pstmt=con.prepareStatement(insertRoomType.toString());
pstmt.setInt(1, mrVO.getRoomNum());
pstmt.setString(2, mrVO.getRoomName());
pstmt.setString(3, mrVO.getRoomSize());
pstmt.setInt(4, mrVO.getPrice());
pstmt.setInt(5, mrVO.getMaxGuest());
pstmt.setString(6, mrVO.getAmenity());
pstmt.setString(7, mrVO.getIntro());
pstmt.setString(8, mrVO.getImg1());
pstmt.setString(9, mrVO.getImg2());
pstmt.setString(10, mrVO.getImg3());
pstmt.setString(11, mrVO.getImg4());
pstmt.setString(12, mrVO.getImg5());
pstmt.executeUpdate();
pstmt.close();
con.setAutoCommit(false);
StringBuilder insertRoomCnt = new StringBuilder();
insertRoomCnt
.append(" insert into room_info(room_name, room_num) ")
.append(" values(?, seq_room_num.nextval) ");
pstmt=con.prepareStatement(insertRoomCnt.toString());
pstmt.setString(1, mrVO.getRoomName());
for(int i=0; i<mrVO.getRoomCnt()-1; i++) {
pstmt.executeUpdate();
}//end for
con.commit();
con.setAutoCommit(true);
}finally {
if(rs != null) {rs.close();}
if(pstmt != null) {pstmt.close();}
if(con != null) {con.close();}
}//end catch
}//insertRoomInfo
/**
* (룸 관리 처음화면)모든 룸을 리스트로 출력
* @return
* @throws SQLException
*/
public List<String> selectAllRoom() throws SQLException{
List<String> allRoomList = new ArrayList<String>();
Connection con=null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con=getConn();
pstmt=con.prepareStatement("select room_name from room_type");
rs=pstmt.executeQuery();
while(rs.next()) {
allRoomList.add(rs.getString("room_name"));
}//end while
}finally {
if(rs != null) {rs.close();}
if(pstmt != null) {pstmt.close();}
if(con != null) {con.close();}
}//end catch
return allRoomList;
}//selectAllMember
/**
* 룸 선택
* @param roomName
* @return
* @throws SQLException
*/
public MgrRoomListVO[] selectRoomList(String roomName) throws SQLException{
MgrRoomListVO[] mrlList = null;
Connection con=null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con=getConn();
// 방 갯수가 총 몇개인지 알기 위해 select query로 조회
StringBuilder selectRoomList= new StringBuilder();
selectRoomList.append(" select count(*) roomCnt from room_info where room_name=? ");
pstmt=con.prepareStatement(selectRoomList.toString());
pstmt.setString(1, roomName);
rs = pstmt.executeQuery();
int roomCnt = 0;
if(rs.next()) {
roomCnt = rs.getInt("roomCnt");
}
mrlList = new MgrRoomListVO[roomCnt];
// 쿼리 다시 날리기 위해 초기화
rs.close();
pstmt.close();
selectRoomList.setLength(0);
selectRoomList
.append(" select room_name, available, room_num ")
.append(" from room_info ")
.append(" where room_name=? ");
pstmt=con.prepareStatement(selectRoomList.toString());
pstmt.setString(1, roomName);
rs=pstmt.executeQuery();
int index=0;
while(rs.next()) {
mrlList[index] = new MgrRoomListVO(rs.getString("room_name"), rs.getString("available"), rs.getInt("room_num"));
index++;
}//end while
}finally {
if(rs != null) {rs.close();}
if(pstmt != null) {pstmt.close();}
if(con != null) {con.close();}
}//end catch
return mrlList;
}//selectAllMember
/**
* 룸수정 눌렀을 때 룸 정보 변경
* @param mrmVO
* @return
* @throws SQLException
*/
public boolean updateRoomInfo(MgrRoomModifyVO mrmVO) throws SQLException {
boolean flag = false;
Connection con=null;
PreparedStatement pstmt = null;
try {
con=getConn();
StringBuilder updateInfo= new StringBuilder();
updateInfo
.append(" update room_type ")
.append(" set room_size=?, price=?, max_guest=?, amenity=?, room_intro=?, img1=?,img2=?, img3=?, img4=?, img5=? ")
.append(" where room_name=? ");
pstmt=con.prepareStatement(updateInfo.toString());
pstmt.setString(1, mrmVO.getRoomSize());
pstmt.setInt(2, mrmVO.getPrice());
pstmt.setInt(3, mrmVO.getMaxGuest());
pstmt.setString(4, mrmVO.getAmenity());
pstmt.setString(5, mrmVO.getIntro());
pstmt.setString(6, mrmVO.getImg1());
pstmt.setString(7, mrmVO.getImg2());
pstmt.setString(8, mrmVO.getImg3());
pstmt.setString(9, mrmVO.getImg4());
pstmt.setString(10, mrmVO.getImg5());
pstmt.setString(11, mrmVO.getRoomName());
flag=pstmt.executeUpdate() == 1;
}finally {
if(pstmt != null) {pstmt.close();}
if(con != null) {con.close();}
}//end catch
return flag;
}//updateRoomInfo
/**
* 방 비활성화 여부를 업데이트
* @param flag
* @return
* @throws SQLException
*/
//메소드에서 List로 받아서 뿌리기
public int updateRoomDisable(List<MgrRoomInfoVO> mrInfoVO) throws SQLException{
int cnt = 0;
Connection con=null;
PreparedStatement pstmt = null;
try {
con=getConn();
// 여러 쿼리를 update 하기 위해 auto commit 잠시 false로 변경
con.setAutoCommit(false);
String chkDisable=" update room_info set available=? where room_num=? ";
for(int i=0; i<mrInfoVO.size(); i++) {
pstmt=con.prepareStatement(chkDisable);
MgrRoomInfoVO mrInfo = mrInfoVO.get(i);
if(mrInfo.isInfoFlag()) {
pstmt.setString(1, "T");
}else {
pstmt.setString(1, "F");
}//end else
pstmt.setInt(2, mrInfo.getInfoRoomNum());
cnt+=pstmt.executeUpdate();
pstmt.close();
}//end for
con.commit();
con.setAutoCommit(true);
}finally {
if(pstmt != null) {pstmt.close();}
if(con != null) {con.close();}
}//end catch
return cnt;
}//updateRoomDisable
/**
*
* 방 상세페이지 조회
* @param roomName
* @return
* @throws SQLException
*/
public MgrRoomVO selectRoomInfo(String roomName) throws SQLException {
MgrRoomVO mrVO = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConn();
StringBuilder sb = new StringBuilder();
sb.append("select amenity, room_size, max_guest, price, room_intro, input_date, room_num,")
.append(" img1, img2, img3, img4, img5 ")
.append(" from room_type where room_name=?");
pstmt = conn.prepareStatement(sb.toString());
pstmt.setString(1, roomName);
rs = pstmt.executeQuery();
if(rs.next()) {
mrVO = new MgrRoomVO();
mrVO.setRoomName(roomName);
mrVO.setAmenity(rs.getString("amenity"));
mrVO.setRoomInputDate(rs.getString("input_date"));
mrVO.setIntro(rs.getString("room_intro"));
mrVO.setRoomSize(rs.getString("room_size"));
mrVO.setImg1(rs.getString("img1"));
mrVO.setImg2(rs.getString("img2"));
mrVO.setImg3(rs.getString("img3"));
mrVO.setImg4(rs.getString("img4"));
mrVO.setImg5(rs.getString("img5"));
mrVO.setMaxGuest(rs.getInt("max_guest"));
mrVO.setPrice(rs.getInt("price"));
mrVO.setRoomNum(rs.getInt("room_num"));
//count 필요
rs.close();
pstmt.close();
sb.setLength(0);
sb.append("select count(*) room_cnt from room_info where room_name=?");
pstmt = conn.prepareStatement(sb.toString());
pstmt.setString(1, roomName);
rs = pstmt.executeQuery();
if(rs.next()) {
int roomCnt = rs.getInt("room_cnt");
mrVO.setRoomCnt(roomCnt);
}
}
} finally{
if(rs != null) {
rs.close();
}
if(pstmt != null) {
pstmt.close();
}
if(conn != null) {
conn.close();
}
}
return mrVO;
}
}//class
|
package com.tefper.daas.parque.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
import lombok.Data;
@Entity
@Table(name = "APPILIMITADA")
@IdClass(AppsIlimitadaIdentity.class)
@Data
public class AppsIlimitada {
@Id
@Column(name = "ID")
private String id;
@Id
@Column(name = "NAME")
private String name;
}
|
package edu.curd.dto;
import edu.curd.operation.JDBCDataObject;
public class TeacherDTO implements JDBCDataObject {
private int teacherId;
private String userName;
private String password;
private String timeStamp;
public TeacherDTO() {
}
public TeacherDTO(int teacherId,
String userName,
String password,
String timeStamp) {
this.teacherId = teacherId;
this.userName = userName;
this.password = password;
this.timeStamp = timeStamp;
}
public int getTeacherId() {
return teacherId;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTeacherId(int teacherId) {
this.teacherId = teacherId;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
}
|
package com.company.Exceptions;
public class CannotFindMealException extends Exception {
public CannotFindMealException() {
super("Meal Not Found ! \n Try another meal");
}
}
|
import java.util.Scanner;
public class String_typ{
public static void main(String args[]){
String str="envelope book";
System.out.println(str.replace('e','a'));
System.out.println(str.replaceFirst("envelope","Cover"));
System.out.println(str.replaceAll("envelope","book"));
System.out.println(str.contains("u"));
System.out.println(str.substring(1,2));
System.out.println(str.concat("execution"));
System.out.println(str.charAt(9));
}
}
|
package com.deltastuido.project.interfaces;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import com.deltastuido.project.Project;
import com.deltastuido.project.domain.ProjectKeyValue;
import com.deltastuido.shared.IdGenerator;
import com.deltastuido.shared.KeyValue;
import com.deltastuido.store.domain.Sku;
import com.deltastuido.store.domain.SkuAttributeValue;
import com.deltastuido.store.domain.SkuKeyValue;
import com.deltastuido.store.domain.Spu;
import com.deltastuido.store.domain.SpuAttribute;
/**
*
* @author zhnag
*
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ProjectDetails {
@XmlTransient
private IdGenerator idGenerator;
private CatalogueEnum catalogue;
private String name;
private BigDecimal price;
private int targetSales;
private int fundraisingDays;
private String blurb;
private String assure;
private List<SkuDetails> skus;
/**
* rest参数对象不能有带参数的构造方法,使用factory模式。
*
* @param project
* @return details
*/
public static ProjectDetails build(Project project) {
ProjectDetails details = new ProjectDetails();
// details.name = project.getTheName();
// details.price = project.getSpu().getPrice();
// details.targetSales = project.getTargetSales();
//
// Timestamp expired = project.getTimeExpired();
// Timestamp now = Timestamp.from(Instant.now());
//
// if (expired.before(now)) {
// details.fundraisingDays = 0;
// } else {
// Duration d = Duration.between(expired.toInstant(), now.toInstant());
// details.fundraisingDays = (int) d.get(ChronoUnit.DAYS);
// }
//
// Map<String, ProjectKeyValue> kvs = project.getProjectKeyValues();
// details.blurb = kvs.get("blurb").getTheValue();
// details.assure = kvs.get("assure").getTheValue();
//
// details.skus = new ArrayList<>();
// for (Sku sku : project.getSpu().getSkus()) {
// SkuDetails d = SkuDetails.build(sku);
// details.skus.add(d);
// }
return details;
}
public Project extractProject() {
Timestamp now = Timestamp.from(Instant.now());
String id = idGenerator.generateId("project");
// Project project = new Project();
// project.setIncome(BigDecimal.ZERO);
// project.setSaledNumber(0);
// project.setId(id);
// project.setTheName(name);
// Instant expired = now.toInstant().plus(fundraisingDays,
// ChronoUnit.DAYS);
// project.setTimeCreated(now);
// project.setTimeExpired(Timestamp.from(expired));
// project.setTargetSales(targetSales);
// project.setProjectKeyValues(extractProjectKeyValues());
//
// Spu spu = extractSpu();
//
// project.setSpu(spu);
// return project;
return null;
}
private List<SpuAttribute> getSpuAttributes(Spu spu) {
List<SpuAttribute> spuAttributes = new ArrayList<>();
Set<String> theAttribute = new HashSet<>();
for (SkuDetails sku : skus) {
for (KeyValue kv : sku.getAttributeValues()) {
theAttribute.add(kv.getKey());
}
}
for (String attrName : theAttribute) {
SpuAttribute sa = new SpuAttribute();
sa.setTheName(attrName);
sa.setSpuBean(spu);
spuAttributes.add(sa);
}
return spuAttributes;
}
private Spu extractSpu() {
Timestamp now = Timestamp.from(Instant.now());
Spu spu = new Spu();
String spuId = idGenerator.generateId("spu");
spu.setId(spuId);
spu.setProductName(name);
spu.setPrice(price);
spu.setTimeCreated(now);
spu.setTimeLastModified(now);
spu.setSpuAttributes(getSpuAttributes(spu));
// 暂时没有key value列表
spu.setSkus(extractSkus(spu));
return spu;
}
private void setSkuAvs(SkuDetails detail, Spu spu, Sku sku) {
for (KeyValue kv : detail.getAttributeValues()) {
sku.getAttributeValuesMap().put(kv.getKey(), new SkuAttributeValue(
spu, sku.getId(), kv.getKey(), kv.getValue()));
}
}
private void setSkuKvs(SkuDetails detail, Sku sku) {
for (KeyValue kv : detail.getKeyValues()) {
sku.getKeyValuesMap().put(kv.getKey(),
new SkuKeyValue(sku.getId(), kv.getKey(), kv.getValue()));
}
}
public List<Sku> extractSkus(Spu spu) {
Timestamp now = Timestamp.from(Instant.now());
List<Sku> skuEntitys = new ArrayList<>();
for (SkuDetails s : skus) {
String id = idGenerator.generateId("sku");
Sku skuEntity = new Sku();
skuEntity.setSpu(spu.getId());
skuEntity.setId(id);
skuEntity.setPrice(price);
skuEntity.setTimeCreated(now);
skuEntity.setTimeLastModified(now);
setSkuAvs(s, spu, skuEntity);
setSkuKvs(s, skuEntity);
skuEntitys.add(skuEntity);
}
return skuEntitys;
}
private Map<String, ProjectKeyValue> extractProjectKeyValues() {
Map<String, ProjectKeyValue> kvs = new HashMap<>();
ProjectKeyValue kv = new ProjectKeyValue();
kv.setTheKey("blurb");
kv.setTheValue(blurb);
kvs.put(kv.getTheKey(), kv);
kv = new ProjectKeyValue();
kv.setTheKey("assure");
kv.setTheValue(assure);
kvs.put(kv.getTheKey(), kv);
return kvs;
}
public CatalogueEnum getCatalogue() {
return catalogue;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price;
}
public int getTargetSales() {
return targetSales;
}
public int getFundraisingDays() {
return fundraisingDays;
}
public String getBlurb() {
return blurb;
}
public String getAssure() {
return assure;
}
public List<SkuDetails> getSkus() {
return skus;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + fundraisingDays;
result = prime * result + ((assure == null) ? 0 : assure.hashCode());
result = prime * result + ((blurb == null) ? 0 : blurb.hashCode());
result = prime * result
+ ((catalogue == null) ? 0 : catalogue.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + targetSales;
result = prime * result + ((price == null) ? 0 : price.hashCode());
result = prime * result + ((skus == null) ? 0 : skus.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProjectDetails other = (ProjectDetails) obj;
if (fundraisingDays != other.fundraisingDays)
return false;
if (assure == null) {
if (other.assure != null)
return false;
} else if (!assure.equals(other.assure))
return false;
if (blurb == null) {
if (other.blurb != null)
return false;
} else if (!blurb.equals(other.blurb))
return false;
if (catalogue != other.catalogue)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (targetSales != other.targetSales)
return false;
if (price == null) {
if (other.price != null)
return false;
} else if (!price.equals(other.price))
return false;
if (skus == null) {
if (other.skus != null)
return false;
} else if (!skus.equals(other.skus))
return false;
return true;
}
public IdGenerator getIdGenerator() {
return idGenerator;
}
public void setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
public void setCatalogue(CatalogueEnum catalogue) {
this.catalogue = catalogue;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public void setTargetSales(int targetSales) {
this.targetSales = targetSales;
}
public void setFundraisingDays(int fundraisingDays) {
this.fundraisingDays = fundraisingDays;
}
public void setBlurb(String blurb) {
this.blurb = blurb;
}
public void setAssure(String assure) {
this.assure = assure;
}
public void setSkus(List<SkuDetails> skus) {
this.skus = skus;
}
}
|
package com.snow.weevideo.module.attention;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.snow.weevideo.R;
import me.yokeyword.fragmentation.SupportFragment;
/**
* @user steven
* @createDate 2019/6/24 16:51
* @description 自定义
*/
public class AttentionMainFragment extends SupportFragment {
public static AttentionMainFragment getInstance(String title) {
AttentionMainFragment attentionMainFragment = new AttentionMainFragment();
Bundle bundle = new Bundle();
bundle.putString("title", title);
attentionMainFragment.setArguments(bundle);
return attentionMainFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_attention_main, null);
return view;
}
@Override
public void onLazyInitView(Bundle savedInstanceState) {
super.onLazyInitView(savedInstanceState);
}
}
|
package com.korea.mvc17.dao;
import java.util.ArrayList;
import com.koreait.mvc17.dto.BoardDto;
public interface BoardDao {
public ArrayList<BoardDto> list(); // list 메소드명
public BoardDto view(int bIdx);
public int modify(String bTitle, String bContent, int bIdx);
public int write(String bWriter, String bTitle, String bContent);
public int delete(int bIdx);
}
|
package net.cupmouse.minecraft.eplugin.music;
import com.flowpowered.math.vector.Vector3d;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.world.Location;
public final class NoteLayer {
private final NoteSound[] ticks;
private float volume = 1F;
public NoteLayer(NoteSound[] notesounds) {
ticks = notesounds;
}
public NoteSound getNote(int tick) {
return ticks[tick];
}
public float getVolume() {
return volume;
}
public void playOn(int tick, Location loc) {
NoteSound s;
if ((s = ticks[tick]) != null) s.playOn(loc, volume);
}
public void playOnlyFor(int tick, Player player) {
NoteSound s;
if ((s = ticks[tick]) != null) s.playOnlyFor(player, volume);
}
public void playOnOnlyFor(int tick, Vector3d pos, Player player) {
NoteSound s;
if ((s = ticks[tick]) != null) s.playOnOnlyFor(player, pos, volume);
}
}
|
package com.hb.javacad.panel;
import java.awt.Color;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ShapeButton extends JToggleButton implements ChangeListener{
/**
*
*/
private static final long serialVersionUID = -3745730381292760462L;
public ShapeButton(){
this.addChangeListener(this);
}
public void stateChanged(ChangeEvent e) {
if(this.isSelected()){
this.setForeground(Color.red);
}else{
this.setForeground(Color.black);
}
}
}
|
package rs.code9.taster.repository;
import java.util.List;
import rs.code9.taster.model.Question;
/**
* Question JPA access layer interface.
*
* @author s.bogdanovic
* @author r.zuljevic
*/
public interface QuestionRepository extends BaseRepository<Question> {
/**
* Find and return questions by category id.
*
* @param id
* the category id
* @return list of questions from a category
*/
List<Question> findQuestionsByCategoryId(Long id);
/**
* Find and return questions by test id.
*
* @param id
* the test id
* @return list of questions from the test
*/
List<Question> findQuestionsByTestId(Long id);
}
|
package aws_social.social;
import org.testng.annotations.Test;
import actions.Actions;
import objectrepository.Social.Global;
import objectrepository.Social.POM_Posts;
import resusablemethods.RU_Login_Logout;
import resusablemethods.RU_Posts;
import testdata.ConfigData;
import testdata.TestData;
import utility.Utility;
public class TS10_Comments_13507_13508_13509 extends Utility
{
String usr1=ConfigData.USER1;
String usr2=ConfigData.USER2;
String usr3=ConfigData.USER3;
String pwd=ConfigData.PASSWORD;
String srchuser2=ConfigData.srchuser2;
String srchuser1=ConfigData.srchuser1;
String object_connected=TestData.prvcy_dropdpwn_Connected;
String obj_public=TestData.prvcy_dropdpwn_public;
String obj_tagged=TestData.prvcy_dropdpwn_taggedUsrGrp;
String pstmsg=TestData.Txt_posttext;
String sharetext=TestData.Txt_Sharetext;
String tagatRate=TestData.typeattherate;
String tagusrMatch=ConfigData.taguser;
String count=TestData.Count;
String comment=TestData.AdComment;
@Test
public void AddComment() throws Exception
{
try
{
new Actions(Utility.driver);
Global.login_Env(usr1, pwd);
RU_Posts.NewPost(pstmsg);
RU_Posts.EditPost();
RU_Posts.EnterComment(comment);
RU_Posts.sendcomment();
Actions.pause(3);
Actions.mobile_StoreandMatch(POM_Posts.tvComments, count);
RU_Posts.DeleteComment();
}
catch(Exception e)
{
System.out.println("enable:Force Logout ");
System.out.println(e.getMessage());
RU_Login_Logout.forceLogout();
}
}
@Test(dependsOnMethods="AddComment")
public void Comments_TaggedUser() throws Exception{
try{
new Actions(Utility.driver);
RU_Posts.Comments_TaggedUser(tagatRate, srchuser2);
RU_Posts.sendcomment();
Actions.pause(4);
RU_Posts.clicktaguser();
RU_Posts.backtoprevious();
RU_Posts.backtoprevious();
RU_Posts.DeletePost();
RU_Login_Logout.CloudLogout();
}
catch(Exception e)
{
System.out.println("enable:Force Logout ");
System.out.println(e.getMessage());
RU_Login_Logout.forceLogout();
}
}
}
|
package Zad2;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Kolejki {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Queue<Integer> tenNumbersQueue = new LinkedList<>();
for (int i = 0; i < 10; i++) {
System.out.println("Podaj liczbe nr " + (i + 1));
int x = scanner.nextInt();
tenNumbersQueue.offer(x);
}
int sum = 0;
while (tenNumbersQueue.peek() != null) {
sum += tenNumbersQueue.peek();
System.out.print(tenNumbersQueue.poll() + "+");
}
System.out.print("=" + sum);
// int sum = 0;
// for(Integer num: tenNumbersQueue){
// System.out.print(num+"+");
// sum += num;
// }
// System.out.println("="+sum);
}
}
|
package LessonsJavaCore_3;
import static MyClassesToWork.Print.print;
public class LessonCircleMain {
public static void main(String[] args){
print ( "ведіть радіус" );
LessonCircle circle = new LessonCircle ();
circle.scanner.nextLine ();
print ( "діаметер - " + circle.diameter () );
print ("площа - " + circle.area () );
print ( "довжина - " + circle.length () );
}
}
|
package ladder.DynamicProgrammingII;
/**
* Given a string s and a dictionary of words dict, determine if s can be break into
* a space-separated sequence of one or more dictionary words.
*
* Given s = "leetcode", dict = ["leet", "code"].
* Return true because "lintcode" can be break as "lint code".
*/
public class WordBreak {
/**
* @param s: A string s
* @param dict: A dictionary of words dict
*/
public boolean wordBreak(String s, Set<String> dict) {
if (s == null || s.length() == 0) {
return true;
}
boolean[] isWord = new boolean[s.length() + 1];
isWord[0] = true;
int maxLen = getMaxLength(dict);
for (int i = 1; i <= s.length(); i++) {
isWord[i] = false;
// 通常word不会很长,只取到最长的word长度即可
for (int wordLength = 1; wordLength <= maxLen && wordLength <= i; wordLength++) {
// if f[j] == false, 不用取substring
if (!isWord[i - wordLength]) {
continue;
}
String word = s.substring(i - wordLength, i);
// 找到一个true,直接break
if (dict.contains(word)) {
isWord[i] = true;
break;
}
}
}
return isWord[s.length()];
}
private int getMaxLength(Set<String> dict) {
int max = 0;
for (String word : dict) {
if (word.length() > max) {
max = word.length();
}
}
return max;
}
}
|
package com.mantisclaw.italianpride15.ridesharehome;
import java.net.URLEncoder;
/**
* Created by italianpride15 on 2/22/15.
*/
public class UberRideModel extends BaseRideModel {
private static final String uber_client_id = "XikKX8YmAoiTaE4PxmvKK2xImKtMFKIG";
private static final String uber_server_token = "p4xGiso2Lt5slHGTHSg9fHRgJMT0OUmsn5ksrJw3";
private static final String uber_base_url = "https://api.uber.com/v1/estimates/price?";
private static final String deepLink = "com.ubercab";
private static final String query = "uber://?client_id=" + uber_client_id + "&action=setPickup&pickup=my_location";
UberRideModel(UserModel user) {
client_id = uber_client_id;
deepLinkAppName = deepLink;
StringBuilder requestString = new StringBuilder();
requestString.append(uber_base_url);
requestString.append("start_latitude=");
requestString.append(user.currentLatitude);
requestString.append("&start_longitude=");
requestString.append(user.currentLongitude);
requestString.append("&end_latitude=");
requestString.append(user.homeLatitude);
requestString.append("&end_longitude=");
requestString.append(user.homeLongitude);
requestURL = requestString.toString();
StringBuilder queryString = new StringBuilder();
queryString.append(query);
queryString.append("&dropoff[latitude]=" + user.homeLatitude);
queryString.append("&dropoff[longitude]=" + user.homeLongitude);
try {
queryString.append("&dropoff[formatted_address]=" + URLEncoder.encode(user.homeAddress, "UTF-8").toString().replace("+", "%20"));
} catch (Exception e) {}
deepLinkQuery = queryString.toString() ;
drawableImageResource = "uber";
serviceName = "Uber";
}
public static String getUber_server_token() {
return uber_server_token;
}
}
|
package fr.pederobien.uhc.commands.configuration.edit.editions.configurations.hungergame;
import fr.pederobien.uhc.commands.configuration.edit.editions.CommonDelete;
import fr.pederobien.uhc.dictionary.dictionaries.MessageCode;
import fr.pederobien.uhc.interfaces.IHungerGameConfiguration;
public class DeleteHungerGame extends CommonDelete<IHungerGameConfiguration> {
public DeleteHungerGame() {
super(MessageCode.DELETE_HUNGER_GAME_EXPLANATION);
}
@Override
protected void onDeleted(String name) {
sendMessage(MessageCode.DELETE_HUNGER_GAME_MESSAGE, name);
}
}
|
package org.alienideology.jcord.event.guild.update;
import org.alienideology.jcord.Identity;
import org.alienideology.jcord.event.guild.GuildUpdateEvent;
import org.alienideology.jcord.handle.guild.IGuild;
/**
* @author AlienIdeology
*/
public class GuildNotificationUpdateEvent extends GuildUpdateEvent {
private final IGuild.Notification oldNotification;
public GuildNotificationUpdateEvent(Identity identity, int sequence, IGuild guild, IGuild.Notification oldNotification) {
super(identity, sequence, guild);
this.oldNotification = oldNotification;
}
public IGuild.Notification getNewNotification() {
return guild.getNotificationsLevel();
}
public IGuild.Notification getOldNotification() {
return oldNotification;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.cmsitems.populators;
import de.hybris.platform.cmsfacades.constants.CmsfacadesConstants;
import de.hybris.platform.cmsfacades.data.ComponentTypeAttributeData;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.core.model.type.AttributeDescriptorModel;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
/**
* Populator that removes external and urlLink fields from structure and create a new field linkToggle.
*/
public class CMSItemLinkToggleTypeAttributePopulator implements Populator<AttributeDescriptorModel, ComponentTypeAttributeData>
{
@Override
public void populate(AttributeDescriptorModel source,
ComponentTypeAttributeData target) throws ConversionException
{
if (source.getQualifier().equals(CmsfacadesConstants.FIELD_EXTERNAL_NAME))
{
target.setCmsStructureType(null);
}
if (source.getQualifier().equals(CmsfacadesConstants.FIELD_URL_LINK_NAME))
{
target.setQualifier(CmsfacadesConstants.FIELD_LINK_TOGGLE_NAME);
target.setCmsStructureType("LinkToggle");
target.setI18nKey("se.editor.linkto.label");
}
}
}
|
package com.rastiehaiev.notebook.response;
/**
* @author Roman Rastiehaiev
* Created on 04.10.15.
*/
public class RegisterUserResponse extends BaseResponse {
}
|
package tkhub.project.kesbewa.data.db;
import java.lang.System;
@androidx.room.Database(entities = {tkhub.project.kesbewa.data.model.CartItem.class}, version = 2, exportSchema = false)
@kotlin.Metadata(mv = {1, 1, 16}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000\u0014\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\b\'\u0018\u0000 \u00052\u00020\u0001:\u0001\u0005B\u0005\u00a2\u0006\u0002\u0010\u0002J\b\u0010\u0003\u001a\u00020\u0004H&\u00a8\u0006\u0006"}, d2 = {"Ltkhub/project/kesbewa/data/db/AppDatabase;", "Landroidx/room/RoomDatabase;", "()V", "orderDao", "Ltkhub/project/kesbewa/data/db/OrderDao;", "Companion", "app_release"})
public abstract class AppDatabase extends androidx.room.RoomDatabase {
private static volatile tkhub.project.kesbewa.data.db.AppDatabase instance;
@org.jetbrains.annotations.NotNull()
private static final androidx.room.migration.Migration MIGRATION_1_2 = null;
public static final tkhub.project.kesbewa.data.db.AppDatabase.Companion Companion = null;
@org.jetbrains.annotations.NotNull()
public abstract tkhub.project.kesbewa.data.db.OrderDao orderDao();
public AppDatabase() {
super();
}
@kotlin.Metadata(mv = {1, 1, 16}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000$\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\b\u0086\u0003\u0018\u00002\u00020\u0001B\u0007\b\u0002\u00a2\u0006\u0002\u0010\u0002J\u0010\u0010\t\u001a\u00020\b2\u0006\u0010\n\u001a\u00020\u000bH\u0002J\u000e\u0010\f\u001a\u00020\b2\u0006\u0010\n\u001a\u00020\u000bR\u0011\u0010\u0003\u001a\u00020\u0004\u00a2\u0006\b\n\u0000\u001a\u0004\b\u0005\u0010\u0006R\u0010\u0010\u0007\u001a\u0004\u0018\u00010\bX\u0082\u000e\u00a2\u0006\u0002\n\u0000\u00a8\u0006\r"}, d2 = {"Ltkhub/project/kesbewa/data/db/AppDatabase$Companion;", "", "()V", "MIGRATION_1_2", "Landroidx/room/migration/Migration;", "getMIGRATION_1_2", "()Landroidx/room/migration/Migration;", "instance", "Ltkhub/project/kesbewa/data/db/AppDatabase;", "buildDatabase", "context", "Landroid/content/Context;", "getInstance", "app_release"})
public static final class Companion {
@org.jetbrains.annotations.NotNull()
public final tkhub.project.kesbewa.data.db.AppDatabase getInstance(@org.jetbrains.annotations.NotNull()
android.content.Context context) {
return null;
}
@org.jetbrains.annotations.NotNull()
public final androidx.room.migration.Migration getMIGRATION_1_2() {
return null;
}
private final tkhub.project.kesbewa.data.db.AppDatabase buildDatabase(android.content.Context context) {
return null;
}
private Companion() {
super();
}
}
} |
package com.amoraesdev.mobify.api.resources;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.amoraesdev.mobify.api.valueobjects.ApplicationVO;
import com.amoraesdev.mobify.api.valueobjects.UserApplicationSettingsPutVO;
import com.amoraesdev.mobify.api.valueobjects.UserApplicationSettingsVO;
import com.amoraesdev.mobify.entities.Application;
import com.amoraesdev.mobify.entities.User;
import com.amoraesdev.mobify.entities.UserApplicationSettings;
import com.amoraesdev.mobify.exceptions.NotFoundException;
import com.amoraesdev.mobify.repositories.ApplicationRepository;
import com.amoraesdev.mobify.repositories.UserApplicationSettingsRepository;
import com.amoraesdev.mobify.utils.AuthorizationHelper;
/**
* API endpoint to manipulate {@link UserApplicationSettings}
* @author Alessandro Moraes (alessandro at amoraesdev.com)
*/
@RestController
public class UserApplicationsSettingsResource {
public static final String BASE_URL = "/api/user/applications/settings";
public static final String BASE_URL_WITH_APPLICATION_ID = "/api/user/applications/{applicationId}/settings";
@Autowired
private ApplicationRepository applicationRepositoy;
@Autowired
private UserApplicationSettingsRepository userApplicationSettingsRepository;
@Autowired
private AuthorizationHelper authorizationHelper;
/**
* Get all {@link UserApplicationSettings} of the authenticated {@link User}
* @return
*/
@RequestMapping(path = BASE_URL, method = RequestMethod.GET)
public Collection<UserApplicationSettingsVO> getAllByUser(Principal user) throws NotFoundException{
String username = authorizationHelper.getUsername(user);
Collection<UserApplicationSettings> listSettings = userApplicationSettingsRepository
.findByUsername(username);
Collection<UserApplicationSettingsVO> listVOs = new ArrayList<>();
for(UserApplicationSettings settings : listSettings) {
Application application = applicationRepositoy.findByApplicationId(settings.getApplicationId());
//not found?
if(application == null){
throw new NotFoundException("error.entity_not_found", "Application", String.format("[applicationId=%s]", settings.getApplicationId()));
}
//populate the value object and return it
ApplicationVO applicationVO = new ApplicationVO();
applicationVO.setApplicationId(application.getApplicationId());
applicationVO.setName(application.getName());
applicationVO.setIcon(application.getIcon());
//create the settings vo
UserApplicationSettingsVO vo = new UserApplicationSettingsVO();
vo.setUsername(username);
vo.setApplication(applicationVO);
vo.setSilent(settings.getSilent());
listVOs.add(vo);
}
return listVOs;
}
/**
* Update settings for an {@link Application} of the authenticated {@link User}
* @return
*/
@RequestMapping(path = BASE_URL_WITH_APPLICATION_ID, method = RequestMethod.PUT)
public void toogleSilent(@PathVariable("applicationId") String applicationId, @RequestBody UserApplicationSettingsPutVO settingsVO, Principal user) throws NotFoundException{
String username = authorizationHelper.getUsername(user);
UserApplicationSettings settings = userApplicationSettingsRepository
.findByUsernameAndApplicationId(username, applicationId);
//not found?
if(settings == null){
throw new NotFoundException("error.entity_not_found", "UserApplicationSettings", String.format("[username=%s,applicationId=%s]", username, applicationId));
}
Application application = applicationRepositoy.findByApplicationId(settings.getApplicationId());
//not found?
if(application == null){
throw new NotFoundException("error.entity_not_found", "Application", String.format("[applicationId=%s]", settings.getApplicationId()));
}
if(settings.getSilent() != null && settingsVO.getSilent() != null){
settings.setSilent(settingsVO.getSilent());
}
userApplicationSettingsRepository.save(settings);
}
}
|
package com.smartup.manageorderapplication.utils;
import java.util.Random;
public enum OrderStatus {
OK,
ERROR,
FINALIZED;
public static OrderStatus getRandomStatus () {
return values()[new Random().nextInt(values().length-1)];
}
}
|
import java.util.*;
public class ChuiniuGame {
private int[] dices; // 0, 1, ..., 4 -> player, 5, 6, ..., 9 -> computer
private Random rand;
private Scanner scan;
public ChuiniuGame(Random rand, Scanner scan) {
this.rand = rand;
this.scan = scan;
dices = new int[10];
for (int i = 0; i < dices.length; ++i)
dices[i] = rand.nextInt(6) + 1;
}
public void play() {
ChuiniuRule rule = new ChuiniuRule();
boolean diceOneHasBeenCalled = false;
boolean playerWin = false;
ChuiniuCall lastCall = null;
System.out.println("> **水牛(Chuiniu)ゲーム開始**");
System.out.println("> Playerのカップのダイスは " + formatDices(dices, 0, 5) + " です");
while (true) {
// Playerの宣言
ChuiniuCall call = this.askPlayerCall(lastCall);
System.out.println("Player: " + call.dice + " が " + call.count + " 個!");
// Comの開
if (rand.nextInt(4) >= 3) {
System.out.println("Com: 開!");
this.openCups();
playerWin = rule.satisfy(this.dices, call.dice, call.count, diceOneHasBeenCalled);
break; // while
}
// ゲームの状況のデータの更新
if (call.dice == 1)
diceOneHasBeenCalled = true;
lastCall = call;
// Comの宣言
call = this.askComputerCall(lastCall);
System.out.println("Com: " + call.dice + " が " + call.count + " 個!");
// Playerの開
System.out.println("> 「開」しますか?(0=しない、1=する)");
int ans = scan.nextInt();
if (ans == 1) {
this.openCups();
playerWin = ! rule.satisfy(this.dices, call.dice, call.count, diceOneHasBeenCalled);
break; // while
}
// ゲームの状況のデータの更新
if (call.dice == 1)
diceOneHasBeenCalled = true;
lastCall = call;
}
// ゲームの結果の表示
if (playerWin) {
System.out.println("> Playerの勝ちです!");
System.out.println("Com: 負けた");
} else {
System.out.println("> Playerの負けです");
System.out.println("Com: 勝った!");
}
}
/** ダイスの配列の一部をフォーマットする
*
* @param dices ダイスの目の配列, not {@code null}
* @param from 印字する最初のダイスの添字
* @param to 印字する最後のダイスの添字 + 1
*/
public static String formatDices(int[] dices, int from, int to) {
StringBuilder buf = new StringBuilder();
for (int i = from; i < to; ++i) {
if (i > from)
buf.append(", ");
buf.append(dices[i]);
}
return buf.toString();
}
public ChuiniuCall askPlayerCall(ChuiniuCall lastCall) {
ChuiniuRule rule = new ChuiniuRule();
System.out.println("> Playerの宣言を入力してください");
while (true) {
System.out.print("> ダイスの目: ");
int dice = scan.nextInt();
System.out.print("> 個数: ");
int count = scan.nextInt();
if (! rule.isValidCall(dice, count)) {
System.out.println("> 宣言が不正です");
}
if (lastCall != null && ! rule.largerThan(dice, count, lastCall.dice, lastCall.count)) {
System.out.println("> 前回の宣言より大きな数を宣言してください");
continue; // while
}
return new ChuiniuCall(dice, count);
}
}
public ChuiniuCall askComputerCall(ChuiniuCall lastCall) {
ChuiniuCall call = new ChuiniuCall(lastCall.dice, lastCall.count);
if (call.dice < 6 && rand.nextInt(3) >= 2) {
call.dice += 1;
} else {
call.count += rand.nextInt(3) + 1;
}
return call;
}
public void openCups() {
System.out.println("> Playerのカップのダイスは " + formatDices(dices, 0, 5) + " です");
System.out.println("> Comのカップのダイスは " + formatDices(dices, 5, 10) + " です");
}
}
|
package com.accp.pub.pojo;
import java.util.Date;
public class Leave {
private Integer leaveid;
private Integer userid;
private Integer classid;
private Integer gradeid;
private String leavemessage;
private Date starttime;
private Date endtime;
private Integer guishu;
private Integer auditingstate;
private String groundsdismissal;
private Date sendtime;
private String makeprople;
private Integer makeid;
private Date maketime;
private Integer b1;
private String b2;
private String b3;
private Integer state;
public Integer getLeaveid() {
return leaveid;
}
public void setLeaveid(Integer leaveid) {
this.leaveid = leaveid;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public Integer getClassid() {
return classid;
}
public void setClassid(Integer classid) {
this.classid = classid;
}
public Integer getGradeid() {
return gradeid;
}
public void setGradeid(Integer gradeid) {
this.gradeid = gradeid;
}
public String getLeavemessage() {
return leavemessage;
}
public void setLeavemessage(String leavemessage) {
this.leavemessage = leavemessage == null ? null : leavemessage.trim();
}
public Date getStarttime() {
return starttime;
}
public void setStarttime(Date starttime) {
this.starttime = starttime;
}
public Date getEndtime() {
return endtime;
}
public void setEndtime(Date endtime) {
this.endtime = endtime;
}
public Integer getGuishu() {
return guishu;
}
public void setGuishu(Integer guishu) {
this.guishu = guishu;
}
public Integer getAuditingstate() {
return auditingstate;
}
public void setAuditingstate(Integer auditingstate) {
this.auditingstate = auditingstate;
}
public String getGroundsdismissal() {
return groundsdismissal;
}
public void setGroundsdismissal(String groundsdismissal) {
this.groundsdismissal = groundsdismissal == null ? null : groundsdismissal.trim();
}
public Date getSendtime() {
return sendtime;
}
public void setSendtime(Date sendtime) {
this.sendtime = sendtime;
}
public String getMakeprople() {
return makeprople;
}
public void setMakeprople(String makeprople) {
this.makeprople = makeprople == null ? null : makeprople.trim();
}
public Integer getMakeid() {
return makeid;
}
public void setMakeid(Integer makeid) {
this.makeid = makeid;
}
public Date getMaketime() {
return maketime;
}
public void setMaketime(Date maketime) {
this.maketime = maketime;
}
public Integer getB1() {
return b1;
}
public void setB1(Integer b1) {
this.b1 = b1;
}
public String getB2() {
return b2;
}
public void setB2(String b2) {
this.b2 = b2 == null ? null : b2.trim();
}
public String getB3() {
return b3;
}
public void setB3(String b3) {
this.b3 = b3 == null ? null : b3.trim();
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
} |
package com.tencent.mm.plugin.luckymoney.ui;
import android.content.Intent;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.luckymoney.b.ac;
import com.tencent.mm.plugin.luckymoney.b.ah;
import com.tencent.mm.plugin.luckymoney.b.f;
import com.tencent.mm.plugin.luckymoney.b.n;
import com.tencent.mm.plugin.luckymoney.b.w;
import com.tencent.mm.plugin.wallet_core.id_verify.util.RealnameGuideHelper;
import com.tencent.mm.plugin.wxpay.a$f;
import com.tencent.mm.plugin.wxpay.a$g;
import com.tencent.mm.plugin.wxpay.a.i;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.base.a;
import com.tencent.mm.ui.base.h;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@a(3)
public class LuckyMoneyBusiDetailUI extends LuckyMoneyBaseUI {
private View Iq;
private TextView hVS;
private TextView hXT;
private boolean ikj = false;
private View iln;
private TextView kLF;
private ListView kLN;
private ImageView kLO;
private TextView kLP;
private View kLR;
private View kLS;
OnScrollListener kLU = new 1(this);
private List<n> kLz = new LinkedList();
private LuckyMoneyWishFooter kUh;
private ImageView kUi;
private View kUj;
private ImageView kUk;
private boolean kUl = true;
private int kUm;
private String kUn;
private String kUo;
private String kUp;
private String kUq;
private int kUr = 0;
private Map<String, Integer> kUs = new HashMap();
private i kUt;
private String kUu = "";
private boolean kUv = false;
private TextView klp;
private int tH = 0;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
this.kLN = (ListView) findViewById(a$f.busi_detail_record_list);
this.kUt = new i(this.mController.tml);
this.Iq = LayoutInflater.from(this).inflate(a$g.lucky_money_busi_detail_header, null);
this.kLN.addHeaderView(this.Iq);
this.kLN.setAdapter(this.kUt);
this.Iq.setOnClickListener(new 7(this));
this.kLN.setOnScrollListener(this.kLU);
this.kLN.setOnItemClickListener(new 8(this));
this.iln = LayoutInflater.from(this).inflate(a$g.lucky_money_busi_detail_footer, null);
this.kLO = (ImageView) this.Iq.findViewById(a$f.busi_detail_avatar);
this.kLP = (TextView) this.Iq.findViewById(a$f.busi_detail_whose);
this.klp = (TextView) this.Iq.findViewById(a$f.busi_detail_wishing);
this.kLR = this.Iq.findViewById(a$f.busi_detail_amount_area);
this.kLF = (TextView) this.Iq.findViewById(a$f.busi_detail_amount);
this.kLS = this.Iq.findViewById(a$f.busi_detail_hint_layout);
this.hXT = (TextView) this.Iq.findViewById(a$f.busi_detail_tips);
this.kUi = (ImageView) this.Iq.findViewById(a$f.busi_detail_icon);
this.hVS = (TextView) this.Iq.findViewById(a$f.busi_detail_desc);
this.kUj = this.Iq.findViewById(a$f.busi_detail_opertiaon_ll);
this.kUk = (ImageView) this.Iq.findViewById(a$f.busi_detail_adimage);
ImageView imageView = (ImageView) findViewById(a$f.busi_detail_close_btn);
this.kUh = (LuckyMoneyWishFooter) findViewById(a$f.busi_detail_wish_footer);
this.kUh.a(new 9(this));
this.kUh.setOnWishSendImp(new 10(this));
this.kUh.post(new 11(this));
this.kUh.setOnkbdStateListener(new 12(this));
this.kUt.kXt = new 13(this);
i iVar = this.kUt;
iVar.kXu = new i.a(iVar);
this.kUh.setMaxLength(25);
imageView.setOnClickListener(new 14(this));
fixBackgroundRepeat(findViewById(a$f.busi_detail_bottom_decoration));
this.kUn = getIntent().getStringExtra("key_sendid");
this.kUp = getIntent().getStringExtra("key_native_url");
this.kUm = getIntent().getIntExtra("key_jump_from", 2);
this.kUr = getIntent().getIntExtra("key_static_from_scene", 0);
x.i("MicroMsg.LuckyMoneyDetailUI", "initData: sendid=%s , nativeurl=%s, jumpFrom=%d", new Object[]{this.kUn, this.kUp, Integer.valueOf(this.kUm)});
if (this.kUm == 2) {
try {
byte[] byteArrayExtra = getIntent().getByteArrayExtra("key_detail_info");
if (byteArrayExtra != null) {
f fVar = (f) new f().aG(byteArrayExtra);
if (fVar != null) {
a(fVar);
if (getIntent().getBooleanExtra("play_sound", false)) {
k.I(this, i.lucky_cashrecivedrevised);
}
}
}
} catch (Exception e) {
x.w("MicroMsg.LuckyMoneyDetailUI", "initData: parse LuckyMoneyDetail fail!" + e.getLocalizedMessage());
}
}
if (bi.oW(this.kUn) && !bi.oW(this.kUp)) {
try {
this.kUn = Uri.parse(this.kUp).getQueryParameter("sendid");
} catch (Exception e2) {
x.w("MicroMsg.LuckyMoneyDetailUI", "initData: parse uri exp:" + e2.getLocalizedMessage());
}
}
if (bi.oW(this.kUn)) {
x.w("MicroMsg.LuckyMoneyDetailUI", "sendid null or nil, finish");
} else {
bbr();
}
if (getIntent().getBooleanExtra("play_sound", false)) {
k.I(this, i.lucky_cashrecivedrevised);
}
}
public static void fixBackgroundRepeat(View view) {
if (view != null) {
Drawable background = view.getBackground();
if (background != null && (background instanceof BitmapDrawable)) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) background;
bitmapDrawable.mutate();
bitmapDrawable.setTileModeX(TileMode.REPEAT);
}
}
}
public boolean dispatchKeyEvent(KeyEvent keyEvent) {
if (keyEvent.getKeyCode() != 4 || this.kUh.getVisibility() != 0) {
return super.dispatchKeyEvent(keyEvent);
}
this.kUh.setVisibility(8);
return true;
}
public final boolean d(int i, int i2, String str, l lVar) {
boolean z = false;
if (lVar instanceof w) {
if (i == 0 && i2 == 0) {
w wVar = (w) lVar;
f fVar = wVar.kQP;
this.kUu = wVar.kRb;
a(fVar);
return true;
}
h.bA(this, str);
return true;
} else if (lVar instanceof ac) {
if (i == 0 && i2 == 0) {
h.bA(this, getString(i.has_send));
this.kUt.kLB = false;
bbs();
ac acVar = (ac) lVar;
if (this.kLz != null) {
while (true) {
boolean z2 = z;
if (z2 >= this.kLz.size()) {
break;
}
n nVar = (n) this.kLz.get(z2);
if (nVar.kPS.equalsIgnoreCase(acVar.kPS)) {
nVar.kQE = acVar.kLf;
this.kUt.notifyDataSetChanged();
break;
}
z = z2 + 1;
}
}
return true;
}
h.bA(this, str);
return true;
} else if (!(lVar instanceof ah)) {
return false;
} else {
if (i == 0 && i2 == 0) {
h.bA(this, getString(i.has_send));
return true;
}
h.bA(this, str);
return true;
}
}
protected void onActivityResult(int i, int i2, Intent intent) {
switch (i) {
case 1:
if (i2 == -1 && intent != null) {
String stringExtra = intent.getStringExtra("Select_Conv_User");
if (!bi.oW(stringExtra)) {
if (this.kUq != null && this.kUq.startsWith("wxpay://c2cbizmessagehandler/hongbao/festivalhongbao")) {
x.i("MicroMsg.LuckyMoneyDetailUI", "Not expected branch since 2015 fesitval");
break;
} else {
l(new ah(stringExtra.replaceAll(",", "|"), this.kUn, "v1.0"));
break;
}
}
}
break;
}
super.onActivityResult(i, i2, intent);
}
public void finish() {
if (getIntent().hasExtra("key_realname_guide_helper")) {
RealnameGuideHelper realnameGuideHelper = (RealnameGuideHelper) getIntent().getParcelableExtra("key_realname_guide_helper");
Bundle bundle = new Bundle();
bundle.putString("realname_verify_process_jump_plugin", "luckymoney");
bundle.putString("realname_verify_process_jump_activity", ".ui.LuckyMoneyBusiDetailUI");
boolean b = realnameGuideHelper.b(this, bundle, new 2(this));
getIntent().removeExtra("key_realname_guide_helper");
if (!b) {
super.finish();
return;
}
return;
}
super.finish();
}
protected final int getLayoutId() {
return a$g.lucky_money_busi_detail_ui;
}
private void bbr() {
this.ikj = true;
if (this.tH <= 0 || this.kLz.size() <= 0 || this.kLz.get(this.kLz.size() - 1) == null) {
this.kUu = "";
l(new w(this.kUn, 11, this.tH, this.kUp, "v1.0", this.kUu));
return;
}
l(new w(this.kUn, this.tH, this.kUp, bi.getLong(((n) this.kLz.get(this.kLz.size() - 1)).kQq, 0), "v1.0", this.kUu));
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private void a(com.tencent.mm.plugin.luckymoney.b.f r13) {
/*
r12 = this;
if (r13 != 0) goto L_0x0003;
L_0x0002:
return;
L_0x0003:
r0 = r13.kPV;
r1 = 1;
if (r0 != r1) goto L_0x0339;
L_0x0008:
r0 = 1;
L_0x0009:
r12.kUl = r0;
r0 = r12.tH;
if (r0 != 0) goto L_0x023d;
L_0x000f:
r0 = r13.kPS;
r12.kUo = r0;
r0 = r12.kUt;
r1 = r12.kUo;
r0.kLA = r1;
r0 = r12.kUt;
r1 = r13.kQd;
r0.kLC = r1;
if (r13 == 0) goto L_0x00eb;
L_0x0021:
r0 = r12.mController;
r0 = r0.tml;
r1 = r13.kQd;
r2 = 2;
if (r1 != r2) goto L_0x0344;
L_0x002a:
r1 = r12.kLO;
r2 = com.tencent.mm.plugin.wxpay.a.e.lucky_money_busi_default_avatar;
r1.setImageResource(r2);
r1 = r13.resourceId;
if (r1 == 0) goto L_0x033c;
L_0x0035:
r1 = "MicroMsg.LuckyMoneyDetailUI";
r2 = new java.lang.StringBuilder;
r3 = "busi logo load from file:";
r2.<init>(r3);
r3 = r13.resourceId;
r2 = r2.append(r3);
r2 = r2.toString();
com.tencent.mm.sdk.platformtools.x.i(r1, r2);
r1 = new com.tencent.mm.g.a.hg;
r1.<init>();
r2 = r1.bQx;
r3 = r13.resourceId;
r2.bQz = r3;
r2 = new com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyBusiDetailUI$3;
r2.<init>(r12, r1, r13);
r1.bJX = r2;
r2 = com.tencent.mm.sdk.b.a.sFg;
r3 = android.os.Looper.myLooper();
r2.a(r1, r3);
L_0x0068:
r1 = r12.kLP;
r2 = r13.kPL;
com.tencent.mm.plugin.luckymoney.b.o.a(r0, r1, r2);
r1 = r12.klp;
r2 = r13.kLf;
com.tencent.mm.plugin.luckymoney.b.o.a(r0, r1, r2);
r0 = r13.ceT;
r1 = 2;
if (r0 != r1) goto L_0x0356;
L_0x007b:
r0 = r12.kUm;
r1 = 3;
if (r0 == r1) goto L_0x0356;
L_0x0080:
r0 = r12.kLF;
r2 = r13.cfh;
r2 = (double) r2;
r4 = 4636737291354636288; // 0x4059000000000000 float:0.0 double:100.0;
r2 = r2 / r4;
r1 = com.tencent.mm.wallet_core.ui.e.A(r2);
r0.setText(r1);
r0 = r13.kPT;
r1 = 1;
if (r0 == r1) goto L_0x034f;
L_0x0094:
r0 = r12.kUt;
r1 = 1;
r0.kLB = r1;
L_0x0099:
r0 = r12.kLR;
r1 = 0;
r0.setVisibility(r1);
L_0x009f:
r0 = r13.kNi;
r0 = com.tencent.mm.sdk.platformtools.bi.oW(r0);
if (r0 != 0) goto L_0x0382;
L_0x00a7:
r0 = r12.kLS;
r1 = 0;
r0.setVisibility(r1);
r0 = r12.hXT;
r1 = r13.kNi;
r0.setText(r1);
r0 = r13.kNg;
r1 = 1;
if (r0 != r1) goto L_0x0368;
L_0x00b9:
r0 = r13.kNh;
r0 = android.text.TextUtils.isEmpty(r0);
if (r0 != 0) goto L_0x035f;
L_0x00c1:
r0 = r13.kNh;
r1 = "weixin://wxpay";
r0 = r0.startsWith(r1);
if (r0 != 0) goto L_0x035f;
L_0x00cc:
r0 = r12.kUi;
r1 = 0;
r0.setVisibility(r1);
L_0x00d2:
r0 = r12.hXT;
r1 = new com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyBusiDetailUI$4;
r1.<init>(r12, r13);
r0.setOnClickListener(r1);
L_0x00dc:
r0 = r13.kPW;
r0 = com.tencent.mm.sdk.platformtools.bi.oW(r0);
if (r0 != 0) goto L_0x0394;
L_0x00e4:
r0 = r12.hVS;
r1 = r13.kPW;
r0.setText(r1);
L_0x00eb:
if (r13 == 0) goto L_0x0206;
L_0x00ed:
r4 = r13.kPZ;
if (r4 == 0) goto L_0x01da;
L_0x00f1:
r0 = r4.size();
if (r0 <= 0) goto L_0x01da;
L_0x00f7:
r0 = r12.Iq;
r1 = com.tencent.mm.plugin.wxpay.a$f.busi_detail_operation_container_1;
r5 = r0.findViewById(r1);
r0 = r12.Iq;
r1 = com.tencent.mm.plugin.wxpay.a$f.busi_detail_operation_container_2;
r6 = r0.findViewById(r1);
r0 = r12.Iq;
r1 = com.tencent.mm.plugin.wxpay.a$f.busi_detail_operation_container_3;
r7 = r0.findViewById(r1);
r0 = r12.Iq;
r1 = com.tencent.mm.plugin.wxpay.a$f.busi_detail_operation_1;
r0 = r0.findViewById(r1);
r0 = (android.view.ViewGroup) r0;
r1 = r12.Iq;
r2 = com.tencent.mm.plugin.wxpay.a$f.busi_detail_operation_2;
r1 = r1.findViewById(r2);
r1 = (android.view.ViewGroup) r1;
r2 = r12.Iq;
r3 = com.tencent.mm.plugin.wxpay.a$f.busi_detail_operation_3;
r2 = r2.findViewById(r3);
r2 = (android.view.ViewGroup) r2;
r3 = r12.Iq;
r8 = com.tencent.mm.plugin.wxpay.a$f.busi_detail_divider_operation_1;
r8 = r3.findViewById(r8);
r3 = r12.Iq;
r9 = com.tencent.mm.plugin.wxpay.a$f.busi_detail_divider_operation_2;
r9 = r3.findViewById(r9);
r10 = new com.tencent.mm.plugin.luckymoney.ui.g$c;
r10.<init>();
r3 = r12.getResources();
r11 = com.tencent.mm.plugin.wxpay.a.c.lucky_money_goldstyle_detail_primary_text_color;
r3 = r3.getColor(r11);
r10.textColor = r3;
r3 = 1;
r10.kWM = r3;
r3 = r13.resourceId;
r10.resourceId = r3;
r3 = r12.kUr;
r10.kWN = r3;
r3 = r4.size();
if (r3 <= 0) goto L_0x016d;
L_0x015f:
r3 = 0;
r3 = r4.get(r3);
r3 = (com.tencent.mm.plugin.luckymoney.b.ai) r3;
com.tencent.mm.plugin.luckymoney.ui.g.a(r12, r0, r3, r10);
r0 = 0;
r5.setVisibility(r0);
L_0x016d:
r0 = r4.size();
r3 = 1;
if (r0 <= r3) goto L_0x0182;
L_0x0174:
r0 = 1;
r0 = r4.get(r0);
r0 = (com.tencent.mm.plugin.luckymoney.b.ai) r0;
com.tencent.mm.plugin.luckymoney.ui.g.a(r12, r1, r0, r10);
r0 = 0;
r6.setVisibility(r0);
L_0x0182:
r0 = r4.size();
r1 = 2;
if (r0 <= r1) goto L_0x0197;
L_0x0189:
r0 = 2;
r0 = r4.get(r0);
r0 = (com.tencent.mm.plugin.luckymoney.b.ai) r0;
com.tencent.mm.plugin.luckymoney.ui.g.a(r12, r2, r0, r10);
r0 = 0;
r7.setVisibility(r0);
L_0x0197:
r0 = r5.getVisibility();
if (r0 != 0) goto L_0x01ad;
L_0x019d:
r0 = r6.getVisibility();
if (r0 == 0) goto L_0x01a9;
L_0x01a3:
r0 = r7.getVisibility();
if (r0 != 0) goto L_0x01ad;
L_0x01a9:
r0 = 0;
r8.setVisibility(r0);
L_0x01ad:
r0 = r6.getVisibility();
if (r0 != 0) goto L_0x01bd;
L_0x01b3:
r0 = r7.getVisibility();
if (r0 != 0) goto L_0x01bd;
L_0x01b9:
r0 = 0;
r9.setVisibility(r0);
L_0x01bd:
r0 = r5.getVisibility();
if (r0 == 0) goto L_0x01cf;
L_0x01c3:
r0 = r6.getVisibility();
if (r0 == 0) goto L_0x01cf;
L_0x01c9:
r0 = r7.getVisibility();
if (r0 != 0) goto L_0x01da;
L_0x01cf:
r0 = r12.kUj;
r0.requestLayout();
r0 = r12.kUj;
r1 = 0;
r0.setVisibility(r1);
L_0x01da:
r0 = r12.iln;
r1 = com.tencent.mm.plugin.wxpay.a$f.busi_detail_footer_operation;
r0 = r0.findViewById(r1);
r0 = (android.view.ViewGroup) r0;
r1 = new com.tencent.mm.plugin.luckymoney.ui.g$c;
r1.<init>();
r2 = r12.getResources();
r3 = com.tencent.mm.plugin.wxpay.a.c.lucky_money_goldstyle_detail_primary_text_color;
r2 = r2.getColor(r3);
r1.textColor = r2;
r2 = r12.getResources();
r3 = com.tencent.mm.plugin.wxpay.a.d.SmallerTextSize;
r2 = r2.getDimensionPixelSize(r3);
r1.textSize = r2;
r2 = r13.kQa;
com.tencent.mm.plugin.luckymoney.ui.g.a(r12, r0, r2, r1);
L_0x0206:
r0 = com.tencent.mm.plugin.report.service.h.mEJ;
r1 = 11701; // 0x2db5 float:1.6397E-41 double:5.781E-320;
r2 = 5;
r2 = new java.lang.Object[r2];
r3 = 0;
r4 = r13.kQd;
r4 = sj(r4);
r4 = java.lang.Integer.valueOf(r4);
r2[r3] = r4;
r3 = 1;
r4 = 0;
r4 = java.lang.Integer.valueOf(r4);
r2[r3] = r4;
r3 = 2;
r4 = 0;
r4 = java.lang.Integer.valueOf(r4);
r2[r3] = r4;
r3 = 3;
r4 = 0;
r4 = java.lang.Integer.valueOf(r4);
r2[r3] = r4;
r3 = 4;
r4 = 1;
r4 = java.lang.Integer.valueOf(r4);
r2[r3] = r4;
r0.h(r1, r2);
L_0x023d:
if (r13 == 0) goto L_0x0304;
L_0x023f:
r0 = r13.ceS;
r1 = 3;
if (r0 == r1) goto L_0x0249;
L_0x0244:
r0 = r13.ceS;
r1 = 2;
if (r0 != r1) goto L_0x039c;
L_0x0249:
r0 = r13.kPU;
r1 = 1;
if (r0 != r1) goto L_0x039c;
L_0x024e:
r0 = r12.kUl;
if (r0 != 0) goto L_0x039c;
L_0x0252:
r0 = r13.kPX;
r1 = 1;
if (r0 != r1) goto L_0x039c;
L_0x0257:
r0 = 1;
r1 = r0;
L_0x0259:
r0 = r13.kPY;
if (r0 == 0) goto L_0x03a0;
L_0x025d:
r0 = r13.kPY;
r0 = r0.ddp;
r2 = 1;
if (r0 != r2) goto L_0x03a0;
L_0x0264:
r0 = r13.kPY;
r0 = r0.kPw;
r0 = com.tencent.mm.sdk.platformtools.bi.oW(r0);
if (r0 != 0) goto L_0x03a0;
L_0x026e:
r0 = 1;
r2 = r0;
L_0x0270:
r0 = r12.iln;
r3 = com.tencent.mm.plugin.wxpay.a$f.busi_detail_send_btn;
r0 = r0.findViewById(r3);
r0 = (android.widget.TextView) r0;
if (r1 != 0) goto L_0x027e;
L_0x027c:
if (r2 == 0) goto L_0x03a4;
L_0x027e:
r1 = new com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyBusiDetailUI$5;
r1.<init>(r12, r13);
r0.setOnClickListener(r1);
if (r2 == 0) goto L_0x0295;
L_0x0288:
r1 = r13.kPY;
r1 = r1.kPw;
r12.kUq = r1;
r1 = r13.kPY;
r1 = r1.kPx;
r0.setText(r1);
L_0x0295:
r1 = com.tencent.mm.plugin.report.service.h.mEJ;
r2 = 11701; // 0x2db5 float:1.6397E-41 double:5.781E-320;
r3 = 5;
r3 = new java.lang.Object[r3];
r4 = 0;
r5 = r13.kQd;
r5 = sj(r5);
r5 = java.lang.Integer.valueOf(r5);
r3[r4] = r5;
r4 = 1;
r5 = 0;
r5 = java.lang.Integer.valueOf(r5);
r3[r4] = r5;
r4 = 2;
r5 = 0;
r5 = java.lang.Integer.valueOf(r5);
r3[r4] = r5;
r4 = 3;
r5 = 0;
r5 = java.lang.Integer.valueOf(r5);
r3[r4] = r5;
r4 = 4;
r5 = 2;
r5 = java.lang.Integer.valueOf(r5);
r3[r4] = r5;
r1.h(r2, r3);
r1 = 0;
r0.setVisibility(r1);
L_0x02d0:
r1 = r12.iln;
r2 = com.tencent.mm.plugin.wxpay.a$f.busi_detail_record_link;
r1 = r1.findViewById(r2);
r1 = (android.widget.TextView) r1;
r2 = r12.kUm;
r3 = 1;
if (r2 == r3) goto L_0x03ab;
L_0x02df:
r2 = r12.kUm;
r3 = 3;
if (r2 == r3) goto L_0x03ab;
L_0x02e4:
r0 = r0.getVisibility();
if (r0 == 0) goto L_0x03ab;
L_0x02ea:
r0 = new com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyBusiDetailUI$6;
r0.<init>(r12, r13);
r1.setOnClickListener(r0);
r0 = 0;
r1.setVisibility(r0);
L_0x02f6:
r0 = r12.kUv;
if (r0 != 0) goto L_0x0304;
L_0x02fa:
r0 = r12.kLN;
r1 = r12.iln;
r0.addFooterView(r1);
r0 = 1;
r12.kUv = r0;
L_0x0304:
r2 = r13.kQe;
if (r2 == 0) goto L_0x03c5;
L_0x0308:
r0 = 0;
r1 = r0;
L_0x030a:
r0 = r2.size();
if (r1 >= r0) goto L_0x03b2;
L_0x0310:
r0 = r2.get(r1);
r0 = (com.tencent.mm.plugin.luckymoney.b.n) r0;
r3 = r12.kUs;
r4 = r0.kPS;
r3 = r3.containsKey(r4);
if (r3 != 0) goto L_0x0335;
L_0x0320:
r3 = r12.kLz;
r4 = r2.get(r1);
r3.add(r4);
r3 = r12.kUs;
r0 = r0.kPS;
r4 = 1;
r4 = java.lang.Integer.valueOf(r4);
r3.put(r0, r4);
L_0x0335:
r0 = r1 + 1;
r1 = r0;
goto L_0x030a;
L_0x0339:
r0 = 0;
goto L_0x0009;
L_0x033c:
r1 = r13.kPM;
r1 = com.tencent.mm.sdk.platformtools.bi.oW(r1);
if (r1 != 0) goto L_0x0068;
L_0x0344:
r1 = r12.kLO;
r2 = r13.kPM;
r3 = r13.kQg;
com.tencent.mm.plugin.luckymoney.b.o.a(r1, r2, r3);
goto L_0x0068;
L_0x034f:
r0 = r12.kUt;
r1 = 0;
r0.kLB = r1;
goto L_0x0099;
L_0x0356:
r0 = r12.kLR;
r1 = 8;
r0.setVisibility(r1);
goto L_0x009f;
L_0x035f:
r0 = r12.kUi;
r1 = 8;
r0.setVisibility(r1);
goto L_0x00d2;
L_0x0368:
r0 = "MicroMsg.LuckyMoneyDetailUI";
r1 = "detail.jumpChange is false";
com.tencent.mm.sdk.platformtools.x.e(r0, r1);
r0 = r12.hXT;
r1 = r12.getResources();
r2 = com.tencent.mm.plugin.wxpay.a.c.lucky_money_operation_text_normal_color;
r1 = r1.getColor(r2);
r0.setTextColor(r1);
goto L_0x00dc;
L_0x0382:
r0 = "MicroMsg.LuckyMoneyDetailUI";
r1 = "detail.changeWording is empty";
com.tencent.mm.sdk.platformtools.x.e(r0, r1);
r0 = r12.kLS;
r1 = 8;
r0.setVisibility(r1);
goto L_0x00dc;
L_0x0394:
r0 = r12.hVS;
r1 = 0;
r0.setText(r1);
goto L_0x00eb;
L_0x039c:
r0 = 0;
r1 = r0;
goto L_0x0259;
L_0x03a0:
r0 = 0;
r2 = r0;
goto L_0x0270;
L_0x03a4:
r1 = 8;
r0.setVisibility(r1);
goto L_0x02d0;
L_0x03ab:
r0 = 8;
r1.setVisibility(r0);
goto L_0x02f6;
L_0x03b2:
r0 = r12.tH;
r1 = r2.size();
r0 = r0 + r1;
r12.tH = r0;
r0 = 0;
r12.ikj = r0;
r0 = r12.kUt;
r1 = r12.kLz;
r0.bw(r1);
L_0x03c5:
r0 = r13.kQc;
r1 = r13.kQf;
r2 = r12.kUk;
r3 = com.tencent.mm.plugin.wxpay.a.e.lucky_money_busi_ad_img_default;
r2.setImageResource(r3);
r2 = com.tencent.mm.sdk.platformtools.bi.oW(r0);
if (r2 == 0) goto L_0x043a;
L_0x03d6:
r0 = "MicroMsg.LuckyMoneyDetailUI";
r1 = "renderAdImage: no adImage";
com.tencent.mm.sdk.platformtools.x.i(r0, r1);
r0 = r12.kUk;
r1 = 8;
r0.setVisibility(r1);
L_0x03e6:
r0 = com.tencent.mm.plugin.report.service.h.mEJ;
r1 = 13051; // 0x32fb float:1.8288E-41 double:6.448E-320;
r2 = 10;
r2 = new java.lang.Object[r2];
r3 = 0;
r4 = r12.kUr;
r4 = java.lang.Integer.valueOf(r4);
r2[r3] = r4;
r3 = 1;
r4 = 1;
r4 = java.lang.Integer.valueOf(r4);
r2[r3] = r4;
r3 = 2;
r4 = r13.kQc;
r2[r3] = r4;
r3 = 3;
r4 = r13.kPZ;
r4 = com.tencent.mm.plugin.luckymoney.b.o.bv(r4);
r2[r3] = r4;
r3 = 4;
r4 = "";
r2[r3] = r4;
r3 = 5;
r4 = "";
r2[r3] = r4;
r3 = 6;
r4 = "";
r2[r3] = r4;
r3 = 7;
r4 = "";
r2[r3] = r4;
r3 = 8;
r4 = r13.kPL;
r2[r3] = r4;
r3 = 9;
r4 = r13.resourceId;
r4 = java.lang.Integer.valueOf(r4);
r2[r3] = r4;
r0.h(r1, r2);
goto L_0x0002;
L_0x043a:
r2 = new android.util.DisplayMetrics;
r2.<init>();
r2 = com.tencent.mm.sdk.platformtools.ad.getContext();
r2 = r2.getResources();
r2 = r2.getDisplayMetrics();
if (r2 == 0) goto L_0x047b;
L_0x044d:
r2 = r2.widthPixels;
r3 = r12.getResources();
r4 = com.tencent.mm.plugin.wxpay.a.d.lucky_money_busi_detail_list_padding;
r3 = r3.getDimensionPixelSize(r4);
r3 = r3 * 2;
r2 = r2 - r3;
r3 = r12.getResources();
r4 = com.tencent.mm.plugin.wxpay.a.d.lucky_money_busi_detail_list_margin;
r3 = r3.getDimensionPixelSize(r4);
r3 = r3 * 2;
r2 = r2 - r3;
r2 = (float) r2;
r3 = 1061158912; // 0x3f400000 float:0.75 double:5.24282163E-315;
r2 = r2 * r3;
r2 = (int) r2;
r3 = r12.kUk;
r3 = r3.getLayoutParams();
r3.height = r2;
r2 = r12.kUk;
r2.setLayoutParams(r3);
L_0x047b:
r2 = r12.kUk;
r3 = 0;
com.tencent.mm.plugin.luckymoney.b.o.a(r2, r0, r1, r3);
r0 = r12.kUk;
r1 = 0;
r0.setVisibility(r1);
goto L_0x03e6;
*/
throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyBusiDetailUI.a(com.tencent.mm.plugin.luckymoney.b.f):void");
}
private void bbs() {
if (this.kUh != null && this.kUh.getVisibility() != 8) {
this.kUh.setVisibility(8);
}
}
protected void onDestroy() {
super.onDestroy();
if (this.kUh != null) {
this.kUh.bbE();
}
}
private static int sj(int i) {
if (i == 2) {
return 13;
}
return 7;
}
}
|
package com.rhysnguyen.casestudyjavaweb.entity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import com.rhysnguyen.casestudyjavaweb.validation.IdentityCard;
import com.rhysnguyen.casestudyjavaweb.validation.PhoneNumber;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.util.Set;
@Entity
@Table(name = "employee")
@Setter
@Getter
@NoArgsConstructor
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@NotNull(message = "{Employee.id.NotNull}")
private Long id;
@Column(name = "full_name")
@NotBlank(message = "{Employee.fullName.NotBlank}")
private String fullName;
@Column(name = "date_of_birth")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Temporal(TemporalType.DATE)
@NotNull(message = "{Employee.dateOfBirth.NotNull}")
private Date dateOfBirth;
@Column(name = "identity_card_number")
@IdentityCard(message = "{Employee.identityCardNumber.Valid}")
@NotBlank(message = "{Employee.identityCardNumber.NotBlank}")
private String identityCardNumber;
@Column(name = "contact_number")
@PhoneNumber
@NotBlank(message = "{Employee.contactNumber.NotBlank}")
private String contactNumber;
@Email(message = "{Employee.email.Valid}")
@Column(name = "email")
@NotBlank(message = "{Employee.email.NotBlank}")
private String email;
@Column(name = "address")
@NotBlank(message = "{Employee.address.NotBlank}")
private String address;
@Min(value = 0 , message = "Wages should be greater than 0.")
@Column(name = "wages")
@NotNull(message = "{Employee.wages.NotNull}")
private Double wages;
@ManyToOne(targetEntity = Degree.class,
fetch = FetchType.EAGER,
cascade = {CascadeType.DETACH, CascadeType.MERGE,
CascadeType.PERSIST, CascadeType.REFRESH}
)
@JoinColumn(name = "degree_id")
private Degree degree;
@ManyToOne(targetEntity = Department.class,
fetch = FetchType.EAGER,
cascade = {CascadeType.DETACH, CascadeType.MERGE,
CascadeType.PERSIST, CascadeType.REFRESH}
)
@JoinColumn(name = "department_id")
private Department department;
@ManyToOne(targetEntity = Position.class,
fetch = FetchType.EAGER,
cascade = {CascadeType.DETACH, CascadeType.MERGE,
CascadeType.PERSIST, CascadeType.REFRESH}
)
@JoinColumn(name = "position_id")
private Position position;
@OneToMany(targetEntity = Contract.class,
mappedBy = "employee", fetch = FetchType.LAZY,
cascade = CascadeType.ALL
)
private Set<Contract> contracts;
}
|
import java.lang.Math;
import java.util.*;
import java.util.concurrent.TimeUnit;
//TimeUnit.SECONDS.sleep(1);
public class BingoCard {
private int[][] board = new int[5][5];
private boolean[][] guessArr = new boolean[5][5];
public String[][] boardS=new String[5][5];
public String boardFull;
Scanner scan = new Scanner(System.in);
// public void BingoCard(int[][] bingo){
// board=bingo;
// }
public BingoCard(){
// System.out.println("DEBUG:BINGOconstructor ");
while(!checkDupes()){
for(int row=0;row<board.length;row++){
for(int col=0;col<board[row].length;col++){
board[col][row]= (int) (((Math.random()*15)+((row*15)+1)));
}
}
}
// System.out.println("DEBUG:finished BINGOconstructor ");
// for(int row=0;row<board.length;row++){
// for(int col=0;col<board[row].length;col++){
// System.out.print(board[row][col]+"\t");
// }
// }
}
public boolean checkDupes(){
// System.out.println("DEBUG: duplicates");
int count =0;
for(int row=0;row<board.length;row++){
for(int col=0;col<board[row].length;col++){
if(count>1){
return false;
}
count = 0;
int temp=board[row][col];
for(int row1=0;row1<board.length;row1++){
for(int col1=0;col1<board[row].length;col1++){
if(board[row1][col1]==temp){
count++;
}
}
}
}
}
return true;
}
public void guess(int num){
// System.out.println("DEBUG: guess");
for(int row=0;row<board.length;row++){
for(int col=0;col<board[row].length;col++){
if(board[row][col]==num){
guessArr[row][col]=true;
}
}
}
}
public String toBoardString(){
// System.out.println("DEBUG: toString");
for(int row=0;row<boardS.length;row++){
for(int col=0;col<boardS[row].length;col++){
boardS[row][col]=Integer.toString(board[row][col]);
}
}
boardFull+="\033[2J"+"\n";
boardFull+= "B"+"\t"+"I"+"\t"+"N"+"\t"+"G"+"\t"+"O"+"\n";
for(int row=0;row<boardS.length;row++){
for(int col=0;col<boardS[row].length;col++){
if(guessArr[row][col]){
boardFull+="\033[1;91m"+boardS[row][col]+"\t"+"\u001B[0m";
}else{
boardFull+=boardS[row][col]+"\t";
}
}
boardFull+="\n";
}
System.out.print(boardFull);
return boardFull;
}
public void inputNum(){
boolean finished=false;
int input;
int countRow=0;
int countCol=0;
int countDiag=0;
int windex=0;
String wintype="";
while(!finished){
System.out.print("\nInput number: ");
input=scan.nextInt();
guess(input);
toBoardString();
for(int row=0;row<guessArr.length;row++){
countRow=0;
for(int col=0;col<guessArr[row].length;col++){
if(guessArr[row][col]){
countRow++;
}
if(countRow>=5){
finished=true;
windex=row;
wintype="ROW";
}
}
}
for(int col=0;col<5;col++){
countCol=0;
for(int row=0;row<guessArr.length;row++){
if(guessArr[row][col]){
countCol++;
}
if(countCol>=5){
finished=true;
windex=col;
wintype="COL";
}
}
}
countCol=0;
countRow=0;
countDiag=0;
for(int i=0;i<5;i++){
if(guessArr[i][i]){
countDiag++;
}
if(countDiag>=5){
finished=true;
wintype="diagL";
}
}
countDiag=0;
for(int i=4;i>=0;i--){
if(guessArr[4-i][i]){
countDiag++;
}
if(countDiag>=5){
finished=true;
wintype="diagR";
}
}
}
winSequence(wintype, windex);
System.out.println("\033[0;96m"+"BINGO!");
}
public void autoGsr(){
boolean finished=false;
int input;
int countRow=0;
int countCol=0;
int countDiag=0;
int windex=0;
String wintype="";
while(!finished){
try{
Thread.sleep(1000);
}
catch(InterruptedException ex){
Thread.currentThread().interrupt();
}
input=((int) (Math.random()*75)+1);
guess(input);
toBoardString();
for(int row=0;row<guessArr.length;row++){
countRow=0;
for(int col=0;col<guessArr[row].length;col++){
if(guessArr[row][col]){
countRow++;
}
if(countRow>=5){
finished=true;
windex=row;
wintype="ROW";
}
}
}
for(int col=0;col<5;col++){
countCol=0;
for(int row=0;row<guessArr.length;row++){
if(guessArr[row][col]){
countCol++;
}
if(countCol>=5){
finished=true;
windex=col;
wintype="COL";
}
}
}
countCol=0;
countRow=0;
countDiag=0;
for(int i=0;i<5;i++){
if(guessArr[i][i]){
countDiag++;
}
if(countDiag>=5){
finished=true;
wintype="diagL";
}
}
countDiag=0;
for(int i=4;i>=0;i--){
if(guessArr[4-i][i]){
countDiag++;
}
if(countDiag>=5){
finished=true;
wintype="diagR";
}
}
}
winSequence(wintype, windex);
System.out.println("\033[0;96m"+"BINGO!");
}
public void autoGsrPlus(){
boolean finished=false;
int input;
int countRow=0;
int countCol=0;
int countDiag=0;
int windex=0;
String wintype="";
while(!finished){
try{
Thread.sleep(1000);
}
catch(InterruptedException ex){
Thread.currentThread().interrupt();
}
int[] slot={((int) (Math.random()*5)),((int) (Math.random()*5))};
input=board[slot[0]][slot[1]];
guess(input);
toBoardString();
for(int row=0;row<guessArr.length;row++){
countRow=0;
for(int col=0;col<guessArr[row].length;col++){
if(guessArr[row][col]){
countRow++;
}
if(countRow>=5){
finished=true;
windex=row;
wintype="ROW";
}
}
}
for(int col=0;col<5;col++){
countCol=0;
for(int row=0;row<guessArr.length;row++){
if(guessArr[row][col]){
countCol++;
}
if(countCol>=5){
finished=true;
windex=col;
wintype="COL";
}
}
}
countCol=0;
countRow=0;
countDiag=0;
for(int i=0;i<5;i++){
if(guessArr[i][i]){
countDiag++;
}
if(countDiag>=5){
finished=true;
wintype="diagL";
}
}
countDiag=0;
for(int i=4;i>=0;i--){
if(guessArr[4-i][i]){
countDiag++;
}
if(countDiag>=5){
finished=true;
wintype="diagR";
}
}
}
winSequence(wintype, windex);
System.out.println("\033[0;96m"+"BINGO!");
}
public void winSequence(String type, int windex){
boardFull="";
// System.out.println("DEBUG: toString");
for(int row=0;row<boardS.length;row++){
for(int col=0;col<boardS[row].length;col++){
boardS[row][col]=Integer.toString(board[row][col]);
}
}
boardFull+="\033[2J"+"\n";
// System.out.println(boardFull+":DEBUG");
boardFull+= "B"+"\t"+"I"+"\t"+"N"+"\t"+"G"+"\t"+"O"+"\n";
if(type.equals("ROW")){
for(int row=0;row<boardS.length;row++){
for(int col=0;col<boardS[row].length;col++){
if(row==windex){
boardFull+="\033[0;93m"+boardS[row][col]+"\t"+"\u001B[0m";
}else{
boardFull+=boardS[row][col]+"\t";
}
}
boardFull+="\n";
}
}else if(type.equals("COL")){
for(int row=0;row<boardS.length;row++){
for(int col=0;col<boardS[row].length;col++){
if(col==windex){
boardFull+="\033[0;93m"+boardS[row][col]+"\t"+"\u001B[0m";
}else{
boardFull+=boardS[row][col]+"\t";
}
}
boardFull+="\n";
}
}else if(type.equals("diagL")){
for(int row=0;row<boardS.length;row++){
for(int col=0;col<boardS[row].length;col++){
if(row==col){
boardFull+="\033[0;93m"+boardS[row][col]+"\t"+"\u001B[0m";
}else{
boardFull+=boardS[row][col]+"\t";
}
}
boardFull+="\n";
}
}else{
for(int row=0;row<boardS.length;row++){
for(int col=0;col<boardS[row].length;col++){
if(4-col==row){
boardFull+="\033[0;93m"+boardS[row][col]+"\t"+"\u001B[0m";
}else{
boardFull+=boardS[row][col]+"\t";
}
}
boardFull+="\n";
}
}
// System.out.printf("\033[2J"+"\n");
System.out.print(boardFull);
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.types.service;
import de.hybris.platform.cmsfacades.data.ComponentTypeAttributeData;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.core.model.type.AttributeDescriptorModel;
import java.util.List;
/**
* Service to provide populators for AttributeDescriptorModels
*/
public interface AttributePopulatorsProvider
{
/**
* Given an attribute descriptor model, return the list of Populators for this attribute type defined in the configuration map.
* @param attributeDescriptor the attribute that will be tested to look for populators.
* @return the list of populators.
*/
List<Populator<AttributeDescriptorModel, ComponentTypeAttributeData>> getAttributePopulators(final AttributeDescriptorModel attributeDescriptor);
}
|
package br.com.professorisidro.paintbrush.core;
public class Retangulo extends FormaGeometrica{
public Retangulo(int posX, int posY, int altura, int largura) {
super(posX, posY, altura, largura);
}
@Override
public void desenhar() {
System.out.println("Desenho retangulo");
}
}
|
/***
* 现在你总共有 n 门课需要选,记为 0 到 n-1。
*
* 在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1]
*
* 给定课程总量以及它们的先决条件,判断是否可能完成所有课程的学习?
*
* 示例 1:
*
* 输入: 2, [[1,0]]
* 输出: true
* 解释: 总共有 2 门课程。学习课程 1 之前,你需要完成课程 0。所以这是可能的。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/course-schedule
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class CourserSchedule{
public static void main(String[] args) {
int[][] prerequisites ={{1,0}};
boolean res = canFinish(2,prerequisites);
System.out.println(res);
}
public static boolean canFinish(int numCourses, int[][] prerequisites) {
int[] scheduleCources = new int[numCourses];
boolean[] visited = new boolean[numCourses];
for (int i = 0; i < prerequisites.length; i++) {
System.out.println(prerequisites[i][0]);
scheduleCources[prerequisites[i][0]]++;
}
for (; ; ) {
// 找一个 入度 为0的节点。
int i = 0;
for (i = 0; i < numCourses; i++) {
if (!visited[i] && scheduleCources[i] == 0) {
break;
}
}
if (i == numCourses) {//如果i和课程数量相等说明 数组和 课程必然有重复
break;
}
// update the node
for (int k = 0; k < prerequisites.length; k++) {
if (prerequisites[k][1] == i) {
scheduleCources[prerequisites[k][0]]--;
}
}
visited[i] = true;
}
for (int i = 0; i < scheduleCources.length; i++) {
if (scheduleCources[i] > 0) {
return false;
}
}
return true;
}
}
|
package game.app.entities;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.Data;
@Entity
@Table(name = "STOCKS")
@Data
public class Stock {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "CANTIDAD")
private Double cantidad;
//RELACIONES STOCK CON TIENDA Y JUEGO
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="shop")
Shop shop;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="game")
//@Relation(parentColumn = "title", entityColumn = "game")
Game game;
}
|
package com.teebz.hrf.fragments;
import com.teebz.hrf.helpers.ApplicationHelper;
import com.teebz.hrf.R;
import com.teebz.hrf.activities.SingleImageActivity;
import com.teebz.hrf.entities.Call;
import com.teebz.hrf.listeners.QuickReferenceListItemClickListener;
import com.teebz.hrf.searchparsers.CallSearcher;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class QuickReferenceFragment extends android.app.Fragment {
private ArrayList<Call> mCalls = null;
private CallSearcher mCallSearcher;
private QuickReferenceListItemClickListener mItemClickListener;
public static QuickReferenceFragment newInstance() {
return new QuickReferenceFragment();
}
public QuickReferenceFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quick_reference_fragment, container, false);
mCallSearcher = CallSearcher.getSearcher(rootView.getContext().getAssets());
mCalls = mCallSearcher.getCalls();
registerClickCallback(rootView);
populateListView(rootView);
//Hide the keyboard if it happens to be up
InputMethodManager keyboard = (InputMethodManager) container.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.hideSoftInputFromWindow(container.getWindowToken(), 0);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mItemClickListener = (QuickReferenceListItemClickListener)activity;
}
catch (Exception e) {
Toast.makeText(activity.getBaseContext(), "Click listener failed", Toast.LENGTH_LONG).show();
}
}
private void populateListView(View theView) {
if (mCalls != null) {
ArrayAdapter<Call> adapter = new QuickRefListAdapter();
ListView list = (ListView) theView.findViewById(R.id.quickRefListView);
list.setAdapter(adapter);
}
}
private void registerClickCallback(View theView) {
ListView list = (ListView) theView.findViewById(R.id.quickRefListView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//A rule was clicked, get the corresponding rules to pass to the parent.
Call c = mCalls.get(position);
//Alert our parent that a click happened.
mItemClickListener.onQuickRefListItemClick(view, position, c.assocRuleNum);
}
});
}
private void showLargeImage(String smallName) {
//If this is copied again, move it to a shared location w/the other usage.
Call c = mCallSearcher.getCallByCallId(smallName);
Intent newActivity = new Intent(getActivity(), SingleImageActivity.class);
newActivity.putExtra(SingleImageActivity.SINGLE_IMAGE_KEY, c.imgName);
newActivity.putExtra(SingleImageActivity.SINGLE_IMAGE_TITLE, c.name);
newActivity.putExtra(SingleImageActivity.SINGLE_IMAGE_FOLDER, ApplicationHelper.CALL_IMGS_FOLDER);
startActivity(newActivity);
}
private class QuickRefListAdapter extends ArrayAdapter<Call> {
public QuickRefListAdapter() {
super(getActivity(), R.layout.quick_reference_row, mCalls);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getActivity().getLayoutInflater().inflate(R.layout.quick_reference_row, parent, false);
}
Call current = mCalls.get(position);
//Set the header text
TextView nameText = (TextView)itemView.findViewById(R.id.qrNameTextView);
nameText.setText(current.name);
//Set the desc text
TextView descText = (TextView)itemView.findViewById(R.id.qrDescTextView);
descText.setText(current.desc);
//Set the image
String imageName = current.imgName.replace("img_", "img_sm_");
ImageButton quickRefImageBtn = (ImageButton)itemView.findViewById(R.id.qrImageBtn);
//If this call does not have an image, handle it differently.
if (!imageName.equals("NO SIGNAL")) {
Drawable d = ApplicationHelper.getDrawableFromAssets(getContext(),
ApplicationHelper.CALL_IMGS_FOLDER,
imageName,
".png");
quickRefImageBtn.setImageDrawable(d);
}
else {
quickRefImageBtn.setImageResource(android.R.color.white);
}
quickRefImageBtn.setTag(current.id);
quickRefImageBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Call c = mCallSearcher.getCallByCallId(view.getTag().toString());
ApplicationHelper.showLargeImage(getActivity(),
c.imgName,
c.name,
ApplicationHelper.CALL_IMGS_FOLDER);
}
});
//Last, determine how tall the row should be.
int height = 0;
ViewGroup.LayoutParams layoutParams = itemView.getLayoutParams();
layoutParams.height = convertDpToPixels(height, itemView.getContext());
itemView.setLayoutParams(layoutParams);
return itemView;
}
}
public static int convertDpToPixels(float dp, Context context){
Resources resources = context.getResources();
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
resources.getDisplayMetrics()
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.