text
stringlengths 10
2.72M
|
|---|
package com.heartmarket.model.dto.response;
import java.util.List;
import com.heartmarket.model.dto.Trade;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class MySellList {
// 거래 리스트
Trade sTrade;
// 거래 완료 여부
int complete;
}
|
package cn.edu.zucc.music.entity;
import org.neo4j.ogm.annotation.*;
import java.io.Serializable;
import java.util.List;
@NodeEntity(label = "artist")
public class ArtistEntityItem implements Serializable {
@Id
@GeneratedValue
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Property(name = "artistName")
private String artistName;
@Property(name = "artistId")
private String artistId;
@Property(name = "musicSize")
private String musicSize;
@Property(name = "albumSize")
private String albumSize;
@Relationship(type = "art_to_alb",direction = Relationship.OUTGOING)
private List<AlbumEntityItem> albumEntityItemList;
public List<AlbumEntityItem> getAlbumEntityItemList() {
return albumEntityItemList;
}
public void setAlbumEntityItemList(List<AlbumEntityItem> albumEntityItemList) {
this.albumEntityItemList = albumEntityItemList;
}
public String getArtistId() {
return artistId;
}
public void setArtistId(String artistId) {
this.artistId = artistId;
}
public String getMusicSize() {
return musicSize;
}
public void setMusicSize(String musicSize) {
this.musicSize = musicSize;
}
public String getAlbumSize() {
return albumSize;
}
public void setAlbumSize(String albumSize) {
this.albumSize = albumSize;
}
public String getArtistName() {
return artistName;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
}
|
import java.util.Scanner;
/**
* Created by jason chou on 2016/11/17.
*/
public class classwork {
public static void main(String[] args) {
int age;
Scanner scanner = new Scanner(System.in);
System.out.print("enter your age");
age = scanner.nextInt();
if(age>18){
System.out.print("welcome");
}else{
System.out.print("Access denied");
}
}
}
|
package com.prashanth.sunvalley.Model;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
@Data
public class FeeDTO {
private Long id;
private BigDecimal tuitionFee;
private BigDecimal bookFee;
private BigDecimal uniformFee;
private BigDecimal transportFee;
private BigDecimal oldBalance;
private List<PaymentDTO> payments;
private List<MiscFeeDTO> miscFee;
}
|
package com.ctac.jpmc.game.conway;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import com.ctac.jpmc.game.ICoordinates;
public class Coordinates3DTest {
@Test
public void testGetValues() {
ICoordinates c = new Coordinates3D (33,57,81);
int [] values = c.getValues();
assertEquals("size", 3, values.length);
assertEquals("Equals x", 33, values[0]);
assertEquals("Equals y", 57, values[1]);
assertEquals("Equals y", 81, values[2]);
}
@Test
public void testEquals() {
ICoordinates a = new Coordinates3D (33,57,81);
ICoordinates b = new Coordinates3D (33,57,81);
assertEquals("Equals", a, b);
}
@Test
public void testNotEquals() {
ICoordinates a = new Coordinates3D (33,57,81);
ICoordinates b = new Coordinates3D (57,33,81);
assertNotEquals("Not Equals", a, b);
ICoordinates c = new Coordinates3D (33,57,88);
assertNotEquals("Not Equals", a, c);
}
@Test
public void testSet() {
Set <ICoordinates> set = new HashSet <ICoordinates> ();
ICoordinates a = new Coordinates3D (2,2,0);
set.add(a);
ICoordinates b = new Coordinates3D (0,1,0);
set.add( b);
ICoordinates c = new Coordinates3D (2,2,0);
set.add( c);
set.add( a);
assertEquals("set size", 2, set.size());
}
}
|
package com.tencent.mm.plugin.appbrand.q;
import android.support.v4.e.a;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public final class g<K, V> {
private final Map<K, Set<V>> gBs = new a();
public final void o(K k, V v) {
if (k != null) {
Set l = l(k, true);
synchronized (l) {
l.add(v);
}
}
}
private Set<V> l(K k, boolean z) {
Set<V> set;
synchronized (this.gBs) {
set = (Set) this.gBs.get(k);
if (set == null && z) {
set = new HashSet();
this.gBs.put(k, set);
}
}
return set;
}
public final Set<V> bo(K k) {
if (k == null) {
return null;
}
Collection l = l(k, false);
if (l == null) {
return Collections.emptySet();
}
Set<V> hashSet = new HashSet();
synchronized (l) {
hashSet.addAll(l);
}
return hashSet;
}
public final Set<V> bp(K k) {
if (k == null) {
return null;
}
Set<V> set;
synchronized (this.gBs) {
set = (Set) this.gBs.remove(k);
}
return set;
}
}
|
package com.szcinda.express.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.List;
public interface ClientRepository extends JpaRepository<Client,String> {
Client findFirstById(String id);
List<Client> findByNameIn(Collection<String> names);
@Modifying
@Transactional
@Query("delete from Client where id = ?1")
void deleteById(String id);
}
|
package BinTree.OJExer;
import java.util.LinkedList;
import java.util.Queue;
public class isSubTree {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public boolean isSubtree(TreeNode s, TreeNode t) {
if (isSameTree(s,t)){
return true;
}
if (s!=null){
if (isSubtree(s.left,t)){
return true;
}else if (isSubtree(s.right,t)){
return true;
}
}
return false;
}
private boolean isSameTree(TreeNode p,TreeNode q){
if (p == null && q == null){
return true;
}
if (p != null && q != null && p.val == q.val){
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}
return false;
}
}
|
package win.yulongsun.a01storage;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import win.yulongsun.a01storage.file.FileStorageActivity;
import win.yulongsun.a01storage.realm.RealmActivity;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView mListView;
private String[] mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listview);
mData = new String[]{"文件存储", "Realm"};
mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, mData));
mListView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = null;
Log.d("MainActivity", "onItemClick: " + i);
switch (i) {
case 0:
intent = new Intent(this, FileStorageActivity.class);
break;
case 1:
intent = new Intent(this, RealmActivity.class);
break;
}
if (intent != null) {
startActivity(intent);
}
}
}
|
package com.sfa.vo;
public class AffirmationVo {
private Long no;
private String content;
public Long getNo() {
return no;
}
public void setNo(Long no) {
this.no = no;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "AffirmationVo [no=" + no + ", content=" + content + "]";
}
}
|
package hdfs.server;
import java.io.Serializable;
import hdfs.FileDescriptionI;
public interface FileDataI extends Serializable, Iterable<Integer> {
FileDescriptionI getFile();
int getNumberDaemons();
void addDaemon(int daemon);
int getNumberFragments();
void setNumberFragments(int numberFragments);
void clear();
}
|
package org.usfirst.frc.team1155.robot.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc.team1155.robot.Robot;
import org.usfirst.frc.team1155.robot.subsystems.DriveSubsystem.SensorMode;
class DistanceDriveCommand extends Command {
private double distanceToDrive;
//distance in inches
protected DistanceDriveCommand(double distance) {
requires(Robot.driveSubsystem);
distanceToDrive = distance;
}
// Called just before this Command runs the first time
protected void initialize() {
Robot.driveSubsystem.resetEncoders();
Robot.driveSubsystem.sensorMode = SensorMode.ENCODER;
Robot.driveSubsystem.startAdjustment(Robot.driveSubsystem.getEncDistance(), distanceToDrive);
Robot.driveSubsystem.getPIDController().setPID(1 , 0, 0.1);
Robot.driveSubsystem.getPIDController().setAbsoluteTolerance(2);
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
System.out.println(Robot.driveSubsystem.getEncDistance());
return Robot.driveSubsystem.getPIDController().onTarget();
}
// Called once after isFinished returns true
protected void end() {
System.out.println("Finished");
Robot.driveSubsystem.endAdjustment();
Robot.driveSubsystem.setTankSpeed(0, 0);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
end();
}
}
|
package com.wat.exception;
public class Personnes {
private String nom;
private String prenom;
private int age;
public static final int NbreMaxOreil = 2;
public static int nbreTotalDePersonne;
public Personnes() {
}
public Personnes(String nom,String prenom,int age) {
this.nom=nom;
this.prenom=prenom;
this.age=age;
nbreTotalDePersonne++;
}
public Personnes(String nom,String prenom) {
this.nom=nom;
this.prenom=prenom;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
if(age<16) {
throw new IllegalArgumentException("l'age doit etre supperieur a 16 ans");
}else
System.out.println("l'age est :"+ age);
}
public static int getNbremaxoreil() {
return NbreMaxOreil;
}
}
|
package com.techlab.accountproxy;
import com.techlab.account.proxy.test.AccountProxy;
public class AccountProxyTest {
public static void main(String[] args) {
AccountProxy proxy = new AccountProxy("SBI100", "Sonam", 500);
proxy.deposit(100);
System.out.println(proxy.getBalance());
}
}
|
package org.ddth.blogging.yahoo.grabber;
import org.ddth.blogging.Author;
import org.ddth.blogging.yahoo.YahooBlogAPI;
import org.ddth.dinoage.core.ProfileGrabberSession;
import org.ddth.http.core.connection.Request;
import org.ddth.http.core.content.Content;
public class YProfileGrabberSession extends ProfileGrabberSession {
private Author author;
public YProfileGrabberSession() {
super(YahooBlogAPI.YAHOO_360_PROFILE_CONTENT_DISPATCHER);
}
public Author getAuthor() {
return author;
}
@Override
protected void handle(Request request, Content<?> content) {
author = ((YAuthorContent)content).getAuthor();
}
}
|
/*
* Copyright (C) 2014 - 2015 Marko Salmela, http://fuusio.org
*
* 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.fuusio.api.util;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.SmallTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class TupleTest {
private static final double DOUBLE_VALUE_1 = 1.2345678;
private static final double DOUBLE_VALUE_2 = 2.3456789;
private Tuple<Double> mTuple;
@Before
public void beforeTests() {
mTuple = new Tuple<>(DOUBLE_VALUE_1, DOUBLE_VALUE_2);
}
@After
public void afterTests() {
}
@Test
public void testGetValue1() {
mTuple.setValue1(DOUBLE_VALUE_1);
assertEquals(DOUBLE_VALUE_1, mTuple.getValue1(), 0);
}
@Test
public void testSetValue1() {
mTuple.setValue1(DOUBLE_VALUE_2);
assertEquals(DOUBLE_VALUE_2, mTuple.getValue1(), 0);
}
@Test
public void testGetValue2() {
mTuple.setValue2(DOUBLE_VALUE_1);
assertEquals(DOUBLE_VALUE_1, mTuple.getValue2(), 0);
}
@Test
public void testSetValue2() {
mTuple.setValue2(DOUBLE_VALUE_2);
assertEquals(DOUBLE_VALUE_2, mTuple.getValue2(), 0);
}
}
|
package student_record.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import student_records.entity.Student;
import student_records.entity.StudentDto;
public class StudentRecordDao {
private String query1 = "";
private String query2 = "";
private String query3 = "";
private String query4 = "";
private String query5 = "";
private String query6 = "";
private String query7 = "";
private String query8 = "";
private static int streamID;
private static int studentID;
private static String studentName;
private static String streamName;
Statement st = null;
public List<StudentDto> getStudentsCount() throws DaoException {
List<StudentDto> countStudentperStream = new ArrayList<StudentDto>();
StudentDto student = new StudentDto();
try {
Connection conn = DBUtil.getConnection();
st = conn.createStatement();
query3 = "SELECT streams.stream_name,COUNT(students.stream_id) " + "FROM students " +"inner join streams on students.stream_id=streams.stream_id "+ "GROUP BY students.stream_Id;";
System.out.println(query3);
ResultSet rs = st.executeQuery(query3);
while (rs.next()) {
System.out.println(rs.getString(1) + " " + rs.getInt(2));
student.setStream_id(rs.getInt(2));
student.setStudents_count(rs.getInt(2));
countStudentperStream.add(student);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return countStudentperStream;
}
public int insertAllStudents(List<Student> students) throws DaoException {
int result = 0;
Connection conn;
query4 = "insert into students " + "Values(?,?,?);";
query5 = "select * from students;";
query6 = "delete from students where student_id=43;";
query7 = "update students set name='Santan Aryan' where student_id=64";
System.out.println(query4);
try {
conn = DBUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(query4);
PreparedStatement ps1 = conn.prepareStatement(query5);
PreparedStatement ps2 = conn.prepareStatement(query6);
PreparedStatement ps3 = conn.prepareStatement(query7);
for (Student s : students) {
streamID = s.getStream().getStreamId();
streamName = s.getStream().getStreamName();
studentName = s.getName();
studentID = s.getStudentId();
ps.setInt(1, studentID);
ps.setString(2, studentName);
ps.setInt(3, streamID);
ps.executeUpdate();
ResultSet rs = ps1.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getInt(3));
}
}
result = ps2.executeUpdate();
ps3.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public boolean insertAllStudentsBatch(List<Student> students) throws DaoException {
int res[]=new int[students.size()];
Connection conn;
query8 = "insert into students " + "Values(?,?,?);";
try {
conn = DBUtil.getConnection();
PreparedStatement ps=conn.prepareStatement(query8);
for(Student s:students) {
ps.setInt(1, s.getStudentId());
ps.setString(2,s.getName());
ps.setInt(3, s.getStream().getStreamId());
ps.addBatch();
}
res=ps.executeBatch();
for(int k:res) {
System.out.println(k);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (res == null)
return false;
else
return true;
}
// public boolean insertStudents(List<Student> students) throws DaoException{
// // batch insert
// int result = 0;
// try {
// Connection conn = DBUtil.getConnection();
// st=conn.createStatement();
//
// for( Student s:students) {
// streamID=s.getStream().getStreamId();
// streamName=s.getStream().getStreamName();
// studentName=s.getName();
// studentID=s.getStudentId();
//
// query1="insert into students "
// +"Values("+studentID+",'"+studentName+"',"+streamID+");";
// System.out.println(query1);
// query2="select * from students;";
// result=st.executeUpdate(query1);
// ResultSet rs=st.executeQuery(query2);
// while(rs.next()) {
// System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3));
// }
// }
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// if(result == 1)
// return true;
// else
// return false;
// }
}
|
import com.google.gson.Gson;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class GetRequest {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient();
final String app_id = "1c9dba3c1cdd4b5699c41b00c3ea680d";
final String app_key = "veOUqBorXQfdxSDc8CU1ihPFu7m9FVu8";
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://us.battle.net/oauth/token").newBuilder();
urlBuilder.addQueryParameter("client_id", app_id);
urlBuilder.addQueryParameter("client_secret", app_key);
urlBuilder.addQueryParameter("grant_type", "client_credentials");
String url = urlBuilder.build().toString();
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
String access_token = response.body().string();
Gson gson = new Gson();
Token token = gson.fromJson(access_token, Token.class);
System.out.println(token.access_token);
}
}
|
/**
Copyright [2020] [Javier Linares Castrillón]
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 domain.simplex.programLoop.recurring;
import domain.simplex.programLoop.recurring.procesos.IProceso;
import java.util.ArrayList;
import java.util.PriorityQueue;
/**
* @author Javier Linares Castrillón
*/
/**
* Esta clase es la encargada de calcular los procesos entrante y saliente de cada iteración del algoritmo simplex.
*/
public class EntranteSaliente {
private IProceso[][] matrizProcesos;
private int contador;
//maetodo 1
private ArrayList<Double> xs;
//metodo 2
private ArrayList<Double> dividendos, divisores;
/**
* Constructor de la clase EntranteSaliente.
* @param matriz
* @param contador
*/
public EntranteSaliente(IProceso[][] matriz, int contador){
this.contador = contador;
this.matrizProcesos = matriz;
}
/**
* Con este método calculo el proceso entrante.
* @return proceso entrante.
*/
public String getEntrante(){
double solucion = 0; //almacenará la solución de quién es más grande.
int posicion = 0; //almacenará la dirección de memoria del elemento mayor en el ArrayList.
xs = new ArrayList<>();
xs.add((matrizProcesos[0][0]).getCj());
xs.add((matrizProcesos[0][1]).getCj());
xs.add((matrizProcesos[0][2]).getCj());
xs.add((matrizProcesos[0][3]).getCj());
xs.add((matrizProcesos[0][4]).getCj());
xs.add((matrizProcesos[0][5]).getCj());
xs.add((matrizProcesos[0][6]).getCj());
PriorityQueue<Double> values = new PriorityQueue<>();
values.add(xs.get(0));
values.add(xs.get(1));
values.add(xs.get(2));
values.add(xs.get(3));
values.add(xs.get(4));
values.add(xs.get(5));
values.add(xs.get(6));
for (int i = 0; i < 7 - contador; i++)
solucion = values.remove();
for (int i = 0; i < 7; i++)
if (solucion == xs.get(i))
posicion = i + 1;
String solucionFinal = "x" + posicion;
return solucionFinal;
}
/**
* Coon este método calculo el proceso saliente.
* @param entrante
* @return el proceso saliente.
*/
public String getSaliente(String entrante) {
int index = 0;
for (int i = 0; i < 7; i++){
if (matrizProcesos[0][i].getNombreProceso().equals(entrante)) {
index = i;
}
}
dividendos = new ArrayList<>();
divisores = new ArrayList<>();
dividendos.add(matrizProcesos[0][8].getX1());
dividendos.add(matrizProcesos[0][8].getX2());
dividendos.add(matrizProcesos[0][8].getX3());
//Con este bloque de código, repito la misma estrategia pero pasando el parámetro "entrante".
divisores.add(matrizProcesos[0][index].getX1());
divisores.add(matrizProcesos[0][index].getX2());
divisores.add(matrizProcesos[0][index].getX3());
int solIndex = 0; //almaneca la posicion en memoria de la solución.
if((division(dividendos.get(0), divisores.get(0)) < division(dividendos.get(1), divisores.get(1)))) {
if (division(dividendos.get(0), divisores.get(0)) < division(dividendos.get(2), divisores.get(2))) {
solIndex = 0;
} else {
solIndex = 2;
}
}
else if(division(dividendos.get(1), divisores.get(1)) < division(dividendos.get(2), divisores.get(2))){
solIndex = 1;
}
else {
solIndex = 2;
}
//Con este bloque de codigo, obtengo el nombre del proceso horizontal cuya cantidad coincide con un objeto de Procesos verticales.
String saliente = "";
if(solIndex == 0) saliente = matrizProcesos[1][0].getNombreProceso();
if(solIndex == 1) saliente = matrizProcesos[1][1].getNombreProceso();
if(solIndex == 2) saliente = matrizProcesos[1][2].getNombreProceso();
return saliente;
}
private double division(double dividendo, double divisor){
return dividendo / divisor;
}
/**
* Utilizo este método para hallar los procesos que no van a salir.
* ¡Importante! -> Se utiliza el proceso saliente y NO el entrante, de otro modo no funcionaría.
* @param saliente
* @return una tupla con los dos procesos no salientes.
*/
public String[] noSalientes(String saliente){
int idx = 0;
for(int i = 0; i < 3; i++)
if(matrizProcesos[1][i].getNombreProceso().equals(saliente))
idx = i;
ArrayList<Integer> aux = new ArrayList<>();
aux.add(0); aux.add(1); aux.add(2);
aux.remove(aux.indexOf(idx));
String[] procesosNoSalientes = new String[2];
procesosNoSalientes[0] = matrizProcesos[1][aux.get(0)].getNombreProceso();
procesosNoSalientes[1] = matrizProcesos[1][aux.get(1)].getNombreProceso();
return procesosNoSalientes;
}
}
|
package cqu.shy.game;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import cqu.shy.resource.ImageResource;
class Bullet extends FlyingObject{
private MyImage image;
private int Dx;
private int Dy;
private int x;
private int y;
private int move_speed;
private boolean isDeath=false;
private boolean goToDeath=false;
private int count_death=1;
private int death_interval=6;
private int attack;
boolean isLaser=false; //专门为第三个BOSS的激光使用
int laser_time=1;
boolean isSkill=false; //为Boss的技能使用
public Bullet(BufferedImage img,int move_speed,int attack) {
// TODO Auto-generated constructor stub
image = new MyImage(img, img.getWidth(), img.getHeight(), 0, 0);
this.move_speed = move_speed;
this.attack = attack;
Dx=0;Dy=0;
}
public boolean hit(EnemyPlane other) {
if((this.getX()>=other.getX()&&this.getX()<=other.getX()+other.getImage().getWidth()&&this.getY()>=other.getY()&&this.getY()<=other.getY()+other.getImage().getHeight())||
(other.getX()>=this.getX()&&other.getX()<=this.getX()+image.getWidth()&&other.getY()>=this.getY()&&other.getY()<=this.getY()+image.getHeight())||
(this.getX()>=other.getX()&&this.getX()<=other.getX()+other.getImage().getWidth()&&other.getY()>=this.getY()&&other.getY()<=this.getY()+image.getHeight())||
(other.getX()>=this.getX()&&other.getX()<=this.getX()+image.getWidth()&&this.getY()>=other.getY()&&this.getY()<=other.getY()+other.getImage().getHeight()))
return true;
else
return false;
}
public boolean hit(HeroPlane other){
if((this.getX()>=other.getX()&&this.getX()<=other.getX()+other.getImage().getWidth()&&this.getY()>=other.getY()&&this.getY()<=other.getY()+other.getImage().getHeight())||
(other.getX()>=this.getX()&&other.getX()<=this.getX()+image.getWidth()&&other.getY()>=this.getY()&&other.getY()<=this.getY()+image.getHeight())||
(this.getX()>=other.getX()&&this.getX()<=other.getX()+other.getImage().getWidth()&&other.getY()>=this.getY()&&other.getY()<=this.getY()+image.getHeight())||
(other.getX()>=this.getX()&&other.getX()<=this.getX()+image.getWidth()&&this.getY()>=other.getY()&&this.getY()<=other.getY()+other.getImage().getHeight()))
return true;
else
return false;
}
public boolean hit(Boss other){
if((this.getX()>=other.getX()&&this.getX()<=other.getX()+other.getImage().getWidth()&&this.getY()>=other.getY()&&this.getY()<=other.getY()+other.getImage().getHeight())||
(other.getX()>=this.getX()&&other.getX()<=this.getX()+image.getWidth()&&other.getY()>=this.getY()&&other.getY()<=this.getY()+image.getHeight())||
(this.getX()>=other.getX()&&this.getX()<=other.getX()+other.getImage().getWidth()&&other.getY()>=this.getY()&&other.getY()<=this.getY()+image.getHeight())||
(other.getX()>=this.getX()&&other.getX()<=this.getX()+image.getWidth()&&this.getY()>=other.getY()&&this.getY()<=other.getY()+other.getImage().getHeight()))
return true;
else
return false;
}
public boolean hit(Bullet other){
if((this.getX()>=other.getX()&&this.getX()<=other.getX()+other.getImage().getWidth()&&this.getY()>=other.getY()&&this.getY()<=other.getY()+other.getImage().getHeight())||
(other.getX()>=this.getX()&&other.getX()<=this.getX()+image.getWidth()&&other.getY()>=this.getY()&&other.getY()<=this.getY()+image.getHeight())||
(this.getX()>=other.getX()&&this.getX()<=other.getX()+other.getImage().getWidth()&&other.getY()>=this.getY()&&other.getY()<=this.getY()+image.getHeight())||
(other.getX()>=this.getX()&&other.getX()<=this.getX()+image.getWidth()&&this.getY()>=other.getY()&&this.getY()<=other.getY()+other.getImage().getHeight()))
return true;
else
return false;
}
@Override
public void init() {
}
public void doDamage(HeroPlane other){
other.setHP(other.getHP()-attack);
}
public void doDamage(Boss other){
other.setHP(other.getHP()-attack);
}
public void doDamage(EnemyPlane other){
other.setHP(other.getHP()-attack);
}
@Override
public void move() {
x +=Dx*move_speed;
y +=Dy*move_speed;
if(isLaser)
laser_time++;
}
@Override
public void draw(Graphics g) {
if(!isDeath)
{
g.drawImage(image.getImage(), x, y, image.getWidth(), image.getHeight(), null);
}
else {
if(count_death<death_interval){
if(isLaser){
g.drawImage(ImageResource.BossBullet3_2IMG, x, y, ImageResource.BossBullet3_2IMG.getWidth(),
ImageResource.BossBullet3_2IMG.getHeight(), null);
}
else{
g.drawImage(ImageResource.ExplosionBulletIMG, x, y, ImageResource.ExplosionBulletIMG.getWidth(),
ImageResource.ExplosionBulletIMG.getHeight(), null);
}
}
else{
goToDeath=true;
}
count_death++;
}
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public boolean isDeath() {
return isDeath;
}
public void setDeath(boolean isDeath) {
this.isDeath = isDeath;
}
public boolean isGoToDeath() {
return goToDeath;
}
public void setGoToDeath(boolean goToDeath) {
this.goToDeath = goToDeath;
}
public int getDx() {
return Dx;
}
public void setDx(int dx) {
Dx = dx;
}
public int getDy() {
return Dy;
}
public void setDy(int dy) {
Dy = dy;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public MyImage getImage() {
return image;
}
public void setImage(MyImage image) {
this.image = image;
}
public int getMove_speed() {
return move_speed;
}
public void setMove_speed(int move_speed) {
this.move_speed = move_speed;
}
}
|
package com.tencent.mm.ui.video;
import android.media.MediaPlayer.OnPreparedListener;
class VideoView$2 implements OnPreparedListener {
final /* synthetic */ VideoView uFz;
VideoView$2(VideoView videoView) {
this.uFz = videoView;
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public final void onPrepared(android.media.MediaPlayer r3) {
/*
r2 = this;
r0 = r2.uFz;
com.tencent.mm.ui.video.VideoView.c(r0);
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.d(r0);
if (r0 == 0) goto L_0x001c;
L_0x000d:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.d(r0);
r1 = r2.uFz;
r1 = com.tencent.mm.ui.video.VideoView.e(r1);
r0.onPrepared(r1);
L_0x001c:
r0 = r2.uFz;
r1 = r3.getVideoWidth();
com.tencent.mm.ui.video.VideoView.a(r0, r1);
r0 = r2.uFz;
r1 = r3.getVideoHeight();
com.tencent.mm.ui.video.VideoView.b(r0, r1);
r0 = r2.uFz;
r0.cAq();
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.a(r0);
if (r0 == 0) goto L_0x00bb;
L_0x003b:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.b(r0);
if (r0 == 0) goto L_0x00bb;
L_0x0043:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.f(r0);
if (r0 == 0) goto L_0x0059;
L_0x004b:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.e(r0);
r0.start();
r0 = r2.uFz;
com.tencent.mm.ui.video.VideoView.g(r0);
L_0x0059:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.h(r0);
r1 = r2.uFz;
r1 = com.tencent.mm.ui.video.VideoView.a(r1);
if (r0 != r1) goto L_0x00b1;
L_0x0067:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.i(r0);
r1 = r2.uFz;
r1 = com.tencent.mm.ui.video.VideoView.b(r1);
if (r0 != r1) goto L_0x00b1;
L_0x0075:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.j(r0);
if (r0 == 0) goto L_0x0091;
L_0x007d:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.e(r0);
r1 = r2.uFz;
r1 = com.tencent.mm.ui.video.VideoView.j(r1);
r0.seekTo(r1);
r0 = r2.uFz;
com.tencent.mm.ui.video.VideoView.k(r0);
L_0x0091:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.f(r0);
if (r0 != 0) goto L_0x00b1;
L_0x0099:
r0 = r2.uFz;
r0 = r0.isPlaying();
if (r0 != 0) goto L_0x00b1;
L_0x00a1:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.j(r0);
if (r0 != 0) goto L_0x00b1;
L_0x00a9:
r0 = r2.uFz;
r0 = r0.getCurrentPosition();
if (r0 <= 0) goto L_0x00b1;
L_0x00b1:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.e(r0);
r0.isPlaying();
return;
L_0x00bb:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.j(r0);
if (r0 == 0) goto L_0x00d7;
L_0x00c3:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.e(r0);
r1 = r2.uFz;
r1 = com.tencent.mm.ui.video.VideoView.j(r1);
r0.seekTo(r1);
r0 = r2.uFz;
com.tencent.mm.ui.video.VideoView.k(r0);
L_0x00d7:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.f(r0);
if (r0 == 0) goto L_0x00b1;
L_0x00df:
r0 = r2.uFz;
r0 = com.tencent.mm.ui.video.VideoView.e(r0);
r0.start();
r0 = r2.uFz;
com.tencent.mm.ui.video.VideoView.g(r0);
goto L_0x00b1;
*/
throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.ui.video.VideoView$2.onPrepared(android.media.MediaPlayer):void");
}
}
|
import java.util.*;
class Solution {
public int[] solution(String s) {
s = s.substring(2, s.length() - 2);
String[] sList = s.replace("},{", " ").split(" ");
Queue<List<String>> q = new LinkedList<>();
for (String str: sList) {
String[] strList = str.split(",");
List<String> list = new ArrayList<>();
for (String str2: strList) {
list.add(str2);
}
q.add(list);
}
Set<String> set = new HashSet<>();
List<Integer> answerList = new ArrayList<>();
int count = 1;
while(!q.isEmpty()) {
var list = q.poll();
if (list.size() == count) {
for (String temp: list) {
if (set.contains(temp)) {
continue;
}
set.add(temp);
answerList.add(Integer.parseInt(temp));
}
count++;
continue;
}
q.add(list);
}
return answerList.stream().mapToInt(i->i).toArray();
}
}
|
package com.tec2.pdm2.app;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by luishoracio on 29/04/14.
*/
public class Usuarios{
private ArrayList<HashMap<String,String>> usuarios;
private ArrayList<HashMap<String,String>> nombres;
private JSONArray datosAUsar;
Usuarios(){}
Usuarios(JSONArray datos){
datosAUsar = datos;
usuarios = new ArrayList<HashMap<String, String>>();
setValores();
}
private void setValores (){
try {
for (int i = 0; i < datosAUsar.length(); i++) {
JSONObject valor = datosAUsar.getJSONObject(i);
HashMap<String, String> hashValor =
new HashMap<String, String>();
hashValor.put("id", valor.getString("id"));
hashValor.put("nombre", valor.getString("nombre"));
usuarios.add(hashValor);
}
}catch (JSONException e){}
}
private void setTelefonos(){
try {
for (int i = 0; i < datosAUsar.length(); i++) {
JSONObject valor = datosAUsar.getJSONObject(i);
HashMap<String, String> hashValor =
new HashMap<String, String>();
hashValor.put("id", valor.getString("id"));
hashValor.put("telefonos", valor.getString("telefonos"));
usuarios.add(hashValor);
}
}catch (JSONException e){}
}
public ArrayList<HashMap<String,String>> getUsuarios(){
return usuarios;
}
}
|
package PO42Y.Osinnikov.wdad.data.managers;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
/**
* Created by User on 30.10.2016.
*/
public class TestPreferencesManager {
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, TransformerException {
PreferencesManager preferencesManager=PreferencesManager.getInstance();
System.out.println("до изменений");
if (preferencesManager.isCreateRegistry()) {
System.out.println("Create Registry: yes");
}
else System.out.println("Create Registry: no");
System.out.println("Registry Address: "+preferencesManager.getRegistryAddress());
System.out.println("Registry port:"+preferencesManager.getRegistryPort());
System.out.println("Policy Path:"+preferencesManager.getPolicyPath());
if (preferencesManager.isUseCodeBaseOnly()){
System.out.println("Use Code Base Only: yes");
}
else System.out.println("Use Code Base Only: no");
System.out.println("Class Provider: "+preferencesManager.getClassProvider());
System.out.println("после изменений");
preferencesManager.setCreateRegistry(false);
if (preferencesManager.isCreateRegistry()) {
System.out.println("Create Registry: yes");
}
else System.out.println("Create Registry: no");
preferencesManager.setRegistryAddress("192.168.0.1");
System.out.println("Registry Address: "+preferencesManager.getRegistryAddress());
preferencesManager.setRegistryPort("2005");
System.out.println("Registry port:"+preferencesManager.getRegistryPort());
preferencesManager.setPolicyPath("policy");
System.out.println("Policy Path:"+preferencesManager.getPolicyPath());
preferencesManager.setUseCodeBaseOnly(false);
if (preferencesManager.isUseCodeBaseOnly()){
System.out.println("Use Code Base Only: yes");
}
else System.out.println("Use Code Base Only: no");
preferencesManager.setClassProvider("http://vk.com");
System.out.println("Class Provider: "+preferencesManager.getClassProvider());
}
}
|
package com.tencent.mm.plugin.voip.ui;
import com.tencent.mm.R;
import com.tencent.mm.plugin.voip.b.b;
class VideoActivity$4 implements Runnable {
final /* synthetic */ VideoActivity oQn;
VideoActivity$4(VideoActivity videoActivity) {
this.oQn = videoActivity;
}
public final void run() {
if (b.yW(VideoActivity.b(this.oQn)) && !VideoActivity.c(this.oQn) && VideoActivity.d(this.oQn) != null) {
VideoActivity.d(this.oQn).co(this.oQn.getString(R.l.voip_callout_timeout_prompt), 10000);
}
}
}
|
package com.tencent.mm.plugin.scanner.ui;
import android.os.Message;
import com.tencent.mm.plugin.scanner.util.h;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.x;
class BaseScanUI$9 extends ag {
final /* synthetic */ BaseScanUI mHS;
BaseScanUI$9(BaseScanUI baseScanUI) {
this.mHS = baseScanUI;
}
public final void handleMessage(Message message) {
if (BaseScanUI.f(this.mHS) != null && BaseScanUI.m(this.mHS) && !BaseScanUI.G(this.mHS) && message.what == 0) {
BaseScanUI.a(this.mHS, System.currentTimeMillis());
h f = BaseScanUI.f(this.mHS);
BaseScanUI baseScanUI = this.mHS;
if (f.ddt != null && f.iOl) {
try {
f.btf();
f.ddt.autoFocus(baseScanUI);
} catch (RuntimeException e) {
x.w("MicroMsg.scanner.ScanCamera", "autoFocus() " + e.getMessage());
}
}
}
}
}
|
package com.dayone.dao;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import com.dayone.model.Product;
import com.dayone.util.ConnectionUtil;
public class ProductDAO {
private JdbcTemplate jdbcTemplate=ConnectionUtil.getJdbcTemplate();
public void add(Product model)
{
String query="insert into product_details(prod_name,price,prod_details,warranty) values (?,?,?,?)";
Object[] params={model.getProd_name(),model.getPrice(),model.getProd_details(),model.getWarranty()};
int rows=jdbcTemplate.update(query,params);
}
public List<Product> show()
{
String query="select prod_name,price,prod_details,warranty from product_details";
List<Product> productList=jdbcTemplate.query(query, (rs,rowNo)->
{
Product product = new Product();
product.setProd_name(rs.getString("prod_name"));
product.setPrice(rs.getFloat("price"));
product.setProd_details(rs.getString("prod_details"));
product.setWarranty(rs.getString("warranty"));
return product;
});
return productList;
}
}
|
package com.immotor.bluetoothadvertiser.command;
import android.text.TextUtils;
import com.immotor.bluetoothadvertiser.utils.HexUtils;
/**
* Created by ForestWang on 2016/3/28.
*/
public class ManufacturerSpecificDataBuilder {
static final int OFF_ADDRESS = 0;
static final int LEN_ADDRESS = 6;
private final static int OFF_END = (OFF_ADDRESS + LEN_ADDRESS);
private final static int TOTAL_LEN = OFF_END;
private byte[] mData;
public ManufacturerSpecificDataBuilder() {
mData = new byte[TOTAL_LEN];
}
public byte[] getData() {
return mData;
}
public void addAddress(String address) {
if (TextUtils.isEmpty(address))
return;
byte[] bytes = HexUtils.hexStringToBytes(address.replace(":", ""));
System.arraycopy(bytes, 0, mData, OFF_ADDRESS, LEN_ADDRESS);
}
}
|
package id.co.igustiglen.TripBandung;
/**
* Created by I Gusti Glen on 11-Agustus-20.
* Nim :10117099
* Kelas :IF-3
*/
public enum ModelObject {
WISATA(R.string.wisata, R.layout.slider_wisata)
;
private int mTitleResId;
private int mLayoutResId;
ModelObject(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
|
package com.game.entity;
import java.util.ArrayList;
import java.util.List;
public class EntityDatabase {
public List<Entity> entities = new ArrayList<Entity>();
public int size() {
return entities.size();
}
public void addEntity(Entity Entity) {
entities.add(Entity);
}
public void removeEntity(Entity Entity) {
if (hasEntity(Entity))
entities.remove(getIndex(Entity));
}
public int getIndex(Entity Entity) {
for (int i = 0; i < entities.size(); i++) {
if (entities.get(i).equals(Entity))
return i;
}
return -1;
}
public Entity getEntity(String name) {
for (Entity Entity : entities)
if (Entity.getName().toLowerCase().equals(name) || Entity.getName().equals(name))
return Entity;
return null;
}
public boolean hasEntity(Entity Entity2) {
for (Entity Entity : entities)
if (Entity.equals(Entity2))
return true;
return false;
}
public boolean hasEntity(String name) {
for (Entity Entity : entities)
if (Entity.getName().toLowerCase().equals(name) || Entity.getName().equals(name))
return true;
return false;
}
}
|
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Main {
public static void main(String[] args) {
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(registry).getMetadataBuilder().build();
try (SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build()
) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Query course = session.createQuery("from Course");
List<Course> courseList = course.getResultList();
Query student = session.createQuery("from Student");
List<Student> studentList = student.getResultList();
Query link = session.createQuery("from " + LinkedPurchaseList.class.getSimpleName());
List<LinkedPurchaseList> linkedPurchaseLists = link.getResultList();
SQLQuery query = session.createSQLQuery("select student_name, course_name, price, subscription_date from Purchaselist");
List<Object[]> purchaseLists = query.list();
purchaseLists.forEach(s -> {
String stStud = s[0].toString();
String stCourse = s[1].toString();
int intPrice = (int) s[2];
Date subscriptionDate = (Date) s[3];
int j = 0;
int k = 0;
for (int i = 0; i < studentList.size(); i++) {
if (studentList.get(i).getName().equals(stStud)) {
k = i + 1;
break;
}
}
for (int i = 0; i < courseList.size(); i++) {
if (courseList.get(i).getName().equals(stCourse)) {
j = i + 1;
break;
}
}
LinkedPurchaseList linkedPurchaseList = new LinkedPurchaseList(new LinkedPurchaseList.Id(j, k), intPrice, subscriptionDate);
session.save(linkedPurchaseList);
linkedPurchaseLists.add(linkedPurchaseList);
});
linkedPurchaseLists.forEach(s -> System.out.println(s.getId().getStudentId() + " - " +
s.getId().getCourseId() + " - " + s.getPrice() + " - " + s.getSubscriptionDate()));
transaction.commit();
}
}
}
|
package com.tencent.mm.ac.a;
public enum g$a$a {
;
static {
dNy = 1;
dNz = 2;
dNA = 3;
dNB = new int[]{dNy, dNz, dNA};
}
}
|
package messageDigest_test;
import java.security.MessageDigest;
/**
* Description:
*
* @author Baltan
* @date 2018/2/17 14:13
*/
public class Test1 {
public static void main(String[] args) throws Exception {
getMd5("新年好");
}
public static void getMd5(String text) throws Exception {
MessageDigest md = MessageDigest.getInstance("md5");
md.update(text.getBytes());
byte[] bArray1 = md.digest();
for (byte b : bArray1) {
System.out.print(b + "\t");
}
System.out.println();
byte[] bArray2 = md.digest(text.getBytes());
for (byte b : bArray2) {
System.out.print(b + "\t");
}
}
}
|
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
/**
* Clase encargada de manejar lo relacionado con la IA de la maquina al igual que lajugabilidad
* Esta es la clase que debe ser ejecutada.
* @author Miguel Angel Askar Rodriguez - 1355842
* @author Danny Fernando Cruz Arango - 1449949
*/
public class PrincipalControlador implements ActionListener, MouseListener
{
private Vector<Nodo> cero;
private Vector<Nodo> primero;
private Vector<Nodo> segundo;
private Vector<Nodo> tercero;
private JButton[][] botonesTablero;
private PrincipalVista ventanaInicial;
private int x, y;
private int largoTiro;
private int contadorTurno;
/**
* Metodo constructor en el cual se inicializan gran cantidad de variables necesarias
* Se carga un talero desde archivo de texto
* y se inicializa la interfaz
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public PrincipalControlador()
{
x= y= 0;
cero= new Vector(0,1);
primero= new Vector(0,1);
segundo= new Vector(0,1);
tercero= new Vector(0,1);
contadorTurno= 0;
//----------------LECTURA DE ARCHIVOS----------------------
Archivos lector= new Archivos();
lector.leer("tablero.txt"); //Si desea cambiar el estado inicial, se puede modificar o reemplazar este archivo.
String leido= lector.getLeido();
StringTokenizer numeros= new StringTokenizer(leido, "\n");
int[][] tablero= new int[6][10];
for(int i=0; i<6; i++)
{
String numero= numeros.nextToken();
StringTokenizer valores= new StringTokenizer(numero, " ");
for(int j= 0; j<10; j++)
{
tablero[i][j]= Integer.parseInt(valores.nextToken());
}
}
//----------------FIN LECTURA DE ARCHIVOS------------------
Nodo inicial= new Nodo(new Estado(tablero), -1, 0); //Se crea el nodo inicial con el tablero cargado.
inicial.setPosicion(0);
cero.add(inicial);
botonesTablero = new JButton[6][10];
crearBotones();
ventanaInicial = new PrincipalVista(botonesTablero, this);
this.activarDesactivarBotones(2);
ventanaInicial.setVisible(true);
}
/**
* Metodo usado para crear un arreglo de botones con propiedad de casilla vacia de forma predeterminada
* Para casgar como estado inicial antes de iniciar un partida
*/
public void crearBotones(){
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 10; j++) {
JButton btn = new JButton();
btn.setIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Verde.png")));
btn.putClientProperty("row", i);
btn.putClientProperty("column", j);
btn.addMouseListener(this);
botonesTablero[i][j]=btn;
}
}
}
/**
* Metodo que recibe un arreglo de enteros con las siguiente convenciones:
* 0 = Vacio (verde)
* 1 = Usuario (Roja)
* 2 = maquina (Negra)
* Dicho arreglo representa el estado de un tablero y de igual manera los botones en dicha posición seran
* Para representar en tablero en ese estado
* @param tablero El tablero que debe ser representado
*/
public void actualizarTablero(int[][] tablero){
for (int i = 0; i < tablero.length; i++) {
for (int j = 0; j < tablero[0].length; j++) {
if (tablero[i][j]==0){
botonesTablero[i][j].setIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Verde.png")));
botonesTablero[i][j].setDisabledIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Verde.png")));
botonesTablero[i][j].putClientProperty("User", 0);
}
if (tablero[i][j]==1){
botonesTablero[i][j].setIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Roja.png")));
botonesTablero[i][j].setDisabledIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Roja.png")));
botonesTablero[i][j].putClientProperty("User", 1);
}
if (tablero[i][j]==2){
botonesTablero[i][j].setIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Negra.png")));
botonesTablero[i][j].setDisabledIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Negra.png")));
botonesTablero[i][j].putClientProperty("User", 2);
}
}
}
}
/**
* Metodo encargado de crear el arbol por niveles, expandiendo el nodo original
* hasta llegar a las hojas del nivel 3
*/
public void crearArbol()
{
primero= expandirNodo(cero.get(0), 2);
for(int i=0; i<primero.size(); i++)
{
segundo.addAll(expandirNodo(primero.get(i), 2));
}
for(int i=0; i<segundo.size(); i++)
{
tercero.addAll(expandirNodo(segundo.get(i), 2));
}
}
/**
* Calcula la decisión MiniMax, recorriendo el árbol desde sus hojas hasta la raiz (3 niveles)
* @return Entero que representa el nodo que se debe tomar del primer nivel
*/
public int calcularDecisionMinMax()
{
//El nivel 3 es quien define al 2, decisión max
for(int i= 0; i<tercero.size(); i++)
{
if(segundo.elementAt(tercero.get(i).getPadre()).getMinimax()< tercero.get(i).getPuntajeNegro()-tercero.get(i).getPuntajeRojo())
{
Nodo auxiliar = segundo.elementAt(tercero.get(i).getPadre());
auxiliar.setMinimax(tercero.get(i).getPuntajeNegro()-tercero.get(i).getPuntajeRojo());
segundo.setElementAt(auxiliar, tercero.get(i).getPadre());
}
}
//El nivel 2 es quien define al 1, decisión min
for(int i= 0; i<primero.size(); i++)
{
primero.elementAt(i).setMinimax(9999); //Se utiliza un número no alcanzable
}
for(int i= 0; i<segundo.size(); i++)
{
if(primero.elementAt(segundo.get(i).getPadre()).getMinimax()> segundo.get(i).getPuntajeNegro()-segundo.get(i).getPuntajeRojo())
{
Nodo auxiliar= primero.elementAt(segundo.get(i).getPadre());
auxiliar.setMinimax(segundo.get(i).getPuntajeNegro()-segundo.get(i).getPuntajeRojo());
primero.setElementAt(auxiliar, segundo.get(i).getPadre());
}
}
//Se busca la decisión minimax (max) en el nivel 1
int minimax= primero.get(0).getMinimax();
int resultado= 0;
for(int i= 1; i<primero.size(); i++)
{
if(primero.get(i).getMinimax()>minimax)
{
resultado= i;
}
}
return resultado;
}
/**
* Metodo que expande el nodo que llega por parametro, y genera todas sus posibles jugadas
* @param nodo El nodo que debe ser expandido
* @param tipo Representa el jugador a expandir
* @return Un vector de nodos que contiene todas las posibles jugadas del jugador solicitado
*/
public Vector<Nodo> expandirNodo(Nodo nodo, int tipo) //tipo, para saber si expande rojas(1) o negras(2)
{
@SuppressWarnings({ "unchecked", "rawtypes" })
Vector<Nodo> resultado= new Vector(0,1);
for(int i=0; i<6; i++)
{
for(int j=1; j<9; j++)
{
if(nodo.getEstado().getTablero()[i][j]==tipo) //Verifica si es la ficha que se desea usar
{
int[] ficha= {i,j};
int nuevaPosicion= nodo.getEstado().posiblePrimeraJugada(ficha);
if(nuevaPosicion!=0 && nuevaPosicion!=9)
{
int[][] tablero= new int[6][10];
for(int m= 0; m<6; m++)
{
for(int n=0; n<10; n++)
{
tablero[m][n]= nodo.getEstado().getTablero()[m][n]; //Se copia el tablero por valor.
}
}
Estado nuevo= new Estado(tablero);
ficha= nuevo.ponerFicha(ficha, nuevaPosicion, tipo); //Se mueve la ficha
nuevo.setPrimerMovimiento(nuevaPosicion); //Se guarda el primer movimiento que se hizo
Nodo nuevoNodo= new Nodo(nuevo, nodo.getPosicion(), nodo.getProfundidad()+1);
nuevoNodo.setPuntajeNegro(nuevo.puntacionNegro());
nuevoNodo.setPuntajeRojo(nuevo.puntacionRojo());
resultado.add(nuevoNodo); //Se asigna este nodo como si no se decidiera hacer segunda jugada.
//Ahora asignamos la segunda jugada
Vector<int[][]> nuevosEstados= nuevoNodo.getEstado().posiblesSegundasJugadas(tipo);
for(int k= 0; k<nuevosEstados.size(); k++) //Se guardan las posibles segundas jugadas a partir de la primera realizada.
{
Estado nuevoSegundo= new Estado(nuevosEstados.get(k));
Nodo nuevoNodoSegundo= new Nodo(nuevoSegundo, nodo.getPosicion(), nodo.getProfundidad()+1);
nuevoNodoSegundo.setPuntajeNegro(nuevoSegundo.puntacionNegro());
nuevoNodoSegundo.setPuntajeRojo(nuevoSegundo.puntacionRojo());
resultado.add(nuevoNodoSegundo);
}
}
}
}
}
for(int i=0; i<resultado.size(); i++)
{
resultado.elementAt(i).setPosicion(i); //Se guarda la posición de los nodos para poder referenciar los padres en los hijos.
}
return resultado;
}
/**
* Metodo que activa y desactiva los botones necesarios dentro del tablero para la jugada
* Si es el turno dej jugador usuario, se activan los botones donde se encuentran sus fichas
* Si es el turno de la maquina, todos los botones del tablero se desactivan
* @param num Representa el jugador 1 = Usuario; 2 = Maquina
*/
public void activarDesactivarBotones(int num){
if (num==1) {
for (int i = 0; i < botonesTablero.length; i++) {
for (int j = 0; j < botonesTablero[0].length; j++) {
if(botonesTablero[i][j].getClientProperty("User").equals(2)){
botonesTablero[i][j].setEnabled(false);
}else{
if(botonesTablero[i][j].getClientProperty("User").equals(0)){
botonesTablero[i][j].setEnabled(false);
}else botonesTablero[i][j].setEnabled(true);
}
}
}
}
if (num==2) {
for (int i = 0; i < botonesTablero.length; i++) {
for (int j = 0; j < botonesTablero[0].length; j++) {
botonesTablero[i][j].setEnabled(false);
}
}
}
}
/**
* Metodo usado para par inicio al juego
* @param jugador Representa el jugador 1 = Usuario; 2 = Maquina
*/
public void partida(int jugador){
ventanaInicial.actualizarTurno("Usuario");
activarDesactivarBotones(jugador);
largoTiro=1;
}
/**
* Los disparos son realizados de forma automática despues de seleccionar la ficha con la que se
* desea jugar, este metodo se encarga de determinar la posición final de la ficha seleccionada
* teniendo en cuenta su posición inicial, y el largo del tiro
* @param x Ubicación en x de la ficha seleccionada
* @param y Ubicación en y de la ficha seleccionada
*/
public void realizarTiro (int x, int y){
botonesTablero[x][y].setIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Verde.png")));
botonesTablero[x][y].setDisabledIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Verde.png")));
botonesTablero[x][y].putClientProperty("User", 0);
if(y+largoTiro < 8) {
for (int i = 0; i < botonesTablero.length; i++) {
if (botonesTablero[i][y+largoTiro].getClientProperty("User").equals(0)) {
botonesTablero[i][y+largoTiro].setIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Roja.png")));
botonesTablero[i][y+largoTiro].setDisabledIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Roja.png")));
botonesTablero[i][y+largoTiro].putClientProperty("User", 1);
break;
}
}
int cont = 0;
for (int i = 0; i < botonesTablero.length; i++) {
if (botonesTablero[i][y+largoTiro].getClientProperty("User").equals(0)) {
cont++;
}
}
System.out.println(6-(cont+1));
largoTiro=6-(cont+1);
}else{
boolean flag = true;
for (int i = 0; i < botonesTablero.length; i++) {
if (botonesTablero[i][8].getClientProperty("User").equals(0)) {
botonesTablero[i][8].setIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Roja.png")));
botonesTablero[i][8].setDisabledIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Roja.png")));
botonesTablero[i][8].putClientProperty("User", 1);
flag = !flag;
break;
}
}
if (flag) {
for (int i = 0; i < botonesTablero.length; i++) {
if (botonesTablero[i][9].getClientProperty("User").equals(0)) {
botonesTablero[i][9].setIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Roja.png")));
botonesTablero[i][9].setDisabledIcon(new ImageIcon(PrincipalVista.class.getResource("/Img/Roja.png")));
botonesTablero[i][9].putClientProperty("User", 1);
flag = !flag;
break;
}
}
}
int cont = 0;
for (int i = 0; i < botonesTablero.length; i++) {
if (botonesTablero[i][8].getClientProperty("User").equals(0)) {
cont++;
}
}
for (int i = 0; i < botonesTablero.length; i++) {
if (botonesTablero[i][9].getClientProperty("User").equals(0)) {
cont++;
}
}
System.out.println(12-(cont+1));
largoTiro=12-(cont+1);
}
}
/**
* Metodo Main que inicia el juego
* @param args
*/
public static void main(String[] args) {
@SuppressWarnings("unused")
PrincipalControlador p= new PrincipalControlador();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==ventanaInicial.getBtnIniciarPartida()){
actualizarTablero(cero.get(0).getEstado().getTablero());
partida(1);
ventanaInicial.getBtnIniciarPartida().setEnabled(false);
}
if(e.getSource()==ventanaInicial.getBtnReglas())
{
JOptionPane.showMessageDialog(ventanaInicial,
"1-) Se hace un primer movimiento (de una casilla) y el segundo movimiento se hace a partir\n"
+ "del número de piezas (propias y contrarias) que había en la franja donde se hizo el primer\n"
+ "movimiento (sin incluir la pieza que se mueve).");
JOptionPane.showMessageDialog(ventanaInicial,
"2-) Nunca pueden haber mas de 6 piezas en una franja (con excepción de las últimas franjas).");
JOptionPane.showMessageDialog(ventanaInicial, "3-) Si con el primer movimiento se alcanza una franja vacía, no habrá segundo movimiento.");
}
if(e.getSource()==ventanaInicial.getBtnInfo())
{
JOptionPane.showMessageDialog(ventanaInicial, "Juego implementado por: \n"
+ "Miguel Angel Askar Rodriguez - 201355842\n"
+ "Danny Fernando Cruz Arango - 201449949");
}
}
@Override
public void mouseClicked(MouseEvent e) {
if(botonesTablero[x][y].isEnabled()){
realizarTiro(x, y); //Se realiza el movimiento de la ficha.
int[][] tablero= new int[6][10];
for(int i= 0; i<6; i++)
{
for (int j = 0; j < 10; j++)
{
tablero[i][j]= (int)(botonesTablero[i][j].getClientProperty("User")); //Se obtiene el tablero actual desde la interfaz.
}
}
Nodo comprobacion= new Nodo(new Estado(tablero), -1, 0); //Se crea un nodo para saber si el juego se acabó
if(comprobacion.getEstado().juegoAcabado()) //Pregunta si el juego se acabó
{
if(comprobacion.getEstado().puntacionNegro()>comprobacion.getEstado().puntacionRojo())
{
JOptionPane.showMessageDialog(ventanaInicial, "Ganó el computador, una IA es superior a ti");
}
else
{
if(comprobacion.getEstado().puntacionNegro()<comprobacion.getEstado().puntacionRojo())
{
JOptionPane.showMessageDialog(ventanaInicial, "Ganaste... ¡¿ganaste?! ¿Qué clase de brujería es esta?");
}
else
{
JOptionPane.showMessageDialog(ventanaInicial, "Empate... se supone que esto no debía pasar");
}
}
}
contadorTurno++; //Se aumenta el contador para saber en cuál jugada va el usuario.
if(contadorTurno==1 && largoTiro==0) contadorTurno++; //Caso específico donde primera jugada cae en una columna vacía.
if(contadorTurno==2) //Si ya se hicieron los dos turnos.
{
ventanaInicial.actualizarTurno("Máquina"); //Se actualiza el turno.
activarDesactivarBotones(2); //Se desactivan los botones durante la jugada de la máquina.
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
jugarMaquina(); //Empieza el turno de la máquina con 0,5s de retraso. Para que las acciones anteriores puedan tener lugar.
}
},
500
);
}
}
}
/**
* Método que realiza la jugada de la máquina
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public void jugarMaquina()
{
int[][] tablero= new int[6][10];
for(int i= 0; i<6; i++)
{
for (int j = 0; j < 10; j++)
{
tablero[i][j]= (int)(botonesTablero[i][j].getClientProperty("User")); //Se obtiene el tablero actualizado desde la interfaz.
}
}
Nodo inicial= new Nodo(new Estado(tablero), -1, 0);
inicial.setPosicion(0); //Se actualiza el nodo inicial con el nuevo tablero.
cero.set(0, inicial);
crearArbol(); //Se crea el árbol para conocer las posiblies jugadas.
Nodo decision= getPrimero().get(calcularDecisionMinMax()); //Se crea un nodo con el estado decidio a través de minimax.
actualizarTablero(decision.getEstado().getTablero()); //Se actualiza el tablero en la interfaz gráfica.
int[][] tableroComprobacion= new int[6][10];
//--------------------------Se comprueba si el juego terminó
for(int i= 0; i<6; i++)
{
for (int j = 0; j < 10; j++)
{
tableroComprobacion[i][j]= (int)(botonesTablero[i][j].getClientProperty("User"));
}
}
Nodo comprobacion= new Nodo(new Estado(tableroComprobacion), -1, 0);
if(comprobacion.getEstado().juegoAcabado())
{
if(comprobacion.getEstado().puntacionNegro()>comprobacion.getEstado().puntacionRojo())
{
JOptionPane.showMessageDialog(ventanaInicial, "Ganó el computador, una IA es superior a ti");
}
else
{
if(comprobacion.getEstado().puntacionNegro()<comprobacion.getEstado().puntacionRojo())
{
JOptionPane.showMessageDialog(ventanaInicial, "Ganaste... ¡¿ganaste?! ¿Qué clase de brujería es esta?");
}
else
{
JOptionPane.showMessageDialog(ventanaInicial, "Empate... se supone que esto no debía pasar");
}
}
}
//--------------------------Se comprueba si el juego terminó
primero= new Vector(0,1); //Se reinician los vectores donde se guardan los niveles del árbol.
segundo= new Vector(0,1);
tercero= new Vector(0,1);
contadorTurno= 0; //Se reinicia el contador de turno para el usuario.
largoTiro= 1; //Se determina que la primera jugada tendrá una posición de alcance.
ventanaInicial.actualizarTurno("Usuario"); //Se da paso al turno del usuario.
activarDesactivarBotones(1); //Se reactivan los botones para la interacción del usuario con Linja
}
@Override
public void mouseEntered(MouseEvent e) {
JButton btn = (JButton) (e.getSource());
x = (int)btn.getClientProperty("row");
y = (int)btn.getClientProperty("column");
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
/**
* Metodo get de la variable bare_field_name
* @return El valor actual de la variable cero
*/
public Vector<Nodo> getCero() {
return cero;
}
/**
* Metodo set de la variable bare_field_name
* @param cero El nuevo valor que sera asignado a la variable cero
*/
public void setCero(Vector<Nodo> cero) {
this.cero = cero;
}
/**
* Metodo get de la variable bare_field_name
* @return El valor actual de la variable primero
*/
public Vector<Nodo> getPrimero() {
return primero;
}
/**
* Metodo set de la variable bare_field_name
* @param primero El nuevo valor que sera asignado a la variable primero
*/
public void setPrimero(Vector<Nodo> primero) {
this.primero = primero;
}
/**
* Metodo get de la variable bare_field_name
* @return El valor actual de la variable segundo
*/
public Vector<Nodo> getSegundo() {
return segundo;
}
/**
* Metodo set de la variable bare_field_name
* @param segundo El nuevo valor que sera asignado a la variable segundo
*/
public void setSegundo(Vector<Nodo> segundo) {
this.segundo = segundo;
}
/**
* Metodo get de la variable bare_field_name
* @return El valor actual de la variable tercero
*/
public Vector<Nodo> getTercero() {
return tercero;
}
/**
* Metodo set de la variable bare_field_name
* @param tercero El nuevo valor que sera asignado a la variable tercero
*/
public void setTercero(Vector<Nodo> tercero) {
this.tercero = tercero;
}
/**
* Metodo get de la variable bare_field_name
* @return El valor actual de la variable botonesTablero
*/
public JButton[][] getBotonesTablero() {
return botonesTablero;
}
/**
* Metodo set de la variable bare_field_name
* @param botonesTablero El nuevo valor que sera asignado a la variable botonesTablero
*/
public void setBotonesTablero(JButton[][] botonesTablero) {
this.botonesTablero = botonesTablero;
}
/**
* Metodo get de la variable bare_field_name
* @return El valor actual de la variable ventanaInicial
*/
public PrincipalVista getVentanaInicial() {
return ventanaInicial;
}
/**
* Metodo set de la variable bare_field_name
* @param ventanaInicial El nuevo valor que sera asignado a la variable ventanaInicial
*/
public void setVentanaInicial(PrincipalVista ventanaInicial) {
this.ventanaInicial = ventanaInicial;
}
/**
* Metodo get de la variable bare_field_name
* @return El valor actual de la variable x
*/
public int getX() {
return x;
}
/**
* Metodo set de la variable bare_field_name
* @param x El nuevo valor que sera asignado a la variable x
*/
public void setX(int x) {
this.x = x;
}
/**
* Metodo get de la variable bare_field_name
* @return El valor actual de la variable y
*/
public int getY() {
return y;
}
/**
* Metodo set de la variable bare_field_name
* @param y El nuevo valor que sera asignado a la variable y
*/
public void setY(int y) {
this.y = y;
}
/**
* Metodo get de la variable bare_field_name
* @return El valor actual de la variable largoTiro
*/
public int getLargoTiro() {
return largoTiro;
}
/**
* Metodo set de la variable bare_field_name
* @param largoTiro El nuevo valor que sera asignado a la variable largoTiro
*/
public void setLargoTiro(int largoTiro) {
this.largoTiro = largoTiro;
}
/**
* Metodo get de la variable bare_field_name
* @return El valor actual de la variable contadorTurno
*/
public int getContadorTurno() {
return contadorTurno;
}
/**
* Metodo set de la variable bare_field_name
* @param contadorTurno El nuevo valor que sera asignado a la variable contadorTurno
*/
public void setContadorTurno(int contadorTurno) {
this.contadorTurno = contadorTurno;
}
}
|
/*
* Copyright(C)2021, FPT University
* Lab Java Web
*
* Record of change
* DATE VERSION AUTHOR DESCRIPTION
* 2021-06-23 1.0 Ducnxhe141626 First Implement
*/
package entity;
/**
* This class used to contain attribute and method getter, setter of ImagesOfGallery
*
* @author Xuan Duc
*/
public class ImagesOfGallery {
//Create attribute
private int id;
private String url;
private int id_gallery;
/**
* This method used to get id
*
* @return id is an <code>int</code>
*/
public int getId() {
return id;
}
/**
* This method used to set id
*
* @param id is an<code>int</code>
*/
public void setId(int id) {
this.id = id;
}
/**
* This method used to get url
*
* @return url is a <code>String</code>
*/
public String getUrl() {
return url;
}
/**
* This method used to set url
*
* @param url is a<code>String</code>
*/
public void setUrl(String url) {
this.url = url;
}
/**
* This method used to get id_gallery
*
* @return id_gallery is an <code>int</code>
*/
public int getId_gallery() {
return id_gallery;
}
/**
* This method used to set id_gallery
*
* @param id_gallery is an<code>int</code>
*/
public void setId_gallery(int id_gallery) {
this.id_gallery = id_gallery;
}
}
|
package de.raidcraft.skillsandeffects.pve.skills;
import com.sk89q.minecraft.util.commands.CommandContext;
import de.raidcraft.RaidCraft;
import de.raidcraft.skills.api.exceptions.CombatException;
import de.raidcraft.skills.api.hero.Hero;
import de.raidcraft.skills.api.persistance.SkillProperties;
import de.raidcraft.skills.api.profession.Profession;
import de.raidcraft.skills.api.skill.AbstractLevelableSkill;
import de.raidcraft.skills.api.skill.Skill;
import de.raidcraft.skills.api.skill.SkillInformation;
import de.raidcraft.skills.api.trigger.CommandTriggered;
import de.raidcraft.skills.tables.THeroSkill;
import de.raidcraft.skills.util.ConfigUtil;
import de.raidcraft.util.ItemUtils;
import lombok.Data;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Silthus
*/
@SkillInformation(
name = "Conjure",
description = "Materialisiert ein Item aus dem Nichts."
)
public class ConjureItem extends AbstractLevelableSkill implements CommandTriggered {
private final List<ConjuredItem> conjuredItems = new ArrayList<>();
private int minItems = 0;
private int maxItems = 1;
public ConjureItem(Hero hero, SkillProperties data, Profession profession, THeroSkill database) {
super(hero, data, profession, database);
}
@Override
public void load(ConfigurationSection data) {
minItems = data.getInt("min-items", 0);
maxItems = data.getInt("max-items", 1);
ConfigurationSection items = data.getConfigurationSection("items");
if (items == null) return;
for (String key : items.getKeys(false)) {
Material item = ItemUtils.getItem(key);
if (item == null) {
RaidCraft.LOGGER.warning("Unknown item " + item + " in skill config of " + getName());
continue;
}
ConfigurationSection section = data.getConfigurationSection("items." + key);
ConjuredItem conjuredItem = new ConjuredItem(item, section.getInt("amount", 1));
conjuredItem.setChance(section.getConfigurationSection("chance"));
conjuredItem.setExp(section.getInt("exp", 1));
conjuredItem.setRequiredLevel(section.getInt("level", 1));
conjuredItems.add(conjuredItem);
}
// randomize it even more
Collections.shuffle(conjuredItems);
}
@Override
public void runCommand(CommandContext args) throws CombatException {
int conjuredItemsCount = 0;
do {
for (ConjuredItem item : conjuredItems) {
if (item.getRequiredLevel() > getAttachedLevel().getLevel()) {
continue;
}
if (Math.random() < item.getChance(this)) {
ItemStack itemStack = new ItemStack(item.getMaterial(), item.getAmount());
Location location = getHolder().getEntity().getLocation();
location.getWorld().dropItemNaturally(location, itemStack);
getAttachedLevel().addExp(item.getExp());
conjuredItemsCount++;
}
if (conjuredItemsCount >= maxItems) {
break;
}
}
} while (conjuredItemsCount < minItems);
}
@Data
public static class ConjuredItem {
private final Material material;
private final int amount;
private ConfigurationSection chance;
private int requiredLevel;
private int exp;
public ConjuredItem(Material material, int amount) {
this.material = material;
this.amount = amount;
}
public double getChance(Skill skill) {
return ConfigUtil.getTotalValue(skill, chance);
}
}
}
|
package enthu_l;
class e_1037{
void methodA(){
System.out.println("base - MethodA");
}
}
class Sub extends e_1037{
public void methodA(){
System.out.println("sub - MethodA");
}
public void methodB(){
System.out.println("sub - MethodB");
}
public static void main(String args[]){
e_1037 b=new Sub(); //1
b.methodA(); //2
// b.methodB(); //3
}
}
|
package com.codingblocks.sprint1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.codingblocks.sprint1.R;
public class OnProgressActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_on_progress);
}
}
|
package servletsdemo;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Servlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//This logic handles a get request from a client
thisIsMe me = new thisIsMe("Mariah");
//Sending the response to view.jsp
response.sendRedirect("view.jsp");
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//This logic is to handle updating database
}
}
|
package com.qihoo.finance.chronus.metadata.api.user.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.qihoo.finance.chronus.metadata.api.common.Entity;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import java.util.Date;
import java.util.List;
/**
* @author chenxiyu
* @date 2019/10/21
*/
@Getter
@Setter
public class UserEntity extends Entity {
@Id
private String id;
private String userNo;
private String name;
private String pwd;
/**
* 以,分割开组别
*/
private String group;
private String roleNo;
private String email;
private String state;
@Transient
private String token;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date dateCreated;
private String createdBy = "sys";
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date dateUpdated;
private String updatedBy = "sys";
@Transient
private String[] groups;
@Transient
private Integer pageSize;
@Transient
private Integer pageNum;
}
|
package com.tencent.mm.app.plugin;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import com.tencent.mm.app.plugin.URISpanHandlerSet.a;
import com.tencent.mm.bg.d;
import com.tencent.mm.pluginsdk.s;
import com.tencent.mm.pluginsdk.ui.applet.m;
import com.tencent.mm.pluginsdk.ui.d.g;
import com.tencent.mm.sdk.platformtools.x;
@a
class URISpanHandlerSet$ScanQrCodeUriSpanHandler extends URISpanHandlerSet$BaseUriSpanHandler {
final /* synthetic */ URISpanHandlerSet bAt;
URISpanHandlerSet$ScanQrCodeUriSpanHandler(URISpanHandlerSet uRISpanHandlerSet) {
this.bAt = uRISpanHandlerSet;
super(uRISpanHandlerSet);
}
final m db(String str) {
return null;
}
final int[] vB() {
return new int[0];
}
final boolean a(m mVar, g gVar) {
return false;
}
final boolean a(String str, boolean z, s sVar, Bundle bundle) {
boolean z2 = false;
if (!str.equals("weixin://scanqrcode/")) {
return false;
}
if (z) {
Intent intent = new Intent();
intent.putExtra("BaseScanUI_select_scan_mode", 1);
if (bundle != null && bundle.getInt("fromScene") == 100) {
z2 = true;
}
if (!z2) {
intent.addFlags(67108864);
}
if (URISpanHandlerSet.a(this.bAt) instanceof Service) {
intent.addFlags(268435456);
}
if (z2) {
d.b(URISpanHandlerSet.a(this.bAt), "scanner", ".ui.SingleTopScanUI", intent);
return true;
}
d.b(URISpanHandlerSet.a(this.bAt), "scanner", ".ui.BaseScanUI", intent);
return true;
}
x.e("MicroMsg.URISpanHandlerSet", "jumpToActivity, scan qrcode permission fail");
return true;
}
}
|
/*
* UniTime 3.2 - 3.5 (University Timetabling Application)
* Copyright (C) 2008 - 2013, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.model;
import java.util.List;
import org.hibernate.criterion.Order;
import org.unitime.timetable.model.base.BaseOfferingConsentType;
import org.unitime.timetable.model.dao.OfferingConsentTypeDAO;
/**
* @author Tomas Muller
*/
public class OfferingConsentType extends BaseOfferingConsentType {
private static final long serialVersionUID = 1L;
/*[CONSTRUCTOR MARKER BEGIN]*/
public OfferingConsentType () {
super();
}
/**
* Constructor for primary key
*/
public OfferingConsentType (Long uniqueId) {
super(uniqueId);
}
/*[CONSTRUCTOR MARKER END]*/
/** Request attribute name for available consent typess **/
public static String CONSENT_TYPE_ATTR_NAME = "consentTypeList";
/**
* Retrieves all consent types in the database
* ordered by column label
* @return List of ConsentType objects
*/
public static List<OfferingConsentType> getConsentTypeList() {
return OfferingConsentTypeDAO.getInstance().findAll(Order.asc("label"));
}
public static OfferingConsentType getOfferingConsentTypeForReference(String referenceString) {
if (referenceString == null || referenceString.isEmpty()) return null;
return (OfferingConsentType)OfferingConsentTypeDAO.getInstance().getSession().createQuery(
"from OfferingConsentType where reference = :reference")
.setString("reference", referenceString).setMaxResults(1).setCacheable(true).uniqueResult();
}
}
|
package xyz.maksimenko.iqbuzztt;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "places")
public class Place {
@Id
@Column(name = "placeid")
@GenericGenerator(name="autoincrement",strategy="increment")
@GeneratedValue(generator="autoincrement")
protected int placeId;
@Column(name = "comfclass")
/* 0 - cheap
* 1 - middle
2 - lux */
protected byte comfClass;
@Column(name = "price")
protected short price;
@Column(name = "row")
protected byte row;
@Column(name = "seat")
protected byte seat;
@OneToMany(fetch = FetchType.EAGER)
@Cascade(CascadeType.ALL)
@JoinColumn(name="placeid", referencedColumnName="placeid")
protected List<Ticket> tickets;
//for displaying type of seat on map
@Transient
protected String cssClass;
public int getPlaceId() {
return placeId;
}
public void setPlaceId(int placeId) {
this.placeId = placeId;
}
public short getPrice() {
return price;
}
public void setPrice(short price) {
this.price = price;
}
public byte getRow() {
return row;
}
public void setRow(byte row) {
this.row = row;
}
public byte getColumn() {
return seat;
}
public void setColumn(byte column) {
this.seat = column;
}
public List<Ticket> getTickets() {
return tickets;
}
public void setTickets(List<Ticket> ticket) {
this.tickets = ticket;
}
public byte getComfClass() {
return comfClass;
}
public void setComfClass(byte comfClass) {
this.comfClass = comfClass;
}
public byte getSeat() {
return seat;
}
public void setSeat(byte seat) {
this.seat = seat;
}
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
public String getCssClass() {
return cssClass;
}
}
|
package UnitTests;
import java.awt.Color;
import Renderer.ImageWriter;
import org.junit.Test;
public class ImageWriterTest {
@Test
public void test() {
ImageWriter imageWriter=new ImageWriter("ImageTest", 500,500,10,10);
for(int i=0;i<imageWriter.getHeight();i++)
{
for(int j=0;j<imageWriter.getWidth();j++)
{
if(i%50==0 || j%50==0)
imageWriter.writePixel(i, j, new Color(255,255,255));
}
}
imageWriter.writeToImage();
}
}
|
package com.tencent.mm.plugin.clean.ui.newui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class CleanMsgUI$4 implements OnMenuItemClickListener {
final /* synthetic */ CleanMsgUI hTx;
CleanMsgUI$4(CleanMsgUI cleanMsgUI) {
this.hTx = cleanMsgUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
CleanMsgUI.a(this.hTx);
return false;
}
}
|
package animatronics.api;
import animatronics.api.misc.Vector3;
import net.minecraft.item.ItemStack;
public interface IItemBlockOutline {
/**
* @param stack Stack the player holds.
* @return Outline draw coordinates.
*/
public Vector3 getBindingCoordinates(ItemStack stack);
}
|
package Tienda;
import java.time.LocalDate;
import java.time.Month;
import java.util.Calendar;
import java.util.Scanner;
public class Main {
public static Fecha f1 = new Fecha();
public static Scanner in = new Scanner(System.in);
public static void DefinirFecha(){
f1.setDia(20);
f1.setMes(8);
f1.setAnio(2020);
}
public static void Adelantar(){
int diaActual = f1.getDia();
int mesActual = f1.getMes();
int anioActual = f1.getAnio();
Calendar oFecha = Calendar.getInstance();
oFecha.set(anioActual, mesActual, diaActual);
oFecha.add(Calendar.DAY_OF_MONTH, f1.getDia());
oFecha.add(Calendar.MONTH, f1.getMes());
oFecha.add(Calendar.YEAR, f1.getAnio());
f1.setAnio(oFecha.get(Calendar.YEAR));
f1.setMes(oFecha.get(Calendar.MONTH));
f1.setDia(oFecha.get(Calendar.DAY_OF_MONTH)+5);
}
public static String ImprimirFecha(){
return "\nDia: "+f1.getDia()+
"\nMes: "+f1.getMes()+
"\nAnio: "+f1.getAnio();
}
public static void main(String[] args) {
Producto p1 = new Producto();
LocalDate date = LocalDate.of(2020, 8, 7);
LocalDate newDate = date.plusDays(10);
char opc = 0;
String respuesta;
p1.setIVA(0.09f);
p1.setPrecio(5.0f);
do{
System.out.print("\nInserte nombre del Producto: "); p1.setNombreProducto(in.next());
System.out.println("\n\nGenerando codigo del Producto...");
System.out.println("\nCodigo de "+p1.getNombreProducto()+" es: "+p1.codigoProducto());
System.out.println("Fecha de Elaboracion "+p1.getNombreProducto()+" es: ");
if(opc == 's' || opc == 'S'){
System.out.println(newDate);
}
else{
System.out.println(date);
}
System.out.println("\n\nEl IVA implementado por el gobierno es: "+p1.getIVA());
System.out.println("\n\nMostrando el Precio: ");
System.out.println("\nPrecio sin IVA de "+p1.getNombreProducto() +" es: "+p1.getPrecio());
System.out.println("\nPrecio Total de "+p1.getNombreProducto()+" es: "+p1.precioTotal());
System.out.print("\n\nDesea comprar este Producto: "+p1.getNombreProducto()+" ?(si/no)"); respuesta = in.next();
if("si".equals(respuesta)){
System.out.println("\nUsted ha comprado el Producto "+p1.getNombreProducto());
}
else{
System.out.println("\nUsted ha decidido no comprar el Producto "+p1.getNombreProducto());
}
System.out.print("\n\nDesea Insertar otro Producto? (s/n): "); opc = in.next().charAt(0);
}while(opc == 's' || opc == 'S');
}
}
|
package org.newdawn.slick.tests;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Color;
import org.newdawn.slick.Game;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Circle;
import org.newdawn.slick.geom.Ellipse;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.geom.RoundedRectangle;
import org.newdawn.slick.geom.Shape;
import org.newdawn.slick.geom.Transform;
import org.newdawn.slick.opengl.renderer.Renderer;
public class GeomTest extends BasicGame {
private Shape rect = (Shape)new Rectangle(100.0F, 100.0F, 100.0F, 100.0F);
private Shape circle = (Shape)new Circle(500.0F, 200.0F, 50.0F);
private Shape rect1 = (new Rectangle(150.0F, 120.0F, 50.0F, 100.0F)).transform(Transform.createTranslateTransform(50.0F, 50.0F));
private Shape rect2 = (new Rectangle(310.0F, 210.0F, 50.0F, 100.0F)).transform(
Transform.createRotateTransform((float)Math.toRadians(45.0D), 335.0F, 260.0F));
private Shape circle1 = (Shape)new Circle(150.0F, 90.0F, 30.0F);
private Shape circle2 = (Shape)new Circle(310.0F, 110.0F, 70.0F);
private Shape circle3 = (Shape)new Ellipse(510.0F, 150.0F, 70.0F, 70.0F);
private Shape circle4 = (new Ellipse(510.0F, 350.0F, 30.0F, 30.0F)).transform(
Transform.createTranslateTransform(-510.0F, -350.0F)).transform(
Transform.createScaleTransform(2.0F, 2.0F)).transform(
Transform.createTranslateTransform(510.0F, 350.0F));
private Shape roundRect = (Shape)new RoundedRectangle(50.0F, 175.0F, 100.0F, 100.0F, 20.0F);
private Shape roundRect2 = (Shape)new RoundedRectangle(50.0F, 280.0F, 50.0F, 50.0F, 20.0F, 20, 5);
public GeomTest() {
super("Geom Test");
}
public void init(GameContainer container) throws SlickException {}
public void render(GameContainer container, Graphics g) {
g.setColor(Color.white);
g.drawString("Red indicates a collision, green indicates no collision", 50.0F, 420.0F);
g.drawString("White are the targets", 50.0F, 435.0F);
g.pushTransform();
g.translate(100.0F, 100.0F);
g.pushTransform();
g.translate(-50.0F, -50.0F);
g.scale(10.0F, 10.0F);
g.setColor(Color.red);
g.fillRect(0.0F, 0.0F, 5.0F, 5.0F);
g.setColor(Color.white);
g.drawRect(0.0F, 0.0F, 5.0F, 5.0F);
g.popTransform();
g.setColor(Color.green);
g.fillRect(20.0F, 20.0F, 50.0F, 50.0F);
g.popTransform();
g.setColor(Color.white);
g.draw(this.rect);
g.draw(this.circle);
g.setColor(this.rect1.intersects(this.rect) ? Color.red : Color.green);
g.draw(this.rect1);
g.setColor(this.rect2.intersects(this.rect) ? Color.red : Color.green);
g.draw(this.rect2);
g.setColor(this.roundRect.intersects(this.rect) ? Color.red : Color.green);
g.draw(this.roundRect);
g.setColor(this.circle1.intersects(this.rect) ? Color.red : Color.green);
g.draw(this.circle1);
g.setColor(this.circle2.intersects(this.rect) ? Color.red : Color.green);
g.draw(this.circle2);
g.setColor(this.circle3.intersects(this.circle) ? Color.red : Color.green);
g.fill(this.circle3);
g.setColor(this.circle4.intersects(this.circle) ? Color.red : Color.green);
g.draw(this.circle4);
g.fill(this.roundRect2);
g.setColor(Color.blue);
g.draw(this.roundRect2);
g.setColor(Color.blue);
g.draw((Shape)new Circle(100.0F, 100.0F, 50.0F));
g.drawRect(50.0F, 50.0F, 100.0F, 100.0F);
}
public void update(GameContainer container, int delta) {}
public void keyPressed(int key, char c) {
if (key == 1)
System.exit(0);
}
public static void main(String[] argv) {
try {
Renderer.setRenderer(2);
AppGameContainer container = new AppGameContainer((Game)new GeomTest());
container.setDisplayMode(800, 600, false);
container.start();
} catch (SlickException e) {
e.printStackTrace();
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\tests\GeomTest.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.tencent.mm.plugin.boots;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.boots.a.a;
import com.tencent.mm.plugin.boots.a.c;
import com.tencent.mm.plugin.boots.a.e;
import java.util.List;
public final class b implements c {
public final void nd(int i) {
if (((e) g.n(e.class)).getTinkerLogic() != null) {
((e) g.n(e.class)).getTinkerLogic().c(i, false, 0);
}
}
public final void ch(int i, int i2) {
if (((e) g.n(e.class)).getTinkerLogic() != null) {
((e) g.n(e.class)).getTinkerLogic().c(i, true, i2);
}
}
public final List<a> aua() {
if (((e) g.n(e.class)).getTinkerLogic() != null) {
return ((e) g.n(e.class)).getTinkerLogic().aua();
}
return null;
}
}
|
package com.qihoo.finance.chronus.core.task.impl;
import com.qihoo.finance.chronus.core.task.TaskItemService;
import com.qihoo.finance.chronus.metadata.api.task.dao.TaskItemDao;
import com.qihoo.finance.chronus.metadata.api.task.entity.TaskItemEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Slf4j
@Service("taskItemService")
public class TaskItemServiceImpl implements TaskItemService {
@Resource
private TaskItemDao taskItemDao;
@Override
public TaskItemEntity getTaskItem(String taskItemId) {
return taskItemDao.getTaskItem(taskItemId);
}
@Override
public List<TaskItemEntity> getTaskItemList(String taskName) {
return taskItemDao.getTaskItemList(taskName);
}
@Override
public void create(TaskItemEntity taskItemEntity) {
taskItemDao.create(taskItemEntity);
}
@Override
public void delete(TaskItemEntity taskItemEntity) {
taskItemDao.delete(taskItemEntity);
}
@Override
public void deleteByTaskItemInfo(TaskItemEntity taskItemEntity) {
taskItemDao.deleteByTaskItemInfo(taskItemEntity);
}
@Override
public List<TaskItemEntity> selectAllTaskItem() {
return taskItemDao.selectAllTaskItem();
}
@Override
public List<TaskItemEntity> selectTaskItemByCluster(String cluster) {
return taskItemDao.selectTaskItemByCluster(cluster);
}
@Override
public void update(TaskItemEntity taskItemEntity) {
taskItemDao.update(taskItemEntity);
}
@Override
public boolean restartLock(TaskItemEntity taskItemEntity) {
return taskItemDao.restartLock(taskItemEntity);
}
}
|
package Controllers;
import backend.Database.PersonGatewayDB;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.ArrayList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import backend.model.*;
import backend.services.*;
import org.springframework.http.ResponseEntity;
import javax.swing.text.View;
public class LoginController implements Initializable {
private static final Logger logger = LogManager.getLogger(ListViewController.class);
String name, name2;
boolean test, test2;
@FXML
private PasswordField txt1;
@FXML
private TextField txt2;
/**
* controller for main and makes sure user inputs data
**/
//take you to the "ListView" pane.
@FXML
public void handle1(ActionEvent event) throws IOException {
String username = txt2.getText();
String password = txt1.getText();
try{
SessionGateway session = new SessionGateway();
String tok = session.loginVerification(username,password);
if (tok.equals("bad")){
throw new Exception();
}else{
ViewSwitcher.getInstance().sessionID(tok);
logger.info("<{}>LOGGED IN", txt2.getText());
ViewSwitcher.globalAction = event;
System.out.println("BEFOREEEEEEEEEEEEEEEEEEEEEEEE");
ViewSwitcher.getInstance().switchView(ViewType.ListViewController);
System.out.println("AFTERRRRRRRRRRRRRRRRRRRRRRRRRR");
}
}catch (Exception e){
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setContentText("Not able to authenticate.\n Please try again.");
txt1.clear();
txt2.clear();
alert.showAndWait();
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
}
}
|
package com.NLPProject;
/**
* NLP Project Part 2
* Use this as the main class for your project.
* Implement the logic to generate the SQL query and the query answer.
* Create additional methods, variables, and classes as needed.
*
*/
import java.util.Scanner;
public class CS421_Project2
{
public static String currentQuery = new String();
public static String sqlQuery = null;
public static String answer = "";
public static void main(String[] args)
{
System.out.println("Welcome! This is MiniWatson.");
System.out.println("Please ask a question. Type 'q' when finished.");
System.out.println();
String input;
Scanner keyboard = new Scanner(System.in);
do{
input = keyboard.nextLine().trim();
if(!input.equalsIgnoreCase("q")){
sqlQuery = "";
currentQuery = input;
System.out.println("<QUERY>\n" + currentQuery + "\n");
QueryBuilderPrint.getAnswer(currentQuery); //Question Processing.
printSQL();
printAnswer();
System.out.println();
}
}while(!input.equalsIgnoreCase("q"));
keyboard.close();
System.out.println("Goodbye.");
}
public static void printSQL(){
System.out.println("\n<SQL>\n" + sqlQuery);
}
public static void printAnswer(){
System.out.println("\n<ANSWER>\n" + answer);
}
}
|
package com.dazhi.config;
import com.dazhi.naming.api.config.ConfigService;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health.Builder;
public class NacosConfigHealthIndicator extends AbstractHealthIndicator {
// private final ConfigService configService;
public NacosConfigHealthIndicator(ConfigService configService) {
// this.configService = configService;
}
protected void doHealthCheck(Builder builder) throws Exception {
// String status = this.configService.getServerStatus();
String status = "UP";
builder.status(status);
byte var4 = -1;
switch(status.hashCode()) {
case 2715:
if (status.equals("UP")) {
var4 = 0;
}
break;
case 2104482:
if (status.equals("DOWN")) {
var4 = 1;
}
}
switch(var4) {
case 0:
builder.up();
break;
case 1:
builder.down();
break;
default:
builder.unknown();
}
}
}
|
package kz.kbtu.auth.main;
import kz.kbtu.auth.base.Employee;
import kz.kbtu.communication.order.Order;
import kz.kbtu.communication.order.OrderStatus;
import kz.kbtu.communication.order.SendingOrders;
import kz.kbtu.study.course.Course;
import kz.kbtu.study.course.CourseStatus;
import kz.kbtu.study.throwable.CreditOverflow;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class ORManager extends Employee implements SendingOrders, Serializable {
public ORManager(int salary, String login, String firstName, String lastName) {
super(salary, login, firstName, lastName);
}
public Course createCourse(String name, int creditNumber, Teacher teacher) {
Course course = new Course(name, creditNumber, teacher);
teacher.addCourse(course);
return course;
}
public void offerCourse(Course course, List<Student> students) throws CreditOverflow {
for (Student student: students) {
course.addStudent(student);
course.updateStatus(student.getLogin(), CourseStatus.FUTURE);
student.addCourse(course);
}
}
@Override
public Order sendOrder(String title, String text, Executor executor) {
Date timestamp = Calendar.getInstance().getTime();
Order order = new Order(OrderStatus.NEW, title, text, this, timestamp);
executor.addOrder(order);
return order;
}
@Override
public String toString() {
return String.format("ORManager: { %s }", super.toString());
}
}
|
package com.chuxin.family.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import com.chuxin.family.global.CxGlobalParams;
public class CxStartUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (TextUtils.equals(intent.getAction(), "RK_ALERM_NOTIFY")) {
new AlarmProcessor(context, intent.getStringExtra("uid"),
intent.getStringExtra("rid")).start();
return;
}
if (intent.getAction().equals("WAKE_UP")) {
Intent rkService = new Intent(context, CxBackgroundService.class);
context.startService(rkService);
return;
}
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
Intent rkService = new Intent(context, CxBackgroundService.class);
rkService.putExtra("INIT", 3);
context.startService(rkService);
return;
}
}
//在此处理是担心service挂掉,提醒没有及时响应
class AlarmProcessor extends Thread{
private Context mContext;
private String mUerId; //该闹钟的用户ID
private String mRecordId; //闹钟本地记录ID
public AlarmProcessor(Context context, String uerId, String recordId){
this.mContext = context;
this.mUerId = uerId;
this.mRecordId = recordId;
}
@Override
public void run() {
if ( (null == mUerId) || (null == mRecordId)
|| (!TextUtils.equals(CxGlobalParams.getInstance().getUserId(), mUerId)) ) {
//异常(没有userid和recordId的情况属于异常)或与当前用户userId不匹配的情况不处理
return;
}
//调用提醒中的接口
// getc
// super.run();
}
}
}
|
package com.ss.android.ugc.aweme.miniapp.g;
import android.app.Application;
import android.content.Context;
import com.ss.android.ugc.aweme.miniapp.f.a;
import com.ss.android.ugc.aweme.miniapp.f.a.b;
import com.ss.android.ugc.aweme.miniapp.f.a.c;
import com.ss.android.ugc.aweme.miniapp.f.a.d;
import com.ss.android.ugc.aweme.miniapp.f.a.e;
import com.ss.android.ugc.aweme.miniapp.f.b;
import com.ss.android.ugc.aweme.miniapp.f.c;
import com.ss.android.ugc.aweme.miniapp.f.d;
import com.ss.android.ugc.aweme.miniapp.f.e;
import com.ss.android.ugc.aweme.miniapp.f.f;
import com.ss.android.ugc.aweme.miniapp.f.h;
import com.ss.android.ugc.aweme.miniapp.f.i;
import com.tt.miniapphost.AppbrandContext;
import com.tt.miniapphost.process.handler.IAsyncHostDataHandler;
import com.tt.miniapphost.process.handler.ISyncHostDataHandler;
import com.tt.option.j.a;
import java.util.ArrayList;
import java.util.List;
public class g extends a {
public List<IAsyncHostDataHandler> createAsyncHostDataHandlerList() {
ArrayList<e> arrayList = new ArrayList();
Application application = AppbrandContext.getInst().getApplicationContext();
arrayList.add(new e());
arrayList.add(new b((Context)application));
arrayList.add(new i());
arrayList.add(new ae());
return (List)arrayList;
}
public List<ISyncHostDataHandler> createSyncHostDataHandlerList() {
ArrayList<f> arrayList = new ArrayList();
AppbrandContext.getInst().getApplicationContext();
arrayList.add(new f());
arrayList.add(new d());
arrayList.add(new a());
arrayList.add(new c());
arrayList.add(new e());
arrayList.add(new h());
arrayList.add(new d());
arrayList.add(new c());
arrayList.add(new b());
return (List)arrayList;
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\ss\androi\\ugc\aweme\miniapp\g\g.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.tencent.mm.plugin.clean.c;
class e$1 implements Runnable {
final /* synthetic */ e hRj;
e$1(e eVar) {
this.hRj = eVar;
}
public final void run() {
e.c(this.hRj).cq(e.a(this.hRj), e.b(this.hRj));
}
}
|
package com.facebook.react.uimanager.layoutanimation;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.IllegalViewOperationException;
import java.util.Map;
abstract class AbstractLayoutAnimation {
private static final Map<InterpolatorType, Interpolator> INTERPOLATOR = MapBuilder.of(InterpolatorType.LINEAR, new LinearInterpolator(), InterpolatorType.EASE_IN, new AccelerateInterpolator(), InterpolatorType.EASE_OUT, new DecelerateInterpolator(), InterpolatorType.EASE_IN_EASE_OUT, new AccelerateDecelerateInterpolator(), InterpolatorType.SPRING, new SimpleSpringInterpolator());
protected AnimatedPropertyType mAnimatedProperty;
private int mDelayMs;
protected int mDurationMs;
private Interpolator mInterpolator;
private static Interpolator getInterpolator(InterpolatorType paramInterpolatorType) {
Interpolator interpolator = INTERPOLATOR.get(paramInterpolatorType);
if (interpolator != null)
return interpolator;
StringBuilder stringBuilder = new StringBuilder("Missing interpolator for type : ");
stringBuilder.append(paramInterpolatorType);
throw new IllegalArgumentException(stringBuilder.toString());
}
public final Animation createAnimation(View paramView, int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
if (!isValid())
return null;
Animation animation = createAnimationImpl(paramView, paramInt1, paramInt2, paramInt3, paramInt4);
if (animation != null) {
animation.setDuration((this.mDurationMs * 1));
animation.setStartOffset((this.mDelayMs * 1));
animation.setInterpolator(this.mInterpolator);
}
return animation;
}
abstract Animation createAnimationImpl(View paramView, int paramInt1, int paramInt2, int paramInt3, int paramInt4);
public void initializeFromConfig(ReadableMap paramReadableMap, int paramInt) {
AnimatedPropertyType animatedPropertyType;
if (paramReadableMap.hasKey("property")) {
animatedPropertyType = AnimatedPropertyType.fromString(paramReadableMap.getString("property"));
} else {
animatedPropertyType = null;
}
this.mAnimatedProperty = animatedPropertyType;
if (paramReadableMap.hasKey("duration"))
paramInt = paramReadableMap.getInt("duration");
this.mDurationMs = paramInt;
if (paramReadableMap.hasKey("delay")) {
paramInt = paramReadableMap.getInt("delay");
} else {
paramInt = 0;
}
this.mDelayMs = paramInt;
if (paramReadableMap.hasKey("type")) {
this.mInterpolator = getInterpolator(InterpolatorType.fromString(paramReadableMap.getString("type")));
if (isValid())
return;
StringBuilder stringBuilder = new StringBuilder("Invalid layout animation : ");
stringBuilder.append(paramReadableMap);
throw new IllegalViewOperationException(stringBuilder.toString());
}
throw new IllegalArgumentException("Missing interpolation type.");
}
abstract boolean isValid();
public void reset() {
this.mAnimatedProperty = null;
this.mDurationMs = 0;
this.mDelayMs = 0;
this.mInterpolator = null;
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\reac\\uimanager\layoutanimation\AbstractLayoutAnimation.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package ch.ubx.startlist.server;
import static org.junit.Assert.assertTrue;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
public class ErrorOutputTestHelperTest {
private static final Logger log = Logger.getLogger(ErrorOutputTestHelperTest.class.getName());
private final static ErrorOutputTestHelper errOutHelper = new ErrorOutputTestHelper();
@Before
public void setUp() throws Exception {
errOutHelper.setUp();
errOutHelper.setOutOutput(false);
}
@After
public void tearDown() throws Exception {
errOutHelper.tearDown();
}
//@Test
public void testSysErr() {
log.log(Level.INFO, "Test output");
assertTrue(errOutHelper.getSysErr(), errOutHelper.contains("Test output"));
assertTrue(errOutHelper.getSysErr(), errOutHelper.contains("Test output"));
assertTrue("First takeSysErr should get a not empty output", errOutHelper.takeSysErr().contains("Test output"));
assertTrue("Second takeSysErr should get a empty output", errOutHelper.takeSysErr().length() == 0);
for (int i = 0; i < 500; i++) {
log.log(Level.INFO, "Blablable-" + i);
assertTrue("ccc", errOutHelper.contains("Blablable-" + i));
}
}
}
|
package br.org.cni.cniws.services;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* The persistent class for the TB_CADASTRO database table.
*
*/
@XmlRootElement(name="dadosCnesDto")
public class DadosCnesDto {
private List<DadosCnes> dadosCnes;
public DadosCnesDto(List<DadosCnes> dadosCnes) {
super();
this.dadosCnes = dadosCnes;
}
public DadosCnesDto() {
super();
}
@XmlElement(nillable = false)
public List<DadosCnes> getDadosCnes() {
return dadosCnes;
}
public void setDadosCnes(List<DadosCnes> dadosCnes) {
this.dadosCnes = dadosCnes;
}
}
|
package distance3;
import java.awt.image.BufferedImage;
import org.ejml.data.DenseMatrix64F;
import boofcv.alg.distort.DistortImageOps;
import boofcv.alg.distort.ImageDistort;
import boofcv.alg.geo.PerspectiveOps;
import boofcv.alg.geo.RectifyImageOps;
import boofcv.alg.geo.rectify.RectifyCalibrated;
import boofcv.core.image.ConvertBufferedImage;
import boofcv.io.image.UtilImageIO;
import boofcv.struct.calib.StereoParameters;
import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.ImageUInt8;
import boofcv.struct.image.MultiSpectral;
import georegression.struct.se.Se3_F64;
public class RectifySaveImage {
/**
* Rektifikál és ment egy szteeo képpárt
* @param origLeft Left stereo image
* @param origRight Right stereo image
* @param param Stereo parameters
* @param outDir Output directory
*/
public static void recifySave(BufferedImage origLeft, BufferedImage origRight, StereoParameters param,
String outDir) {
// distorted images
MultiSpectral<ImageFloat32> distLeft = ConvertBufferedImage.convertFromMulti(origLeft, null, true,
ImageFloat32.class);
MultiSpectral<ImageFloat32> distRight = ConvertBufferedImage.convertFromMulti(origRight, null, true,
ImageFloat32.class);
// storage for undistorted + rectified images
MultiSpectral<ImageFloat32> rectLeft = new MultiSpectral<ImageFloat32>(ImageFloat32.class, distLeft.getWidth(),
distLeft.getHeight(), distLeft.getNumBands());
MultiSpectral<ImageFloat32> rectRight = new MultiSpectral<ImageFloat32>(ImageFloat32.class,
distRight.getWidth(), distRight.getHeight(), distRight.getNumBands());
// Compute rectification
RectifyCalibrated rectifyAlg = RectifyImageOps.createCalibrated();
Se3_F64 leftToRight = param.getRightToLeft().invert(null);
// original camera calibration matrices
DenseMatrix64F K1 = PerspectiveOps.calibrationMatrix(param.getLeft(), null);
DenseMatrix64F K2 = PerspectiveOps.calibrationMatrix(param.getRight(), null);
rectifyAlg.process(K1, new Se3_F64(), K2, leftToRight);
DenseMatrix64F rect1 = rectifyAlg.getRect1();
DenseMatrix64F rect2 = rectifyAlg.getRect2();
DenseMatrix64F rectK = rectifyAlg.getCalibrationMatrix();
RectifyImageOps.allInsideLeft(param.left, rect1, rect2, rectK);
ImageDistort<ImageFloat32, ImageFloat32> imageDistortLeft = RectifyImageOps.rectifyImage(param.getLeft(), rect1,
ImageFloat32.class);
ImageDistort<ImageFloat32, ImageFloat32> imageDistortRight = RectifyImageOps.rectifyImage(param.getRight(),
rect2, ImageFloat32.class);
DistortImageOps.distortMS(distLeft, rectLeft, imageDistortLeft);
DistortImageOps.distortMS(distRight, rectRight, imageDistortRight);
// convert for output
BufferedImage outLeft = ConvertBufferedImage.convertTo(rectLeft, null, true);
BufferedImage outRight = ConvertBufferedImage.convertTo(rectRight, null, true);
UtilImageIO.saveImage(outLeft, outDir+"rectImg1.ppm");
UtilImageIO.saveImage(outRight, outDir+"rectImg2.ppm");
}
public static RectifyCalibrated rectify(ImageFloat32 origLeft, ImageFloat32 origRight, StereoParameters param,
ImageFloat32 rectLeft, ImageFloat32 rectRight) {
// Compute rectification
RectifyCalibrated rectifyAlg = RectifyImageOps.createCalibrated();
Se3_F64 leftToRight = param.getRightToLeft().invert(null);
// original camera calibration matrices
DenseMatrix64F K1 = PerspectiveOps.calibrationMatrix(param.getLeft(), null);
DenseMatrix64F K2 = PerspectiveOps.calibrationMatrix(param.getRight(), null);
rectifyAlg.process(K1, new Se3_F64(), K2, leftToRight);
// rectification matrix for each image
DenseMatrix64F rect1 = rectifyAlg.getRect1();
DenseMatrix64F rect2 = rectifyAlg.getRect2();
// New calibration matrix,
DenseMatrix64F rectK = rectifyAlg.getCalibrationMatrix();
// Adjust the rectification to make the view area more useful
RectifyImageOps.allInsideLeft(param.left, rect1, rect2, rectK);
// undistorted and rectify images
ImageDistort<ImageFloat32, ImageFloat32> imageDistortLeft = RectifyImageOps.rectifyImage(param.getLeft(), rect1,
ImageFloat32.class);
ImageDistort<ImageFloat32, ImageFloat32> imageDistortRight = RectifyImageOps.rectifyImage(param.getRight(), rect2,
ImageFloat32.class);
imageDistortLeft.apply(origLeft, rectLeft);
imageDistortRight.apply(origRight, rectRight);
return rectifyAlg;
}
}
|
package com.tencent.appbrand.mmkv;
public enum c {
LevelDebug, LevelError, LevelInfo, LevelNone, LevelWarning;
static {
LevelError = new c("LevelError", 3);
LevelNone = new c("LevelNone", 4);
a = new c[] { LevelDebug, LevelInfo, LevelWarning, LevelError, LevelNone };
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tencent\appbrand\mmkv\c.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.mimi.mimigroup.ui.utility;
import android.app.Dialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Toast;
import com.mimi.mimigroup.R;
import com.mimi.mimigroup.api.APINet;
import com.mimi.mimigroup.api.APINetCallBack;
import com.mimi.mimigroup.api.SyncPost;
import com.mimi.mimigroup.app.AppSetting;
import com.mimi.mimigroup.base.BaseActivity;
import com.mimi.mimigroup.db.DBGimsHelper;
import com.mimi.mimigroup.model.DM_Tree;
import com.mimi.mimigroup.model.SM_ReportTech;
import com.mimi.mimigroup.model.SM_ReportTechActivity;
import com.mimi.mimigroup.model.SM_ReportTechCompetitor;
import com.mimi.mimigroup.model.SM_ReportTechDisease;
import com.mimi.mimigroup.model.SM_ReportTechMarket;
import com.mimi.mimigroup.ui.adapter.FragmentPagerTabAdapter;
import com.mimi.mimigroup.ui.custom.CustomBoldTextView;
import com.mimi.mimigroup.ui.custom.CustomTextView;
import com.mimi.mimigroup.utils.AppUtils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.FormBody;
import okhttp3.RequestBody;
public class ReportTechFormActivity extends BaseActivity {
@BindView(R.id.tabLayout)
TabLayout tabLayout;
@BindView(R.id.viewPager)
ViewPager viewPager;
FragmentPagerTabAdapter adapter;
@BindView(R.id.btnReportTechDetailAdd)
FloatingActionButton btnReportTechDetailAdd;
@BindView(R.id.btnReportTechDetailDel)
FloatingActionButton btnReportTechDetailDel;
public String getmReportTechID() {
return mReportTechID;
}
public String mReportTechID="";
public String getmPar_Symbol() {
return mPar_Symbol;
}
private String mPar_Symbol;
private String mAction="";
private DBGimsHelper mDB;
private boolean isSaved=false;
SM_ReportTech oReportTech;
List<SM_ReportTechMarket> oReportTechMarket;
List<SM_ReportTechDisease> oReportTechDisease;
List<SM_ReportTechCompetitor> oReportTechCompetitor;
List<SM_ReportTechActivity> oReportTechActivityThisWeek;
List<SM_ReportTechActivity> oReportTechActivityNextWeek;
ReportTechFormItemFragment ReportTechFragment;
ReportTechMarketItemFragment ReportTechMarketFragment;
ReportTechDiseaseItemFragment ReportTechDiseaseFragment;
ReportTechCompetitorItemFragment ReportTechCompetitorFragment;
ReportTechActivityThisWeekItemFragment ReportTechActivityThisWeekFragment;
ReportTechActivityNextWeekItemFragment ReportTechActivityNextWeekFragment;
public String getAction(){return this.mAction;}
public SM_ReportTech getoReportTech() {
return oReportTech;
}
public List<SM_ReportTechMarket> getoReportTechMarket() {
return oReportTechMarket;
}
public List<SM_ReportTechDisease> getoReportTechDisease() {
return oReportTechDisease;
}
public List<SM_ReportTechCompetitor> getoReportTechCompetitor() {
return oReportTechCompetitor;
}
public List<SM_ReportTechActivity> getoReportTechActivityThisWeek() {
return oReportTechActivityThisWeek;
}
public List<SM_ReportTechActivity> getoReportTechActivityNextWeek() {
return oReportTechActivityNextWeek;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_tech_form);
mDB=DBGimsHelper.getInstance(this);
adapter = new FragmentPagerTabAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
mReportTechID = getIntent().getStringExtra("ReportTechID");
mPar_Symbol = getIntent().getStringExtra("PAR_SYMBOL");
mAction=getIntent().getAction().toString();
if(mAction=="EDIT"){
oReportTech = mDB.getReportTechById(mReportTechID);
oReportTechMarket = mDB.getAllReportTechMarket(mReportTechID);
oReportTechDisease = mDB.getAllReportTechDisease(mReportTechID);
oReportTechCompetitor = mDB.getAllReportTechCompetitor(mReportTechID);
oReportTechActivityThisWeek = mDB.getAllReportTechActivity(mReportTechID, 0);
oReportTechActivityNextWeek = mDB.getAllReportTechActivity(mReportTechID, 1);
}else{
oReportTech = new SM_ReportTech();
oReportTechMarket = new ArrayList<>();
oReportTechDisease = new ArrayList<>();
oReportTechCompetitor= new ArrayList<>();
oReportTechActivityThisWeek = new ArrayList<>();
oReportTechActivityNextWeek = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String mReportDate = sdf.format(new Date());
String mRequestDate= AppUtils.DateAdd(mReportDate, 3, "yyyy-MM-dd");
SimpleDateFormat sdfOrderCode = new SimpleDateFormat("ddMMyy");
String mOrderCodeDMY = sdfOrderCode.format(new Date());
SimpleDateFormat sdfhhMMss = new SimpleDateFormat("hhmmss");
String mReportCodeHMS = sdfhhMMss.format(new Date());
String mReportCode=mPar_Symbol+'-'+mReportCodeHMS+'/'+mOrderCodeDMY;
oReportTech.setReportTechId(mReportTechID);
oReportTech.setReportCode(mReportCode);
oReportTech.setReportDate(mReportDate);
oReportTech.setIsStatus("0");
oReportTech.setPost(false);
}
btnReportTechDetailAdd.setVisibility(View.GONE);
btnReportTechDetailDel.setVisibility(View.GONE);
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
ReportTechFragment = new ReportTechFormItemFragment();
adapter.addFragment(ReportTechFragment, "BC Kỹ Thuật");
ReportTechMarketFragment = new ReportTechMarketItemFragment();
adapter.addFragment(ReportTechMarketFragment, "Thị Trường");
ReportTechDiseaseFragment = new ReportTechDiseaseItemFragment();
adapter.addFragment(ReportTechDiseaseFragment, "Dịch Bệnh");
ReportTechCompetitorFragment = new ReportTechCompetitorItemFragment();
adapter.addFragment(ReportTechCompetitorFragment, "Đối Thủ");
ReportTechActivityThisWeekFragment = new ReportTechActivityThisWeekItemFragment();
adapter.addFragment(ReportTechActivityThisWeekFragment, "Hoạt Động Trong Tuần");
ReportTechActivityNextWeekFragment = new ReportTechActivityNextWeekItemFragment();
adapter.addFragment(ReportTechActivityNextWeekFragment, "Hoạt Động Tuần Tới");
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if(tab.getPosition()==0){
btnReportTechDetailAdd.setVisibility(View.INVISIBLE);
btnReportTechDetailDel.setVisibility(View.INVISIBLE);
}else {
checkSaveWhenAddOrEdit();
btnReportTechDetailAdd.setVisibility(View.VISIBLE);
btnReportTechDetailDel.setVisibility(View.INVISIBLE);
btnReportTechDetailAdd.setTag("ADD");
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {}
@Override
public void onTabReselected(TabLayout.Tab tab) {}
});
}
},300);
}
public List<DM_Tree> getListTree(){
List<DM_Tree> lstTree=new ArrayList<DM_Tree>();
try{
lstTree=mDB.getAllTree();
}catch (Exception ex){}
return lstTree;
}
private void checkSaveWhenAddOrEdit(){
if(btnReportTechDetailAdd.getTag() != null && btnReportTechDetailAdd.getTag().equals("SAVE")){
final Dialog oDlg=new Dialog(this);
oDlg.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
oDlg.setContentView(R.layout.dialog_yesno);
oDlg.setTitle("");
CustomTextView dlgTitle=(CustomTextView) oDlg.findViewById(R.id.dlgTitle);
dlgTitle.setText("THÔNG BÁO");
CustomTextView dlgContent=(CustomTextView) oDlg.findViewById(R.id.dlgContent);
dlgContent.setText("Dữ liệu chưa cập nhật. Bạn có muốn lưu ?");
CustomBoldTextView btnYes=(CustomBoldTextView) oDlg.findViewById(R.id.dlgButtonYes);
CustomBoldTextView btnNo=(CustomBoldTextView) oDlg.findViewById(R.id.dlgButtonNo);
final Fragment currentFragment = adapter.getItem(viewPager.getCurrentItem());
btnYes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isSaved = false;
if(currentFragment instanceof ReportTechMarketItemFragment){
isSaved = ((ReportTechMarketItemFragment) currentFragment).onSaveReportTechMarket();
}else if(currentFragment instanceof ReportTechDiseaseItemFragment){
isSaved = ((ReportTechDiseaseItemFragment) currentFragment).onSaveReportTechDisease();
}else if(currentFragment instanceof ReportTechCompetitorItemFragment){
isSaved = ((ReportTechCompetitorItemFragment) currentFragment).onSaveReportTechCompetitor();
} else if(currentFragment instanceof ReportTechActivityThisWeekItemFragment){
isSaved = ((ReportTechActivityThisWeekItemFragment) currentFragment).onSaveReportTechActivity();
} else if(currentFragment instanceof ReportTechActivityNextWeekItemFragment){
isSaved = ((ReportTechActivityNextWeekItemFragment) currentFragment).onSaveReportTechActivity();
}
if(isSaved){
btnReportTechDetailAdd.setTag("ADD");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_add));
}else{
Toast.makeText(ReportTechFormActivity.this,"Dữ liệu không hợp lệ nên thông tin không lưu được..", Toast.LENGTH_SHORT).show();
if(currentFragment instanceof ReportTechMarketItemFragment){
((ReportTechMarketItemFragment) currentFragment).cancelSaveData();
}else if(currentFragment instanceof ReportTechDiseaseItemFragment){
((ReportTechDiseaseItemFragment) currentFragment).cancelSaveData();
}else if(currentFragment instanceof ReportTechCompetitorItemFragment){
((ReportTechCompetitorItemFragment) currentFragment).cancelSaveData();
} else if(currentFragment instanceof ReportTechActivityThisWeekItemFragment){
((ReportTechActivityThisWeekItemFragment) currentFragment).cancelSaveData();
} else if(currentFragment instanceof ReportTechActivityNextWeekItemFragment){
((ReportTechActivityNextWeekItemFragment) currentFragment).cancelSaveData();
}
btnReportTechDetailAdd.setTag("ADD");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_add));
}
oDlg.dismiss();
}
});
btnNo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(currentFragment instanceof ReportTechMarketItemFragment){
((ReportTechMarketItemFragment) currentFragment).cancelSaveData();
}else if(currentFragment instanceof ReportTechDiseaseItemFragment){
((ReportTechDiseaseItemFragment) currentFragment).cancelSaveData();
}else if(currentFragment instanceof ReportTechCompetitorItemFragment){
((ReportTechCompetitorItemFragment) currentFragment).cancelSaveData();
} else if(currentFragment instanceof ReportTechActivityThisWeekItemFragment){
((ReportTechActivityThisWeekItemFragment) currentFragment).cancelSaveData();
} else if(currentFragment instanceof ReportTechActivityNextWeekItemFragment){
((ReportTechActivityNextWeekItemFragment) currentFragment).cancelSaveData();
}
btnReportTechDetailAdd.setTag("ADD");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_add));
oDlg.dismiss();
return;
}
});
oDlg.show();
}
}
/*[TRANSFER DATA FOR FRAMGMENT]*/
public void setVisibleDetailDelete(boolean isVisible){
try {
if (isVisible) {
btnReportTechDetailDel.setVisibility(View.VISIBLE);
} else {
btnReportTechDetailDel.setVisibility(View.INVISIBLE);
}
}catch (Exception ex){}
}
public void setButtonEditStatus(boolean isEdit){
if(isEdit){
btnReportTechDetailAdd.setTag("EDIT");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_edit));
}else{
btnReportTechDetailAdd.setTag("ADD");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_add));
}
}
private void ReceiveDataFragment(){
//SAVE DETAIL
try{
if(btnReportTechDetailAdd.getTag()!=null && btnReportTechDetailAdd.getTag().toString().equalsIgnoreCase("SAVE")) {
onReportTechDetailAdd();
}
if(ReportTechFragment !=null) {
oReportTech = ReportTechFragment.getSMReportTech();
}
if(ReportTechMarketFragment!=null) {
oReportTechMarket = ReportTechMarketFragment.getListReportTechMarket();
}
if(ReportTechDiseaseFragment != null) {
oReportTechDisease = ReportTechDiseaseFragment.getListReportTechDisease();
}
if(ReportTechCompetitorFragment!=null) {
oReportTechCompetitor = ReportTechCompetitorFragment.getListReportTechCompetitor();
}
if(ReportTechActivityThisWeekFragment != null){
oReportTechActivityThisWeek = ReportTechActivityThisWeekFragment.getListReportTechActivityThisWeek();
}
if(ReportTechActivityNextWeekFragment != null){
oReportTechActivityNextWeek = ReportTechActivityNextWeekFragment.getListReportTechActivityNextWeek();
}
}catch (Exception ex){}
}
@Override
public void onBackPressed() {
if (!isSaved) {
final Dialog oDlg=new Dialog(this);
oDlg.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
oDlg.setContentView(R.layout.dialog_yesno);
oDlg.setTitle("");
CustomTextView dlgTitle=(CustomTextView) oDlg.findViewById(R.id.dlgTitle);
dlgTitle.setText("THÔNG BÁO");
CustomTextView dlgContent=(CustomTextView) oDlg.findViewById(R.id.dlgContent);
dlgContent.setText("Dữ liệu báo cáo kỹ thuật chưa cập nhật. Bạn có muốn bỏ qua ?");
CustomBoldTextView btnYes=(CustomBoldTextView) oDlg.findViewById(R.id.dlgButtonYes);
CustomBoldTextView btnNo=(CustomBoldTextView) oDlg.findViewById(R.id.dlgButtonNo);
btnYes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onExcuteBackPress();
oDlg.dismiss();
}
});
btnNo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
oDlg.dismiss();
return;
}
});
oDlg.show();
} else {
super.onBackPressed();
}
}
private void onExcuteBackPress(){
super.onBackPressed();
}
@OnClick(R.id.ivBack)
public void onBack(){
if (!isSaved) {
final Dialog oDlg=new Dialog(this);
oDlg.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
oDlg.setContentView(R.layout.dialog_yesno);
oDlg.setTitle("");
CustomTextView dlgTitle=(CustomTextView) oDlg.findViewById(R.id.dlgTitle);
dlgTitle.setText("THÔNG BÁO");
CustomTextView dlgContent=(CustomTextView) oDlg.findViewById(R.id.dlgContent);
dlgContent.setText("Dữ liệu báo cáo kỹ thuật chưa cập nhật. Bạn có muốn bỏ qua ?");
CustomBoldTextView btnYes=(CustomBoldTextView) oDlg.findViewById(R.id.dlgButtonYes);
CustomBoldTextView btnNo=(CustomBoldTextView) oDlg.findViewById(R.id.dlgButtonNo);
btnYes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onExcuteBackPress();
oDlg.dismiss();
}
});
btnNo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
oDlg.dismiss();
return;
}
});
oDlg.show();
return;
} else {
super.onBackPressed();
}
finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
@OnClick(R.id.btnReportTechDetailAdd)
public void onReportTechDetailAdd(){
final Fragment currentFragment = adapter.getItem(viewPager.getCurrentItem());
if(currentFragment instanceof ReportTechMarketItemFragment){
if(btnReportTechDetailAdd.getTag()!=null && btnReportTechDetailAdd.getTag().toString().equalsIgnoreCase("SAVE")){
if(((ReportTechMarketItemFragment) currentFragment).onSaveReportTechMarket()) {
btnReportTechDetailAdd.setTag("ADD");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_add));
}
}else if(btnReportTechDetailAdd.getTag()!=null && btnReportTechDetailAdd.getTag().toString().equalsIgnoreCase("EDIT")){
//CHI HIỂN THỊ BOX ĐỂ CẬP NHẬT
((ReportTechMarketItemFragment) currentFragment).onAddReportTechMarket(false);
btnReportTechDetailAdd.setTag("SAVE");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_accept));
}else {
//HIỂN THỊ BOX MỚI ĐỂ THÊM
((ReportTechMarketItemFragment) currentFragment).onAddReportTechMarket(true);
btnReportTechDetailAdd.setTag("SAVE");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_accept));
}
}else if(currentFragment instanceof ReportTechDiseaseItemFragment){
if(btnReportTechDetailAdd.getTag()!=null && btnReportTechDetailAdd.getTag().toString().equalsIgnoreCase("SAVE")){
if(((ReportTechDiseaseItemFragment) currentFragment).onSaveReportTechDisease()) {
btnReportTechDetailAdd.setTag("ADD");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_add));
}
}else if(btnReportTechDetailAdd.getTag()!=null && btnReportTechDetailAdd.getTag().toString().equalsIgnoreCase("EDIT")){
//CHI HIỂN THỊ BOX ĐỂ CẬP NHẬT
((ReportTechDiseaseItemFragment) currentFragment).onAddReportTechDisease(false);
btnReportTechDetailAdd.setTag("SAVE");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_accept));
}else {
//HIỂN THỊ BOX MỚI ĐỂ THÊM
((ReportTechDiseaseItemFragment) currentFragment).onAddReportTechDisease(true);
btnReportTechDetailAdd.setTag("SAVE");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_accept));
}
}
else if(currentFragment instanceof ReportTechCompetitorItemFragment){
if(btnReportTechDetailAdd.getTag()!=null && btnReportTechDetailAdd.getTag().toString().equalsIgnoreCase("SAVE")){
if(((ReportTechCompetitorItemFragment) currentFragment).onSaveReportTechCompetitor()) {
btnReportTechDetailAdd.setTag("ADD");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_add));
}
}else if(btnReportTechDetailAdd.getTag()!=null && btnReportTechDetailAdd.getTag().toString().equalsIgnoreCase("EDIT")){
//CHI HIỂN THỊ BOX ĐỂ CẬP NHẬT
((ReportTechCompetitorItemFragment) currentFragment).onAddReportTechCompetitor(false);
btnReportTechDetailAdd.setTag("SAVE");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_accept));
}else {
//HIỂN THỊ BOX MỚI ĐỂ THÊM
((ReportTechCompetitorItemFragment) currentFragment).onAddReportTechCompetitor(true);
btnReportTechDetailAdd.setTag("SAVE");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_accept));
}
} else if(currentFragment instanceof ReportTechActivityThisWeekItemFragment){
if(btnReportTechDetailAdd.getTag()!=null && btnReportTechDetailAdd.getTag().toString().equalsIgnoreCase("SAVE")){
if(((ReportTechActivityThisWeekItemFragment) currentFragment).onSaveReportTechActivity()) {
btnReportTechDetailAdd.setTag("ADD");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_add));
}
}else if(btnReportTechDetailAdd.getTag()!=null && btnReportTechDetailAdd.getTag().toString().equalsIgnoreCase("EDIT")){
//CHI HIỂN THỊ BOX ĐỂ CẬP NHẬT
((ReportTechActivityThisWeekItemFragment) currentFragment).onAddReportTechActivity(false);
btnReportTechDetailAdd.setTag("SAVE");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_accept));
}else {
//HIỂN THỊ BOX MỚI ĐỂ THÊM
((ReportTechActivityThisWeekItemFragment) currentFragment).onAddReportTechActivity(true);
btnReportTechDetailAdd.setTag("SAVE");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_accept));
}
} else if(currentFragment instanceof ReportTechActivityNextWeekItemFragment){
if(btnReportTechDetailAdd.getTag()!=null && btnReportTechDetailAdd.getTag().toString().equalsIgnoreCase("SAVE")){
if(((ReportTechActivityNextWeekItemFragment) currentFragment).onSaveReportTechActivity()) {
btnReportTechDetailAdd.setTag("ADD");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_add));
}
}else if(btnReportTechDetailAdd.getTag()!=null && btnReportTechDetailAdd.getTag().toString().equalsIgnoreCase("EDIT")){
//CHI HIỂN THỊ BOX ĐỂ CẬP NHẬT
((ReportTechActivityNextWeekItemFragment) currentFragment).onAddReportTechActivity(false);
btnReportTechDetailAdd.setTag("SAVE");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_accept));
}else {
//HIỂN THỊ BOX MỚI ĐỂ THÊM
((ReportTechActivityNextWeekItemFragment) currentFragment).onAddReportTechActivity(true);
btnReportTechDetailAdd.setTag("SAVE");
btnReportTechDetailAdd.setImageDrawable(getResources().getDrawable(R.drawable.tiva_accept));
}
}
}
@OnClick(R.id.btnReportTechDetailDel)
public void onReportTechMarketDel(){
final Fragment currentFragment = adapter.getItem(viewPager.getCurrentItem());
if(currentFragment instanceof ReportTechMarketItemFragment){
((ReportTechMarketItemFragment) currentFragment).onDeletedReportTechMarket();
}else if(currentFragment instanceof ReportTechDiseaseItemFragment){
((ReportTechDiseaseItemFragment) currentFragment).onDeletedReportTechDisease();
}else if(currentFragment instanceof ReportTechCompetitorItemFragment){
((ReportTechCompetitorItemFragment) currentFragment).onDeletedReportTechCompetitor();
} else if(currentFragment instanceof ReportTechActivityThisWeekItemFragment){
((ReportTechActivityThisWeekItemFragment) currentFragment).onDeletedReportTechActivity();
} else if(currentFragment instanceof ReportTechActivityNextWeekItemFragment){
((ReportTechActivityNextWeekItemFragment) currentFragment).onDeletedReportTechActivity();
}
}
@OnClick(R.id.btnSaveReportTech)
public void onSaveOnly(){
ReceiveDataFragment();
if(oReportTech==null || oReportTech.getReportTechId().isEmpty()){
Toast.makeText(this, "Không khởi tạo được hoặc chưa nhập báo cáo kỹ thuật..", Toast.LENGTH_SHORT).show();
return;
}
/*if(oReportTechMarket==null || oReportTechMarket.size()<=0){
Toast.makeText(this, "Không khởi tạo được hoặc chưa nhập báo cáo thị trường..", Toast.LENGTH_SHORT).show();
return;
}
if(oReportTechCompetitor==null || oReportTechCompetitor.size()<=0){
Toast.makeText(this, "Không khởi tạo được hoặc chưa nhập báo cáo đối thủ..", Toast.LENGTH_SHORT).show();
return;
}
if(oReportTechActivityThisWeek==null || oReportTechActivityThisWeek.size()<=0){
Toast.makeText(this, "Không khởi tạo được hoặc chưa nhập báo cáo trong tuần trường..", Toast.LENGTH_SHORT).show();
return;
}*/
mDB.addReportTech(oReportTech);
if(mDB.getSizeReportTech(oReportTech.getReportTechId())>0) {
mDB.delReportTechDetail(oReportTech.getReportTechId());
// Save market report
if(oReportTechMarket != null && oReportTechMarket.size() >0){
for (SM_ReportTechMarket oDetail : oReportTechMarket) {
mDB.addReportTechMarket(oDetail);
}
}
// Save disease report
if(oReportTechDisease != null && oReportTechDisease.size() >0){
for (SM_ReportTechDisease oDetail : oReportTechDisease) {
mDB.addReportTechDisease(oDetail);
}
}
// Save competitor report
if(oReportTechCompetitor != null && oReportTechCompetitor.size() > 0){
for (SM_ReportTechCompetitor oDetail : oReportTechCompetitor) {
mDB.addReportTechCompetitor(oDetail);
}
}
// Save activity this week
if(oReportTechActivityThisWeek != null && oReportTechActivityThisWeek.size() > 0){
for (SM_ReportTechActivity oDetail : oReportTechActivityThisWeek) {
mDB.addReportTechActivity(oDetail);
}
}
// Save activity next week
if(oReportTechActivityNextWeek != null && oReportTechActivityNextWeek.size() >0){
for (SM_ReportTechActivity oDetail : oReportTechActivityNextWeek) {
mDB.addReportTechActivity(oDetail);
}
}
}
Toast.makeText(this, "Ghi báo cáo kĩ thuật thành công", Toast.LENGTH_SHORT).show();
setResult(2001);
finish();
isSaved=true;
}
@OnClick(R.id.btnPostReportTech)
public void onPostReportTech(){
ReceiveDataFragment();
if (APINet.isNetworkAvailable(ReportTechFormActivity.this)==false){
Toast.makeText(ReportTechFormActivity.this,"Máy chưa kết nối mạng..",Toast.LENGTH_LONG).show();
return;
}
if(oReportTech==null || oReportTech.getReportTechId().isEmpty()){
Toast.makeText(this, "Không khởi tạo được hoặc chưa nhập báo cáo kỹ thuật..", Toast.LENGTH_SHORT).show();
return;
}
if(oReportTechMarket==null || oReportTechMarket.size()<=0){
Toast.makeText(this, "Không khởi tạo được hoặc chưa nhập báo cáo thị trường..", Toast.LENGTH_SHORT).show();
return;
}
if (oReportTech.getReportCode().isEmpty() || oReportTechMarket.size()<=0) {
Toast.makeText(this, "Không tìm thấy số báo cáo kỹ thuật hoặc chưa nhập báo cáo thị trường", Toast.LENGTH_SHORT).show();
}
else{
mDB.addReportTech(oReportTech);
if(mDB.getSizeReportTech(oReportTech.getReportTechId())>0) {
for (SM_ReportTechMarket oDetail : oReportTechMarket) {
mDB.addReportTechMarket(oDetail);
}
if(oReportTechDisease != null && oReportTechDisease.size() > 0){
for(SM_ReportTechDisease oDetail: oReportTechDisease){
mDB.addReportTechDisease(oDetail);
}
}
if(oReportTechCompetitor != null && oReportTechCompetitor.size() > 0){
for(SM_ReportTechCompetitor oDetail: oReportTechCompetitor){
mDB.addReportTechCompetitor(oDetail);
}
}
if(oReportTechActivityThisWeek != null &&oReportTechActivityThisWeek.size() > 0){
for(SM_ReportTechActivity oDetail: oReportTechActivityThisWeek){
mDB.addReportTechActivity(oDetail);
}
}
if(oReportTechActivityNextWeek != null && oReportTechActivityNextWeek.size() > 0){
for(SM_ReportTechActivity oDetail: oReportTechActivityNextWeek){
mDB.addReportTechActivity(oDetail);
}
}
onPostReportTech(oReportTech, oReportTechMarket, oReportTechDisease, oReportTechCompetitor, oReportTechActivityThisWeek, oReportTechActivityNextWeek);
}else{
Toast.makeText(this, "Không thể ghi báo cáo kỹ thuật..", Toast.LENGTH_SHORT).show();
return;
}
}
isSaved=true;
}
//POST
private String getReportTechMarketData(final List<SM_ReportTechMarket> markets){
String mTechDetail="";
try{
if(markets!=null){
for (SM_ReportTechMarket oOdt : markets) {
String mRow="";
if(oOdt.getMarketId()!=null && !oOdt.getMarketId().isEmpty()){
mRow=oOdt.getMarketId()+"#";
if(oOdt.getReportTechId()!=null && !oOdt.getReportTechId().isEmpty()){
mRow+=oOdt.getReportTechId()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getTitle()!=null && !oOdt.getTitle().isEmpty()){
mRow+=oOdt.getTitle()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getNotes()!=null && !oOdt.getNotes().isEmpty()){
mRow+=oOdt.getNotes()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getUsefull()!=null && !oOdt.getUsefull().isEmpty()){
mRow+=oOdt.getUsefull()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getHarmful()!=null && !oOdt.getHarmful().isEmpty()){
mRow+=oOdt.getHarmful().toString()+"#";
}else{
mRow+=""+"#";
}
mRow+="|";
mTechDetail+=mRow;
}
}
}
}catch (Exception ex){}
return mTechDetail;
}
private String getReportTechDiseaseData(final List<SM_ReportTechDisease> diseases){
String mTechDetail="";
try{
if(diseases!=null){
for (SM_ReportTechDisease oOdt : diseases) {
String mRow="";
if(oOdt.getDiseaseId()!=null && !oOdt.getDiseaseId().isEmpty()){
mRow=oOdt.getDiseaseId()+"#";
if(oOdt.getReportTechId()!=null && !oOdt.getReportTechId().isEmpty()){
mRow+=oOdt.getReportTechId()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getTreeCode()!=null && !oOdt.getTreeCode().isEmpty()){
mRow+=oOdt.getTreeCode()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getStagesCode()!=null && !oOdt.getStagesCode().isEmpty()){
mRow+=oOdt.getStagesCode()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getTitle()!=null && !oOdt.getTitle().isEmpty()){
mRow+=oOdt.getTitle()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getAcreage()!=null){
mRow+=oOdt.getAcreage()+"#";
}else{
mRow+="0"+"#";
}
if(oOdt.getDisease()!=null && !oOdt.getDisease().isEmpty()){
mRow+=oOdt.getDisease().toString()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getPrice()!=null){
mRow+=oOdt.getPrice()+"#";
}else{
mRow+="0"+"#";
}
if(oOdt.getNotes()!=null && !oOdt.getNotes().isEmpty()){
mRow+=oOdt.getNotes().toString()+"#";
}else{
mRow+=""+"#";
}
mRow+="|";
mTechDetail+=mRow;
}
}
}
}catch (Exception ex){}
return mTechDetail;
}
private String getReportTechCompetitorData(final List<SM_ReportTechCompetitor> competitors){
String mTechDetail="";
try{
if(competitors!=null){
for (SM_ReportTechCompetitor oOdt : competitors) {
String mRow="";
if(oOdt.getCompetitorId()!=null && !oOdt.getCompetitorId().isEmpty()){
mRow=oOdt.getCompetitorId()+"#";
if(oOdt.getReportTechId()!=null && !oOdt.getReportTechId().isEmpty()){
mRow+=oOdt.getReportTechId()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getTitle()!=null && !oOdt.getTitle().isEmpty()){
mRow+=oOdt.getTitle()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getNotes()!=null && !oOdt.getNotes().isEmpty()){
mRow+=oOdt.getNotes()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getUseful()!=null && !oOdt.getUseful().isEmpty()){
mRow+=oOdt.getUseful().toString()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getHarmful()!=null && !oOdt.getHarmful().isEmpty()){
mRow+=oOdt.getHarmful().toString()+"#";
}else{
mRow+=""+"#";
}
mRow+="|";
mTechDetail+=mRow;
}
}
}
}catch (Exception ex){}
return mTechDetail;
}
private String getReportTechActivityData(List<SM_ReportTechActivity> thisWeek, List<SM_ReportTechActivity> nextWeek){
String mTechDetail="";
try{
if(thisWeek != null){
thisWeek = new ArrayList<>();
}
if(nextWeek != null && nextWeek.size()>0){
for(SM_ReportTechActivity o: nextWeek){
thisWeek.add(o);
}
}
if(thisWeek!=null){
for (SM_ReportTechActivity oOdt : thisWeek) {
String mRow="";
if(oOdt.getActivitieId()!=null && !oOdt.getActivitieId().isEmpty()){
mRow=oOdt.getActivitieId()+"#";
if(oOdt.getReportTechId()!=null && !oOdt.getReportTechId().isEmpty()){
mRow+=oOdt.getReportTechId()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getIsType()!=null){
mRow+=oOdt.getIsType()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getTitle()!=null && !oOdt.getTitle().isEmpty()){
mRow+=oOdt.getTitle()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getNotes()!=null && !oOdt.getNotes().isEmpty()){
mRow+=oOdt.getNotes().toString()+"#";
}else{
mRow+=""+"#";
}
if(oOdt.getAchievement()!=null && !oOdt.getAchievement().isEmpty()){
mRow+=oOdt.getAchievement().toString()+"#";
}else{
mRow+=""+"#";
}
mRow+="|";
mTechDetail+=mRow;
}
}
}
}catch (Exception ex){}
return mTechDetail;
}
private void onPostReportTech(final SM_ReportTech tech , final List<SM_ReportTechMarket> markets, final List<SM_ReportTechDisease> diseases,
final List<SM_ReportTechCompetitor> competitor, final List<SM_ReportTechActivity> thisWeeks, final List<SM_ReportTechActivity> nextWeeks){
try{
if (APINet.isNetworkAvailable(ReportTechFormActivity.this)==false){
Toast.makeText(ReportTechFormActivity.this,"Máy chưa kết nối mạng..",Toast.LENGTH_LONG).show();
return;
}
final String Imei=AppUtils.getImeil(this);
final String ImeiSim=AppUtils.getImeilsim(this);
final String mDataReportTechMarket = getReportTechMarketData(markets);
final String mDataReportTechDisease = getReportTechDiseaseData(diseases);
final String mDataReportTechCompetitor = getReportTechCompetitorData(competitor);
final String mDataReportTechActivitie = getReportTechActivityData(thisWeeks, nextWeeks);
if(ImeiSim.isEmpty()){
Toast.makeText(this,"Không đọc được số IMEI từ thiết bị cho việc đồng bộ. Kiểm tra Sim của bạn",Toast.LENGTH_LONG).show();
return;
}
if(tech==null){
Toast.makeText(this,"Không tìm thấy dữ liệu báo cáo kỹ thuật.",Toast.LENGTH_LONG).show();
return;
}
if(tech.getReportTechId()==null || tech.getReportCode().isEmpty()){
Toast.makeText(this,"Không tìm thấy mã báo cáo",Toast.LENGTH_SHORT).show();
return;
}
final String mUrlPostReportTech=AppSetting.getInstance().URL_PostReportTech();
try {
if (tech.getReportCode() == null || tech.getReportCode().isEmpty()) {
tech.setReportCode("");
}
if (tech.getReportName() == null || tech.getReportName().isEmpty()) {
tech.setReportName("");
}
if (tech.getReportDate() == null || tech.getReportDate().isEmpty()) {
tech.setReportDate("");
}
if (tech.getLatitude() == null || tech.getLatitude().toString().isEmpty()) {
tech.setLatitude(0.0f);
}
if (tech.getLongtitude() == null || tech.getLongtitude().toString().isEmpty()) {
tech.setLongtitude(0.0f);
}
if (tech.getLocationAddress() == null || tech.getLocationAddress().toString().isEmpty()) {
tech.setLocationAddress("N/A");
}
if(tech.getReceiverList() == null || tech.getReceiverList().toString().isEmpty()){
tech.setReceiverList("");
}
if(tech.getNotes() == null || tech.getNotes().toString().isEmpty()){
tech.setNotes("");
}
if(tech.getIsStatus() == null){
tech.setIsStatus("1");
}
}catch(Exception ex){
Toast.makeText(ReportTechFormActivity.this, "Không tìm thấy dữ liệu đã quét.." + ex.getMessage(), Toast.LENGTH_LONG).show();
return;
}
RequestBody DataBody = new FormBody.Builder()
.add("imei", Imei)
.add("imeisim", ImeiSim)
.add("reportcode",tech.getReportCode())
.add("reportday", tech.getReportDate())
.add("reportname", tech.getReportName())
.add("customerid", "")
.add("longitude", Float.toString(tech.getLongtitude()))
.add("latitude", Float.toString(tech.getLatitude()))
.add("locationaddress", tech.getLocationAddress())
.add("receiverlist", tech.getReceiverList())
.add("notes",tech.getNotes())
.add("isstatus", tech.getIsStatus())
.add("reporttechmarket", mDataReportTechMarket)
.add("reporttechdisease",mDataReportTechDisease)
.add("reporttechcompetitor",mDataReportTechCompetitor)
.add("reporttechactivitie",mDataReportTechActivitie)
.build();
new SyncPost(new APINetCallBack() {
@Override
public void onHttpStart() {
showProgressDialog("Đang đồng bộ dữ liệu về Server.");
}
@Override
public void onHttpSuccess(String ResPonseRs) {
try {
dismissProgressDialog();
if (ResPonseRs!=null && !ResPonseRs.isEmpty()) {
if (ResPonseRs.contains("SYNC_OK")) {
Toast.makeText(ReportTechFormActivity.this, "Đồng bộ thành công.", Toast.LENGTH_LONG).show();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
tech.setPostDate(sdf.format(new Date()));
tech.setPost(true);
tech.setIsStatus("2");
mDB.editReportTech(tech);
setResult(2001);
finish();
}
else if(ResPonseRs.contains("SYNC_REG") || ResPonseRs.contains("SYNC_NOT_REG")){
Toast.makeText(ReportTechFormActivity.this, "Thiết bị chưa được đăng ký hoặc chưa xác thực từ Server.", Toast.LENGTH_LONG).show();
}else if(ResPonseRs.contains("SYNC_ACTIVE")) {
Toast.makeText(ReportTechFormActivity.this, "Thiết bị chưa kích hoạt...", Toast.LENGTH_LONG).show();
}else if(ResPonseRs.contains("SYNC_APPROVE") || ResPonseRs.contains("SYNC_APPROVE")){
Toast.makeText(ReportTechFormActivity.this, "Đơn hàng đang được xử lý. Bạn không thể gửi điều chỉnh.", Toast.LENGTH_LONG).show();
}else if (ResPonseRs.contains("SYNC_BODY_NULL")) {
Toast.makeText(ReportTechFormActivity.this, "Tham số gửi lên BODY=NULL", Toast.LENGTH_LONG).show();
} else if (ResPonseRs.contains("SYNC_ORDERID_NULL")) {
Toast.makeText(ReportTechFormActivity.this, "Mã số REPORT_TECH_ID=NULL", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(ReportTechFormActivity.this , "Không nhận được trang thải trả về.", Toast.LENGTH_LONG).show();
}
}catch (Exception ex){ }
// finish();
}
@Override
public void onHttpFailer(Exception e) {
dismissProgressDialog();
Toast.makeText(ReportTechFormActivity.this,"Không thể đồng bộ:"+e.getMessage(),Toast.LENGTH_LONG).show();
}
},mUrlPostReportTech,"POST_REPORT_TECH",DataBody).execute();
}catch (Exception ex){
Toast.makeText(ReportTechFormActivity.this,"Không thể đồng bộ:"+ex.getMessage(),Toast.LENGTH_LONG).show();
dismissProgressDialog();
}
}
}
|
package com.tencent.mm.plugin.appbrand.dynamic;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public final class i {
private static final i fuP = new i();
public Map<String, String> fuO = new HashMap();
public static i aeT() {
return fuP;
}
public final String sz(String str) {
return (String) this.fuO.get(str);
}
public final Collection<String> aeU() {
return this.fuO.values();
}
}
|
package com.tencent.xweb.x5;
import android.content.Context;
import android.widget.TextView;
import com.tencent.smtt.utils.TbsLogClient;
import org.xwalk.core.Log;
class X5WebFactory$a extends TbsLogClient {
final /* synthetic */ X5WebFactory vDN;
public X5WebFactory$a(X5WebFactory x5WebFactory, Context context) {
this.vDN = x5WebFactory;
super(context);
}
public final void writeLog(String str) {
super.writeLog(str);
}
public final void writeLogToDisk() {
super.writeLogToDisk();
}
public final void showLog(String str) {
super.showLog(str);
}
public final void setLogView(TextView textView) {
super.setLogView(textView);
}
public final void i(String str, String str2) {
super.i(str, str2);
Log.i(str, str2);
}
public final void e(String str, String str2) {
super.e(str, str2);
Log.e(str, str2);
}
public final void w(String str, String str2) {
super.w(str, str2);
Log.w(str, str2);
}
public final void d(String str, String str2) {
super.d(str, str2);
Log.d(str, str2);
}
public final void v(String str, String str2) {
super.v(str, str2);
Log.v(str, str2);
}
}
|
package Domain;
import Exceptions.DomainException;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import server.GiocatoreRemotoForTest;
import server.Partita;
import server.Server;
import java.util.HashMap;
import java.util.LinkedHashMap;
import static org.junit.Assert.*;
/**
* Created by Michele on 09/06/2017.
*/
public class TabelloneTest {
Tabellone tabellone;
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setUp() throws Exception {
Partita partita = new Partita();
tabellone = partita.getTabellone();
partita.AggiungiGiocatore((short)1, "Michele", new GiocatoreRemotoForTest());
partita.AggiungiGiocatore((short)2, "Pietro", new GiocatoreRemotoForTest());
}
@Test
public void aggiungiGiocatore_OK() throws Exception {
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
assertEquals(3, tabellone.Giocatori.size());
assertEquals("Carlo", tabellone.getNomeGiocatoreById((short)3));
assertEquals(7, tabellone.Giocatori.get(2).Risorse.getMonete());
}
@Test
public void aggiungiGiocatore_DoppioUsername() throws Exception {
exception.expect(DomainException.class);
exception.expectMessage("Esiste già un giocatore con lo stesso username.");
tabellone.AggiungiGiocatore((short)3, "Michele", new Giocatore());
}
@Test
public void aggiungiGiocatore_PiuDiQuattro() throws Exception {
exception.expect(DomainException.class);
exception.expectMessage("E' stato raggiunto il numero limite di giocatori");
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
tabellone.AggiungiGiocatore((short)4, "Matteo", new Giocatore());
tabellone.AggiungiGiocatore((short)5, "Extra", new Giocatore());
}
@Test
public void aggiornaOrdineGiocatori_UnGiocatore() throws Exception {
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
Giocatore michele = tabellone.getGiocatoreById((short)1);
Giocatore pietro = tabellone.getGiocatoreById((short)2);
Giocatore carlo = tabellone.getGiocatoreById((short)3);
tabellone.SpazioAzioneConsiglio.FamiliariPiazzati.add(carlo.Familiari.get(0));
tabellone.AggiornaOrdineGiocatori();
assertEquals(1, carlo.getOrdineTurno());
assertEquals(2, michele.getOrdineTurno());
assertEquals(3, pietro.getOrdineTurno());
}
@Test
public void aggiornaOrdineGiocatori_DueGiocatori() throws Exception {
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
Giocatore michele = tabellone.getGiocatoreById((short)1);
Giocatore pietro = tabellone.getGiocatoreById((short)2);
Giocatore carlo = tabellone.getGiocatoreById((short)3);
tabellone.SpazioAzioneConsiglio.FamiliariPiazzati.add(carlo.Familiari.get(0));
tabellone.SpazioAzioneConsiglio.FamiliariPiazzati.add(pietro.Familiari.get(0));
tabellone.AggiornaOrdineGiocatori();
assertEquals(1, carlo.getOrdineTurno());
assertEquals(2, pietro.getOrdineTurno());
assertEquals(3, michele.getOrdineTurno());
}
@Test
public void aggiornaOrdineGiocatori_ZeroTreGiocatori() throws Exception {
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
Giocatore michele = tabellone.getGiocatoreById((short)1);
Giocatore pietro = tabellone.getGiocatoreById((short)2);
Giocatore carlo = tabellone.getGiocatoreById((short)3);
tabellone.AggiornaOrdineGiocatori();
assertEquals(1, michele.getOrdineTurno());
assertEquals(2, pietro.getOrdineTurno());
assertEquals(3, carlo.getOrdineTurno());
tabellone.SpazioAzioneConsiglio.FamiliariPiazzati.add(michele.Familiari.get(0));
tabellone.SpazioAzioneConsiglio.FamiliariPiazzati.add(carlo.Familiari.get(0));
tabellone.SpazioAzioneConsiglio.FamiliariPiazzati.add(pietro.Familiari.get(0));
tabellone.AggiornaOrdineGiocatori();
assertEquals(1, michele.getOrdineTurno());
assertEquals(2, carlo.getOrdineTurno());
assertEquals(3, pietro.getOrdineTurno());
}
@Test
public void validaPiazzamentoFamiliareProduzione_Vuoto() throws Exception {
Giocatore michele = tabellone.getGiocatoreById((short)1);
tabellone.ValidaPiazzamentoFamiliareProduzione(michele.Familiari.get(0));
}
@Test
public void validaPiazzamentoFamiliareProduzione_NeutroColorato() throws Exception {
Giocatore michele = tabellone.getGiocatoreById((short)1);
Familiare familiareBianco = michele.getFamiliareByColor(ColoreDado.BIANCO);
Familiare familiareNeutro = michele.getFamiliareByColor(ColoreDado.NEUTRO);
tabellone.ValidaPiazzamentoFamiliareProduzione(familiareBianco);
tabellone.SpaziAzioneProduzione.get(0).FamiliariPiazzati.add(familiareBianco);
tabellone.ValidaPiazzamentoFamiliareProduzione(familiareNeutro);
}
@Test (expected = DomainException.class)
public void validaPiazzamentoFamiliareProduzione_DueColorati() throws Exception {
Giocatore michele = tabellone.getGiocatoreById((short)1);
Familiare familiareBianco = michele.getFamiliareByColor(ColoreDado.BIANCO);
Familiare familiareNero = michele.getFamiliareByColor(ColoreDado.NERO);
tabellone.ValidaPiazzamentoFamiliareProduzione(familiareBianco);
tabellone.SpaziAzioneProduzione.get(0).FamiliariPiazzati.add(familiareBianco);
tabellone.ValidaPiazzamentoFamiliareProduzione(familiareNero);
}
@Test
public void validaPiazzamentoFamiliareRaccolto_Vuoto() throws Exception {
Giocatore michele = tabellone.getGiocatoreById((short)1);
tabellone.ValidaPiazzamentoFamiliareRaccolto(michele.Familiari.get(0));
}
@Test
public void validaPiazzamentoFamiliareRaccolto_NeutroColorato() throws Exception {
Giocatore michele = tabellone.getGiocatoreById((short)1);
Familiare familiareBianco = michele.getFamiliareByColor(ColoreDado.BIANCO);
Familiare familiareNeutro = michele.getFamiliareByColor(ColoreDado.NEUTRO);
tabellone.ValidaPiazzamentoFamiliareRaccolto(familiareBianco);
tabellone.SpaziAzioneRaccolto.get(0).FamiliariPiazzati.add(familiareBianco);
tabellone.ValidaPiazzamentoFamiliareRaccolto(familiareNeutro);
}
@Test (expected = DomainException.class)
public void validaPiazzamentoFamiliareRaccolto_DueColorati() throws Exception {
Giocatore michele = tabellone.getGiocatoreById((short)1);
Familiare familiareBianco = michele.getFamiliareByColor(ColoreDado.BIANCO);
Familiare familiareNero = michele.getFamiliareByColor(ColoreDado.NERO);
tabellone.ValidaPiazzamentoFamiliareRaccolto(familiareBianco);
tabellone.SpaziAzioneRaccolto.get(0).FamiliariPiazzati.add(familiareBianco);
tabellone.ValidaPiazzamentoFamiliareRaccolto(familiareNero);
}
@Test
public void esistonoFamiliariPiazzabili_True() throws Exception {
boolean esistonoFamiliariPiazzabili = this.tabellone.EsistonoFamiliariPiazzabili();
assertTrue(esistonoFamiliariPiazzabili);
}
@Test
public void esistonoFamiliariPiazzabili_TuttiPiazzati() throws Exception {
this.tabellone.Giocatori.stream().forEach(g -> g.Familiari.stream().forEach(f -> f.SpazioAzioneAttuale = new SpazioAzione()));
boolean esistonoFamiliariPiazzabili = this.tabellone.EsistonoFamiliariPiazzabili();
assertFalse(esistonoFamiliariPiazzabili);
}
@Test
public void esistonoFamiliariPiazzabili_NeutriSenzaServi() throws Exception {
this.tabellone.Giocatori.stream().forEach(g -> g.Familiari.stream().forEach(f -> f.SpazioAzioneAttuale = (f.ColoreDado != ColoreDado.NEUTRO) ? new SpazioAzione() : null ));
this.tabellone.Giocatori.stream().forEach(g -> g.Risorse.setRisorse(Risorsa.TipoRisorsa.SERVI, 0));
boolean esistonoFamiliariPiazzabili = this.tabellone.EsistonoFamiliariPiazzabili();
assertFalse(esistonoFamiliariPiazzabili);
}
@Test
public void riscuotiPrivilegiDelConsiglio() throws Exception {
Giocatore michele = tabellone.getGiocatoreById((short)1);
michele.incrementaPrivilegiDaScegliere();
michele.incrementaPrivilegiDaScegliere();
tabellone.RiscuotiPrivilegiDelConsiglio(michele.getIdGiocatore(), new Risorsa(Risorsa.TipoRisorsa.LEGNO, 10));
assertEquals(1, michele.getPrivilegiDaScegliere());
assertEquals(12, michele.Risorse.getLegno());
}
@Test
public void scomunicaGiocatore() throws Exception {
Giocatore michele = tabellone.getGiocatoreById((short)1);
tabellone.ScomunicaGiocatore(michele, 1);
assertTrue(michele.getRapportoVaticanoEffettuato());
assertEquals(1, michele.CarteScomunica.size());
}
@Test
public void iniziaTurno() throws Exception {
this.tabellone.Giocatori.stream().forEach(g -> g.Familiari.stream().forEach(f -> f.SpazioAzioneAttuale = new SpazioAzione()));
Giocatore michele = tabellone.getGiocatoreById((short)1);
Familiare familiareBianco = michele.getFamiliareByColor(ColoreDado.BIANCO);
Familiare familiareNeutro = michele.getFamiliareByColor(ColoreDado.NEUTRO);
HashMap<Integer, String> mappaCarte1 = tabellone.IniziaTurno(1);
tabellone.SpaziAzioneRaccolto.get(0).FamiliariPiazzati.add(familiareBianco);
tabellone.SpaziAzioneProduzione.get(0).FamiliariPiazzati.add(familiareNeutro);
HashMap<Integer, String> mappaCarte2 = tabellone.IniziaTurno(1);
assertTrue(tabellone.Giocatori.stream().allMatch(g -> g.Familiari.stream().allMatch(f -> f.SpazioAzioneAttuale == null)));
assertTrue(mappaCarte2.values().stream().allMatch(v -> !mappaCarte1.containsValue(v)));
assertTrue(mappaCarte2.keySet().stream().allMatch(k -> mappaCarte1.containsKey(k)));
assertTrue(tabellone.Torri.stream().allMatch(t -> t.SpaziAzione.stream().allMatch(s -> s.CartaAssociata != null)));
assertEquals(16, mappaCarte1.size());
assertEquals(16, mappaCarte2.size());
assertEquals(96-16-16, tabellone.getMazzoCarte().size());
}
@Test
public void calcolaPunteggiFinali_SenzaEffetti() throws Exception {
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
Giocatore michele = tabellone.getGiocatoreById((short)1);
Giocatore pietro = tabellone.getGiocatoreById((short)2);
Giocatore carlo = tabellone.getGiocatoreById((short)3);
//Territori
CartaTerritorio cartaBosco = (CartaTerritorio)tabellone.getCartaByName("Bosco");
michele.CarteTerritorio.add(cartaBosco);
michele.CarteTerritorio.add(cartaBosco);
michele.CarteTerritorio.add(cartaBosco); //3 carte territorio = +1
pietro.CarteTerritorio.add(cartaBosco); //1 carta territorio = +0
//Personaggio
CartaPersonaggio contadino = (CartaPersonaggio)tabellone.getCartaByName("Contadino");
pietro.CartePersonaggio.add(contadino);
pietro.CartePersonaggio.add(contadino); //2 carta personaggio = +3
//Punti Fede
michele.Risorse.setRisorse(Risorsa.TipoRisorsa.PFEDE, 10); //10 pti fede = +15
pietro.Risorse.setRisorse(Risorsa.TipoRisorsa.PFEDE, 5); //5 pti fede = +5
//Punti Militari
michele.Risorse.setRisorse(Risorsa.TipoRisorsa.PMILITARI, 5); //Secondo in classifica militare = +2
pietro.Risorse.setRisorse(Risorsa.TipoRisorsa.PMILITARI, 10); //Primo in classifica militare = +5
//Aggiorna in base agli effetti
//le carte contadino e bosco non hanno effetti da applicare alla fine della partita
//in questo test non vengono inserite carte scomunica quindi non ci sono altri effetti da applicare
//Risorse
pietro.Risorse.setRisorse(Risorsa.TipoRisorsa.SERVI, 10);
//michele -> 2 legni 2 pietre 3 servi 5 monete = 12 /5 = +2
//pietro -> 2 legni 2 pietre 10 servi 6 monete = 20 / 5 = +4
//carlo -> 2 legni 2 pietre 3 servi 5 monete = 12 / 5 = +2
michele.Risorse.setRisorse(Risorsa.TipoRisorsa.PVITTORIA, 5);
pietro.Risorse.setRisorse(Risorsa.TipoRisorsa.PVITTORIA, 3);
carlo.Risorse.setRisorse(Risorsa.TipoRisorsa.PVITTORIA, 8);
//Effettua il conteggio
tabellone.CalcolaPunteggiFinali();
//Totali previsti
//michele -> 1 + 15 + 2 + 2 = 20 + 5 = 25
//pietro -> 3 + 5 + 5 + 4 = 17 + 3 = 20
//carlo -> 2 + 8 = 10
assertEquals(25, michele.Risorse.getPuntiVittoria());
assertEquals(20, pietro.Risorse.getPuntiVittoria());
assertEquals(10, carlo.Risorse.getPuntiVittoria());
}
@Test
public void calcolaPunteggiFinali_ConEffetti() throws Exception {
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
Giocatore michele = tabellone.getGiocatoreById((short)1);
Giocatore pietro = tabellone.getGiocatoreById((short)2);
Giocatore carlo = tabellone.getGiocatoreById((short)3);
//Territori
CartaTerritorio cartaBosco = (CartaTerritorio)tabellone.getCartaByName("Bosco");
michele.CarteTerritorio.add(cartaBosco);
michele.CarteTerritorio.add(cartaBosco);
michele.CarteTerritorio.add(cartaBosco); //3 carte territorio = +1
pietro.CarteTerritorio.add(cartaBosco); //1 carta territorio = +0
//Personaggio
CartaPersonaggio contadino = (CartaPersonaggio)tabellone.getCartaByName("Contadino");
pietro.CartePersonaggio.add(contadino);
pietro.CartePersonaggio.add(contadino); //2 carta personaggio = +3
//Punti Fede
michele.Risorse.setRisorse(Risorsa.TipoRisorsa.PFEDE, 10); //10 pti fede = +15
pietro.Risorse.setRisorse(Risorsa.TipoRisorsa.PFEDE, 5); //5 pti fede = +5
//Punti Militari
michele.Risorse.setRisorse(Risorsa.TipoRisorsa.PMILITARI, 5); //Secondo in classifica militare = +2
pietro.Risorse.setRisorse(Risorsa.TipoRisorsa.PMILITARI, 10); //Primo in classifica militare = +5
//Aggiorna in base agli effetti
//Impresa
CartaImpresa ingaggiareReclute = (CartaImpresa) tabellone.getCartaByName("IngaggiareReclute");
CartaImpresa costruireMura = (CartaImpresa) tabellone.getCartaByName("CostruireLeMura");
michele.CarteImpresa.add(ingaggiareReclute); // Effetto = +4
pietro.CarteImpresa.add(ingaggiareReclute);
pietro.CarteImpresa.add(costruireMura); // Effetti = +7
//Scomunica
TesseraScomunica perdiPuntiPerOgniRisorsa = tabellone.getTesseraScomunicaByName("15");
michele.CarteScomunica.add(perdiPuntiPerOgniRisorsa); //Effetto = (legno + pietra + servitori + monete) * -1
//Risorse
pietro.Risorse.setRisorse(Risorsa.TipoRisorsa.SERVI, 10);
//michele -> 2 legni 2 pietre 3 servi 5 monete = 12 / 5 = +2 -12 (scomunica)
//pietro -> 2 legni 2 pietre 10 servi 6 monete = 20 / 5 = +4
//carlo -> 2 legni 2 pietre 3 servi 5 monete = 12 / 5 = +2
michele.Risorse.setRisorse(Risorsa.TipoRisorsa.PVITTORIA, 8);
pietro.Risorse.setRisorse(Risorsa.TipoRisorsa.PVITTORIA, 6);
carlo.Risorse.setRisorse(Risorsa.TipoRisorsa.PVITTORIA, 8);
//Effettua il conteggio
tabellone.CalcolaPunteggiFinali();
//Totali previsti
//michele -> 1 + 15 + 2 + 4 + 2 - 12 = 12 + 8 = 20
//pietro -> 3 + 5 + 5 + 7 + 4 = 24 + 6 = 30
//carlo -> 2 + 8 = 10
assertEquals(20, michele.Risorse.getPuntiVittoria());
assertEquals(30, pietro.Risorse.getPuntiVittoria());
assertEquals(10, carlo.Risorse.getPuntiVittoria());
}
@Test
public void getBonusVittoriaByPuntiMilitari_PuntiDiversi() throws Exception {
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
//michele 1
//pietro 2
//carlo 3
int[] primiGiocatori = new int[]{3};
int[] secondiGiocatori = new int[]{2};
int punti = tabellone.getBonusVittoriaByPuntiMilitari(1, primiGiocatori, secondiGiocatori);
assertEquals(0, punti);
punti = tabellone.getBonusVittoriaByPuntiMilitari(2, primiGiocatori, secondiGiocatori);
assertEquals(2, punti);
punti = tabellone.getBonusVittoriaByPuntiMilitari(3, primiGiocatori, secondiGiocatori);
assertEquals(5, punti);
}
@Test
public void getBonusVittoriaByPuntiMilitari_DuePrimi() throws Exception {
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
//michele 1
//pietro 2
//carlo 3
int[] primiGiocatori = new int[]{3,2};
int[] secondiGiocatori = new int[]{1};
int punti = tabellone.getBonusVittoriaByPuntiMilitari(1, primiGiocatori, secondiGiocatori);
assertEquals(0, punti);
punti = tabellone.getBonusVittoriaByPuntiMilitari(2, primiGiocatori, secondiGiocatori);
assertEquals(5, punti);
punti = tabellone.getBonusVittoriaByPuntiMilitari(3, primiGiocatori, secondiGiocatori);
assertEquals(5, punti);
}
@Test
public void getBonusVittoriaByPuntiMilitari_DueSecondi() throws Exception {
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
//michele 1
//pietro 2
//carlo 3
int[] primiGiocatori = new int[]{3};
int[] secondiGiocatori = new int[]{1,2};
int punti = tabellone.getBonusVittoriaByPuntiMilitari(1, primiGiocatori, secondiGiocatori);
assertEquals(2, punti);
punti = tabellone.getBonusVittoriaByPuntiMilitari(2, primiGiocatori, secondiGiocatori);
assertEquals(2, punti);
punti = tabellone.getBonusVittoriaByPuntiMilitari(3, primiGiocatori, secondiGiocatori);
assertEquals(5, punti);
}
@Test
public void getBonusVittoriaByPuntiMilitari_TuttiPrimi() throws Exception {
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
//michele 1
//pietro 2
//carlo 3
int[] primiGiocatori = new int[]{3, 1, 2};
int[] secondiGiocatori = new int[]{};
int punti = tabellone.getBonusVittoriaByPuntiMilitari(1, primiGiocatori, secondiGiocatori);
assertEquals(5, punti);
punti = tabellone.getBonusVittoriaByPuntiMilitari(2, primiGiocatori, secondiGiocatori);
assertEquals(5, punti);
punti = tabellone.getBonusVittoriaByPuntiMilitari(3, primiGiocatori, secondiGiocatori);
assertEquals(5, punti);
}
@Test
public void finePartita_PunteggiDiversi() throws Exception {
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
Giocatore michele = tabellone.getGiocatoreById((short)1);
Giocatore pietro = tabellone.getGiocatoreById((short)2);
Giocatore carlo = tabellone.getGiocatoreById((short)3);
michele.Risorse.setRisorse(Risorsa.TipoRisorsa.PVITTORIA, 1);
pietro.Risorse.setRisorse(Risorsa.TipoRisorsa.PVITTORIA, 10);
carlo.Risorse.setRisorse(Risorsa.TipoRisorsa.PVITTORIA, 100);
LinkedHashMap<Short, Integer> classifica = tabellone.FinePartita();
Short idPrimo = classifica.keySet().stream().findFirst().orElse(null);
Short idSecondo = classifica.keySet().stream().filter(x -> x != idPrimo).findFirst().orElse(null);
Short idTerzo = classifica.keySet().stream().filter(x -> x != idPrimo && x != idSecondo).findFirst().orElse(null);
assertEquals(3, idPrimo.intValue());
assertEquals(2, idSecondo.intValue());
assertEquals(1, idTerzo.intValue());
}
@Test
public void finePartita_PariPunti() throws Exception {
tabellone.AggiungiGiocatore((short)3, "Carlo", new Giocatore());
Giocatore michele = tabellone.getGiocatoreById((short)1);
Giocatore pietro = tabellone.getGiocatoreById((short)2);
Giocatore carlo = tabellone.getGiocatoreById((short)3);
michele.Risorse.setRisorse(Risorsa.TipoRisorsa.PVITTORIA, 10);
pietro.Risorse.setRisorse(Risorsa.TipoRisorsa.PVITTORIA, 10);
carlo.Risorse.setRisorse(Risorsa.TipoRisorsa.PVITTORIA, 100);
LinkedHashMap<Short, Integer> classifica = tabellone.FinePartita();
Short idPrimo = classifica.keySet().stream().findFirst().orElse(null);
Short idSecondo = classifica.keySet().stream().filter(x -> x != idPrimo).findFirst().orElse(null);
Short idTerzo = classifica.keySet().stream().filter(x -> x != idPrimo && x != idSecondo).findFirst().orElse(null);
assertEquals(3, idPrimo.intValue());
assertEquals(1, idSecondo.intValue());
assertEquals(2, idTerzo.intValue());
}
}
|
package com.tencent.tencentmap.mapsdk.a;
public interface ej {
void b();
}
|
package com.tiroller.diceroller;
import com.tiroller.diceroller.model.Result;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import java.util.Random;
import static org.junit.Assert.assertEquals;
@SpringBootTest
public class ResultTest {
@Test
public void testHitCalculation() {
int diceSides = 10;
int actualHits = 0;
int combat = 9;
int count = 4;
ArrayList<Integer> rolls = new ArrayList<Integer>();
Random randomGenerator = new Random();
for (int i = 0; i < count; i++) {
int roll = randomGenerator.nextInt(diceSides) + 1;
rolls.add(roll);
if (roll >= combat || roll == diceSides) {
actualHits++;
}
}
Result result = new Result("Test", diceSides, combat, count, rolls, 0 );
assertEquals(result.getHits(), actualHits);
}
}
|
package demo.plagdetect.calfeature;
import demo.plagdetect.util.FileUtil;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CalCommentSim {
private final static String REGEX_EXTRACT_COMMENT = "\\/\\/[^\\n]*|\\/\\*([^\\*^\\/]*|[\\*^\\/*]*|[^\\**\\/]*)*\\*+\\/";
/**
* @Author duanding
* @Description 从旧文件中提取注释部分,放到新的文件中
* @Date 10:34 AM 2019/9/20
* @Param [oldFile, commentFile]
* @return void
**/
public static void extractCommentToFile(File oldFile, File commentFile){
FileReader fileReader = null;
BufferedReader bufferedReader = null;
FileWriter fileWriter = null;
BufferedWriter bufferedWriter = null;
try {
fileReader = new FileReader(oldFile);
bufferedReader = new BufferedReader(fileReader);
fileWriter = new FileWriter(commentFile);
bufferedWriter = new BufferedWriter(fileWriter);
String line = "";
Pattern pattern = Pattern.compile(REGEX_EXTRACT_COMMENT);
while ((line = bufferedReader.readLine()) != null) {
if (line.trim().length() > 0) {
Matcher matcher = pattern.matcher(line.trim());
if(matcher.find() || line.trim().charAt(0) == '/' || line.trim().charAt(0) == '*') {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
}
}
} catch (IOException e) {
e.getStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
bufferedReader = null;
}
if (fileReader != null) {
fileReader.close();
fileReader = null;
}
if(bufferedWriter != null){
bufferedWriter.close();
bufferedWriter = null;
}
if(fileWriter != null){
fileWriter.close();
fileWriter = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @Author duanding
* @Description 用diff计算行相似度
* @Date 5:39 PM 2019/9/20
* @Param [commentFile1, commentFile2, compareFile]
* @return double
**/
public static double calLineSimByDiff(File commentFile1, File commentFile2,File compareFile){
double sim = 0.0;
TerminalExec terminalExec = new TerminalExec();
terminalExec.runDiff(commentFile1,commentFile2,compareFile);
int diffLine = FileUtil.calculateDiffLineFromDiffFile(compareFile);
// System.out.println(diffLine);
int file1Line = FileUtil.calculateFileLineFromTargetFile(commentFile1);
// System.out.println(file1Line);
int file2Line = FileUtil.calculateFileLineFromTargetFile(commentFile2);
// System.out.println(file2Line);
sim = CalFileSim.calculateSimValueByDiff(file1Line,file2Line,diffLine);
return sim;
}
}
|
import io.reactivex.Flowable;
import org.reactivestreams.Publisher;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
// CompletableFuture only passes through the 'then' chain/ tree once
// where as flow in for continuous data, like timer, WebSocket, database read(one by one), reading or uploading file
// it works on 'Consumer request n object' -> Provider then calls onNext 'n' times.
//
// Lazy / Cold:
// Element are only generated when 'Consumer'(next in chain) ask for it.
// And if you subscribe multiple time -> each will create a different unique stream, with independent elements
//
// Hot:
// Immediately starts, Don't wait for the subscriber,
// all subscribers get the same element,
// Only one steam for all subscriber,
// If the subscriber does not request the element, it is stacked as a backpressure, till the size is reached.
//
// CF:
// for completable future you will create a future for each data entity, and they will be running in parallel
// where as in flow there is stream of data which goes through pipeline
//
// JavaScript:
// java flux vs js generator -> generator waits for the element to process before asking for next element
// i.e backpressure is responsibility of the sender.
// Here Completable future is used for doing things in parallel
// And RX for doing it in flow (stream) -> Data will come in as a pipe, one after another
// Even though all the CompletableFutures are running in parallel, Node that all the callbacks are running on Main thread
// MONO from future will wait for future to complete (CompletableFutures are 'hot')
// and MONO it will emmit when it is subscribed (Mono is cold)
// but on each subscribe it will give the same future
// * Code Help From : https://www.baeldung.com/java-aws-s3-reactive#2-handling-a-single-file-upload
// * Marble Diagram: https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html
// * Reactive Streams Specification: https://github.com/reactive-streams/reactive-streams-jvm
// * S3 FileAsyncRequestBody (putObject) (Publisher/Provider) : https://github.com/aws/aws-sdk-java-v2/blob/master/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/async/FileAsyncRequestBody.java
// * S3 FileAsyncResponseTransformer (getObject) (Subscriber/Consumer) : https://github.com/aws/aws-sdk-java-v2/blob/master/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/async/FileAsyncResponseTransformer.java
// if we convert the arrayList of completable future to Flux,
// "Flux is for streaming" but the "List of completable future is for parallel"
// https://stackoverflow.com/a/49494849/10066692
// https://github.com/ketan-10/aws-lambda-test
public class Main {
public void subscribe(Function function){}
public Publisher map(Function function){
// send publisher so other can subscribe on return value
// 's' subscription callback function
// eg. map().subscribe(value -> {})
// s = value -> {} // function
return s -> {
// subscribed is called on returned publisher
// so, we will call subscribe on parent(self) in chain
this.subscribe(x->{
// transform the result according to mapping function
var transformed = function.apply(x);
// call the child subscribe callback
s.send(transformed);
});
};
}
public Publisher flatMap(Function function) {
// send publisher so other can subscribe on return value
// 's' subscription callback function
// eg. map().subscribe(value -> {})
// s = value -> {} // function
return s -> {
// subscribed is called on returned publisher
// so, we will call subscribe on parent(self) in chain
this.subscribe(x -> {
// mapping function returns a publisher in 'flatmap' callback
var newPublisher = function.apply(x);
// subscribe to the mapping publisher
newPublisher.subscribe(data -> {
// call the child subscribe callback
s.send(data);
});
});
};
}
public static void main(String[] args) {
Flowable.interval(1000, TimeUnit.MILLISECONDS)
.flatMap(x-> Flowable.interval(250, TimeUnit.MILLISECONDS)
// .map(a-> a+" [T]")
)
.map(a-> a+" [T]")
.subscribe(System.out::println);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package ive.dsa.exception;
/**
* When the input message is emxpty, it occurs.
*
* @author POON Ngai Kuen(180091780)
* @version 1.0
*/
public class EmptyMessageException extends RuntimeException {
// Constructor
public EmptyMessageException() {
super("<message_string> is empty.");
// TODO Auto-generated constructor stub
}
}
|
package jwscert.rest.services;
import static org.junit.Assert.assertEquals;
import java.net.URISyntaxException;
import org.junit.Test;
import com.sun.jersey.api.client.WebResource;
public class HelloWorldTest extends BaseTest {
@Test
public void get() throws URISyntaxException {
WebResource webResource = resource();
String responseMsg = webResource.path("/hello").get(String.class);
assertEquals("Hello World", responseMsg);
}
}
|
package com.mxfit.mentix.menu3.Utils;
import android.content.Context;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by Mentix on 2018-02-26.
*/
public class CopyDatabase {
public CopyDatabase(Context context){
try{
InputStream inputStream = context.getAssets()
.open(DatabasePremadesHelper.DATABASE_NAME);
String OutFileName = DatabasePremadesHelper.DBLOCATION
+ DatabasePremadesHelper.DATABASE_NAME;
OutputStream outputStream = new FileOutputStream(OutFileName);
byte[] buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff))>0){
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
|
package com.tsm.template.controller;
import com.tsm.template.dto.MessageDTO;
import com.tsm.template.exceptions.BadRequestException;
import com.tsm.template.exceptions.MessageException;
import com.tsm.template.exceptions.ResourceNotFoundException;
import com.tsm.template.mappers.MessageMapper;
import com.tsm.template.model.Client;
import com.tsm.template.model.Message;
import com.tsm.template.model.Message.MessageStatus;
import com.tsm.template.service.ClientService;
import com.tsm.template.service.MessageService;
import com.tsm.template.util.ClientTestBuilder;
import com.tsm.template.util.MessageTestBuilder;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@FixMethodOrder(MethodSorters.JVM)
public class MessagesControllerTest {
private static final String CLIENT_TOKEN = ClientTestBuilder.CLIENT_TOKEN;
private static final String VALID_HEADER_HOST = "http://localhost";
private static final Long MESSAGE_ID = null;
@Mock
private MessageService service;
@Mock
private ClientService clientService;
@InjectMocks
private MessagesController controller;
@Mock
private Validator validator;
@Mock
private MockHttpServletRequest request;
@Mock
private MessageMapper messageMapper;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(request.getHeader("Referer")).thenReturn(VALID_HEADER_HOST);
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
}
@Test
public void save_InvalidMessageDTOGiven_ShouldThrowException() {
// Set up
MessageDTO dto = MessageTestBuilder.buildResoure();
// Expectations
when(validator.validate(dto, Default.class)).thenThrow(new ValidationException());
// Do test
try {
controller.save(CLIENT_TOKEN, dto, request);
fail();
} catch (ValidationException e) {
}
// Assertions
verify(validator).validate(dto, Default.class);
verifyZeroInteractions(service, clientService, messageMapper);
}
@SuppressWarnings("unchecked")
@Test
public void save_InvalidClientGiven_ShouldThrowException() {
// Set up
MessageDTO dto = MessageTestBuilder.buildResoure();
// Expectations
when(validator.validate(dto, Default.class)).thenReturn(Collections.emptySet());
when(clientService.findByToken(CLIENT_TOKEN)).thenThrow(ResourceNotFoundException.class);
// Do test
try {
controller.save(CLIENT_TOKEN, dto, request);
fail();
} catch (ResourceNotFoundException e) {
}
// Assertions
verify(validator).validate(dto, Default.class);
verify(clientService).findByToken(CLIENT_TOKEN);
verifyZeroInteractions(service, messageMapper);
}
@Test
public void save_ValidMessageDTOGiven_ShouldSaveMessage() {
// Set up
MessageDTO dto = MessageTestBuilder.buildResoure();
Message message = MessageTestBuilder.buildModel();
Client client = ClientTestBuilder.buildModel();
// Expectations
when(validator.validate(dto, Default.class)).thenReturn(Collections.emptySet());
when(messageMapper.toModel(dto, client)).thenReturn(message);
when(clientService.findByToken(CLIENT_TOKEN)).thenReturn(client);
when(service.save(message)).thenReturn(message);
when(messageMapper.toDTO(message)).thenReturn(dto);
// Do test
MessageDTO result = controller.save(CLIENT_TOKEN, dto, request);
// Assertions
verify(validator).validate(dto, Default.class);
verify(service).save(message);
verify(messageMapper).toModel(dto, client);
verify(service).save(message);
verify(messageMapper).toDTO(message);
assertNotNull(result);
assertThat(result,
allOf(hasProperty("id", notNullValue()), hasProperty("message", is(dto.getMessage())),
hasProperty("subject", is(dto.getSubject())),
hasProperty("senderName", is(dto.getSenderName())),
hasProperty("senderEmail", is(dto.getSenderEmail())),
hasProperty("status", is(MessageStatus.CREATED.name()))));
}
@SuppressWarnings("unchecked")
@Test
public void findById_InvalidClientGiven_ShouldThrowException() {
// Expectations
when(clientService.findByToken(CLIENT_TOKEN)).thenThrow(ResourceNotFoundException.class);
// Do test
try {
controller.findById(CLIENT_TOKEN, MESSAGE_ID, request);
fail();
} catch (ResourceNotFoundException e) {
}
// Assertions
verify(clientService).findByToken(CLIENT_TOKEN);
verifyZeroInteractions(service, messageMapper);
}
@SuppressWarnings("unchecked")
@Test
public void findById_NotFoundMessageGiven_ShouldThrowException() {
// Set up
Client client = ClientTestBuilder.buildModel();
// Expectations
when(clientService.findByToken(CLIENT_TOKEN)).thenReturn(client);
when(service.findByIdAndClient(MESSAGE_ID, client)).thenThrow(ResourceNotFoundException.class);
// Do test
try {
controller.findById(CLIENT_TOKEN, MESSAGE_ID, request);
fail();
} catch (ResourceNotFoundException e) {
}
// Assertions
verify(clientService).findByToken(CLIENT_TOKEN);
verify(service).findByIdAndClient(MESSAGE_ID, client);
verifyZeroInteractions(messageMapper);
}
@Test
public void findById_ValidMessageDTOGiven_ShouldSaveMessage() {
// Set up
MessageDTO dto = MessageTestBuilder.buildResoure();
Message message = MessageTestBuilder.buildModel();
Client client = ClientTestBuilder.buildModel();
// Expectations
when(clientService.findByToken(CLIENT_TOKEN)).thenReturn(client);
when(service.findByIdAndClient(MESSAGE_ID, client)).thenReturn(message);
when(messageMapper.toDTO(message)).thenReturn(dto);
// Do test
MessageDTO result = controller.findById(CLIENT_TOKEN, MESSAGE_ID, request);
// Assertions
verify(clientService).findByToken(CLIENT_TOKEN);
verify(service).findByIdAndClient(MESSAGE_ID, client);
verify(messageMapper).toDTO(message);
assertNotNull(result);
assertThat(result,
allOf(hasProperty("id", notNullValue()), hasProperty("message", is(dto.getMessage())),
hasProperty("subject", is(dto.getSubject())),
hasProperty("senderName", is(dto.getSenderName())),
hasProperty("senderEmail", is(dto.getSenderEmail())),
hasProperty("status", is(MessageStatus.CREATED.name()))));
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.types.service.impl;
import static de.hybris.platform.cmsfacades.constants.CmsfacadesConstants.TYPE_CACHE_EXPIRATION;
import static java.util.function.Function.identity;
import de.hybris.platform.cms2.common.functions.Converter;
import de.hybris.platform.cms2.model.contents.CMSItemModel;
import de.hybris.platform.cmsfacades.data.ComponentTypeData;
import de.hybris.platform.cmsfacades.types.service.ComponentTypeAttributeStructure;
import de.hybris.platform.cmsfacades.types.service.ComponentTypeStructure;
import de.hybris.platform.cmsfacades.types.service.ComponentTypeStructureRegistry;
import de.hybris.platform.cmsfacades.types.service.ComponentTypeStructureService;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.core.model.type.ComposedTypeModel;
import de.hybris.platform.servicelayer.config.ConfigurationService;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException;
import de.hybris.platform.servicelayer.type.TypeService;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Required;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Sets;
/**
* Implementation of the {@link ComponentTypeStructureService} that first attempts to get type using the registered
* structure type {@link ComponentTypeStructureRegistry#getComponentTypeStructure(String)}.
* As a fallback strategy, it creates an instance of the {@link ComponentTypeStructure} by introspecting the Type and its
* attributes.
* This service will be first lookup for the {@link ComposedTypeModel} and check if one of its super type is {@link CMSItemModel}.
* If it passes this verification, then it will convert an instance of {@link ComposedTypeModel} into a new instance of
* {@link ComponentTypeStructure}.
*/
public class GenericComponentTypeStructureService implements ComponentTypeStructureService, InitializingBean
{
protected static final Long DEFAULT_EXPIRATION_TIME = 360L;
private ComponentTypeStructureRegistry componentTypeStructureRegistry;
private TypeService typeService;
private Set<String> typeBlacklistSet;
private ConfigurationService configurationService;
private Converter<ComposedTypeModel, ComponentTypeStructure> composedTypeToStructureConverter;
private Supplier<Map<String, ComponentTypeStructure>> internalComponentTypeStructureMap = initializeInternalStructureMap(
DEFAULT_EXPIRATION_TIME);
/**
* @throws UnknownIdentifierException when the typeCode does not exist
* @throws ConversionException when the type requested does not extend CMSItem
*/
@Override
public ComponentTypeStructure getComponentTypeStructure(final String typeCode)
{
return getInternalComponentTypeStructureMap().get().get(typeCode);
}
@Override
public Collection<ComponentTypeStructure> getComponentTypeStructures()
{
// should contain all types inheriting from CMSItem (except for those in the type blacklist) PLUS the types solely defined in the registry
return getInternalComponentTypeStructureMap().get().values();
}
/**
* Supplier function to initialize the ComponentTypeStructure map.
*/
protected Supplier<Map<String, ComponentTypeStructure>> initializeComponentTypeStructureMap()
{
return () ->
{
final Set<String> typeCodes = Sets.newLinkedHashSet();
// add types that extend CMSItemModel
final ComposedTypeModel cmsItemComposedType = getTypeService().getComposedTypeForCode(CMSItemModel._TYPECODE);
typeCodes.add(cmsItemComposedType.getCode());
cmsItemComposedType.getAllSubTypes()
.stream()
.forEach(subType -> typeCodes.add(subType.getCode()));
// add all types from the registry
typeCodes.addAll(getComponentTypeStructureRegistry().getComponentTypeStructures() //
.stream() //
.map(ComponentTypeStructure::getTypecode) //
.collect(Collectors.toSet()));
// the Set difference contains all valid types we want to support
return typeCodes.stream()
.filter(Objects::nonNull) //
.filter(isAbstractType().negate()) //
.filter(typeCode -> !getTypeBlacklistSet().contains(typeCode))
.map(this::getComponentTypeStructureInternal) //
.collect(Collectors.toMap(ComponentTypeStructure::getTypecode, identity(), (o, o2) -> o));
};
}
/**
* Predicate to test if the composed type represented by the typeCode is abstract.
* <p>
* Returns <tt>TRUE</tt> if the composed type is abstract.
* </p>
*/
protected Predicate<String> isAbstractType()
{
return typeCode -> getTypeService().getComposedTypeForCode(typeCode).getAbstract();
}
/**
* Internal method to get the component type structure for a given typeCode
* @param typeCode the type code that represents the component type structure
* @return the {@link ComponentTypeStructure} represented by this typeCode.
*/
protected ComponentTypeStructure getComponentTypeStructureInternal(final String typeCode)
{
final ComposedTypeModel composedType = getTypeService().getComposedTypeForCode(typeCode);
boolean isCMSItem = composedType.getCode().equals(CMSItemModel._TYPECODE) //
|| composedType.getAllSuperTypes() //
.stream() //
.anyMatch(superType -> StringUtils.equals(superType.getCode(), CMSItemModel._TYPECODE));
// if it is not a CMS Item Type structure, then use what is defined in the registry only
if (!isCMSItem)
{
return getComponentTypeStructureRegistry().getComponentTypeStructure(typeCode);
}
// manually set the category from the registry
final ComponentTypeStructure componentTypeStructure = getComposedTypeToStructureConverter().convert(composedType);
Optional.ofNullable(getComponentTypeStructureRegistry().getComponentTypeStructure(typeCode))
.ifPresent(componentTypeStructureOnRegistry ->
componentTypeStructure.setCategory(componentTypeStructureOnRegistry.getCategory()));
// add populators from the registry
collectTypePopulatorsFromTypeAndAncestorsInRegistry(composedType, componentTypeStructure.getPopulators());
// adds all extra attributes from the registry
collectExtraAttributesFromTypeAndAncestorsInRegistry(composedType, componentTypeStructure.getAttributes());
return componentTypeStructure;
}
/**
* Recursively collects type populators from the registry until it reaches the root type (CMSItem)
* @param composedType the type being used to look for populators
* @param populators the list of populators that has to be modified
*/
protected void collectTypePopulatorsFromTypeAndAncestorsInRegistry(final ComposedTypeModel composedType,
final List<Populator<ComposedTypeModel, ComponentTypeData>> populators)
{
// add populators from the registry
Optional.ofNullable(getComponentTypeStructureRegistry().getComponentTypeStructure(composedType.getCode()))
.ifPresent(componentTypeStructureOnRegistry -> populators.addAll(componentTypeStructureOnRegistry.getPopulators()));
// check if it is necessary to continue digging for new attributes
if (!StringUtils.equals(composedType.getCode(), CMSItemModel._TYPECODE) && composedType.getSuperType() != null)
{
collectTypePopulatorsFromTypeAndAncestorsInRegistry(composedType.getSuperType(), populators);
}
}
/**
* Recursively collects extra attributes that are not in the Data Model, but it is present on the the registry
* @param composedType the type being used to look for populators
* @param attributes
*/
protected void collectExtraAttributesFromTypeAndAncestorsInRegistry(final ComposedTypeModel composedType,
final Set<ComponentTypeAttributeStructure> attributes)
{
final Set<ComponentTypeAttributeStructure> attributesFromRegistry = Optional //
.ofNullable(getComponentTypeStructureRegistry().getComponentTypeStructure(composedType.getCode())) //
.map(ComponentTypeStructure::getAttributes) //
.orElse(Sets.newHashSet());
final Set<String> attrQualifiers = attributes.stream() //
.map(ComponentTypeAttributeStructure::getQualifier) //
.collect(Collectors.toSet());
attributes.addAll(attributesFromRegistry.stream() //
.filter(attributeOnRegistry -> !attrQualifiers.contains(attributeOnRegistry.getQualifier())) //
.collect(Collectors.toList()));
// check if it is necessary to continue digging for new attributes
if (!StringUtils.equals(composedType.getCode(), CMSItemModel._TYPECODE) && composedType.getSuperType() != null)
{
collectExtraAttributesFromTypeAndAncestorsInRegistry(composedType.getSuperType(), attributes);
}
}
protected Supplier<Map<String, ComponentTypeStructure>> getInternalComponentTypeStructureMap()
{
return internalComponentTypeStructureMap;
}
protected Supplier<Map<String, ComponentTypeStructure>> initializeInternalStructureMap(final Long expirationTime)
{
return Suppliers.memoizeWithExpiration(
initializeComponentTypeStructureMap(),
expirationTime,
TimeUnit.MINUTES);
}
@Override
public void afterPropertiesSet() throws Exception
{
this.internalComponentTypeStructureMap = initializeInternalStructureMap(
getConfigurationService().getConfiguration().getLong(TYPE_CACHE_EXPIRATION, DEFAULT_EXPIRATION_TIME));
}
protected TypeService getTypeService()
{
return typeService;
}
@Required
public void setTypeService(final TypeService typeService)
{
this.typeService = typeService;
}
protected Set<String> getTypeBlacklistSet()
{
return typeBlacklistSet;
}
@Required
public void setTypeBlacklistSet(final Set<String> typeBlacklistSet)
{
this.typeBlacklistSet = typeBlacklistSet;
}
protected ConfigurationService getConfigurationService()
{
return configurationService;
}
@Required
public void setConfigurationService(final ConfigurationService configurationService)
{
this.configurationService = configurationService;
}
protected Converter<ComposedTypeModel, ComponentTypeStructure> getComposedTypeToStructureConverter()
{
return composedTypeToStructureConverter;
}
@Required
public void setComposedTypeToStructureConverter(
final Converter<ComposedTypeModel, ComponentTypeStructure> composedTypeToStructureConverter)
{
this.composedTypeToStructureConverter = composedTypeToStructureConverter;
}
protected ComponentTypeStructureRegistry getComponentTypeStructureRegistry()
{
return componentTypeStructureRegistry;
}
@Required
public void setComponentTypeStructureRegistry(final ComponentTypeStructureRegistry componentTypeStructureRegistry)
{
this.componentTypeStructureRegistry = componentTypeStructureRegistry;
}
}
|
package be.bewire.slp.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
// TODO: handle exception here or in ApplicationExceptionHandler
//@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "resource not found")
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException() {
super();
}
public ResourceNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public ResourceNotFoundException(String message) {
super(message);
}
public ResourceNotFoundException(Throwable cause) {
super(cause);
}
}
|
package network.kekejl.com.mvpdemo;
import android.os.SystemClock;
import android.support.v4.widget.SwipeRefreshLayout;
import java.util.ArrayList;
/**
* 作者:tzh on 2016/6/12 11:48
* <p/>
* 类描述:
* <p/>
* 修改描述:
*/
public class ListViewIteratorImpl implements ListViewIteatore {
ArrayList<String> mList = new ArrayList<>();
//业务模型层
@Override
public void loadData(final LoadDataFinishListener loadDataFinishListener) {
// 加载数据的操作
new Thread(){
@Override
public void run() {
SystemClock.sleep(2000);
for(int i = 0;i < 50; i++){
mList.add("中正" + i);
}
loadDataFinishListener.onFinishedLoadData(mList);
}
}.start();
}
//ListViewAdapter lvAdapter,SwipeRefreshLayout sw,
@Override
public void pullDownToRefresh(final ListViewAdapter listViewAdapter, final SwipeRefreshLayout swipeRefreshLayout, final LoadDataFinishListener loadDataFinishListener) {
new Thread(){
@Override
public void run() {
// 模仿耗时操作
SystemClock.sleep(2000);
mList.add(0,"这是下拉刷新出来的数据");
//刷新界面
loadDataFinishListener.onRefresh(listViewAdapter,swipeRefreshLayout);
}
}.start();
}
}
|
// Kufas.ru 6.1.1.2
package hw.gorovtsov.mathtesting.tasks;
import hw.gorovtsov.mathtesting.input.*;
;
public class Second {
public static void main(String[] args) {
double a;
double b;
double c;
double d;
double[] vars = new double[4];
double rez;
NumSetFour s = new NumSetFour();
vars = s.go();
a = vars[0];
b = vars[1];
c = vars[2];
d = vars[3];
rez = (a * b) / (c * d) - ((a * b - c) / (c * d));
System.out.println("Result: " + rez);
}
}
|
package com.moon.institution.serviceimpl;
import com.moon.institution.dao.IInstitutionDao;
import com.moon.institution.entity.Institution;
import com.moon.institution.service.IInstitutionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Service("institutionService")
public class InstitutionServiceImpl implements IInstitutionService {
@Resource(name = "institutionDao")
private IInstitutionDao institutionDao;
@Transactional
public Institution getInstitutionByItem(String id) {
return new Institution();
}
}
|
package com.lot.parking.division;
import lombok.Data;
@Data
public class ElectricDivision extends Division {
public ElectricDivision(int availableCount) {
super(availableCount);
}
}
|
package com.training.day17.collections;
import java.util.LinkedList;
import java.util.List;
public class FifthLinkedList {
public static void main(String[] args) {
LinkedList list = new LinkedList();
//1.Adding elements to the LinkedList
list.add("Harry");
list.add("Ajeet");
list.add("Tom");
list.add("Steve");
// Displaying LinkedList elements
System.out.println("LinkedList elements: "+list); //[Harry, Ajeet, Tom, Steve]
// Adding another element
list.add("Kate");
// Displaying LinkedList elements after add(E e)
System.out.println("LinkedList elements: "+list); //[Harry, Ajeet, Tom, Steve, Kate]
// 2.Adding new Element at 4TH Position
list.add(3, "NEW ELEMENT");
System.out.println("LinkedList elements After Addition:" + list);//[Harry, Ajeet, Tom, NEW ELEMENT, Steve, Kate]
// 3. Adding elements at first and last of the list
list.addFirst("first"); // list.offerFirst("first")
list.addLast("last");//list.offerLast("last")
System.out.println("LinkedList elements:" + list);//[first, Harry, Ajeet, Tom, NEW ELEMENT, Steve, Kate, last]
// 4. removing first and last elements from LinkedList
list.removeFirst(); // list.offerFirst("first")
list.removeLast();//list.offerLast("last")
System.out.println("\nList Elements after Remove:" + list); //[Harry, Ajeet, Tom, NEW ELEMENT, Steve, Kate]
// 5. removing element from sepecified index
list.remove(3);
System.out.println("\nList Elements after Remove:" + list); //[Harry, Ajeet, Tom, Steve, Kate]
// 6. removing first occurenece of an element using remove() or removeFirst() ore removeFirstOccurence()
list.add("Harry");
System.out.println(list);
list.remove("Harry"); // list.rempoveFirst("Harry") or list.removeFirstOccurence("Harry")
System.out.println("List Elements after Remove:" + list);
/* //7. removign all elements of linked list
list.clear();
System.out.println("elements after removal" + list);
*/
// 8. append all elements of linked list to another list
LinkedList subList = new LinkedList();
subList.add("One");
subList.add("Two");
subList.add("Three");
subList.add("Four");
list.addAll(subList);
System.out.println("list after adding sublist:" + list);
}
}
|
package banking.exceptions.sign_up_exceptions;
public class UsernameAlreadyExistException extends Exception {
/**
*
*/
private static final long serialVersionUID = 2210029269480514960L;
}
|
package com.tencent.mm.plugin.webview.ui.tools.fts;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.bg.d;
import com.tencent.mm.plugin.websearch.api.p;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.fts.widget.FTSMainUIHotWordLayout$a;
import com.tencent.tmassistantsdk.storage.table.DownloadSettingTable$Columns;
import java.util.HashMap;
import java.util.Map;
class FTSSOSHomeWebViewUI$17 implements OnClickListener {
final /* synthetic */ FTSSOSHomeWebViewUI qeq;
FTSSOSHomeWebViewUI$17(FTSSOSHomeWebViewUI fTSSOSHomeWebViewUI) {
this.qeq = fTSSOSHomeWebViewUI;
}
public final void onClick(View view) {
Bundle bundle;
Map hashMap;
FTSMainUIHotWordLayout$a fTSMainUIHotWordLayout$a = (FTSMainUIHotWordLayout$a) view.getTag();
switch (fTSMainUIHotWordLayout$a.bYt) {
case 1:
if (this.qeq.qdo) {
FTSSOSHomeWebViewUI.o(this.qeq);
FTSSOSHomeWebViewUI.e(this.qeq, 0);
this.qeq.bXk().clearText();
this.qeq.bXk().j(fTSMainUIHotWordLayout$a.utK, null);
this.qeq.bXk().aQY();
FTSSOSHomeWebViewUI.a(this.qeq).Dd(13);
try {
bundle = new Bundle();
bundle.putInt(DownloadSettingTable$Columns.TYPE, 0);
bundle.putBoolean("isHomePage", true);
bundle.putInt("scene", 20);
bundle = FTSSOSHomeWebViewUI.p(this.qeq).p(4, bundle);
hashMap = new HashMap();
hashMap.put("sceneActionType", "2");
hashMap.put("recommendId", FTSSOSHomeWebViewUI.q(this.qeq).getSearchId());
FTSSOSHomeWebViewUI.t(this.qeq).post(new 1(this, bundle, hashMap));
break;
} catch (Exception e) {
break;
}
}
return;
case 4:
Intent intent = new Intent();
intent.putExtra("rawUrl", fTSMainUIHotWordLayout$a.jumpUrl);
intent.putExtra("convertActivityFromTranslucent", false);
d.b(ad.getContext(), "webview", ".ui.tools.WebViewUI", intent);
break;
}
try {
hashMap = new HashMap();
hashMap.put("isclick", Integer.valueOf(1));
hashMap.put("scene", Integer.valueOf(20));
hashMap.put("recommendid", FTSSOSHomeWebViewUI.q(this.qeq).getSearchId());
hashMap.put("businesstype", Integer.valueOf(0));
hashMap.put("docid", fTSMainUIHotWordLayout$a.utK != null ? Uri.encode(fTSMainUIHotWordLayout$a.utK) : "");
hashMap.put("docpos", Integer.valueOf(fTSMainUIHotWordLayout$a.utL + 1));
hashMap.put("ishomepage", Integer.valueOf(1));
hashMap.put("typepos", Integer.valueOf(1));
hashMap.put("jumpurl", Uri.encode(fTSMainUIHotWordLayout$a.jumpUrl));
String U = p.U(hashMap);
bundle = new Bundle();
bundle.putString("logString", U);
FTSSOSHomeWebViewUI.u(this.qeq).g(131, bundle);
} catch (Exception e2) {
x.w("MicroMsg.FTS.FTSSOSHomeWebViewUI", "onHotwordCellClickListener cgi report fail for %s", new Object[]{e2.toString()});
}
}
}
|
package org.gtap;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GCanvas extends JPanel implements MouseListener, MouseMotionListener, KeyListener {
/**
*
*/
private static final long serialVersionUID = 1L;
SimpleGraph graph;
GUndoManager undoManager;
Node currentNode;
Edge currentEdge;
int numNodes = 0;
public GCanvas() {
graph = new SimpleGraph();
undoManager = new GUndoManager(graph);
setBackground(Color.white);
setBorder(BorderFactory.createLineBorder(Color.black));
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.addKeyListener(this);
this.setFocusable(true);
}
private void moveNode(Node n, int x, int y) {
n.setX(x);
n.setY(y);
ArrayList<Edge> edges = n.getEdges();
for (Edge e : edges) {
e.nodeMoved(n);
}
repaint();
}
private Node selectNode(int x, int y) {
Node current = null;
for (Node n : graph.getNodes()) {
if (n.contains(x, y)) {
current = n;
}
}
return current;
}
public void removeNode(Node n) {
graph.removeNode(n);
repaint();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (Edge e : graph.getEdges()) {
e.paint(g2);
}
for (Node n : graph.getNodes()) {
n.paint(g2);
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
currentNode = new Node(e.getX(), e.getY());
graph.addNode(currentNode);
undoManager.add(new GraphElement(currentNode, null));
currentNode = null;
numNodes++;
repaint();
}
// FOR TESTING
// System.out.println(nodeList);
// System.out.println(edgeList);
}
@Override
public void mousePressed(MouseEvent e) {
currentNode = this.selectNode(e.getX(), e.getY());
if (SwingUtilities.isRightMouseButton(e) && currentNode != null) {
currentEdge = new Edge(currentNode, e.getX(), e.getY());
graph.addEdge(currentEdge);
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
// get the second node the edge will be attached to
Node endNode = selectNode(e.getX(), e.getY());
// check if it is valid, if not remove, if yes add
if (endNode == null || currentNode.hasNeighbor(endNode) || currentNode == endNode) {
graph.removeEdge(currentEdge);
} else {
currentEdge.setNode2(endNode);
undoManager.add(new GraphElement(null, currentEdge));
}
currentEdge = null;
repaint();
}
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseDragged(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && currentNode != null) {
this.moveNode(currentNode, e.getX(), e.getY());
} else if (SwingUtilities.isRightMouseButton(e) && currentNode != null) {
currentEdge.setX2(e.getX());
currentEdge.setY2(e.getY());
repaint();
}
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
if ((e.getKeyCode() == KeyEvent.VK_Z) && (e.isControlDown())) {
undoManager.undo();
repaint();
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
|
package com.github.igorsuhorukov.gcode;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.impl.ScheduledPollConsumer;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The LinuxCnc consumer.
*/
public class LinuxCncConsumer extends ScheduledPollConsumer {
private static final Logger LOG = LoggerFactory.getLogger(LinuxCncConsumer.class);
private final LinuxCncEndpoint endpoint;
public LinuxCncConsumer(LinuxCncEndpoint endpoint, Processor processor) {
super(endpoint, processor);
this.endpoint = endpoint;
ObjectHelper.notEmpty(endpoint.getCommand(), "command");
}
@Override
protected int poll() throws Exception {
Exchange exchange = endpoint.createExchange();
try {
String result = endpoint.sendCncCommand(endpoint.getCommand());
exchange.getIn().setBody(result);
} catch (Exception e) {
exchange.setException(e);
}
try {
// send message to next processor in the route
getProcessor().process(exchange);
return 1; // number of messages polled
} finally {
// log exception if an exception occurred and was not handled
if (exchange.getException() != null) {
getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
}
}
}
}
|
package com.github.grimsa.aoc2018.day3;
import java.awt.*;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public final class Area extends Rectangle {
private static final Pattern CLAIM_PATTERN = Pattern.compile("^#(?<id>\\d+) @ (?<left>\\d+),(?<top>\\d+): (?<width>\\d+)x(?<height>\\d+)$");
private final int id;
public static Area parse(final String areaString) {
final var matcher = CLAIM_PATTERN.matcher(areaString);
if (!matcher.matches()) {
throw new IllegalArgumentException();
}
return new Area(
Integer.parseInt(matcher.group("id")),
Integer.parseInt(matcher.group("left")),
Integer.parseInt(matcher.group("top")),
Integer.parseInt(matcher.group("width")),
Integer.parseInt(matcher.group("height"))
);
}
private Area(final int id, final int distanceFromLeft, final int distanceFromTop, final int width, final int height) {
super(distanceFromLeft, distanceFromTop, width, height);
this.id = id;
}
public Stream<Square> squares() {
return IntStream.range(0, height).boxed()
.flatMap(relativeY -> IntStream.range(0, width)
.mapToObj(relativeX -> new Square(x + relativeX, y + relativeY))
);
}
@Override
public boolean intersects(final Rectangle other) {
return this != other
&& super.intersects(other);
}
public int getId() {
return id;
}
public static final class Square {
private final int x;
private final int y;
private Square(final int x, final int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
final var square = (Square) other;
return x == square.x &&
y == square.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
}
|
package com.aitest.web.util;
import org.springframework.stereotype.Component;
@Component
public class ClassTransferUtil {
}
|
package com.df.Dialog;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.df.network.protocol;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.SystemColor;
//UDP协议的窗口
public class UDPDialog extends JDialog {
static protocol pro = new protocol();
private final JPanel contentPanel = new JPanel();
private JTextField scrport;
private JTextField destport;
private JTextField len;
/**
* Create the dialog.
*/
public UDPDialog(protocol pro) {
this.pro = pro;
setTitle("UDP");
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setForeground(SystemColor.desktop);
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
JLabel lblNewLabel = new JLabel("源端口");
lblNewLabel.setBounds(69, 45, 82, 39);
contentPanel.add(lblNewLabel);
}
{
scrport = new JTextField();
scrport.setText(pro.udp.scr_port);
scrport.setBounds(161, 54, 91, 21);
contentPanel.add(scrport);
scrport.setColumns(10);
}
{
JLabel lblNewLabel_1 = new JLabel("目标端口");
lblNewLabel_1.setBounds(69, 112, 54, 15);
contentPanel.add(lblNewLabel_1);
}
{
destport = new JTextField();
destport.setText(pro.udp.dest_port);
destport.setBounds(163, 109, 91, 21);
contentPanel.add(destport);
destport.setColumns(10);
}
{
JLabel lblNewLabel_2 = new JLabel("长度");
lblNewLabel_2.setBounds(69, 165, 54, 15);
contentPanel.add(lblNewLabel_2);
}
{
len = new JTextField();
len.setText(pro.udp.length);
len.setBounds(161, 162, 66, 21);
contentPanel.add(len);
len.setColumns(10);
}
}
}
|
package com.adelegue.reactivestreams;
import com.ning.http.client.AsyncCompletionHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.Response;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static com.adelegue.reactivestreams.utils.Utils.print;
public class JavaStream {
public static void main(String[] args) {
// collections();
// streams();
// streamsBloquing();
streamsAsync();
}
public static void collections() {
List<String> minuscules = Arrays.asList("a", "b", "c", "d", "e");
List<String> majuscules = new ArrayList<>();
for (String elt : minuscules) {
majuscules.add(elt.toUpperCase());
}
majuscules.forEach(System.out::println);
}
public static void mapFlatMap() {
Stream<Integer> ints = Arrays.asList(1, 2, 3, 4).stream();
Stream<String> strings = ints.map(i -> String.valueOf(i));
Stream<String> phrases = Arrays.asList("abcd", "efg", "hijk", "lmnopq", "rst", "uvw", "xyz").stream();
Stream<Stream<String>> letters = phrases.map(p -> Stream.of(p.split("")));
Stream<String> letters2 = phrases.flatMap(p -> Stream.of(p.split("")));
}
public static void streams() {
List<String> minuscule = Arrays.asList("a", "b", "c", "d", "e");
List<String> majuscules = minuscule
.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
majuscules.forEach(System.out::println);
}
public static void streamsBloquing() {
Stream.iterate(0, i -> i + 1)
.map(String::valueOf)
.map(id -> getFromApi(id))
.map(String::toUpperCase)
.forEach(System.out::println);
}
public static String getFromApi(String id){
try {
return asyncHttpClient.prepareGet("http://localhost:8080/api/" + id).execute().get().getResponseBody();
} catch (IOException | InterruptedException | ExecutionException e) {
throw new RuntimeException("Oups", e);
}
}
public static void streamsAsync() {
List<CompletableFuture<String>> results = IntStream.range(0, 20).boxed()
.filter(i -> i % 2 == 0)
.map(String::valueOf)
.map(JavaStream::getFromAsyncApi)
.map(value -> value.thenApply(String::toUpperCase))
.collect(Collectors.toList());
CompletableFuture<List<String>> futureList = sequence(results);
futureList.thenAccept(list -> list.forEach(System.out::println));
}
public static void streamsAsync2() {
IntStream.range(0, 20).boxed()
.filter(i -> i % 2 == 0)
.map(String::valueOf)
.flatMap(id -> Stream.of(getFromAsyncApi(id)))
// .map(String::toUpperCase)
.collect(Collectors.toList());
}
private static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) {
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
.thenApply(any -> futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.<T>toList())
);
}
private static AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
public static CompletableFuture<String> getFromAsyncApi(String id){
CompletableFuture<String> completableFuture = new CompletableFuture<>();
asyncHttpClient.prepareGet("http://localhost:8080/api/" + id).execute(new AsyncCompletionHandler<Response>() {
@Override
public Response onCompleted(Response response) throws Exception {
completableFuture.complete(response.getResponseBody());
return response;
}
@Override
public void onThrowable(Throwable t) {
completableFuture.completeExceptionally(t);
}
});
return completableFuture;
}
public static void subscribe() {
Publisher<String> publisher = null;
publisher.subscribe(new Subscriber<String>() {
private Subscription subscription;
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
this.subscription.request(1);
}
@Override
public void onNext(String s) {
System.out.println("onNext "+s);
this.subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
System.out.println("Oups : "+throwable.getMessage());
}
@Override
public void onComplete() {
System.out.println("End");
}
});
}
}
|
package pkg1;
public class TestCons {
public TestCons()
{
this(22,23,41);
System.out.println("this is default constructor");
}
public TestCons(int a)
{
this();
System.out.println("this is 1 parameterized constuctor");
}
public TestCons(int a,int b)
{
this(22);
System.out.println("this is 2 parameterized constructor");
}
public TestCons(int a,int b,int c)
{
System.out.println("This is 3 parameterized constructor");
}
public static void main(String[] args) {
TestCons t1=new TestCons(33,23);
// TODO Auto-generated method stub
}
}
|
package rjm.romek.awscourse.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentHealthRequest;
import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentHealthResult;
@Service
public class ElasticBeanstalkService {
private static final String ALL = "All";
private static final String GREEN = "Green";
private final AWSElasticBeanstalk amazonElasticBeanstalk;
@Autowired
public ElasticBeanstalkService(AWSElasticBeanstalk amazonElasticBeanstalk) {
this.amazonElasticBeanstalk = amazonElasticBeanstalk;
}
public boolean environmentHealthy(String environmentName) {
DescribeEnvironmentHealthResult describeEnvironmentHealthResult =
amazonElasticBeanstalk.describeEnvironmentHealth(
new DescribeEnvironmentHealthRequest()
.withEnvironmentName(environmentName)
.withAttributeNames(ALL)
);
return GREEN.equals(describeEnvironmentHealthResult.getColor());
}
}
|
package com.tencent.mm.plugin.freewifi.model;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.x;
public final class h {
boolean heV;
a jka;
BroadcastReceiver jkb;
/* synthetic */ h(byte b) {
this();
}
private h() {
this.heV = false;
this.jkb = new 1(this);
}
public final boolean a(a aVar) {
if (this.heV) {
return false;
}
this.heV = true;
this.jka = aVar;
WifiManager wifiManager = (WifiManager) ad.getContext().getSystemService("wifi");
if (wifiManager == null) {
x.e("MicroMsg.FreeWifi.WifiScanReceiver", "wifiDetectingTask, get wifi manager failed");
return false;
}
ad.getContext().registerReceiver(this.jkb, new IntentFilter("android.net.wifi.SCAN_RESULTS"));
wifiManager.startScan();
return true;
}
}
|
package com.coco.winter.common.serviceImpl;
import com.coco.winter.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName GetNewJwtToken
* @Description 获取新的JwtToken
* @Author like
* @Data 2018/11/16 17:18
* @Version 1.0
**/
@Service
public class GetNewJwtToken {
@Autowired
private RedisUtil redisUtil;
/**
* 获取当前用户token未过期时,新创建的token值
* @return
*/
public Map<String, Object> getNewJWTToken(HttpServletRequest request) {
String username = "";
if(StringUtils.isNotBlank(request.getParameter("useraccount"))){
username = request.getParameter("useraccount");
}else {
Subject subject = SecurityUtils.getSubject();
//为了方便测试,增加不登录也可以测试后台方法
if(null == subject.getPrincipal()){
Map<String, Object> map = new HashMap<String, Object>();
map.put("jwtToken", "");
return map;
}
username = String.valueOf(subject.getSession().getId());
}
String redisToken = String.valueOf(redisUtil.get("pansoft:tokenKey:"+username));
Map<String, Object> map = new HashMap<String,Object>();
map.put("jwtToken", redisToken);
return map;
}
}
|
package com.bierocratie.model.accounting;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* Created with IntelliJ IDEA.
* User: pir
* Date: 31/10/14
* Time: 16:52
* To change this template use File | Settings | File Templates.
*/
public class CategoryAndMonth {
private Category category;
private String month;
private BigInteger amount;
public CategoryAndMonth(Category category, String month, BigDecimal amount) {
if (category != null) {
this.category = category;
} else {
this.category = new Category();
}
this.month = month;
if (amount != null) {
this.amount = amount.toBigInteger();
} else {
this.amount = BigInteger.ZERO;
}
}
public CategoryAndMonth(Category category, String month, double amount) {
if (category != null) {
this.category = category;
} else {
this.category = new Category();
}
this.month = month;
this.amount = new BigDecimal(amount).toBigInteger();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CategoryAndMonth)) return false;
CategoryAndMonth that = (CategoryAndMonth) o;
if (category != null ? !category.equals(that.category) : that.category != null) return false;
if (!month.equals(that.month)) return false;
return true;
}
@Override
public int hashCode() {
int result = category != null ? category.hashCode() : 0;
result = 31 * result + month.hashCode();
return result;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public BigInteger getAmount() {
return amount;
}
public void setAmount(BigInteger amount) {
this.amount = amount;
}
}
|
package com.hiwes.cores.thread.thread2.Thread0215;
/**
* 验证第二个结论:
* 当其他线程执行X对象中synchronized同步方法时呈同步效果;
*/
public class MyThread12 extends Thread {
private Service12 service;
private MyObject2 object;
public MyThread12(Service12 service, MyObject2 object) {
super();
this.service = service;
this.object = object;
}
@Override
public void run() {
super.run();
service.testMethod1(object);
}
}
class MyThread12_2 extends Thread {
private MyObject2 object;
public MyThread12_2(MyObject2 object) {
super();
this.object = object;
}
@Override
public void run() {
super.run();
object.speedPrintString();
}
}
class MyObject2 {
synchronized public void speedPrintString() {
System.out.println("speedPrintString ____getLock time = " + System.currentTimeMillis() + " run ThreadName = " + Thread.currentThread().getName());
System.out.println("------------------------");
System.out.println("speedPrintString releaseLock time = " + System.currentTimeMillis() + " run ThreadName = " + Thread.currentThread().getName());
}
}
class Service12 {
public void testMethod1(MyObject2 object) {
synchronized (object) {
try {
System.out.println("testMethod1 ____getLock time = " + System.currentTimeMillis() + " run ThreadName = " + Thread.currentThread().getName());
Thread.sleep(5000);
System.out.println("testMethod2 releaseLock time = " + System.currentTimeMillis() + " run ThreadName = " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Run12 {
public static void main(String[] args) throws InterruptedException {
Service12 service = new Service12();
MyObject2 object = new MyObject2();
MyThread12 a = new MyThread12(service, object);
a.setName("A");
a.start();
Thread.sleep(100);
MyThread12_2 b = new MyThread12_2(object);
b.setName("B");
b.start();
}
}
|
import processing.core.PApplet;
import processing.core.PImage;
public class HybridImage extends PApplet{
PImage image;
PImage image2;
PImage resImage;
public void setup() {
image = loadImage("../data/retrato1.jpg");
image2 = loadImage("../data/retrato2.jpg");
}
int convolution(int x, int y, float[][] matrix, int matrixsize, PImage img) {
float rtotal = 0.0f;
float gtotal = 0.0f;
float btotal = 0.0f;
int offset = matrixsize / 2;
// Loop through convolution matrix
for (int i = 0; i < matrixsize; i++){
for (int j= 0; j < matrixsize; j++){
// What pixel are we testing
int xloc = x+i-offset;
int yloc = y+j-offset;
int loc = xloc + img.width*yloc;
// Make sure we have not walked off the edge of the pixel array
loc = constrain(loc,0,img.pixels.length-1);
// Calculate the convolution
// We sum all the neighboring pixels multiplied by the values in the convolution matrix.
rtotal += (red(img.pixels[loc]) * matrix[i][j]);
gtotal += (green(img.pixels[loc]) * matrix[i][j]);
btotal += (blue(img.pixels[loc]) * matrix[i][j]);
}
}
// Make sure RGB is within range
rtotal = constrain(rtotal,0,255);
gtotal = constrain(gtotal,0,255);
btotal = constrain(btotal,0,255);
// Return the resulting color
return color(rtotal,gtotal,btotal);
}
}
|
package com.lizogub.LabWork9.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import static org.testng.Assert.assertEquals;
public class DashboardPage {
WebDriver driver;
String dictionaryButtonXPath = "//*[@data-a-target='topmenu-dict']";
String accountMenuDivXPath = "//*[@data-a-target='topmenu-account']";
String currentURL = "https://lingualeo.com/ru/dashboard";
public DashboardPage(WebDriver driver){
this.driver = driver;
}
public void openDictionary(){
String dictionaryURL = driver.findElement(By.xpath(dictionaryButtonXPath)).getAttribute("href");
driver.get(dictionaryURL);
}
public ExpectedCondition isLoggedIn(){
return ExpectedConditions.visibilityOfElementLocated(By.xpath(accountMenuDivXPath));
}
public void checkCurrentPage(){
assertEquals(driver.getCurrentUrl(),currentURL,"Current url doesn't match " + currentURL);
}
}
|
package com.xiaoxiao.controller;
import com.xiaoxiao.pojo.XiaoxiaoAdminMessage;
import com.xiaoxiao.service.backend.TinyAdminManagerService;
import com.xiaoxiao.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*
* @project_name:xiaoxiao_final_blogs
* @date:2019/12/2:11:50
* @author:shinelon
* @Describe:
*/
@RestController
@RequestMapping(value = "/admin/tiny_admin_manager_service")
@CrossOrigin(origins = "*",maxAge = 3600)
@Api("后台管理")
public class TinyAdminManagerController
{
@Autowired
private TinyAdminManagerService tinyAdminManagerService;
@ApiOperation(value = "查找全部的后台管理菜单", response = Result.class, notes = "查找全部的后台管理菜单")
@PostMapping(value = "/find_all_manager")
public Result findAllManager()
{
return this.tinyAdminManagerService.findAllManager();
}
@ApiOperation(value = "查询全部的后台管理信息", response = Result.class, notes = "查询全部的后台管理信息")
@PostMapping(value = "/find_manager_all")
public Result findAllManager(@RequestParam(name = "page", defaultValue = "1") Integer page,
@RequestParam(name = "rows", defaultValue = "10") Integer rows)
{
return this.tinyAdminManagerService.findAllManager(page,rows);
}
/**
* 插入
* @param message
* @return
*/
@ApiOperation(value = "插入一个的新的后台菜单",response = Result.class,notes = "插入一个的新的后台菜单")
@PostMapping(value = "/insert")
public Result insert(@RequestBody XiaoxiaoAdminMessage message){
return this.tinyAdminManagerService.insert(message);
}
/**
* 删除
* @param adminId
* @return
*/
@ApiOperation(value = "删除一个后台菜单",response = Result.class,notes = "删除一个后台菜单")
@PostMapping(value = "/delete")
public Result deleteAdminManager(@RequestParam(name = "adminId") String adminId){
return this.tinyAdminManagerService.deleteAdminManager(adminId);
}
}
|
package tilePack;
import org.newdawn.slick.Image;
public class Platform extends Tile{
public Platform(String name, Image Frames) {
super(name, Frames);
this.setTag("platform");
// TODO Auto-generated constructor stub
}
}
|
package com.example.lebox;
import androidx.annotation.NonNull;
import androidx.camera.camera2.internal.PreviewConfigProvider;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.impl.ImageAnalysisConfig;
import androidx.camera.core.impl.ImageCaptureConfig;
import androidx.camera.core.impl.ImageOutputConfig;
import androidx.camera.core.impl.PreviewConfig;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraDevice;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.AlteredCharSequence;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.Toast;
import com.camerakit.CameraKitView;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import static android.os.Environment.DIRECTORY_DCIM;
public class MainActivity extends Activity implements LifecycleOwner {
private String correct ="\"TRUE\"";
private LifecycleRegistry lifecycleRegistry;
private Button ViewPageButton, ScanPageButton,lock;
private ImageCapture imageCapture;
private Executor cameraExecutor = Executors.newSingleThreadExecutor();
public String str_ifView="some",str_qrCode,str_coorr="some",str;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lifecycleRegistry = new LifecycleRegistry(this);
lifecycleRegistry.markState(Lifecycle.State.CREATED);
ifview thread = new ifview();
thread.start();
intialUi();
changePage();
// startcamera();
}
@Override
protected void onStart() {
super.onStart();
lifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycleRegistry;
}
class ifview extends Thread {
OkHttpClient client = new OkHttpClient();
Request request_ifview = new Request.Builder().url("http://120.101.8.52/aubox604/WebService1.asmx/ifvideo?boxnumber=0407").build();
@Override
public void run() {
client.newCall(request_ifview).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
str_ifView = response.body().string();
}
});
}
}
class qr extends Thread {
OkHttpClient client_qrcode = new OkHttpClient();
Request request_qrcode= new Request.Builder().url(("http://120.101.8.52/aubox604/WebService1.asmx/ifopen?QRcode="+str_qrCode+"&boxnumber=0407")).build();
@Override
public void run() {
client_qrcode.newCall(request_qrcode).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
str_coorr = response.body().string();
}
});
}
}
class vi extends Thread {
OkHttpClient client_video = new OkHttpClient();
Request request_video= new Request.Builder().url(("http://120.101.8.52/aubox604/WebService1.asmx/Updatevideostatus?videostatus=1&boxnumber=0407")).build();
@Override
public void run() {
client_video.newCall( request_video).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
str = response.body().toString();
}
});
}
}
class lock extends Thread {
OkHttpClient client_lock = new OkHttpClient();
Request request_lock= new Request.Builder().url(("http://120.101.8.52/aubox604/WebService1.asmx/Updatearduinolock?arduinolock=1&boxnumber=0407")).build();
@Override
public void run() {
client_lock.newCall( request_lock).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
}
});
}
}
class ulock extends Thread {
OkHttpClient client_lock = new OkHttpClient();
Request request_lock= new Request.Builder().url(("http://120.101.8.52/aubox604/WebService1.asmx/Updatearduinolock?arduinolock=0&boxnumber=0407")).build();
@Override
public void run() {
client_lock.newCall( request_lock).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
}
});
}
}
private void intialUi() {
ViewPageButton = findViewById(R.id.btn_view);
ScanPageButton = findViewById(R.id.btn_scan);
lock =(Button)findViewById(R.id.close);
}//初始化ui
private void scanFrameSet() {
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);//選擇掃描qrcode
integrator.setCameraId(1);//相機前後鏡頭調整,1為前鏡頭,0為後鏡頭
integrator.setCaptureActivity(Scan.class);//抓取自己定義的頁面
integrator.setBeepEnabled(false);//掃描後有沒有提示音
integrator.setBarcodeImageEnabled(false);
integrator.setPrompt(" ");//最下方的提示字
integrator.initiateScan();//初始化掃描設定
} //掃描條碼之設定
private void setDiaolgString(String scanResult) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);//設定對話框內容
builder.setTitle("掃描結果");//對話框標題
builder.setMessage("掃描結果:" + scanResult + ":正確");//對話框內容
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {//點擊確定後跳轉至視訊頁
if( correct.equals(str_ifView) && correct.equals(str_coorr))
{
vi thread2 = new vi();
thread2.start();
Intent intents=new Intent();
intents.setClass(MainActivity.this,view.class);
startActivity(intents);
}
else if(correct.equals(str_coorr))
{
lock threadLock = new lock();
threadLock.setPriority(1);
threadLock.start();
}
}
});//對話框按鈕
AlertDialog dialog = builder.create();
dialog.show();//顯示對話框
}//傳送文字至對話框內容中
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "You cancelled the scanning", Toast.LENGTH_SHORT).show();
} else {
str_qrCode = result.getContents();
qr thread1 = new qr();
thread1.start();
System.out.println( str_coorr);
setDiaolgString(result.getContents());//顯示掃描結果於對話框
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}//掃描後執行之動作
private void changePage() {
ViewPageButton.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intentv = new Intent();
intentv.setClass(MainActivity.this, input.class);
startActivity(intentv);
}
});//換到視訊頁
ScanPageButton.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
//Intent intentv = new Intent();
//intentv.setClass(MainActivity.this, camera.class);
//startActivity(intentv);
scanFrameSet();
}
});//換到掃描頁
lock.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ulock thread_lock = new ulock();
thread_lock .start();
}
});
}
private void takepic(){
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//抓取當下日期
Date curDate = new Date(System.currentTimeMillis());//抓取當下時間
String str = sDateFormat.format(curDate);//當下日期+時間的字串
File savedPhoto = new File(Environment.getExternalStorageDirectory(), str+".jpg");//儲存空間的路徑
ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(savedPhoto).build();
imageCapture.takePicture(outputFileOptions, (Executor) cameraExecutor, new ImageCapture.OnImageSavedCallback() {
@Override
public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
System.out.println(outputFileResults);
}
@Override
public void onError(@NonNull ImageCaptureException exception) {
System.out.println("error");
}
});
}
@SuppressLint("RestrictedApi")
private void startcamera() {
ListenableFuture cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_FRONT).build();
imageCapture = new ImageCapture.Builder().setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY).setCameraSelector(cameraSelector).build();
ImageAnalysis imageAnalysis = new ImageAnalysis.Builder().setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).build();
CameraX.bindToLifecycle((LifecycleOwner) this, cameraSelector,imageAnalysis, imageCapture);
}, ContextCompat.getMainExecutor(this));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.