blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
9c80a5539e097bc881f0483bb4677dec4ce8eaf0 | Java | lmkr/dat159 | /roomcontrol/src/no/hvl/dat159/roomcontrol/tests/SimpleController.java | UTF-8 | 699 | 3.078125 | 3 | [] | no_license | package no.hvl.dat159.roomcontrol.tests;
import no.hvl.dat159.roomcontrol.Heating;
public class SimpleController implements Runnable {
Heating heater;
public SimpleController(Heating heater) {
this.heater = heater;
}
public void run() {
System.out.println("Controller running");
try {
for (int i = 1; i<=6; i++) {
// receive from CloudMQTT
heater.write(true);
Thread.sleep(5000);
heater.write(false);
Thread.sleep(5000);
// determine whether to publish on CloudMQTT
}
} catch (Exception ex) {
System.out.println("Controller: " + ex.getMessage());
ex.printStackTrace();
}
System.out.println("Controller stopping");
}
}
| true |
d37571986504f099f7facc05986b64d175fbc0a0 | Java | GaryLeong/processonline | /src/main/java/com/careland/processonline/controller/UserLoginController.java | UTF-8 | 3,760 | 2.5 | 2 | [] | no_license | package com.careland.processonline.controller;
import com.careland.processonline.entity.MyUser;
import com.careland.processonline.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Administrator
*/
@Controller
@RequestMapping(value = {"/user"})
public class UserLoginController {
/**
* 最开始希望用Map的形式接参数,后来不用了,将请求对应的接受方式记录一下
*
* @RequestBody Map<String , Object> map post请求
* @RequestParam Map<String , Object> map get请求
*/
/**
* 注入service
*/
@Autowired
private UserLoginService userLoginService;
/**
* 同时这个时候可以自己了解一下@Controller与@RestController的区别,以及@ResponseBody的用法。
*/
/**
* 跳转到用户登录页面
*
* @return 登录页面
*/
@RequestMapping(value = {"/loginHtml"})
public String loginHtml() {
return "userLogin";
}
/**
* 跳转到用户注册页面
*
* @return 注册页面
*/
@RequestMapping(value = {"/registerpage"})
public String registerpage() {
return "register";
}
/**
* 获取用户名与密码,用户登录
*
* @return 登录成功页面
*/
@ResponseBody
@RequestMapping(value = {"/userLogin"})
public String userLogin(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpServletRequest request) {
if (StringUtils.isEmpty(username)) {
return "用户名不能为空";
}
if (StringUtils.isEmpty(password)) {
return "密码不能为空";
}
MyUser user = userLoginService.userLogin(username, password);
//登录成功
if (user != null) {
//将用户信息放入session 用于后续的拦截器
request.getSession().setAttribute("session_user", user);
return "登录成功";
}
return "登录失败,用户名或密码错误";
}
/**
* 注册新用户
*
* @return 注册结果
*/
@ResponseBody
@RequestMapping(value = {"/uregister"})
public String addUser(@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("password2") String password2,
@RequestParam("age") int age) {
if (StringUtils.isEmpty(username)) {
return "用户名不能为空";
}
if (StringUtils.isEmpty(password)) {
return "密码不能为空";
}
if (StringUtils.isEmpty(password2)) {
return "确认密码不能为空";
}
if (!password.equals(password2)) {
return "两次密码不相同,注册失败!!";
} else {
//int res = userLoginService.adduser(username, password, age);
int res = userLoginService.addUser1(username, password, age);
if (res == 0) {
return "注册失败!";
} else {
return "注册成功!";
}
}
}
}
| true |
de03388c4a3a8fdcf0732bf8dcd18db13c50fbcb | Java | QXL4515/DRCF | /data and code/surfaceData/Matrix.java | WINDOWS-1252 | 2,478 | 3.296875 | 3 | [] | no_license | package math;
import java.io.*;
import java.util.Scanner;
public class Matrix {
private int m;
private int n;
private double[][] matrix;
public Matrix() {}
public Matrix(int m,int n) {
this.m=m;
this.n=n;
this.matrix=new double[m][n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
this.matrix[i][j]=0;
}
public Matrix(Matrix matrix1) {
this.m=matrix1.getM();
this.n=matrix1.getN();
this.matrix=new double[this.m][this.n];
for(int i=0;i<this.m;i++)
for(int j=0;j<this.n;j++)
this.matrix[i][j]=matrix1.get(i, j);
}
public Matrix(String path,int n) throws IOException{
this.n=n;
File file=new File(path);
if(!file.exists()) {
this.m=1;
System.out.println("file do not exist!");
this.matrix=new double[m][n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
this.matrix[i][j]=0;
}
else {
// Scanner sc1=new Scanner(file);
// int j=0;
// while(sc1.hasNextLine())
// j++;
// this.m=j;
// sc1.close();
matrix=new double[10000][this.n];
Scanner sc=new Scanner(file);
String read;
String[] string=new String[n+2];
int i=0;
while(sc.hasNextLine()) {
read=sc.nextLine();
string=read.split("\\s++");
for(int k=0;k<n;k++)
matrix[i][k]=Double.parseDouble(string[k]);
i=i+1;
}
this.m=i;
sc.close();
}
}
public int getM() {
return m;
}
public int getN() {
return n;
}
public double get(int i,int j) {
return matrix[i][j];
}
public void set(int i,int j,double x) {
matrix[i][j]=x;
}
public void deleteRow(int i) {
if(i<0||i>=m)
System.out.println("wrong!");
for(int k=i;k<m-1;k++)
for(int j=0;j<n;j++)
matrix[k][j]=matrix[k+1][j];
this.m=this.m-1;
}
public void deleteCol(int k) {
if(k<0||k>=n)
System.out.println("wrong!");
for(int i=0;i<m;i++)
for(int j=k;j<n-1;j++)
matrix[i][j]=matrix[i][j+1];
this.n=this.n-1;
}
public void printOut() {
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++)
System.out.print(matrix[i][j]+" ");
System.out.println(" ");
}
}
public static void main(String[] args) throws IOException{
Matrix matrix=new Matrix("F:\\data\\2016\\58102.txt",21);
matrix.printOut();
}
}
| true |
7e552f818f8f6eac6f0bdc4d9096ddddd3b60748 | Java | ryanbartolay/ocpjp | /OCP Review/chapter09/com/ryan/ioandnio/file/FileExample.java | UTF-8 | 439 | 3.34375 | 3 | [] | no_license | package com.ryan.ioandnio.file;
import java.io.File;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) throws IOException {
File file = new File("file.txt");
if(file.exists()) {
System.out.println("File exists");
} else {
if(file.createNewFile()) {
System.out.println("File created");
} else {
assert(false) : "Something is wrong";
}
}
}
}
| true |
5dea65becfe5def77a5839f0da5c10dae676acaf | Java | ashishshresthatest/Javatest | /LearningJava/src/datastructure/ArrayListExample.java | UTF-8 | 359 | 3.25 | 3 | [] | no_license | package datastructure;
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("ram");
list.add("tiger");
list.add("is fap");
System.out.println(list.size());
for (String a : list) {
System.out.println(a);
}
}
}
| true |
2e2c9b1f65e384fe859e1431a10efc6a77067d0d | Java | CoolCommando/StockBucks | /app/src/main/java/imprika/stockbucks/InstanceIDCheck.java | UTF-8 | 541 | 1.976563 | 2 | [] | no_license | package imprika.stockbucks;
import android.content.Intent;
import android.content.SharedPreferences;
import com.google.android.gms.iid.InstanceIDListenerService;
public class InstanceIDCheck extends InstanceIDListenerService {
@Override
public void onTokenRefresh() {
SharedPreferences SharePre= getSharedPreferences("TokenCheck", this.MODE_PRIVATE);
if(SharePre.getBoolean("Subscribe", false)== true) {
startService(new Intent(this, GcmRegistrationService.class));}
else{this.stopSelf();}
}
}
| true |
802e4602a133401a1db697f91a03d51189349df6 | Java | xf06/crmc | /src/main/java/com/blackjade/crm/apis/dword/CDepositCode.java | UTF-8 | 1,385 | 2.296875 | 2 | [
"Apache-2.0"
] | permissive | package com.blackjade.crm.apis.dword;
import java.util.UUID;
import com.blackjade.crm.apis.dword.ComStatus.DepositCodeStatus;
//CRMC/GW cDepositCode 0x4001 {requestid, clientid, pnsid, pnsgid} HTTP
public class CDepositCode {
private UUID requestid;
private String messageid;
private int clientid;
private int pnsid;
private int pnsgid;
public DepositCodeStatus reviewData() {
if (!"4001".equals(this.messageid))
return ComStatus.DepositCodeStatus.WRONGMID;
// if()
// return ComStatus.
return ComStatus.DepositCodeStatus.SUCCESS;
}
public UUID getRequestid() {
return requestid;
}
public void setRequestid(UUID requestid) {
this.requestid = requestid;
}
public String getMessageid() {
return messageid;
}
public void setMessageid(String messageid) {
this.messageid = messageid;
}
public int getClientid() {
return clientid;
}
public void setClientid(int clientid) {
this.clientid = clientid;
}
public int getPnsid() {
return pnsid;
}
public void setPnsid(int pnsid) {
this.pnsid = pnsid;
}
public int getPnsgid() {
return pnsgid;
}
public void setPnsgid(int pnsgid) {
this.pnsgid = pnsgid;
}
@Override
public String toString() {
return "CDepositCode [requestid=" + requestid.toString() + ", messageid=" + messageid + ", clientid=" + clientid
+ ", pnsid=" + pnsid + ", pnsgid=" + pnsgid + "]";
}
}
| true |
530d8845fe869c8423ae9d64d19536dbb3128e56 | Java | pcmac94/CMPE133Cookit | /MainMenuPanel.java | UTF-8 | 4,117 | 2.4375 | 2 | [] | no_license |
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ActionEvent;
import java.awt.Font;
import java.awt.Image;
import javax.swing.SwingConstants;
import javax.swing.JFormattedTextField;
import javax.swing.JPasswordField;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.JTextPane;
public class MainMenuPanel extends JFrame {
private JPanel contentPane;
private JPanel transferPan;
private JPanel mainMenuPan;
private JLayeredPane layeredPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMenuPanel frame = new MainMenuPanel();
frame.setPreferredSize(new Dimension(1600, 900));
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void switchPanels(JPanel panel)
{
layeredPane.removeAll();
layeredPane.add(panel);
layeredPane.repaint();
layeredPane.revalidate();
}
/**
* Create the frame.
*/
public MainMenuPanel() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1600, 900);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 0, 1582, 853);
contentPane.add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
mainMenuPan = new JPanel();
layeredPane.add(mainMenuPan, "name_1876842692619100");
mainMenuPan.setLayout(null);
JButton playButton = new JButton("Play");
mainMenuPan.add(playButton);
playButton.setBorder(null);
playButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
playButton.setBorder(new MatteBorder(4, 4, 4, 4, (Color) new Color(0, 0, 0)));
}
@Override
public void mouseExited(MouseEvent e) {
playButton.setBorder(null);
}
@Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("New game button");
}
});
playButton.setIcon(null);
playButton.setBounds(822, 390, 271, 82);
JButton btnHelp = new JButton("Help");
btnHelp.setBorder(null);
btnHelp.setBounds(822, 518, 271, 82);
mainMenuPan.add(btnHelp);
JButton btnExit = new JButton("Exit");
btnExit.setBorder(null);
btnExit.setBounds(822, 640, 271, 82);
mainMenuPan.add(btnExit);
btnExit.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
btnExit.setBorder(new MatteBorder(4, 4, 4, 4, (Color) new Color(0, 0, 0)));
}
@Override
public void mouseExited(MouseEvent e) {
btnExit.setBorder(null);
}
@Override
public void mouseClicked(MouseEvent arg0) {
System.exit(0);
}
});
JLabel mainMenu = new JLabel("");
Image img = new ImageIcon(this.getClass().getResource("/background.jpg")).getImage();
mainMenu.setIcon(new ImageIcon(img));
mainMenu.setBounds(0, 0, 1582, 853);
mainMenuPan.add(mainMenu);
}
}
| true |
f93c4cd1293491c411055df90ed22e9da02a6ac3 | Java | mitchellirvin/parking-lot | /src/main/java/Vehicle.java | UTF-8 | 3,278 | 3.09375 | 3 | [] | no_license | import java.util.Objects;
public final class Vehicle {
private boolean isCompact;
private boolean isHandicapped;
private String owner;
private String make;
private String model;
private int year;
private Vehicle(
boolean isCompact,
boolean isHandicapped,
String owner,
String make,
String model,
int year) {
this.isCompact = isCompact;
this.isHandicapped = isHandicapped;
this.owner = owner;
this.make = make;
this.model = model;
this.year = year;
}
public boolean isCompact() {
return this.isCompact;
}
public boolean isHandicapped() {
return this.isHandicapped;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vehicle vehicle = (Vehicle) o;
return isCompact == vehicle.isCompact &&
isHandicapped == vehicle.isHandicapped &&
year == vehicle.year &&
owner.equals(vehicle.owner) &&
make.equals(vehicle.make) &&
model.equals(vehicle.model);
}
@Override
public int hashCode() {
return Objects.hash(isCompact, isHandicapped, owner, make, model, year);
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private boolean isCompact;
private boolean isHandicapped;
private String owner;
private String make;
private String model;
private int year;
Builder() { }
public Builder isCompact(boolean isCompact) {
this.isCompact = isCompact;
return this;
}
public Builder isHandicapped(boolean isHandicapped) {
this.isHandicapped = isHandicapped;
return this;
}
public Builder owner(String owner) {
this.owner = owner;
return this;
}
public Builder make(String make) {
this.make = make;
return this;
}
public Builder model(String model) {
this.model = model;
return this;
}
public Builder year(int year) {
this.year = year;
return this;
}
public Vehicle build() {
if (owner == null) {
throw new IllegalArgumentException("Vehicle Builder: Owner must not be null.");
} else if (make == null) {
throw new IllegalArgumentException("Vehicle Builder: Make must not be null.");
} else if (model == null) {
throw new IllegalArgumentException("Vehicle Builder: Model must not be null.");
} else if (year > 2019 || year < 1900) {
throw new IllegalArgumentException("Vehicle Builder: Year must not be between 1900 and 2019.");
}
return new Vehicle(
this.isCompact,
this.isHandicapped,
this.owner,
this.make,
this.model,
this.year);
}
}
}
| true |
84b913c8fadd8bbe87eb01a01bc2e03318db356e | Java | djagielo/mgr | /JppfTestsMgr/src/main/java/pl/polsl/kmeans2/JppfKMeansTest2.java | UTF-8 | 5,143 | 2.5625 | 3 | [] | no_license | package pl.polsl.kmeans2;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.math3.linear.RealVector;
import org.jppf.client.JPPFClient;
import org.jppf.client.JPPFJob;
import org.jppf.node.protocol.DataProvider;
import org.jppf.node.protocol.MemoryMapDataProvider;
import pl.polsl.data.RealVectorDataPreparator;
import pl.polsl.kmeans.KMeansHelper;
import pl.polsl.kmeans.SubmitQueue;
public class JppfKMeansTest2 {
private static final String SPLIT_MARK = ",";
public static void main(String[] args) throws Exception {
if (args.length < 6) {
System.err.println("Usage: JppfKMeans <file> <k> <submitQueSize> <tasksPerJob> <convergeDist> <partitionSize>");
System.exit(1);
}
try(JPPFClient client = new JPPFClient()){
String path = args[0];
int K = Integer.parseInt(args[1]);
int submitQueSize = Integer.parseInt(args[2]);
int tasksPerJob = Integer.parseInt(args[3]);
double convergeDist = Double.parseDouble(args[4]);
int partitionSize = Integer.parseInt(args[5]);
RealVectorDataPreparator dp = new RealVectorDataPreparator(path, SPLIT_MARK);
// reading all data to list
List<RealVector> data = dp.getAllData();
// take sample of K size
final List<RealVector> centroids = KMeansHelper.takeSample(data, K);
SubmitQueue queue = new SubmitQueue(submitQueSize, client);
List<List<Integer>> partitionedIndexes = getPartitionedData(data, partitionSize);
long start = System.currentTimeMillis();
// data provider mechanism
DataProvider dataProvider = new MemoryMapDataProvider();
dataProvider.setParameter("data", data);
//
double tempDist;
do{
// 1. allocate each vector to closest centroid and group by id
JobProvider jobProvider = new JobProvider(dataProvider);
List<JPPFJob> allocateJobs = jobProvider.createClosestCentroidsJobs(partitionedIndexes, centroids,tasksPerJob);
System.out.println(String.format("Allocate jobs size: %s", allocateJobs.size()));
for(JPPFJob job: allocateJobs)
queue.submit(job);
// waiting for all jobs gets done
Object lock = new Object();
// wait until all job results have been processed
while (jobProvider.getProcessedTasksCount() < jobProvider.getSubmittedTasksCount()) {
synchronized(lock) {
lock.wait(1L);
}
}
// 2. average the vectors within each cluster to compute centroids
List<JPPFJob> groupByJobs = jobProvider.createGroupByAndAverageJobs(KMeansHelper.toListOfPairs(jobProvider.getClosestCentroidsMerger().getMergedResults().entrySet()),tasksPerJob);
//client.submitJob(groupByJob);
System.out.println(String.format("GroupByJobs size: %s", groupByJobs.size()));
for(JPPFJob job: groupByJobs)
queue.submit(job);
// waiting for all jobs gets done
Object lock2 = new Object();
// wait until all job results have been processed
while (jobProvider.getProcessedTasksCount() < jobProvider.getSubmittedTasksCount()) {
synchronized(lock2) {
lock2.wait(1L);
}
}
Map<Integer, RealVector> newCentroids = jobProvider.getNewCentroidsMerger().getMergedResults();
// 3. compute new centroids
tempDist = 0.0;
for (int i = 0; i < K; i++) {
tempDist += centroids.get(i).getDistance(newCentroids.get(i));
}
for (Map.Entry<Integer, RealVector> t: newCentroids.entrySet()) {
centroids.set(t.getKey(), t.getValue());
}
System.out.println("Finished iteration (delta = " + tempDist + ")");
}while(tempDist > convergeDist);
System.out.println(String.format("JppfKMeansTest executed in %s[ms]", (System.currentTimeMillis() - start)));
}
}
private static List<Integer> takeSample(List<RealVector> data, int k){
Random random = new Random(System.currentTimeMillis());
int s = data.size();
List<Integer> usedIndexes = new ArrayList<Integer>();
for (int i = 0; i < s; i++) {
int randomIndex = -1;
do {
randomIndex = random.nextInt(s - 1);
} while (randomIndex < 0 || usedIndexes.contains(randomIndex));
usedIndexes.add(randomIndex);
}
return usedIndexes;
}
private static List<List<Integer>> getPartitionedData(List<RealVector> data, int partitionSize){
if(partitionSize > 0){
List<List<Integer>> result = new LinkedList<>();
List<Integer> embeddedList = new LinkedList<>();
int counter = 0;
int cnt = 0;
while(cnt <= data.size()-1){
embeddedList.add(cnt++);
counter++;
if(counter == partitionSize){
result.add(embeddedList);
embeddedList = new LinkedList<>();
counter = 0;
}
}
if(embeddedList != null && embeddedList.size() > 0){
result.add(embeddedList);
}
return result;
}
else
return null;
}
}
| true |
a19429666d614585436c32df479bf840962e3545 | Java | gangsijay/myjob | /LG-MICRO/oauth/src/main/java/com/two/config/CustomUserService.java | UTF-8 | 2,411 | 2.515625 | 3 | [] | no_license | package com.two.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import com.two.dao.SysPermissionDao;
import com.two.dao.SysUserDao;
import com.two.pojo.SysPermission;
import com.two.pojo.SysUser;
/**
* 自定义UserDetailsService,将用户权限交给springsecurity进行管控
*
* @Author: 我爱大金子
* @Description: 将用户权限交给Springsecurity进行管控
* @Date: Create in 16:19 2017/7/5
*/
@Component
public class CustomUserService implements UserDetailsService {
@Autowired
private SysUserDao sysUserDao;
@Autowired
private SysPermissionDao sysPermissionDao;
@Override
public UserDetails loadUserByUsername(String username) {
SysUser user = sysUserDao.findByUserName(username);
if (user != null) {
List<SysPermission> permissions = sysPermissionDao.findByAdminUserId(user.getId());
List<GrantedAuthority> grantedAuthorities = new ArrayList <>();
for (SysPermission permission : permissions) {
if (permission != null && permission.getName()!=null) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
//1:此处将权限信息添加到 GrantedAuthority 对象中,在后面进行全权限验证时会使用GrantedAuthority 对象。
grantedAuthorities.add(grantedAuthority);
}
}
// return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()), grantedAuthorities);
return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()), grantedAuthorities);
} else {
throw new UsernameNotFoundException("admin: " + username + " do not exist!");
}
}
} | true |
c7f5c511f41a6c629d0f6c46d167282208ec907b | Java | jonasinta/mqtt-mysql | /src/org/eclipse/pahodemoAsync/PahoListenPostSynchronus.java | UTF-8 | 3,770 | 2.25 | 2 | [] | no_license | package org.eclipse.pahodemoAsync;
import java.util.Date;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class PahoListenPostSynchronus implements MqttCallback{
MqttClient client;
public PahoListenPostSynchronus() {}
public static void main(String[] args) throws InterruptedException {
mqttClientInit();
}
public static void mqttClientInit() throws InterruptedException {
PahoListenPostSynchronus boing = new PahoListenPostSynchronus();
while (boing.doDemo() ==0 ) {
System.err.println("network problem");
Thread.sleep(10000);
}
}
public int doDemo() {
try {
MqttConnectOptions options;
client = new MqttClient("tcp://192.168.1.71:10002", "Mqtt-mysql-JavaMonitor");
//client = new MqttClient("tcp://jonas-home.duckdns.org:10002", "Mqtt-mysql-JavaMonitor");
//blank line
client.setCallback(this);
client.setTimeToWait(10000L);
options = new MqttConnectOptions();
options.setWill("pahodemo/clienterrors", "mqtt-mysql-crashed".getBytes(),2,true);
client.connect(options);
System.out.println("just tried to connect and subscribed \"/mcu/+/heap,volts,stamp/");
client.subscribe("/mcu/+/heap,volts,stamp/");//chip id part is the "+" bit
} catch (MqttException e) {
System.err.println("inside catch MqttExeption");
e.printStackTrace();
System.err.println(e.getMessage());
return 0;
}
return 1;
}
@Override
public void connectionLost(Throwable cause) {
System.err.println("inside connection lost callback");
System.err.print(cause.getMessage());
try {
mqttClientInit();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
String stringChipID;
String[] chipID = topic.split("/");
stringChipID = chipID[2];
tmMysql_obj toMysqlInstance1 = new tmMysql_obj();
//paho_gui.setTextField_sentValueText(message.toString());
String Str = new String(message.toString());
System.out.println("recieved message; "+message+"\n");
System.out.println("recieved topic; "+topic+"\n");
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse( Str);
JSONObject jsonObject = (JSONObject) obj;
Str=jsonObject.get("timestamp").toString();
Date date = new Date((Long) jsonObject.get("timestamp")*1000);
System.out.println("Volts; "+ jsonObject.get("Volts"));
System.out.println("Heap; "+ jsonObject.get("HEAP"));
System.out.println("Date; "+ date.toString());
System.out.println("------------------------------------------");
Number voltage = (Number) jsonObject.get("Volts");
Number heap = (Number) jsonObject.get("HEAP");
Float v1 = voltage.floatValue();
Integer v2 = heap.intValue();
toMysqlInstance1.get2Database(stringChipID, 0,0,v2,v1);
//System.out.println("Must have sent to database -------------------------------------");
} catch (ParseException e) {
System.err.println("inside json parser catch- musthave been a json parse problem");
e.printStackTrace();
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// TODO Auto-generated method stub
System.out.println("delivered to mosquitto server");
}
}
| true |
69e9461bb1df6bd421a9cef1d159363c0423c91c | Java | Jally-S/gitLearning | /JDWebStore/src/com/anjoyo/jd/activity/JDMainActivity.java | GB18030 | 1,282 | 2.046875 | 2 | [] | no_license | package com.anjoyo.jd.activity;
import com.anjoyo.jd.ExitApplication;
import com.anjoyo.jd.R;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TabHost;
public class JDMainActivity extends Activity {
public static final int TAG_MESSAGE_DELAYED=100;
private Handler mHandler=new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case TAG_MESSAGE_DELAYED:
startActivity(new Intent(JDMainActivity.this, TabHostContent.class));
overridePendingTransition( R.anim.push_up_in,R.anim.push_up_out);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.jdmain_activity);
ExitApplication.getInstance().addActivity2(this);
//Ч
animationMethod();
}
/**
* Чʾ
*/
private void animationMethod() {
// TODO Auto-generated method stub
Message msg=mHandler.obtainMessage();
msg.what=TAG_MESSAGE_DELAYED;
mHandler.sendMessageDelayed(msg, 1000);
}
}
| true |
cafb96d5afedd0c82af5b9195a2c1a5f82b39d31 | Java | varuneshwarmathur/adidas-subscriptions | /subscriptionservice/src/main/java/com/adidas/subscription/service/SubscriptionProcessorService.java | UTF-8 | 364 | 1.648438 | 2 | [] | no_license | package com.adidas.subscription.service;
import com.adidas.subscription.model.SubscriptionServiceResponse;
import com.adidas.subscription.model.SubscriptionServiceData;
/**
* @author varmathu0
*/
public interface SubscriptionProcessorService {
public SubscriptionServiceResponse createSubscription(SubscriptionServiceData subscriptionServiceData);
}
| true |
6cb7fe8959ef4282df725612cbbe39ead2d645b1 | Java | ChrisVent/C-Examples | /Java/Hilo.java | UTF-8 | 799 | 3.65625 | 4 | [] | no_license | package App;
// el otro metodo para hacerlo es public class Hilo implements Runnable
// y se instancia ==> Thread myHilo = new Thread( [objeto tipo clasename] , [nombre del hilo]);
// ej: una clase hilo llamada: MyClase
// MyClase [objeto] = new MyClase();
// Thread myHilo = new Thread([objeto] , [nombre del hilo]);
public class Hilo extends Thread{
/**
* @param args
*/
private String desc;
public Hilo(String Nombre){
this.desc = Nombre;
}
//metodo run , esto es como el main del hilo - lo que hara el hilo cuando se encuentre en ejecucion
public void run(){
for(int i = 0 ; i < 5 ; i++){
System.out.println("[*] " + this.desc +" Esto es un hilo que hereda de la clase Thread!");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| true |
988d59b67c3d2f9279e8a16e487363f0aadd8b9c | Java | sjwangzju/leetcode | /LeetcodeProblems/Intuit/ConfigurationValues_OA.java | UTF-8 | 4,908 | 3.15625 | 3 | [] | no_license | package Intuit;
import java.util.*;
public class ConfigurationValues_OA {
/**
* time: O(NlogN), N is the number of different servers
*
* space: O(N)
*
*
*
* input:
*
* [base_server]
* ram = 16G
* disk = 15G
*
* [review_console:admin_console]
*
* [admin_console:base_server]
* ram = 32G
* owner = root
*
*
*
* output:
* [admin_console]
* disk = 16G
* owner = root
* ram = 32G
*
* [base_server]
* disk = 16G
* ram = 16G
*
* [review_console]
* disk = 16G
* owner = root
* ram = 32G
*
*
* @param input
*/
public void getValues(String[] input) {
// map stores the configurations of each server
Map<String, Map<String, String>> config = new HashMap<>();
// use adj map to save parent and its children
// construct a graph
Map<String, List<String>> adj = new HashMap<>();
Map<String, Integer> indegree = new HashMap<>();
String s1 = "";
// traverse through all lines to store the original property for each server
// and construct a graph to save the relationship between different servers
// time: O(N)
for (String s: input) {
// server ID line
if (!s.contains("=")) {
// get rid of brackets [ ]
s = s.substring(1, s.length() - 1);
s1 = s;
// contains extension relationship: [admin_console:base_server]
// inherits parent's property, but not overridden
if (s.contains(":")) {
s1 = s.split(":")[0];
String s2 = s.split(":")[1];
// s1 is the child of s2
// add s1 into the value of s2 in the adj map
if (!adj.containsKey(s2)) {
adj.put(s2, new LinkedList<>());
}
adj.get(s2).add(s1);
// increase the indegree of s1
indegree.put(s1, indegree.getOrDefault(s1, 0) + 1);
}
if (!indegree.containsKey(s1)) {
indegree.put(s1, 0);
}
config.put(s1, new HashMap<>());
}
else {
// parse the configuration section, and add it into map
s = s.replaceAll(" ", "");
config.get(s1).put(s.split("=")[0], s.split("=")[1]);
}
}
// topological sort for the graph to update properties for each server
// server IDs in the q has indegree of 0
PriorityQueue<String> q = new PriorityQueue<>();
for (String s: indegree.keySet()) {
if (indegree.get(s) == 0) {
q.add(s);
}
}
List<String> res = new LinkedList<>();
while (!q.isEmpty()) {
String tmp = q.poll();
res.add(tmp);
Map<String, String> map1 = config.get(tmp);
if (adj.containsKey(tmp)) {
List<String> neigh = adj.get(tmp);
for (String n: neigh) {
// inherit new properties form parent
Map<String, String> map2 = config.get(n);
for (String s: map1.keySet()) {
if (!map2.containsKey(s)) {
map2.put(s, map1.get(s));
}
}
indegree.put(n, indegree.get(n) - 1);
if (indegree.get(n) == 0) {
q.offer(n);
}
}
}
}
// sort server IDs in alphabetic order and output
// time: O(NlogN)
Collections.sort(res, (a,b) -> (a.compareTo(b)));
for (String s: res) {
System.out.println("[" + s + "]");
Map<String, String> m = config.get(s);
List<String> key = new ArrayList<>(m.keySet());
Collections.sort(key);
for (String str: key) {
System.out.println(str + " = " + m.get(str));
}
System.out.println();
}
}
public static void main(String[] args) {
String[] input = {"[base_server]", "ram = 16G", "disk = 15G", "[review_console:admin_console]",
"[admin_console:base_server]", "ram = 32G", "owner = root"};
// String[] input = {"[staging_server:base_server]", "ram = 8G", "envname = Staging",
// "[dev_server:staging_server]", "envname = Dev", "[test_server:dev_server]", "disk = 4G",
// "[base_server]", "ram = 16G", "disk = 15G", "[qa_server:base_server]", "ram = 4G"};
new ConfigurationValues_OA().getValues(input);
}
}
| true |
c51a67d19fde28e3cacf99d10ca78e33271d433c | Java | xiaoxianglala/jvm | /src/main/java/com/ysy/thread/MyTest3.java | UTF-8 | 484 | 3.203125 | 3 | [] | no_license | package com.ysy.thread;
/**
* @ClassName MyTest3
* @Description 设置线程名
* @Author ysy
* @Date 2020/6/3 16:31
**/
public class MyTest3 implements Runnable {
@Override
public void run() {
System.out.println("MyTest runnable is running");
}
public static void main(String[] args) {
Thread thread = new Thread(new MyTest3(),"Thread-1");
thread.run();
System.out.println("current thread name is " + thread.getName());
}
}
| true |
63d55af0d06ce72c903f27b04083787dae44efad | Java | yollpoll/MyApp | /app/src/main/java/com/example/xlm/mydrawerdemo/utils/RxTools.java | UTF-8 | 7,110 | 2.4375 | 2 | [] | no_license | package com.example.xlm.mydrawerdemo.utils;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import com.example.xlm.mydrawerdemo.bean.Draft;
import com.example.xlm.mydrawerdemo.bean.DraftWithPath;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Scheduler;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
/**
* 存放一些异步操作
* Created by 鹏祺 on 2017/7/13.
*/
public class RxTools {
/**
* 解析图库中的图片返回bitmap
*
* @param cr
* @param uri
* @param callback
*/
public static void DecodeStream(final ContentResolver cr, final Uri uri, final BitmapCallback callback) {
Observable.create(new Observable.OnSubscribe<Bitmap>() {
@Override
public void call(Subscriber<? super Bitmap> subscriber) {
try {
subscriber.onNext(BitmapFactory.decodeStream(cr.openInputStream(uri)));
} catch (FileNotFoundException e) {
e.printStackTrace();
subscriber.onNext(null);
} finally {
subscriber.onCompleted();
}
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Bitmap>() {
@Override
public void call(Bitmap bitmap) {
callback.callback(bitmap);
}
});
}
/**
* 通过文件地址获得bitmap,rxJava异步
*
* @param path
* @param callback
*/
public static void DecodeStream(final String path, final BitmapCallback callback) {
Observable.create(new Observable.OnSubscribe<Bitmap>() {
@Override
public void call(Subscriber<? super Bitmap> subscriber) {
File file = new File(path);
FileInputStream fileInputStream;
Bitmap bitmap;
try {
fileInputStream = new FileInputStream(file);
subscriber.onNext(BitmapFactory.decodeStream(fileInputStream));
} catch (FileNotFoundException e) {
subscriber.onNext(null);
e.printStackTrace();
} finally {
subscriber.onCompleted();
}
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Bitmap>() {
@Override
public void call(Bitmap bitmap) {
callback.callback(bitmap);
}
});
}
/**
* 循环遍历获取bitmap集合
* 将带地址的草稿列表转化成带bitmap的草稿列表
*/
public static void DecodeStreamList(final List<DraftWithPath> draftWithPaths, final DraftCallback callback) {
Observable.create(new Observable.OnSubscribe<List<DraftWithPath>>() {
@Override
public void call(Subscriber<? super List<DraftWithPath>> subscriber) {
subscriber.onNext(draftWithPaths);
subscriber.onCompleted();
}
}).flatMap(new Func1<List<DraftWithPath>, Observable<List<Draft>>>() {
@Override
public Observable<List<Draft>> call(List<DraftWithPath> draftWithPaths) {
List<Draft> drafts = new ArrayList<Draft>();
for (int i = 0; i < draftWithPaths.size(); i++) {
Bitmap bitmap = null;
File file = new File(draftWithPaths.get(i).getPicture());
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fileInputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Draft draft = new Draft(draftWithPaths.get(i).getDate(), draftWithPaths.get(i).getContent(), bitmap);
drafts.add(draft);
}
List<List<Draft>> result = new ArrayList<List<Draft>>();
result.add(drafts);
return Observable.from(result);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<Draft>>() {
@Override
public void call(List<Draft> drafts) {
callback.callback(drafts);
}
});
}
/**
* 变化整个队列
*
* @param context
* @param drafts
* @param callback
*/
public static void ChangeBitmapToPath(final Context context, final List<Draft> drafts, final DraftWithPathCallback callback) {
Observable.create(new Observable.OnSubscribe<List<Draft>>() {
@Override
public void call(Subscriber<? super List<Draft>> subscriber) {
subscriber.onNext(drafts);
subscriber.onCompleted();
}
}).flatMap(new Func1<List<Draft>, Observable<List<DraftWithPath>>>() {
@Override
public Observable<List<DraftWithPath>> call(List<Draft> drafts) {
List<DraftWithPath> draftWithPathList = new ArrayList<DraftWithPath>();
for (int i = 0; i < drafts.size(); i++) {
String path = Tools.saveImage(context, drafts.get(i).getPicture(), "draft_" + System.currentTimeMillis() + ".jpg");
draftWithPathList.add(new DraftWithPath(drafts.get(i).getDate(), drafts.get(i).getContent(), path));
}
List<List<DraftWithPath>> result = new ArrayList<List<DraftWithPath>>();
result.add(draftWithPathList);
return Observable.from(result);
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<DraftWithPath>>() {
@Override
public void call(List<DraftWithPath> draftWithPaths) {
callback.callback(draftWithPaths);
}
});
}
public interface BitmapCallback {
void callback(Bitmap bitmap);
}
public interface DraftCallback {
void callback(List<Draft> drafts);
}
public interface DraftWithPathCallback {
void callback(List<DraftWithPath> draftWithPaths);
}
}
| true |
7b20bfdcfa135150ce49331fb279d8429cfa6abe | Java | swapan-datahawklab/sql-wrapper-codegen | /src/main/java/org/jet/sql/codegen/wrapper/model/QueryArgument.java | UTF-8 | 3,216 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | package org.jet.sql.codegen.wrapper.model;
import java.sql.JDBCType;
/**
* Simple POJO to hold the query arguments parsed from the yaml file.
*
* @author tgorthi
* @since December 2019
*/
public class QueryArgument
{
private final int paramType;
private final String paramClassName;
private final String paramName;
private final int paramIndex;
public QueryArgument(
final String paramName, final int paramType, final String paramClassName,
final int paramIndex
)
{
this.paramType = paramType;
this.paramClassName = paramClassName;
this.paramName = paramName;
this.paramIndex = paramIndex;
}
public String getParamTypeName()
{
return JDBCType.valueOf(paramType).getName();
}
public String getParamClassName()
{
return paramClassName;
}
public String getParamName()
{
return paramName;
}
public int getParamIndex()
{
return paramIndex;
}
/**
* @return Returns a string in special format after
* - removing any and all underscores
* - the return string is in camelcase format , except the first character is lower case
* and upper case
* (since the method names need to start with lower case and the value returned by this
* method is used as the method name in the generated sql wrapper classes)
* @throws RuntimeException if the argument name has special characters excluding ("-")
*/
public String evaluateAndGetArgumentSetterMethodName()
{
final StringBuilder sb = new StringBuilder();
boolean previousCharWasUnderscore = false;
for (int i = 0; i < paramName.length(); i++)
{
final char c = paramName.charAt(i);
if (c == '_')
{
if (previousCharWasUnderscore)
{
throw new RuntimeException("Invalid argument name, underscore must be followed by a valid " +
"alphanumeric character");
}
previousCharWasUnderscore = true;
sb.append(c);
continue;
}
if (!Character.isAlphabetic(c) && !Character.isDigit(c))
{
throw new RuntimeException("argument name cannot contain special characters, only letters or numbers " +
"are" +
" allowed");
}
sb.append(previousCharWasUnderscore && Character.isAlphabetic(c) ? Character.toUpperCase(c) : Character.isAlphabetic(c) ? Character.toLowerCase(c) : c);
previousCharWasUnderscore = false;
}
if (sb.length() == 0)
{
throw new RuntimeException("Invalid argument name : " + paramName);
}
return sb.toString().toUpperCase();
}
@Override
public String toString()
{
return "QueryArgument{" +
"paramType=" + paramType +
", paramClassName='" + paramClassName + '\'' +
", paramName='" + paramName + '\'' +
", paramIndex=" + paramIndex +
'}';
}
}
| true |
64256a3965146699aa3b5cb20252910f98890ad2 | Java | DeadActive/CH8 | /src/chip/ChipPanel.java | UTF-8 | 514 | 2.53125 | 3 | [] | no_license | package chip;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class ChipPanel extends JPanel{
/**
*
*/
private static final long serialVersionUID = -5532772509883739069L;
public void paint(Graphics g){
byte[] display = CPU.screen;
for (int i = 0;i<display.length;i++){
if(display[i] == 0)
g.setColor(Color.BLACK);
else
g.setColor(Color.WHITE);
int x = (i%64);
int y = (int)Math.floor(i/64);
g.fillRect(x*10, y*10, 10, 10);
}
}
}
| true |
c206e0978472234965af1d6bc79c206f7adc272a | Java | WilliamHXu/Maven.Casino | /src/main/java/io/zipcoder/casino/utilities/Dice.java | UTF-8 | 1,081 | 3.84375 | 4 | [] | no_license | package io.zipcoder.casino.utilities;
public class Dice {
// Instance Variables
private Integer numberOfDice;
private Integer[] diceArray;
// Constructors
public Dice(Integer numberOfDice){
this.numberOfDice = numberOfDice;
this.diceArray = new Integer[numberOfDice];
for(int i = 0; i < numberOfDice; i++){
diceArray[i] = 1;
}
}
// Methods
/**
* Throws the dice and returns the sum. Changes the diceArray array.
* @return Sum
*/
public Integer throwAndSum() {
Integer sum = 0;
for (int i = 0; i < numberOfDice; i++) {
Integer dieResult = RandomNumber.getRandomNumber(6);
sum += dieResult;
diceArray[i] = dieResult;
}
return sum;
}
/**
* Gets the numberOfDice
* @return
*/
public Integer getNumberOfDice(){
return this.numberOfDice;
}
/**
* Gets the diceArray
* @return
*/
public Integer[] getDiceArray(){
return this.diceArray;
}
}
| true |
5d0313a38a10681c33ba7004874b7f9cfa19f89f | Java | axl72/Analizador_lexico | /src/Principal.java | UTF-8 | 477 | 1.78125 | 2 | [] | no_license |
import controlador.CtrlVista;
import modelo.ADP.Parser;
import modelo.Sistema;
import vista.Vista;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author axell
*/
public class Principal {
public static void main(String [] args){
Vista vs = new Vista();
CtrlVista ctrl= new CtrlVista(vs);
}
}
| true |
c9ecce8f3274b2e2f0ab102c1fa3d7c04ddf86af | Java | ballyang747/sqlserverdemo | /src/main/java/org/fkjava/mybatis1sb/util/wsDemo.java | UTF-8 | 920 | 2.28125 | 2 | [] | no_license | package org.fkjava.mybatis1sb.util;
import java.util.List;
import javax.xml.bind.JAXB;
import javax.xml.transform.dom.DOMSource;
import org.fkjava.mybatis1sb.domain.AirLine;
import org.fkjava.mybatis1sb.domain.AirLine.Address;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import cn.com.webxml.DomesticAirline;
import cn.com.webxml.DomesticAirlineSoap;
public class wsDemo {
public static void main(String[] args) {
DomesticAirline da = new DomesticAirline();
DomesticAirlineSoap soap = da.getDomesticAirlineSoap12();
Object any = soap.getDomesticCity().getAny();
Element e = (Element) any;
Node airline1 = e.getChildNodes().item(0);
AirLine airline= JAXB.unmarshal(new DOMSource(airline1), AirLine.class);
List<Address> addresses = airline.getAddresses();
String cnCityName = addresses.get(0).getCnCityName();
System.out.println(cnCityName);
}
}
| true |
05d83660050e7cbac4c22e36fe185cd10f7a9e51 | Java | colining/leetcode | /src/cn/colining/bat/dp/Backpack.java | UTF-8 | 651 | 3.203125 | 3 | [] | no_license | package cn.colining.bat.dp;
/**
* Created by colin on 2017/8/11.
*/
public class Backpack {
public static void main(String[] args) {
int[] a = new int[]{1, 2, 3};
int[] b = new int[]{1, 2, 3};
int n = 3;
int cap = 6;
System.out.println(maxValue(a, b, n, cap));
}
public static int maxValue(int[] w, int[] v, int n, int cap) {
// write code here
int[] dp = new int[cap+1];
for (int i = 0; i < n; i++) {
for (int j = cap; j >= w[i]; j--) {
dp[j] = Math.max(dp[j], dp[j - w[i]] + v[i]);
}
}
return dp[cap];
}
}
| true |
a7f3540492a7a96befafe2d29c66f000f37c256f | Java | soldiers1989/forcer | /src/main/java/com/huagu/common/enums/CabinetStatus.java | UTF-8 | 346 | 2.140625 | 2 | [] | no_license | package com.huagu.common.enums;
/**
* @ClassName: CabinetStatus
* @Description: 柜组状态(是否通电<=>是否接入系统)
* @author tj
* @date 2018年3月12日 上午11:37:18
*/
public enum CabinetStatus {
/**
* 0没有接入系统,1接入系统
* 0没有启用,1启用中
*/
NOTJOINUP, JOINUP;
}
| true |
601d19719ee7b536c720a279e85d7336df4d0240 | Java | sullis/twilio-java | /src/main/java/com/twilio/rest/video/v1/CompositionCreator.java | UTF-8 | 11,927 | 1.992188 | 2 | [
"MIT"
] | permissive | /**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.rest.video.v1;
import com.twilio.base.Creator;
import com.twilio.converter.Converter;
import com.twilio.converter.Promoter;
import com.twilio.exception.ApiConnectionException;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
import java.net.URI;
import java.util.List;
import java.util.Map;
public class CompositionCreator extends Creator<Composition> {
private final String roomSid;
private Map<String, Object> videoLayout;
private List<String> audioSources;
private List<String> audioSourcesExcluded;
private String resolution;
private Composition.Format format;
private URI statusCallback;
private HttpMethod statusCallbackMethod;
private Boolean trim;
/**
* Construct a new CompositionCreator.
*
* @param roomSid The SID of the Group Room with the media tracks to be used as
* composition sources
*/
public CompositionCreator(final String roomSid) {
this.roomSid = roomSid;
}
/**
* An object that describes the video layout of the composition in terms of
* regions. See <a
* href="https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts">Specifying
* Video Layouts</a> for more info. Please, be aware that either video_layout or
* audio_sources have to be provided to get a valid creation request.
*
* @param videoLayout An object that describes the video layout of the
* composition
* @return this
*/
public CompositionCreator setVideoLayout(final Map<String, Object> videoLayout) {
this.videoLayout = videoLayout;
return this;
}
/**
* An array of track names from the same group room to merge into the new
* composition. Can include zero or more track names. The new composition
* includes all audio sources specified in `audio_sources` except for those
* specified in `audio_sources_excluded`. The track names in this parameter can
* include an asterisk as a wild card character, which will match zero or more
* characters in a track name. For example, `student*` includes `student` as
* well as `studentTeam`. Please, be aware that either video_layout or
* audio_sources have to be provided to get a valid creation request.
*
* @param audioSources An array of track names from the same group room to merge
* @return this
*/
public CompositionCreator setAudioSources(final List<String> audioSources) {
this.audioSources = audioSources;
return this;
}
/**
* An array of track names from the same group room to merge into the new
* composition. Can include zero or more track names. The new composition
* includes all audio sources specified in `audio_sources` except for those
* specified in `audio_sources_excluded`. The track names in this parameter can
* include an asterisk as a wild card character, which will match zero or more
* characters in a track name. For example, `student*` includes `student` as
* well as `studentTeam`. Please, be aware that either video_layout or
* audio_sources have to be provided to get a valid creation request.
*
* @param audioSources An array of track names from the same group room to merge
* @return this
*/
public CompositionCreator setAudioSources(final String audioSources) {
return setAudioSources(Promoter.listOfOne(audioSources));
}
/**
* An array of track names to exclude. The new composition includes all audio
* sources specified in `audio_sources` except for those specified in
* `audio_sources_excluded`. The track names in this parameter can include an
* asterisk as a wild card character, which will match zero or more characters
* in a track name. For example, `student*` excludes `student` as well as
* `studentTeam`. This parameter can also be empty..
*
* @param audioSourcesExcluded An array of track names to exclude
* @return this
*/
public CompositionCreator setAudioSourcesExcluded(final List<String> audioSourcesExcluded) {
this.audioSourcesExcluded = audioSourcesExcluded;
return this;
}
/**
* An array of track names to exclude. The new composition includes all audio
* sources specified in `audio_sources` except for those specified in
* `audio_sources_excluded`. The track names in this parameter can include an
* asterisk as a wild card character, which will match zero or more characters
* in a track name. For example, `student*` excludes `student` as well as
* `studentTeam`. This parameter can also be empty..
*
* @param audioSourcesExcluded An array of track names to exclude
* @return this
*/
public CompositionCreator setAudioSourcesExcluded(final String audioSourcesExcluded) {
return setAudioSourcesExcluded(Promoter.listOfOne(audioSourcesExcluded));
}
/**
* A string that describes the columns (width) and rows (height) of the
* generated composed video in pixels. Defaults to `640x480`.
* The string's format is `{width}x{height}` where:
*
* * 16 <= `{width}` <= 1280
* * 16 <= `{height}` <= 1280
* * `{width}` * `{height}` <= 921,600
*
* Typical values are:
*
* * HD = `1280x720`
* * PAL = `1024x576`
* * VGA = `640x480`
* * CIF = `320x240`
*
* Note that the `resolution` imposes an aspect ratio to the resulting
* composition. When the original video tracks are constrained by the aspect
* ratio, they are scaled to fit. See <a
* href="https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts">Specifying
* Video Layouts</a> for more info..
*
* @param resolution A string that describes the columns (width) and rows
* (height) of the generated composed video in pixels
* @return this
*/
public CompositionCreator setResolution(final String resolution) {
this.resolution = resolution;
return this;
}
/**
* The container format of the composition's media files. Can be: `mp4` or
* `webm` and the default is `webm`. If you specify `mp4` or `webm`, you must
* also specify one or more `audio_sources` and/or a `video_layout` element that
* contains a valid `video_sources` list, otherwise an error occurs..
*
* @param format The container format of the composition's media files
* @return this
*/
public CompositionCreator setFormat(final Composition.Format format) {
this.format = format;
return this;
}
/**
* The URL we should call using the `status_callback_method` to send status
* information to your application on every composition event. If not provided,
* status callback events will not be dispatched..
*
* @param statusCallback The URL we should call to send status information to
* your application
* @return this
*/
public CompositionCreator setStatusCallback(final URI statusCallback) {
this.statusCallback = statusCallback;
return this;
}
/**
* The URL we should call using the `status_callback_method` to send status
* information to your application on every composition event. If not provided,
* status callback events will not be dispatched..
*
* @param statusCallback The URL we should call to send status information to
* your application
* @return this
*/
public CompositionCreator setStatusCallback(final String statusCallback) {
return setStatusCallback(Promoter.uriFromString(statusCallback));
}
/**
* The HTTP method we should use to call `status_callback`. Can be: `POST` or
* `GET` and the default is `POST`..
*
* @param statusCallbackMethod The HTTP method we should use to call
* status_callback
* @return this
*/
public CompositionCreator setStatusCallbackMethod(final HttpMethod statusCallbackMethod) {
this.statusCallbackMethod = statusCallbackMethod;
return this;
}
/**
* Whether to clip the intervals where there is no active media in the
* composition. The default is `true`. Compositions with `trim` enabled are
* shorter when the Room is created and no Participant joins for a while as well
* as if all the Participants leave the room and join later, because those gaps
* will be removed. See <a
* href="https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts">Specifying
* Video Layouts</a> for more info..
*
* @param trim Whether to clip the intervals where there is no active media in
* the composition
* @return this
*/
public CompositionCreator setTrim(final Boolean trim) {
this.trim = trim;
return this;
}
/**
* Make the request to the Twilio API to perform the create.
*
* @param client TwilioRestClient with which to make the request
* @return Created Composition
*/
@Override
@SuppressWarnings("checkstyle:linelength")
public Composition create(final TwilioRestClient client) {
Request request = new Request(
HttpMethod.POST,
Domains.VIDEO.toString(),
"/v1/Compositions"
);
addPostParams(request);
Response response = client.request(request);
if (response == null) {
throw new ApiConnectionException("Composition creation failed: Unable to connect to server");
} else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) {
RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper());
if (restException == null) {
throw new ApiException("Server Error, no content");
}
throw new ApiException(restException);
}
return Composition.fromJson(response.getStream(), client.getObjectMapper());
}
/**
* Add the requested post parameters to the Request.
*
* @param request Request to add post params to
*/
private void addPostParams(final Request request) {
if (roomSid != null) {
request.addPostParam("RoomSid", roomSid);
}
if (videoLayout != null) {
request.addPostParam("VideoLayout", Converter.mapToJson(videoLayout));
}
if (audioSources != null) {
for (String prop : audioSources) {
request.addPostParam("AudioSources", prop);
}
}
if (audioSourcesExcluded != null) {
for (String prop : audioSourcesExcluded) {
request.addPostParam("AudioSourcesExcluded", prop);
}
}
if (resolution != null) {
request.addPostParam("Resolution", resolution);
}
if (format != null) {
request.addPostParam("Format", format.toString());
}
if (statusCallback != null) {
request.addPostParam("StatusCallback", statusCallback.toString());
}
if (statusCallbackMethod != null) {
request.addPostParam("StatusCallbackMethod", statusCallbackMethod.toString());
}
if (trim != null) {
request.addPostParam("Trim", trim.toString());
}
}
} | true |
2a52f48607116671d40eb94d93d3844fc5697087 | Java | 2021-j3/spring-backend | /src/main/java/com/ecommerce/j3/domain/mapper/AccountMapper.java | UTF-8 | 2,602 | 2.3125 | 2 | [] | no_license | package com.ecommerce.j3.domain.mapper;
import com.ecommerce.j3.domain.entity.Account;
import com.ecommerce.j3.controller.dto.AccountDto;
import com.ecommerce.j3.domain.entity.Order;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.ReportingPolicy;
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE, uses = {CommonMapper.class})
public abstract class AccountMapper implements DefaultMapper<Account, AccountDto.AccountApiRequest, AccountDto.AccountApiResponse>{
@Mapping(source="password", target="passwordHash")
@Override
public abstract Account toEntity(AccountDto.AccountApiRequest dto);
@Override
public abstract AccountDto.AccountApiResponse toApiResponse(Account entity);
public abstract AccountDto.AccountApiRequest toRequestDto(AccountDto.UpdateAccountRequest dtoWithSomeField);
public abstract AccountDto.AccountApiRequest toRequestDto(AccountDto.CreateAccountRequest dtoWithSomeField);
public abstract AccountDto.CreateAccountResponse toCreateAccountResponse(Account account);
@Override
public Account updateFromDto(@MappingTarget Account entity, AccountDto.AccountApiRequest dto){
if (dto == null) return entity;
Account db = entity;
entity = Account.builder()
// db 값만 존재
.accountId(db.getAccountId())
.registeredAt(db.getRegisteredAt())
.lastLogin(db.getLastLogin())
// 필수 값, 입력된 값이 null일 경우, 기존 값을 사용
.defaultAddress(dto.getDefaultAddress()!=null? dto.getDefaultAddress() : db.getDefaultAddress())
.email((dto.getEmail()!=null && !dto.getEmail().equals("")) ? dto.getEmail() : db.getEmail())
.passwordHash((dto.getPassword()!=null && !dto.getPassword().equals("")) ? dto.getPassword() : db.getPasswordHash())
.firstName((dto.getFirstName()!=null && !dto.getFirstName().equals("")) ? dto.getFirstName() : db.getFirstName())
.lastName((dto.getLastName()!=null && !dto.getLastName().equals("")) ? dto.getLastName() : db.getLastName())
.gender(dto.getGender() != null ? dto.getGender() : db.getGender())
.accountType(dto.getAccountType() != null ? dto.getAccountType() : db.getAccountType())
// 필수 아님, null 가능
.birthday(dto.getBirthday())
.phoneNumber(dto.getPhoneNumber())
.build();
return entity;
}
}
| true |
1d8ccccd4669aecc067069864bd9347dd1a41eb0 | Java | sagara177/atndbot | /src/atndbot/CronTaskHandler.java | UTF-8 | 1,133 | 2.203125 | 2 | [] | no_license | package atndbot;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import atndbot.util.AtndCalendar;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.*;
@SuppressWarnings("serial")
public class CronTaskHandler extends HttpServlet {
@SuppressWarnings("unused")
private static Logger logger =
Logger.getLogger(CronTaskHandler.class.getName());
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// fetch 2 months event data
List<String> yyyymmddList = AtndCalendar.getYYYYMMDDList(30 * 2);
// set task queue
Queue queue = QueueFactory.getQueue("atnd-event-fetch-queue");
for (String yyyymmdd : yyyymmddList) {
queue.add(url("/atndFetchHandler").param("yyyymmdd", yyyymmdd));
}
}
}
| true |
59babed906bd5e6fe3bdfecb7326e72da8458ae8 | Java | goofy1019/Monster-TECG | /src/cartas/Carta.java | UTF-8 | 1,062 | 2.640625 | 3 | [] | no_license | package cartas;
public class Carta {
private String tipo;
private String nombre;
private String descripcion;
private int ID;
private int mana;
private boolean status;
public Carta(boolean stat, String tip, String nom, String des, int id, int man) {
this.status = stat;
this.tipo = tip;
this.nombre = nom;
this.descripcion = des;
this.ID = id;
this.mana = man;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public int getMana() {
return mana;
}
public void setMana(int mana) {
this.mana = mana;
}
}
| true |
ed6f52acf713a11dffe7ba61927e2c651bb72985 | Java | xlsbz/javaEE | /SignIn/src/controller/SignInS.java | GB18030 | 6,014 | 2.453125 | 2 | [] | no_license | package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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 entity.Apply;
import entity.Meeting;
import entity.SignIn;
import page.PageInfo;
import dao.SignInInfo;
/**
* @author ǩϢĿ
* @Servlet implementation class MeetingC
*/
@WebServlet("/SignInS")
public class SignInS extends HttpServlet {
private static final long serialVersionUID = 1L;
SignInInfo signInInfo;
String url;
public SignInS() {
signInInfo = new SignInInfo();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();// ã
String option = request.getParameter("option");// requestûûύݣύ
switch (option) {
case "getAllSignIn":
getAllSignIn(request);
break;
case "addSignInInfo":// ͨԱŲѯԱǩϢ
addSignInInfo(request);
break;
case "deleteSignInInfo":// ͨǩڲѯǩϢ
deleteSignInInfo(request);
break;
case "updateSignInInfo":// ǩϢ
updateSignInInfo(request);
break;
case "addMSI":// ӻǩϢ
// addMSI(request);
break;
case "getMSI":// ͨԱŲѯǩϢ
// getAllSI(request);
break;
case "getMSIByDate":// ͨԱŲѯǩϢ
// getAllSI(request);
break;
case "deleteAllWSI":// ͨԱŲѯǩϢ
//deleteAllWSI(request);
break;
case "deleteAllMSI":// ͨԱŲѯǩϢ
// deleteAllMSI(request);
break;
default:
break;
}
request.getRequestDispatcher(url).forward(request, response);
}
public void getAllSignIn(HttpServletRequest request) {
String firstResult = request.getParameter("firstResult");
PageInfo pageInfo = new PageInfo();//ûûдȷIJĬϵһҳ
if(firstResult == null){
firstResult = "0";
}
pageInfo.setFirstResult(firstResult);//ûõĵһıţ浽pageInfoзһ
pageInfo.setMaxResults("4");
List<SignIn> signins;
if(request.getParameter("suboption")!=null&&request.getParameter("suboption").equals("nopage")){
signins = signInInfo.getAllSignIn();
}else{
signins = signInInfo.getAllSignInByPage(pageInfo);
}
//List<Admin> admins = adminInfo.getAllAdminByPage(pageInfo);
request.setAttribute("pageInfo", pageInfo);
request.setAttribute("signins", signins);//studentsһjavaеıϣҪ浽ҳУҳʾ
}
public void getSignInByID(HttpServletRequest request) {
SignIn signin = signInInfo.getSignInByID();
request.setAttribute("signin", signin);
}
public void addSignInInfo(HttpServletRequest request) {
String signId = request.getParameter("signId");
String signNumber = request.getParameter("signNumber");
String signAdress = request.getParameter("signAdress");
String signTime = request.getParameter("signTime");
String signBeizhu = request.getParameter("signBeizhu");
String admId = request.getParameter("admId");
SignIn sigin = new SignIn(signId,signNumber,signAdress,signTime,signBeizhu,admId);
int result = signInInfo.addSignInfo(sigin);
request.setAttribute("result", result);
request.setAttribute("sigin", sigin);
System.out.println(result);
//adminInfo.addAdminInfo(admin);//еݷװstudent֮dao
//msgҳʾûصIJ
String msg = "";
if(result >=1){
msg = "ӳɹ";
}else{
msg = "ʧܣԭǸûѴ";
}
request.setAttribute("msg", msg);
url = "admin/sign/signlist.jsp";//תĵַ
}
public void updateSignInInfo(HttpServletRequest request) {
String signId = request.getParameter("signId");
String signNumber = request.getParameter("signNumber");
String signAdress = request.getParameter("signAdress");
String signTime = request.getParameter("signTime");
String signBeizhu = request.getParameter("signBeizhu");
String admId = request.getParameter("admId");
SignIn sigin = new SignIn(signId,signNumber,signAdress,signTime,signBeizhu,admId);
int result = signInInfo.updateSignInInfo(sigin);
request.setAttribute("result", result);
request.setAttribute("sigin", sigin);
System.out.println(result);
//msgҳʾûصIJ
String msg = "";
if(result >=1){
msg = "³ɹ";
}else{
msg = "ʧ";
}
request.setAttribute("msg", msg);
url = "admin/sign/signlist.jsp";//תĵַ
}
public void deleteSignInInfo(HttpServletRequest request) {
String signId = request.getParameter("signId"); ;
int result = signInInfo.deleteSignInInfo(signId);//еݷװstudent֮dao
request.setAttribute("result", result);
//request.setAttribute("admin", admin);
System.out.println(result);
//msgҳʾûصIJ
String msg = "";
if(result >=1){
msg = "ɾɹ";
}else{
msg = "ɾʧ";
}
request.setAttribute("msg", msg);
url = "admin/sign/signlist.jsp";//תĵַ
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| true |
016a3aabad54d1f9799b0258ecb9afbf782b3549 | Java | rcoolboy/guilvN | /app/src/main/java/com/p118pd/sdk/C9539LliII.java | UTF-8 | 6,140 | 1.695313 | 2 | [] | no_license | package com.p118pd.sdk;
import com.umeng.message.proguard.C3848l;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import org.bouncycastle.cert.crmf.CRMFException;
import org.bouncycastle.operator.RuntimeOperatorException;
import org.bouncycastle.util.Strings;
/* renamed from: com.pd.sdk.丨Ll丨iII reason: invalid class name and case insensitive filesystem */
public class C9539LliII {
public int OooO00o;
/* renamed from: OooO00o reason: collision with other field name */
public C5612LI1l f23102OooO00o;
/* renamed from: OooO00o reason: collision with other field name */
public C6456l1ilL f23103OooO00o;
/* renamed from: OooO00o reason: collision with other field name */
public AbstractC6594lLi1l1 f23104OooO00o;
/* renamed from: OooO00o reason: collision with other field name */
public SecureRandom f23105OooO00o;
public int OooO0O0;
/* renamed from: OooO0O0 reason: collision with other field name */
public C6456l1ilL f23106OooO0O0;
public int OooO0OO;
/* renamed from: com.pd.sdk.丨Ll丨iII$OooO00o */
public class OooO00o implements AbstractC6296il1il1 {
public final /* synthetic */ C5612LI1l OooO00o;
/* renamed from: OooO00o reason: collision with other field name */
public ByteArrayOutputStream f23108OooO00o = new ByteArrayOutputStream();
/* renamed from: OooO00o reason: collision with other field name */
public final /* synthetic */ byte[] f23109OooO00o;
public OooO00o(C5612LI1l r2, byte[] bArr) {
this.OooO00o = r2;
this.f23109OooO00o = bArr;
}
@Override // com.p118pd.sdk.AbstractC6296il1il1, com.p118pd.sdk.AbstractC6296il1il1, com.p118pd.sdk.AbstractC6296il1il1, com.p118pd.sdk.AbstractC6296il1il1
public LIiI11 OooO00o() {
return new LIiI11(m21593OooO00o(), this.f23109OooO00o);
}
@Override // com.p118pd.sdk.AbstractC6296il1il1, com.p118pd.sdk.AbstractC6296il1il1, com.p118pd.sdk.AbstractC6296il1il1, com.p118pd.sdk.AbstractC6296il1il1
/* renamed from: OooO00o reason: collision with other method in class */
public C6456l1ilL m21593OooO00o() {
return new C6456l1ilL(lILIlI.OooO00o, this.OooO00o);
}
@Override // com.p118pd.sdk.AbstractC6296il1il1, com.p118pd.sdk.AbstractC6296il1il1, com.p118pd.sdk.AbstractC6296il1il1, com.p118pd.sdk.AbstractC6296il1il1
/* renamed from: OooO00o reason: collision with other method in class */
public OutputStream m21594OooO00o() {
return this.f23108OooO00o;
}
@Override // com.p118pd.sdk.AbstractC6296il1il1, com.p118pd.sdk.AbstractC6296il1il1, com.p118pd.sdk.AbstractC6296il1il1, com.p118pd.sdk.AbstractC6296il1il1
/* renamed from: OooO00o reason: collision with other method in class */
public byte[] m21595OooO00o() {
try {
return C9539LliII.this.f23104OooO00o.OooO00o(this.f23109OooO00o, this.f23108OooO00o.toByteArray());
} catch (CRMFException e) {
throw new RuntimeOperatorException("exception calculating mac: " + e.getMessage(), e);
}
}
}
public C9539LliII(C6456l1ilL r2, int i, C6456l1ilL r4, AbstractC6594lLi1l1 r5) {
this.OooO0O0 = 20;
this.f23103OooO00o = r2;
this.OooO00o = i;
this.f23106OooO0O0 = r4;
this.f23104OooO00o = r5;
}
public C9539LliII(AbstractC6594lLi1l1 r5) {
this(new C6456l1ilL(AbstractC9733l.OooO), 1000, new C6456l1ilL(AbstractC5604L1ll.OooOOOO, C6452l1Lll.OooO00o), r5);
}
public C9539LliII(AbstractC6594lLi1l1 r2, int i) {
this.OooO0O0 = 20;
this.OooO0OO = i;
this.f23104OooO00o = r2;
}
private AbstractC6296il1il1 OooO00o(C5612LI1l r5, char[] cArr) throws CRMFException {
byte[] OooO0O02 = Strings.OooO0O0(cArr);
byte[] OooO00o2 = r5.m16021OooO00o().m17938OooO00o();
byte[] bArr = new byte[(OooO0O02.length + OooO00o2.length)];
System.arraycopy(OooO0O02, 0, bArr, 0, OooO0O02.length);
System.arraycopy(OooO00o2, 0, bArr, OooO0O02.length, OooO00o2.length);
this.f23104OooO00o.OooO00o(r5.m16022OooO0O0(), r5.OooO00o());
int intValue = r5.m16020OooO00o().m17647OooO0O0().intValue();
do {
bArr = this.f23104OooO00o.OooO00o(bArr);
intValue--;
} while (intValue > 0);
return new OooO00o(r5, bArr);
}
private void OooO00o(int i) {
int i2 = this.OooO0OO;
if (i2 > 0 && i > i2) {
throw new IllegalArgumentException("iteration count exceeds limit (" + i + " > " + this.OooO0OO + C3848l.f10402t);
}
}
public AbstractC6296il1il1 OooO00o(char[] cArr) throws CRMFException {
C5612LI1l r0 = this.f23102OooO00o;
if (r0 != null) {
return OooO00o(r0, cArr);
}
byte[] bArr = new byte[this.OooO0O0];
if (this.f23105OooO00o == null) {
this.f23105OooO00o = new SecureRandom();
}
this.f23105OooO00o.nextBytes(bArr);
return OooO00o(new C5612LI1l(bArr, this.f23103OooO00o, this.OooO00o, this.f23106OooO0O0), cArr);
}
/* renamed from: OooO00o reason: collision with other method in class */
public C9539LliII m21592OooO00o(int i) {
if (i >= 100) {
OooO00o(i);
this.OooO00o = i;
return this;
}
throw new IllegalArgumentException("iteration count must be at least 100");
}
public C9539LliII OooO00o(C5612LI1l r2) {
OooO00o(r2.m16020OooO00o().m17647OooO0O0().intValue());
this.f23102OooO00o = r2;
return this;
}
public C9539LliII OooO00o(SecureRandom secureRandom) {
this.f23105OooO00o = secureRandom;
return this;
}
public C9539LliII OooO0O0(int i) {
if (i >= 8) {
this.OooO0O0 = i;
return this;
}
throw new IllegalArgumentException("salt length must be at least 8 bytes");
}
}
| true |
583ab848f6a769c4121d0015075ad8c4bfe2ff14 | Java | jebedi/java-exercises | /src/main/java/designpattern/behavioral/mediator/ChatParticipant.java | UTF-8 | 654 | 3.234375 | 3 | [] | no_license | package designpattern.behavioral.mediator;
public class ChatParticipant {
private final String username;
private final ChatMediator chatRoom;
public ChatParticipant(String username, ChatMediator chatRoom) {
this.username = username;
this.chatRoom = chatRoom;
}
public String getUsername() {
return username;
}
void sendMessage(String message) {
System.out.println(">" + username + ": " + message);
chatRoom.sendMessage(message, username);
}
void receiveMessage(String message, String user) {
System.out.println("|" + username + "|" + user + ":" + message);
}
}
| true |
26ec85ec964b5e98da332a3c303fc8b37350d4e2 | Java | edisaac/carrito | /cart/src/main/java/cart/com/entity/Orden.java | UTF-8 | 1,659 | 2.0625 | 2 | [] | no_license | package cart.com.entity;
// Generated 15-may-2016 19:15:35 by Hibernate Tools 4.3.1.Final
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
/**
* Orden generated by hbm2java
*/
public class Orden implements java.io.Serializable {
private int idOrden;
private Establecimiento establecimiento;
private String celular;
private BigDecimal monto;
private Set<DetalleOrden> detalleOrdens = new HashSet<DetalleOrden>(0);
public Orden() {
}
public Orden(int idOrden) {
this.idOrden = idOrden;
}
public Orden(int idOrden, Establecimiento establecimiento, String celular, BigDecimal monto,
Set<DetalleOrden> detalleOrdens) {
this.idOrden = idOrden;
this.establecimiento = establecimiento;
this.celular = celular;
this.monto = monto;
this.detalleOrdens = detalleOrdens;
}
public int getIdOrden() {
return this.idOrden;
}
public void setIdOrden(int idOrden) {
this.idOrden = idOrden;
}
public Establecimiento getEstablecimiento() {
return this.establecimiento;
}
public void setEstablecimiento(Establecimiento establecimiento) {
this.establecimiento = establecimiento;
}
public String getCelular() {
return this.celular;
}
public void setCelular(String celular) {
this.celular = celular;
}
public BigDecimal getMonto() {
return this.monto;
}
public void setMonto(BigDecimal monto) {
this.monto = monto;
}
public Set<DetalleOrden> getDetalleOrdens() {
return this.detalleOrdens;
}
public void setDetalleOrdens(Set<DetalleOrden> detalleOrdens) {
this.detalleOrdens = detalleOrdens;
}
}
| true |
0cfb6c71582325d6b2f7fe2488ef401e8d6244b5 | Java | bondardima1990/MainAcademy | /src/SE/Theme08JavaNetworking/Lab1/Main.java | UTF-8 | 1,035 | 4.03125 | 4 | [] | no_license | package SE.Theme08JavaNetworking.Lab1;
/**
* 1) Create a Student class with private fields: String name, String course, int id.
* Add getters and setters to Student class. Override the toString() method. <p>
*
* 2) Create a MyClient class, which receives a Student's instance and sends it to the server via a socket connection,
* and then receives and outputs the server's response.
* You can implement this class as a separate thread. <p>
*
* 3) Create a MyServer class, which establishes a socket connection with the client,
* and then outputs the received information, and sends the response to the client.
* You can implement this class as a separate thread. <p>
*
* 4) Create a Main class with a main() method, which creates an instance of the class Student
* and runs the threads of server and of client on execution.
*/
public class Main {
public static void main(String[] args) throws InterruptedException {
//Student student = new Student("Dima", "Java", 1);
}
}
| true |
4450dba2679efef81a41a1c737a6a1b33514c007 | Java | tangflash/jewelryApp | /src/main/java/com/flash/jewelry/service/GoldTypeService.java | UTF-8 | 555 | 1.921875 | 2 | [] | no_license | package com.flash.jewelry.service;
import java.util.Collection;
import java.util.List;
import com.flash.jewelry.model.GoldType;
public interface GoldTypeService {
Collection<GoldType> selectGoldType(List list);
GoldType selectGoldTypeById(long id);
void updateGoldType(GoldType goldType);
void deleteGoldType(long id);
void insertGoldType(GoldType goldType);
boolean isRepeatByNum(GoldType goldType);
boolean isRepeatByName(GoldType goldType);
GoldType selectGoldTypeByNum(String num);
GoldType getGoldTypeByNumOrName(String goldTypeName);
}
| true |
dfd74d931fa4be4313c553c174d37dee63b648ad | Java | aibolit/BaseInvaders | /src/main/java/Server/BIServer.java | UTF-8 | 388 | 1.78125 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Server;
import Objects.GameMap;
/**
*
* @author Aleks
*/
public interface BIServer extends Runnable {
public GameMap getGameMap();
public boolean isRunning();
}
| true |
dc900ebfa0779703687fb8182aab9a33cc81b4ec | Java | KRUBERLICK/LearnJava | /src/lessons/java_complete_guide/part1/chapter3/AGScope.java | UTF-8 | 406 | 3.0625 | 3 | [] | no_license | package lessons.java_complete_guide.part1.chapter3;
/**
* Created by kruberlick on 2/9/16.
*/
public class AGScope {
public static void main(String[] args) {
int x;
x = 10;
if (x == 10) {
int y = 20;
x = y * 2;
}
// y = 100; Error! y is not known here!
System.out.println("x is " + x); // but x is still known here
}
}
| true |
6574ed788f08217ff966335a656666a9a46f70c0 | Java | xufuzhou1201/reportBuild | /src/main/java/com/jump/aop/constant/ConvertRegister.java | UTF-8 | 342 | 1.828125 | 2 | [
"MIT"
] | permissive | package com.jump.aop.constant;
/**
* @author Jump
* @date 2020/3/9 11:57
*/
public interface ConvertRegister<T, F, R> {
/**
* 转化
*
* @param targetObj targetObj
* @param filedName filedName
* @param filedVale filedVale
* @return R
*/
R convert(T targetObj, String filedName, F filedVale);
}
| true |
30c4e234bcd5bfc3efd66705fe9934ecdf91b03a | Java | LDawns/java20-homework | /8-Generics/韩畅-171860551/src/Units/OldMan.java | UTF-8 | 5,097 | 2.546875 | 3 | [] | no_license | package Units;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Random;
import java.util.Vector;
import Ground.Ground;
import Ground.Tile;
import UnitCollection.CharacterColl;
import UnitCollection.ORDER;
public class OldMan extends Character {
// private Vector<HuLuBaby> childList;
private CharacterColl<HuLuBaby> childList;
// ---- 一些随机起名的参数 ----
private static final String FuYinBase = "bcdfghjklmnpqrstvwxyz";
private static final String YuanYinBase = "aeiou";
private static final String FuYinBaseSuf = "ygklmnpsxztv";
private static final int MIN_NAME_LEN = 2;
private static final int NAME_LEN_OFF = 2;
private String randANewName()
{
Random rand = new Random();
int wordsNum = MIN_NAME_LEN + rand.nextInt(NAME_LEN_OFF);
StringBuilder nameBd = new StringBuilder();
for (int i = 0; i < wordsNum; ++i){
int fuYinInd1 = rand.nextInt(FuYinBase.length());
int fuYinInd2 = rand.nextInt(FuYinBaseSuf.length());
int yuanYinInd = rand.nextInt(YuanYinBase.length());
nameBd.append(FuYinBase.charAt(fuYinInd1));
nameBd.append(YuanYinBase.charAt(yuanYinInd));
nameBd.append(FuYinBaseSuf.charAt(fuYinInd2));
if (i != wordsNum-1)
nameBd.append(" ");
}
return nameBd.toString();
}
// 构造函数
// 阵营为正义阵营,维持一个葫芦娃的名单表
public OldMan(String n, int s, int h, Ground g) {
// TODO Auto-generated constructor stub
super(n, s, h, g, true);// 必然是男性
this.factionType = FACTION_TYPE.JUSTICE;
//childList = new Vector<HuLuBaby>();
childList = new CharacterColl<>();
}
// 为葫芦娃接生,需要给出名字
// public void giveBirth(String n, COLOR c) {
// childList.add(new HuLuBaby(n, 10, 100, new Random().nextBoolean(), myGr, this, c, childList.size() + 1));
// }
//
// public void giveBirth(){
// Random r = new Random();
// childList.add(new HuLuBaby(randANewName(), 10, 100, r.nextBoolean(), myGr, this, COLOR.values()[r.nextInt(7)], childList.size() + 1));
// }
// ---8th hw 之前由老爷爷决定葫芦娃的视野和血量等实现不太合适
// --- 下面的实现将属于两侧的属性区分开来
public void giveBirth(){
Random r = new Random();
childList.add(new HuLuBaby(randANewName(),myGr, this, childList.size() + 1));
}
// 使自己踏入地块中,仅仅做尝试
public void getMeIn() {
// TODO 错误检测
findAMerginToStepIn();
}
// 使所有葫芦娃踏入地块中
public void getAllTheBabyIn() {
// TODO 错误检测
Iterable<HuLuBaby> ls = childList.getIterable();
for (HuLuBaby hu : ls) {
hu.findAMerginToStepIn();
}
}
// 命令所有的葫芦娃走到1,0至1,6的位置
public void orderTheBabyToASeq() {
// TODO 命令友方做移开尝试
boolean success = true;
for (int j = 0; j < 3; ++j) {
for (int i = 0; i < 7; ++i) {
if (childList.get(i).findWayToXY(1, i) == false)
success = false;
}
if (success == true)
break;
}
}
// 命令葫芦娃随机平行交换位置
public void exchangeRandomly() {
for (int i = 0; i < 20; ++i) {
Random r = new Random();
int temR = r.nextInt(7);
// 随机到一个葫芦娃
Tile temT = myGr.whereIsHim(childList.get(temR));
HuLuBaby temBaby = childList.get(temR);
if (temT != null && temT.getLongitude() > 0) {
// TODO 这里的逻辑有点小问题,换位置不需要这么复杂
Tile des = myGr.howIsXY(temT.getLatitute(), temT.getLongitude() - 1, temBaby, sightSize);
temBaby.swap(des);
}
}
}
// 命令各个葫芦娃互相自行调整位置以排序
public void orderTheBabySwapToSort() {
boolean done = false;
while (done == false) {
done = true;
for (int i = 0; i < 7; ++i) {
if (!childList.get(i).swapIfMyRightIsOlderThanMe())
done = false;
}
}
}
@Override
public String[] situation(int line, int maxColLen) {
// TODO Auto-generated method stub
return super.situation(line, maxColLen);
}
public void ReadOutMyBabyListByIterable() {
System.out.println("Read Out My Baby List By Iterable: ");
Iterable<HuLuBaby> ls = childList.getIterable();
int i = 1;
for (HuLuBaby h: ls) {
System.out.println(String.valueOf(i++) + " " + h);
}
}
public void ReadOutMyBabyListByIterator() {
System.out.println("Read Out My Babies By Iterator: ");
Iterator<HuLuBaby> it = childList.getIterator();
int i = 1;
while(it.hasNext()) {
System.out.println(String.valueOf(i++) + " " + it.next());
}
}
public void sortChildList(ORDER od) {
System.out.println("Sort my babies by the " + od + " order");
childList.sortLs(od);
}
public void sortChildList(ORDER od, boolean sex) {
System.out.println("Sort my babies by the " + od + "order and group by sex" );
childList.sortLs(od, sex);
}
public void sortChildListByComparator(ORDER o, boolean b) {
Comparator<HuLuBaby> c = HuLuBaby.getComparator(o,b);
System.out.println("Sort my babies by the comparator");
childList.sortByComparator(c);
}
public void shuffle() {
System.out.println("Shuffling ... ");
childList.shuffle();
}
}
| true |
0b607f060b1dd092ad77f8b760bf94843d27b11d | Java | imakedev/imakedev-tem | /TEMRestServices/src/th/co/imake/tem/dto/TemMsIsdnPackageDetail.java | UTF-8 | 769 | 1.867188 | 2 | [] | no_license | package th.co.imake.tem.dto;
import java.io.Serializable;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("temMsIsdnPackageDetailDTO")
public class TemMsIsdnPackageDetail extends BaseDTO implements Serializable {
private static final long serialVersionUID = 1L;
@XStreamAlias("msIsdn")
private String msIsdn;
@XStreamAlias("temPackageDetailDTO")
private TemPackageDetail temPackageDetail;
public String getMsIsdn() {
return msIsdn;
}
public void setMsIsdn(String msIsdn) {
this.msIsdn = msIsdn;
}
public TemPackageDetail getTemPackageDetail() {
return temPackageDetail;
}
public void setTemPackageDetail(TemPackageDetail temPackageDetail) {
this.temPackageDetail = temPackageDetail;
}
}
| true |
74079cdd3c002f72829249a6991f6a9c617f992e | Java | sfurlow/SMP | /SMP/src/org/optaplanner/examples/tarostering/domain/TaRoster.java | UTF-8 | 5,799 | 1.65625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.examples.tarostering.domain;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.api.domain.solution.Solution;
import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.optaplanner.core.impl.score.buildin.hardsoft.HardSoftScoreDefinition;
import org.optaplanner.examples.common.domain.AbstractPersistable;
import org.optaplanner.examples.tarostering.domain.contract.Contract;
import org.optaplanner.examples.tarostering.domain.contract.ContractLine;
import org.optaplanner.examples.tarostering.domain.request.CourseOffRequest;
import org.optaplanner.examples.tarostering.domain.request.CourseOnRequest;
import org.optaplanner.persistence.xstream.impl.score.XStreamScoreConverter;
@PlanningSolution
@XStreamAlias("TaRoster")
public class TaRoster extends AbstractPersistable implements Solution<HardSoftScore> {
private String code;
private List<CourseType> courseTypeList;
private List<Contract> contractList;
private List<ContractLine> contractLineList;
private List<Ta> taList;
private List<CourseDay> courseDayList;
private List<Course> courseList;
private List<CourseOffRequest> courseOffRequestList;
private List<CourseOnRequest> courseOnRequestList;
//private List<Coordinator> coordinatorList;
private List<CourseAssignment> courseAssignmentList;
@XStreamConverter(value = XStreamScoreConverter.class, types = {HardSoftScoreDefinition.class})
private HardSoftScore score;
// public List<Coordinator> getCoordinatorList() {
// return coordinatorList;
// }
// public void setCoordinatorList(List<Coordinator> coordinatorList) {
// this.coordinatorList = coordinatorList;
// }
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public List<CourseType> getCourseTypeList() {
return courseTypeList;
}
public void setCourseTypeList(List<CourseType> courseTypeList) {
this.courseTypeList = courseTypeList;
}
public List<Contract> getContractList() {
return contractList;
}
public void setContractList(List<Contract> contractList) {
this.contractList = contractList;
}
public List<ContractLine> getContractLineList() {
return contractLineList;
}
public void setContractLineList(List<ContractLine> contractLineList) {
this.contractLineList = contractLineList;
}
@ValueRangeProvider(id = "taRange")
public List<Ta> getTaList() {
return taList;
}
public void setTaList(List<Ta> taList) {
this.taList = taList;
}
public List<CourseDay> getCourseDayList() {
return courseDayList;
}
public void setCourseDayList(List<CourseDay> courseDayList) {
this.courseDayList = courseDayList;
}
public List<Course> getCourseList() {
return courseList;
}
public void setCourseList(List<Course> courseList) {
this.courseList = courseList;
}
public List<CourseOffRequest> getCourseOffRequestList() {
return courseOffRequestList;
}
public void setCourseOffRequestList(List<CourseOffRequest> courseOffRequestList) {
this.courseOffRequestList = courseOffRequestList;
}
public List<CourseOnRequest> getCourseOnRequestList() {
return courseOnRequestList;
}
public void setCourseOnRequestList(List<CourseOnRequest> courseOnRequestList) {
this.courseOnRequestList = courseOnRequestList;
}
@PlanningEntityCollectionProperty
public List<CourseAssignment> getCourseAssignmentList() {
return courseAssignmentList;
}
public void setCourseAssignmentList(List<CourseAssignment> courseAssignmentList) {
this.courseAssignmentList = courseAssignmentList;
}
@Override
public HardSoftScore getScore() {
return score;
}
@Override
public void setScore(HardSoftScore score) {
this.score = score;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@Override
public Collection<? extends Object> getProblemFacts() {
List<Object> facts = new ArrayList<>();
facts.addAll(courseTypeList);
facts.addAll(contractList);
facts.addAll(contractLineList);
facts.addAll(taList);
facts.addAll(courseDayList);
facts.addAll(courseList);
facts.addAll(courseOffRequestList);
facts.addAll(courseOnRequestList);
// facts.addAll(coordinatorList);
// Do not add the planning entity's (courseAssignmentList) because that will be done automatically
return facts;
}
}
| true |
7f57852a7f3e2b7eb261a854799e159a96b36bb4 | Java | cenbow/fuxiaofengfugib | /cqliving-online/src/main/java/com/cqliving/cloud/online/config/dao/ConfigPermissionDao.java | UTF-8 | 385 | 1.578125 | 2 | [] | no_license | package com.cqliving.cloud.online.config.dao;
import com.cqliving.framework.common.dao.jpa.EntityJpaDao;
import com.cqliving.cloud.online.config.domain.ConfigPermission;
/**
* 前端资源权限,该表数据需要初始化好 JPA Dao
* Date: 2016-12-14 16:50:57
* @author Code Generator
*/
public interface ConfigPermissionDao extends EntityJpaDao<ConfigPermission, Long> {
}
| true |
47d7bb1edb4f395df47a1c95f93b3231c29855e2 | Java | slashman/castlevaniarl | /src/crl/action/vanquisher/Recover.java | UTF-8 | 670 | 2.5625 | 3 | [] | no_license | package crl.action.vanquisher;
import crl.action.Action;
import crl.action.HeartAction;
import crl.actor.Actor;
import crl.level.Level;
import crl.player.Player;
public class Recover extends HeartAction{
public int getHeartCost() {
return 15;
}
public String getID(){
return "RECOVER";
}
public String getSFX(){
return null;
}
public int getCost(){
Player p = (Player) performer;
return (int)(p.getCastCost() * 1.1);
}
public void execute(){
super.execute();
Player aPlayer = (Player)performer;
aPlayer.recoverHitsP(10+aPlayer.getSoulPower());
aPlayer.getLevel().addMessage("You feel relieved!");
}
} | true |
fd27dcfe0054d6cf8a06c49f14fcc8ed93ab895e | Java | cesaregb/EasyClick | /src/com/il/easyclick/android/adapters/ActivityDetailItemAdapter.java | UTF-8 | 2,765 | 2.453125 | 2 | [] | no_license | package com.il.easyclick.android.adapters;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.il.easyclick.R;
import com.il.easyclick.dao.ActivitiesDAO;
import com.il.easyclick.views.ActivityDetailVo;
public class ActivityDetailItemAdapter extends ArrayAdapter<ActivityDetailVo> {
ActivityListListener mCallback;
public interface ActivityListListener{
public void itemSelected(ActivityDetailVo activity);
}
public void setCallback(ActivityListListener callback){
this.mCallback = callback;
}
int resource;
List<ActivityDetailVo> items;
public ActivityDetailItemAdapter(Context context, int resource,
List<ActivityDetailVo> items) {
super(context, resource, items);
this.resource = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout activityListView;
ActivityDetailVo item = getItem(position);
if (convertView == null) {
activityListView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li;
li = (LayoutInflater) getContext().getSystemService(inflater);
li.inflate(resource, activityListView, true);
} else {
activityListView = (LinearLayout) convertView;
}
ImageView iconImage = (ImageView) activityListView.findViewById(R.id.simple_list_item_icon);
TextView text = (TextView) activityListView.findViewById(R.id.simple_list_item_text);
iconImage.setImageDrawable(item.getIcon());
if (item.getType() == ActivitiesDAO.TYPE_ACTION){
if (item.getApplication()!=null && item.getApplication().getName() != null)
text.setText(item.getApplication().getName());
else
text.setText("Application not found");
}else if (item.getType() == ActivitiesDAO.TYPE_SERVICE){
if (item.getService() != null && item.getService().getName() != null)
text.setText(item.getService().getName());
else
text.setText("Error getting the service");
}
final ActivityDetailVo itemParam = item;
if (mCallback != null){
OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
mCallback.itemSelected(itemParam);
}
};
activityListView.setOnClickListener(listener);
iconImage.setOnClickListener(listener);
}
return activityListView;
}
public void setItems(List<ActivityDetailVo> _items){
this.items = _items;
}
@Override
public ActivityDetailVo getItem(int position) {
return super.getItem(position);
}
}
| true |
478d4db3d2545b9d438c25365459df9262319fb1 | Java | archehyun/ksg | /src/main/java/com/ksg/workbench/adv/xls/XLSStringUtil.java | UHC | 9,297 | 2.75 | 3 | [] | no_license | package com.ksg.workbench.adv.xls;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.StringTokenizer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
/**
* ŸԿ ȯϿ ȯ ϴ Ŭ
*
* @author â
*
*/
public class XLSStringUtil {
protected Logger logger = LogManager.getLogger(this.getClass());
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/M/d");
private static FormulaEvaluator evaluator;
/**
* @param cell
* @return
*/
public static String getVesselData(HSSFCell cell)
{
String vesselResult="";
if(cell==null)
{
return "-";
}
switch (cell.getCellType())
{
case HSSFCell.CELL_TYPE_STRING:
vesselResult=cell.getRichStringCellValue().toString();
break;
case HSSFCell.CELL_TYPE_FORMULA:
evaluator.evaluateFormulaCell(cell);
vesselResult=String.valueOf(evaluator.evaluateFormulaCell(cell));
break;
default:
vesselResult="(error)";
}
vesselResult = vesselResult.replace("\n"," ").trim();
return vesselResult;
}
public static String getVoyageData(HSSFCell cell,boolean getformual)
{
if(cell==null)
return "-";
DataFormatter df = new DataFormatter();
evaluator=cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
String voyageResult="";
switch (cell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC:
{
// voyage Ÿ 100 쿡 Ÿ ȵ
// 쿡 ... Ŀ 氡ɼ
try
{
String fo =cell.getCellStyle().getDataFormatString();
Format formatter = new DecimalFormat(fo.replace("\"", "\'"));
if(fo.equals("General"))// Ϲ
{
voyageResult= String.valueOf(new Double(cell.getNumericCellValue()).intValue());
System.out.println("voy general type Ȯ:"+voyageResult);
}
else if(fo.equals("@"))//
{
//
//
//2014.7.17
//voyageResult= formatter.format(cell.getNumericCellValue());
//2014.7.17
voyageResult= formatter.format(String.valueOf(Double.valueOf(cell.getNumericCellValue())));
}
else
{
//
//
//2014.7.17
voyageResult= formatter.format(cell.getNumericCellValue());
//2014.7.17
}
}catch(Exception e){
voyageResult= String.valueOf(evaluator.evaluateInCell(cell));
}
break;
}
case HSSFCell.CELL_TYPE_BOOLEAN:
voyageResult= cell.getBooleanCellValue()+"";
break;
case HSSFCell.CELL_TYPE_STRING:
StringTokenizer st = new StringTokenizer(cell.getStringCellValue(),"/");
try{
if(st.countTokens()==2)
{
voyageResult= getDateType(st);// /
}else
{
StringTokenizer st2 = new StringTokenizer(cell.getStringCellValue(),".");
if(st2.countTokens()==2)
{
voyageResult= getDateType(st2);//
}else
{
voyageResult= cell.getRichStringCellValue().toString();
}
}
}catch(Exception e)
{
voyageResult= cell.getRichStringCellValue().toString();
}
break;
case HSSFCell.CELL_TYPE_FORMULA:
//
Cell cells =evaluator.evaluateInCell(cell);
try{
if(cells.getCellType()!=HSSFCell.CELL_TYPE_ERROR)
{
voyageResult= String.valueOf(evaluator.evaluateInCell(cell));
}else
{
voyageResult= "error";
}
}catch(IllegalStateException e)
{
//logger.error("error cell:"+cell+","+cell.getCellType()+","+cell.getColumnIndex()+","+cell.getRowIndex());
e.printStackTrace();
voyageResult= String.valueOf(cell.getNumericCellValue());
}catch(RuntimeException ee)
{
//logger.error(cell+","+cell.getCellType()+","+cell.getColumnIndex()+","+cell.getRowIndex());
ee.printStackTrace();
voyageResult= "error";
}
break;
case HSSFCell.CELL_TYPE_ERROR:
voyageResult= Byte.toString(cell.getErrorCellValue());
break;
default:
voyageResult= "-";
break;
}
// ڸ ϰ
voyageResult = voyageResult.replace("\n"," ").trim();
return voyageResult;
}
public static String getStringData(HSSFCell cell,boolean getformual) {
if(cell==null)
return "-";
evaluator=cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
DataFormatter df = new DataFormatter();
String result="";
switch (cell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC:
double d = cell.getNumericCellValue();
if(!getformual)
{
result=df.formatCellValue(cell);
}
if(HSSFDateUtil.isValidExcelDate(d))
{
result= sdf.format(cell.getDateCellValue());
}
break;
case HSSFCell.CELL_TYPE_BLANK:
result="-";
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
result=cell.getBooleanCellValue()+"";
break;
case HSSFCell.CELL_TYPE_STRING:
byte[] a = cell.getStringCellValue().getBytes();
if(a.length==1)
{
result="-";
}
StringTokenizer st = new StringTokenizer(cell.getStringCellValue(),"/");
try{
if(st.countTokens()==2)
{
try{
result = getDateType(st);//
}catch(Exception e)
{
result = st.nextToken();
}
}else
{
StringTokenizer st2 = new StringTokenizer(cell.getStringCellValue(),".");
if(st2.countTokens()==2)
{
try{
result = getDateType(st2);//
}catch(Exception e)
{
result = st2.nextToken();
}
}else
{
result = cell.getRichStringCellValue().toString();
}
break;
}
}catch(Exception e)
{
//e.printStackTrace();
return cell.getRichStringCellValue().toString();
}
case HSSFCell.CELL_TYPE_FORMULA:
try{
if(getformual)
{
String value=sdf.format(cell.getDateCellValue());
// TODO Ŀ ѹ Ȯ غ .
if(value.length()<=0||value.equals(""))
{
result="-1";
break;
}else
{
result =value;
break;
}
}
double ds = cell.getNumericCellValue();
if(HSSFDateUtil.isValidExcelDate(ds))
{
result = sdf.format(cell.getDateCellValue());
}else
{
result = String.valueOf(evaluator.evaluateInCell(cell));
}
}catch(IllegalStateException e)
{
result=cell.getRichStringCellValue().toString();
//e.printStackTrace();
}
break;
default:
result="-";
}
if(result.length()<=0||result.equals(""))
{
return "-+"+cell.getCellType();
}else
{
// Ȯ κ
//System.out.println("Ȯλ:"+result);
result = result.replace("\n"," ").trim();
return result;
}
}
/**
* @param st
* @return
* @throws NumberFormatException
*/
private static String getDateType(StringTokenizer st) throws NumberFormatException{
int month = Integer.parseInt(st.nextToken().trim());
int day = Integer.parseInt(st.nextToken().trim());
return month+"/"+day;
}
/**
* @param cell
* @return
*/
public static String getColumString(HSSFCell cell)
{
if(cell==null)
return "";
switch (cell.getCellType())
{
case HSSFCell.CELL_TYPE_STRING:
return cell.getRichStringCellValue().toString();
default:
break;
}
return "";
}
/**
* @param cell
* @param b
* @return
*/
public static String getPortName(HSSFCell cell, boolean b)
{
// ɼ
String result = null;
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
byte[] a = cell.getStringCellValue().getBytes();
if(a.length==1)
{
result="-";
}else
{
result= cell.getStringCellValue();
}
break;
case HSSFCell.CELL_TYPE_FORMULA:
result=String.valueOf(evaluator.evaluateInCell(cell));
default:
break;
}
if(result==null)
result="-";
result = result.replace("\n"," ").trim();
return result;
}
/**
* @param cell
* @return
*/
public String getVesselName(HSSFCell cell)
{
// ɼ
String result = null;
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
byte[] a = cell.getStringCellValue().getBytes();
if(a.length==1)
{
result="-";
}else
{
result= cell.getStringCellValue();
}
break;
case HSSFCell.CELL_TYPE_FORMULA:
result=String.valueOf(evaluator.evaluateInCell(cell));
default:
break;
}
if(result==null)
result="-";
return result;
}
}
| true |
c41519144e66560bf86d6808404dab35f2e67375 | Java | GPC-debug/andclient | /common/src/main/java/com/easymi/common/mvp/splash/SplashPresenter.java | UTF-8 | 2,706 | 1.851563 | 2 | [] | no_license | package com.easymi.common.mvp.splash;
import android.content.Context;
import android.content.Intent;
import com.easymi.common.mvp.home.HomeActivity;
import com.easymi.component.Config;
import com.easymi.component.app.XApp;
import com.easymi.component.entity.CompanyInfo;
import com.easymi.component.entity.EmLoc;
import com.easymi.component.network.ErrCode;
import com.easymi.component.network.HaveErrSubscriberListener;
import com.easymi.component.network.MySubscriber;
import com.easymi.component.update.UpdateHelper;
import com.easymi.component.utils.EmUtil;
import com.easymi.component.utils.Log;
import com.easymi.component.widget.MsgDialog;
import com.google.gson.Gson;
import rx.Subscription;
/**
* Created by liuzihao on 2018/12/3.
*/
public class SplashPresenter implements SplashContract.Presenter {
private Context context;
private SplashContract.Model model;
private SplashContract.View view;
public static final String GET_COMPANY_SUC = "com.easymi.common.GET_COMPANY_SUC";
private Subscription subscription;
public SplashPresenter(Context context, SplashContract.View view) {
this.view = view;
this.context = context;
model = new SplashModel(context);
}
/**
* 启动定位服务
*/
@Override
public void startLoc() {
EmLoc loc = EmUtil.getLastLoc();
if (!loc.poiName.equals("未知")) {
loadCompany(loc.latitude, loc.longitude, loc.adCode, loc.cityCode);
// loadCompany(31.1267900000,104.3979000000, "1234", "0838");
}
XApp.getInstance().startLocService();
}
/**
* 根据经纬度查询公司
*
* @param lat
* @param lng
* @param adCode
* @param cityCode
*/
@Override
public void loadCompany(double lat, double lng, String adCode, String cityCode) {
context.startActivity(new Intent(context, HomeActivity.class));
view.actFinish();
}
private void goHomeActivity(CompanyInfo companyInfo) {
if (companyInfo == null) {
companyInfo = EmUtil.getDefaultCompany();
}
XApp.getEditor().putString(Config.SP_COMPANY_INFO, new Gson().toJson(companyInfo)).apply();
context.startActivity(new Intent(context, HomeActivity.class));
view.actFinish();
}
/**
* 检查更新
*/
@Override
public void checkUpdate() {
new UpdateHelper(context, new UpdateHelper.OnNextListener() {
@Override
public void onNext() {
startLoc();
}
@Override
public void onNoVersion() {
startLoc();
}
});
}
}
| true |
1f495ff6a4313e81cb2ce0b5cf42418ce8390a38 | Java | whf605319646/docker-monitor | /src/main/java/com/github/docker/monitor/service/impl/CaMonitorServiceImpl.java | UTF-8 | 2,673 | 2.015625 | 2 | [] | no_license | package com.github.docker.monitor.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.docker.monitor.service.CaMonitorService;
@Service
public class CaMonitorServiceImpl implements CaMonitorService{
@Autowired
private RestTemplate restTemplate;
//String url = "http://9.111.141.61:4040/api/topology/containers";
String ip = "9.111.141.61";
String port = "8080";
String events = "/api/v1.3/events";
String sub = "/api/v1.1/subcontainers/docker";
String containers = "/api/v1.0/containers";
String docker = "/api/v1.2/docker/";
String machine = "/api/v2.0/machine";
private StringBuilder getHead(){
StringBuilder head = new StringBuilder("http://");
return head;
}
@Override
public String containerInfo(String cid) {
StringBuilder cUrl =getHead().append(ip).append(":").append(port);
cUrl.append(docker).append(cid);
return restTemplate.getForObject(cUrl.toString(), String.class);
}
@Override
public String subcontainers(String id) {
StringBuilder cUrl =getHead().append(ip).append(":").append(port);
cUrl.append(sub).append("/").append(id);
return restTemplate.getForObject(cUrl.toString(), String.class);
}
@Override
public String subcontainers() {
StringBuilder cUrl =getHead().append(ip).append(":").append(port);
cUrl.append(sub);
String forObject = restTemplate.getForObject(cUrl.toString(), String.class);
JSONArray array = (JSONArray) JSONArray.parse(forObject);
for (Object object : array) {
if(object instanceof JSONObject) {
object = (JSONObject) object;
((JSONObject) object).fluentRemove("spec");
((JSONObject) object).fluentRemove("stats");
}
}
return array.toJSONString();
}
@Override
public String containers() {
StringBuilder cUrl =getHead().append(ip).append(":").append(port);
cUrl.append(containers);
return restTemplate.getForObject(cUrl.toString(),String.class);
}
@Override
public String docker() {
StringBuilder cUrl =getHead().append(ip).append(":").append(port);
return restTemplate.getForObject(cUrl.append(docker).toString(), String.class);
}
@Override
public String machine() {
StringBuilder cUrl =getHead().append(ip).append(":").append(port);
cUrl.append(machine);
String string = restTemplate.getForObject(cUrl.toString(), String.class);
JSONObject j = (JSONObject) JSONObject.parse(string);
j.fluentRemove("disk_map");
j.fluentRemove("topology");
return j.toJSONString();
}
}
| true |
3eec3eae6d188f54d696c7a8e60b8389778c5c1e | Java | patytavares/Java | /ss/TesteAnimal.java | UTF-8 | 611 | 2.515625 | 3 | [] | no_license | package Anayr;
public class TesteAnimal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cachorro trovao = new Cachorro ("trovao",1,"\n preto ", 7 );
trovao.ImprimirInformacoesp();
System.out.println("\n");
Cavalo dio = new Cavalo("dio",6," \n branco ", 1 );
dio.ImprimirInformacoes();
System.out.println("\n");
Preguica sono = new Preguica("sono",3," \n cinza ", 7 );
sono.ImprimirInformcoesm();
System.out.println("\n");
trovao.emitirSom();
dio.emitirSom();
sono.emitirSom();
}
}
| true |
9dac219d067de1f4ca1f53b7fa8849b35441bda3 | Java | ksalic/brxm-ugc-microservice-integration | /jh-ugc/src/test/java/org/example/ugc/web/rest/UserGeneratedContentResourceIT.java | UTF-8 | 14,442 | 1.914063 | 2 | [] | no_license | package org.example.ugc.web.rest;
import org.example.ugc.UgcApp;
import org.example.ugc.domain.UserGeneratedContent;
import org.example.ugc.repository.UserGeneratedContentRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.Base64Utils;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.time.ZoneOffset;
import java.time.ZoneId;
import java.util.List;
import static org.example.ugc.web.rest.TestUtil.sameInstant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.example.ugc.domain.enumeration.UgcState;
import org.example.ugc.domain.enumeration.PublicationState;
/**
* Integration tests for the {@link UserGeneratedContentResource} REST controller.
*/
@SpringBootTest(classes = UgcApp.class)
@AutoConfigureMockMvc
@WithMockUser
public class UserGeneratedContentResourceIT {
private static final String DEFAULT_NAME = "AAAAAAAAAA";
private static final String UPDATED_NAME = "BBBBBBBBBB";
private static final String DEFAULT_EMAIL = "AAAAAAAAAA";
private static final String UPDATED_EMAIL = "BBBBBBBBBB";
private static final String DEFAULT_TEXT = "AAAAAAAAAA";
private static final String UPDATED_TEXT = "BBBBBBBBBB";
private static final ZonedDateTime DEFAULT_DATE = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_DATE = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
private static final String DEFAULT_IP_ADDRESS = "AAAAAAAAAA";
private static final String UPDATED_IP_ADDRESS = "BBBBBBBBBB";
private static final String DEFAULT_REFERENCE_ID = "AAAAAAAAAA";
private static final String UPDATED_REFERENCE_ID = "BBBBBBBBBB";
private static final String DEFAULT_CHANNEL_ID = "AAAAAAAAAA";
private static final String UPDATED_CHANNEL_ID = "BBBBBBBBBB";
private static final Boolean DEFAULT_RECENT = false;
private static final Boolean UPDATED_RECENT = true;
private static final UgcState DEFAULT_STATE = UgcState.OPEN;
private static final UgcState UPDATED_STATE = UgcState.CLOSE;
private static final PublicationState DEFAULT_PUBLICATION_STATE = PublicationState.PUBLISHED;
private static final PublicationState UPDATED_PUBLICATION_STATE = PublicationState.UNPUBLISHED;
@Autowired
private UserGeneratedContentRepository userGeneratedContentRepository;
@Autowired
private MockMvc restUserGeneratedContentMockMvc;
private UserGeneratedContent userGeneratedContent;
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static UserGeneratedContent createEntity() {
UserGeneratedContent userGeneratedContent = new UserGeneratedContent()
.name(DEFAULT_NAME)
.email(DEFAULT_EMAIL)
.text(DEFAULT_TEXT)
.date(DEFAULT_DATE)
.ipAddress(DEFAULT_IP_ADDRESS)
.referenceId(DEFAULT_REFERENCE_ID)
.channelId(DEFAULT_CHANNEL_ID)
.recent(DEFAULT_RECENT)
.state(DEFAULT_STATE)
.publicationState(DEFAULT_PUBLICATION_STATE);
return userGeneratedContent;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static UserGeneratedContent createUpdatedEntity() {
UserGeneratedContent userGeneratedContent = new UserGeneratedContent()
.name(UPDATED_NAME)
.email(UPDATED_EMAIL)
.text(UPDATED_TEXT)
.date(UPDATED_DATE)
.ipAddress(UPDATED_IP_ADDRESS)
.referenceId(UPDATED_REFERENCE_ID)
.channelId(UPDATED_CHANNEL_ID)
.recent(UPDATED_RECENT)
.state(UPDATED_STATE)
.publicationState(UPDATED_PUBLICATION_STATE);
return userGeneratedContent;
}
@BeforeEach
public void initTest() {
userGeneratedContentRepository.deleteAll();
userGeneratedContent = createEntity();
}
@Test
public void createUserGeneratedContent() throws Exception {
int databaseSizeBeforeCreate = userGeneratedContentRepository.findAll().size();
// Create the UserGeneratedContent
restUserGeneratedContentMockMvc.perform(post("/api/user-generated-contents")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userGeneratedContent)))
.andExpect(status().isCreated());
// Validate the UserGeneratedContent in the database
List<UserGeneratedContent> userGeneratedContentList = userGeneratedContentRepository.findAll();
assertThat(userGeneratedContentList).hasSize(databaseSizeBeforeCreate + 1);
UserGeneratedContent testUserGeneratedContent = userGeneratedContentList.get(userGeneratedContentList.size() - 1);
assertThat(testUserGeneratedContent.getName()).isEqualTo(DEFAULT_NAME);
assertThat(testUserGeneratedContent.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(testUserGeneratedContent.getText()).isEqualTo(DEFAULT_TEXT);
assertThat(testUserGeneratedContent.getDate()).isEqualTo(DEFAULT_DATE);
assertThat(testUserGeneratedContent.getIpAddress()).isEqualTo(DEFAULT_IP_ADDRESS);
assertThat(testUserGeneratedContent.getReferenceId()).isEqualTo(DEFAULT_REFERENCE_ID);
assertThat(testUserGeneratedContent.getChannelId()).isEqualTo(DEFAULT_CHANNEL_ID);
assertThat(testUserGeneratedContent.isRecent()).isEqualTo(DEFAULT_RECENT);
assertThat(testUserGeneratedContent.getState()).isEqualTo(DEFAULT_STATE);
assertThat(testUserGeneratedContent.getPublicationState()).isEqualTo(DEFAULT_PUBLICATION_STATE);
}
@Test
public void createUserGeneratedContentWithExistingId() throws Exception {
int databaseSizeBeforeCreate = userGeneratedContentRepository.findAll().size();
// Create the UserGeneratedContent with an existing ID
userGeneratedContent.setId("existing_id");
// An entity with an existing ID cannot be created, so this API call must fail
restUserGeneratedContentMockMvc.perform(post("/api/user-generated-contents")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userGeneratedContent)))
.andExpect(status().isBadRequest());
// Validate the UserGeneratedContent in the database
List<UserGeneratedContent> userGeneratedContentList = userGeneratedContentRepository.findAll();
assertThat(userGeneratedContentList).hasSize(databaseSizeBeforeCreate);
}
@Test
public void getAllUserGeneratedContents() throws Exception {
// Initialize the database
userGeneratedContentRepository.save(userGeneratedContent);
// Get all the userGeneratedContentList
restUserGeneratedContentMockMvc.perform(get("/api/user-generated-contents?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(userGeneratedContent.getId())))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
.andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)))
.andExpect(jsonPath("$.[*].text").value(hasItem(DEFAULT_TEXT.toString())))
.andExpect(jsonPath("$.[*].date").value(hasItem(sameInstant(DEFAULT_DATE))))
.andExpect(jsonPath("$.[*].ipAddress").value(hasItem(DEFAULT_IP_ADDRESS)))
.andExpect(jsonPath("$.[*].referenceId").value(hasItem(DEFAULT_REFERENCE_ID)))
.andExpect(jsonPath("$.[*].channelId").value(hasItem(DEFAULT_CHANNEL_ID)))
.andExpect(jsonPath("$.[*].recent").value(hasItem(DEFAULT_RECENT.booleanValue())))
.andExpect(jsonPath("$.[*].state").value(hasItem(DEFAULT_STATE.toString())))
.andExpect(jsonPath("$.[*].publicationState").value(hasItem(DEFAULT_PUBLICATION_STATE.toString())));
}
@Test
public void getUserGeneratedContent() throws Exception {
// Initialize the database
userGeneratedContentRepository.save(userGeneratedContent);
// Get the userGeneratedContent
restUserGeneratedContentMockMvc.perform(get("/api/user-generated-contents/{id}", userGeneratedContent.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(userGeneratedContent.getId()))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME))
.andExpect(jsonPath("$.email").value(DEFAULT_EMAIL))
.andExpect(jsonPath("$.text").value(DEFAULT_TEXT.toString()))
.andExpect(jsonPath("$.date").value(sameInstant(DEFAULT_DATE)))
.andExpect(jsonPath("$.ipAddress").value(DEFAULT_IP_ADDRESS))
.andExpect(jsonPath("$.referenceId").value(DEFAULT_REFERENCE_ID))
.andExpect(jsonPath("$.channelId").value(DEFAULT_CHANNEL_ID))
.andExpect(jsonPath("$.recent").value(DEFAULT_RECENT.booleanValue()))
.andExpect(jsonPath("$.state").value(DEFAULT_STATE.toString()))
.andExpect(jsonPath("$.publicationState").value(DEFAULT_PUBLICATION_STATE.toString()));
}
@Test
public void getNonExistingUserGeneratedContent() throws Exception {
// Get the userGeneratedContent
restUserGeneratedContentMockMvc.perform(get("/api/user-generated-contents/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
public void updateUserGeneratedContent() throws Exception {
// Initialize the database
userGeneratedContentRepository.save(userGeneratedContent);
int databaseSizeBeforeUpdate = userGeneratedContentRepository.findAll().size();
// Update the userGeneratedContent
UserGeneratedContent updatedUserGeneratedContent = userGeneratedContentRepository.findById(userGeneratedContent.getId()).get();
updatedUserGeneratedContent
.name(UPDATED_NAME)
.email(UPDATED_EMAIL)
.text(UPDATED_TEXT)
.date(UPDATED_DATE)
.ipAddress(UPDATED_IP_ADDRESS)
.referenceId(UPDATED_REFERENCE_ID)
.channelId(UPDATED_CHANNEL_ID)
.recent(UPDATED_RECENT)
.state(UPDATED_STATE)
.publicationState(UPDATED_PUBLICATION_STATE);
restUserGeneratedContentMockMvc.perform(put("/api/user-generated-contents")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(updatedUserGeneratedContent)))
.andExpect(status().isOk());
// Validate the UserGeneratedContent in the database
List<UserGeneratedContent> userGeneratedContentList = userGeneratedContentRepository.findAll();
assertThat(userGeneratedContentList).hasSize(databaseSizeBeforeUpdate);
UserGeneratedContent testUserGeneratedContent = userGeneratedContentList.get(userGeneratedContentList.size() - 1);
assertThat(testUserGeneratedContent.getName()).isEqualTo(UPDATED_NAME);
assertThat(testUserGeneratedContent.getEmail()).isEqualTo(UPDATED_EMAIL);
assertThat(testUserGeneratedContent.getText()).isEqualTo(UPDATED_TEXT);
assertThat(testUserGeneratedContent.getDate()).isEqualTo(UPDATED_DATE);
assertThat(testUserGeneratedContent.getIpAddress()).isEqualTo(UPDATED_IP_ADDRESS);
assertThat(testUserGeneratedContent.getReferenceId()).isEqualTo(UPDATED_REFERENCE_ID);
assertThat(testUserGeneratedContent.getChannelId()).isEqualTo(UPDATED_CHANNEL_ID);
assertThat(testUserGeneratedContent.isRecent()).isEqualTo(UPDATED_RECENT);
assertThat(testUserGeneratedContent.getState()).isEqualTo(UPDATED_STATE);
assertThat(testUserGeneratedContent.getPublicationState()).isEqualTo(UPDATED_PUBLICATION_STATE);
}
@Test
public void updateNonExistingUserGeneratedContent() throws Exception {
int databaseSizeBeforeUpdate = userGeneratedContentRepository.findAll().size();
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restUserGeneratedContentMockMvc.perform(put("/api/user-generated-contents")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userGeneratedContent)))
.andExpect(status().isBadRequest());
// Validate the UserGeneratedContent in the database
List<UserGeneratedContent> userGeneratedContentList = userGeneratedContentRepository.findAll();
assertThat(userGeneratedContentList).hasSize(databaseSizeBeforeUpdate);
}
@Test
public void deleteUserGeneratedContent() throws Exception {
// Initialize the database
userGeneratedContentRepository.save(userGeneratedContent);
int databaseSizeBeforeDelete = userGeneratedContentRepository.findAll().size();
// Delete the userGeneratedContent
restUserGeneratedContentMockMvc.perform(delete("/api/user-generated-contents/{id}", userGeneratedContent.getId())
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<UserGeneratedContent> userGeneratedContentList = userGeneratedContentRepository.findAll();
assertThat(userGeneratedContentList).hasSize(databaseSizeBeforeDelete - 1);
}
}
| true |
1ec1f072891683440f1771a9fb7fbeb56c98b767 | Java | latuan1987/OrderItv2 | /app/src/main/java/com/dinogroup/screen/order/OrderScreen.java | UTF-8 | 789 | 1.882813 | 2 | [] | no_license | package com.dinogroup.screen.order;
import com.dinogroup.R;
import com.dinogroup.screen.main.MainScreen;
import com.dinogroup.screen.status.StatusScreen;
import flow.HasParent;
import flow.Layout;
import mortar.Blueprint;
@Layout(R.layout.activity_table_order)
public class OrderScreen implements Blueprint, HasParent<StatusScreen> {
@Override
public String getMortarScopeName() {
return getClass().getName();
}
@Override
public Object getDaggerModule() {
return new Module();
}
@Override
public StatusScreen getParent() {
return new StatusScreen();
}
@dagger.Module(
injects = OrderView.class,
addsTo = MainScreen.Module.class
)
class Module {
}
}
| true |
3a4f7a61ffa755eb1bbb4623a7516049ffec8b16 | Java | LittleFlowerPig/lfp-pattern | /src/main/java/com/lfp/demo/pattern/behaviour/memento/Memento.java | UTF-8 | 583 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | package com.lfp.demo.pattern.behaviour.memento;
/**
* Title: 快照对象
* Description: 对应于快照domain
* Project: lfp-pattern
* Date: 2017-12-21
* Copyright: Copyright (c) 2020
* Company: LFP
*
* @author ZhuTao
* @version 1.0
*/
public class Memento {
private String profile;
private SnapObject state;
public Memento(String profile, SnapObject state) {
this.profile = profile;
this.state = state;
}
public String getProfile() {
return profile;
}
public SnapObject getState() {
return state;
}
}
| true |
b8b56027dee83fad7c487b1bc93da518e219e3ec | Java | suninno/access-log-tiger | /src/main/java/com/lge/cto/swinfra/tiger/form/PeriodDateForm.java | UTF-8 | 1,141 | 2.46875 | 2 | [] | no_license | package com.lge.cto.swinfra.tiger.form;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.NotEmpty;
public class PeriodDateForm {
/**
* 검색 일자(yyyy-mm-dd)
*/
@NotEmpty(message = "검색할 일자는 필수입니다!.")
@Pattern(
regexp = "^[\\d]{4}-[\\d]{2}-[\\d]{2}$",
message = "검색 시작 일자(yyyy-mm-dd)를 입력하세요!.")
protected String sdate;
@NotEmpty(message = "검색할 일자는 필수입니다!.")
@Pattern(
regexp = "^[\\d]{4}-[\\d]{2}-[\\d]{2}$",
message = "검색 종료 일자(yyyy-mm-dd)를 입력하세요!.")
protected String edate;
public String getSdate() {
return sdate;
}
public void setSdate(String sdate) {
this.sdate = sdate;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
@Override
public String toString() {
return this.getClass().getName() + " - sdate: " + sdate
+ " , edate: " + edate;
}
}
| true |
4c55b6a4b36bcfa884a973c43c3819457dd7886e | Java | seo-young-kim/BOJ | /src/단기간성장/우주신과의교감.java | UHC | 1,309 | 2.53125 | 3 | [] | no_license | package ܱⰣ;
import java.util.*;
import java.io.*;
public class ֽŰDZ {
static int N;
static int M;
public static void main(String[] args) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
int[][] location = new int[N][2];
for(int i=0;i<N;i++) {
st = new StringTokenizer(bf.readLine());
location[i][0] = Integer.parseInt(st.nextToken());
location[i][1] = Integer.parseInt(st.nextToken());
}
//Ÿ 迭 adj
double[][] adj = new double[N][N];
for(int i=0;i<N;i++) {
for(int j=i+1;j<N;j++) {
int dx = location[i][0]-location[j][0];
int dy = location[i][1]-location[j][1];
adj[i][j] = Math.sqrt(dx*dx+dy*dy);
adj[j][i]=adj[i][j];
}
}
//̸ Ǿ ִ 迭 map
int[][] map = new int[N][N];
double answer = 0.0;
for(int i=0;i<M;i++) {
st = new StringTokenizer(bf.readLine());
int n1 = Integer.parseInt(st.nextToken())-1;
int n2 = Integer.parseInt(st.nextToken())-1;
map[n1][n2]=1;
map[n2][n1]=1;
answer +=adj[n1][n2];
}
//Prim()
boolean[] S = new boolean[N];
}
}
| true |
93cebebfb830b1ebd62f81d1c521459c997c5532 | Java | monkeyzi/monkeyzicloud | /monkeyzicloud-provider/monkeyzicloud-provider-ucloud/src/main/java/com/gaoyg/monkeyzicloud/provider/model/dto/menu/UcloudMenuStatusDto.java | UTF-8 | 743 | 1.703125 | 2 | [] | no_license | package com.gaoyg.monkeyzicloud.provider.model.dto.menu;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* @author: 高yg
* @date: 2018/9/16 17:01
* @qq:854152531@qq.com
* @blog http://www.monkeyzi.xin
* @description:
*/
@Data
@ApiModel(value = "UcloudMenuStatusDto")
public class UcloudMenuStatusDto implements Serializable {
private static final long serialVersionUID = 7834606418601316142L;
/**
* 菜单的Id
*/
@ApiModelProperty(value = "菜单的Id", required = true)
private Long id;
/**
* 菜单的父Id
*/
@ApiModelProperty(value = "菜单的状态", required = true)
private String status;
}
| true |
34cfa1a691baf212b07fa42eea3c123cd080af17 | Java | aesmeral/fabflix | /movies/src/main/java/edu/uci/ics/AESMERAL/service/movies/resources/Thumbnail.java | UTF-8 | 3,463 | 2.40625 | 2 | [] | no_license | package edu.uci.ics.AESMERAL.service.movies.resources;
import edu.uci.ics.AESMERAL.service.movies.core.MyUtil;
import edu.uci.ics.AESMERAL.service.movies.core.Queries;
import edu.uci.ics.AESMERAL.service.movies.core.ResultResponse;
import edu.uci.ics.AESMERAL.service.movies.logger.ServiceLogger;
import edu.uci.ics.AESMERAL.service.movies.models.MovieModel;
import edu.uci.ics.AESMERAL.service.movies.models.ThumbnailModel;
import edu.uci.ics.AESMERAL.service.movies.models.ThumbnailRequestModel;
import edu.uci.ics.AESMERAL.service.movies.models.ThumbnailResponseModel;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@Path("thumbnail")
public class Thumbnail {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response thumbnail(@Context HttpHeaders headers, String jsonText)
{
String email = headers.getHeaderString("email");
String session_id = headers.getHeaderString("session_id");
String transaction_id = headers.getHeaderString("transaction_id");
Response.ResponseBuilder builder = null;
ThumbnailRequestModel requestModel = new ThumbnailRequestModel();
ThumbnailResponseModel responseModel = new ThumbnailResponseModel();
requestModel = MyUtil.modelMapper(jsonText,ThumbnailRequestModel.class,responseModel);
ArrayList<String> movie_ids = new ArrayList<String>();
Collections.addAll(movie_ids, requestModel.getMovie_ids());
builder = Response.status(Response.Status.OK);
ArrayList<ThumbnailModel> thumbnails = new ArrayList<ThumbnailModel>();
ResultSet rs = null;
ThumbnailModel thumbnail = null;
for(String movie : movie_ids)
{
rs = Queries.getMovieByID(movie, true);
try{
if(rs.next())
{
thumbnail = new ThumbnailModel(movie, rs.getString("M.title"));
thumbnail.setBackdrop_path(rs.getString("M.backdrop_path"));
thumbnail.setPoster_path(rs.getString("M.poster_path"));
thumbnails.add(thumbnail);
}
} catch (SQLException e)
{
ServiceLogger.LOGGER.info("Something went wrong: " + e);
e.printStackTrace();
}
}
if(thumbnails.isEmpty())
{
responseModel.setResult(ResultResponse.NO_MOVIES_FOUND);
builder.entity(responseModel);
}
else
{
ServiceLogger.LOGGER.info("Successfully created a Response with Movies Found");
ThumbnailModel[] sendThumbnails = new ThumbnailModel[thumbnails.size()];
sendThumbnails = thumbnails.toArray(sendThumbnails);
responseModel.setThumbnails(sendThumbnails);
responseModel.setResult(ResultResponse.FOUND_MOVIES);
builder.entity(responseModel);
}
builder.header("email", email);
builder.header("session_id",session_id);
builder.header("transaction_id", transaction_id);
return builder.build();
}
}
| true |
2f72ad774e215f5720a50c5122c8107b7f2e343a | Java | congtaowang/AFT | /app/src/main/java/cn/aft/sample/adapter/SimpleFrescoImageViewHolder.java | UTF-8 | 2,118 | 2.078125 | 2 | [] | no_license | package cn.aft.sample.adapter;
import android.net.Uri;
import android.view.View;
import android.widget.TextView;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.drawable.ProgressBarDrawable;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import butterknife.Bind;
import butterknife.ButterKnife;
import cn.aft.sample.AFTApplicatioin;
import cn.aft.sample.R;
import cn.aft.sample.bean.SimpleDisplayer;
import cn.aft.template.adapter.BaseViewHolder;
/**
* 16/1/28 by congtaowang.
* Version 1.0
*/
public class SimpleFrescoImageViewHolder implements BaseViewHolder<SimpleDisplayer> {
@Bind(R.id.pic) SimpleDraweeView pic;
@Bind(R.id.desc) TextView desc;
@Override
public void attachView(View itemView) {
ButterKnife.bind(this,itemView);
}
@Override
public void bindData(SimpleDisplayer data, int position) {
desc.setText(data.getDesc());
if (!(pic.getTag() instanceof GenericDraweeHierarchy)) {
GenericDraweeHierarchyBuilder builder = new GenericDraweeHierarchyBuilder(AFTApplicatioin.getInstance().getResources());
builder.setFadeDuration(300).setProgressBarImage(new ProgressBarDrawable());
GenericDraweeHierarchy hierarchy = builder.build();
hierarchy.setPlaceholderImage(R.drawable.ic_placeholder);
pic.setHierarchy(hierarchy);
}
ImageRequest lowResImageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(data.getThumbPic()))
.setAutoRotateEnabled(true)
.build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setLowResImageRequest(lowResImageRequest)
.setUri(Uri.parse(data.getPic())).build();
pic.setController(controller);
}
}
| true |
93587c06ec180445eca05c343a664c29def73909 | Java | TSoftTest/DimQCIntegration | /Dim-QC Integration/src/com/tsoft/dimqc/connectors/utils/parser/HtmlWrapperSpan.java | UTF-8 | 1,475 | 2.703125 | 3 | [] | no_license | package com.tsoft.dimqc.connectors.utils.parser;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HtmlWrapperSpan extends HtmlWrapper {
@Override
public String dibujar() {
// return getSourceElement().text() + "\n";
return getSourceElement().text();
}
@Override
public String dibujarHtml() {
if ("".equals(texto)) {
return "<span style=\"font-size:8pt\"><br /></span>";
} else {
return "<span style=\"font-size:8pt\">" + limpiarTexto() + "</span>";
}
}
private String limpiarTexto() {
String textolimpio = texto;
Pattern pattern = null;
@SuppressWarnings("unused")
Matcher matcher = null;
if (ArmadoHtml.isListaNumerica(textolimpio)) {
String regex = "^ {" + HtmlWrapperComposite.SANGRIA_SIMBOLO.length() + "}[1-9]+\\" + HtmlWrapperComposite.SIMBOLO_OL + " {"
+ HtmlWrapperComposite.SEGUNDA_SANGRIA_SIMBOLO.length() + "}";
pattern = Pattern.compile(regex);
matcher = pattern.matcher(textolimpio);
textolimpio = textolimpio.replaceAll(regex, "");
} else if (ArmadoHtml.isListaConSimbolo(texto)) {
String regex = "^ {" + HtmlWrapperComposite.SANGRIA_SIMBOLO.length() + "}" + HtmlWrapperUl.SIMBOLO_UL + " {" + HtmlWrapperComposite.SEGUNDA_SANGRIA_SIMBOLO.length() + "}";
pattern = Pattern.compile(regex);
matcher = pattern.matcher(textolimpio);
textolimpio = textolimpio.replaceAll(regex, "");
}
return textolimpio;
}
}
| true |
3d166366ee89529603170240be64de72183221f4 | Java | Ameg-yag/TLS-Attacker | /TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/protocol/message/cert/CertificateEntry.java | UTF-8 | 1,391 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | /**
* TLS-Attacker - A Modular Penetration Testing Framework for TLS
*
* Copyright 2014-2017 Ruhr University Bochum / Hackmanit GmbH
*
* Licensed under Apache License 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
package de.rub.nds.tlsattacker.core.protocol.message.cert;
import de.rub.nds.modifiablevariable.util.ByteArrayAdapter;
import de.rub.nds.tlsattacker.core.protocol.message.extension.ExtensionMessage;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlAccessorType(XmlAccessType.FIELD)
public class CertificateEntry {
@XmlJavaTypeAdapter(ByteArrayAdapter.class)
private byte[] certificate;
private List<ExtensionMessage> extensions;
public CertificateEntry(byte[] certificate, List<ExtensionMessage> extensions) {
this.certificate = certificate;
this.extensions = extensions;
}
public CertificateEntry() {
}
public byte[] getCertificate() {
return certificate;
}
public void setCertificate(byte[] certificate) {
this.certificate = certificate;
}
public List<ExtensionMessage> getExtensions() {
return extensions;
}
public void setExtensions(List<ExtensionMessage> extensions) {
this.extensions = extensions;
}
}
| true |
c453d25e32a63a7e5af67a0a5be6303a50658239 | Java | Kenanfa/AOOP-CALC | /src/UnitConverter/VolumeUnitConverter.java | UTF-8 | 876 | 3.171875 | 3 | [] | no_license | package UnitConverter;
public class VolumeUnitConverter implements UnitConverter {
private static final double GALLON_TO_LITRE = 3.7854;
private static final double LITRE_TO_GALLON = 0.2642;
@Override
public double convert(String fromUnit, String toUnit, double value) {
double valueInLitre = convertToLitre(fromUnit, value);
double multiplier = 1;
switch (toUnit.toLowerCase()) {
case "gallon":
multiplier = LITRE_TO_GALLON;
break;
}
return multiplier * valueInLitre;
}
private double convertToLitre(String fromUnit, double value) {
double multiplier = 1;
switch (fromUnit.toLowerCase()) {
case "gallon":
multiplier = GALLON_TO_LITRE;
break;
}
return multiplier * value;
}
}
| true |
1ffc125d84aa7179d7bbee92acedf1374bb6a569 | Java | michaelperez/fruitshop | /src/test/java/com/perezma/fruitshop/api/v1/mapper/CustomerMapperTest.java | UTF-8 | 926 | 2.546875 | 3 | [] | no_license | package com.perezma.fruitshop.api.v1.mapper;
import com.perezma.fruitshop.api.v1.model.CustomerDTO;
import com.perezma.fruitshop.domain.Customer;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CustomerMapperTest {
public static final long ID = 1L;
public static final String FIRST_NAME = "Tyrion";
public static final String LAST_NAME = "Lannister";
CustomerMapper customerMapper = new CustomerMapperImpl();
@Test
public void customerToCustomerDTO() throws Exception {
//given
Customer customer = new Customer();
customer.setId(ID);
customer.setFirstName(FIRST_NAME);
customer.setLastName(LAST_NAME);
//when
CustomerDTO dto = customerMapper.customerToCustomerDTO(customer);
//then
assertEquals(FIRST_NAME, dto.getFirstName());
assertEquals(LAST_NAME, dto.getLastName());
}
} | true |
6c7f2159d8b3c3e4336e06c4a8a283b55c872543 | Java | Sadario/GridBagLayoutEditor | /src/test/java/no/ntnu/imt3281/project1/TextAreaTest.java | UTF-8 | 3,067 | 2.96875 | 3 | [] | no_license | /**
*
*/
package no.ntnu.imt3281.project1;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* @author oivindk
*
* This class tests the TextArea component. It inherits from
* BaseComponent and is used to represent a JTextArea component in the
* model.
*/
public class TextAreaTest {
@Test
public void testTextArea() {
// nextComponentID is a static member in BaseComponent. Need to reset it to
// 1 (one) because we do not know in what order the tests is executed.
BaseComponent.nextComponentID = 1;
TextArea textArea = new TextArea();
assertEquals("component1", textArea.getVariableName());
assertTrue(textArea instanceof BaseComponent);
assertTrue(textArea.getSpecialEditor() instanceof java.awt.Component);
textArea.setText("Test");
textArea.setCol(2);
textArea.setRow(3);
textArea.setCols(4);
textArea.setRows(5);
// Creating a button based on a component should be the same
// as creating a component based on a component
BaseComponent component = new BaseComponent(textArea);
TextArea textArea2 = new TextArea(component);
assertEquals("component1", textArea2.getVariableName());
assertEquals("Test", textArea2.getText());
assertEquals(2, textArea2.getCol(), 0);
assertEquals(3, textArea2.getRow(), 0);
assertEquals(4, textArea2.getCols(), 0);
assertEquals(5, textArea2.getRows(), 0);
}
@Test
public void testTextAreaCodeCreation() {
// nextComponentID is a static member in BaseComponent. Need to reset it to
// 1 (one) because we do not know in what order the tests is executed.
BaseComponent.nextComponentID = 1;
TextArea textArea = new TextArea();
textArea.setText("Test");
textArea.setCol(2);
textArea.setRow(3);
textArea.setCols(4);
textArea.setRows(5);
textArea.setAnchor(6);
textArea.setFill(7);
textArea.setTextRows(12);
textArea.setTextCols(42);
textArea.setWrap(true);
// This is the code that is to be placed at class level for
// this component
String definition = "\tJTextArea component1 = new JTextArea(\"Test\", 12, 42);\n";
assertEquals(definition, textArea.getDefinition());
// This is the code that is to be placed in the constructor
// of the generated class
// Note the component1.setWrap(true); line, default for wrapping
// is false
String layoutCode = "\t\tgbc.gridx = 2;\n" + "\t\tgbc.gridy = 3;\n"
+ "\t\tgbc.gridwidth = 4;\n" + "\t\tgbc.gridheight = 5;\n"
+ "\t\tgbc.anchor = 6;\n" + "\t\tgbc.fill = 7;\n"
+ "\t\tlayout.setConstraints(component1, gbc);\n"
+ "\t\tadd(component1);\n" + "\t\tcomponent1.setWrapStyleWord(true);\n";
assertEquals(layoutCode, textArea.getLayoutCode());
}
}
| true |
9b93f19cba0badb814fafbc79371f28c72c294f0 | Java | evilZ1994/JavaLearning | /JavaNotes/src/Thread/demo04/TestReadWriteLock.java | UTF-8 | 1,341 | 3.828125 | 4 | [] | no_license | package Thread.demo04;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* ReadWriteLock:读写锁
* 写写/读写 需要"互斥"
* 读读 不需要"互斥"
*/
public class TestReadWriteLock {
public static void main(String[] args) {
ReadWriteLockDemo demo = new ReadWriteLockDemo();
// 写线程
new Thread(() -> demo.set((int)(Math.random() * 101)), "Writer").start();
for (int i=0; i<10; i++) {
// 读线程
new Thread(demo::get, "Reader").start();
}
}
}
class ReadWriteLockDemo {
private int number = 0;
private ReadWriteLock lock = new ReentrantReadWriteLock();
// 读
public void get() {
// 上锁 (读锁)
lock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " : " + number);
} finally {
// 释放锁
lock.readLock().unlock();
}
}
// 写
public void set(int number) {
// 上锁 (写锁)
lock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName());
this.number = number;
} finally {
// 释放锁
lock.writeLock().unlock();
}
}
} | true |
a7453f21e5e88c7456f346e8bf5c14b05b2c4cd5 | Java | wh01683/HW_Grader | /src/main/java/entries/assignments/Lab.java | UTF-8 | 1,528 | 2.875 | 3 | [] | no_license | package entries.assignments;
import static util.Constants.*;
/**
* Created by Howerton on 3/30/2016.
*/
public class Lab implements Assignment{
private static double totalPointWorth = 10;
private String assignmentName, className, section;
boolean reqUML;
public Lab(String assignmentName, String className, String section, boolean reqUML){
this.assignmentName = assignmentName;
this.className = className;
this.section = section;
this.reqUML = reqUML;
if(reqUML){
totalPointWorth = TOTAL_POINTS_LAB * (1 - UML_GRADE_PERCENTAGE);
}else{
totalPointWorth = TOTAL_POINTS_LAB;
}
}
public String type() {
return "LAB";
}
public String styleDescription() {
return "Proper programming style";
}
public double totalPoints() {
return totalPointWorth;
}
public double maxImplementationPoints() {
return IMPLEMENTATION_GRADE_PERCENTAGE * totalPointWorth;
}
public double maxStylePoints() {
return STYLE_GRADE_PERCENTAGE * totalPointWorth;
}
public double maxResultPoints() {
return RESULTS_GRADE_PERCENTAGE * totalPointWorth;
}
public String getClassName() {
return this.className;
}
public String getSection() {
return this.section;
}
public String getAssignmentName() {
return assignmentName;
}
public double masterTotalPoints() {
return TOTAL_POINTS_LAB;
}
}
| true |
81167fd797bb3e27795b4d1eb3a12dc497e02fe5 | Java | BartoszKowalczyk98/inzynierka | /ZPO/zpo5_1ksiazki/src/dekoratornia/Dekorator.java | UTF-8 | 467 | 2.625 | 3 | [] | no_license | package dekoratornia;
public class Dekorator implements Publikacja {
Publikacja publikacja;
public Dekorator(Publikacja publikacja) {
this.publikacja = publikacja;
}
@Override
public String getAutor() {
return publikacja.getAutor();
}
@Override
public String getTytul() {
return publikacja.getTytul();
}
@Override
public int getIloscStron() {
return publikacja.getIloscStron();
}
}
| true |
fc05856e155258a0deb0f71ec03b542cce095067 | Java | hujunjiehit/HealthMail | /app/src/main/java/com/june/healthmail/model/AccessToken.java | UTF-8 | 1,500 | 1.84375 | 2 | [] | no_license | package com.june.healthmail.model;
/**
* Created by june on 2017/3/4.
*/
public class AccessToken {
private String recId;
private String mallId;
private String telephone;
private String token;
private String userName;
private String openId;
private String unionId;
private String userType;
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getRecId() {
return recId;
}
public void setRecId(String recId) {
this.recId = recId;
}
public String getMallId() {
return mallId;
}
public void setMallId(String mallId) {
this.mallId = mallId;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getUnionId() {
return unionId;
}
public void setUnionId(String unionId) {
this.unionId = unionId;
}
}
| true |
2009510982dca8860171e7ab3cd95a57d2985cd6 | Java | cckmit/ddhb_v2 | /hshb_src/com/huatek/hbwebsite/util/CallERPPublicCls.java | UTF-8 | 4,327 | 2.109375 | 2 | [] | no_license | package com.huatek.hbwebsite.util;
import com.huatek.ddhb.manage.frontsystemsetting.entity.FrontSystemSetting;
import com.huatek.ddhb.manage.frontsystemsetting.service.FrontSystemSettingService;
import com.huatek.framework.util.SpringContext;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.log4j.Logger;
public class CallERPPublicCls {
private static FrontSystemSettingService frontSystemSettingService = null;
private static final CallERPPublicCls callERPPublicCls = new CallERPPublicCls();
private static String ERPWebServiceAddr_path = "";
private static String ERPWebServiceAddr_UserName = "";
private static String ERPWebServiceAddr_PassWord = "";
private static final Logger LOGGER = Logger.getLogger(CallERPPublicCls.class);
public static CallERPPublicCls getInstance() {
return callERPPublicCls;
}
public static synchronized String getERPWebServiceAddrUserName() {
if (!"".equals(ERPWebServiceAddr_UserName) && ERPWebServiceAddr_UserName != null) {
return ERPWebServiceAddr_UserName;
} else {
frontSystemSettingService = (FrontSystemSettingService) SpringContext.getBean("frontSystemSettingService");
FrontSystemSetting frontSystemSetting = frontSystemSettingService.loadSpecificSetting("WS_UserName");
return frontSystemSetting.getSettingValue();
}
}
public static synchronized String getERPWebServiceAddrPassword() {
if (!"".equals(ERPWebServiceAddr_PassWord) && ERPWebServiceAddr_PassWord != null) {
return ERPWebServiceAddr_PassWord;
} else {
frontSystemSettingService = (FrontSystemSettingService) SpringContext.getBean("frontSystemSettingService");
FrontSystemSetting frontSystemSetting = frontSystemSettingService.loadSpecificSetting("WS_Password");
return frontSystemSetting.getSettingValue();
}
}
public static synchronized String getERPWebServiceAddrPath() {
if (!"".equals(ERPWebServiceAddr_path) && ERPWebServiceAddr_path != null) {
return ERPWebServiceAddr_path;
} else {
frontSystemSettingService = (FrontSystemSettingService) SpringContext.getBean("frontSystemSettingService");
FrontSystemSetting frontSystemSetting = frontSystemSettingService.loadSpecificSetting("WS_Path");
return frontSystemSetting.getSettingValue();
}
}
public static synchronized void clean() {
ERPWebServiceAddr_UserName = "";
ERPWebServiceAddr_PassWord = "";
ERPWebServiceAddr_path = "";
}
public static String CallERPWebser(String strXML) {
String strResult = "";
try {
Service ex = new Service();
Call call = (Call) ex.createCall();
call.setTargetEndpointAddress(new URL(getERPWebServiceAddrPath()));
call.setUseSOAPAction(true);
call.setSOAPActionURI("http://xerp.hzhuabang.net/DataSync");
call.setOperationName(new QName("http://xerp.hzhuabang.net/", "DataSync"));
call.addParameter(new QName("http://xerp.hzhuabang.net/", "xmlString"), XMLType.XSD_STRING, ParameterMode.IN);
call.setReturnType(XMLType.XSD_STRING);
SOAPHeaderElement soapHeaderElement = new SOAPHeaderElement("http://xerp.hzhuabang.net/", "ERPSoapHeader");
soapHeaderElement.setNamespaceURI("http://xerp.hzhuabang.net/");
soapHeaderElement.addChildElement("UserName").setValue(getERPWebServiceAddrUserName());
soapHeaderElement.addChildElement("PassWord").setValue(getERPWebServiceAddrPassword());
call.addHeader(soapHeaderElement);
strResult = (String) call.invoke(new Object[] { strXML });
} catch (Exception var5) {
LOGGER.error(var5.getMessage());
}
return strResult;
}
public static String strXML(String UUID, String DataType, String DataBodyXML) {
StringBuffer strBu = new StringBuffer();
DataBodyXML = DataBodyXML.replace("<list>", "<DataBody>");
DataBodyXML = DataBodyXML.replace("</list>", "</DataBody>");
strBu.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
strBu.append("<BasicData>");
strBu.append("<DataHeader>");
strBu.append("<DataSetID>" + UUID + "</DataSetID>");
strBu.append("<DataType>" + DataType + "</DataType>");
strBu.append("</DataHeader>");
strBu.append(DataBodyXML);
strBu.append("</BasicData>");
return strBu.toString();
}
}
| true |
1aab1abf620c34dc02efc520f85925ca323ead3c | Java | MehmedMazlum/Java-Gsu | /son_ekler/src/son_ekler/bomba_bomba.java | UTF-8 | 1,327 | 2.8125 | 3 | [] | no_license | package son_ekler;
import java.awt.*;
import java.applet.*;
import java.awt.event.* ;
public class bomba_bomba extends Applet implements KeyListener {
int x = 50 ;
int v = 10 ;
int p ;
int d ;
int g = 5 ;
int t = 0 ;
int k = 0 ;
int m = 200 ;
public void init() {
setSize(500,300);
setBackground(Color.yellow);
addKeyListener(this) ;
}
public void paint(Graphics g) {
Font tt = new Font ("Times New Roman", Font.PLAIN, 30) ;
g.setFont(tt) ;
//g.drawString("Welcome to Java!!", 50, 60 );
g.drawLine(0,280,500,280);
g.fillRect(m,230,50,50) ;
g.fillRect(x, 50, 50,30) ;
g.fillOval(p,d,10,10);
p = x + 20 ;
d = 50 ;
if ( k == 1 )
{
t = t + 1 ;
p = p + v*t ;
d = d + 5*t*t ;
}
if ( d > 300 || p > 500)
{
k = 0 ;
t = 0 ;
}
if ( (p >= m && p <= (m +50)) && (d>= 230 && d<= 280 ) )
{
g.drawString("hedef vurulmustur", 100, 100);
m = m + 10 ;
}
try
{
Thread.sleep(100);
}catch(Exception e)
{
}
x = x + 10;
if (x == 500 )
{
x = 0 ;
}
repaint();
}
public void keyPressed ( KeyEvent e )
{
int tus = e.getKeyCode() ;
switch(tus)
{
case(KeyEvent.VK_SPACE):
{
k++ ;
} break ;
}
repaint() ;
}
public void keyReleased(KeyEvent e )
{
}
public void keyTyped( KeyEvent e )
{
}
}
| true |
76e4f1a7e063e063e561f5813bddda2e6072ba43 | Java | ofs-vinoth/myrepo | /src/bean/GetAll.java | UTF-8 | 472 | 2.203125 | 2 | [] | no_license | package bean;
import java.sql.ResultSet;
import java.util.ArrayList;
import database.Database;
public class GetAll {
public static ResultSet getEmp(){
ResultSet result=null;
try {
String queryString ="select a.eid,name,dept,basic,hra,dp,pi " +
"from empone a,emptwo b where a.eid=b.eid";
result = Database.getStatement().executeQuery(queryString);
return result;
}
catch (Exception e) {
// TODO: handle exception
return result;
}
}
}
| true |
c73b50453d1ea3aefcb3fe8858e892f21ce993b5 | Java | gnerga/zzpj | /src/main/java/com/example/zzpj/users/UserController.java | UTF-8 | 554 | 1.75 | 2 | [] | no_license | package com.example.zzpj.users;
import com.example.zzpj.security.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("user")
public class UserController {
private UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
} | true |
36dfc0b05b66b68812b9b78a539cad527d7950b0 | Java | ezbake/ezbake-intent-query | /intentquerysampleapp/intentquery-sample-app-mongo/src/main/java/ezbake/IntentQuery/Sample/MongoDatasource/Client/TestPredicatesBuilder.java | UTF-8 | 6,298 | 2.0625 | 2 | [
"Apache-2.0"
] | permissive | /* Copyright (C) 2013-2014 Computer Sciences Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
package ezbake.IntentQuery.Sample.MongoDatasource.Client;
import java.util.ArrayList;
import java.util.List;
import com.cloudera.impala.extdatasource.thrift.TBinaryPredicate;
import com.cloudera.impala.extdatasource.thrift.TColumnDesc;
import com.cloudera.impala.extdatasource.thrift.TComparisonOp;
import com.cloudera.impala.thrift.TColumnType;
import com.cloudera.impala.thrift.TColumnValue;
import com.cloudera.impala.thrift.TPrimitiveType;
public class TestPredicatesBuilder {
// (employer = "Cloudera")
public static List<List<TBinaryPredicate>> ConstructPredicates_01() {
List<List<TBinaryPredicate>> predicates = new ArrayList<List<TBinaryPredicate>>();
List<TBinaryPredicate> binaryPredicateList1 = new ArrayList<TBinaryPredicate>();
TColumnDesc colDesc_1 = new TColumnDesc("employer", new TColumnType(TPrimitiveType.STRING));
TColumnValue colValue_1 = new TColumnValue();
colValue_1.setStringVal("Cloudera");
TBinaryPredicate p_1 = new TBinaryPredicate(colDesc_1, TComparisonOp.EQ, colValue_1);
binaryPredicateList1.add(p_1);
predicates.add(binaryPredicateList1);
return predicates;
}
// (employer = "Cloudera") and (gender = "M")
public static List<List<TBinaryPredicate>> ConstructPredicates_02() {
List<List<TBinaryPredicate>> predicates = new ArrayList<List<TBinaryPredicate>>();
List<TBinaryPredicate> binaryPredicateList_1 = new ArrayList<TBinaryPredicate>();
TColumnDesc colDesc = null;
TColumnValue colValue = null;
TBinaryPredicate binary_p = null;
colDesc = new TColumnDesc("employer", new TColumnType(TPrimitiveType.STRING));
colValue = new TColumnValue();
colValue.setStringVal("Cloudera");
binary_p = new TBinaryPredicate(colDesc, TComparisonOp.EQ, colValue);
binaryPredicateList_1.add(binary_p);
List<TBinaryPredicate> binaryPredicateList_2 = new ArrayList<TBinaryPredicate>();
colDesc = new TColumnDesc("gender", new TColumnType(TPrimitiveType.STRING));
colValue = new TColumnValue();
colValue.setStringVal("M");
binary_p = new TBinaryPredicate(colDesc, TComparisonOp.EQ, colValue);
binaryPredicateList_2.add(binary_p);
predicates.add(binaryPredicateList_1);
predicates.add(binaryPredicateList_2);
return predicates;
}
// (employer2 = "Cloudera") and (employer = "Cloudera") and (age > 40 or gender = "F")
public static List<List<TBinaryPredicate>> ConstructPredicates_03() {
List<List<TBinaryPredicate>> predicates = new ArrayList<List<TBinaryPredicate>>();
TColumnDesc colDesc = null;
TColumnValue colValue = null;
TBinaryPredicate binary_p = null;
// a wrong predicate
List<TBinaryPredicate> binaryPredicateList_0 = new ArrayList<TBinaryPredicate>();
colDesc = new TColumnDesc("employer2", new TColumnType(TPrimitiveType.STRING));
colValue = new TColumnValue();
colValue.setStringVal("Cloudera");
binary_p = new TBinaryPredicate(colDesc, TComparisonOp.EQ, colValue);
binaryPredicateList_0.add(binary_p);
// employer = Cloudera
List<TBinaryPredicate> binaryPredicateList_1 = new ArrayList<TBinaryPredicate>();
colDesc = new TColumnDesc("employer", new TColumnType(TPrimitiveType.STRING));
colValue = new TColumnValue();
colValue.setStringVal("Cloudera");
binary_p = new TBinaryPredicate(colDesc, TComparisonOp.EQ, colValue);
binaryPredicateList_1.add(binary_p);
// age > 30 or gender = "F"
List<TBinaryPredicate> binaryPredicateList_2 = new ArrayList<TBinaryPredicate>();
colDesc = new TColumnDesc("age", new TColumnType(TPrimitiveType.INT));
colValue = new TColumnValue();
colValue.setIntVal(40);
binary_p = new TBinaryPredicate(colDesc, TComparisonOp.GT, colValue);
binaryPredicateList_2.add(binary_p);
colDesc = new TColumnDesc("gender", new TColumnType(TPrimitiveType.STRING));
colValue = new TColumnValue();
colValue.setStringVal("F");
binary_p = new TBinaryPredicate(colDesc, TComparisonOp.EQ, colValue);
binaryPredicateList_2.add(binary_p);
predicates.add(binaryPredicateList_0);
predicates.add(binaryPredicateList_1);
predicates.add(binaryPredicateList_2);
return predicates;
}
// employer = "Cloudera" and (age > 30) and (age < 50)
public static List<List<TBinaryPredicate>> ConstructPredicates_04() {
List<List<TBinaryPredicate>> predicates = new ArrayList<List<TBinaryPredicate>>();
List<TBinaryPredicate> binaryPredicateList_1 = new ArrayList<TBinaryPredicate>();
TColumnDesc colDesc = null;
TColumnValue colValue = null;
TBinaryPredicate binary_p = null;
// employer = Cloudera
colDesc = new TColumnDesc("employer", new TColumnType(TPrimitiveType.STRING));
colValue = new TColumnValue();
colValue.setStringVal("Cloudera");
binary_p = new TBinaryPredicate(colDesc, TComparisonOp.EQ, colValue);
binaryPredicateList_1.add(binary_p);
// age > 30
List<TBinaryPredicate> binaryPredicateList_2 = new ArrayList<TBinaryPredicate>();
colDesc = new TColumnDesc("age", new TColumnType(TPrimitiveType.INT));
colValue = new TColumnValue();
colValue.setIntVal(30);
binary_p = new TBinaryPredicate(colDesc, TComparisonOp.GT, colValue);
binaryPredicateList_2.add(binary_p);
// age > 30
List<TBinaryPredicate> binaryPredicateList_3 = new ArrayList<TBinaryPredicate>();
colDesc = new TColumnDesc("age", new TColumnType(TPrimitiveType.INT));
colValue = new TColumnValue();
colValue.setIntVal(50);
binary_p = new TBinaryPredicate(colDesc, TComparisonOp.LT, colValue);
binaryPredicateList_3.add(binary_p);
predicates.add(binaryPredicateList_1);
predicates.add(binaryPredicateList_2);
predicates.add(binaryPredicateList_3);
return predicates;
}
}
| true |
c5d1651e161c2a214107967d232ddfa7488c4eca | Java | happy6eve/AppPackager | /02_SourceCode/front/service/app/enums/LayoutCustomizedEnum.java | UTF-8 | 599 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | package enums;
/**
* Created by admin on 2015/11/12.
*/
public enum LayoutCustomizedEnum {
LAYOUT_CUSTOMIZED_PARAMS_ISNULL("layout_customized_0001","缺少主要参数"),
LAYOUT_CUSTOMIZED_SCENEID_ISNULL("layout_customized_0002","场景id为空"),
;
private final String code;
private final String message;
LayoutCustomizedEnum(String code, String message){
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
}
| true |
c43d1851d6d0c3783f87dcfd235255713a42c8f4 | Java | lbroudoux/apicurio-data-models | /src/main/java/io/apicurio/datamodels/asyncapi/v2/models/Aai20Message.java | UTF-8 | 505 | 2 | 2 | [
"Apache-2.0"
] | permissive | package io.apicurio.datamodels.asyncapi.v2.models;
import io.apicurio.datamodels.asyncapi.models.AaiMessage;
import io.apicurio.datamodels.core.models.Node;
/**
* @author Jakub Senko <jsenko@redhat.com>
*/
public class Aai20Message extends AaiMessage {
/**
* Constructor.
*/
public Aai20Message(String name) {
super(name);
}
public Aai20Message(Node parent) {
super(parent);
}
public Aai20Message(Node parent, String name) {
super(parent, name);
}
}
| true |
f467d67c07efba8a1eb0caea6c5044868ce99ca3 | Java | pjs6747/LBMS | /src/model/Visit.java | UTF-8 | 1,377 | 3.5625 | 4 | [] | no_license | package model;
/*
Project: LBMS
File: Visit
Author: Group 4
*/
import java.time.LocalDate;
import java.time.LocalTime;
public class Visit {
/**
* Visitor makeing the visit
*/
private Visitor visitor;
/**
* Date of the visit
*/
private LocalDate Date;
/**
* Start time of visit
*/
private LocalTime startTime;
/**
* End time of visit
*/
private LocalTime endTime;
public Visit(Visitor visitor, LocalDate date, LocalTime startTime){
this.visitor = visitor;
this.startTime = startTime;
this.Date = date;
}
/**
* Records the time the visit ended
* @param endTime
*/
public void endVisit(LocalTime endTime){
this.endTime = endTime;
}
/**
* Gets visitor
* @return visit visitor
*/
public Visitor getVisitor() {
return visitor;
}
/**
* Gets startDate
* @return visit startDate
*/
public LocalDate getDate() {
return Date;
}
public LocalTime getStartTime(){return startTime;}
/**
* Gets endDate
* @return visit endDate
*/
public LocalTime getEndTime() {
return endTime;
}
@Override
public String toString() {
return visitor + " visited on " + Date + " at " + startTime + " and left at " + endTime;
}
}
| true |
4578a32a2f1ac9198f0c14027aa58c0a6340edec | Java | rcauth-eu/OA4MP | /oa4mp-server-loader-oauth2/src/main/java/edu/uiuc/ncsa/myproxy/oa4mp/oauth2/storage/OA2MTStore.java | UTF-8 | 1,770 | 2.3125 | 2 | [] | no_license | package edu.uiuc.ncsa.myproxy.oa4mp.oauth2.storage;
import edu.uiuc.ncsa.myproxy.oa4mp.oauth2.OA2ServiceTransaction;
import edu.uiuc.ncsa.security.core.IdentifiableProvider;
import edu.uiuc.ncsa.security.delegation.storage.impl.TransactionMemoryStore;
import edu.uiuc.ncsa.security.delegation.token.RefreshToken;
/**
* <p>Created by Jeff Gaynor<br>
* on 3/25/14 at 12:51 PM
*/
public class OA2MTStore<V extends OA2ServiceTransaction> extends TransactionMemoryStore<V> implements RefreshTokenStore<V>, UsernameFindable<V>{
public OA2MTStore(IdentifiableProvider identifiableProvider) {
super(identifiableProvider);
}
TokenIndex rtIndex;
TokenIndex userIndex;
public TokenIndex getRTIndex() {
if (rtIndex == null) {
rtIndex = new TokenIndex();
}
return rtIndex;
}
public TokenIndex getUserIndex(){
if(userIndex == null){
userIndex = new TokenIndex();
}
return userIndex;
}
@Override
protected void updateIndices(V v) {
super.updateIndices(v);
if (v.getRefreshToken() != null) {
getRTIndex().put(v.getRefreshToken().getToken(), v);
}
if(v.getUsername()!= null){
getUserIndex().put(v.getUsername(), v);
}
}
@Override
protected void removeItem(V value) {
super.removeItem(value);
getRTIndex().remove(value.getRefreshToken());
getUserIndex().remove(value.getUsername());
}
@Override
public OA2ServiceTransaction get(RefreshToken refreshToken) {
return getRTIndex().get(refreshToken.getToken());
}
@Override
public V getByUsername(String username) {
return getUserIndex().get(username);
}
}
| true |
5c028637004a83d95c58dcbbd27238cb22b78ab4 | Java | FlashChenZhi/ykk_sz_gm | /webapp/wms/WEB-INF/src/jp/co/daifuku/wms/asrs/communication/as21/CommunicationAgc.java | UTF-8 | 14,878 | 2.078125 | 2 | [] | no_license | // $Id: CommunicationAgc.java,v 1.3 2006/11/13 08:30:58 suresh Exp $
package jp.co.daifuku.wms.asrs.communication.as21 ;
//#CM30992
/*
* Copyright 2000-2001 DAIFUKU Co.,Ltd. All Rights Reserved.
*
* This software is the proprietary information of DAIFUKU Co.,Ltd.
* Use is subject to license terms.
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.DecimalFormat;
import jp.co.daifuku.wms.asrs.common.AsrsParam;
import jp.co.daifuku.common.CommonParam;
import jp.co.daifuku.common.InvalidProtocolException;
import jp.co.daifuku.common.LogMessage;
import jp.co.daifuku.common.RandomAcsFileHandler;
//#CM30993
/**
* This class sends/receives texts according to AS21 ptrotocol.
* Connection is made with specified group controller, then text is sent/received.
* Send/receive txet are done according to TCP/IP protocol.
*
* <BR>
* <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0">
* <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"><TD>Date</TD><TD>Name</TD><TD>Comment</TD></TR>
* <TR><TD>2001/07/01</TD><TD>mura</TD><TD>created this class</TD></TR>
* </TABLE>
* <BR>
* @version $Revision: 1.3 $, $Date: 2006/11/13 08:30:58 $
* @author $Author: suresh $
*/
public class CommunicationAgc extends Object
{
//#CM30994
// Class fields --------------------------------------------------
//#CM30995
/**
* Defines the default server name on AGC side for AS21.
*/
public static final String DEFAULT_NAME = "AGC01";
//#CM30996
/**
* Defines the default server port on AGC side for AS21.
*/
public static final int DEFAULT_PORT = 2000;
//#CM30997
/**
* Defines the length of communication message of AS21.
*/
public static final int DEFAULT_LENGTH = 512;
//#CM30998
/**
* Defines the least length of communication message of AS 21.
*/
public static final int MINIMAM_LENGTH = 24;
//#CM30999
/**
* Defines the start mark STX of the communication message according to AS21.
*/
public static final int STX = 0x02;
//#CM31000
/**
* Defines the end mark ETX of the communication message according to AS21.
*/
public static final int ETX = 0x03;
//#CM31001
/**
* Defines the Seqence No. Format according to AS21.
*/
public static final String SEQ_FORMAT = "0000";
//#CM31002
/**
* Defines the character coding of communication message according to AS21.
*/
public static final String CODE = "Shift_JIS";
//#CM31003
/**
* Defines the name of resource (trace directory)
*/
public static final String LOGS_PATH = "LOGS_PATH" ;
//#CM31004
/**
* Defines the name of resource (file name of Send trace pointer)
*/
public static final String S_POINTER_NAME = "AS21_SEND_TRACE_POINTER_NAME" ;
//#CM31005
/**
* Defines the name of resource (file name of Receive file pointer)
*/
public static final String R_POINTER_NAME = "AS21_RECEIVE_TRACE_POINTER_NAME" ;
//#CM31006
/**
* Defines the name of resource (log-on the action of communication )
*/
public static final String A_LOG_ON = "AS21_ACTION_LOG_ON" ;
//#CM31007
/**
* Defines the name of resource (file name of the operation log of communication)
*/
public static final String A_LOG_NAME = "AS21_ACTION_LOG_NAME" ;
//#CM31008
/**
* Defines the name of resource (MAX. of the trace file size, in byte)
*/
public static final String MAX_SIZE = "TRACE_MAX_SIZE" ;
//#CM31009
/**
* Maximal value as a sequence number in communicating with AGC
*/
public static final int MAX_SEQ_NUMBER = 9999;
//#CM31010
/**
* Initial value as a sequesnce number in communicating with AGC
*/
public static final int INITIAL_NUMBER = 0;
//#CM31011
/**
* Start value of the loop as a sequence number in communicating with AGC
*/
public static final int LOOP_START_NUMBER = 1;
//#CM31012
// Class variables -----------------------------------------------
//#CM31013
/**
* Name of AGC server
*/
protected String host;
//#CM31014
/**
* AGC's server port
*/
protected int port;
//#CM31015
/**
* COnnection socket with AGC
*/
protected Socket socket = null ;
//#CM31016
/**
* Output data stream to AGC
*/
protected DataOutputStream wDataOut ;
//#CM31017
/**
* INput data stream from AGC
*/
protected DataInputStream wDataIn ;
//#CM31018
/**
* Directory to record the trace file
*/
protected String LogDir = null ;
//#CM31019
/**
* Flag to indicate whether/not to record messages sent to AGC in the trace file
*/
protected boolean sTrOn = false ;
//#CM31020
/**
* Trace file of messages sent to AGC
*/
protected String sTrName = "sendTrace.txt" ;
//#CM31021
/**
* Log handler for the trace file of messages sent to AGC
*/
protected RandomAcsFileHandler sTrHandler = null;
//#CM31022
/**
* Flag to indicate whether/not to record messages recived from AGC in the trace file
*/
protected boolean rTrOn = false ;
//#CM31023
/**
* Trace file of messages received from AGC
*/
protected String rTrName = "receiveTrace.txt" ;
//#CM31024
/**
* Log handler for the trace file of messages received from AGC
*/
protected RandomAcsFileHandler rTrHandler = null;
//#CM31025
/**
* Parameter for the AGC operation log file
*/
protected static Object[] aLogParam = new Object[1];
//#CM31026
/**
* Parameter for the Send trace file to AGC
*/
protected static Object[] sTrcParam = new Object[1];
//#CM31027
/**
* Parameter for the Receive trace file with AGC
*/
protected static Object[] rTrcParam = new Object[1];
//#CM31028
/**
* Format the port number for the operation log file of AGC communication
*/
protected static DecimalFormat fmt = new DecimalFormat("000000");
//#CM31029
/**
* Buffer for detailed description of the opreration for the opration log of AGC communciation
*/
String action = "";
//#CM31030
/**
* Maximal size of the trace file (byte)
*/
protected int FileSize = 1000000 ;
//#CM31031
/**
* Size of a line in the trace file (byte)
*/
protected int LineLength = 512 ;
//#CM31032
// Class method --------------------------------------------------
//#CM31033
/**
* Returns the version of this class.
* @return Version and the date
*/
public static String getVersion()
{
return ("$Revision: 1.3 $,$Date: 2006/11/13 08:30:58 $") ;
}
//#CM31034
// Constructors --------------------------------------------------
//#CM31035
/**
* Prepares to establish the connection of AGC in lower class controller and TCP/IP.
* Behaves by default to connect with the host AGC 01, at port number 2000, as a client.
*/
public CommunicationAgc()
{
this(DEFAULT_NAME, DEFAULT_PORT) ;
}
//#CM31036
/**
* Prepares to establish the connection of AGC in lower class controller and TCP/IP.
* It behaves as a cliant that connect with the specified Host, to the specified port number.
* @param host : name of the host connecting to
* @param port : port number of the connecting host
*/
public CommunicationAgc( String host, int port )
{
this.host = host;
this.port = port;
//#CM31037
// Sets the directory to record trace file
LogDir = CommonParam.getParam(LOGS_PATH);
//#CM31038
// Sets the MAX. of size of trace file
FileSize = AsrsParam.TRACE_MAX_SIZE;
//#CM31039
// Sets the flag to indicate whether/not to record the sending message in trace file
if( AsrsParam.AS21_SEND_TRACE_ON )
{
//#CM31040
// Sets the trace file which the sending message should be recorded
sTrName = LogDir + host + AsrsParam.AS21_SEND_TRACE_NAME;
sTrOn = true;
}
//#CM31041
// Sets the flag to indicate whether/not to record the receiving message in trace file
if( AsrsParam.AS21_RECEIVE_TRACE_ON )
{
//#CM31042
// Sets the trace file which the receiving message should be recorded
rTrName = LogDir + host + AsrsParam.AS21_RECEIVE_TRACE_NAME;
rTrOn = true;
}
}
//#CM31043
// Public methods ------------------------------------------------
//#CM31044
/**
* Connects with AGC as a cliant
* @return : socket to the connecting AGC
* @throws IOException : Notifies if file I/O error occured.
*/
public Socket connect() throws IOException
{
socket = new Socket( host, port );
wDataIn = new DataInputStream( new BufferedInputStream( socket.getInputStream() ) ) ;
wDataOut = new DataOutputStream( new BufferedOutputStream( socket.getOutputStream() ) ) ;
//#CM31045
// Check whether/not the operation log to be recorded; records log accordingly.
action = "AGC Connect HostName =" + host + " PortNumber = " + fmt.format(port) ;
this.actionLogWrite(action);
return( socket ) ;
}
//#CM31046
/**
* Disconnect with AGC as a cliant.
* @throws IOException : Notifies if file I/O error occured.
*/
public void disconnect() throws IOException
{
socket.close();
}
//#CM31047
/**
* Confirms that connection has comleted.
* @return Returns 'true' if connection is complete.
*/
public boolean isConnected()
{
return(socket != null) ;
}
//#CM31048
/**
* Returns input stream to AGC
* @return DataInputStream to the TCP/IP Socket
*/
public DataInputStream getInStream()
{
return( wDataIn ) ;
}
//#CM31049
/**
* Returns output stream to AGC
* @return DataOutputStream to the TCP/IP Socket
*/
public DataOutputStream getOutStream()
{
return( wDataOut ) ;
}
//#CM31050
/**
* Sends the communication message to AGC.
* @param msg : Communication message (ID, ID classification, MC send time, AGC send time, data)
* @param seqNo : Sequesnce no. of the sent message
* @throws IOException : Notifies if file I/O error occured.
*/
public void send(String msg, int seqNo) throws IOException
{
StringBuffer wkstbuf = new StringBuffer();
//#CM31051
// Editing the Seq no.
DecimalFormat fmt1 = new DecimalFormat(SEQ_FORMAT) ;
String c_seqNo = fmt1.format(seqNo) ;
//#CM31052
// Sequense No. is merged with the communication message.
String wkstr = wkstbuf.append(c_seqNo).append(msg).toString();
//#CM31053
// Sending data must be Shift_JIS (according to the regulation of AS21 communication)
byte[] s_byteMsg = wkstr.getBytes(CODE);
//#CM31054
// Creates Bcc.
Bcc bcc = new Bcc();
String sBcc = bcc.make(s_byteMsg, s_byteMsg.length);
byte[] s_byteBcc = sBcc.getBytes(CODE);
//#CM31055
// Sends STX.
wDataOut.writeByte( STX );
//#CM31056
// Sends the communication message body.
wDataOut.write( s_byteMsg, 0, s_byteMsg.length);
//#CM31057
// Sends BCC.
wDataOut.write( s_byteBcc, 0, s_byteBcc.length);
//#CM31058
// Sends ETX.
wDataOut.writeByte( ETX );
//#CM31059
// Sends as an actual process
wDataOut.flush();
//#CM31060
// Check whether/not the operation log to be recorded; records log accordingly
action = "AGC Send ";
this.actionLogWrite(action);
//#CM31061
// Check whether/not the receiving trace to be recorded; records trace accordingly.
this.sendTraceWrite(wkstr);
}
//#CM31062
/**
* Receive communication message from AGC.
* @return Receiving message should be a message with STX, ETX and BCC omitted.
* @throws InvalidProtocolException : Notifies if improper information is included for protocol aspect.
* @throws IOException : Notifies if file I/O error occured.
*/
public byte[] recv() throws InvalidProtocolException, IOException
{
byte[] inByte = new byte[DEFAULT_LENGTH];
byte ret = 0;
int ii = 0;
int rcvLength = 0;
while( true )
{
ret = wDataIn.readByte();
rcvLength++ ;
if( ret == STX )
{
//#CM31063
// Ignore message of STX only.
rcvLength = 1;
continue;
}
else if ( ret == ETX )
{
if( rcvLength == 1 )
{
rcvLength = 0;
continue;
}
else
{
if( rcvLength > MINIMAM_LENGTH )
{
break;
}
//#CM31064
// Break the message if its length is less than the pre-defined least message length.
else
{
rcvLength = 0;
ii = 0;
continue;
}
}
}
//#CM31065
// Receive normal message
else
{
if( rcvLength > DEFAULT_LENGTH )
{
//#CM31066
// 6026059=database error occurred message={0}
throw new InvalidProtocolException("6026059");
}
else if( rcvLength != 1 )
{
inByte[ii++] = ret;
continue;
}
//#CM31067
// Keep breaking until STX is received
else
{
rcvLength = 0;
continue;
}
}
}
Bcc bcc = new Bcc();
//#CM31068
// Check the BCC value.
boolean cBcc = bcc.check( inByte, ii );
//#CM31069
// Transfer the required message length to the different array; then convert to string
//#CM31070
// In so doing, omit BCC part. (2 byte portion)
if( cBcc )
{
byte[] retbyte = new byte[ii];
for(int jj=0; jj < ii-2 ; jj++)
{
retbyte[jj] = inByte[jj];
}
//#CM31071
// Check whether/not the operation log to be recorded; records log accordingly
action = "AGC Receive ";
this.actionLogWrite(action);
//#CM31072
// Check whether/not the receiving trace to be recorded; records trace accordingly
this.receiveTraceWrite(new String (retbyte) );
return( retbyte );
}
else
{
throw new InvalidProtocolException("FTTB 6025131");
}
}
//#CM31073
/**
* Logging of operation over communication with AGC
* @param Content of logging
*/
public void actionLogWrite(String action1)
{
aLogParam[0] = action1;
}
//#CM31074
/**
* Trace the content sent to AGC
* @param content of the trace
* @throws IOException : Notifies if file I/O error occured.
*/
public void sendTraceWrite(String trdata) throws IOException
{
if( sTrOn && (sTrHandler == null) )
{
sTrHandler = new RandomAcsFileHandler(sTrName, FileSize) ;
}
if( !(sTrHandler == null))
{
synchronized ( sTrHandler )
{
sTrcParam[0] = trdata;
sTrHandler.write(0, LogMessage.F_INFO, "CommunicatinAgc", sTrcParam);
}
}
}
//#CM31075
/**
* Trace the content received from AGC
* @param content of the trace
* @throws IOException : Notifies if file I/O error occured.
*/
public void receiveTraceWrite(String trdata) throws IOException
{
if( rTrOn && (rTrHandler == null) )
{
rTrHandler = new RandomAcsFileHandler(rTrName, FileSize) ;
}
if( !(rTrHandler == null))
{
synchronized ( rTrHandler )
{
rTrcParam[0] = trdata;
rTrHandler.write(1, LogMessage.F_INFO, "CommunicatinAgc", rTrcParam);
}
}
}
//#CM31076
// Package methods -----------------------------------------------
//#CM31077
// Protected methods ---------------------------------------------
//#CM31078
// Private methods -----------------------------------------------
}
//#CM31079
//end of class
| true |
f44ce41ff62fecefc76fd81ea1b385ad3ab46c4b | Java | longphamit/FakeFlappyBird | /src/Entity/Bird.java | UTF-8 | 852 | 2.8125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Entity;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;
/**
*
* @author Asus
*/
public class Bird extends Rectangle {
String image;
public Bird(String image, int x, int y, int width, int height) {
super(x, y, width, height);
this.image = image;
}
public void DrawBird(Graphics g){
ImageIcon icon= new ImageIcon(image);
Image image=icon.getImage();
g.drawImage(image, x, y,null);
// g.setColor(Color.red);
// g.fillRect(x, y, width, height);
}
}
| true |
625ee679c28b6bb8921d48806a83c1b315e1a2c3 | Java | Jan-OkeMettendorf/my-first-maven-repo | /src/test/java/CalculatorTest.java | UTF-8 | 2,626 | 3.15625 | 3 | [] | no_license | import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class CalculatorTest {
@Test
void testCalcAdd(){
//GIVE
int a = 2;
double b = 3;
//WHEN
double result = Calculator.calculateAdd(a, b);
//THEN
Assertions.assertEquals(5, result);
}
@Test
void testCalcSub(){
//GIVE
int a = 2;
double b = 3;
//WHEN
double result = Calculator.calculateSub(a, b);
//THEN
Assertions.assertEquals(-1, result);
}
@Test
void testCalcMul(){
//GIVE
int a = 2;
double b = 3;
//WHEN
double result = Calculator.calculateMul(a, b);
//THEN
Assertions.assertEquals(6, result);
}
@Test
void testCalcDiv(){
//GIVE
int a = 2;
double b = 4;
//WHEN
double result = Calculator.calculateDiv(a, b);
//THEN
Assertions.assertEquals(0.5, result);
}
@Test
void testCheckGreaterThan100True(){
//GIVE
int a = 200;
double b = 4;
//WHEN
boolean result = Calculator.checkSomeNumberGreaterThan100(a, b);
//THEN
Assertions.assertTrue(result);
}
@Test
void testCheckGreaterThan100False(){
//GIVE
int a = 5;
double b = 4;
//WHEN
boolean result = Calculator.checkSomeNumberGreaterThan100(a, b);
//THEN
Assertions.assertFalse(result);
}
@Test
void testCheckFancyTrue(){
//GIVE
String word = "asdfancyasd";
//WHEN
boolean result = Calculator.checkWordContainsFancy(word);
//THEN
Assertions.assertTrue(result);
}
@Test
void testCheckFancyFalse(){
//GIVE
String word = "asdasd";
//WHEN
boolean result = Calculator.checkWordContainsFancy(word);
//THEN
Assertions.assertFalse(result);
}
@Test
void testCheckLengthGreaterThan20CharsTrue(){
//GIVE
String word = "asdasasdag4gneklbmemb54b5zt45d";
//WHEN
boolean result = Calculator.checkLengthWordGreaterThan20Chars(word);
//THEN
Assertions.assertTrue(result);
}
@Test
void testCheckLengthGreaterThan20CharsFalse(){
//GIVE
String word = "asdasat45d";
//WHEN
boolean result = Calculator.checkLengthWordGreaterThan20Chars(word);
//THEN
Assertions.assertFalse(result);
}
}
| true |
62015e9df3633d7b81d6837cd0d90bb2d5c37046 | Java | SahanaK321/UniversityCourseSelection | /UniversityCourseSelection/src/main/java/com/cg/mts/entities/Applicant.java | UTF-8 | 3,177 | 2.3125 | 2 | [] | no_license | package com.cg.mts.entities;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Length;
@Entity
@Table(name = "Applicants")
public class Applicant {
@Id
@Column(name = "applicantId",length=20)
private String applicantId;
@Column(name = "applicantName",length=20)
private String applicantName;
@Column(name = "mobNo", unique = true)
@Size(min=10,max=10)
private String mobileNumber;
@Column(name = "applicantDegree",length=20)
private String applicantDegree;
@Column(name = "applicantPer")
@Min(0)
@Max(100)
private int applicantGraduationPercent;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "applicantId")
private List<Admission> admissions = new ArrayList<>();
@Enumerated(EnumType.STRING)
@Column(length=20)
private AdmissionStatus status;
public Applicant() {
// TODO Auto-generated constructor stub
}
public Applicant(String applicantId, String applicantName, String mobileNumber, String applicantDegree,
int applicantGraduationPercent, AdmissionStatus status) {
super();
this.applicantId = applicantId;
this.applicantName = applicantName;
this.mobileNumber = mobileNumber;
this.applicantDegree = applicantDegree;
this.applicantGraduationPercent = applicantGraduationPercent;
this.status = status;
}
public String getApplicantId() {
return applicantId;
}
public void setApplicantId(String applicantId) {
this.applicantId = applicantId;
}
public String getApplicantName() {
return applicantName;
}
public void setApplicantName(String applicantName) {
this.applicantName = applicantName;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getApplicantDegree() {
return applicantDegree;
}
public void setApplicantDegree(String applicantDegree) {
this.applicantDegree = applicantDegree;
}
public int getApplicantGraduationPercent() {
return applicantGraduationPercent;
}
public void setApplicantGraduationPercent(int applicantGraduationPercent) {
this.applicantGraduationPercent = applicantGraduationPercent;
}
public List<Admission> getAdmissions() {
return admissions;
}
public void setAdmissions(List<Admission> admissions) {
this.admissions = admissions;
}
public AdmissionStatus getStatus() {
return status;
}
public void setStatus(AdmissionStatus status) {
this.status = status;
}
} | true |
409fd72fcd010b069aea4b7d2ae22790d30aac97 | Java | younesschaoui15/Gestion-Des-Etudiants-ENSA | /app/src/main/java/chaoui/cy_15/www/gestiondabsencecy_15/classesActivity.java | UTF-8 | 3,472 | 2.390625 | 2 | [] | no_license | package chaoui.cy_15.www.gestiondabsencecy_15;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import chaoui.cy_15.www.gestiondabsencecy_15.classes.Adapters.rv_classesAdapter;
import chaoui.cy_15.www.gestiondabsencecy_15.classes.Database.myDBHelper;
import chaoui.cy_15.www.gestiondabsencecy_15.classes.Dialog.Popup;
import chaoui.cy_15.www.gestiondabsencecy_15.classes.Metier.Classe;
public class classesActivity extends AppCompatActivity
{
myDBHelper database;
RecyclerView rv_classes;
rv_classesAdapter classesAdapter;
AlertDialog popupAddClass;
Button btnAjouterClasse;
FloatingActionButton fab;
EditText etLibClasse;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_classes);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
database=new myDBHelper(this);
rv_classes = (RecyclerView) findViewById(R.id.rv_classes);
rv_classes.setLayoutManager(new LinearLayoutManager(this, 1, false));
classesAdapter=new rv_classesAdapter(database.getAllClasses());
rv_classes.setAdapter(classesAdapter);
fab = (FloatingActionButton) findViewById(R.id.fab);
View view = LayoutInflater.from(this).inflate(R.layout.popup_add_classe, null);
popupAddClass = Popup.createPopup(this, view, true);
btnAjouterClasse = (Button) view.findViewById(R.id.btnAjouterClasse);
etLibClasse = (EditText) view.findViewById(R.id.etLibClasse);
/*Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();*/
}
@Override
protected void onStart()
{
super.onStart();
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popupAddClass.show();
}
});
btnAjouterClasse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
String lib = etLibClasse.getText().toString();
if (lib.length() == 0) {
Toast.makeText(getApplicationContext(), "Veuillez remplire tout les champs !", Toast.LENGTH_LONG).show();
return;
}
Long insertedId = database.ajouterClasse(new Classe(0, lib));
if (insertedId == -1)
Toast.makeText(getApplicationContext(), "Une erreur dans l'insertion !", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "La classe (" + lib + ") à été ajoutée avec succes.", Toast.LENGTH_LONG).show();
popupAddClass.dismiss();
etLibClasse.setText("");
classesAdapter.setListeClasses(database.getAllClasses());
}
});
}
}
| true |
0043746395072c8131b2e978bb9ecee8acf2e932 | Java | koobonhui/java8 | /java8/src/Day14/DmbCellPhone.java | UHC | 459 | 3.203125 | 3 | [] | no_license | package Day14;
public class DmbCellPhone extends CellPhone{
int channel;
DmbCellPhone(String model, String color, int channel) {
this.model = model;
this.color = color;
this.channel = channel;
}
void On( ) {
System.out.println("Dmb Ҵ");
}
void Off( ) {
System.out.println("Dmb ");
}
void setChannel(int channel) {
this.channel = channel;
System.out.println(channel + " ");
}
}
| true |
95be2ff363d1bd729d20521474c6752f58b4a34b | Java | datree-amdocs-open-demo/zusammen-metadata-cassandra | /zusammen-state-store-cassandra-plugin/src/main/java/com/amdocs/zusammen/plugin/statestore/cassandra/VersionStateStore.java | UTF-8 | 5,054 | 1.75 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright © 2016-2017 European Support Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amdocs.zusammen.plugin.statestore.cassandra;
import com.amdocs.zusammen.plugin.statestore.cassandra.dao.VersionDaoFactory;
import com.amdocs.zusammen.datatypes.Id;
import com.amdocs.zusammen.datatypes.SessionContext;
import com.amdocs.zusammen.datatypes.Space;
import com.amdocs.zusammen.datatypes.item.ItemVersion;
import com.amdocs.zusammen.datatypes.item.ItemVersionData;
import com.amdocs.zusammen.plugin.statestore.cassandra.dao.ElementRepository;
import com.amdocs.zusammen.plugin.statestore.cassandra.dao.ElementRepositoryFactory;
import com.amdocs.zusammen.plugin.statestore.cassandra.dao.VersionDao;
import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntity;
import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext;
import java.util.Collection;
import java.util.Date;
class VersionStateStore {
Collection<ItemVersion> listItemVersions(SessionContext context, Space space, Id itemId) {
return getVersionDao(context).list(context, StateStoreUtil.getSpaceName(context, space), itemId);
}
boolean isItemVersionExist(SessionContext context, Space space, Id itemId, Id versionId) {
return getVersionDao(context).get(context, StateStoreUtil.getSpaceName(context, space), itemId, versionId)
.isPresent();
}
ItemVersion getItemVersion(SessionContext context, Space space, Id itemId, Id versionId) {
return getVersionDao(context).get(context, StateStoreUtil.getSpaceName(context, space), itemId, versionId)
.orElse(null);
}
void createItemVersion(SessionContext context, Space space, Id itemId, Id baseVersionId,
Id versionId, ItemVersionData data, Date creationTime) {
String spaceName = StateStoreUtil.getSpaceName(context, space);
getVersionDao(context)
.create(context, spaceName, itemId, baseVersionId, versionId, data, creationTime);
if (baseVersionId == null) {
return;
}
copyElements(context, spaceName, itemId, baseVersionId, versionId);
}
void updateItemVersion(SessionContext context, Space space, Id itemId, Id versionId,
ItemVersionData data, Date modificationTime) {
getVersionDao(context)
.update(context, StateStoreUtil.getSpaceName(context, space), itemId, versionId, data, modificationTime);
}
void deleteItemVersion(SessionContext context, Space space, Id itemId, Id versionId) {
String spaceName = StateStoreUtil.getSpaceName(context, space);
deleteElements(context, spaceName, itemId, versionId);
getVersionDao(context).delete(context, spaceName, itemId, versionId);
}
public void updateItemVersionModificationTime(SessionContext context, Space space, Id itemId,
Id versionId, Date modificationTime) {
getVersionDao(context)
.updateItemVersionModificationTime(context, StateStoreUtil.getSpaceName(context, space), itemId, versionId,
modificationTime);
}
private void copyElements(SessionContext context, String space, Id itemId, Id sourceVersionId,
Id targetVersionId) {
ElementRepository elementRepository = getElementRepository(context);
ElementEntityContext elementContext = new ElementEntityContext(space, itemId, sourceVersionId);
Collection<ElementEntity> versionElements = elementRepository.list(context, elementContext);
elementContext.setVersionId(targetVersionId);
versionElements
.forEach(elementEntity -> elementRepository.create(context, elementContext, elementEntity));
}
private void deleteElements(SessionContext context, String space, Id itemId, Id versionId) {
ElementRepository elementRepository = getElementRepository(context);
ElementEntityContext elementContext = new ElementEntityContext(space, itemId, versionId);
Collection<ElementEntity> versionElements = elementRepository.list(context, elementContext);
versionElements.stream()
.peek(elementEntity -> elementEntity.setParentId(null))
.forEach(elementEntity -> elementRepository.delete(context, elementContext, elementEntity));
}
protected VersionDao getVersionDao(SessionContext context) {
return VersionDaoFactory.getInstance().createInterface(context);
}
protected ElementRepository getElementRepository(SessionContext context) {
return ElementRepositoryFactory.getInstance().createInterface(context);
}
} | true |
077e9de4ef0b3dba007b2d6cd4ebdf6f131d6cba | Java | mwk719/springboot-jpa-frame | /src/main/java/com/jdy/sys/role/decker/SysRoleDecker.java | UTF-8 | 539 | 2.09375 | 2 | [] | no_license | package com.jdy.sys.role.decker;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.jdy.sys.role.dto.SysRole;
import com.jdy.sys.role.repository.SysRoleRepository;
@Repository
public class SysRoleDecker {
@Autowired
SysRoleRepository sysRoleRepository;
public SysRole findById(Integer roleId) {
Optional<SysRole> opt = sysRoleRepository.findById(roleId);
return opt.isPresent() ? opt.get() : null;
}
}
| true |
04fbdec3b22840219eb458177bee8eaa5ca61b3c | Java | almibaren/AlmibarenAndroid | /app/src/main/java/com/baren/almi/almibarenandroid/fragment/SmartphoneTabletFragment.java | UTF-8 | 1,816 | 2.125 | 2 | [] | no_license | package com.baren.almi.almibarenandroid.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.baren.almi.almibarenandroid.R;
import com.baren.almi.almibarenandroid.adapter.ListSmarTabAdapter;
public class SmartphoneTabletFragment extends Fragment {
private ListView lvSmarTab;
private ListSmarTabAdapter adapter;
public SmartphoneTabletFragment() {
}
public static Fragment newInstance() {
SmartphoneTabletFragment smartphoneTabletFragment = new SmartphoneTabletFragment();
return smartphoneTabletFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View vista = inflater.inflate(R.layout.fragment_smartphone_tablet, container, false);
return vista;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
lvSmarTab=view.findViewById(R.id.lvSmartphoneTablets);
adapter = new ListSmarTabAdapter(getContext());
lvSmarTab.setAdapter(adapter);
}
@Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
}
| true |
07e5daf45b04ae144df9619ce39535345817fe99 | Java | flywind2/joeis | /src/irvine/oeis/a207/A207724.java | UTF-8 | 567 | 2.546875 | 3 | [] | no_license | package irvine.oeis.a207;
// Generated by gen_pattern.pl - DO NOT EDIT here!
import irvine.oeis.GeneratingFunctionSequence;
/**
* A207724 Number of <code>n X 3 0..1</code> arrays avoiding <code>0 0 0</code> and <code>0 1 0</code> horizontally and <code>0 1 1</code> and <code>1 0 1</code> vertically.
* @author Georg Fischer
*/
public class A207724 extends GeneratingFunctionSequence {
/** Construct the sequence. */
public A207724() {
super(1, new long[] {0, 6, 18, -18, 9, 7, 3, -9, -1, -1, 1},
new long[] {1, -3, 2, -3, 6, 0, 0, -3, -1, 0, 1});
}
}
| true |
50545cea4fceec5dc3cadef39ede7190e7bd4246 | Java | KoopahTManiac/RoadRusherBeta | /core/src/com/koopahtmaniac/roadrusher/Items/Coins.java | UTF-8 | 935 | 2.703125 | 3 | [] | no_license | package com.koopahtmaniac.roadrusher.Items;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.koopahtmaniac.roadrusher.GameCore;
import com.koopahtmaniac.roadrusher.Objects.Coin;
import java.util.ArrayList;
public class Coins
{
public ArrayList<Coin> Coins = new ArrayList<Coin>();
public Coins()
{
// TODO Auto-generated constructor stub
}
public void Update(float GameTime)
{
for (int i =Coins.size()-1; i > 0;i--)
{
if(Coins.get(i).Y > GameCore.Height || Coins.get(i).Consumed)
{
Coins.remove(i);
}
else
{
Coins.get(i).Y += ((GameCore.MainRoad.BaseSpeed * GameCore.MainRoad.SpeedModifier) / (4*GameCore.SlowMotion+1)) * (GameTime/GameCore.FrameLimiter);
Coins.get(i).Update(GameTime);
}
}
}
public void Add(Coin coin)
{
Coins.add(coin);
}
public void Draw(SpriteBatch spritebatch)
{
for (Coin coin : this.Coins)
{
coin.Draw(spritebatch);
}
}
}
| true |
fcac852dc479fa1d84aa4689849f726f28b65a1e | Java | anathema/anathema-rcp | /net.sf.anathema.character.core/src/net/sf/anathema/character/core/model/content/ModelContentChecker.java | UTF-8 | 1,325 | 2.171875 | 2 | [] | no_license | package net.sf.anathema.character.core.model.content;
import net.sf.anathema.basics.eclipse.extension.AttributePredicate;
import net.sf.anathema.basics.eclipse.extension.ClassConveyerBelt;
import net.sf.anathema.basics.eclipse.extension.EclipseExtensionPoint;
import net.sf.anathema.character.core.plugin.internal.CharacterCorePlugin;
public class ModelContentChecker implements IContentChecker {
private static final String ATTRIB_CONTENT_ID = "contentId"; //$NON-NLS-1$
public String getContentValue(String definition) {
int seperator = definition.lastIndexOf('.');
return definition.substring(seperator + 1);
}
public IModelContentCheck getCheck(String definition) {
int seperator = definition.lastIndexOf('.');
final String contentId = definition.substring(0, seperator);
EclipseExtensionPoint extensionPoint = new EclipseExtensionPoint(CharacterCorePlugin.ID, "modelcheck"); //$NON-NLS-1$
AttributePredicate predicate = AttributePredicate.FromNameAndValue(ATTRIB_CONTENT_ID, contentId);
IModelContentCheck check = new ClassConveyerBelt<IModelContentCheck>(extensionPoint, IModelContentCheck.class, predicate).getFirstObject();
if (check == ClassConveyerBelt.NO_OBJECT_FOUND) {
return new NullModelContentCheck();
}
return check;
}
} | true |
08dd3c26cd447e7d803640630d22b66dddc16c56 | Java | hung060798/md2_bai18-thread | /src/taoThread/Main.java | UTF-8 | 474 | 2.5 | 2 | [] | no_license | package taoThread;
public class Main {
public static void main(String[] args) {
NumberGenerator numberGen1 = new NumberGenerator();
NumberGenerator numberGen2 = new NumberGenerator();
// numberGen1.getThread().setPriority(Thread.MAX_PRIORITY);
// numberGen2.getThread().setPriority(Thread.MIN_PRIORITY);
Thread t = new Thread(numberGen1);
Thread t1 = new Thread(numberGen1);
t.start();
t1.start();
}
}
| true |
49323937514c2d6906c80bd7ce814fe79bb44f1b | Java | jenkinsci/prometheus-plugin | /src/test/java/org/jenkinsci/plugins/prometheus/config/PrometheusConfigurationTest.java | UTF-8 | 9,699 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package org.jenkinsci.plugins.prometheus.config;
import hudson.model.Descriptor;
import hudson.util.FormValidation;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import net.sf.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kohsuke.stapler.StaplerRequest;
import org.mockito.Mockito;
import java.util.Arrays;
import java.util.List;
import static com.github.stefanbirkner.systemlambda.SystemLambda.withEnvironmentVariable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.*;
@RunWith(JUnitParamsRunner.class)
public class PrometheusConfigurationTest {
private PrometheusConfiguration configuration;
@Before
public void setup() {
configuration = Mockito.mock(PrometheusConfiguration.class);
Mockito.doNothing().when((Descriptor) configuration).load();
}
private List<String> wrongMetricCollectorPeriodsProvider() {
return Arrays.asList("0", "-1", "test", null, "100L");
}
@Test
@Parameters(method = "wrongMetricCollectorPeriodsProvider")
public void shouldGetErrorWhenNotPositiveNumber(String metricCollectorPeriod) throws Descriptor.FormException {
//given
Mockito.when(configuration.configure(any(), any())).thenCallRealMethod();
Mockito.when(configuration.doCheckCollectingMetricsPeriodInSeconds(any())).thenCallRealMethod();
JSONObject config = getDefaultConfig();
config.accumulate("collectingMetricsPeriodInSeconds", metricCollectorPeriod);
FormValidation formValidation = configuration.doCheckCollectingMetricsPeriodInSeconds(metricCollectorPeriod);
assertThat(formValidation.kind).isEqualTo(FormValidation.Kind.ERROR);
assertThat(formValidation.getMessage()).isEqualTo("CollectingMetricsPeriodInSeconds must be a positive value");
}
private List<String> correctMetricCollectorPeriodsProvider() {
return Arrays.asList("1", "100", "5.7", String.valueOf(Integer.MAX_VALUE));
}
@Test
@Parameters(method = "correctMetricCollectorPeriodsProvider")
public void shouldReturnOk(String metricCollectorPeriod) throws Descriptor.FormException {
//given
Mockito.when(configuration.configure(any(), any())).thenCallRealMethod();
JSONObject config = getDefaultConfig();
StaplerRequest request = Mockito.mock(StaplerRequest.class);
Mockito.doNothing().when(request).bindJSON(any(Object.class), any(JSONObject.class));
config.accumulate("collectingMetricsPeriodInSeconds", metricCollectorPeriod);
// when
boolean actual = configuration.configure(request, config);
// then
assertThat(actual).isTrue();
}
@Test
public void shouldSetDefaultValue() {
// given
Mockito.doCallRealMethod().when(configuration).setCollectingMetricsPeriodInSeconds(anyLong());
Mockito.when(configuration.getCollectingMetricsPeriodInSeconds()).thenCallRealMethod();
long metricCollectorPeriod = -1L;
// when
configuration.setCollectingMetricsPeriodInSeconds(metricCollectorPeriod);
long actual = configuration.getCollectingMetricsPeriodInSeconds();
// then
assertThat(actual).isEqualTo(PrometheusConfiguration.DEFAULT_COLLECTING_METRICS_PERIOD_IN_SECONDS);
}
@Test
public void shouldSetValueFromEnvForCollectingMetricsPeriodInSeconds() throws Exception {
// given
Mockito.doCallRealMethod().when(configuration).setCollectingMetricsPeriodInSeconds(anyLong());
Mockito.when(configuration.getCollectingMetricsPeriodInSeconds()).thenCallRealMethod();
long metricCollectorPeriod = -1L;
// when
withEnvironmentVariable(PrometheusConfiguration.COLLECTING_METRICS_PERIOD_IN_SECONDS, "1000")
.execute(() -> configuration.setCollectingMetricsPeriodInSeconds(metricCollectorPeriod));
long actual = configuration.getCollectingMetricsPeriodInSeconds();
// then
assertThat(actual).isEqualTo(1000);
}
@Test
@Parameters(method = "wrongMetricCollectorPeriodsProvider")
public void shouldSetDefaultValueWhenEnvCannotBeConvertedToLongORNegativeValue(String wrongValue) throws Exception {
// given
Mockito.doCallRealMethod().when(configuration).setCollectingMetricsPeriodInSeconds(anyLong());
Mockito.when(configuration.getCollectingMetricsPeriodInSeconds()).thenCallRealMethod();
long metricCollectorPeriod = -1L;
// when
withEnvironmentVariable(PrometheusConfiguration.COLLECTING_METRICS_PERIOD_IN_SECONDS, wrongValue)
.execute(() -> configuration.setCollectingMetricsPeriodInSeconds(metricCollectorPeriod));
long actual = configuration.getCollectingMetricsPeriodInSeconds();
// then
assertThat(actual).isEqualTo(PrometheusConfiguration.DEFAULT_COLLECTING_METRICS_PERIOD_IN_SECONDS);
}
@Test
public void shouldTakeDefaultValueWhenNothingConfigured() {
Mockito.doCallRealMethod().when(configuration).setCollectDiskUsageBasedOnEnvironmentVariableIfDefined();
Mockito.doCallRealMethod().when(configuration).getCollectDiskUsage();
// simulate constructor call
configuration.setCollectDiskUsageBasedOnEnvironmentVariableIfDefined();
assertThat(configuration.getCollectDiskUsage()).isFalse();
}
@Test
public void shouldTakeEnvironmentVariableWhenNothingConfigured() throws Exception {
Mockito.doCallRealMethod().when(configuration).setCollectDiskUsageBasedOnEnvironmentVariableIfDefined();
Mockito.doCallRealMethod().when(configuration).getCollectDiskUsage();
withEnvironmentVariable(PrometheusConfiguration.COLLECT_DISK_USAGE, "false")
.execute(() -> {
// simulate constructor call
configuration.setCollectDiskUsageBasedOnEnvironmentVariableIfDefined();
});
assertThat(configuration.getCollectDiskUsage()).isFalse();
}
@Test
public void shouldTakeDefaultIfEnvironmentVariableIsFaulty() throws Exception {
Mockito.doCallRealMethod().when(configuration).setCollectDiskUsageBasedOnEnvironmentVariableIfDefined();
Mockito.doCallRealMethod().when(configuration).getCollectDiskUsage();
withEnvironmentVariable(PrometheusConfiguration.COLLECT_DISK_USAGE, "not_true_not_false")
.execute(() -> {
// simulate constructor call
configuration.setCollectDiskUsageBasedOnEnvironmentVariableIfDefined();
});
assertThat(configuration.getCollectDiskUsage()).isFalse();
}
@Test
public void shouldTakeConfiguredValueIfEnvironmentVariableIsFaulty() throws Exception {
Mockito.doCallRealMethod().when(configuration).setCollectDiskUsageBasedOnEnvironmentVariableIfDefined();
Mockito.doCallRealMethod().when(configuration).getCollectDiskUsage();
Mockito.doCallRealMethod().when(configuration).setCollectDiskUsage(anyBoolean());
withEnvironmentVariable(PrometheusConfiguration.COLLECT_DISK_USAGE, "not_true_not_false")
.execute(() -> {
// simulate user clicked on checkbox
configuration.setCollectDiskUsage(true);
// simulate constructor call
configuration.setCollectDiskUsageBasedOnEnvironmentVariableIfDefined();
});
assertThat(configuration.getCollectDiskUsage()).isTrue();
}
@Test
public void shouldTakeConfiguredValueIfItIsConfigured() {
Mockito.doCallRealMethod().when(configuration).setCollectDiskUsage(any());
Mockito.doCallRealMethod().when(configuration).getCollectDiskUsage();
// simulate someone configured it over the UI
configuration.setCollectDiskUsage(false);
assertThat(configuration.getCollectDiskUsage()).isFalse();
// simulate constructor call
configuration.setCollectDiskUsageBasedOnEnvironmentVariableIfDefined();
assertThat(configuration.getCollectDiskUsage()).isFalse();
// simulate someone configured it over the UI
configuration.setCollectDiskUsage(true);
assertThat(configuration.getCollectDiskUsage()).isTrue();
// simulate constructor call
configuration.setCollectDiskUsageBasedOnEnvironmentVariableIfDefined();
assertThat(configuration.getCollectDiskUsage()).isTrue();
}
private JSONObject getDefaultConfig() {
JSONObject config = new JSONObject();
config.accumulate("path", "prometheus");
config.accumulate("useAuthenticatedEndpoint", "true");
config.accumulate("defaultNamespace", "default");
config.accumulate("jobAttributeName", "jenkins_job");
config.accumulate("countSuccessfulBuilds", "true");
config.accumulate("countUnstableBuilds", "true");
config.accumulate("countFailedBuilds", "true");
config.accumulate("countNotBuiltBuilds", "true");
config.accumulate("countAbortedBuilds", "true");
config.accumulate("fetchTestResults", "true");
config.accumulate("processingDisabledBuilds", "false");
config.accumulate("appendParamLabel", "false");
config.accumulate("appendStatusLabel", "false");
config.accumulate("labeledBuildParameterNames", "");
config.accumulate("collectDiskUsage", "true");
config.accumulate("collectNodeStatus", "true");
config.accumulate("perBuildMetrics", "false");
return config;
}
}
| true |
9e76006e1a405a4e04d3ef4ee4f2c1e42842dfeb | Java | Sknictik/NewsApp | /news/src/main/java/noveo/school/android/newsapp/activity/ReadNewsEntryActivity.java | UTF-8 | 11,677 | 2.078125 | 2 | [] | no_license | package noveo.school.android.newsapp.activity;
import android.app.ActionBar;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android_news.newsapp.R;
import noveo.school.android.newsapp.ApplicationState;
import noveo.school.android.newsapp.NewsUtils;
import noveo.school.android.newsapp.fragment.NewsEmptyFragment;
import noveo.school.android.newsapp.fragment.NewsEntryFragment;
import noveo.school.android.newsapp.retrofit.entities.FullNewsEntry;
import noveo.school.android.newsapp.retrofit.entities.ShortNewsEntry;
import noveo.school.android.newsapp.retrofit.service.RestClient;
/**
* Activity used to display full information about single news entry.
*/
// CR#1 (DONE) the same as MainActivity (move the key to class constant)
public class ReadNewsEntryActivity extends AbstractErrorDialogActivity {
public static final String ID_RESULT_KEY = "noveo.school.android.newsapp.ReadNewsEntryActivity.NEWS_ID_RESULT";
public static final String IS_FAVE_RESULT_KEY = "noveo.school.android.newsapp.ReadNewsEntryActivity.IS_FAVE_RESULT";
public static final String NEWS_TITLE_PARAM_KEY = "noveo.school.android.newsapp.ReadNewsEntryActivity.NEWS_TITLE_PARAM";
private static final String SAVED_IS_FAVE_KEY =
"noveo.school.android.newsapp.ReadNewsEntryActivity.SAVED_IS_FAVE";
public static final String NEWS_ENTRY_ID_PARAM_KEY =
"noveo.school.android.newsapp.ReadNewsEntryActivity.NEWS_ENTRY_ID_PARAM";
private static final String SAVED_IS_RESULT_SET_KEY =
"noveo.school.android.newsapp.ReadNewsEntryActivity.SAVED_IS_RESULT_SET";
public static final String NEWS_ENTRY_KEY = "noveo.school.android.newsapp.NewsTopicFragment.NEWS_ENTRY";
private static final Logger READ_NEWS_ENTRY_ACTIVITY_LOGGER = LoggerFactory.getLogger(ReadNewsEntryActivity.class);
//SavedInstanceState keys and values
private final Format timeFormat = new SimpleDateFormat("yyyy.MM.dd | HH:mm", new Locale("ru"));
private MenuItem faveBtn;
private ShortNewsEntry passedNewsEntryObj;
private FullNewsEntry newsEntryObj;
private boolean isFavourite;
private boolean isResultSet;
public static Intent createIntent(Context context, ShortNewsEntry shortNewsEntry) {
return new Intent(context, ReadNewsEntryActivity.class).putExtra(NEWS_ENTRY_KEY, shortNewsEntry);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_news_entry);
Intent intent = getIntent();
getActionBar().setDisplayHomeAsUpEnabled(true);
TextView dateTV = (TextView) findViewById(R.id.date_tv);
// CR#2 (DONE) I see the same code in another classes.
// Please do some utility class for colors
TypedArray colors = NewsUtils.getTypedArray(getResources(), R.array.newsHighlightColorsArray);
final int color = colors.getColor(ApplicationState.getCurrentTopic().ordinal(), 0);
colors.recycle();
dateTV.setTextColor(color);
passedNewsEntryObj = intent.getParcelableExtra(NEWS_ENTRY_KEY);
Date newsDate = passedNewsEntryObj.getPubDate();
String stringTime = timeFormat.format(newsDate);
dateTV.setText(stringTime);
TextView titleTV = (TextView) findViewById(R.id.title_tv);
titleTV.setText(passedNewsEntryObj.getTitle());
// Check whether we're restoring a previously destroyed instance
if (savedInstanceState == null) {
if (intent.getBooleanExtra(IS_FAVE_RESULT_KEY, passedNewsEntryObj.isFavourite())) {
isFavourite = true;
SharedPreferences mPrefs = getSharedPreferences(MainActivity.SHARED_PREFERENCE_NAME,
Context.MODE_PRIVATE);
Gson gson = new Gson();
FullNewsEntry newsEntry;
String jsonString = mPrefs.getString(passedNewsEntryObj.getId(), "");
try {
newsEntry = gson.fromJson(jsonString, FullNewsEntry.class);
} catch (JsonSyntaxException e) {
READ_NEWS_ENTRY_ACTIVITY_LOGGER.error("Unable to convert stored json string in object.", e);
setNewsEntryFragment();
return;
}
setNewsEntryFragment(newsEntry);
} else {
isFavourite = false;
setNewsEntryFragment();
}
} else {
isFavourite = savedInstanceState.getBoolean(SAVED_IS_FAVE_KEY);
//If result was already set and configuration change
// happened set result again as it is likely reset.
isResultSet = savedInstanceState.getBoolean(SAVED_IS_RESULT_SET_KEY);
this.setResult(RESULT_OK, intent);
}
}
@Override
public void onBackPressed() {
if (getErrorDialog() != null && getErrorDialog().isVisible()) {
getErrorDialog().dismiss();
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
ActionBar actionBar = getActionBar();
String mTitle = getResources().getStringArray(R.array.topics)[ApplicationState.getCurrentTopic().ordinal()];
actionBar.setTitle(mTitle);
getMenuInflater().inflate(R.menu.news_entry_menu, menu);
faveBtn = menu.findItem(R.id.fave_btn);
if (isFavourite) {
faveBtn.setIcon(R.drawable.ic_menu_star_checked);
faveBtn.setChecked(true);
} else {
faveBtn.setIcon(R.drawable.ic_menu_star_default);
faveBtn.setChecked(false);
}
TypedArray colors = NewsUtils.getTypedArray(getResources(), R.array.newsActionBarColorsArray);
int topicNum = ApplicationState.getCurrentTopic().ordinal();
final int color = colors.getColor(topicNum, 0);
colors.recycle();
actionBar.setBackgroundDrawable(new ColorDrawable(color));
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
final int displayOptions = getActionBar().getDisplayOptions();
if ((displayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) == 0) {
faveBtn.setVisible(true);
} else {
faveBtn.setVisible(false);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(SAVED_IS_FAVE_KEY, isFavourite);
savedInstanceState.putBoolean(SAVED_IS_RESULT_SET_KEY, isResultSet);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
return true;
} else if (id == R.id.fave_btn) {
if (newsEntryObj == null) {
return true;
}
SharedPreferences mPrefs = getSharedPreferences(MainActivity.SHARED_PREFERENCE_NAME,
MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Intent intent = getIntent();
if (item.isChecked()) {
item.setIcon(R.drawable.ic_menu_star_default);
item.setChecked(false);
prefsEditor.remove(newsEntryObj.getId());
intent.putExtra(IS_FAVE_RESULT_KEY, false);
READ_NEWS_ENTRY_ACTIVITY_LOGGER.trace("News object was marked for deletion");
isFavourite = false;
} else {
item.setIcon(R.drawable.ic_menu_star_checked);
item.setChecked(true);
Gson gson = new Gson();
String jsonObj = gson.toJson(newsEntryObj);
prefsEditor.putString(newsEntryObj.getId(), jsonObj);
intent.putExtra(IS_FAVE_RESULT_KEY, true);
READ_NEWS_ENTRY_ACTIVITY_LOGGER.trace("News object was marked for storage");
isFavourite = true;
}
intent.putExtra(ID_RESULT_KEY, newsEntryObj.getId());
this.setResult(RESULT_OK, intent);
isResultSet = true;
prefsEditor.apply();
return true;
}
return super.onOptionsItemSelected(item);
}
public void onLoadFinished(FullNewsEntry news) {
newsEntryObj = news;
restoreActionBar();
}
public void onLoadFailed(RestClient.Error reason) {
restoreActionBar();
showErrorDialog(reason);
setEmptyFragment();
}
public void onLoadStart() {
setActionBarLoading();
}
private void setEmptyFragment() {
FragmentManager fragmentManager = getFragmentManager();
NewsEmptyFragment mFragment = NewsEmptyFragment.newInstance(true);
fragmentManager.beginTransaction()
.replace(R.id.container, mFragment)
.commit();
}
private void setNewsEntryFragment() {
setNewsEntryFragment(null);
}
private void setNewsEntryFragment(FullNewsEntry newsEntry) {
FragmentManager fragmentManager = getFragmentManager();
NewsEntryFragment fragment = NewsEntryFragment.newInstance(newsEntry,
((TextView) findViewById(R.id.title_tv)).getText().toString(), passedNewsEntryObj.getId());
fragmentManager.beginTransaction()
.add(R.id.container, fragment).commit();
}
private void setActionBarLoading() {
ActionBar bar = getActionBar();
bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
bar.setCustomView(R.layout.actionbar_loading);
bar.setDisplayShowHomeEnabled(false);
if (faveBtn != null) {
faveBtn.setVisible(false);
invalidateOptionsMenu();
}
ProgressBar loadingBar = (ProgressBar) findViewById(R.id.loadingBar);
loadingBar.setVisibility(View.VISIBLE);
}
private void restoreActionBar() {
ActionBar bar = getActionBar();
bar.setDisplayHomeAsUpEnabled(true);
bar.setDisplayShowCustomEnabled(false);
bar.setDisplayShowHomeEnabled(true);
bar.setDisplayShowTitleEnabled(true);
bar.setDisplayUseLogoEnabled(true);
ProgressBar loadingBar = (ProgressBar) findViewById(R.id.loadingBar);
loadingBar.setVisibility(View.GONE);
if (faveBtn != null) {
faveBtn.setVisible(true);
invalidateOptionsMenu();
}
}
@Override
public void onRetryClick() {
getErrorDialog().dismiss();
setNewsEntryFragment();
}
}
| true |
843234199157dcc2a878dd536e37af046db80eb7 | Java | SE-Stuttgart/riot | /integration-tests/src/test/java/de/uni_stuttgart/riot/clientlibrary/thing/test/Fridge.java | UTF-8 | 13,143 | 2.125 | 2 | [
"WTFPL"
] | permissive | package de.uni_stuttgart.riot.clientlibrary.thing.test;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.databind.JsonNode;
import de.uni_stuttgart.riot.clientlibrary.NotFoundException;
import de.uni_stuttgart.riot.clientlibrary.RequestException;
import de.uni_stuttgart.riot.commons.rest.usermanagement.data.User;
import de.uni_stuttgart.riot.references.DelegatingReferenceResolver;
import de.uni_stuttgart.riot.references.Reference;
import de.uni_stuttgart.riot.references.ResolveReferenceException;
import de.uni_stuttgart.riot.references.StaticReference;
import de.uni_stuttgart.riot.thing.Action;
import de.uni_stuttgart.riot.thing.ActionInstance;
import de.uni_stuttgart.riot.thing.Event;
import de.uni_stuttgart.riot.thing.EventInstance;
import de.uni_stuttgart.riot.thing.Property;
import de.uni_stuttgart.riot.thing.Thing;
import de.uni_stuttgart.riot.thing.ThingBehavior;
import de.uni_stuttgart.riot.thing.ThingBehaviorFactory;
import de.uni_stuttgart.riot.thing.WritableProperty;
import de.uni_stuttgart.riot.thing.WritableReferenceProperty;
import de.uni_stuttgart.riot.thing.client.ExecutingThingBehavior;
import de.uni_stuttgart.riot.thing.client.ThingClient;
import de.uni_stuttgart.riot.thing.client.TypedExecutingThingBehavior;
/**
* A {@Thing} that represents a fridge. A fridge has a temperature that can only be read and a state. In addition, it has an action
* "eat" that can be executed with the name of a food. This action will always trigger the event "out of food" for the given food.
*/
public class Fridge extends Thing {
private final WritableProperty<Boolean> state = newWritableProperty("State", Boolean.class, false);
private final Property<Integer> temp = newProperty("Temp", Integer.class, 4);
private final Action<EatActionInstance> eatEverything = newAction("EatEverything", EatActionInstance.class);
private final Event<OutOfFoodEventInstance> outOfFood = newEvent("OutOfFood", OutOfFoodEventInstance.class);
private final WritableReferenceProperty<User> deliveryGuy = newWritableReferenceProperty("DeliveryGuy", User.class);
private final Event<FiredDeliveryGuyEventInstance> firedDeliveryGuy = newEvent("firedDeliveryGuy", FiredDeliveryGuyEventInstance.class);
private final Action<HireDeliveryGuyActionInstance> hireDeliveryGuy = newAction("hireDeliveryGuy", HireDeliveryGuyActionInstance.class);
/**
* Creates a new fridge.
*
* @param behavior
* The behavior of the fridge. For testing purposes, just use {@link FridgeBehavior}.
*/
public Fridge(ThingBehavior behavior) {
super(behavior);
}
public boolean getState() {
return state.get();
}
public void setState(boolean state) {
this.state.set(state);
}
public WritableProperty<Boolean> getStateProperty() {
return state;
}
public int getTemp() {
return temp.get();
}
public Property<Integer> getTempProperty() {
return temp;
}
public Action<EatActionInstance> getEatEverythingAction() {
return eatEverything;
}
public void eatEverythingOf(String food) {
eatEverything.fire(new EatActionInstance(eatEverything, food));
}
public Event<OutOfFoodEventInstance> getOutOfFoodEvent() {
return outOfFood;
}
public User getDeliveryGuy() throws ResolveReferenceException {
return deliveryGuy.getTarget();
}
public void setDeliveryGuy(User newGuy) {
deliveryGuy.setTarget(newGuy);
}
public Long getDeliveryGuyId() {
return deliveryGuy.get();
}
public void setDeliveryGuyId(Long newId) {
deliveryGuy.set(newId);
}
public WritableReferenceProperty<User> getDeliveryGuyProperty() {
return deliveryGuy;
}
public Event<FiredDeliveryGuyEventInstance> getFiredDeliveryGuyEvent() {
return firedDeliveryGuy;
}
public void hireDeliveryGuy(User newGuy) {
hireDeliveryGuy.fire(new HireDeliveryGuyActionInstance(hireDeliveryGuy, newGuy));
}
public Action<HireDeliveryGuyActionInstance> getHireDeliveryGuyAction() {
return hireDeliveryGuy;
}
/**
* Creates a new fridge for testing purposes.
*
* @param client
* The ThingClient to communicate with the server.
* @param name
* The name of the fridge.
* @return The behavior of the fridge. Call {@link FridgeBehavior#getFridge()} to get the fridge.
* @throws RequestException
* When registering the thing with the server failed.
* @throws IOException
* When a network error occured.
*/
public static FridgeBehavior create(ThingClient client, String name) throws RequestException, IOException {
@SuppressWarnings("unchecked")
ThingBehaviorFactory<FridgeBehavior> behaviorFactory = mock(ThingBehaviorFactory.class);
when(behaviorFactory.newBehavior(any())).thenReturn(new FridgeBehavior(client));
return ExecutingThingBehavior.launchNewThing(Fridge.class, client, name, behaviorFactory);
}
/**
* A behavior for using the fridge as a standalone thing in tests. Note that this behavior would usually be a runnable behavior. For the
* purpose of testing, however, the {@link #fetchUpdates()} method should be called manually.
*/
public static class FridgeBehavior extends TypedExecutingThingBehavior<Fridge> {
/**
* Creates a new FridgeBehavior.
*
* @param thingClient
* The client that handles the REST operations
*/
public FridgeBehavior(ThingClient thingClient) {
super(thingClient, Fridge.class);
}
public void simulateTemperatureChange(int newTemperature) {
changePropertyValue(getThing().temp, newTemperature);
}
@Override
protected void fetchUpdates() throws IOException, NotFoundException {
super.fetchUpdates();
}
@Override
protected <A extends ActionInstance> void executeAction(Action<A> action, A actionInstance) {
// The ExecutingThingBehavior will take care of the PropertySetActions for us.
if (actionInstance instanceof EatActionInstance && action == getThing().eatEverything) {
// After eating everything, there is nothing left:
executeEvent(new OutOfFoodEventInstance(getThing().outOfFood, ((EatActionInstance) actionInstance).getFood()));
} else if (actionInstance instanceof HireDeliveryGuyActionInstance && action == getThing().hireDeliveryGuy) {
try {
User newGuy = resolve(((HireDeliveryGuyActionInstance) actionInstance).getNewGuy(), User.class);
// First fire the old guy, if necessary
if (getThing().getDeliveryGuy() != null) {
String reason = getThing().getDeliveryGuy().getUsername() + " was too slow, we now hired " + newGuy.getUsername();
executeEvent(new FiredDeliveryGuyEventInstance(getThing().firedDeliveryGuy, getThing().getDeliveryGuy(), reason));
}
// Then put in the new guy.
getThing().getDeliveryGuyProperty().setTarget(newGuy);
} catch (ResolveReferenceException e) {
// Ignore
}
}
}
@Override
protected DelegatingReferenceResolver getDelegatingResolver() {
return super.getDelegatingResolver();
}
}
/**
* A eat action that represents the eating of food - usually as long until there is nothing left.
*/
public static class EatActionInstance extends ActionInstance {
private final String food;
/**
* Instantiates a new action instance. The time is set to now.
*
* @param action
* The action that was fired.
* @param food
* The food that was eaten.
*/
public EatActionInstance(Action<? extends ActionInstance> action, String food) {
super(action);
this.food = food;
}
/**
* Creates a new instance from JSON.
*
* @param node
* The JSON node.
*/
@JsonCreator
public EatActionInstance(JsonNode node) {
super(node);
this.food = node.get("food").asText();
}
/**
* Gets the food that was eaten during this action.
*
* @return The food.
*/
public String getFood() {
return food;
}
}
/**
* An event that is raised when the fridge runs out of a particular type of food. This is especially the case after the food has been
* eaten {@link EatActionInstance}.
*/
public static class OutOfFoodEventInstance extends EventInstance {
private final String food;
/**
* Instantiates a new event instance. The time is set to now.
*
* @param event
* The event that was fired.
* @param food
* The food that we ran out of.
*/
public OutOfFoodEventInstance(Event<? extends EventInstance> event, String food) {
super(event);
this.food = food;
}
/**
* Creates a new instance from JSON.
*
* @param node
* The JSON node.
*/
@JsonCreator
public OutOfFoodEventInstance(JsonNode node) {
super(node);
this.food = node.get("food").asText();
}
/**
* Gets the food that we ran out of.
*
* @return The food.
*/
public String getFood() {
return food;
}
}
/**
* An event that is raised when a delivery guy for the fridge was fired, probably because he didn't do a good job. In particular, those
* guys get fired when a {@link HireDeliveryGuyActionInstance} is executed.
*/
public static class FiredDeliveryGuyEventInstance extends EventInstance {
private final Reference<User> poorGuy;
private final String reason;
/**
* Instantiates a new event instance. The time is set to now.
*
* @param event
* The event that was fired.
* @param poorGuy
* The poor guy who was fired.
* @param reason
* The reason for firing him.
*/
public FiredDeliveryGuyEventInstance(Event<? extends EventInstance> event, User poorGuy, String reason) {
super(event);
this.poorGuy = StaticReference.create(poorGuy);
this.reason = reason;
}
/**
* Creates a new instance from JSON.
*
* @param node
* The JSON node.
*/
@JsonCreator
public FiredDeliveryGuyEventInstance(JsonNode node) {
super(node);
this.poorGuy = StaticReference.create(node.get("poorGuy"));
this.reason = node.get("reason").asText();
}
/**
* Gets the poor guy who was fired.
*
* @return The old delivery guy.
*/
public Reference<User> getPoorGuy() {
return poorGuy;
}
/**
* Gets the reason for firing the guy.
*
* @return The reason.
*/
public String getReason() {
return reason;
}
}
/**
* An action that will fire the old delivery guy and employ the new one.
*/
public static class HireDeliveryGuyActionInstance extends ActionInstance {
private final Reference<User> newGuy;
/**
* Instantiates a new action instance. The time is set to now.
*
* @param action
* The action that is being fired.
* @param newGuy
* The new delivery guy (we will just fire the old one).
*/
public HireDeliveryGuyActionInstance(Action<? extends ActionInstance> action, User newGuy) {
super(action);
this.newGuy = StaticReference.create(newGuy);
}
/**
* Creates a new instance from JSON.
*
* @param node
* The JSON node.
*/
@JsonCreator
public HireDeliveryGuyActionInstance(JsonNode node) {
super(node);
this.newGuy = StaticReference.create(node.get("newGuy"));
}
/**
* Gets the new delivery guy.
*
* @return The new guy.
*/
public Reference<User> getNewGuy() {
return newGuy;
}
}
}
| true |
74787b524584e30f7a5eb0f7ef2a9bf6a755a961 | Java | Minghou-Lei/A-simple-example-for-getting-started-with-Spring-MVC-and-Hibernate | /src/BookStore/controller/LoginController.java | UTF-8 | 1,199 | 2.25 | 2 | [] | no_license | package BookStore.controller;
import BookStore.service.impl.BookStoreServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@RequestMapping("/login")
public ModelAndView login(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session,
HttpServletRequest request,
HttpServletResponse response) {
ModelAndView mv = new ModelAndView();
try {
BookStoreServiceImpl service = new BookStoreServiceImpl(username, password);
mv.setViewName("bookstore");
//Session传值
session.setAttribute("bssi",service);
return mv;
} catch (Exception e) {
mv.setViewName("index");
mv.addObject("errorMessage","登录错误!<br>"+ e.toString());
}
return mv;
}
}
| true |
396f6a1d3a47d29f5422ca2bf918608e448e6468 | Java | projectnessie/nessie | /api/client/src/main/java/org/projectnessie/client/builder/BaseGetEntriesBuilder.java | UTF-8 | 3,415 | 1.90625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2022 Dremio
*
* 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.projectnessie.client.builder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Stream;
import org.projectnessie.client.api.GetEntriesBuilder;
import org.projectnessie.error.NessieNotFoundException;
import org.projectnessie.model.ContentKey;
import org.projectnessie.model.EntriesResponse;
import org.projectnessie.model.EntriesResponse.Entry;
public abstract class BaseGetEntriesBuilder<PARAMS>
extends BaseOnReferenceBuilder<GetEntriesBuilder> implements GetEntriesBuilder {
private final BiFunction<PARAMS, String, PARAMS> paramsForPage;
private String pageToken;
protected Integer maxRecords;
protected final List<ContentKey> keys = new ArrayList<>();
protected ContentKey minKey;
protected ContentKey maxKey;
protected ContentKey prefixKey;
protected String filter;
protected Integer namespaceDepth;
protected boolean withContent;
protected BaseGetEntriesBuilder(BiFunction<PARAMS, String, PARAMS> paramsForPage) {
this.paramsForPage = paramsForPage;
}
@Override
public GetEntriesBuilder maxRecords(int maxRecords) {
this.maxRecords = maxRecords;
return this;
}
@Override
public GetEntriesBuilder pageToken(String pageToken) {
this.pageToken = pageToken;
return this;
}
@Override
public GetEntriesBuilder key(ContentKey key) {
this.keys.add(key);
return this;
}
@Override
public GetEntriesBuilder keys(Collection<ContentKey> keys) {
this.keys.addAll(keys);
return this;
}
@Override
public GetEntriesBuilder minKey(ContentKey minKey) {
this.minKey = minKey;
return this;
}
@Override
public GetEntriesBuilder maxKey(ContentKey maxKey) {
this.maxKey = maxKey;
return this;
}
@Override
public GetEntriesBuilder prefixKey(ContentKey prefixKey) {
this.prefixKey = prefixKey;
return this;
}
@Override
public GetEntriesBuilder filter(String filter) {
this.filter = filter;
return this;
}
@Override
public GetEntriesBuilder namespaceDepth(Integer namespaceDepth) {
this.namespaceDepth = namespaceDepth;
return this;
}
@Override
public GetEntriesBuilder withContent(boolean withContent) {
this.withContent = withContent;
return this;
}
protected abstract PARAMS params();
protected abstract EntriesResponse get(PARAMS p) throws NessieNotFoundException;
@Override
public EntriesResponse get() throws NessieNotFoundException {
return get(paramsForPage.apply(params(), pageToken));
}
@Override
public Stream<Entry> stream() throws NessieNotFoundException {
PARAMS p = params();
return StreamingUtil.generateStream(
EntriesResponse::getEntries, pageToken -> get(paramsForPage.apply(p, pageToken)));
}
}
| true |
3816dce716a10c39e29fed29b8d196ad4b817949 | Java | yxm785872911/learngit | /offer/Offer18DeleteNode.java | UTF-8 | 1,091 | 3.84375 | 4 | [] | no_license | package com.yxm.offer;
import com.yxm.leetcode.ListNode;
public class Offer18DeleteNode {
public static void main(String[] args) {
}
/**
* 删除一个链表中指定节点的两种方式:
* 一:从头开始遍历节点
* 二:将指定节点的下一个节点的值替换当前节点的值,并更新节点的指针。(前提是指定的链表中一定包含该节点)
* 需要考虑的情况有:
* 头结点为null的时候直接返回null;
* 只有一个节点并且该节点的值等于要删除的节点的值,那么也应该返回null
* 给定节点是尾节点的时候需要从头开始遍历。
* @param head
* @param node
*/
public static void deleteNode(ListNode head,ListNode node){
if (head==null||(head.next==null&&node==head)) {
head = null;
return;
}
if (node.next!=null) {
ListNode tmp = node.next;
node.val = node.next.val;
node.next = node.next.next;
tmp.next = null;
}else{
ListNode tmp = head;
while (tmp.next!=node) {
tmp = tmp.next;
}
tmp.next = null;
}
}
}
| true |
2399336f48fc79dc334e4595044cb110f2cd232e | Java | DequocNga/App_SQLite_Demo_3_Update | /app/src/main/java/com/russia/app_sqlite_demo_3/main/MainActivity.java | UTF-8 | 3,829 | 2.34375 | 2 | [] | no_license | package com.russia.app_sqlite_demo_3.main;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.russia.app_sqlite_demo_3.R;
import com.russia.app_sqlite_demo_3.adapter.CustomAdapter;
import com.russia.app_sqlite_demo_3.database.DBManager;
import com.russia.app_sqlite_demo_3.model.Student;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText editTextName;
EditText editTextPhone;
EditText editTextEmail;
EditText editTextAddress;
Button buttonSave;
Button buttonUpdate;
ListView listViewShow;
DBManager dbManager = new DBManager(this);
CustomAdapter customAdapter;
ArrayList<Student> studentArrayList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectView();
/*load data from database*/
studentArrayList = dbManager.getAllStudent();
setAdapter();
buttonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Student student = createStudent();
if (student != null) {
dbManager.addStudent(student);
}
updateListStudent();
setAdapter();
}
});
buttonUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
listViewShow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
listViewShow.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
return false;
}
});
}
private void updateListStudent() {
studentArrayList.clear();
studentArrayList.addAll(dbManager.getAllStudent());
if(customAdapter != null){
customAdapter.notifyDataSetChanged();
}
}
private Student createStudent() {
String name = editTextName.getText().toString().trim();
String phone = editTextPhone.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
Student student = new Student(name, phone, email, address);
return student;
}
private void setAdapter() {
if (customAdapter == null) {
customAdapter = new CustomAdapter(this, R.layout.item_list_student, studentArrayList);
listViewShow.setAdapter(customAdapter);
} else {
customAdapter.notifyDataSetChanged();
/*vi bo dem bat dau tu vi tri thu 0 nen ta se phai giam vi tri di 1 don vi, moi dung vi tri
* dang chon hien tai tren man hinh*/
listViewShow.setSelection(customAdapter.getCount() - 1);
}
}
private void connectView() {
editTextName = findViewById(R.id.edt_name);
editTextPhone = findViewById(R.id.edt_telephone);
editTextEmail = findViewById(R.id.edt_email);
editTextAddress = findViewById(R.id.edt_address);
buttonSave = findViewById(R.id.btn_save);
buttonUpdate = findViewById(R.id.btn_update);
listViewShow = findViewById(R.id.lv_showList);
}
}
| true |
f609d067df8fcc202b669f7d1e101c8a10f2d657 | Java | alex-sakharov/ShellGame | /app/src/main/java/com/example/lexa/shellgame/MainActivity.java | UTF-8 | 4,075 | 2.78125 | 3 | [] | no_license | package com.example.lexa.shellgame;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends Activity {
private ArrayList<Shell> mShells = new ArrayList<Shell>(3);
private Button buttonNewGame;
private boolean mGameOver;
private final String GAME_OVER = "GAME_OVER";
private ImageView shellView;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mShells.add(new Shell(R.id.shell1));
mShells.add(new Shell(R.id.shell2));
mShells.add(new Shell(R.id.shell3));
buttonNewGame = findViewById(R.id.buttonNewGame);
buttonNewGame.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newGame();
}
});
if (savedInstanceState != null) {
for (Shell shell : mShells) {
shell.loadState(savedInstanceState);
}
mGameOver = savedInstanceState.getBoolean(GAME_OVER);
if (mGameOver) {
buttonNewGame.setVisibility(View.VISIBLE);
}
else {
buttonNewGame.setVisibility(View.INVISIBLE);
}
}
else {
newGame();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
for (Shell shell : mShells) {
shell.saveState(outState);
}
outState.putBoolean(GAME_OVER, mGameOver);
}
private void newGame() {
Random random = new Random();
int luckyShellNumber = random.nextInt(2);
for (int i = 0; i < mShells.size(); i++) {
if (i == luckyShellNumber) {
mShells.get(i).reset(true);
}
else {
mShells.get(i).reset(false);
}
}
mGameOver = false;
buttonNewGame.setVisibility(View.INVISIBLE);
}
private class Shell implements View.OnClickListener {
private final int CLOSED = 0, OPEN = 1, OPEN_AND_HAS_BALL = 2;
private ImageView mView;
private final String LEVEL = "STATE";
private final String HAS_BALL = "HAS_BALL";
private boolean mHasBall;
public void reset(boolean hasBall) {
this.mHasBall = hasBall;
mView.getDrawable().setLevel(CLOSED);
}
public Shell (int id) {
mView = MainActivity.this.findViewById(id);
mView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (mGameOver) return;
Drawable d = ((ImageView) v).getDrawable();
if (d.getLevel() == CLOSED) {
if (mHasBall) {
d.setLevel(OPEN_AND_HAS_BALL);
Toast.makeText(getApplicationContext(), R.string.you_have_won, Toast.LENGTH_LONG).show();
}
else {
d.setLevel(OPEN);
Toast.makeText(getApplicationContext(), R.string.you_loose, Toast.LENGTH_LONG).show();
}
mGameOver = true;
buttonNewGame.setVisibility(View.VISIBLE);
}
}
public void loadState( final Bundle state) {
((ImageView) mView).getDrawable().setLevel(state.getInt(LEVEL + mView.getId()));
mHasBall = state.getBoolean(HAS_BALL + mView.getId());
}
public void saveState( final Bundle state) {
state.putInt(LEVEL + mView.getId(), ((ImageView) mView).getDrawable().getLevel());
state.putBoolean(HAS_BALL + mView.getId(), mHasBall);
}
}
}
| true |
212098db0ac4dfdc0f8fad186641ec678a9b3842 | Java | vigneshnbmedia/task | /app/src/main/java/com/android/task2/di/ActivityBuilder.java | UTF-8 | 465 | 1.835938 | 2 | [
"MIT"
] | permissive | package com.android.task2.di;
import com.android.task2.ui.main.MainActivity;
import com.android.task2.ui.main.MainActivityModule;
import com.android.task2.ui.pages.PageProvider;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
@Module
public abstract class ActivityBuilder {
@ContributesAndroidInjector(modules = {
MainActivityModule.class,PageProvider.class
})
abstract MainActivity bindMainActivity();
}
| true |
40669dbe48cc340b6fd80258e3e4f49e2b00c807 | Java | rauljose32/consumindoJson | /app/src/main/java/com/example/json_01/MainActivity.java | UTF-8 | 3,620 | 2.359375 | 2 | [
"MIT"
] | permissive | /*https://stackoverflow.com/questions/58889465/json-parsing-error-value-jsonstr-of-type-java-lang-string-cannot-be-converted-t*/
package com.example.json_01;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.example.json_01.util.Auxiliar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView lv;
private static final String URL = "https://api.androidhive.info/contacts/";
private List<HashMap<String, String>> listacontatos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listacontatos = new ArrayList();
lv = findViewById(R.id.listView);
ObtencaoDeContatos odc = new ObtencaoDeContatos();
odc.execute();
}//onCreate
private class ObtencaoDeContatos extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "Download JSON", Toast.LENGTH_SHORT).show();
}//method
@Override
protected Void doInBackground(Void... voids) {
Auxiliar aux = new Auxiliar();
String jsonString = aux.conectar(URL);
if (jsonString != null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("contacts");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String cod = c.getString("id");
String nome = c.getString("name");
String email = c.getString("email");
String endereco = c.getString("address");
String genero = c.getString("gender");
JSONObject fone = c.getJSONObject("phone");
String movel = fone.getString("mobile");
String casa = fone.getString("home");
String trabalho = fone.getString("office");
HashMap<String, String> contatos = new HashMap<>();
contatos.put("nome", nome);
contatos.put("email", email);
contatos.put("endereco", endereco);
contatos.put("movel", movel);
listacontatos.add(contatos);
}//for
} catch (JSONException e) {
e.printStackTrace();
}
}//if
return null;
}//method
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
listacontatos,
R.layout.item_list,
new String[]{"nome", "email", "endereco", "movel"},
new int[]{R.id.textViewNome, R.id.textViewEmail, R.id.textViewEndereco, R.id.textViewMovel});
lv.setAdapter(adapter);
}
}//innerClass
}//class
| true |
d6d09e741ccc14f3d1c5240fefa31b69335bb2c0 | Java | weichk/yiji-sdk | /openapi-sdk-message/src/main/java/com/yiji/openapi/message/common/register/PpmRedirectRegisterResponse.java | UTF-8 | 669 | 1.710938 | 2 | [] | no_license | package com.yiji.openapi.message.common.register;
import com.yiji.openapi.sdk.common.annotation.OpenApiField;
import com.yiji.openapi.sdk.common.annotation.OpenApiMessage;
import com.yiji.openapi.sdk.common.enums.ApiMessageType;
import com.yiji.openapi.sdk.common.message.ApiResponse;
/**
* Created by Jason Ma on 2015/3/30.
*/
@Deprecated
@OpenApiMessage(service = "ppmRedirectRegister", type = ApiMessageType.Response)
public class PpmRedirectRegisterResponse extends ApiResponse {
@OpenApiField(desc = "gid")
private String gid;
public String getGid() {
return gid;
}
public void setGid(String gid) {
this.gid = gid;
}
}
| true |
01950f7bd433d12ba396a1bb1946000430604aaf | Java | zyl0501/common-controller | /common/src/main/java/com/ray/common/api/JsonResult.java | UTF-8 | 1,858 | 2.5625 | 3 | [] | no_license | package com.ray.common.api;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonResult<T> implements ApiResult<T> {
protected int code;
protected String msg;
protected T data;
protected boolean success = false;
public JsonResult(IErrorCode errorCode) {
this.code = errorCode.getCode();
this.msg = errorCode.getMsg();
}
public JsonResult() {
}
public JsonResult(T data) {
this.code = 200;
this.data = data;
this.success = true;
}
public JsonResult(int code, String msg) {
this.code = code;
this.msg = msg;
}
public JsonResult(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
this.success = true;
}
@Override
public int code() {
return code;
}
@Override
public T data() {
return data;
}
@Override
public String msg() {
return msg;
}
@Override
public boolean success() {
return success;
}
public void setCode(int code) {
this.code = code;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
JSONObject json = new JSONObject();
try {
json.put("code", code);
json.put("msg", msg);
json.put("data", data);
json.put("success", success);
} catch (JSONException e) {
}
return json.toString();
}
public static <T> ApiResult<T> failure(int code, String msg) {
return new JsonResult<>(code, msg);
}
public static <T> ApiResult<T> failure(IErrorCode errorCode) {
return new JsonResult<>(errorCode);
}
}
| true |
a979b80679194ed4786b88142fd6190f98942a6c | Java | iju1633/eclipse | /hello/src/ch3class/Ex3Mini.java | UHC | 687 | 3.859375 | 4 | [] | no_license | package ch3class;
import java.util.*;
public class Ex3Mini {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choice;
int answer = (int) (Math.random() * 100); // Math.random() * 100 ̰ſ ȣ ϸ Math.random()̰ int Ǵϱ ׳ 0. Լ 0!
int i = 0;
do {
System.out.print(" Ͽÿ: ");
choice = sc.nextInt();
if (choice > answer) {
System.out.println("LOW");
} else if (choice < answer) {
System.out.println("HIGH");
}
i++;
} while (choice != answer);
System.out.println("մϴ. õȽ=" + i);
}
}
| true |