text stringlengths 10 2.72M |
|---|
package clib.javafx.i18n;
import java.awt.ComponentOrientation;
import java.util.Locale;
import java.util.ResourceBundle;
import org.jetbrains.annotations.Nullable;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
import javafx.collections.ObservableSet;
import javafx.collections.SetChangeListener;
import javafx.geometry.NodeOrientation;
/**
* <p><b>Warning!</b> There are some reasons to think twice before using this class:</p>
* <br>
* <p><b>1) NOT tested</b> on complicated apps.</p>
* <p><b>2) NOT optimized</b> very well. So, it may use too much memory.</p>
* <p><b>3) NOT completed.</b> There are still features to be added.</p>
* <p><b>4) NOT documented.</b> You must first read the example codes in the module "Examples"</p>
*/
@SuppressWarnings("unchecked")
public class I18N
{
private static final ObjectProperty<Locale> LOCALE = new SimpleObjectProperty<>();
private static final SetProperty<Locale> SUPPORTED_LOCALES = new SimpleSetProperty<>();
private static final MapProperty<String, ResourceBundle> BUNDLES = new SimpleMapProperty<>();
private static final MapProperty<StringProperty, I18NString> BINDINGS = new SimpleMapProperty<>();
private static final SetProperty<ObjectProperty<NodeOrientation>> ORIENTATIONS = new SimpleSetProperty<>();
private static final ObjectProperty<NodeOrientation> ORIENTATION = new SimpleObjectProperty<>();
static
{
SUPPORTED_LOCALES.set(FXCollections.observableSet());
BUNDLES.set(FXCollections.observableHashMap());
BINDINGS.set(FXCollections.observableHashMap());
ORIENTATIONS.set(FXCollections.observableSet());
ORIENTATIONS.addListener((SetChangeListener<ObjectProperty<NodeOrientation>>) change ->
{
if (change.wasAdded()) change.getElementAdded().set(ORIENTATION.get());
});
ORIENTATION.addListener((observable, old, newValue) -> ORIENTATIONS.forEach(p -> p.set(newValue)));
LOCALE.addListener((observable, oldValue, newValue) -> ORIENTATION.set(getOrientation(newValue)));
}
public static void addBundle(String baseName)
{
getSupportedLocales().forEach(locale ->
BUNDLES.put(
locale.toLanguageTag() + ':' + baseName.substring(baseName.lastIndexOf('.') + 1),
ResourceBundle.getBundle(baseName, locale)));
}
private static boolean getLocaleAutomatically()
{
Locale defaultLocale = Locale.getDefault();
Locale defaultLanguage = new Locale(defaultLocale.getLanguage());
if (getSupportedLocales().contains(defaultLocale)) LOCALE.set(defaultLocale);
else if (getSupportedLocales().contains(defaultLanguage)) LOCALE.set(defaultLanguage);
else return false;
return true;
}
public static void setLocale(Locale locale)
{
setLocale(locale, false);
}
public static void setLocale(Locale defaultLocale, boolean autoDetect)
{
//noinspection StatementWithEmptyBody
if (autoDetect && getLocaleAutomatically()) ;
else I18N.LOCALE.set(defaultLocale);
}
private static NodeOrientation getOrientation(Locale locale)
{
ComponentOrientation awtOrientation = ComponentOrientation.getOrientation(locale);
if (awtOrientation.equals(ComponentOrientation.RIGHT_TO_LEFT)) return NodeOrientation.RIGHT_TO_LEFT;
else return NodeOrientation.LEFT_TO_RIGHT;
}
public static void createBinding(String bundleKey, StringProperty textProperty, String key, Object... args)
{
I18NString i18NString = new I18NString(bundleKey);
textProperty.bind(i18NString);
if (args.length > 0) i18NString.set(key, args);
else i18NString.set(key);
BINDINGS.put(textProperty, i18NString);
}
public static void updateBinding(StringProperty textProperty, @Nullable String key, Object... args)
{
I18NString i18NString = BINDINGS.get(textProperty);
if (key == null) i18NString.update(args);
else if (args.length > 0) i18NString.set(key, args);
else i18NString.set(key);
}
public static void updateArgs(StringProperty textProperty, Object... args)
{
updateBinding(textProperty, null, args);
}
// GETTERS
static Locale getLocale()
{
return LOCALE.get();
}
static ObjectProperty<Locale> LOCALEProperty()
{
return LOCALE;
}
public static ObservableSet<Locale> getSupportedLocales()
{
return SUPPORTED_LOCALES.get();
}
static ObservableMap<String, ResourceBundle> getBundles()
{
return BUNDLES.get();
}
public static ObservableSet<ObjectProperty<NodeOrientation>> getOrientations()
{
return ORIENTATIONS.get();
}
}
|
package com.kareo.ui.codingcapture.implementation.service;
import com.kareo.library.kareoframework.session.model.Session;
import com.kareo.library.kareoframework.session.model.SessionState;
import com.kareo.ui.codingcapture.implementation.controller.TaskController;
import com.kareo.ui.codingcapture.implementation.data.CustomerInfo;
import com.kareo.ui.codingcapture.implementation.data.Task;
import com.kareo.ui.codingcapture.implementation.data.Reason;
import com.kareo.ui.codingcapture.implementation.data.TaskStateCount;
import com.kareo.ui.codingcapture.implementation.query.TaskQuery;
import com.kareo.ui.codingcapture.implementation.request.TaskCreationRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.UUID;
public class TaskServiceImpl implements TaskService {
private static Logger logger = LoggerFactory.getLogger(TaskServiceImpl.class);
private TaskController taskController;
public TaskServiceImpl(TaskController taskController) {
logger.trace("TaskServiceImpl Instantiated.");
this.taskController = taskController;
}
@Override
public Task getTask(long taskId) {
logger.trace("TaskServiceImpl getTask()");
return taskController.getTask(taskId);
}
@Override
public List<Task> searchTasks(Session session, TaskQuery taskQuery) {
logger.trace("TaskServiceImpl searchTasks(): " + taskQuery.toString());
SessionState sessionState = session.getSessionState();
UUID userGuid = null;
if(sessionState != null) userGuid = sessionState.getUserGuid();
return taskController.searchTasks(userGuid, taskQuery);
}
@Override
public List<TaskStateCount> getTaskStateCount(Session session) {
logger.trace("TaskServiceImpl getTaskStateCount()");
SessionState sessionState = session.getSessionState();
UUID userGuid = null;
if(sessionState != null) userGuid = sessionState.getUserGuid();
return taskController.getTaskStateCount(userGuid);
}
@Override
public List<Reason> findTaskReasonForType(String taskType){
logger.trace("TaskServiceImpl getTaskStateCount()");
return taskController.findTaskReasonForType(taskType);
}
@Override
public List<Task> customerTaskSearch(Session session, TaskQuery taskQuery) {
logger.trace("TaskServiceImpl customerTaskSearch()");
SessionState sessionState = session.getSessionState();
Long userId = null;
if(sessionState != null) userId = sessionState.getUserId();
return taskController.customerTaskSearch(userId, taskQuery);
}
@Override
public CustomerInfo findCustomerName(long customerId){
logger.trace("TaskServiceImpl findCustomerName()");
return taskController.findCustomerName(customerId);
}
@Override
public List<TaskStateCount> getCustomerTaskStateCount(Session session) {
logger.trace("TaskServiceImpl getCustomerTaskStateCount()");
SessionState sessionState = session.getSessionState();
Long userId = null;
if(sessionState != null) userId = sessionState.getUserId();
return taskController.getCustomerTaskStateCount(userId);
}
@Override
public void createCustomerFollowUpTask(Session session, TaskCreationRequest taskCreationRequest){
logger.trace("TaskServiceImpl createCustomerFollowUpTask()");
SessionState sessionState = session.getSessionState();
if (sessionState != null){
taskController.createCustomerFollowUpTask(taskCreationRequest,sessionState.getUserId());
}
}
}
|
/**
*
*/
package br.usp.memoriavirtual.controle;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import br.usp.memoriavirtual.modelo.entidades.Autoria;
import br.usp.memoriavirtual.modelo.entidades.Multimidia;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.Assunto;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.BemArqueologico;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.BemArquitetonico;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.BemNatural;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.BemPatrimonial;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.Descritor;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.Diagnostico;
import br.usp.memoriavirtual.modelo.fachadas.ModeloException;
import br.usp.memoriavirtual.modelo.fachadas.remoto.EditarBemPatrimonialRemote;
/**
* @author mac
*
*/
@SessionScoped
public class EditarBemPatrimonialMB extends GerenciarBemPatrimonial implements
BeanComMidia, Serializable {
/**
*
*/
private static final long serialVersionUID = 2482974978856128676L;
@EJB
private EditarBemPatrimonialRemote editarBemPatrimonialEJB;
//private String strDeBusca;
//private List<BemPatrimonial> bemPatrimoniais = new ArrayList<BemPatrimonial>();
private boolean etapa1 = true;
private boolean etapa2 = false;
//private boolean listarTodos = false;
//@EJB
//private RealizarBuscaSimplesRemote realizarBuscaEJB;
/**
*
*/
public EditarBemPatrimonialMB() {
}
public void listarBemPatrimonial(AjaxBehaviorEvent event) {
this.listarBemPatrimonial();
}
public String selecionarBemPatrimonial() {
return null;
}
public String selecionarBemPatrimonial(BemPatrimonial bemPatrimonial) {
FacesContext context = FacesContext.getCurrentInstance();
String bundleName = "mensagens";
ResourceBundle bundle = context.getApplication().getResourceBundle(
context, bundleName);
if (!bemPatrimonial.getTituloPrincipal().equals(
bundle.getString("listarTodos"))) {
intervencoes = bemPatrimonial.getIntervencoes();
pesquisadores = bemPatrimonial.getPesquisadores();
fontesInformacao = bemPatrimonial.getFontesInformacao();
midias.clear();
midias.addAll(bemPatrimonial
.getContainerMultimidia().getMultimidia()) ;
geralExterno = bemPatrimonial.isExterno();
geralNomeInstituicao = bemPatrimonial.getInstituicao().getNome();
// geralNaturezaBem = bemPatrimonial.get;
geralTipoDoBemPatrimonial = bemPatrimonial
.getTipoDoBemPatrimonial();
geralNumeroRegistro = bemPatrimonial.getNumeroDeRegistro();
geralColecao = bemPatrimonial.getColecao();
geralComplemento = bemPatrimonial.getComplemento();
geralLatitude = bemPatrimonial.getLatitude();
geralLongitude = bemPatrimonial.getLongitude();
geralTitulos = bemPatrimonial.getTitulos();
geralTituloPrincipal = bemPatrimonial.getTituloPrincipal();
autorias = bemPatrimonial.getAutorias();
producaoLocal = bemPatrimonial.getProducao().getLocal();
producaoAno = bemPatrimonial.getProducao().getAno();
producaoEdicao = bemPatrimonial.getProducao().getEdicao();
producaoOutrasRes = bemPatrimonial.getProducao()
.getOutrasResponsabilidades();
caracteristicasFisicas = bemPatrimonial
.getCaracteristicasFisTecExec();
// Arqueologico
if (this.geralTipoDoBemPatrimonial.equalsIgnoreCase(bundle
.getString("cadastrarBemTipoLista0"))) {
condicaoTopografica = ((BemArqueologico) bemPatrimonial)
.getCondicaoTopografica();
sitioDaPaisagem = ((BemArqueologico) bemPatrimonial)
.getSitioDaPaisagem();
aguaProxima = ((BemArqueologico) bemPatrimonial)
.getAguaProximo();
possuiVegetacao = ((BemArqueologico) bemPatrimonial)
.getPossuiVegetacao();
exposicao = ((BemArqueologico) bemPatrimonial).getExposicao();
usoAtual = ((BemArqueologico) bemPatrimonial).getUsoAtual();
descricaoOutros = ((BemArqueologico) bemPatrimonial)
.getOutros();
descricaoNotas = ((BemArqueologico) bemPatrimonial).getNotas();
this.areaTotal = ((BemArqueologico) bemPatrimonial)
.getAreaTotal();
this.comprimento = ((BemArqueologico) bemPatrimonial)
.getComprimento();
this.altura = ((BemArqueologico) bemPatrimonial).getAltura();
this.largura = ((BemArqueologico) bemPatrimonial).getLargura();
this.profundidade = ((BemArqueologico) bemPatrimonial)
.getProfundidade();
estadoConservPreserv = bemPatrimonial.getDiagnostico()
.getEstPreservacao();
this.estadoConservNotas = bemPatrimonial.getDiagnostico()
.getNotaEstConservacao();
} else if (this.geralTipoDoBemPatrimonial.equalsIgnoreCase(bundle
.getString("cadastrarBemTipoLista4"))) {
// Arquitetonico
condicaoTopografica = ((BemArquitetonico) bemPatrimonial)
.getCondicaoTopografia();
this.uso = ((BemArquitetonico) bemPatrimonial).getUso();
this.numPavimentos = ((BemArquitetonico) bemPatrimonial)
.getNumeroDePavimentos();
numAmbientes = ((BemArquitetonico) bemPatrimonial)
.getNumeroDeAmbientes();
alcova = ((BemArquitetonico) bemPatrimonial).getAlcova();
porao = ((BemArquitetonico) bemPatrimonial).getPorao();
sotao = ((BemArquitetonico) bemPatrimonial).getSotao();
descricaoOutros = ((BemArquitetonico) bemPatrimonial)
.getOutros();
areaTotal = ((BemArquitetonico) bemPatrimonial).getAreaTotal();
alturaFachadaFrontal = ((BemArquitetonico) bemPatrimonial)
.getAlturaFachFrontal();
this.alturaFachadaSuperior = ((BemArquitetonico) bemPatrimonial)
.getAlturaFachPosterior();
this.largura = ((BemArquitetonico) bemPatrimonial).getLargura();
profundidade = ((BemArquitetonico) bemPatrimonial)
.getProfundidade();
alturaTotal = ((BemArquitetonico) bemPatrimonial)
.getAlturaTotal();
peDireitoTerreo = ((BemArquitetonico) bemPatrimonial)
.getPeDireitoTerreo();
peDireitoTipo = ((BemArquitetonico) bemPatrimonial)
.getTipoPeDireito();
this.estadoPreser = bemPatrimonial.getDiagnostico()
.getEstPreservacao();
this.estadoConser = bemPatrimonial.getDiagnostico()
.getEstConservacao();
this.estadoConservNotas = bemPatrimonial.getDiagnostico()
.getNotaEstConservacao();
} else if (this.geralTipoDoBemPatrimonial.equalsIgnoreCase(bundle
.getString("cadastrarBemTipoLista6"))) {
// System.out.println("natural");
relevo = ((BemNatural) bemPatrimonial).getRelevo();
caracteristicasAntropico = ((BemNatural) bemPatrimonial)
.getMeioAntropico();
caracteristicasAmbientais = ((BemNatural) bemPatrimonial)
.getCaracteristicasAmbientais();
this.estadoConservPreserv = ((BemNatural) bemPatrimonial)
.getDiagnostico().getEstConservacao();
this.estadoConservNotas = ((BemNatural) bemPatrimonial)
.getDiagnostico().getNotaEstConservacao();
} else {
this.bemPatrimonial.setDiagnostico(new Diagnostico(
this.estadoConservPreserv, this.estadoConservNotas));
}
disponibilidadeDoBem = bemPatrimonial
.getDisponibilidadeUsoProtecao().getDisponibilidade();
condicoesDeAcesso = bemPatrimonial.getDisponibilidadeUsoProtecao()
.getCondicoesAcesso();
dataDeRetorno = bemPatrimonial.getDisponibilidadeUsoProtecao()
.getDataRetorno();
condicoesDeReproducao = bemPatrimonial
.getDisponibilidadeUsoProtecao().getCondicoesReproducao();
notasUsoAproveitamento = bemPatrimonial
.getDisponibilidadeUsoProtecao()
.getNotasUsoAproveitamento();
protecao = bemPatrimonial.getDisponibilidadeUsoProtecao()
.getProtecao();
instituicaoProtetora = bemPatrimonial
.getDisponibilidadeUsoProtecao().getProtetoraInstituicao();
legislacaoNprocesso = bemPatrimonial
.getDisponibilidadeUsoProtecao().getLegislacao();
tipoDeAquisicao = bemPatrimonial.getHistoricoProcedencia()
.getTipoAquisicao();
valorVenalEpocaTransacao = bemPatrimonial
.getHistoricoProcedencia().getValorVenalTransacao();
dataAquisicaoDocumento = bemPatrimonial.getHistoricoProcedencia()
.getDataAquisicao();
documentoDeAquisicao = bemPatrimonial.getHistoricoProcedencia()
.getDadosDocTransacao();
primeiroPropietario = bemPatrimonial.getHistoricoProcedencia()
.getPrimeiroProprietario();
historico = bemPatrimonial.getHistoricoProcedencia()
.getHistorico();
intrumentoDePesquisa = bemPatrimonial.getHistoricoProcedencia()
.getInstrumentoPesquisa();
for (Assunto a : bemPatrimonial.getAssuntos()) {
assunto += (a.getAssunto() + " ");
}
for (Descritor a : bemPatrimonial.getDescritores()) {
descritores += (a.getDescritor() + " ");
}
// apresentações
int aux = 0;
for (@SuppressWarnings("unused") Multimidia a : this.midias) {
aux += 1;
if ((aux % 4) == 1) {
Integer mult = aux - 1;
this.ApresentaMidias.add(mult);
}
}
aux = 0;
for (Autoria b : this.autorias) {
if (aux < Autoria.TipoAutoria.values().length - 1) {
aux += 1;
ApresentaAutoria c = new ApresentaAutoria();
c.setNomeAutor(b.getNomeAutor());
c.setTipoAutoria(this.getTipoAutoria(b.getTipoAutoria()));
this.apresentaAutorias.add(c);
}
}
bensRelacionados = bemPatrimonial.getBensrelacionados();
id = bemPatrimonial.getId();
this.etapa1 = false;
this.etapa2 = true;
}else{
bemPatrimoniais.clear();
try {
this.bemPatrimoniais = realizarBuscaEJB.buscar("");
} catch (ModeloException e) {
e.printStackTrace();
}
}
strDeBusca = "";
return null;
}
public String salvarBemPatrimonial(){
super.salvarBemPatrimonial();
this.zerarMB();
return null;
}
public String zerarMB(){
super.zerarMB();
this.etapa2 = false;
this.etapa1 = true;
strDeBusca = "";
return null;
}
public boolean isEtapa1() {
return etapa1;
}
public void setEtapa1(boolean etapa1) {
this.etapa1 = etapa1;
}
public boolean isEtapa2() {
return etapa2;
}
public void setEtapa2(boolean etapa2) {
this.etapa2 = etapa2;
}
}
|
/**
* Nguru Ian Davis
* 15059844
*/
public class AircraftFunctionTester
{
public static void main(String[] args)
{
Aircraft a1 = new Aircraft(Route.GLASGOW, Route.GLASGOW_MAX_PASSENGERS, Route.GLASGOW_MAXIMUM_WEIGHT);
System.out.println(a1.toString());
Crew cru1 = new Crew(0, "Josphat", "Nguru", 90, 90, "captain");
a1.addPassenger(cru1);
//auto generated passengers
for(int c=0;c<99;c++) //set c < maxpassengers allowed per route(Glasgow = 100) and to test whethermax is not exceeded, make it MORE
{
double x = 5;
String pfn = c+"Fname";
String pln = c+"Lname";
EconomyPassenger ep = new EconomyPassenger(0, pfn,pln,80.0, x,Economy.TYPE_CHARGE, Economy.GLASGOW_BASE_FARE);
//x =32.0;
a1.addPassenger(ep);
}
a1.findPassenger(0);
a1.removePassenger(1010);
System.out.println("");
a1.listPassengers();
}
}
|
package com.pratiyush.curd.create.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.therealdanvega.domain.Author;
import com.pratiyush.curd.create.repository.AuthorRepository;
@Service
public class AuthorService {
private AuthorRepository authorRepository;
@Autowired
public AuthorService(AuthorRepository authorRepository) {
super();
this.authorRepository = authorRepository;
}
public List<Author> list() {
return authorRepository.findAllByOrderByLastNameAscFirstNameAsc();
}
}
|
package com.plumnix.cloud.transaction.template;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MultiThreadTransactionTemplateTest {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private PlatformTransactionManager platformTransactionManager;
private ExecutorService threadPool = Executors.newFixedThreadPool(20);
@Test
public void test_multi_thread_using_transaction_template_is_OK() throws InterruptedException {
jdbcTemplate.execute("delete from test");
jdbcTemplate.execute("insert into test values(0)");
TransactionTemplate transactionTemplate =
new TransactionTemplate(platformTransactionManager);
CountDownLatch countDownLatch = new CountDownLatch(10);
IntStream.range(0, 10).forEach(value -> {
threadPool.execute(() -> {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
jdbcTemplate.execute("insert test values(" + value + ")");
if(value % 2 == 0) {
throw new Exception();
}
} catch(Exception e) {
status.setRollbackOnly();
} finally {
countDownLatch.countDown();
}
}
});
});
});
jdbcTemplate.execute("insert into test values(11)");
countDownLatch.await();
}
}
|
package com.bignerdranch.android.bqtabs.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.bignerdranch.android.bqtabs.database.BurgerQueenDBSchema.*;
import static com.bignerdranch.android.bqtabs.database.BurgerQueenDBFunc.createDummyUser;
import static com.bignerdranch.android.bqtabs.database.BurgerQueenDBFunc.populateMenuTable;
import static com.bignerdranch.android.bqtabs.database.BurgerQueenDBFunc.saveSpecials;
public class BurgerQueenDBHelper extends SQLiteOpenHelper {
public static final int VERSION = 1;
public static final String DATABASE_NAME = "burgerQueen.db";
public BurgerQueenDBHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
public void onCreate(SQLiteDatabase db) {
final String CREATE_MENU_SQL = "CREATE TABLE " + MenuTable.NAME + "(" +
" _id integer primary key autoincrement, " +
MenuTable.Cols.ITEMID + " INTEGER, " +
MenuTable.Cols.ITEMNAME + " TEXT, " +
MenuTable.Cols.ITEMIMAGE + " TEXT, " +
MenuTable.Cols.ITEMCATEGORY + " TEXT, " +
MenuTable.Cols.ITEMDESCRIPTION + " TEXT, " +
MenuTable.Cols.ITEMPRICE + " INTEGER" +
")";
final String CREATE_FAVOURITES_SQL = "CREATE TABLE " + FavouritesTable.NAME + "(" +
" _id integer primary key autoincrement, " +
FavouritesTable.Cols.ITEMID + " INTEGER" +
")";
final String CREATE_USERTABLE_SQL = "CREATE TABLE " + UserTable.NAME + "(" +
" _id integer primary key autoincrement, " +
UserTable.Cols.USERNAME + " TEXT, " +
UserTable.Cols.PASSWORD + " VARCHAR, " +
UserTable.Cols.EMAIL + " VARCHAR, " +
UserTable.Cols.HOME_RESTAURANT + " TEXT, " +
UserTable.Cols.DATE_REGISTERED + " DEFAULT CURRENT_TIMESTAMP, " +
UserTable.Cols.FIRST_LOGIN_DATE + " VARCHAR " +
")";
final String CREATE_SPECIALSTABLE_SQL = "CREATE TABLE " + SpecialsTable.NAME + "(" +
" _id integer primary key autoincrement, " +
SpecialsTable.Cols.ITEMID + " INTEGER" +
")";
final String CREATE_ORDERTABLE_SQL = "CREATE TABLE " + OrderTable.NAME + "(" +
" _id integer primary key autoincrement, " +
OrderTable.Cols.ITEMID + " INTEGER " +
")";
final String CREATE_COUPONSTABLE_SQL = "CREATE TABLE " + CouponsTable.NAME + "(" +
" _id integer primary key autoincrement, " +
CouponsTable.Cols.COUPONNAME + " TEXT, " +
CouponsTable.Cols.COUPONID + " TEXT, " +
CouponsTable.Cols.DISCOUNT + " INTEGER," +
CouponsTable.Cols.USERID + " INTEGER, " +
CouponsTable.Cols.COUPONUSED + " TEXT" +
")";
db.execSQL(CREATE_MENU_SQL);
db.execSQL(CREATE_FAVOURITES_SQL);
db.execSQL(CREATE_USERTABLE_SQL);
db.execSQL(CREATE_SPECIALSTABLE_SQL);
db.execSQL(CREATE_COUPONSTABLE_SQL);
db.execSQL(CREATE_ORDERTABLE_SQL);
populateMenuTable(db);
saveSpecials(db);
createDummyUser(db);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
public Cursor alluserdata(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from CREATE_USERTABLE_SQL ",null);
return cursor;
}
}
|
package net.minecraft.client.renderer.entity;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelCow;
import net.minecraft.entity.Entity;
import net.minecraft.entity.passive.EntityCow;
import net.minecraft.util.ResourceLocation;
public class RenderCow extends RenderLiving<EntityCow> {
private static final ResourceLocation COW_TEXTURES = new ResourceLocation("textures/entity/cow/cow.png");
public RenderCow(RenderManager p_i47210_1_) {
super(p_i47210_1_, (ModelBase)new ModelCow(), 0.7F);
}
protected ResourceLocation getEntityTexture(EntityCow entity) {
return COW_TEXTURES;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\client\renderer\entity\RenderCow.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package com.tencent.mm.plugin.shake.c.a;
import android.text.TextUtils;
import com.tencent.mm.ab.e;
import com.tencent.mm.model.au;
import com.tencent.mm.modelgeo.a.a;
import com.tencent.mm.modelgeo.c;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.shake.b.l;
import com.tencent.mm.plugin.shake.b.l.b;
import com.tencent.mm.plugin.shake.b.m;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.x;
public final class g extends b implements e {
private static int mXk = 0;
private float cXm = -85.0f;
private float cXn = -1000.0f;
private a cXs = new a() {
public final boolean a(boolean z, float f, float f2, int i, double d, double d2, double d3) {
if (!z) {
return true;
}
if (g.this.cXm == -85.0f && g.this.cXn == -1000.0f) {
g.this.cXm = f2;
g.this.cXn = f;
m.buI().cXm = g.this.cXm;
m.buI().cXn = g.this.cXn;
if (g.this.mXH) {
x.i("MicroMsg.ShakeCardService", "ShakeCardService do netscen from onGetLocation()");
g.this.buM();
}
}
return false;
}
};
private c dMm;
public String fHA = "";
public int hop = 0;
public int hwF;
private boolean jOf = false;
private ag mHandler = new ag();
private c mXF;
private e mXG = new e();
private boolean mXH = false;
private long mXl = 0;
public g(l.a aVar) {
super(aVar);
}
public final void init() {
mXk = m.buI().mXk;
this.mXl = m.buI().mXl;
this.cXm = m.buI().cXm;
this.cXn = m.buI().cXn;
au.DF().a(1250, this);
buo();
}
public final void reset() {
if (this.mXF != null) {
au.DF().c(this.mXF);
}
}
public final void start() {
init();
reset();
if (this.dMm == null) {
buo();
}
this.dMm.b(this.cXs, true);
d buI = m.buI();
CharSequence charSequence = "key_shake_card_item";
Object obj = (TextUtils.isEmpty(charSequence) || !buI.htT.containsKey(charSequence)) ? null : buI.htT.get(charSequence);
long currentTimeMillis = (System.currentTimeMillis() / 1000) - this.mXl;
if (obj == null || !(obj instanceof e)) {
boolean z;
if (this.mXl == 0) {
z = true;
} else if (currentTimeMillis >= 0) {
z = true;
} else {
h.mEJ.h(11666, new Object[]{Integer.valueOf(this.hop)});
this.mHandler.postDelayed(new Runnable() {
public final void run() {
g.this.mXG.hwF = 3;
g.this.hwF = g.this.mXG.hwF;
g.this.mXG.mXr = m.buI().mXm;
if (g.this.mWQ != null) {
g.this.mWQ.a(1250, g.this.mXG, 2);
}
}
}, 3000);
x.i("MicroMsg.ShakeCardService", "ShakeCardService do not doNetSceneShakeCard, because time is not expire");
z = false;
}
if (!z) {
return;
}
if (this.jOf) {
x.i("MicroMsg.ShakeCardService", "ShakeCardService is doing netscene, return");
return;
} else if (this.cXm == -85.0f || this.cXn == -1000.0f) {
this.mXH = true;
x.i("MicroMsg.ShakeCardService", "ShakeCardService location is not geted, wait 4 second");
this.mHandler.postDelayed(new Runnable() {
public final void run() {
if (!g.this.jOf) {
g.this.buM();
}
}
}, 4000);
return;
} else {
buM();
return;
}
}
this.mWQ.a(1250, (e) obj, 1);
m.buI().putValue("key_shake_card_item", null);
x.i("MicroMsg.ShakeCardService", "getlbscard return data is no empty, don't do doNetSceneShakeCard, return ok");
}
private void buM() {
if (this.jOf) {
x.i("MicroMsg.ShakeCardService", "ShakeCardService is doing doNetSceneShakeCard, return");
return;
}
this.jOf = true;
this.mXH = false;
x.i("MicroMsg.ShakeCardService", "ShakeCardService do doNetSceneShakeCard");
this.mXF = new c(this.cXn, this.cXm, this.hop, this.fHA);
au.DF().a(this.mXF, 0);
}
public final void pause() {
avL();
}
public final void resume() {
if (this.dMm != null) {
this.dMm.a(this.cXs, true);
}
}
public final void bup() {
au.DF().b(1250, this);
avL();
super.bup();
}
private void buo() {
this.dMm = c.OB();
this.dMm.a(this.cXs, true);
}
private void avL() {
if (this.dMm != null) {
this.dMm.c(this.cXs);
}
}
public final void a(int i, int i2, String str, com.tencent.mm.ab.l lVar) {
if (lVar instanceof c) {
c cVar = (c) lVar;
e eVar = this.mXG;
e eVar2 = cVar.mXj;
eVar.hwF = eVar2.hwF;
eVar.huU = eVar2.huU;
eVar.cad = eVar2.cad;
eVar.title = eVar2.title;
eVar.huX = eVar2.huX;
eVar.huY = eVar2.huY;
eVar.hwh = eVar2.hwh;
eVar.huW = eVar2.huW;
eVar.dxh = eVar2.dxh;
eVar.mXk = eVar2.mXk;
eVar.mXn = eVar2.mXn;
eVar.mXo = eVar2.mXo;
eVar.mXp = eVar2.mXp;
eVar.mXq = eVar2.mXq;
eVar.mXr = eVar2.mXr;
eVar.end_time = eVar2.end_time;
eVar.mXs = eVar2.mXs;
eVar.mXt = eVar2.mXt;
this.hwF = this.mXG.hwF;
x.i("MicroMsg.ShakeCardService", "ShakeCardService onSceneEnd() action_type:" + this.hwF + " frequency_level:" + mXk + " control_flag:" + this.mXG.mXn);
if (i == 0 && i2 == 0) {
mXk = this.mXG.mXk;
x.i("MicroMsg.ShakeCardService", "ShakeCardService onSceneEnd is OK ");
if (this.mWQ != null) {
this.mWQ.a(1250, this.mXG, 1);
}
buN();
} else if (!(i == 5 && i2 == -1) && (i != 4 || i2 == 0)) {
x.i("MicroMsg.ShakeCardService", "ShakeCardService onSceneEnd errType is " + i + " errCode is " + i2);
if (this.mWQ != null) {
this.mWQ.a(1250, this.mXG, 2);
}
buN();
} else {
x.i("MicroMsg.ShakeCardService", "ShakeCardService onSceneEnd errType is " + i + " errCode is " + i2);
if (this.mWQ != null) {
this.mWQ.a(1250, this.mXG, 2);
}
long currentTimeMillis = System.currentTimeMillis() / 1000;
long vX = (long) com.tencent.mm.plugin.shake.c.c.a.vX(com.tencent.mm.plugin.shake.c.c.a.bva());
x.i("MicroMsg.ShakeCardService", "ShakeCardService onSceneEnd wait nextInterval is " + vX);
this.mXl = currentTimeMillis + vX;
}
m.buI().mXk = mXk;
m.buI().mXl = this.mXl;
this.jOf = false;
}
}
private void buN() {
long vW;
long currentTimeMillis = System.currentTimeMillis() / 1000;
if (com.tencent.mm.plugin.shake.c.c.a.vV(mXk)) {
x.i("MicroMsg.ShakeCardService", "ShakeCardService frequency_level is valid");
vW = (long) com.tencent.mm.plugin.shake.c.c.a.vW(mXk);
} else {
x.i("MicroMsg.ShakeCardService", "ShakeCardService frequency_level is not valid");
vW = (long) com.tencent.mm.plugin.shake.c.c.a.vX(com.tencent.mm.plugin.shake.c.c.a.bva());
}
x.i("MicroMsg.ShakeCardService", "ShakeCardService updateWaitingTime wait nextInterval is " + vW);
this.mXl = vW + currentTimeMillis;
}
}
|
package com.company;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
double res = RPN.Calculate("10 20 +");
System.out.println(res);
}
}
|
public class Main {
public static void main(String[] args) {
BinTree<String, String> tree = new BinTree<>();
tree.put("D", "00");
tree.put("A", "01");
tree.put("F", "02");
tree.put("C", "03");
tree.put("B", "04");
tree.put("S", "05");
tree.put("E", "06");
if (tree.get("S") == null) System.out.println("No elements with key \"S\"");
else System.out.println("There is element with key \"S\"");
System.out.println("Tree:" + "\n" + tree);
}
}
public class BinTree<K extends Comparable, V> {
private class Node {
K key;
V value;
Node right, left;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
public StringBuilder toString(StringBuilder prefix, boolean isTail, StringBuilder sb) {
if (right != null) {
right.toString(new StringBuilder().append(prefix).append(isTail ? " | " : " "), false, sb);
}
sb.append(prefix).append(isTail ? " └── " : " ┌── ").append(key.toString()).append(":").append(value.toString()).append("\n");
if (left != null) {
left.toString(new StringBuilder().append(prefix).append(isTail ? " | " : " "), true, sb);
}
return sb;
}
@Override
public String toString() {
return this.toString(new StringBuilder(), true, new StringBuilder()).toString();
}
}
private Node root;
private int size;
private Node find(K key) {
if (root == null) {
return null;
}
Node iterator = root;
Node required = root;
while (iterator != null) {
required = iterator;
if (key.compareTo(iterator.key) > 0) {
iterator = iterator.right;
} else if (key.compareTo(iterator.key) < 0) {
iterator = iterator.left;
} else {
iterator = null;
}
}
return required;
}
public void put(K key, V value) {
Node node = new Node(key, value);
if (root == null) {
root = node;
return;
}
Node parent = find(key);
if (key.compareTo(parent.key) > 0) {
parent.right = node;
} else if (key.compareTo(parent.key) < 0) {
parent.left = node;
} else {
parent.value = node.value;
}
size++;
}
public V get(K key) {
Node required = find(key);
return required.key.compareTo(key) == 0 ? required.value : null;
}
@Override
public String toString() {
return root + "";
}
}
|
package com.amitay.arye.songsmash;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Created by A&A on 2/21/2017.
*
* This class is for handling CSV files
*/
public class CsvHelper {
private static final String DEFAULT_EXPORT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/summarizedList.csv";
/**
* Constructs a FileWriter object given a file name.
*
* @param inputStream List of String[] that contains song name and status
* @return List<String[]> that contains the CSV data
* @throws RuntimeException If got an error with reading the CSV file
* or while closing the inputStream
*/
public static List<String[]> readCsv(InputStream inputStream) throws RuntimeException {
List<String[]> resultList = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
} catch(IOException ex) {
throw new RuntimeException("Error in reading CSV file:" + ex);
} finally {
try{
inputStream.close();
} catch(IOException e) {
throw new RuntimeException("Error while closing input stream: " + e);
}
}
return resultList;
}
/**
* Constructs a FileWriter object given a file name.
*
* @param inputList List of String[] that contains song name and status
* @param targetFilePath Set a custom file path - use null for default
* @return Target file path
* @throws IOException if the named file exists but is a directory rather
* than a regular file, does not exist but cannot be
* created, or cannot be opened for any other reason
*/
public static String writeToCsv(List<String[]> inputList, String targetFilePath) throws IOException {
targetFilePath = targetFilePath == null ? DEFAULT_EXPORT_PATH : targetFilePath;
FileWriter writer = new FileWriter(targetFilePath);
for(String[] csvRow : inputList){
writer.append(TextUtils.join(",", csvRow) + "\n");
}
writer.flush();
writer.close();
return targetFilePath;
}
/**
* Constructs a FileWriter object given a file name.
*
* @param uri Uri object with file details
* @return file real path
*/
public static String getFilePath(Uri uri) {
if ("content".equalsIgnoreCase(uri.getScheme())) {
//will return: primary:<file path inside the sdcard>
return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + uri.getLastPathSegment().split(":")[1];
}
if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
}
|
package com.codepath.simpletodo.views;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.text.format.DateUtils;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.codepath.simpletodo.R;
import com.codepath.simpletodo.models.Priority;
import com.codepath.simpletodo.models.ToDoItem;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ToDoItemView extends RelativeLayout {
private ToDoItem mItem;
@BindView(R.id.tv_name)
TextView mNameTextView;
@BindView(R.id.tv_due_date)
TextView mDueDateTextView;
@BindView(R.id.tv_priority)
TextView mPriorityIndicatorView;
public ToDoItemView(final Context context) {
super(context);
init();
}
public ToDoItemView(final Context context, final AttributeSet attrs) {
super(context, attrs);
init();
}
public ToDoItemView(final Context context, final AttributeSet attrs, final int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ToDoItemView(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
public void init() {
inflate(getContext(), R.layout.merge_item_todo_item,this);
ButterKnife.bind(this);
}
public void setItem(final ToDoItem todoItem) {
mItem = todoItem;
bindItem();
}
private void bindItem() {
mNameTextView.setText(mItem.getName());
if (mItem.isCompleted()) {
mNameTextView.setPaintFlags(mNameTextView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
// setBackgroundColor(getResources().getColor(R.color.color_item_complete));
} else {
mNameTextView.setPaintFlags(mNameTextView.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
// setBackgroundColor(getResources().getColor(R.color.color_item_not_complete));
}
final String relativeTime = DateUtils.getRelativeTimeSpanString(mItem.getDueDate(), System.currentTimeMillis(), DateUtils.DAY_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE).toString();
mDueDateTextView.setText(relativeTime);
final Priority priority = Priority.getPriorityByOrder(mItem.getPriority());
((GradientDrawable) mPriorityIndicatorView.getBackground()).setColor(getResources().getColor(priority.getColorResourceId()));
mPriorityIndicatorView.setText(priority.name());
}
}
|
package com.mmall.concurrency.example.singleton;
import com.mmall.concurrency.annotation.ThreadSafe;
/**
* @Auther: Mr.Dong
* @Date: 2019/3/1 09:59
* @Description: 饿汉模式
*/
@ThreadSafe
public class SingletonExample2 {
private static SingletonExample2 instance = new SingletonExample2();
private SingletonExample2() {
}
// 静态的工厂方法
public static SingletonExample2 getInstance() {
return instance;
}
}
|
package com.tencent.mm.plugin.collect.ui;
import com.tencent.mm.plugin.collect.ui.CollectCreateQRCodeUI.4.2;
class CollectCreateQRCodeUI$4$2$1 implements Runnable {
final /* synthetic */ 2 hXH;
CollectCreateQRCodeUI$4$2$1(2 2) {
this.hXH = 2;
}
public final void run() {
this.hXH.hXG.hXF.YC();
}
}
|
package com.minephone.network;
import java.lang.ref.SoftReference;
import java.util.HashMap;
/**
* ObjectCache,软引用的数据存储类,有效防止oom错误
* @author ping
* 2014-4-13 1:28:59
*/
public class ObjectCache {
private HashMap<String, SoftReference> data;
public ObjectCache() {
data = new HashMap<String, SoftReference>();
}
public int getsum () {
try {
return data.size();
} catch (Exception e) {}
return 0;
}
public HashMap<String, SoftReference> getAllData() {
return data;
}
public <T> boolean addCache(String key,T object) {
try {
if (!data.containsKey(key)) {
return putCache(key,object);
}
} catch (Exception e) { }
return false;
}
public <T> boolean putCache(String key,T object) {
try {
data.put(key, new SoftReference<T>(object));
return true;
} catch (Exception e) { }
return false;
}
public boolean delCache(String key) {
try {
SoftReference sf = data.get(key);
if (sf !=null) {
sf.clear();
data.put(key, null);
data.remove(key);
}
return true;
} catch (Exception e) { }
return false;
}
public static void gc() {
System.gc();
System.runFinalization();
}
public <T> T getCache(String key,Class<T> cls) {
try {
SoftReference<T> sf = data.get(key);
return sf.get();
} catch (Exception e) { }
return null;
}
public Object getCache(String key) {
try {
SoftReference sf = data.get(key);
return sf.get();
} catch (Exception e) { }
return null;
}
}
|
package problem_solve.brute_force.baekjoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BaekJoon15650 {
static int num[];
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s[] = br.readLine().split(" ");
int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]);
num = new int[m];
getNext(0, n, m, 0);
br.close();
}
private static void getNext(int index, int n, int m, int start){
if(index == m){
for(int p : num){
System.out.print(p + " ");
}
System.out.println();
return;
} else if(index < m && n == start){
return;
}
for(int s = start+1; s <= n; s++){
num[index] = s;
getNext(index+1, n, m, s);
}
}
}
|
package com.example.crypsis.customkeyboard.presenter;
import rx.subscriptions.CompositeSubscription;
/**
* Created by crypsis on 21/11/16.
*/
public interface SearchPresenter {
void getSearchResult(CompositeSubscription compositeSubscription, String searchText);
}
|
package exam_module5.demo.controller;
import exam_module5.demo.model.Car;
import exam_module5.demo.model.Type;
import exam_module5.demo.service.CarService;
import exam_module5.demo.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@CrossOrigin(origins = "*")
@RestController
@RequestMapping(value = "/type/api/v1")
public class TypeRestController {
@Autowired
private TypeService typeService;
@GetMapping
public ResponseEntity<List<Type>> getTypeList(){
List<Type> typeList = typeService.findAll();
if (typeList.isEmpty()){
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(typeList, HttpStatus.OK);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package PRO1041.FORM;
import PRO1041.DAO.TaiXeDAO;
import java.awt.Image;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import PRO1041.DAO.XeDAO;
/**
*
* @author phamt
*/
public class Xe extends javax.swing.JFrame {
String username = "sa";
String password = "123";
String url = "jdbc:sqlserver://localhost:1433;databaseName=QL_NhaXe";
private String header[] = {"Mã Xe", "Biển Số", "Trạng Thái", "Hình Ảnh"};
private DefaultTableModel tblModel = new DefaultTableModel(header, 0);
private ArrayList<XeDAO> list = new ArrayList<XeDAO>();
String strHinhanh = null;
String thongbao = "";
private int curredIndex = -1;
/**
* Creates new form TuyenDuong
*/
public Xe() {
initComponents();
loadDataToTable();
LoadData();
}
public void loadDataToTable() {
try {
tblModel.setRowCount(0);
Connection con = DriverManager.getConnection(url, username, password);
Statement st = con.createStatement();
String sql = "select * from Xe";
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
Vector r = new Vector();
r.add(rs.getInt(1));
r.add(rs.getString(2));
r.add(rs.getString(3));
r.add(rs.getString(4));
tblModel.addRow(r);
}
tbl_xe.setModel(tblModel);
con.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
public void LoadData() {
Connection conn = null;
Statement stm = null;
try {
conn = DriverManager.getConnection(url, username, password);
stm = conn.createStatement();
String sql = "";
sql = "select * from Xe";
ResultSet rs = stm.executeQuery(sql);
list.clear();
while (rs.next()) {
String MaXe = rs.getString("MaXe");
String BienSo = rs.getString("BienSo");
String TrangThai = rs.getString("TrangThai");
String HinhAnh = rs.getString("HinhAnh");
XeDAO xe = new XeDAO(MaXe, BienSo, TrangThai, HinhAnh);
list.add(xe);
}
curredIndex = 0;
DislayTX();
rs.close();
stm.close();
conn.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
public void LoadImage(String hinh) {
ImageIcon image = new ImageIcon("src\\IMG\\ImageXe\\" + hinh);
Image im = image.getImage();
ImageIcon icon = new ImageIcon(im.getScaledInstance(btn_anh.getWidth(), btn_anh.getHeight(), im.SCALE_SMOOTH));
btn_anh.setIcon(icon);
}
public void DislayTX() {
XeDAO txs = list.get(curredIndex);
txt_ma.setText(txs.MaXe);
txt_bienso.setText(txs.BienSo);
cbb_trangthai.setSelectedItem(txs.TrangThai);
LoadImage(txs.HinhAnh);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel12 = new javax.swing.JLabel();
txt_tim = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
tbl_xe = new javax.swing.JTable();
btn_them = new javax.swing.JButton();
btn_anh = new javax.swing.JButton();
btn_tim = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
btn_back = new javax.swing.JButton();
btn_reset = new javax.swing.JButton();
btn_xoa = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
cbb_trangthai = new javax.swing.JComboBox<>();
btn_sua = new javax.swing.JButton();
txt_bienso = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
txt_ma = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setLocation(new java.awt.Point(325, 90));
jPanel1.setLayout(null);
jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel12.setText("Trạng thái");
jPanel1.add(jLabel12);
jLabel12.setBounds(110, 170, 80, 17);
txt_tim.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_timActionPerformed(evt);
}
});
jPanel1.add(txt_tim);
txt_tim.setBounds(70, 320, 400, 30);
tbl_xe.setBackground(new java.awt.Color(204, 204, 255));
tbl_xe.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tbl_xe.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tbl_xeMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tbl_xe);
jPanel1.add(jScrollPane1);
jScrollPane1.setBounds(40, 360, 670, 90);
btn_them.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btn_them.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/them.png"))); // NOI18N
btn_them.setText("THÊM");
btn_them.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_themActionPerformed(evt);
}
});
jPanel1.add(btn_them);
btn_them.setBounds(200, 250, 300, 40);
btn_anh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/them.png"))); // NOI18N
btn_anh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_anhActionPerformed(evt);
}
});
jPanel1.add(btn_anh);
btn_anh.setBounds(520, 70, 190, 160);
btn_tim.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btn_tim.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/timve.png"))); // NOI18N
btn_tim.setText("TÌM");
btn_tim.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_timActionPerformed(evt);
}
});
jPanel1.add(btn_tim);
btn_tim.setBounds(500, 310, 160, 40);
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel6.setText("BACK");
jPanel1.add(jLabel6);
jLabel6.setBounds(30, 140, 34, 14);
btn_back.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btn_back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/ql.png"))); // NOI18N
btn_back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_backActionPerformed(evt);
}
});
jPanel1.add(btn_back);
btn_back.setBounds(10, 40, 70, 140);
btn_reset.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btn_reset.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/reset.png"))); // NOI18N
btn_reset.setText("RESET");
btn_reset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_resetActionPerformed(evt);
}
});
jPanel1.add(btn_reset);
btn_reset.setBounds(40, 250, 130, 39);
btn_xoa.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btn_xoa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/xoa.png"))); // NOI18N
btn_xoa.setText("XÓA");
btn_xoa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_xoaActionPerformed(evt);
}
});
jPanel1.add(btn_xoa);
btn_xoa.setBounds(160, 480, 190, 60);
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setText("Biển số");
jPanel1.add(jLabel4);
jLabel4.setBounds(110, 130, 110, 30);
cbb_trangthai.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Hoạt động", "Không hoạt động" }));
jPanel1.add(cbb_trangthai);
cbb_trangthai.setBounds(220, 180, 230, 40);
btn_sua.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btn_sua.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/icon-bao-hanh.png"))); // NOI18N
btn_sua.setText("SỬA");
btn_sua.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_suaActionPerformed(evt);
}
});
jPanel1.add(btn_sua);
btn_sua.setBounds(400, 480, 200, 60);
jPanel1.add(txt_bienso);
txt_bienso.setBounds(220, 130, 270, 30);
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel9.setText("Mã xe");
jPanel1.add(jLabel9);
jLabel9.setBounds(110, 90, 110, 30);
jPanel1.add(txt_ma);
txt_ma.setBounds(220, 90, 270, 30);
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 51, 51));
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel7.setText("Xe Khách");
jPanel1.add(jLabel7);
jLabel7.setBounds(50, 30, 640, 44);
jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/background/nen2.png"))); // NOI18N
jPanel1.add(jLabel5);
jLabel5.setBounds(20, 30, 710, 280);
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/background/nen3.png"))); // NOI18N
jPanel1.add(jLabel2);
jLabel2.setBounds(20, -20, 720, 580);
jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/background/nen3.png"))); // NOI18N
jPanel1.add(jLabel10);
jLabel10.setBounds(20, -20, 720, 580);
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/background/nen1.png"))); // NOI18N
jPanel1.add(jLabel3);
jLabel3.setBounds(20, 0, 750, 510);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/background/nen1.png"))); // NOI18N
jPanel1.add(jLabel1);
jLabel1.setBounds(0, 0, 750, 560);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 745, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txt_timActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_timActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_timActionPerformed
private void tbl_xeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_xeMouseClicked
int r = tbl_xe.getSelectedRow();
if (r < 0) {
return;
}
txt_ma.setText(tbl_xe.getValueAt(r, 0).toString());
txt_bienso.setText(tbl_xe.getValueAt(r, 1).toString());
cbb_trangthai.setSelectedItem(tbl_xe.getValueAt(r, 2).toString());
LoadImage(tbl_xe.getValueAt(r, 3).toString());
}//GEN-LAST:event_tbl_xeMouseClicked
private void btn_themActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_themActionPerformed
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(url, username, password);
String sql = "insert into Xe values(?,?,?)\n";
PreparedStatement st = con.prepareStatement(sql);
st.setString(1, txt_bienso.getText());
st.setString(2, cbb_trangthai.getSelectedItem().toString());
st.setString(3, strHinhanh);
st.executeUpdate();
JOptionPane.showMessageDialog(this, "Thêm thông tin xe thành công");
con.close();
loadDataToTable();
} catch (Exception e) {
System.out.println(e);
}
}//GEN-LAST:event_btn_themActionPerformed
private void btn_anhActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_anhActionPerformed
try {
JFileChooser choose=new JFileChooser("src\\IMG\\ImageXe");
int chon=choose.showOpenDialog(this);
File file = choose.getSelectedFile();
Image img = ImageIO.read(file);
strHinhanh = file.getName();
int width = btn_anh.getWidth();
int height= btn_anh.getHeight();
btn_anh.setIcon(new ImageIcon(img.getScaledInstance(width, height, 0)));
}catch(Exception e){
}
}//GEN-LAST:event_btn_anhActionPerformed
private void btn_timActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_timActionPerformed
int i;
String matx = txt_tim.getText();
for (i = 0; i < list.size(); i++) {
XeDAO xe = list.get(i);
if (xe.MaXe.equals(matx) == true) {
curredIndex = i;
tbl_xe.setRowSelectionInterval(curredIndex, curredIndex);
DislayTX();
break;
}
}
if (i == list.size()) {
JOptionPane.showMessageDialog(this, "Không tìm thấy xe");
}
}//GEN-LAST:event_btn_timActionPerformed
private void btn_xoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_xoaActionPerformed
int ret = JOptionPane.showConfirmDialog(this, "Bạn có muốn xóa không?", "Có",
JOptionPane.YES_NO_OPTION);
if (ret != JOptionPane.YES_OPTION) {
return;
}
Connection c = null;
PreparedStatement ps = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
c = DriverManager.getConnection(url, username, password);
ps = c.prepareStatement("Delete From Xe where MaXe = ?");
ps.setString(1, txt_ma.getText());
String ten = txt_bienso.getText();
ret = ps.executeUpdate();
if (ret != -1) {
JOptionPane.showMessageDialog(this, "Đã xóa xe có biển số: " + ten);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (c != null) {
c.close();
}
if (ps != null) {
ps.close();
loadDataToTable();
LoadData();
}
} catch (Exception ex2) {
ex2.printStackTrace();
}
}
}//GEN-LAST:event_btn_xoaActionPerformed
private void btn_suaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_suaActionPerformed
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(url, username, password);
String sql = "update Xe set BienSo=?, TrangThai=?, HinhAnh=? where MaXe=?";
PreparedStatement st = con.prepareStatement(sql);
st.setString(1, txt_bienso.getText());
st.setString(2, cbb_trangthai.getSelectedItem().toString());
st.setString(3, strHinhanh);
st.setString(4, txt_ma.getText());
st.executeUpdate();
JOptionPane.showMessageDialog(this, "Sửa thông tin xe thành công");
con.close();
loadDataToTable();
LoadData();
} catch (Exception e) {
System.out.println(e);
JOptionPane.showMessageDialog(this, "Error");
}
}//GEN-LAST:event_btn_suaActionPerformed
private void btn_backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_backActionPerformed
TrangChu tc = new TrangChu();
tc.setVisible(true);
dispose();
}//GEN-LAST:event_btn_backActionPerformed
private void btn_resetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_resetActionPerformed
txt_ma.setText("");
txt_bienso.setText("");
cbb_trangthai.setSelectedItem("");
LoadImage("");
}//GEN-LAST:event_btn_resetActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Xe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Xe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Xe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Xe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Xe().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_anh;
private javax.swing.JButton btn_back;
private javax.swing.JButton btn_reset;
private javax.swing.JButton btn_sua;
private javax.swing.JButton btn_them;
private javax.swing.JButton btn_tim;
private javax.swing.JButton btn_xoa;
private javax.swing.JComboBox<String> cbb_trangthai;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tbl_xe;
private javax.swing.JTextField txt_bienso;
private javax.swing.JTextField txt_ma;
private javax.swing.JTextField txt_tim;
// End of variables declaration//GEN-END:variables
}
|
package edu.bupt.cbh.testing.entity;
/**
* Created by changbohong on 2017/10/29.
*/
public class RandomTestingInput {
private Integer inputId;
private Integer inputType;
private String inputValue;
public Integer getInputId() {
return inputId;
}
public void setInputId(Integer inputId) {
this.inputId = inputId;
}
public Integer getInputType() {
return inputType;
}
public void setInputType(Integer inputType) {
this.inputType = inputType;
}
public String getInputValue() {
return inputValue;
}
public void setInputValue(String inputValue) {
this.inputValue = inputValue;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package miniatm;
/**
*
* @author ASUS
*/
public class BalanceInquiry extends Transaction
{
public BalanceInquiry( int userAccountNumber, Screen atmScreen, BankDatabase atmBankDatabase )
{
super(userAccountNumber, atmScreen, atmBankDatabase);
}
@Override
public void execute()
{
BankDatabase bankDatabase = getBankDatabase();
Screen screen = getScreen();
double availableBalance = bankDatabase.getAvailableBalance( getAccountNumber());
double totalBalance = bankDatabase.getTotalBalance( getAccountNumber());
screen.displayMessageLine( "\nInformasi Saldo:" );
screen.displayMessage( " - Saldo yang Tersedia: ");
screen.displayRupiahAmount( availableBalance );
screen.displayMessage( "\n - Saldo Total: ");
screen.displayRupiahAmount( totalBalance );
screen.displayMessageLine("");
}
}
|
package com.jjc.mailshop.service.imp;
import com.jjc.mailshop.common.Conts;
import com.jjc.mailshop.common.ServerResponse;
import com.jjc.mailshop.dao.UserMapper;
import com.jjc.mailshop.pojo.User;
import com.jjc.mailshop.service.IUserService;
import com.jjc.mailshop.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by jjc on 2017/5/22.
* <p>用户服务的实现</p>
*/
@Service("iUserService")
public class UserServiceImp implements IUserService {
@Autowired
UserMapper userMapper;
@Override
public ServerResponse<User> login(String username, String password) {
//检查用户是否存在
if (userMapper.checkUserExit(username) == 0) {
return ServerResponse.createByErrorMessage("用户不存在");
}
//登陆
User user = userMapper.selectLogin(username, MD5Util.MD5EncodeUtf8(password));
if (user == null) {
return ServerResponse.createByErrorMessage("用户名或密码错误");
}
//清空密码
user.setPassword("");
//返回数据
return ServerResponse.createBySuccess("登陆成功", user);
}
@Override
public ServerResponse<List<User>> selectAllUser() {
return null;
}
@Override
public ServerResponse<String> register(User user) {
//先检测邮箱是否存在
ServerResponse<String> checkEmail = checkEmail(user.getEmail());
if (!checkEmail.isSuccess()) {
return checkEmail;
}
//检测用户名是否存在
ServerResponse<String> checkUsername = checkUsername(user.getUsername());
if (!checkUsername.isSuccess()) {
return checkEmail;
}
//加密密码
user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
//插入用户到数据库
if (userMapper.insert(user) == 0) {
return ServerResponse.createByErrorMessage("注册失败");
}
//返回注册成功
return ServerResponse.createBySuccessMessage("注册成功");
}
@Override
public ServerResponse<String> checkEmail(String email) {
if (userMapper.checkEmail(email) > 0) {
return ServerResponse.createByErrorMessage("邮箱已存在");
}
return ServerResponse.createBySuccessMessage("验证成功");
}
@Override
public ServerResponse<String> checkUsername(String username) {
if (userMapper.checkUserExit(username) > 0) {
return ServerResponse.createByErrorMessage("用户已存在");
}
return ServerResponse.createBySuccessMessage("验证成功");
}
@Override
public ServerResponse<String> getUserQuestion(String username) {
//检测用户名是否存在
ServerResponse<String> checkUsername = checkUsername(username);
//不存在
if (checkUsername.isSuccess()) {
return checkUsername;
}
//查找问题
String question = userMapper.selectUserQuestion(username);
if (StringUtils.isEmpty(question)) {
return ServerResponse.createByErrorMessage("该用户未设置问题");
}
//返回问题
return ServerResponse.createBySuccess("查询问题成功", question);
}
@Override
public ServerResponse<User> validUserQuestionAndAnswer(String username, String question, String answer) {
//查找用户
User user = userMapper.selectUserQuestionAndAnswer(username, question, answer);
//判断是否为空
if (user == null) {
return ServerResponse.createByErrorMessage("验证失败");
}
//返回用户
return ServerResponse.createBySuccess("验证成功", user);
}
@Override
public ServerResponse<String> forgetPassword(String username, String oldPass, String newPass) {
//查询用户是否存在
ServerResponse<String> checkUsername = checkUsername(username);
//不存在
if (checkUsername.isSuccess()) {
return checkUsername;
}
//根据用户名和密码查询用户
if (userMapper.selectForgetPasswordUser(username, oldPass) == 0) {
return ServerResponse.createByErrorMessage("用户名或密码错误");
}
//修改密码
return null;
}
//---------------------admin
@Override
public ServerResponse<User> loginAdmin(String username, String password) {
//登陆
ServerResponse<User> response = login(username, password);
//判断是否登陆成功
if (response.isSuccess()) {
//设置为管理员
response.getData().setRole(Conts.Role.ROLE_ADMIN);
}
return response;
}
//---------------------admin
}
|
package com.simbircite.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import com.simbircite.demo.repository.UsersRepository;
import com.simbircite.homesecretary.entity.Users;
public class UsersService {
@Autowired
UsersRepository repository;
public void add(Users data) {
repository.save(data);
}
public void update(Users data) {
repository.save(data);
}
public void delete(int id) {
repository.delete(id);
}
public Iterable<Users> getAll() {
return repository.findAll();
}
public Users getById(int id) {
return repository.findOne(id);
}
}
|
public class Node {
private String value;
private Node leftChild;
private Node rightChild;
private boolean isVisited = false;
Node() {
}
Node(String value) {
this.value = value;
this.leftChild = null;
this.rightChild = null;
}
String getValue() {
return value;
}
void setValue(String value) {
this.value = value;
}
Node getLeftChild() {
return leftChild;
}
void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
Node getRightChild() {
return rightChild;
}
void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
public boolean isVisited() {
return isVisited;
}
public void setVisited(boolean visited) {
isVisited = visited;
}
@Override
public String toString() {
return "Node{" +
"value='" + value + '\'' +
", leftChild=" + leftChild +
", rightChild=" + rightChild +
'}';
}
}
|
package com.tencent.mm.plugin.remittance.ui;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.tencent.mm.ab.l;
import com.tencent.mm.compatible.util.d;
import com.tencent.mm.plugin.remittance.a.b;
import com.tencent.mm.plugin.wallet_core.id_verify.util.RealnameGuideHelper;
import com.tencent.mm.plugin.wallet_core.model.Orders;
import com.tencent.mm.plugin.wallet_core.model.Orders.Commodity;
import com.tencent.mm.plugin.wallet_core.ui.view.WalletSuccPageAwardWidget;
import com.tencent.mm.plugin.wxpay.a.f;
import com.tencent.mm.plugin.wxpay.a.g;
import com.tencent.mm.plugin.wxpay.a.i;
import com.tencent.mm.pluginsdk.ui.d.j;
import com.tencent.mm.pluginsdk.wallet.PayInfo;
import com.tencent.mm.protocal.c.lr;
import com.tencent.mm.sdk.platformtools.BackwardSupportUtil;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa;
import com.tencent.mm.ui.base.a;
import com.tencent.mm.wallet_core.ui.WalletTextView;
import com.tencent.mm.wallet_core.ui.e;
import d.a.a.c;
@a(19)
public class RemittanceResultNewUI extends RemittanceResultUI {
private c mAh;
private WalletSuccPageAwardWidget mAi;
private Orders mCZ;
private String mDa;
private boolean mDc;
private TextView mDd;
private ViewGroup mDe;
private TextView mDf;
private WalletTextView mDg;
private ViewGroup mDh;
private ViewGroup mDi;
private ViewGroup mDj;
private TextView mDk;
private TextView mDl;
private WalletTextView mDm;
private lr mDn;
private Button mDo;
private PayInfo mpb;
private int myU;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (d.fR(21)) {
if (d.fR(23)) {
getWindow().setStatusBarColor(-1);
getWindow().getDecorView().setSystemUiVisibility(8192);
} else {
getWindow().setStatusBarColor(Color.parseColor("#E5E5E5"));
}
}
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
this.mCZ = (Orders) this.sy.getParcelable("key_orders");
this.mpb = (PayInfo) this.sy.getParcelable("key_pay_info");
if (this.mpb == null) {
x.e("MicroMsg.RemittanceResultNewUI", "payInfo is null!!!");
finish();
return;
}
String str = "";
String str2 = "";
if (this.mpb.qUL != null) {
this.mDc = this.mpb.qUL.getBoolean("extinfo_key_4");
str = this.mpb.qUL.getString("extinfo_key_1");
str2 = this.mpb.qUL.getString("extinfo_key_16");
}
this.myU = this.mpb.bVY;
this.mDa = str;
x.i("MicroMsg.RemittanceResultNewUI", "payScene: %s", new Object[]{Integer.valueOf(r2)});
initView();
if (this.myU == 31) {
x.i("MicroMsg.RemittanceResultNewUI", "transId: %s", new Object[]{str2});
b.bqQ().bqT().en(str2, this.mDa);
}
}
protected final int getLayoutId() {
return g.remittance_result_new_ui;
}
public boolean onKeyUp(int i, KeyEvent keyEvent) {
if (i == 4) {
brF();
}
return super.onKeyUp(i, keyEvent);
}
protected final void initView() {
boolean z = false;
setBackBtn(null);
showHomeBtn(false);
enableBackMenu(false);
this.mDd = (TextView) findViewById(f.pay_succ_wording_tv);
this.mDe = (ViewGroup) findViewById(f.f2f_transfer_result_money_layout);
this.mDf = (TextView) findViewById(f.f2f_money_unit_tv);
this.mDg = (WalletTextView) findViewById(f.f2f_money_amount_tv);
this.mDh = (ViewGroup) findViewById(f.f2f_transfer_detail_layout);
this.mDi = (ViewGroup) findViewById(f.f2f_transfer_detail_list_layout);
this.mDj = (ViewGroup) findViewById(f.normal_transfer_result_money_layout);
this.mDk = (TextView) findViewById(f.normal_transfer_desc_tv);
this.mDl = (TextView) findViewById(f.normal_money_unit_tv);
this.mDm = (WalletTextView) findViewById(f.normal_money_amount_tv);
this.mDo = (Button) findViewById(f.transfer_finish_button);
this.mDo.setOnClickListener(new OnClickListener() {
public final void onClick(View view) {
RemittanceResultNewUI.this.brF();
}
});
this.mAi = (WalletSuccPageAwardWidget) findViewById(f.award_widget);
String gT = e.gT(this.mDa);
if (this.myU == 31 || this.myU == 5) {
this.mDl.setText(e.abW(this.mCZ.lNV));
this.mDm.setText(e.A(this.mCZ.mBj));
if (this.myU == 31) {
CharSequence string = getString(i.remittance_result_receiver_desc, new Object[]{gT});
if (bi.oW(string)) {
this.mDk.setVisibility(8);
} else {
this.mDk.setText(j.a(this, string, this.mDk.getTextSize()));
}
} else {
boolean z2;
if (this.mpb.qUL == null || !this.mpb.qUL.getBoolean("extinfo_key_10")) {
z2 = false;
} else {
z2 = true;
}
x.i("MicroMsg.RemittanceResultNewUI", "isEmojiReward: %s", new Object[]{Boolean.valueOf(z2)});
if (z2) {
this.mDk.setText(getString(i.remittance_emoji_reward_desc));
} else if (!(this.mCZ.ppf == null || this.mCZ.ppf.get(0) == null || TextUtils.isEmpty(((Commodity) this.mCZ.ppf.get(0)).lNK))) {
this.mDk.setText(((Commodity) this.mCZ.ppf.get(0)).lNK);
}
}
this.mDj.setVisibility(0);
if (this.mCZ.mxE > 0.0d) {
brE();
((MarginLayoutParams) this.mDh.getLayoutParams()).topMargin = com.tencent.mm.bp.a.fromDPToPix(this, 20);
this.mDh.setVisibility(0);
this.mDi.setVisibility(0);
}
} else {
byte[] byteArray = this.sy.getByteArray("key_succpage_resp");
if (byteArray != null) {
this.mDn = new lr();
try {
this.mDn.aG(byteArray);
this.mAh = this.mDn.pqb;
} catch (Throwable e) {
this.mDn = null;
this.mAh = null;
x.printErrStackTrace("MicroMsg.RemittanceResultNewUI", e, "parse f2FPaySucPageResp error: %s", new Object[]{e.getMessage()});
}
}
gT = e.gT(this.mDa);
this.mDf.setText(e.abW(this.mCZ.lNV));
this.mDg.setText(e.A(this.mCZ.mBj));
this.mDi.removeAllViews();
if (this.myU == 32 || this.myU == 33 || this.myU == 48) {
CharSequence charSequence;
ViewGroup viewGroup;
TextView textView;
String str = "";
if (this.mpb.qUL != null) {
str = this.mpb.qUL.getString("extinfo_key_2");
}
if (gT != null && gT.length() > 10) {
gT = gT.substring(0, 10) + "...";
}
Object charSequence2;
if (bi.oW(str)) {
charSequence2 = gT;
} else if (bi.oW(gT)) {
charSequence2 = str;
} else {
charSequence2 = gT + "(" + e.abZ(str) + ")";
}
x.i("MicroMsg.RemittanceResultNewUI", "setF2FNameView");
ViewGroup viewGroup2 = (ViewGroup) getLayoutInflater().inflate(g.f2f_transfer_new_detail_item, this.mDi, false);
TextView textView2 = (TextView) viewGroup2.findViewById(f.rbru_rcvr_tv);
com.tencent.mm.pluginsdk.ui.a.b.a((ImageView) viewGroup2.findViewById(f.remittance_busi_logo), this.mDa, 0.06f, false);
textView2.setText(charSequence2);
this.mDi.addView(viewGroup2);
x.i("MicroMsg.RemittanceResultNewUI", "setF2FReceiverRemarkView");
CharSequence string2 = this.mpb.qUL.getString("extinfo_key_3");
CharSequence string3 = this.mpb.qUL.getString("extinfo_key_8");
if (!bi.oW(string2)) {
viewGroup = (ViewGroup) getLayoutInflater().inflate(g.f2f_transfer_detail_item_2, this.mDi, false);
textView2 = (TextView) viewGroup.findViewById(f.title_tv);
textView = (TextView) viewGroup.findViewById(f.desc_tv);
if (bi.oW(string3)) {
textView2.setText(getString(i.collect_create_qrcode_receiver_msg_title));
} else {
textView2.setText(string3);
}
textView.setText(string2);
this.mDi.addView(viewGroup);
}
x.i("MicroMsg.RemittanceResultNewUI", "setF2FPayerRemarkView");
string2 = this.mpb.qUL.getString("extinfo_key_6");
string3 = this.mpb.qUL.getString("extinfo_key_7");
if (!bi.oW(string3)) {
viewGroup = (ViewGroup) getLayoutInflater().inflate(g.f2f_transfer_detail_item_2, this.mDi, false);
textView2 = (TextView) viewGroup.findViewById(f.title_tv);
textView = (TextView) viewGroup.findViewById(f.desc_tv);
if (bi.oW(string2)) {
textView2.setText(getString(i.collect_create_qrcode_payer_msg_title));
} else {
textView2.setText(string2);
}
textView.setText(string3);
this.mDi.addView(viewGroup);
}
brE();
this.mDh.setVisibility(0);
this.mDi.setVisibility(0);
View findViewById;
if (WalletSuccPageAwardWidget.a(this.mAh)) {
String str2 = "";
if (this.mCZ.ppf.size() > 0) {
str2 = ((Commodity) this.mCZ.ppf.get(0)).bOe;
}
x.i("MicroMsg.RemittanceResultNewUI", "transId: %s", new Object[]{str2});
this.mAi.a(this, this.mAh, str2, true, (ImageView) findViewById(f.background));
this.mAi.init();
this.mAi.setVisibility(0);
if (viewGroup2 != null) {
findViewById = viewGroup2.findViewById(f.rbru_rcvr_tv_v2_layout);
if (findViewById != null && findViewById.getVisibility() == 8) {
findViewById = findViewById(f.split_line);
if (findViewById != null) {
findViewById.setVisibility(8);
}
}
}
} else {
this.mAi.setVisibility(8);
if (this.mDi.getChildCount() == 1) {
LayoutParams layoutParams = (LayoutParams) this.mDh.getLayoutParams();
layoutParams.topMargin = BackwardSupportUtil.b.b(this, 78.0f);
this.mDh.setLayoutParams(layoutParams);
View findViewById2 = viewGroup2.findViewById(f.remittance_layout_line2);
layoutParams = (LayoutParams) findViewById2.getLayoutParams();
layoutParams.topMargin = BackwardSupportUtil.b.b(this, 24.0f);
layoutParams.bottomMargin = 0;
findViewById2.setLayoutParams(layoutParams);
ImageView imageView = (ImageView) viewGroup2.findViewById(f.remittance_busi_logo);
((TextView) viewGroup2.findViewById(f.rbru_rcvr_tv)).setVisibility(8);
findViewById(f.rbru_rcvr_tv_v2_layout).setVisibility(0);
((TextView) findViewById(f.rbru_rcvr_tv_v2)).setText(charSequence2);
LayoutParams layoutParams2 = (LayoutParams) imageView.getLayoutParams();
int b = BackwardSupportUtil.b.b(this, 52.0f);
layoutParams2.width = b;
layoutParams2.height = b;
imageView.setLayoutParams(layoutParams2);
this.mDg.setTextSize(1, 42.0f);
this.mDf.setTextSize(1, 42.0f);
((TextView) findViewById(f.rec_name_tip)).setTextSize(1, 16.0f);
imageView = (ImageView) findViewById(f.wxpay_succes_page_logo_iv);
layoutParams2 = (LayoutParams) imageView.getLayoutParams();
layoutParams2.width = BackwardSupportUtil.b.b(this, 26.0f);
layoutParams2.height = BackwardSupportUtil.b.b(this, 22.0f);
imageView.setLayoutParams(layoutParams2);
findViewById = findViewById(f.split_line);
if (findViewById != null) {
findViewById.setVisibility(8);
}
}
}
}
this.mDe.setVisibility(0);
}
com.tencent.mm.kernel.g.Ek();
Object obj = com.tencent.mm.kernel.g.Ei().DT().get(aa.a.sQv, Boolean.valueOf(false));
if (obj != null) {
z = ((Boolean) obj).booleanValue();
}
if (z) {
x.i("MicroMsg.RemittanceResultNewUI", "has show the finger print auth guide!");
return;
}
com.tencent.mm.wallet_core.c af = com.tencent.mm.wallet_core.a.af(this);
Bundle bundle = new Bundle();
if (af != null) {
bundle = af.jfZ;
}
if (TextUtils.isEmpty(bundle.getString("key_pwd1"))) {
x.i("MicroMsg.RemittanceResultNewUI", "pwd is empty, not show the finger print auth guide!");
} else if (af != null) {
af.a((Activity) this, "fingerprint", ".ui.FingerPrintAuthTransparentUI", bundle);
}
}
private void brE() {
boolean z = true;
if (this.mCZ != null) {
String str = "MicroMsg.RemittanceResultNewUI";
String str2 = "need set charge fee: %s";
Object[] objArr = new Object[1];
if (this.mCZ.mxE <= 0.0d) {
z = false;
}
objArr[0] = Boolean.valueOf(z);
x.i(str, str2, objArr);
if (this.mCZ.mxE > 0.0d) {
CharSequence string = getString(i.remittance_result_charge_fee_wording);
CharSequence e = e.e(this.mCZ.mxE, this.mCZ.lNV);
ViewGroup viewGroup = (ViewGroup) getLayoutInflater().inflate(g.f2f_transfer_detail_item, this.mDi, false);
ImageView imageView = (ImageView) viewGroup.findViewById(f.avatar_iv);
TextView textView = (TextView) viewGroup.findViewById(f.desc_tv);
((TextView) viewGroup.findViewById(f.title_tv)).setText(string);
imageView.setVisibility(8);
textView.setText(e);
this.mDi.addView(viewGroup);
}
}
}
private void brF() {
x.i("MicroMsg.RemittanceResultNewUI", "endRemittance");
if (this.sy.containsKey("key_realname_guide_helper")) {
RealnameGuideHelper realnameGuideHelper = (RealnameGuideHelper) this.sy.getParcelable("key_realname_guide_helper");
if (realnameGuideHelper != null) {
Bundle bundle = new Bundle();
bundle.putString("realname_verify_process_jump_activity", ".ui.RemittanceResultUI");
bundle.putString("realname_verify_process_jump_plugin", "remittance");
realnameGuideHelper.b(this, bundle, new 2(this));
realnameGuideHelper.a(this, bundle, new 3(this));
this.sy.remove("key_realname_guide_helper");
return;
}
return;
}
brG();
}
private void brG() {
x.i("MicroMsg.RemittanceResultNewUI", "doEndRemittance");
cDK().b(this, this.sy);
new ag().postDelayed(new 4(this), 100);
}
public final boolean d(int i, int i2, String str, l lVar) {
if (WalletSuccPageAwardWidget.a(this.mAh)) {
return this.mAi.d(i, i2, str, lVar);
}
return super.d(i, i2, str, lVar);
}
public final void ux(int i) {
this.mController.contentView.setVisibility(i);
}
protected final boolean brH() {
return false;
}
public void onResume() {
super.onResume();
if (WalletSuccPageAwardWidget.a(this.mAh)) {
this.mAi.onResume();
}
}
public void onDestroy() {
super.onDestroy();
if (WalletSuccPageAwardWidget.a(this.mAh)) {
this.mAi.onDestroy();
}
}
}
|
package uo.asw.inciManager;
import java.util.UUID;
public class IdentifierGenerator {
public static String getIdentifier() {
return UUID.randomUUID().toString().replace("-", "");
}
}
|
package com.cnk.travelogix.acco.rate.populator;
import com.cnk.travelogix.rate.acco.data.AccoSurchargeSuppDetailData;
import com.cnk.travelogix.supplier.rates.enums.AccoSurchargeSubType;
import com.cnk.travelogix.supplier.rates.enums.SupplementType;
import com.cnk.travelogix.supplier.rates.enums.SurchargeSupplementType;
import com.cnk.travelogix.supplier.rates.supplierrate.model.accommodation.AccoSurchargeSuppDetailModel;
import com.cnk.travelogix.supplier.settlementterms.core.enums.ThresholdType;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
public class AccoSurchargeSuppDetailReversePopulator implements Populator<AccoSurchargeSuppDetailData, AccoSurchargeSuppDetailModel> {
@Override
public void populate(AccoSurchargeSuppDetailData source, AccoSurchargeSuppDetailModel target)
throws ConversionException {
target.setSurchargeId(source.getSurchargeID());
target.setSurchargeName(source.getSurchageName());
target.setType(SurchargeSupplementType.valueOf(source.getType()));
target.setSupplement(SupplementType.valueOf(source.getSupplement()));
target.setPriceInclusion(source.getPriceInclusion());
target.setPriceExclusion(source.getPriceExclusion());
target.setInternalDescription(source.getInternalDescription());
target.setExternalDescription(source.getExternalDescription());
target.setPayOnArrival(source.getPayOnArrival());
target.setSubType(AccoSurchargeSubType.valueOf(source.getSubType()));
//target.setRoomCategories(source.getRoomCategories());// need to check as it is set type
//target.setRoomTypes(source.getRoomTypes()); //need to check as it is set type
//target.setMealPlan(source.getMealPlan());// Collection enum type
target.setStdCommissionType(ThresholdType.valueOf(source.getStdCommissionType()));
target.setStdCommissionValue(source.getStdCommissionValue());
target.setAmount(source.getAmount());
//target.setPassengerLevelSurchargeDetails(source.getPassengerLevelSurchargeDetails()); TODO Collection type
}
}
|
package com.gcteam.yandextranslate.utils;
import android.support.annotation.Nullable;
/**
* Created by turist on 12.04.2017.
*/
public class Strings {
public static boolean isNullOrEmpty(@Nullable String str) {
return str == null || str.isEmpty();
}
public static boolean areEqual(@Nullable String str1, @Nullable String str2) {
if(str1 == str2) {
return true;
}
if(str1 == null || str2 == null) {
return false;
}
return str1.equals(str2);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.monash.assg1;
/**
*
* @author Pammy
*/
//flick class to store a flickr object from renturn json response.
public class Flickr {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
package com.espendwise.manta.service;
import com.espendwise.manta.model.view.ProfilePasswordMgrView;
public interface ProfileService {
public ProfilePasswordMgrView getPasswordManagementInfo(Long storeId);
public ProfilePasswordMgrView savePasswordManagementInfo(ProfilePasswordMgrView passwordView) throws DatabaseUpdateException;
}
|
package com.codingblocks.sqlitepractice.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class dbHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "todo.db";
public dbHelper(@Nullable Context context) {
super(context, DB_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TodoTable.CMD_CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
|
package com.anexa.livechat.dto.waboxapp;
import java.io.Serializable;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class WaBoxAppBodyDto implements Serializable {
private static final long serialVersionUID = 1L;
private String text;
private String caption;
private String mimetype;
private String url;
private String thumb;
private Long size;
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package an1.persistence;
import an1.exceptions.NonexistentEntityException;
import an1.exceptions.PreexistingEntityException;
import an1.exceptions.RollbackFailureException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
//import javax.transaction.UserTransaction;
/**
*
* @author bbernard
*/
public class EcrituresJpaController {
private EntityTransaction utx = null;
public EntityManager getEntityManager() {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("anbJPA");
EntityManager em = emf.createEntityManager();
return em;
}
public void create(Ecritures ecriture) throws PreexistingEntityException,
RollbackFailureException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
utx = em.getTransaction();
utx.begin();
em.persist(ecriture);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException(
"An error occurred attempting to roll back the transaction.",
re);
}
if (findEcritures(ecriture.getNumero()) != null) {
throw new PreexistingEntityException("Ecriture " + ecriture
+ " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Ecritures ecriture) throws NonexistentEntityException,
RollbackFailureException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
utx = em.getTransaction();
utx.begin();
ecriture = em.merge(ecriture);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException(
"An error occurred attempting to roll back the transaction.",
re);
}
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = ecriture.getNumero();
if (findEcritures(id) == null) {
throw new NonexistentEntityException("The membres with id "
+ id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws NonexistentEntityException,
RollbackFailureException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
utx = em.getTransaction();
utx.begin();
Ecritures ecriture;
try {
ecriture = em.getReference(Ecritures.class, id);
ecriture.getCode();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The ecriture with id "
+ id + " no longer exists.", enfe);
}
em.remove(ecriture);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException(
"An error occurred attempting to roll back the transaction.",
re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public List<Ecritures> findEcrituresEntities() {
return findEcrituresEntities(true, -1, -1);
}
public List<Ecritures> findEcrituresEntities(int maxResults, int firstResult) {
return findEcrituresEntities(false, maxResults, firstResult);
}
@SuppressWarnings("unchecked")
private List<Ecritures> findEcrituresEntities(boolean all, int maxResults,
int firstResult) {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select object(o) from ecritures as o");
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Ecritures findEcritures(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Ecritures.class, id);
} finally {
em.close();
}
}
public int getEcrituresCount() {
EntityManager em = getEntityManager();
try {
return ((Long) em
.createQuery("select count(o) from ecritures as o")
.getSingleResult()).intValue();
} finally {
em.close();
}
}
@SuppressWarnings("unchecked")
public List<Ecritures> getEcritures(Membres m) {
// TODO Auto-generated method stub
EntityManager em = getEntityManager();
try {
Query q = em
.createQuery("select object(o) from Ecritures as o where o.membre=:membre");
q.setParameter("membre", m);
return q.getResultList();
} finally {
em.close();
}
}
public float getSoldeEcritures(Membres m) {
EntityManager em = getEntityManager();
try {
Query q = em
.createQuery("select sum(o.credit) from Ecritures as o where o.membre=:membre");
q.setParameter("membre", m);
Number credit = (Number) q.getSingleResult();
q = em
.createQuery("select sum(o.debit) from Ecritures as o where o.membre=:membre");
q.setParameter("membre", m);
Number debit = (Number) q.getSingleResult();
float creditf=0;
if (credit!=null) creditf=credit.floatValue();
float debitf=0;
if (debit!=null) debitf=debit.floatValue();
return creditf - debitf;
} finally {
em.close();
}
}
}
|
package com.spizzyrichlife.ussrpg_v01.Activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.spizzyrichlife.ussrpg_v01.R;
//This is where players will be able to roll dice and will be affected by which character is currently selected as the active character.
//TODO: Allow user to roll dice //TODO: Allow player to roll dice based on Active Character. //TODO: Allow player to "play" cards to the cup (Gesture control?)
public class DicePoolerActivity extends AppCompatActivity {
EditText blues;
EditText greens;
EditText yellows;
EditText blacks;
EditText purples;
EditText reds;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dice_pooler);
//Find roll nums
blues = (EditText) findViewById(R.id.blueDiceET);
greens = (EditText) findViewById(R.id.greenDiceET);
yellows = (EditText) findViewById(R.id.yellowDiceET);
blacks = (EditText) findViewById(R.id.blackDiceET);
purples = (EditText) findViewById(R.id.purpleDiceET);
reds = (EditText) findViewById(R.id.redDiceET);
Button rollButton = (Button) findViewById(R.id.rollDiceButton);
rollButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(DicePoolerActivity.this, RollResultsActivity.class);
//Pass numbers of dice to roll, store as array
// int[] diceBundle = {Integer.parseInt(blues.getText().toString()), Integer.parseInt(greens.getText().toString()), Integer.parseInt(yellows.getText().toString()), Integer.parseInt(blacks.getText().toString()), Integer.parseInt(purples.getText().toString()), Integer.parseInt(reds.getText().toString())};
// intent.putExtra("dice", diceBundle);
intent.putExtra("blues", Integer.parseInt(blues.getText().toString()));
intent.putExtra("greens", Integer.parseInt(greens.getText().toString()));
intent.putExtra("yellows", Integer.parseInt(yellows.getText().toString()));
intent.putExtra("blacks", Integer.parseInt(blacks.getText().toString()));
intent.putExtra("purples", Integer.parseInt(purples.getText().toString()));
intent.putExtra("reds", Integer.parseInt(reds.getText().toString()));
startActivity(intent);
}
});
}
}
|
package edu.kit.pse.osip.monitoring.view.dialogs;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import javafx.stage.Stage;
import org.junit.Test;
import org.testfx.framework.junit.ApplicationTest;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Test class for the Dialog classes.
*
* @author Martin Armbruster
* @version 1.0
*/
public class DialogTest extends ApplicationTest {
/**
* Saves a test instance of the AboutDialog.
*/
private AboutDialog about;
/**
* Saves a test instance of the HelpDialog.
*/
private HelpDialog help;
@Override
public void start(Stage arg0) throws Exception {
about = new AboutDialog();
help = new HelpDialog();
}
/**
* Tests the constructors of the Dialog classes.
*
* @throws Exception when something goes wrong.
*/
@Test
public void testDialogs() throws Exception {
assertNotNull(about);
assertNotNull(help);
final CompletableFuture<Boolean> showed = new CompletableFuture<>();
Platform.runLater(() -> {
about.show();
help.show();
showed.complete(true);
});
assertTrue(showed.get(5, TimeUnit.SECONDS));
assertTrue(about.isShowing());
assertTrue(help.isShowing());
final CompletableFuture<Boolean> hidden = new CompletableFuture<>();
Platform.runLater(() -> {
about.hide();
help.hide();
hidden.complete(true);
});
assertTrue(hidden.get(5, TimeUnit.SECONDS));
assertFalse(about.isShowing());
assertFalse(help.isShowing());
}
}
|
package ru.vanilla.ink.findway.utils;
import ru.vanilla.ink.findway.map.element.Cell;
/**
* Created by hedgehog on 03.08.17.
*/
public class Arrays {
public static Cell[][] get2Dcell(int height, int width) {
return new Cell[height][width];
}
}
|
package com.adventuregames;
import java.util.List;
import java.util.Vector;
public class AdventureGame
{
GameInitializer initializer;
ObstacleGenerator jungleObstacleGenerator, dessertObstacleGenerator, seaObstacleGenerator;
GameGUI gui;
User user;
int generatorIndex,obstacleIndex,totalChoices,optionIndex;
ObstacleGenerator[] obstacleGenerators;
List<String> choicesSelected;
boolean healthFlag= true, stopGame=false,gameWon=false;
public AdventureGame()
{
user = new User();
choicesSelected = new Vector<String>();
obstacleGenerators = new ObstacleGenerator[3];
new UserInfoGUI(user,this);
}
public void setOptionIndex(int optionIndex)
{
this.optionIndex=optionIndex;
checkHealth();
}
public void checkHealth()
{
if(generatorIndex==0)
{
if(obstacleIndex==0 && optionIndex==1)
updateHealth(40);
else if(obstacleIndex==1 && optionIndex==0)
updateHealth(40);
else if(obstacleIndex==2 && optionIndex==0)
updateHealth(15);
else if(obstacleIndex==2 && optionIndex==1)
updateHealth(40);
else if(obstacleIndex==5 && optionIndex==0)
updateHealth(5);
else if(obstacleIndex==5 && optionIndex==1)
updateHealth(15);
else if(obstacleIndex==5 && optionIndex==2)
updateHealth(10);
else if(obstacleIndex==6 && optionIndex==0)
updateHealth(5);
}
else if(generatorIndex==1)
{
if(obstacleIndex==1 && optionIndex==2)
updateHealth(5);
else if(obstacleIndex==4 && optionIndex==1)
updateHealth(5);
else if(obstacleIndex==5 && optionIndex==0)
updateHealth(40);
else if(obstacleIndex==6 && optionIndex==0)
updateHealth(40);
}
else if(generatorIndex==2)
{
if(obstacleIndex==7 && optionIndex==0)
updateHealth(40);
}
if(user.getHealth()<=0)
stopGame=true;
else
gui.jpb.setValue(user.getHealth());
if(generatorIndex==2&&obstacleIndex==7)
gameWon=true;
}
private void updateHealth(int health)
{
user.setHealth(user.getHealth()-health);
}
public void initalizeGame()
{
initializer = new GameInitializer(this);
jungleObstacleGenerator = initializer.getJungleObstacleGenerator();
dessertObstacleGenerator = initializer.getDessertObstacleGenerator();
seaObstacleGenerator = initializer.getSeaObstacleGenerator();
obstacleGenerators[0] = jungleObstacleGenerator;
obstacleGenerators[1] = dessertObstacleGenerator;
obstacleGenerators[2] = seaObstacleGenerator;
gui = initializer.getGameGUI();
setInitialStoryLine();
}
public void setInitialStoryLine()
{
gui.jta.append("Welcome to Adventure Game\n");
gui.jta.append("To reach your Destination Get Started\n");
ObstacleHandlingChoice choice1 = new ObstacleHandlingChoiceImpl("1. Brittle Bridge that breaks with weight\n\n","Brittle bridge, as the name suggests,\n can be broken easily, and that is what has really happened.",1,1);
ObstacleHandlingChoice choice2 = new ObstacleHandlingChoiceImpl("2. The Lava Bridge with volcano beneath it\n\n","The lava bridge is known for it's burning temperatures,\n something which you cannot endure.",4,1);
ObstacleHandlingChoice choice3 = new ObstacleHandlingChoiceImpl("3. The Rocky bridge with heavy obstacles\n\n","The rocky bridge now has something for you!",6,1);
Obstacle obstacle = new ObstacleImpl("You need to choose a bridge to cross the jungle and enter the desert.\nWhich bridge would you choose?\n", new ObstacleHandlingChoice[] {choice1,choice2,choice3});
gui.setObstacle(obstacle);
/*
gui.jta.append("Welcome to Adventure Game\n");
gui.jta.append("To reach your Destination Get Started\n");
gui.jta.append("\n\n 1. Cruise through the Land\n");
gui.jta.append("\n\n 2. Swim through the Occean\n");
*/
}
public void setGeneratorIndex(int generatorIndex)
{
this.generatorIndex = generatorIndex;
}
public void setObstacleIndex(int obstacleIndex)
{
this.obstacleIndex = obstacleIndex;
}
public void incrementTotalChoices()
{
totalChoices = totalChoices+1;
}
public void setNextObstacle()
{
if(!stopGame && !gameWon)
gui.setObstacle(obstacleGenerators[generatorIndex].getObstacle(obstacleIndex));
else
{
if(!gameWon)
{
gui.jta.append("\n\nSince the health has been reduced to zero, the game has ended");
}
else
gui.jta.append("\n\nYou have finally accomplished your mission!!!");
gui.option1btn.setEnabled(false);
gui.option2btn.setEnabled(false);
gui.option3btn.setEnabled(false);
gui.jta.append("\n\n\nTotal Choices you selected during the game = "+totalChoices);
gui.jta.append("\n\nFollowing are the choices you selected\n");
for(String s: choicesSelected)
{
gui.jta.append("\n\n"+s);
}
}
}
public void addChoiceSelected(String choiceSelected)
{
choicesSelected.add(choiceSelected);
}
public static void main(String args[])
{
new AdventureGame();
}
};
|
package com.supconit.kqfx.web.analysis.controllers;
import hc.base.domains.AjaxMessage;
import hc.base.domains.Pageable;
import hc.base.domains.Pagination;
import hc.business.dic.services.DataDictionaryService;
import hc.mvc.annotations.FormBean;
import hc.safety.manager.SafetyManager;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.supconit.honeycomb.business.authorization.entities.Role;
import com.supconit.honeycomb.business.authorization.entities.User;
import com.supconit.honeycomb.business.authorization.services.RoleService;
import com.supconit.honeycomb.business.organization.services.DepartmentService;
import com.supconit.honeycomb.business.organization.services.PersonService;
import com.supconit.kqfx.web.analysis.entities.JgZcd;
import com.supconit.kqfx.web.analysis.entities.TimeZone;
import com.supconit.kqfx.web.analysis.services.JgZcdService;
import com.supconit.kqfx.web.analysis.services.TimeZoneService;
import com.supconit.kqfx.web.util.DictionaryUtil;
import com.supconit.kqfx.web.util.OperateType;
import com.supconit.kqfx.web.util.UtilTool;
import com.supconit.kqfx.web.xtgl.entities.ExtPerson;
import com.supconit.kqfx.web.xtgl.services.SystemLogService;
/**
* 超限统计-按小时超限统计
*
* @author zongkai
*/
@SuppressWarnings("deprecation")
@RequestMapping("/analysis/overload/houroverload")
@Controller("analysis_hour_controller")
public class HourAnalysisController {
private static final String MODULE_CODE = "HOUR_ANALYSIS";
@Autowired
private TimeZoneService timeZoneService;
@Autowired
private DataDictionaryService dataDictionaryService;
@Autowired
private SafetyManager safetyManager;
@Autowired
private RoleService roleService;
@Autowired
private DepartmentService departmentService;
@Autowired
private PersonService personService;
@Autowired
private JgZcdService jgZcdService;
@Autowired
private SystemLogService systemLogService;
@Resource
private HttpServletRequest request;
@ModelAttribute("timezone")
private TimeZone getTimeZone() {
TimeZone timezone = new TimeZone();
return timezone;
}
private transient static final Logger logger = LoggerFactory.getLogger(HourAnalysisController.class);
@RequestMapping(value = "list", method = RequestMethod.GET)
public String list(ModelMap model) {
this.systemLogService.log(MODULE_CODE, OperateType.view.getCode(), "按小时超限统计", request.getRemoteAddr());
try {
User user = (User) safetyManager.getAuthenticationInfo().getUser();
if (null != user && null != user.getPerson() && null != user.getPersonId()) {
ExtPerson person = personService.getById(user.getPersonId());
//根据JGID进行权限限制
//若是超级管理员查询JGID = null
//大桥的为 JGID = 133
// 二桥为JGID=134
model.put("jgid", person.getJgbh());
}
HashMap<String, String> stationMap = DictionaryUtil.dictionary("STATIONNAME", dataDictionaryService);
for (String key : stationMap.keySet()) {
model.put("station" + key, stationMap.get(key));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return "analysis/overload/houroverload/list";
}
@ResponseBody
@RequestMapping(value = "list", method = RequestMethod.POST)
public Pagination<TimeZone> list(Pagination<TimeZone> pager, @FormBean(value = "condition", modelCode = "timezone") TimeZone condition) {
try {
this.systemLogService.log(MODULE_CODE, OperateType.query.getCode(), "按小时超限统计", request.getRemoteAddr());
if (pager.getPageNo() < 1 || pager.getPageSize() < 1 || pager.getPageSize() > Pagination.MAX_PAGE_SIZE)
return pager;
timeZoneService.findByHourPager(pager, condition);
TimeZone hourCnt = timeZoneService.getPartTimeCount(condition);
for (TimeZone hour : pager) {
if (hour.getTimeString() != null) {
hour.setTimeString(hour.getTimeString().substring(0, 2));
int time1 = Integer.valueOf(hour.getTimeString());
int time2 = time1 + 1;
hour.setTimeString(String.valueOf(time1) + "~" + String.valueOf(time2) + "点");
if (hour.getStationA() == null) {
hour.setStationA(0);
} else {
hour.setStationA(hour.getStationA() / hourCnt.getCntHours(hour.getTimeString()));
}
if (hour.getStationB() == null) {
hour.setStationB(0);
} else {
hour.setStationB(hour.getStationB() / hourCnt.getCntHours(hour.getTimeString()));
}
if (hour.getStationC() == null) {
hour.setStationC(0);
} else {
hour.setStationC(hour.getStationC() / hourCnt.getCntHours(hour.getTimeString()));
}
if (hour.getStationD() == null) {
hour.setStationD(0);
} else {
hour.setStationD(hour.getStationD() / hourCnt.getCntHours(hour.getTimeString()));
}
if (hour.getStationE() == null) {
hour.setStationE(0);
} else {
hour.setStationE(hour.getStationE() / hourCnt.getCntHours(hour.getTimeString()));
}
if (condition.getJgid() == null) {
hour.setTotal(hour.getStationA() + hour.getStationB() + hour.getStationC() + hour.getStationD() + hour.getStationE());
} else {
if (condition.getJgid() == 133) {
hour.setTotal(hour.getStationA() + hour.getStationB());
} else if (condition.getJgid() == 134) {
hour.setTotal(hour.getStationC() + hour.getStationD() + hour.getStationE());
} else {
hour.setTotal(hour.getStationA() + hour.getStationB() + hour.getStationC() + hour.getStationD() + hour.getStationE());
}
}
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return pager;
}
/**
* 获取治超站数据
*
* @return
*/
@ResponseBody
@RequestMapping(value = "detectionStation", method = RequestMethod.POST)
AjaxMessage getDetectionStation() {
try {
HashMap<String, String> stationMap = DictionaryUtil.dictionary("STATIONNAME", dataDictionaryService);
List<String> stationList = new ArrayList<String>();
Boolean isAdmin = false;
Long jgid = null;
// 根据人员来获取查询权限
User user = (User) safetyManager.getAuthenticationInfo().getUser();
List<Role> rolelist = this.roleService.findAssigned(user.getId());
if (!CollectionUtils.isEmpty(rolelist)) {
for (Role role : rolelist) {
if ("ROLE_ADMIN".equals(role.getCode())) isAdmin = true;
}
}
if (!isAdmin) {
ExtPerson person = personService.getById(user.getPersonId());
jgid = null != person ? person.getJgbh() : null;
// 人员部分权限
// 根据权限设置查询的治超站范围
List<JgZcd> zcdList = jgZcdService.getByJgid(jgid);
for (JgZcd jgZcd : zcdList) {
stationList.add(jgZcd.getDeteStation() + ":" + stationMap.get(jgZcd.getDeteStation()));
}
} else {
// 超级管理员权限
// 所有的治超站权限
for (String key : stationMap.keySet()) {
stationList.add(key + ":" + stationMap.get(key));
}
}
return AjaxMessage.success(stationList);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* 获取柱状图数据
*
* @return
*/
@ResponseBody
@RequestMapping(value = "getChartData", method = RequestMethod.POST)
public AjaxMessage getChartData(@FormBean(value = "condition", modelCode = "timezone") TimeZone condition) {
try {
this.systemLogService.log(MODULE_CODE, OperateType.view.getCode(),
"查询按小时超限图表信息", request.getRemoteAddr());
TimeZone hourCnt = new TimeZone();
//是否选择日期没有选择查看昨天数据信息
List<TimeZone> houroverLoadList = new ArrayList<TimeZone>();
if (condition.getTjDate() == null) {
houroverLoadList = timeZoneService.getByPartTime(condition);
hourCnt = timeZoneService.getPartTimeCount(condition);
} else {
//获取选择时间段内统计数据信息
houroverLoadList = timeZoneService.getByPartTime(condition);
hourCnt = timeZoneService.getPartTimeCount(condition);
}
if (!CollectionUtils.isEmpty(houroverLoadList)) {
// 横轴数据(1~24小时)
List<String> xAisData = new ArrayList<String>();
for (int i = 0; i < 24; i++) {
xAisData.add(String.valueOf(i) + "~" + String.valueOf(i + 1) + "点");
}
// 设置legend(治超站)
HashMap<String, String> detectionLengend = DictionaryUtil.dictionary("STATIONNAME", dataDictionaryService);
List<String> legend = new ArrayList<String>();
if (condition.getJgid() == null) {
Iterator<String> iterator = detectionLengend.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
legend.add(detectionLengend.get(key));
}
} else {
if (condition.getJgid() == 133) {
legend.add(detectionLengend.get("1"));
legend.add(detectionLengend.get("2"));
} else if (condition.getJgid() == 134) {
legend.add(detectionLengend.get("3"));
legend.add(detectionLengend.get("4"));
legend.add(detectionLengend.get("5"));
} else {
Iterator<String> iterator = detectionLengend.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
legend.add(detectionLengend.get(key));
}
}
}
legend.add("汇总");
// 纵轴数据
List<TimeZone> yAisData = new ArrayList<TimeZone>();
for (TimeZone timeZone : houroverLoadList) {
//设置治超站名称
timeZone.setStation(detectionLengend.get(timeZone.getDetectStation()));
//设置24小时的值
if (timeZone.getAh() == null) {
timeZone.setAh(0);
} else {
timeZone.setAh(timeZone.getAh() / hourCnt.getAh());
}
if (timeZone.getBh() == null) {
timeZone.setBh(0);
} else {
timeZone.setBh(timeZone.getBh() / hourCnt.getBh());
}
if (timeZone.getCh() == null) {
timeZone.setCh(0);
} else {
timeZone.setCh(timeZone.getCh() / hourCnt.getCh());
}
if (timeZone.getDh() == null) {
timeZone.setDh(0);
} else {
timeZone.setDh(timeZone.getDh() / hourCnt.getDh());
}
if (timeZone.getEh() == null) {
timeZone.setEh(0);
} else {
timeZone.setEh(timeZone.getEh() / hourCnt.getEh());
}
if (timeZone.getFh() == null) {
timeZone.setFh(0);
} else {
timeZone.setFh(timeZone.getFh() / hourCnt.getFh());
}
if (timeZone.getGh() == null) {
timeZone.setGh(0);
} else {
timeZone.setGh(timeZone.getGh() / hourCnt.getGh());
}
if (timeZone.getHh() == null) {
timeZone.setHh(0);
} else {
timeZone.setHh(timeZone.getHh() / hourCnt.getHh());
}
if (timeZone.getIh() == null) {
timeZone.setIh(0);
} else {
timeZone.setIh(timeZone.getIh() / hourCnt.getIh());
}
if (timeZone.getJh() == null) {
timeZone.setJh(0);
} else {
timeZone.setJh(timeZone.getJh() / hourCnt.getJh());
}
if (timeZone.getKh() == null) {
timeZone.setKh(0);
} else {
timeZone.setKh(timeZone.getKh() / hourCnt.getKh());
}
if (timeZone.getLh() == null) {
timeZone.setLh(0);
} else {
timeZone.setLh(timeZone.getLh() / hourCnt.getLh());
}
if (timeZone.getMh() == null) {
timeZone.setMh(0);
} else {
timeZone.setMh(timeZone.getMh() / hourCnt.getMh());
}
if (timeZone.getNh() == null) {
timeZone.setNh(0);
} else {
timeZone.setNh(timeZone.getNh() / hourCnt.getNh());
}
if (timeZone.getOh() == null) {
timeZone.setOh(0);
} else {
timeZone.setOh(timeZone.getOh() / hourCnt.getOh());
}
if (timeZone.getPh() == null) {
timeZone.setPh(0);
} else {
timeZone.setPh(timeZone.getPh() / hourCnt.getPh());
}
if (timeZone.getQh() == null) {
timeZone.setQh(0);
} else {
timeZone.setQh(timeZone.getQh() / hourCnt.getQh());
}
if (timeZone.getRh() == null) {
timeZone.setRh(0);
} else {
timeZone.setRh(timeZone.getRh() / hourCnt.getRh());
}
if (timeZone.getSh() == null) {
timeZone.setSh(0);
} else {
timeZone.setSh(timeZone.getSh() / hourCnt.getSh());
}
if (timeZone.getTh() == null) {
timeZone.setTh(0);
} else {
timeZone.setTh(timeZone.getTh() / hourCnt.getTh());
}
if (timeZone.getUh() == null) {
timeZone.setUh(0);
} else {
timeZone.setUh(timeZone.getUh() / hourCnt.getUh());
}
if (timeZone.getVh() == null) {
timeZone.setVh(0);
} else {
timeZone.setVh(timeZone.getVh() / hourCnt.getVh());
}
if (timeZone.getWh() == null) {
timeZone.setWh(0);
} else {
timeZone.setWh(timeZone.getWh() / hourCnt.getWh());
}
if (timeZone.getXh() == null) {
timeZone.setXh(0);
} else {
timeZone.setXh(timeZone.getXh() / hourCnt.getXh());
}
timeZone.setTotal(timeZone.getAh() + timeZone.getBh() + timeZone.getCh() + timeZone.getDh() + timeZone.getEh() + timeZone.getFh() + timeZone.getGh() +
timeZone.getHh() + timeZone.getIh() + timeZone.getJh() + timeZone.getKh() + timeZone.getLh() + timeZone.getMh() + timeZone.getNh() +
timeZone.getOh() + timeZone.getPh() + timeZone.getQh() + timeZone.getRh() + timeZone.getSh() + timeZone.getTh() + timeZone.getUh() +
timeZone.getVh() + timeZone.getWh() + timeZone.getXh()
);
yAisData.add(timeZone);
}
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("xAis", xAisData);
resultMap.put("legend", legend);
resultMap.put("yAis", yAisData);
//标志查询结果是否为空
resultMap.put("success", 200);
return AjaxMessage.success(resultMap);
} else {
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("success", 1002);
return AjaxMessage.success(resultMap);
}
} catch (Exception e) {
logger.error("", e);
return AjaxMessage.success("请求服务器错误");
}
}
@RequestMapping(value = "exportAll", method = RequestMethod.GET)
public void exportAll(HttpServletRequest request,
HttpServletResponse response,
String total,
@FormBean(value = "condition", modelCode = "timezone") TimeZone condition) {
logger.info("-------------------------导出全部excel列表---------------");
try {
this.systemLogService.log(MODULE_CODE, OperateType.export.getCode(),
"按小时超限导出全部记录", request.getRemoteAddr());
Pagination<TimeZone> pager = new Pagination<TimeZone>();
pager.setPageNo(1);
pager.setPageSize(Integer.MAX_VALUE);
timeZoneService.findByHourPager(pager, condition);
TimeZone hourCnt = timeZoneService.getPartTimeCount(condition);
for (TimeZone hour : pager) {
if (hour.getTimeString() != null) {
hour.setTimeString(hour.getTimeString().substring(0, 2));
int time1 = Integer.valueOf(hour.getTimeString());
int time2 = time1 + 1;
hour.setTimeString(String.valueOf(time1) + "~" + String.valueOf(time2) + "点");
if (hour.getStationA() == null) {
hour.setStationA(0);
} else {
hour.setStationA(hour.getStationA() / hourCnt.getCntHours(hour.getTimeString()));
}
if (hour.getStationB() == null) {
hour.setStationB(0);
} else {
hour.setStationB(hour.getStationB() / hourCnt.getCntHours(hour.getTimeString()));
}
if (hour.getStationC() == null) {
hour.setStationC(0);
} else {
hour.setStationC(hour.getStationC() / hourCnt.getCntHours(hour.getTimeString()));
}
if (hour.getStationD() == null) {
hour.setStationD(0);
} else {
hour.setStationD(hour.getStationD() / hourCnt.getCntHours(hour.getTimeString()));
}
if (hour.getStationE() == null) {
hour.setStationE(0);
} else {
hour.setStationE(hour.getStationE() / hourCnt.getCntHours(hour.getTimeString()));
}
hour.setTotal(hour.getStationA() + hour.getStationB() + hour.getStationC() +
hour.getStationD() + hour.getStationE()
);
}
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
String time = formatter.format(date);
String title = "按小时超限统计记录_" + time + ".xls";
editExcel(pager, response, title, condition);
} catch (Exception e) {
logger.info("-------------------------导出全部excel列表---------------");
}
}
HSSFCellStyle setHSSFCellStyle(HSSFCellStyle style) {
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
return style;
}
void editExcel(Pageable<TimeZone> pager, HttpServletResponse response, String title, TimeZone condition) {
OutputStream out = null;
try {
response.setHeader("Content-Disposition", "attachment; filename="
+ new String(title.getBytes("GB2312"), "iso8859-1"));
response.setContentType("application/msexcel;charset=UTF-8");
out = response.getOutputStream();
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(UtilTool.toGBK("按小时超限统计记录"));
HSSFRow top = sheet.createRow(0);
HSSFRow row = sheet.createRow(1);
HSSFCellStyle style1 = workbook.createCellStyle();
HSSFCellStyle style2 = workbook.createCellStyle();
HSSFCellStyle style3 = workbook.createCellStyle();
/** 字体font **/
HSSFFont font1 = workbook.createFont();
font1.setColor(HSSFColor.BLACK.index);
font1.setFontHeightInPoints((short) 10);
font1.setBoldweight((short) 24);
font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFFont font2 = workbook.createFont();
font2.setColor(HSSFColor.BLACK.index);
font2.setFontHeightInPoints((short) 10);
font2.setBoldweight((short) 24);
style1.setFont(font1);
style1 = setHSSFCellStyle(style1);
style1.setFillBackgroundColor(HSSFColor.AQUA.index);
style1.setFillForegroundColor(HSSFColor.AQUA.index);
style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setFont(font2);
style2 = setHSSFCellStyle(style2);
style3.setFont(font1);
style3 = setHSSFCellStyle(style3);
/** 字体居中 **/
style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style3.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//获取导出条件
String conditionString = "";
//获取导出的时间
if (condition.getTjDate() != null) {
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String begin = format1.format(condition.getTjDate());
if (condition.getUpdateTime() != null) {
String end = format1.format(condition.getUpdateTime());
end = format1.format(condition.getUpdateTime());
conditionString = "统计日期:" + begin + " 至 " + end + "\r\n";
} else {
conditionString = "统计日期:" + begin + "开始至今为止\r\n";
}
}
//获取导出治超站
HashMap<String, String> stationMap = DictionaryUtil.dictionary("STATIONNAME", dataDictionaryService);
String detecString = "";
if (condition.getDetectStation() == null || condition.getDetectStation().equals("") || condition.getDetectStation() == "") {
if (condition.getJgid() == null) {
detecString = detecString + "全部治超站";
} else {
if (condition.getJgid() == 133) {
detecString = detecString + " " + stationMap.get("1");
detecString = detecString + " " + stationMap.get("2");
} else if (condition.getJgid() == 134) {
detecString = detecString + " " + stationMap.get("3");
detecString = detecString + " " + stationMap.get("4");
detecString = detecString + " " + stationMap.get("5");
} else {
detecString = detecString + "全部治超站";
}
}
} else {
detecString = stationMap.get(condition.getDetectStation());
}
conditionString = conditionString + "统计治超站:" + detecString;
//获取用户权限,根据权限导出数据
User user = (User) safetyManager.getAuthenticationInfo().getUser();
if (null != user && null != user.getPerson() && null != user.getPersonId()) {
ExtPerson person = personService.getById(user.getPersonId());
condition.setJgid(person.getJgbh());
}
if (condition.getJgid() == null) {
//导出全部
exportExcelAll(pager, conditionString, style1, style2, style3, row, top, sheet);
} else {
if (condition.getJgid() == 133) {
//导出JGBH133
exportExcelJgid133(pager, conditionString, style1, style2, style3, row, top, sheet);
} else if (condition.getJgid() == 134) {
//导出JGBH134
exportExcelJgid134(pager, conditionString, style1, style2, style3, row, top, sheet);
}
}
workbook.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void exportExcelAll(Pageable<TimeZone> pager, String conditionString,
HSSFCellStyle style1, HSSFCellStyle style2, HSSFCellStyle style3,
HSSFRow row, HSSFRow top, HSSFSheet sheet) {
//设置表头长度
for (int i = 0; i < 8; i++) {
HSSFCell cell = top.createCell(i);
cell.setCellStyle(style3);
}
//设置表头长度
top.getSheet().addMergedRegion(new Region(0, (short) 0, 0, (short) 7));
//设置表头样式
HSSFCell celltop = top.createCell(0);
top.setHeight((short) (200 * 4));
celltop.setCellStyle(style3);
//设置表头内容:
celltop.setCellValue("按小时超限统计\r\n" + conditionString);
String[] head = {"序号", "统计日期", "K110+150", "K109+800", "总计"};
int i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0;
for (int i = 0; i < head.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(head[i]);
cell.setCellStyle(style1);
if (i == 0) {
i0 = head[i].length() * 256 + 256 * 10;
}
if (i == 1) {
i1 = head[i].length() * 256 + 256 * 10;
}
if (i == 2) {
i2 = head[i].length() * 256 + 256 * 10;
}
if (i == 3) {
i3 = head[i].length() * 256 + 256 * 10;
}
if (i == 4) {
i4 = head[i].length() * 256 + 256 * 10;
}
}
for (int i = 0; i < pager.size(); i++) {
row = sheet.createRow(i + 2);
// 序号
HSSFCell cell0 = row.createCell(0);
cell0.setCellValue(1 + i);
cell0.setCellStyle(style2);
if (String.valueOf(1 + i).length() * 256 >= i0) {
i0 = String.valueOf(1 + i).length() * 256 + 256 * 8;
}
// 统计时间
HSSFCell cell1 = row.createCell(1);
cell1.setCellStyle(style2);
if (pager.get(i).getTimeString() != null) {
cell1.setCellValue(pager.get(i).getTimeString());
if (pager.get(i).getTimeString().length() * 256 >= i1) {
i1 = pager.get(i).getTimeString().length() * 256 + 256 * 10;
}
} else {
cell1.setCellValue("");
}
//// 兰亭往绍兴
HSSFCell cell2 = row.createCell(2);
cell2.setCellStyle(style2);
if (pager.get(i).getStationA() != null) {
cell2.setCellValue(pager.get(i).getStationA());
} else {
cell2.setCellValue("");
}
//// 兰亭往诸暨
HSSFCell cell3 = row.createCell(3);
cell3.setCellStyle(style2);
if (pager.get(i).getStationB() != null) {
cell3.setCellValue(pager.get(i).getStationB());
} else {
cell3.setCellValue("");
}
//// 总计
HSSFCell cell4 = row.createCell(4);
cell4.setCellStyle(style2);
if (pager.get(i).getStationC() != null) {
cell4.setCellValue(pager.get(i).getStationC());
} else {
cell4.setCellValue("");
}
}
sheet.setColumnWidth(0, i0);
sheet.setColumnWidth(1, i1);
sheet.setColumnWidth(2, i2);
sheet.setColumnWidth(3, i3);
sheet.setColumnWidth(4, i4);
}
private void exportExcelJgid133(Pageable<TimeZone> pager, String conditionString,
HSSFCellStyle style1, HSSFCellStyle style2, HSSFCellStyle style3,
HSSFRow row, HSSFRow top, HSSFSheet sheet) {
//设置表头长度
for (int i = 0; i < 5; i++) {
HSSFCell cell = top.createCell(i);
cell.setCellStyle(style3);
}
//设置表头长度
top.getSheet().addMergedRegion(new Region(0, (short) 0, 0, (short) 4));
//设置表头样式
HSSFCell celltop = top.createCell(0);
top.setHeight((short) (200 * 4));
celltop.setCellStyle(style3);
//设置表头内容:
celltop.setCellValue("按小时超限统计\r\n" + conditionString);
String[] head = {"序号", "统计日期", "K110+150", "K109+800", "总计"};
int i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0;
for (int i = 0; i < head.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(head[i]);
cell.setCellStyle(style1);
if (i == 0) {
i0 = head[i].length() * 256 + 256 * 10;
}
if (i == 1) {
i1 = head[i].length() * 256 + 256 * 10;
}
if (i == 2) {
i2 = head[i].length() * 256 + 256 * 10;
}
if (i == 3) {
i3 = head[i].length() * 256 + 256 * 10;
}
if (i == 4) {
i4 = head[i].length() * 256 + 256 * 10;
}
}
for (int i = 0; i < pager.size(); i++) {
row = sheet.createRow(i + 2);
// 序号
HSSFCell cell0 = row.createCell(0);
cell0.setCellValue(1 + i);
cell0.setCellStyle(style2);
if (String.valueOf(1 + i).length() * 256 >= i0) {
i0 = String.valueOf(1 + i).length() * 256 + 256 * 8;
}
// 统计时间
HSSFCell cell1 = row.createCell(1);
cell1.setCellStyle(style2);
if (pager.get(i).getTimeString() != null) {
cell1.setCellValue(pager.get(i).getTimeString());
if (pager.get(i).getTimeString().length() * 256 >= i1) {
i1 = pager.get(i).getTimeString().length() * 256 + 256 * 10;
}
} else {
cell1.setCellValue("");
}
//// 椒江一桥北
HSSFCell cell2 = row.createCell(2);
cell2.setCellStyle(style2);
if (pager.get(i).getStationA() != null) {
cell2.setCellValue(pager.get(i).getStationA());
} else {
cell2.setCellValue("");
}
//// 椒江一桥南
HSSFCell cell3 = row.createCell(3);
cell3.setCellStyle(style2);
if (pager.get(i).getStationB() != null) {
cell3.setCellValue(pager.get(i).getStationB());
} else {
cell3.setCellValue("");
}
//// 总计
HSSFCell cell4 = row.createCell(4);
cell4.setCellStyle(style2);
if (pager.get(i).getTotal() != null) {
cell4.setCellValue(pager.get(i).getTotal());
} else {
cell4.setCellValue("");
}
}
sheet.setColumnWidth(0, i0);
sheet.setColumnWidth(1, i1);
sheet.setColumnWidth(2, i2);
sheet.setColumnWidth(3, i3);
sheet.setColumnWidth(4, i4);
}
private void exportExcelJgid134(Pageable<TimeZone> pager, String conditionString,
HSSFCellStyle style1, HSSFCellStyle style2, HSSFCellStyle style3,
HSSFRow row, HSSFRow top, HSSFSheet sheet) {
//设置表头长度
for (int i = 0; i < 6; i++) {
HSSFCell cell = top.createCell(i);
cell.setCellStyle(style3);
}
//设置表头长度
top.getSheet().addMergedRegion(new Region(0, (short) 0, 0, (short) 5));
//设置表头样式
HSSFCell celltop = top.createCell(0);
top.setHeight((short) (200 * 4));
celltop.setCellStyle(style3);
//设置表头内容:
celltop.setCellValue("按小时超限统计\r\n" + conditionString);
String[] head = {"序号", "统计日期", "椒江二桥北74省道", "椒江二桥北75省道", "椒江二桥南75省道", "总计"};
int i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0;
for (int i = 0; i < head.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(head[i]);
cell.setCellStyle(style1);
if (i == 0) {
i0 = head[i].length() * 256 + 256 * 10;
}
if (i == 1) {
i1 = head[i].length() * 256 + 256 * 10;
}
if (i == 2) {
i2 = head[i].length() * 256 + 256 * 10;
}
if (i == 3) {
i3 = head[i].length() * 256 + 256 * 10;
}
if (i == 4) {
i4 = head[i].length() * 256 + 256 * 10;
}
if (i == 5) {
i5 = head[i].length() * 256 + 256 * 10;
}
}
for (int i = 0; i < pager.size(); i++) {
row = sheet.createRow(i + 2);
// 序号
HSSFCell cell0 = row.createCell(0);
cell0.setCellValue(1 + i);
cell0.setCellStyle(style2);
if (String.valueOf(1 + i).length() * 256 >= i0) {
i0 = String.valueOf(1 + i).length() * 256 + 256 * 8;
}
// 统计时间
HSSFCell cell1 = row.createCell(1);
cell1.setCellStyle(style2);
if (pager.get(i).getTimeString() != null) {
cell1.setCellValue(pager.get(i).getTimeString());
if (pager.get(i).getTimeString().length() * 256 >= i1) {
i1 = pager.get(i).getTimeString().length() * 256 + 256 * 10;
}
} else {
cell1.setCellValue("");
}
//// 椒江二桥北74省道
HSSFCell cell2 = row.createCell(2);
cell2.setCellStyle(style2);
if (pager.get(i).getStationC() != null) {
cell2.setCellValue(pager.get(i).getStationC());
} else {
cell2.setCellValue("");
}
//// 椒江二桥北75省道
HSSFCell cell3 = row.createCell(3);
cell3.setCellStyle(style2);
if (pager.get(i).getStationD() != null) {
cell3.setCellValue(pager.get(i).getStationD());
} else {
cell3.setCellValue("");
}
//// 椒江二桥南75省道
HSSFCell cell4 = row.createCell(4);
cell4.setCellStyle(style2);
if (pager.get(i).getStationE() != null) {
cell4.setCellValue(pager.get(i).getStationE());
} else {
cell4.setCellValue("");
}
// 总计
HSSFCell cell5 = row.createCell(5);
cell5.setCellStyle(style2);
if (pager.get(i).getTotal() != null) {
cell5.setCellValue(pager.get(i).getTotal());
} else {
cell5.setCellValue("");
}
}
sheet.setColumnWidth(0, i0);
sheet.setColumnWidth(1, i1);
sheet.setColumnWidth(2, i2);
sheet.setColumnWidth(3, i3);
sheet.setColumnWidth(4, i4);
sheet.setColumnWidth(5, i5);
}
}
|
/*
* <p>Title: TreeBuilder.java</p>
* <p>Description: </p>
* <p>Copyright: ChaoChuang (c) 2005 </p>
* <p>Company: 南宁超创信息工程有限公司</p>
* Created on 2005-4-1
*/
package com.spower.basesystem.common.tree;
import java.util.List;
import java.util.Map;
/**
* @author fzw
* @version 1.0
*/
public interface TreeBuilder {
/**
* 获取已经按树关系排序的节点列表
* @return
*/
List getTreeNodeList();
/**
* 取得树的所有节点的信息
* @return 树的信息数组
*/
List getTreeInfoList();
/**
* 取得树的根节点列表
* @param treeInfoList 包含要显示树的各个节点的所有信息的List列表
* @return 包含所有根节点信息的List
*/
List getRootStack(List treeInfoList);
/**
* 取得整个信息树的节点间的关系图
* @param treeInfoList 包含要显示树的各个节点的所有信息的List列表
* @return 节点间的关系图
*/
Map getNodeRelMap(List treeInfoList);
/**
* 根据当前所在的节点取得节点对象的编号
* @param nodeObject 当前节点对象
* @return 节点对象的编号
*/
Integer getNodeId(Object nodeObject);
/**
* 在树信息的List中找出当前节点编号的父节点对象的编号
* @param nodeId 当前节点对象的编号
* @param seedList 包含所有节点对象信息的List
* @return 父节点编号
*/
Integer getNodeParentId(Integer nodeId);
/**
* 取当前节点对象的名称
* @param nodeObject 当前节点对象
* @return 节点的名称
*/
String getNodeName(Object nodeObject);
/**
* 取得当前节点编号的父节点层次总数
* @param nodeId
* @return 父节点层次
*/
int getParentSize(Integer nodeId);
/**
* 生成树视图的实体部分,通过堆栈实现递归调用
* @param rootStack 包含所有根节点信息的List
* @param treeRelMap 节点间的关系图
* @return 构成树视图部分html字符串信息
*/
public List formtTreeNodeList(List rootStack, Map treeRelMap);
/**
* 刷新树节点数据
*/
void refreshTreeNodeData();
/** 获取节点的子节点列表
* @param nodeId 节点Id
* @return 子节点列表
*/
List getSonNodeList(Integer nodeId);
}
|
package com.zhouyi.business.core.config;
import com.thoughtworks.xstream.converters.basic.ByteConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
/**
* @author 李秸康
* @ClassNmae: TestConfig
* @Description: TODO
* @date 2019/9/2 16:46
* @Version 1.0
**/
@Configuration
public class TestConfig {
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter(){
return new ByteArrayHttpMessageConverter();
}
}
|
package org.dmonix.xml;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* <p>
* Copyright: Copyright (c) 2003
* </p>
* <p>
* Company: dmonix.org
* </p>
*
* @author Peter Nerg
* @since 1.0
*/
public abstract class XMLPropertyHandler {
private static final Logger log = Logger.getLogger(XMLPropertyHandler.class.getName());
private static Document properties = null;
/**
* Get the value of a Boolean property.
*
* @param property
* The name of the property to get
* @param defaultValue
* The value to return if the method fails
* @return true if the property is true, default value otherwise
*/
public static boolean getBooleanProperty(String property, boolean defaultValue) {
String value = XMLPropertyHandler.getProperty(property, null);
if (value == null || value.length() < 4)
return defaultValue;
return Boolean.valueOf(value).booleanValue();
}
/**
* Get the value of a Boolean property.
*
* @param property
* The name of the property to get
* @return true if the property is true, false otherwise
*/
public static boolean getBooleanProperty(String property) {
return XMLPropertyHandler.getBooleanProperty(property, false);
}
/**
* Get the value of an property.
*
* @param property
* The name of the property to get
* @return The value of the property if found, null otherwise
*/
public static String getProperty(String property) {
return XMLPropertyHandler.getProperty(property, null);
}
/**
* Get the value of an property.
*
* @param property
* The name of the property to get
* @param defaultValue
* The value to return if the method fails
* @return The value of the property if found, default value otherwise
*/
public static String getProperty(String property, String defaultValue) {
if (properties == null)
return null;
return XMLUtil.getElementValue(properties.getElementsByTagName(property), defaultValue);
}
public static boolean parsePropertyFile(File file) {
try {
properties = XMLUtil.getDocument(file);
} catch (Exception ex) {
properties = XMLUtil.newDocument();
Element p = properties.createElement("properties");
properties.appendChild(p);
log.log(Level.CONFIG, "Could not read properties : " + ex.getMessage());
return false;
}
return true;
}
public static void savePropertyFile(File file) {
try {
XMLUtil.saveToFile(properties, file);
} catch (Exception ex) {
log.log(Level.SEVERE, "Could not save properties", ex);
}
}
/**
* Set a property value
*
* @param name
* The name of the property
* @param value
* The value of the property
* @param append
*/
public static void setProperty(String name, boolean value, boolean append) {
XMLPropertyHandler.setProperty(name, "" + value, append);
}
public static void setProperty(String name, int value, boolean append) {
XMLPropertyHandler.setProperty(name, "" + value, append);
}
public static void setProperty(String name, long value, boolean append) {
XMLPropertyHandler.setProperty(name, "" + value, append);
}
public static void setProperty(String name, String value, boolean append) {
if (append) {
XMLUtil.appendChildElement(properties, name, value);
return;
}
NodeList list = properties.getElementsByTagName(name);
if (list.getLength() < 1) {
XMLUtil.appendChildElement(properties, name, value);
return;
}
Element e = (Element) list.item(0);
if (!e.hasChildNodes()) {
e.appendChild(properties.createTextNode(value));
return;
}
e.getFirstChild().setNodeValue(value);
}
public static void setTransformerProperty(String name, String value) {
XMLUtil.setTransformerProperty(name, value);
}
} |
package thread;
public class Cat<T> {
public void add(T t){
System.out.println("ΜνΌΣ");
}
}
|
/*
* Copyright 2006 Ameer Antar.
*
* 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.antfarmer.ejce.hibernate;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.spec.AlgorithmParameterSpec;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;
import java.util.concurrent.locks.ReentrantLock;
import java.util.zip.Deflater;
import java.util.zip.DeflaterInputStream;
import java.util.zip.InflaterInputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import org.antfarmer.ejce.exception.EncryptorConfigurationException;
import org.antfarmer.ejce.parameter.AlgorithmParameters;
import org.antfarmer.ejce.stream.EncryptInputStream;
import org.antfarmer.ejce.util.ByteUtil;
import org.antfarmer.ejce.util.ConfigurerUtil;
import org.antfarmer.ejce.util.TextUtil;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
/**
* Abstract extension of <code>AbstractHibernateType</code> for LOB types that encrypts as well as compresses
* arbitrarily large binary data.
* @see AbstractHibernateType
* @author Ameer Antar
*/
public abstract class AbstractLobType extends AbstractHibernateType {
private static final int[] sqlTypes = {Types.BLOB};
private static final File TEMP_DIR = new File(System.getProperty("java.io.tmpdir"));
private static final String TEMP_FILE_PREFIX = "ejce_";
private boolean useCompression;
private boolean useStreams;
private int streamBuffSize = 4 * 1024;
private int maxInMemoryBuffSize = 512 * 1024;
private AlgorithmParameters<?> parameters;
private Cipher encCipher;
private Cipher decCipher;
private final ReentrantLock encLock = new ReentrantLock();
private final ReentrantLock decLock = new ReentrantLock();
/**
* {@inheritDoc}
*/
@Override
public int[] sqlTypes() {
return sqlTypes;
}
/**
* {@inheritDoc}
*/
@Override
protected void configure(final Properties parameters) {
String value;
setCharset(parameters);
// check if compression is enabled
value = parameters.getProperty(ConfigurerUtil.KEY_COMPRESS_LOB);
if (TextUtil.hasLength(value)) {
useCompression = value.trim().toLowerCase().equals("true");
}
Integer intVal;
// set streaming buffer size
value = parameters.getProperty(ConfigurerUtil.KEY_STREAM_BUFF_SIZE);
intVal = ConfigurerUtil.parseInt(value);
if (intVal != null && intVal > 1) {
streamBuffSize = intVal;
}
// set max in memory buffer size
value = parameters.getProperty(ConfigurerUtil.KEY_MAX_IN_MEM_BUFF_SIZE);
intVal = ConfigurerUtil.parseInt(value);
if (intVal != null && intVal > 1) {
maxInMemoryBuffSize = intVal;
}
// check if compression is enabled
value = parameters.getProperty(ConfigurerUtil.KEY_STREAM_LOBS);
if (TextUtil.hasLength(value)) {
useStreams = value.trim().toLowerCase().equals("true");
}
this.parameters = ConfigurerUtil.loadAlgorithmParameters(parameters, null);
}
@Override
protected void initializeIfNot() {
try {
encCipher = ConfigurerUtil.getCipherInstance(parameters);
decCipher = ConfigurerUtil.getCipherInstance(parameters);
}
catch (final GeneralSecurityException e) {
throw new EncryptorConfigurationException("Error initializing cipher for Hibernate Usertype.", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void nullSafeSet(final PreparedStatement st, final Object value, final int index, final SessionImplementor session)
throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, sqlTypes()[0]);
}
else {
final InputStream is = lobToStream(value);
encLock.lock();
try {
setStream(st, index, encryptStream(is));
}
catch (final GeneralSecurityException e) {
throw new HibernateException("Error encrypting object.", e);
}
catch (final IOException e) {
throw new HibernateException("Error encrypting object.", e);
}
finally {
encLock.unlock();
}
}
}
/**
* {@inheritDoc}
*/
@Override
public Object nullSafeGet(final ResultSet rs, final String[] names, final SessionImplementor session, final Object owner)
throws HibernateException, SQLException {
final InputStream is = rs.getBinaryStream(names[0]);
try {
if (rs.wasNull()) {
return null;
}
decLock.lock();
try {
return streamToLob(decryptStream(is), session);
}
finally {
decLock.unlock();
}
}
catch (final GeneralSecurityException e) {
throw new HibernateException("Error decrypting object.", e);
}
catch (final IOException e) {
throw new HibernateException("Error decrypting object.", e);
}
}
/**
* Encrypts the given <tt>InputStream</tt>.
* @param is the InputStream
* @return an encrypted InputStream
* @throws GeneralSecurityException GeneralSecurityException
* @throws IOException IOException
*/
protected InputStream encryptStream(final InputStream is) throws GeneralSecurityException, IOException {
final byte[] paramData = parameters.generateParameterSpecData();
final AlgorithmParameterSpec paramSpec = parameters.createParameterSpec(paramData);
encCipher.init(Cipher.ENCRYPT_MODE, parameters.getEncryptionKey(), paramSpec);
return useCompression
? new EncryptInputStream(new DeflaterInputStream(is, new Deflater(Deflater.BEST_COMPRESSION)), encCipher)
: new EncryptInputStream(is, encCipher);
}
/**
* Decrypts the given <tt>InputStream</tt>.
* @param is the InputStream
* @return a decrypted InputStream
* @throws GeneralSecurityException GeneralSecurityException
* @throws IOException IOException
*/
protected InputStream decryptStream(final InputStream is) throws GeneralSecurityException, IOException {
final int paramSize = parameters.getParameterSpecSize();
AlgorithmParameterSpec algorithmSpec = null;
if (paramSize > 0) {
final byte[] buff = new byte[paramSize];
if (is.read(buff) < paramSize) {
throw new GeneralSecurityException("Error loading parameter spec data.");
}
algorithmSpec = parameters.getParameterSpec(buff);
}
decCipher.init(Cipher.DECRYPT_MODE, parameters.getEncryptionKey(), algorithmSpec);
return useCompression ? new InflaterInputStream(new CipherInputStream(is, decCipher)) : new CipherInputStream(is, decCipher);
}
/**
* Sets the <tt>InputStream</tt> on the given <tt>PreparedStatement</tt>. If the given <tt>InputStream</tt> contains
* less data than the <tt>maxInMemoryBuffSize</tt> setting, the data will be set on the <tt>PreparedStatement</tt>
* using an in-memory byte array, unless the stream LOB's option is enabled. If maximum buffer size is exceeded,
* the stream will be set via a temporary file to determine its true length and limit memory usage.
* @param st the PreparedStatement
* @param index the parameter index
* @param is the InputStream
* @throws IOException IOException
* @throws SQLException SQLException
*/
protected void setStream(final PreparedStatement st, final int index, final InputStream is) throws IOException, SQLException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(streamBuffSize);
try {
int read;
int totalRead = 0;
final byte[] buff = new byte[streamBuffSize];
try {
while ((read = is.read(buff)) > -1) {
baos.write(buff, 0, read);
totalRead += read;
if (totalRead >= maxInMemoryBuffSize) {
break;
}
}
final byte[] bytes = baos.toByteArray();
if (totalRead < maxInMemoryBuffSize) {
if (useStreams) {
st.setBinaryStream(index, new ByteArrayInputStream(bytes), baos.size());
}
else {
st.setBytes(index, bytes);
}
}
else {
File file = createTempFile();
try {
final FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(bytes);
while ((read = is.read(buff)) > -1) {
fos.write(buff, 0, read);
}
fos.flush();
}
finally {
fos.close();
}
file = new File(file.getAbsolutePath());
st.setBinaryStream(index, new BufferedInputStream(new FileInputStream(file)), file.length());
}
finally {
file.delete();
}
}
}
finally {
ByteUtil.clear(buff);
}
}
finally {
is.close();
}
}
protected Object streamToLob(final InputStream is, final SessionImplementor session) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(streamBuffSize);
try {
int read;
int totalRead = 0;
final byte[] buff = new byte[streamBuffSize];
try {
while ((read = is.read(buff)) > -1) {
baos.write(buff, 0, read);
totalRead += read;
if (totalRead >= maxInMemoryBuffSize) {
break;
}
}
final byte[] bytes = baos.toByteArray();
if (totalRead < maxInMemoryBuffSize) {
return createLob(bytes, session);
}
else {
File file = createTempFile();
try {
final FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(bytes);
while ((read = is.read(buff)) > -1) {
fos.write(buff, 0, read);
}
fos.flush();
}
finally {
fos.close();
}
file = new File(file.getAbsolutePath());
return createLob(new BufferedInputStream(new FileInputStream(file)), file.length(), session);
}
finally {
file.delete();
}
}
}
finally {
ByteUtil.clear(buff);
}
}
finally {
is.close();
}
}
/**
* Returns a newly created temp file. The file will be deleted on normal termination of the VM.
* @return a newly created temp file
* @throws IOException IOException
*/
protected File createTempFile() throws IOException {
File file;
while (!(file = new File(TEMP_DIR, generateTempFileName())).createNewFile()) {
// loop
}
file.deleteOnExit();
return file;
}
/**
* Returns a temp file name based on the current time and a random number.
* @return a temp file name based on the current time and a random number
*/
protected String generateTempFileName() {
return TEMP_FILE_PREFIX + System.currentTimeMillis() + "-" + random.nextInt(100);
}
/**
* Converts the LOB value to an <tt>InputStream</tt>.
* @param value the LOB value
* @return the InputStream
* @throws SQLException an error converting the value to an InputStream
*/
protected abstract InputStream lobToStream(Object value) throws SQLException;
/**
* Converts the <tt>InputStream</tt> to a LOB.
* @param is the InputStream
* @param length the stream length
* @param session the {@link SessionImplementor}
* @return the LOB
* @throws IOException an error converting the stream to a LOB
*/
protected abstract Object createLob(InputStream is, long length, SessionImplementor session) throws IOException;
/**
* Converts the <tt>InputStream</tt> to a LOB.
* @param bytes the bytes
* @param session the {@link SessionImplementor}
* @return the LOB
* @throws IOException an error converting the stream to a LOB
*/
protected abstract Object createLob(byte[] bytes, SessionImplementor session) throws IOException;
/**
* {@inheritDoc}
*/
@Override
protected Object decrypt(final String value) throws GeneralSecurityException {
// not used
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected String encrypt(final Object value) throws GeneralSecurityException {
// not used
return null;
}
/**
* {@inheritDoc}
*/
@Override
public abstract Class<?> returnedClass();
/**
* Returns the useCompression.
* @return the useCompression
*/
protected boolean isUseCompression() {
return useCompression;
}
/**
* Returns the streamBuffSize.
* @return the streamBuffSize
*/
protected int getStreamBuffSize() {
return streamBuffSize;
}
/**
* Returns the maxInMemoryBuffSize.
* @return the maxInMemoryBuffSize
*/
protected int getMaxInMemoryBuffSize() {
return maxInMemoryBuffSize;
}
}
|
package id.voela.wifiku;
import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import java.io.IOException;
import java.net.InetAddress;
import static android.content.Context.WIFI_SERVICE;
/**
* Created by farhan on 1/26/18.
*/
public class WifiKu {
public static String getWifiSSID(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo.getSSID();
}
public static String getWifiBSSID(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo.getBSSID();
}
public static String getWifiMacAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo.getMacAddress();
}
public static int getWifiIPAdressPlain(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo.getIpAddress();
}
public static int getWifiRSSIPlain(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo.getRssi();
}
public static int getWifiRSSIStrength(Context context, int level) {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return WifiManager.calculateSignalLevel(wifiInfo.getRssi(), level);
}
@SuppressLint("DefaultLocale")
public static String getWifiIPAdressFormatted(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
return String.format(
"%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
}
public static boolean isNetworkConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo() != null;
}
public static boolean isInternetAvailable(String siteUrl) {
try {
if (siteUrl.isEmpty()) {
siteUrl = "google.com";
}
InetAddress ipAddr = InetAddress.getByName(siteUrl);
return !ipAddr.equals("");
} catch (Exception e) {
return false;
}
}
public static boolean isPingSuccess(String siteUrl) throws InterruptedException, IOException {
String command;
if (siteUrl.isEmpty()) {
command = "google.com -c 1 google.com";
} else {
command = "ping -c 1 " + siteUrl;
}
return (Runtime.getRuntime().exec(command).waitFor() == 0);
}
}
|
package com.demo2;
public class Method {
public static <U> void print(U[] list) {
System.out.println();
for (int i = 0; i < list.length; i++) {
System.out.print(" " + list[i]);
}
System.out.println();
}
public static void main(String[] args) {
String a[]={"a","b","c","d","e"};
Character b[]={'1','2','3','4','5'};
Integer c[]={1,2,3,4,5};
Method.print(a);
Method.print(b);
Method.print(c);
}
}
|
package cl.evilcorp.perritos2.domain.presenter;
import java.util.List;
import cl.evilcorp.perritos2.data.model.InterfaceModel;
import cl.evilcorp.perritos2.ui.presenter.IPresenterViewList;
public class PresenterList implements IPresenterList, IPresenterModel{
InterfaceModel interfaceModel;
IPresenterViewList iPresenterViewList;
public PresenterList(IPresenterViewList iPresenterViewList) {
this.iPresenterViewList = iPresenterViewList;
}
public void setInterfaceModel(InterfaceModel interfaceModel) {
this.interfaceModel = interfaceModel;
}
@Override
public void loadBreeds() {
interfaceModel.loadBreeds();
}
@Override
public void notificar(List<String> list) {
iPresenterViewList.showDogs(list);
}
}
|
package com.home.test;
public enum Permission {
READ(1), WRITE(2);
private int value;
Permission(int value) {
this.value = value;
}
public static String getPermissionValue(int value){
for(Permission permission : Permission.values()){
if(permission.value == value){
return permission.name();
}
}
return null;
}
}
|
package com.spring.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.spring.domain.ApprovedScoreCard;
import com.spring.domain.DealerLenderCustomerCreationFile;
import com.spring.domain.Transaction_Archive;
import com.spring.domain.User;
import com.spring.service.IIFLLenderService;
import com.spring.service.PrincipalUpdateService;
import com.spring.service.RBLLenderService;
import com.spring.service.SMEDocumentService;
import com.spring.service.TransactionProcessService;
import com.spring.service.UserService;
import com.spring.util.EmailerService;
import com.spring.util.IIFLLenderFetchFileServiceUtils;
import com.spring.util.IIFLLenderFileServiceUtils;
import com.spring.util.LenderFileServiceUtils;
import com.spring.util.Utils;
@Controller
public final class IIFLLenderController {
private static Logger logger = Logger.getLogger(IIFLLenderController.class);
@Autowired
SMEDocumentService smeDocumentService;
@Autowired
UserService userService;
@Autowired
PrincipalUpdateService principalUpdateService;
@Autowired
TransactionProcessService transactionProcessService;
@Autowired
EmailerService emailerService;
@Autowired
IIFLLenderService iiflLenderService;
@Autowired
RBLLenderService rblLenderService;
/*
@Autowired
ChequeInventoryService chequeInventoryService;
@Autowired
EmailerService emailerService;
@Autowired
SellerIntegrationService sellerIntegrationService;
@Autowired
private ZipcodeService zipcodeService;
@Autowired
private ConfigurationService configurationService;
@Autowired
LenderIntegrationService lenderIntegrationService;
@Autowired
ReportService reportService;*/
@Value("${sampleInvoiceLocationFilePath}")
private String sampleInvoiceLocationFilePath;
@Value("${fetchLCCFFileinFolder}")
private String fetchLCCFFileinFolder;
@Value("${fetchLPRFFileinFolder}")
private String fetchLPRFFileinFolder;
@Value("${fetchLCCFFileinFolderProcessed}")
private String fetchLCCFFileinFolderProcessed;
@Value("${fetchLPRFFileinFolderProcessed}")
private String fetchLPRFFileinFolderProcessed;
@Value("${uploadLPCFFileinFolder}")
private String uploadLPCFFileinFolder;
@Value("${uploadLPCFFileinFolderProcessed}")
private String uploadLPCFFileinFolderProcessed;
@Value("${uploadLLAFFileinFolder}")
private String uploadLLAFFileinFolder;
@Value("${uploadLLAFFileinFolderProcessed}")
private String uploadLLAFFileinFolderProcessed;
@Value("${uploadLBRFFileinFolder}")
private String uploadLBRFFileinFolder;
@Value("${uploadLBRFFileinFolderProcessed}")
private String uploadLBRFFileinFolderProcessed;
@Value("${dealerAccountFilePath}")
private String dealerAccountFilePath;
@Value("${uploadDCAFileinFolder}")
private String uploadDCAFileinFolder;
@Value("${uploadDCAFileinFolderProcessed}")
private String uploadDCAFileinFolderProcessed;
@Value("${uploadDTFFileinFolder}")
private String uploadDTFFileinFolder;
@Value("${uploadDTFFileinFolderProcessed}")
private String uploadDTFFileinFolderProcessed;
@Value("${fetchDPFFileinFolder}")
private String fetchDPFFileinFolder;
@Value("${fetchDRPFFileinFolder}")
private String fetchDRPFFileinFolder;
@Value("${fetchDRPFFFileinFolder}")
private String fetchDRPFFFileinFolder;
@Value("${fetchDRPDFFileinFolder}")
private String fetchDRPDFFileinFolder;
@Value("${fetchDPFFileinFolderProcessed}")
private String fetchDPFFileinFolderProcessed;
@Value("${fetchDRPFFileinFolderProcessed}")
private String fetchDRPFFileinFolderProcessed;
@Value("${fetchDRPFFFileinFolderProcessed}")
private String fetchDRPFFFileinFolderProcessed;
@Value("${fetchDRPDFFileinFolderProcessed}")
private String fetchDRPDFFileinFolderProcessed;
@Value("${generateCIBILKey}")
private String generateCIBILKey;
@Value("${need_to_access_cibil_live}")
private String need_to_access_cibil_live;
@Value("${IP_ADDRESS}")
private String IP_ADDRESS;
@Value("${PORT}")
private String PORT;
@Value("${cibiluser}")
private String cibiluser;
@Value("${cibilpass}")
private String cibilpass;
/**
* @param model
* @param session
* @param request
* @param fetchCFFFileinFolder
* @return
*/
@RequestMapping(value = "/fetchByLenderCustomerCreationFile", method = RequestMethod.GET)
public String fetchByLenderCustomerCreationFile(ModelMap model , HttpSession session,HttpServletRequest request, String fetchCFFFileinFolder) {
User userdetails=(User)session.getAttribute("userdetails");
Integer lenderID=userdetails.getUsercode();
String current_date=Utils.getCurrentDateInDDMMYYYY2();
String lender_name=userdetails.getCompanyname();
// String fileName = "Innoviti_SME_to_lender_Customer_Creation_File_XXXXXX_DDMMYYYY.xls";
String fileName1 = "Innoviti_SME_to_lender_Customer_Creation_File_"+lenderID+"_"+current_date+".xls";
model.put("processedFile",fileName1);
if(null !=session.getAttribute("redmesg") )
{ logger.info(session.getAttribute("redmesg"));
model.put("mesg", session.getAttribute("redmesg"));
session.removeAttribute("redmesg");
}
if( null !=session.getAttribute("rederror")){
logger.info(session.getAttribute("rederror"));
model.put("error", session.getAttribute("rederror"));
session.removeAttribute("rederror");
}
if( null !=session.getAttribute("processedFile")){
logger.info(session.getAttribute("processedFile"));
model.put("processedFile", session.getAttribute("processedFile"));
session.removeAttribute("processedFile");
}
if( null !=session.getAttribute("warning")){
logger.info(session.getAttribute("warning"));
model.put("warning", session.getAttribute("warning"));
session.removeAttribute("warning");
}
//for temporary
try{
File folderCreatedbefore=new File(fetchLCCFFileinFolder);
File folderCreate=new File(fetchLCCFFileinFolderProcessed);
if(!folderCreatedbefore.exists())
{
if(folderCreatedbefore.mkdirs())
{
logger.info("Folder structure created for :: "+fetchLCCFFileinFolder);
}
}
if(!folderCreate.exists())
{
if(folderCreate.mkdirs())
{
logger.info("Folder structure created for :: "+fetchLCCFFileinFolderProcessed);
}
}
else{
logger.info("Folder structure already exist");
//should generate file from transaction_archive where lender_name = login name
//and repayment_status=0 and batch_run_date= today
File f=new File (fetchLCCFFileinFolderProcessed,fileName1);
if(!f.exists())
{
logger.info("File does not exist...");
//Need to find dealer approved by IIFL for current date
List<ApprovedScoreCard> approvedDealerUsers= iiflLenderService.findDealerforLenderCustomerCreationFiles(lenderID);
logger.info("dealer approved for LCCF :: "+approvedDealerUsers);
logger.info("Lender Name for LCCF :: "+lender_name);
// List<String> pendingDealersDetails=new ArrayList<String>();
if(approvedDealerUsers!=null)
{
logger.info("count of approvedDealerUsers :: "+approvedDealerUsers.size());
List<DealerLenderCustomerCreationFile> list=iiflLenderService.saveDealerLenderCustomerCreationFiles(userService,approvedDealerUsers, lenderID);
if(list!=null && !list.isEmpty())
{
logger.info("count of LCCFs :: "+list.size());
//List<DealerLenderCustomerCreationFile> list =iiflLenderService.getDealerLenderCustomerCreationFiles(approvedDealerUsers,lender_name);
IIFLLenderFetchFileServiceUtils.createDealerPaymentTransactionXLSSheet(list, fetchLCCFFileinFolderProcessed, fileName1);
}
}
}
else
{
logger.info("File already exist...");
}
File folder = new File(fetchLCCFFileinFolderProcessed);
File[] listOfFiles = folder.listFiles();
System.out.println("+++++++++++++++++++++++++==");
Set<String> lccffileset=new TreeSet<>(new FetchLCCFComparator());
for (File file : listOfFiles) {
if (file.isFile()) {
lccffileset.add(file.getName());
String strfileDate=file.getName().split("_")[8].substring(0,8);
Date filedate=getStringDateInDDMMYYYYIntoDate(strfileDate);
logger.info("Files for LCCF :: "+file.getName() +" Date : "+ filedate);
}
}
logger.info("saving file in fetchLCCFFileinFolderProcessed folder :"+fetchLCCFFileinFolderProcessed);
//copyFileUsingStream(finalFile,dest);
List<String> lccffilelist=new ArrayList<>(lccffileset);
//session.setAttribute("processedFile",fileName1);
model.put("lccffilelist",lccffilelist);
}
}
catch(Exception e)
{
logger.info(e);
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
}
return "fetchByLenderCustomerCreationFileIndex";
}
@RequestMapping(value = "/uploadByLenderLoanApprovalFile", method = RequestMethod.GET)
public String uploadByLenderLoanApprovalFile(ModelMap model , HttpSession session) {
if(null !=session.getAttribute("redmesg") )
{ logger.info(session.getAttribute("redmesg"));
model.put("mesg", session.getAttribute("redmesg"));
session.removeAttribute("redmesg");
}
if( null !=session.getAttribute("rederror")){
logger.info(session.getAttribute("rederror"));
model.put("error", session.getAttribute("rederror"));
session.removeAttribute("rederror");
}
if( null !=session.getAttribute("processedFile")){
logger.info(session.getAttribute("processedFile"));
model.put("processedFile", session.getAttribute("processedFile"));
session.removeAttribute("processedFile");
}
if( null !=session.getAttribute("warning")){
logger.info(session.getAttribute("warning"));
model.put("warning", session.getAttribute("warning"));
session.removeAttribute("warning");
}
try{
File folderCreatedbefore=new File(uploadLLAFFileinFolder);
File folderCreate=new File(uploadLLAFFileinFolderProcessed);
if(!folderCreatedbefore.exists())
{
if(folderCreatedbefore.mkdirs())
{
logger.info("Folder structure created for :: "+uploadLLAFFileinFolder);
}
}
if(!folderCreate.exists())
{
if(folderCreate.mkdirs())
{
logger.info("Folder structure created for :: "+uploadLLAFFileinFolderProcessed);
}
}
else{
logger.info("Folder structure already exist");
}
}
catch(Exception e)
{
logger.info(e);
}
File folder = new File(uploadLLAFFileinFolderProcessed);
File[] listOfFiles = folder.listFiles();
Set<String> llaffileset=new TreeSet<>(new UploadLLAFComparator());
for (File file : listOfFiles) {
if (file.isFile()) {
llaffileset.add(file.getName());
logger.info("Files for LLAF :: "+file.getName());
}
}
List<String> llaffilelist=new ArrayList<>(llaffileset);
model.put("llaffilelist",llaffilelist);
return "uploadByLenderLoanApprovalFileIndex";
}
@RequestMapping(value = "/doUploadLenderLoanApprovalFile", method = RequestMethod.POST)
public String doUploadLenderLoanApprovalFile(HttpServletRequest request, ModelMap model, Map<String, Object> map, HttpSession session) {
String fileName = "";
logger.info("inside doUploadLenderLoanApprovalFile()");
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
User userdetails=(User)session.getAttribute("userdetails");
logger.info("lender code :::"+userdetails.getUsercode());
String userId =String.valueOf( userdetails.getUsercode());
try {
File folderCreate=new File(uploadLLAFFileinFolder);
if(!folderCreate.exists())
{
if(folderCreate.mkdirs())
{
logger.info("Folder structure created"+uploadLLAFFileinFolder);
}
}
else{
logger.info("Folder structure already exist");
}
MultipartFile file = multipartRequest.getFile("LLAfile");
File finalFile= multipartToFile(file);
fileName = file.getOriginalFilename();
String [] fileNameArr = fileName.split("_");
if (fileNameArr.length==9) {
String lenderId = fileNameArr[7];
String date = fileName.substring(fileName.lastIndexOf("_")+1,fileName.lastIndexOf("."));
if (!lenderId.equals(userId)) {
session.setAttribute("rederror", "Lender code is invalid.");
return "redirect:uploadByLenderLoanApprovalFile";
}
else if(date.length()==8&&Utils.isThisDateValid(date, "ddMMyyyy") ){
File dest = new File(uploadLLAFFileinFolder,fileName);
logger.info("saving file in upload folder :"+uploadLLAFFileinFolder);
copyFileUsingStream(finalFile,dest);
//file.transferTo(dest);
String message = IIFLLenderFileServiceUtils.updateLLAFiledata( uploadLLAFFileinFolderProcessed,
uploadLBRFFileinFolderProcessed,transactionProcessService,Integer.valueOf(lenderId),date,finalFile,iiflLenderService,userService);
if(null!=message){
if (message.equalsIgnoreCase("Invalid file format. Check your header names")) {
session.setAttribute("rederror", "Invalid file format. Check your header names");
return "redirect:uploadByLenderLoanApprovalFile";
} else if(message.equalsIgnoreCase("Excel sheet name is wrong, sheet name should be LLAF. Please change name and try again")) {
session.setAttribute("rederror", "Invalid sheet name, sheet name should be LLAF");
return "redirect:uploadByLenderLoanApprovalFile";
} }
}
else{
session.setAttribute("rederror", "invalid date format");
return "redirect:uploadByLenderLoanApprovalFile";
}
} else {
session.setAttribute("rederror", "invalid file name file name sould be Innoviti_SME_from_lender_Loan_Approval_File_XXXXXX_DDMMYYYY.xls/xlsx");
return "redirect:uploadByLenderLoanApprovalFile";
}
} catch (Exception e) {
e.printStackTrace();
}
session.setAttribute("processedFile",fileName);
if (IIFLLenderFileServiceUtils.errorsInLLAF==0) {
session.setAttribute("redmesg","LLAF file has been processed. Please download the result file.");
}
else if(IIFLLenderFileServiceUtils.SuccessInLLAF!=0) {
session.setAttribute("warning","LLAF file has been processed. "+IIFLLenderFileServiceUtils.SuccessInLLAF+" records processed successfully and "+IIFLLenderFileServiceUtils.errorsInLLAF+" records failed" );
}
else
session.setAttribute("rederror","LLAF file has been processed. "+IIFLLenderFileServiceUtils.errorsInLLAF+" records failed" );
return "redirect:uploadByLenderLoanApprovalFile";
}
@RequestMapping(value = "/uploadByLenderPaymentConfirmationFile", method = RequestMethod.GET)
public String uploadByLenderPaymentConfirmationFile(ModelMap model , HttpSession session) {
if(null !=session.getAttribute("redmesg") )
{ logger.info(session.getAttribute("redmesg"));
model.put("mesg", session.getAttribute("redmesg"));
session.removeAttribute("redmesg");
}
if( null !=session.getAttribute("rederror")){
logger.info(session.getAttribute("rederror"));
model.put("error", session.getAttribute("rederror"));
session.removeAttribute("rederror");
}
if( null !=session.getAttribute("processedFile")){
logger.info(session.getAttribute("processedFile"));
model.put("processedFile", session.getAttribute("processedFile"));
session.removeAttribute("processedFile");
}
if( null !=session.getAttribute("warning")){
logger.info(session.getAttribute("warning"));
model.put("warning", session.getAttribute("warning"));
session.removeAttribute("warning");
}
try{
File folderCreatedbefore=new File(uploadLPCFFileinFolder);
File folderCreate=new File(uploadLPCFFileinFolderProcessed);
if(!folderCreatedbefore.exists())
{
if(folderCreatedbefore.mkdirs())
{
logger.info("Folder structure created for :: "+uploadLPCFFileinFolder);
}
}
if(!folderCreate.exists())
{
if(folderCreate.mkdirs())
{
logger.info("Folder structure created for :: "+uploadLPCFFileinFolderProcessed);
}
}
else{
logger.info("Folder structure already exist");
}
}
catch(Exception e)
{
logger.info(e);
}
File folder = new File(uploadLPCFFileinFolderProcessed);
File[] listOfFiles = folder.listFiles();
Set<String> lpcffileset=new TreeSet<>(new UploadLPCFComparator());
for (File file : listOfFiles) {
if (file.isFile()) {
lpcffileset.add(file.getName());
logger.info("Files for LPCF :: "+file.getName());
}
}
List<String> lpcffilelist=new ArrayList<>(lpcffileset);
model.put("lpcffilelist",lpcffilelist);
return "uploadByLenderPaymentConfirmationFileIndex";
}
@RequestMapping(value = "/uploadByLenderBucketReportFile", method = RequestMethod.GET)
public String uploadByLenderBucketReportFile(ModelMap model , HttpSession session) {
if(null !=session.getAttribute("redmesg") )
{ logger.info(session.getAttribute("redmesg"));
model.put("mesg", session.getAttribute("redmesg"));
session.removeAttribute("redmesg");
}
if( null !=session.getAttribute("rederror")){
logger.info(session.getAttribute("rederror"));
model.put("error", session.getAttribute("rederror"));
session.removeAttribute("rederror");
}
if( null !=session.getAttribute("processedFile")){
logger.info(session.getAttribute("processedFile"));
model.put("processedFile", session.getAttribute("processedFile"));
session.removeAttribute("processedFile");
}
if( null !=session.getAttribute("warning")){
logger.info(session.getAttribute("warning"));
model.put("warning", session.getAttribute("warning"));
session.removeAttribute("warning");
}
try{
File folderCreatedbefore=new File(uploadLBRFFileinFolder);
File folderCreate=new File(uploadLBRFFileinFolderProcessed);
if(!folderCreatedbefore.exists())
{
if(folderCreatedbefore.mkdirs())
{
logger.info("Folder structure created for :: "+uploadLBRFFileinFolder);
}
}
if(!folderCreate.exists())
{
if(folderCreate.mkdirs())
{
logger.info("Folder structure created for :: "+uploadLBRFFileinFolderProcessed);
}
}
else{
logger.info("Folder structure already exist");
}
}
catch(Exception e)
{
logger.info(e);
}
File folder = new File(uploadLBRFFileinFolderProcessed);
File[] listOfFiles = folder.listFiles();
Set<String> lbrffileset=new TreeSet<>(new UploadLBRFComparator());
for (File file : listOfFiles) {
if (file.isFile()) {
lbrffileset.add(file.getName());
logger.info("Files for LBRF :: "+file.getName());
}
}
List<String> lbrffilelist=new ArrayList<>(lbrffileset);
model.put("lbrffilelist",lbrffilelist);
return "uploadByLenderBucketReportFileIndex";
}
@RequestMapping(value = "/fetchByLenderPaymentRequestFile", method = RequestMethod.GET)
public String fetchByLenderPaymentRequestFile(ModelMap model , HttpSession session,HttpServletRequest request) {
User userdetails=(User)session.getAttribute("userdetails");
String lenderID=String.valueOf(userdetails.getUsercode());
String current_date=Utils.getCurrentDateInDDMMYYYY2();
String fileName = "Innoviti_SME_to_lender_Payment_Request_File_XXXXXX_DDMMYYYY.xls";
String fileName1 = "Innoviti_SME_to_lender_Payment_Request_File_"+lenderID+"_"+current_date+".xls";
model.put("processedFile",fileName1);
if(null !=session.getAttribute("redmesg") )
{ logger.info(session.getAttribute("redmesg"));
model.put("mesg", session.getAttribute("redmesg"));
session.removeAttribute("redmesg");
}
if( null !=session.getAttribute("rederror")){
logger.info(session.getAttribute("rederror"));
model.put("error", session.getAttribute("rederror"));
session.removeAttribute("rederror");
}
if( null !=session.getAttribute("processedFile")){
logger.info(session.getAttribute("processedFile"));
model.put("processedFile", session.getAttribute("processedFile"));
session.removeAttribute("processedFile");
}
if( null !=session.getAttribute("warning")){
logger.info(session.getAttribute("warning"));
model.put("warning", session.getAttribute("warning"));
session.removeAttribute("warning");
}
//for temporary
try{
File folderCreatedbefore=new File(fetchLPRFFileinFolder);
File folderCreate=new File(fetchLPRFFileinFolderProcessed);
if(!folderCreatedbefore.exists())
{
if(folderCreatedbefore.mkdirs())
{
logger.info("Folder structure created for :: "+fetchLPRFFileinFolder);
}
}
if(!folderCreate.exists())
{
if(folderCreate.mkdirs())
{
logger.info("Folder structure created for :: "+fetchLPRFFileinFolderProcessed);
}
}
else{
logger.info("Folder structure already exist");
//should generate file from transaction_archive where lender_name = login name
//and repayment_status=0 and batch_run_date= today
File f=new File (fetchLPRFFileinFolderProcessed,fileName1);
if(!f.exists())
{
logger.info("File does not exist...");
List<Transaction_Archive> list =userService.getAllPaymentTransactions(userdetails.getCompanyname());
IIFLLenderFetchFileServiceUtils.createDealerPaymentTransactionXLSSheet(userService,rblLenderService ,list, fetchLPRFFileinFolderProcessed, fileName1);
}
else
{
logger.info("File already exist...");
}
File folder = new File(fetchLPRFFileinFolderProcessed);
File[] listOfFiles = folder.listFiles();
Set<String> lprffileset=new TreeSet<>(new FetchLPRFComparator());
for (File file : listOfFiles) {
if (file.isFile()) {
lprffileset.add(file.getName());
String strfileDate=file.getName().split("_")[8].substring(0,8);
Date filedate=getStringDateInDDMMYYYYIntoDate(strfileDate);
logger.info("Files for DPF :: "+file.getName() +" Date : "+ filedate);
}
}
logger.info("saving file in fetchLPRFFileinFolderProcessed folder :"+fetchLPRFFileinFolderProcessed);
//copyFileUsingStream(finalFile,dest);
List<String> lprffilelist=new ArrayList<>(lprffileset);
//session.setAttribute("processedFile",fileName1);
model.put("lprffilelist",lprffilelist);
}
}
catch(Exception e)
{
logger.info(e);
}
return "fetchByLenderPaymentRequestFileIndex";
}
public static Date getStringDateInDDMMYYYYIntoDate(String givenDate)
{
String pattern = "ddMMyyyy";
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
Date date=null;
try{
date = formatter.parse(givenDate);
//logger.info(date);
}
catch(Exception e){logger.info(e);}
return date;
}
class UploadLPCFComparator implements Comparator
{
@Override
public int compare(Object o1,Object o2) {
String strfileDate1=((String)o1).split("_")[8].substring(0,8);
Date filedate1=getStringDateInDDMMYYYYIntoDate(strfileDate1);
String strfileDate2=((String)o2).split("_")[8].substring(0,8);
Date filedate2=getStringDateInDDMMYYYYIntoDate(strfileDate2);
return compare(filedate1,filedate2);
}
public int compare(Date o1,Date o2) {
if (o1.compareTo(o2) == 0) {
return 0;
} else if (o1.compareTo(o2) > 0) {
return -1;
} else {
return 1;
}
}
}
class UploadLBRFComparator implements Comparator
{
@Override
public int compare(Object o1,Object o2) {
String strfileDate1=((String)o1).split("_")[8].substring(0,8);
Date filedate1=getStringDateInDDMMYYYYIntoDate(strfileDate1);
String strfileDate2=((String)o2).split("_")[8].substring(0,8);
Date filedate2=getStringDateInDDMMYYYYIntoDate(strfileDate2);
return compare(filedate1,filedate2);
}
public int compare(Date o1,Date o2) {
if (o1.compareTo(o2) == 0) {
return 0;
} else if (o1.compareTo(o2) > 0) {
return -1;
} else {
return 1;
}
}
}
class UploadLLAFComparator implements Comparator
{
@Override
public int compare(Object o1,Object o2) {
String strfileDate1=((String)o1).split("_")[8].substring(0,8);
Date filedate1=getStringDateInDDMMYYYYIntoDate(strfileDate1);
String strfileDate2=((String)o2).split("_")[8].substring(0,8);
Date filedate2=getStringDateInDDMMYYYYIntoDate(strfileDate2);
return compare(filedate1,filedate2);
}
public int compare(Date o1,Date o2) {
if (o1.compareTo(o2) == 0) {
return 0;
} else if (o1.compareTo(o2) > 0) {
return -1;
} else {
return 1;
}
}
}
class FetchLCCFComparator implements Comparator
{
@Override
public int compare(Object o1,Object o2) {
String strfileDate1=((String)o1).split("_")[8].substring(0,8);
Date filedate1=getStringDateInDDMMYYYYIntoDate(strfileDate1);
String strfileDate2=((String)o2).split("_")[8].substring(0,8);
Date filedate2=getStringDateInDDMMYYYYIntoDate(strfileDate2);
return compare(filedate1,filedate2);
}
public int compare(Date o1,Date o2) {
if (o1.compareTo(o2) == 0) {
return 0;
} else if (o1.compareTo(o2) > 0) {
return -1;
} else {
return 1;
}
}
}
class FetchLPRFComparator implements Comparator
{
@Override
public int compare(Object o1,Object o2) {
String strfileDate1=((String)o1).split("_")[8].substring(0,8);
Date filedate1=getStringDateInDDMMYYYYIntoDate(strfileDate1);
String strfileDate2=((String)o2).split("_")[8].substring(0,8);
Date filedate2=getStringDateInDDMMYYYYIntoDate(strfileDate2);
return compare(filedate1,filedate2);
}
public int compare(Date o1,Date o2) {
if (o1.compareTo(o2) == 0) {
return 0;
} else if (o1.compareTo(o2) > 0) {
return -1;
} else {
return 1;
}
}
}
@RequestMapping(value = "/fetchIIFLResultFile/{fileName}/{returnPage}", method = RequestMethod.GET)
public String fetchResultFile(ModelMap model,@PathVariable("fileName") String fileName, @PathVariable("returnPage") String returnPage, Map<String, Object> map, HttpSession session,HttpServletResponse response) throws Exception {
logger.info("Accessed downloadBusinessTypeDocuments.");
String retval = "";
String folderLocation ="";
User userDetails = (User) session.getAttribute("userdetails");
String lenderName = userDetails.getCompanyname();
//for account and transaction file from lender
if(returnPage.equals("fetchByLenderPaymentRequestFile")){
retval = "fetchByLenderPaymentRequestFile";
folderLocation = fetchLPRFFileinFolderProcessed;
} else if(returnPage.equals("uploadByLenderLoanApprovalFile")){
retval = "uploadByLenderLoanApprovalFile";
folderLocation = uploadLLAFFileinFolderProcessed;
} else if(returnPage.equals("uploadByLenderBucketReportFile")){
retval = "uploadByLenderBucketReportFile";
folderLocation = uploadLBRFFileinFolderProcessed;
}
//for payment and repayment from innoviti
else if(returnPage.equals("fetchByLenderCustomerCreationFile")){
retval = "fetchByLenderCustomerCreationFile";
folderLocation = fetchLCCFFileinFolderProcessed;
}
else if(returnPage.equals("uploadByLenderPaymentConfirmationFile")){
retval = "uploadByLenderPaymentConfirmationFile";
folderLocation = uploadLPCFFileinFolderProcessed;
}
byte b[]=null;
try
{
File file=new File(folderLocation,fileName);
logger.info(file.getCanonicalPath());
FileInputStream fin=new FileInputStream(file.getCanonicalPath());
b=new byte[fin.available()];
fin.read(b);//smeBusinessTypeDocument2.getFile1_idproof();
fin.close();
response.setContentLength(b.length);
response.setHeader("Content-Disposition","attachment; filename=\"" + fileName +"\"");
FileCopyUtils.copy(b, response.getOutputStream());
response.flushBuffer();
model.addAttribute("mesg", fileName+", File downloaded successfully");
logger.info(fileName+", File downloaded successfully");
}
catch(IOException e){
logger.error("Request could not be completed at this moment. Please try again."+e.toString());
e.printStackTrace();
map.put("error","Request could not be completed at this moment. Please try again."+e.toString());
}
catch(Exception e){
logger.error("Request could not be completed at this moment. Please try again."+e.toString());
e.printStackTrace();
map.put("error","Request could not be completed at this moment. Please try again."+e.toString());
}
// logger.info("File created successfully " +fileToDownload.getName());
return "redirect:"+retval;
}
@RequestMapping(value = "/doUploadLenderBucketRepostFile", method = RequestMethod.POST)
public String doUploadLenderBucketRepostFile(HttpServletRequest request, ModelMap model, Map<String, Object> map, HttpSession session) {
String fileName = "";
logger.info("inside doUploadLenderBucketRepostFile()");
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
User userdetails=(User)session.getAttribute("userdetails");
logger.info("lender code :::"+userdetails.getUsercode());
String userId =String.valueOf( userdetails.getUsercode());
try {
File folderCreate=new File(uploadLBRFFileinFolder);
if(!folderCreate.exists())
{
if(folderCreate.mkdirs())
{
logger.info("Folder structure created"+uploadLBRFFileinFolder);
}
}
else{
logger.info("Folder structure already exist");
}
MultipartFile file = multipartRequest.getFile("LBRfile");
File finalFile= multipartToFile(file);
fileName = file.getOriginalFilename();
String [] fileNameArr = fileName.split("_");
if (fileNameArr.length==9) {
String lenderId = fileNameArr[7];
String date = fileName.substring(fileName.lastIndexOf("_")+1,fileName.lastIndexOf("."));
if (!lenderId.equals(userId)) {
session.setAttribute("rederror", "Lender code is invalid.");
return "redirect:uploadByLenderBucketReportFile";
}
else if(date.length()==8&&Utils.isThisDateValid(date, "ddMMyyyy") ){
File dest = new File(uploadLBRFFileinFolder,fileName);
logger.info("saving file in upload folder :"+uploadLBRFFileinFolder);
copyFileUsingStream(finalFile,dest);
//file.transferTo(dest);
String message = IIFLLenderFileServiceUtils.updateLBRFiledata( uploadLLAFFileinFolderProcessed,
uploadLBRFFileinFolderProcessed,transactionProcessService,Integer.valueOf(lenderId),date,finalFile,iiflLenderService,userService);
if(null!=message){
if (message.equalsIgnoreCase("Invalid file format. Check your header names")) {
session.setAttribute("rederror", "Invalid file format. Check your header names");
return "redirect:uploadByLenderBucketReportFile";
} else if(message.equalsIgnoreCase("Excel sheet name is wrong, sheet name should be LBRF. Please change name and try again")) {
session.setAttribute("rederror", "Invalid sheet name, sheet name should be LBRF");
return "redirect:uploadByLenderBucketReportFile";
} }
}
else{
session.setAttribute("rederror", "invalid date format");
return "redirect:uploadByLenderBucketReportFile";
}
} else {
session.setAttribute("rederror", "invalid file name file name sould be Innoviti_SME_from_lender_Bucket_Report_File_XXXXXX_DDMMYYYY.xls/xlsx");
return "redirect:uploadByLenderBucketReportFile";
}
} catch (Exception e) {
e.printStackTrace();
}
session.setAttribute("processedFile",fileName);
if (IIFLLenderFileServiceUtils.errorsInLBRF==0) {
session.setAttribute("redmesg","LBRF file has been processed. Please download the result file.");
}
else if(IIFLLenderFileServiceUtils.SuccessInLLAF!=0) {
session.setAttribute("warning","LBRF file has been processed. "+IIFLLenderFileServiceUtils.SuccessInLBRF+" records processed successfully and "+IIFLLenderFileServiceUtils.errorsInLBRF+" records failed" );
}
else
session.setAttribute("rederror","LBRF file has been processed. "+IIFLLenderFileServiceUtils.errorsInLBRF+" records failed" );
return "redirect:uploadByLenderBucketReportFile";
}
public File multipartToFile(MultipartFile multipart) throws IllegalStateException, IOException
{
logger.info("converting multipartfile to java IO file");
File convFile = new File( multipart.getOriginalFilename());
multipart.transferTo(convFile);
return convFile;
}
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
@RequestMapping(value = "/doUploadPaymentConfirmationFile", method = RequestMethod.POST)
public String doUploadPaymentConfirmationFile(HttpServletRequest request, ModelMap model, Map<String, Object> map, HttpSession session) {
String fileName = "";
logger.info("inside doUploadPaymentConfirmationFile()");
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
User userdetails=(User)session.getAttribute("userdetails");
String userId =String.valueOf( userdetails.getUsercode());
try {
File folderCreate=new File(uploadLPCFFileinFolder);
if(!folderCreate.exists())
{
if(folderCreate.mkdirs())
{
logger.info("Folder structure created :: "+uploadLPCFFileinFolder);
}
}
else{
logger.info("Folder structure already exist");
}
MultipartFile file = multipartRequest.getFile("LPCfile");
if (file.isEmpty()) {
session.setAttribute("rederror", "File is empty please upload a valid file.");
return "redirect:uploadByLenderPaymentConfirmationFile";
}
File finalFile= multipartToFile(file);
fileName = file.getOriginalFilename();
String [] fileNameArr = fileName.split("_");
if (fileNameArr.length==9) {
String lenderId = fileNameArr[7];
String date = fileName.substring(fileName.lastIndexOf("_")+1,fileName.lastIndexOf("."));
if (!lenderId.equals(userId)) {
session.setAttribute("rederror", "Lender code is invalid.");
return "redirect:uploadByLenderPaymentConfirmationFile";
}
else if(date.length()==8&&Utils.isThisDateValid(date, "ddMMyyyy") ){
File dest = new File(uploadLPCFFileinFolder,fileName);
logger.info("saving LPCF file in upload folder :"+uploadLPCFFileinFolder);
copyFileUsingStream(finalFile,dest);
//file.transferTo(dest);
String message = IIFLLenderFileServiceUtils.updateLCFiledata( uploadDCAFileinFolderProcessed, uploadDTFFileinFolderProcessed,
fetchDPFFileinFolderProcessed, fetchDRPFFileinFolderProcessed,
fetchDRPFFFileinFolderProcessed, fetchDRPDFFileinFolderProcessed, uploadLPCFFileinFolderProcessed,transactionProcessService,Integer.valueOf(lenderId),date,finalFile,iiflLenderService,userService);
if(null!=message){
if (message.equalsIgnoreCase("Invalid file format. Check your header names")) {
session.setAttribute("rederror", "Invalid file format. Check your header names");
return "redirect:uploadByLenderPaymentConfirmationFile";
} else if(message.equalsIgnoreCase("Excel sheet name is wrong, sheet name should be LPCF. Please change name and try again")) {
session.setAttribute("rederror", "Invalid sheet name, sheet name should be LPCF");
return "redirect:uploadByLenderPaymentConfirmationFile";
} }
}
else{
session.setAttribute("rederror", "invalid date format");
return "redirect:uploadByLenderPaymentConfirmationFile";
}
} else {
session.setAttribute("rederror", "invalid file name file name sould be Innoviti_SME_from_lender_Payment_Confirmation_File_XXXXXX_DDMMYYY.xls/xlsx");
return "redirect:uploadByLenderPaymentConfirmationFile";
}
} catch (Exception e) {
e.printStackTrace();
}
session.setAttribute("processedFile",fileName);
if (IIFLLenderFileServiceUtils.errorsInPCF==0) {
session.setAttribute("redmesg","LPCF file has been processed. Please download the result file.");
}
else if(IIFLLenderFileServiceUtils.SuccessInPCF!=0) {
session.setAttribute("warning","LPCF file has been processed. "+IIFLLenderFileServiceUtils.SuccessInPCF+" records processed successfully and "+LenderFileServiceUtils.errorsInDRPF+" records failed" );
}
else
session.setAttribute("rederror","LPCF file has been processed. "+IIFLLenderFileServiceUtils.errorsInPCF+" records failed" );
return "redirect:uploadByLenderPaymentConfirmationFile";
}
}
|
package com.zlzkj.app.mapper.warehouse;
import com.zlzkj.app.model.warehouse.Area;
import com.zlzkj.core.sql.Row;
import java.util.List;
import java.util.Map;
public interface AreaMapper {
int deleteByPrimaryKey(String id);
int deleteByMap(Map<String, Object> map);
int insert(Area record);
Area selectByPrimaryKey(String id);
List<Row> selectByMap(Map<String, Object> map);
int countByMap(Map<String, Object> map);
int updateByPrimaryKey(Area record);
} |
package com.bingo.code.example.design.templatemethod.rewrite;
/**
* ������Ա��¼���Ƶ�������
*/
public class WorkerLogin extends LoginTemplate{
public LoginModel findLoginUser(String loginId) {
// ����ʡ�Ծ���Ĵ�������ʾ�⣬����һ����Ĭ�����ݵĶ���
LoginModel lm = new LoginModel();
lm.setLoginId(loginId);
lm.setPwd("workerpwd");
return lm;
}
public String encryptPwd(String pwd){
//���Ǹ���ķ������ṩ�����ļ���ʵ��
//�����������м��ܣ�����ʹ�ã�MD5��3DES�ȵȣ�ʡ����
System.out.println("ʹ��MD5�����������");
return pwd;
}
}
|
package gugutech.elseapp.dao;
import gugutech.elseapp.model.UserBlackListT;
import java.util.List;
public interface UserBlackListTMapper {
int deleteByPrimaryKey(Integer blackId);
int insert(UserBlackListT record);
UserBlackListT selectByPrimaryKey(Integer blackId);
List<UserBlackListT> selectAll();
int updateByPrimaryKey(UserBlackListT record);
} |
package org.sherzberg.guiceplayground;
import org.junit.Test;
public class SanityTest {
@Test
public void testSanity() {
assert 1 + 1 == 2;
}
}
|
package com.dennistjahyadigotama.soaya.activities.warta_ubaya_activity.adapter;
/**
* Created by Denn on 9/21/2016.
*/
public class WartaUbayaGetter {
String title,edisi,photoUrl;
int totalPage;
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getEdisi() {
return edisi;
}
public void setEdisi(String edisi) {
this.edisi = edisi;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
|
package com.tencent.mm.plugin.appbrand.page;
import a.a;
import android.animation.Animator;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.util.Base64;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient.CustomViewCallback;
import com.samsung.android.sdk.look.smartclip.SlookSmartClipMetaTag;
import com.tencent.mm.plugin.appbrand.appcache.WxaCommLibRuntimeReader;
import com.tencent.mm.plugin.appbrand.appcache.ao;
import com.tencent.mm.plugin.appbrand.appstorage.AppBrandLocalMediaObject;
import com.tencent.mm.plugin.appbrand.appstorage.AppBrandLocalMediaObjectManager;
import com.tencent.mm.plugin.appbrand.g;
import com.tencent.mm.plugin.appbrand.g.b;
import com.tencent.mm.plugin.appbrand.g.c;
import com.tencent.mm.plugin.appbrand.k.l;
import com.tencent.mm.plugin.appbrand.performance.AppBrandPerformanceManager;
import com.tencent.mm.plugin.appbrand.r.i;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.pluginsdk.ui.tools.s;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.widget.MMWebView;
import com.tencent.xweb.WebView;
import com.tencent.xweb.d;
import com.tencent.xweb.j;
import com.tencent.xweb.o;
import com.tencent.xweb.p;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedList;
import org.json.JSONObject;
public final class t extends MMWebView implements b {
String fCQ;
g fdO;
private LinkedList<Pair<String, ValueCallback<String>>> fsN;
boolean fwK;
private p fwL;
private o gcI;
private com.tencent.xweb.x5.a.a.a.a.b gcJ;
private c gnB;
long goA;
private long goB;
boolean goC;
private boolean goD;
boolean goE;
private String goF;
long goG;
private String goH;
private String goI;
private j goJ;
String gou;
private w gov;
private v gow;
l gox;
public Animator goy;
private long goz;
String mAppId;
public t(Context context) {
super(context);
this.fwK = false;
this.goC = false;
this.goD = false;
this.goE = true;
this.goH = null;
this.goI = null;
this.fwL = new 6(this);
this.goJ = new j() {
public final void onShowCustomView(View view, CustomViewCallback customViewCallback) {
try {
if (t.this.gnB != null) {
t.this.gnB.r(view, 90);
t.this.gnB.gmk = customViewCallback;
}
} catch (Exception e) {
x.e("MicroMsg.AppBrandWebView", "onShowCustomView error " + e.getMessage());
}
}
public final void onHideCustomView() {
try {
if (t.this.gnB != null) {
t.this.gnB.alE();
}
} catch (Exception e) {
x.e("MicroMsg.AppBrandWebView", "onHideCustomView error " + e.getMessage());
}
}
};
this.gcI = new 8(this);
this.gcJ = new com.tencent.xweb.x5.a.a.a.a.b() {
public final boolean onTouchEvent(MotionEvent motionEvent, View view) {
return t.this.gcI.z(motionEvent);
}
public final boolean onInterceptTouchEvent(MotionEvent motionEvent, View view) {
return t.this.gcI.B(motionEvent);
}
public final boolean dispatchTouchEvent(MotionEvent motionEvent, View view) {
return t.this.gcI.A(motionEvent);
}
public final boolean overScrollBy(int i, int i2, int i3, int i4, int i5, int i6, int i7, int i8, boolean z, View view) {
return t.this.gcI.b(i, i2, i3, i4, i5, i6, i7, i8, z);
}
public final void onScrollChanged(int i, int i2, int i3, int i4, View view) {
t.this.gcI.onScrollChanged(i, i2, i3, i4, view);
}
public final void onOverScrolled(int i, int i2, boolean z, boolean z2, View view) {
t.this.gcI.c(i, i2, z, z2);
}
public final void computeScroll(View view) {
t.this.gcI.akr();
}
public final boolean onShowLongClickPopupMenu() {
if (WebView.getUsingTbsCoreVersion(t.this.getContext()) >= 43011) {
return false;
}
return true;
}
public final Object onMiscCallBack(String str, Bundle bundle) {
if (bi.oW(str) || bundle == null) {
return null;
}
x.i("MicroMsg.AppBrandWebView", "method = %s", new Object[]{str});
if (!str.equalsIgnoreCase("shouldInterceptMediaUrl")) {
return null;
}
String string = bundle.getString(SlookSmartClipMetaTag.TAG_TYPE_URL);
if (bi.oW(string)) {
return null;
}
AppBrandLocalMediaObject itemByLocalId = AppBrandLocalMediaObjectManager.getItemByLocalId(t.this.mAppId, string);
if (itemByLocalId == null) {
x.e("MicroMsg.AppBrandWebView", "get meidiaobj failed, appid : %s, localid :%s", new Object[]{t.this.mAppId, string});
return null;
}
Object obj = itemByLocalId.dDG;
x.i("MicroMsg.AppBrandWebView", "filePath" + obj + "tempFilePath" + string);
return obj;
}
public final boolean shouldDiscardCurrentPage() {
boolean z;
boolean alT = t.this.gow.alT();
String str = "MicroMsg.AppBrandWebView";
String str2 = "shouldTrimCurrentPage: %b";
Object[] objArr = new Object[1];
if (!alT || t.this.goE) {
z = false;
} else {
z = true;
}
objArr[0] = Boolean.valueOf(z);
x.i(str, str2, objArr);
if (!alT || t.this.goE) {
return false;
}
return true;
}
public final void hasDiscardCurrentPage(boolean z) {
boolean z2;
boolean z3 = true;
t.this.goE = z;
t tVar = t.this;
if (z) {
z2 = false;
} else {
z2 = true;
}
tVar.fwK = z2;
t tVar2 = t.this;
if (z) {
z3 = false;
}
tVar2.goD = z3;
}
};
this.dfF = true;
this.isX5Kernel = getX5WebViewExtension() != null;
this.fsN = new LinkedList();
this.goz = System.currentTimeMillis();
he(getContext());
getSettings().cIv();
getSettings().setJavaScriptEnabled(true);
getSettings().setMediaPlaybackRequiresUserGesture(false);
getSettings().cIx();
getSettings().setUserAgentString(s.aV(getContext(), getSettings().getUserAgentString()));
this.goF = getSettings().getUserAgentString();
getView().setHorizontalScrollBarEnabled(false);
getView().setVerticalScrollBarEnabled(false);
setWebViewClient(this.fwL);
setWebChromeClient(this.goJ);
setWebViewCallbackClient(this.gcI);
if (getIsX5Kernel()) {
setWebViewClientExtension(this.gcJ);
try {
a.cJ(getX5WebViewExtension()).y("setEnableAutoPageDiscarding", Boolean.valueOf(false));
a.cJ(getX5WebViewExtension()).y("setEnableAutoPageRestoration", Boolean.valueOf(false));
} catch (Exception e) {
x.e("MicroMsg.AppBrandWebView", "DisableAutoPageDiscarding error " + e);
}
}
x.i("MicroMsg.AppBrandWebView", "Is the current broswer kernel X5, " + getIsX5Kernel());
setBackgroundColor(-1);
setLayoutParams(new LayoutParams(-1, -1));
setOnLongClickListener(new 1(this));
setDownloadListener(new 2(this));
}
public final void setIsPreload(boolean z) {
this.goC = z;
}
public final void init() {
x.i("MicroMsg.AppBrandWebView", "loadPageFrame with url(%s)", new Object[]{getBaseURL()});
loadUrl(getBaseURL());
}
public final String getPagePath() {
return this.fCQ;
}
public final String getPageURL() {
return this.gou;
}
public final void setWebViewTitle(String str) {
if (!bi.oW(str) && com.tencent.mm.sdk.a.b.chp()) {
evaluateJavascript("document.title=\"" + str + "\"", null);
}
}
public final void evaluateJavascript(String str, ValueCallback<String> valueCallback) {
if (this.fwK) {
3 3 = new 3(this, str, valueCallback);
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
3.run();
return;
} else {
ah.A(3);
return;
}
}
this.fsN.add(new Pair(str, valueCallback));
}
public final void a(URL url, String str, ValueCallback<String> valueCallback) {
evaluateJavascript(str, valueCallback);
}
public final void setJsExceptionHandler(d dVar) {
}
private void amc() {
Iterator it = this.fsN.iterator();
while (it.hasNext()) {
Pair pair = (Pair) it.next();
super.evaluateJavascript((String) pair.first, (ValueCallback) pair.second);
}
this.fsN.clear();
}
public final <T extends c> T y(Class<T> cls) {
return null;
}
public final String getUserAgentString() {
return this.goF;
}
public final void destroy() {
super.destroy();
if (this.goy != null) {
this.goy.cancel();
this.goy = null;
}
}
/* renamed from: amd */
final void d() {
JSONObject jSONObject = new JSONObject();
if (this.fdO != null) {
a(jSONObject, "appType", Integer.valueOf(this.fdO.fct.bGM));
} else if (this.goC) {
a(jSONObject, "preload", Boolean.valueOf(true));
}
a(jSONObject, "clientVersion", Integer.valueOf(com.tencent.mm.protocal.d.qVN));
if (this.fdO != null) {
jSONObject = this.fdO.fcy.aaK();
}
JSONObject jSONObject2 = new JSONObject();
a(jSONObject2, "width", Float.valueOf(((float) getResources().getDisplayMetrics().widthPixels) / getResources().getDisplayMetrics().density));
a(jSONObject2, "pixelRatio", Float.valueOf(getResources().getDisplayMetrics().density));
evaluateJavascript(String.format("var __wxConfig = %s;\nvar __deviceInfo__ = %s\n", new Object[]{jSONObject.toString(), jSONObject2.toString()}), null);
String str = "";
if (!this.goD) {
this.goD = true;
str = str + com.tencent.mm.plugin.appbrand.q.c.vM("wxa_library/android.js") + WxaCommLibRuntimeReader.qJ("WAWebview.js");
}
if (this.fdO != null) {
str = str + getVConsoleScript() + getPerformanceScript() + getRemoteDebugScript();
}
if (bi.oW(str)) {
x.v("MicroMsg.AppBrandWebView", "execInitScript, js null");
} else {
h.mEJ.a(370, 1, 1, false);
i.a(this, str, new 4(this));
}
if (this.fdO != null && this.mAppId != null) {
this.fdO.fcJ.o(3, this.goB - this.goz);
com.tencent.mm.plugin.appbrand.performance.a.a(this.mAppId, "Native", "WebViewInit+PageFrameLoad", this.goz, this.goB, "");
if (this.fCQ != null) {
x.i("MicroMsg.AppBrandWebView", "Inject page on frame load finished");
vc(this.fCQ);
}
amc();
}
}
private static void a(JSONObject jSONObject, String str, Object obj) {
try {
jSONObject.put(str, obj);
} catch (Exception e) {
x.e("MicroMsg.AppBrandWebView", e.getMessage());
}
}
private String getVConsoleScript() {
String str = "";
if (!this.fdO.fcu.fqL || this.fdO.aar()) {
return str;
}
return WxaCommLibRuntimeReader.qJ("WAVConsole.js");
}
private String getPerformanceScript() {
String str = "";
if (AppBrandPerformanceManager.vi(this.mAppId)) {
return WxaCommLibRuntimeReader.qJ("WAPerf.js");
}
return str;
}
private String getRemoteDebugScript() {
String str = "";
if (this.fdO.aar()) {
return ";" + WxaCommLibRuntimeReader.qJ("WARemoteDebug.js");
}
return str;
}
private String getBaseURLPrefix() {
if (this.goH == null) {
this.goH = "https://servicewechat.com/";
if (this.goC) {
this.goH += "preload/";
} else {
this.goH += this.mAppId + "/" + this.fdO.fcu.frm.fii + "/";
}
}
return this.goH;
}
private String getBaseURL() {
if (this.goI == null) {
this.goI = getBaseURLPrefix() + "page-frame.html";
}
return this.goI;
}
final void vc(String str) {
this.goA = System.currentTimeMillis();
String a = ao.a(this.fdO, str);
if (bi.oW(a)) {
x.e("MicroMsg.AppBrandWebView", "Cache content empty, abort inject");
return;
}
String str2;
String uB;
if (this.fdO.fcM.alp()) {
str2 = "" + ";" + ao.a(this.fdO, "/app-wxss.js");
uB = this.fdO.fcM.uB(this.fCQ);
uB = str2 + ";" + ao.a(this.fdO, uB + (uB.endsWith("/") ? "" : "/") + "page-frame.js");
} else {
uB = this.goC ? vd(ao.a(this.fdO, "/page-frame.html")) : "";
}
int indexOf = a.indexOf("<style>");
int indexOf2 = a.indexOf("</style>");
str2 = (indexOf == -1 || indexOf2 == (-indexOf)) ? "" : a.substring(indexOf + 7, indexOf2);
String encodeToString = Base64.encodeToString(str2.getBytes(), 2);
indexOf = a.indexOf("<page>");
int indexOf3 = a.indexOf("</page>");
str2 = (indexOf == -1 || indexOf3 == (-indexOf)) ? "" : a.substring(indexOf + 6, indexOf3);
str2 = Base64.encodeToString(str2.getBytes(), 2);
a = vd(a);
evaluateJavascript(String.format("var style = document.createElement('style');style.innerHTML = atob(\"%s\");document.head.appendChild(style);var page = document.createElement('page');page.innerHTML = atob(\"%s\");document.body.appendChild(page);%s;%s", new Object[]{encodeToString, str2, uB, a}), null);
}
private static String vd(String str) {
String str2 = "";
int i = 0;
while (true) {
int indexOf = str.indexOf("<script>", i);
int indexOf2 = str.indexOf("</script>", i);
if (indexOf == -1 || indexOf2 == -1 || indexOf2 <= indexOf) {
return str2;
}
str2 = str2 + (i > 0 ? ";" : "") + str.substring(indexOf + 8, indexOf2);
i = indexOf2 + 9;
}
return str2;
}
public final void setOnScrollChangedListener(w wVar) {
this.gov = wVar;
}
public final void setOnTrimListener(v vVar) {
this.gow = vVar;
}
public final void setFullscreenImpl(c cVar) {
this.gnB = cVar;
}
}
|
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LibraryUserTest {
Library library
LibraryUser libraryUser;
Book book;
@Before
public void before(){
library = new Library(4)
libraryUser = new LibraryUser();
book = new Book("Football: My Life, My Passion", "Graeme Souness", "autobiography");
}
@Test
public void canAddToCollection(){
libraryUser.addBook(book);
assertEquals(1,libraryUser.collectionSize());
}
@Test
public void canAddToCollectionFromLibrary(){
libraryUser.collectFromLibrary(library);
assertEquals(1,libraryUser.collectionSize());
assertEquals(0, library.bookCount());
}
}
|
package org.hpe.df.database;
import org.ojai.Document;
import java.io.Closeable;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.ojai.store.Connection;
import org.ojai.store.DocumentStore;
import org.ojai.store.DriverManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DocLoader<V> implements Closeable {
private static final Logger logger = LoggerFactory.getLogger(DocLoader.class);
private final String storeName;
private final DocumentStore store;
private final Connection connection;
private final Function<V,String> keyFunction;
private final BiFunction<Connection,V,Document> documentFunction;
private DocLoader(Builder<V> builder) {
this.storeName = builder.storeName;
this.keyFunction = builder.keyFunction;
this.documentFunction = builder.documentFunction;
this.connection = DriverManager.getConnection("ojai:mapr:");
if ( connection.storeExists(storeName) ) {
this.store = connection.getStore(this.storeName);
} else {
this.store = connection.createStore(this.storeName);
}
}
public void insert(String key, V data) {
this.store.insertOrReplace( key, documentFunction.apply(connection,data));
}
public void insert(V data) {
this.store.insertOrReplace( keyFunction.apply(data), documentFunction.apply(connection,data));
}
public void close() {
if ( store != null ) store.close();
if ( connection != null ) connection.close();
}
public static class Builder<V> {
private String storeName;
private Function<V,String> keyFunction;
private BiFunction<Connection,V,Document> documentFunction;
public Builder<V> storeName(String storeName) {
this.storeName = storeName;
return this;
}
public Builder<V> keyFunction(Function<V,String> keyFunction) {
this.keyFunction = keyFunction;
return this;
}
public Builder<V> documentFunction(BiFunction<Connection,V,Document> documentFunction) {
this.documentFunction = documentFunction;
return this;
}
public DocLoader<V> build() {
return new DocLoader<V>(this);
}
}
}
|
package Keming;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
public class Find5 {
static FileOutputStream fos;
public static void disassemble(File directory) throws IOException {
_disassemble(directory, null);
}
public static void _disassemble(File directory, UUID parentUUID) throws IOException {
UUID directoryUUID = UUID.randomUUID();
if( parentUUID == null ) {
String output = "\t" + directoryUUID + "\n";
System.out.print( output);
fos.write(output.getBytes());
} else {
String output = parentUUID+ "\t" + directoryUUID
+ "\t" + directory.getName()
+ "\t" + directory.length() + "\n";
System.out.print( output );
fos.write(output.getBytes());
}
if(directory.isDirectory()) {
for(File subfile : directory.listFiles()) {
_disassemble(subfile, directoryUUID);
}
}
}
public static void main(String[] argv) throws IOException {
Find5.fos = new FileOutputStream("diskinfo.dat");
disassemble(new File("."));
fos.close();
}
}
|
package viewer;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.geom.Point2D;
import com.vividsolutions.jts.geom.Coordinate;
import gisviewer.MapObject;
import gisviewer.Transformation;
import graph.types.ColoredNode;
import isochrone.IsoFace;
import util.geometry.Envelope;
public class FaceMapObjectWithId implements MapObject {
private boolean alternatingColors = true;
private final static Color[] colors = { Color.decode("#a6cee3"), Color.decode("#1f78b4"), Color.decode("#b2df8a"),
Color.decode("#33a02c"), Color.decode("#fb9a99"), Color.decode("#e31a1c"), Color.decode("#fdbf6f"),
Color.decode("#ff7f00"), Color.decode("#cab2d6"), Color.decode("#6a3d9a"), Color.decode("#ffff99"),
Color.decode("#b15928") };
private final static double LABELING_MINM = 0.2;
private IsoFace face;
public FaceMapObjectWithId(IsoFace face) {
this.face = face;
}
@Override
public void draw(Graphics2D g, Transformation t) {
// Color initialColor = g.getColor();
if (alternatingColors) {
g.setColor(colors[face.getId() % colors.length]);
}
int[][] coordinates = coordinatesFromPolygon(g, t);
int[] xpoints = coordinates[0];
int[] ypoints = coordinates[1];
// draw polygon
Color currColor = g.getColor();
g.setColor(new Color(currColor.getRed(), currColor.getGreen(), currColor.getBlue(), 100));
Polygon myPolygon = new Polygon(xpoints, ypoints, xpoints.length);
g.fillPolygon(myPolygon);
g.setColor(currColor);
if (t.getM() > LABELING_MINM) {
// write face id
int r = t.getRow(face.barycenterFromBoundary().getY());
int c = t.getColumn(face.barycenterFromBoundary().getX());
String s = "[" + face.getId() + "]";
int dR = (g.getFontMetrics().getHeight());
int dC = (g.getFontMetrics().stringWidth(s));
g.drawString(s, c - dC / 2, r - dR / 2);
}
}
@SuppressWarnings("unused")
private int[][] coordinatesFromBoundary(Graphics2D g, Transformation t) {
int npoints = face.getBoundary().size();
int[][] coordinates = new int[2][];
coordinates[0] = new int[npoints];
coordinates[1] = new int[npoints];
Point2D first = null, prev = null, curr = null;
int row1, col1, row2, col2;
int zaehler = 0;
for (ColoredNode vertex : face.getBoundary()) {
if (prev == null) {
first = vertex;
prev = first;
continue;
}
curr = vertex;
row1 = t.getRow(prev.getY());
col1 = t.getColumn(prev.getX());
row2 = t.getRow(curr.getY());
col2 = t.getColumn(curr.getX());
g.drawLine(col1, row1, col2, row2);
coordinates[0][zaehler] = col1;
coordinates[1][zaehler] = row1;
zaehler++;
prev = curr;
}
// draw closing arc from end to start
row1 = t.getRow(curr.getY());
col1 = t.getColumn(curr.getX());
row2 = t.getRow(first.getY());
col2 = t.getColumn(first.getX());
g.drawLine(col1, row1, col2, row2);
coordinates[0][zaehler] = col1;
coordinates[1][zaehler] = row1;
return coordinates;
}
private int[][] coordinatesFromPolygon(Graphics2D g, Transformation t) {
int npoints = face.getFacePoly().getNumPoints();
int[][] coordinates = new int[2][];
coordinates[0] = new int[npoints];
coordinates[1] = new int[npoints];
Coordinate first = null, prev = null, curr = null;
int row1, col1, row2, col2;
int zaehler = 0;
for (var vertex : face.getFacePoly().getCoordinates()) {
if (prev == null) {
first = vertex;
prev = first;
continue;
}
curr = vertex;
row1 = t.getRow(prev.y);
col1 = t.getColumn(prev.x);
row2 = t.getRow(curr.y);
col2 = t.getColumn(curr.x);
g.drawLine(col1, row1, col2, row2);
coordinates[0][zaehler] = col1;
coordinates[1][zaehler] = row1;
zaehler++;
prev = curr;
}
// draw closing arc from end to start
row1 = t.getRow(curr.y);
col1 = t.getColumn(curr.x);
row2 = t.getRow(first.y);
col2 = t.getColumn(first.x);
g.drawLine(col1, row1, col2, row2);
coordinates[0][zaehler] = col1;
coordinates[1][zaehler] = row1;
return coordinates;
}
@Override
public Envelope getBoundingBox() {
Envelope env = new Envelope();
for (ColoredNode vertex : face.getBoundary()) {
env.expandToInclude(vertex.getX(), vertex.getY());
}
return env;
}
}
|
package com.tencent.mm.plugin.order.model;
public class MallOrderDetailObject$b {
public String jOU;
public String lNA;
public String lNB;
public String thumbUrl;
public int time;
}
|
import java.util.Scanner;
// Input four number and find the roots (if there are any)
// the code needs to check wich x value makes the equation equals to 0.
public class RootsOfAnEquation {
public static void main(String[] args) {
// Create a new scanner
Scanner sc = new Scanner(System.in);
System.out.print("Input: ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
for (int x = 0; x <= 1000; x ++) {
int root = (a * (x * x * x)) + (b * (x * x)) + (c * (x)) + d;
if (root == 0) {
System.out.println(x);
}
}
}
}
|
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;
// Interface for a SubjectManager
public interface ISubjectManager extends Remote{
public void loadSubjects (List<Subject> new_subjects) throws RemoteException;
public List<Subject> getAll() throws RemoteException;
public Subject getSubjectByCode(String Code) throws RemoteException;
public int changeComment(String code, String new_comment, User professor) throws RemoteException;
}
|
package com.example.getresourcesapi;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private EditText mEtID;
private Button mBtnGet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEtID = findViewById(R.id.etID);
mBtnGet = findViewById(R.id.btnGet);
mBtnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, LastActivity.class);
intent.putExtra("id", Integer.parseInt(mEtID.getText().toString()));
startActivity(intent);
}
});
}
} |
package Sorting.JAVASort.Compare;
import java.util.Arrays;
public class Test2 {
public static void main(final String[] args) {
final Integer[] arr = { new Integer(1), new Integer(16), new Integer(13), new Integer(178),
new Integer(6452131), };
for (final Integer i : arr)
System.out.print(i.x + " ");
System.out.println();
Arrays.sort(arr);
for (final Integer i : arr)
System.out.print(i.x + " ");
System.out.println();
}
}
|
package vn.com.tma.entities;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "address")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String city;
private String province;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
// Quan hệ n-n với đối tượng ở dưới (Person) (1 địa điểm có nhiều người ở)
@JoinTable(name = "address_person", //Tạo ra một join Table tên là "address_person"
joinColumns = @JoinColumn(name = "address_id"), // TRong đó, khóa ngoại chính là address_id trỏ tới class hiện tại (Address)
inverseJoinColumns = @JoinColumn(name = "person_id") //Khóa ngoại thứ 2 trỏ tới thuộc tính ở dưới (Person)
)
private Collection<Person> persons;
}
|
package com.bojkosoft.bojko108.testgpscam;
import android.app.Activity;
import android.os.Bundle;
public class CameraPreviewActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
getFragmentManager().beginTransaction()
.replace(R.id.cameraPreview, CameraFragment.newInstance())
.commit();
}
protected void onResume(){
super.onResume();
getFragmentManager().findFragmentById(R.id.cameraPreview);
}
} |
package edu.tecnasa.ecommerce.errors;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import edu.tecnasa.ecommerce.dto.ErrorDetails;
@ControllerAdvice
public class ExceptionManager4Rest {
@ExceptionHandler({ResourceNotFoundException.class})
public ResponseEntity<ErrorDetails> manageResourceNotFoundException(ResourceNotFoundException e, HttpServletRequest request) {
ErrorDetails errorDetail = new ErrorDetails();
errorDetail.setTime(new Date().getTime());
errorDetail.setState(HttpStatus.NOT_FOUND.value());
errorDetail.setTitle("Resource not found.");
errorDetail.setDescriptions(e.getMessage());
errorDetail.setTechMessage(e.getClass().getName());
return new ResponseEntity<ErrorDetails>(errorDetail, null, HttpStatus.NOT_FOUND);
}
@ExceptionHandler({MethodArgumentNotValidException.class})
public ResponseEntity<ErrorDetails> manageMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
ErrorDetails errorDetail = new ErrorDetails();
errorDetail.setTime(new Date().getTime());
errorDetail.setState(HttpStatus.BAD_REQUEST.value());
errorDetail.setTitle("Validation fails.");
errorDetail.setDescriptions(e.getMessage());
errorDetail.setTechMessage(e.getClass().getName());
return new ResponseEntity<ErrorDetails>(errorDetail, null, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler({Exception.class})
public ResponseEntity<ErrorDetails> manageGeneralException(Exception e, HttpServletRequest request) {
ErrorDetails errorDetail = new ErrorDetails();
errorDetail.setTime(new Date().getTime());
errorDetail.setState(HttpStatus.BAD_REQUEST.value());
errorDetail.setTitle("Something is wrong.");
errorDetail.setDescriptions(e.getMessage());
errorDetail.setTechMessage(e.getClass().getName());
return new ResponseEntity<ErrorDetails>(errorDetail, null, HttpStatus.BAD_REQUEST);
}
}
|
package org.apache.pig.impl.io;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Arrays;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.Tuple;
import eu.stratosphere.nephele.configuration.Configuration;
import eu.stratosphere.pact.common.type.base.PactString;
/**
*
* Copy of TextInputFormat reading Tuples instead of PactRecords
* @author hinata
*
*/
public class SPigTextInputFormat extends SPigDelimitedInputFormat {
public static final String CHARSET_NAME = "textformat.charset";
public static final String DEFAULT_CHARSET_NAME = "UTF-8";
private static final Log LOG = LogFactory.getLog(SPigDelimitedInputFormat.class);
protected final PactString theString = new PactString();
protected CharsetDecoder decoder;
protected ByteBuffer byteWrapper;
protected boolean ascii;
@Override
public void configure(Configuration parameters)
{
super.configure(parameters);
// get the charset for the decoding
String charsetName = parameters.getString(CHARSET_NAME, DEFAULT_CHARSET_NAME);
if (charsetName == null || !Charset.isSupported(charsetName)) {
throw new RuntimeException("Unsupported charset: " + charsetName);
}
if (charsetName.equals("ISO-8859-1") || charsetName.equalsIgnoreCase("ASCII")) {
this.ascii = true;
} else {
this.decoder = Charset.forName(charsetName).newDecoder();
this.byteWrapper = ByteBuffer.allocate(1);
}
}
@Override
//TODO: Find where will this target Tuple be instantiated???
public boolean readRecord(Tuple target, byte[] bytes, int offset,
int numBytes) {
PactString str = this.theString;
if (this.ascii) {
str.setValueAscii(bytes, offset, numBytes);
}
else {
ByteBuffer byteWrapper = this.byteWrapper;
if (bytes != byteWrapper.array()) {
byteWrapper = ByteBuffer.wrap(bytes, 0, bytes.length);
this.byteWrapper = byteWrapper;
}
byteWrapper.clear();
byteWrapper.position(offset);
byteWrapper.limit(offset + numBytes);
try {
CharBuffer result = this.decoder.decode(byteWrapper);
str.setValue(result);
}
catch (CharacterCodingException e) {
byte[] copy = new byte[numBytes];
System.arraycopy(bytes, offset, copy, 0, numBytes);
LOG.warn("Line could not be encoded: " + Arrays.toString(copy), e);
return false;
}
}
target.setNull(true);
//target.clear();
try {
target.set(0, str.getValue());
} catch (ExecException e) {
e.printStackTrace();
}
return true;
}
}
|
package com.liwei.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.liwei.application.MyApplation;
import com.liwei.teachsystem.R;
import com.liwei.utils.ToastUtils;
import com.liwei.utils.UrlUtils;
public class MingTiActivity extends Activity{
private int cno;
private String tno;
private EditText question;
private EditText question_a;
private EditText question_b;
private EditText question_zhengque;
private Button ok;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mingti);
MyApplation.setActivity(this);
cno=getIntent().getIntExtra("cno", 0);
tno=getIntent().getStringExtra("tno");
initView();
}
public void initView(){
ImageView close=(ImageView)findViewById(R.id.bjmgf_sdk_closeAboutBtnId);
/**
* 返回按钮
*/
close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
question=(EditText) findViewById(R.id.question);
question_a=(EditText) findViewById(R.id.question_a);
question_b=(EditText) findViewById(R.id.question_b);
question_zhengque=(EditText) findViewById(R.id.zhengque);
ok=(Button) findViewById(R.id.ok);
ok.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(question.getText().toString().equals("")||question_a.getText().toString().equals("")
||question_b.getText().toString().equals("")||question_zhengque.getText().toString().equals("")){
ToastUtils.getToast(MingTiActivity.this, "请确保所填内容都不为空");
}else{
HttpUtils utils=new HttpUtils();
RequestParams params=new RequestParams();
params.addBodyParameter("tno",tno);
params.addBodyParameter("cno",String.valueOf(cno));
params.addBodyParameter("question",question.getText().toString());
params.addBodyParameter("question_a",question_a.getText().toString());
params.addBodyParameter("question_b",question_b.getText().toString());
params.addBodyParameter("question_zhengque",question_zhengque.getText().toString());
utils.send(HttpMethod.POST, UrlUtils.url+"/MingTiServlet", params, new RequestCallBack<String>() {
@Override
public void onFailure(HttpException arg0, String arg1) {
ToastUtils.getToast(MingTiActivity.this,"请求网络数据失败");
}
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
String flag=responseInfo.result;
if(flag.equals("true")){
ToastUtils.getToast(MingTiActivity.this,"命题成功");
finish();
}else{
ToastUtils.getToast(MingTiActivity.this,"命题失败");
}
}
});
}
}
});
}
}
|
package com.meihf.mjoyblog.service.user;
import com.meihf.mjoyblog.bean.PageBean;
import com.meihf.mjoyblog.bean.PageRetInfo;
import com.meihf.mjoyblog.bean.User;
/**
* 用户表的服务
* @author 韩元旭
*/
public interface IUserSvc {
/**
* 根据登录名称查询用户信息
* @param loginName
* @return
*/
User getUserInfoByLoginName(String loginName);
/**
* 验证管理员登录名密码
* @param loginName
* @param loginPwd
* @throws Exception
* @return
*/
User verifyAdminLogin(String loginName, String loginPwd) throws Exception;
/**
* @desc: 记录访问IP地址
* @author: 韩元旭
* @param loginName
* @param loginIP
* @throws Exception
* @date : 2016年1月12日
*/
void logLoginIP(String loginName, String loginIP) throws Exception;
/**
* @desc: 自动登录
* @author: 韩元旭
* @param ip
* @return
* @date : 2016年1月12日
*/
User autoLogin(String ip) throws Exception;
PageRetInfo<User> findByCondition(PageBean page, Object object,String email);
void deleteUserById(String longinName);
void addUser(String loginName, String loginPwd,String blog_name,String email);
int findByByLoginName(String loginName,String loginPwd,String email,String blog_name) throws Exception;
}
|
/*
* UniTime 3.4 - 3.5 (University Timetabling Application)
* Copyright (C) 2012 - 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.security.context;
import java.util.Iterator;
import java.util.List;
import org.springframework.security.access.AccessDeniedException;
import org.unitime.timetable.security.UserAuthority;
import org.unitime.timetable.security.UserContext;
import org.unitime.timetable.security.qualifiers.SimpleQualifier;
import org.unitime.timetable.security.rights.Right;
/**
* @author Tomas Muller
*/
public class ChameleonUserContext extends UniTimeUserContext implements UserContext.Chameleon {
private static final long serialVersionUID = 1L;
private UserContext iOriginalUser;
public ChameleonUserContext(String userId, UserContext originalUser) {
super(userId, originalUser.getUsername(), originalUser.getName(), null);
// Original user is session dependent -> remove all session independent authorities from the new user
if (originalUser.getCurrentAuthority() == null || !originalUser.getCurrentAuthority().hasRight(Right.SessionIndependent)) {
for (Iterator<? extends UserAuthority> i = getAuthorities().iterator(); i.hasNext(); ) {
UserAuthority authority = i.next();
if (authority.hasRight(Right.SessionIndependent))
i.remove();
}
if (getCurrentAuthority() != null && getCurrentAuthority().hasRight(Right.SessionIndependent)) {
List<? extends UserAuthority> authorities = getAuthorities(null, new SimpleQualifier("Session", originalUser.getCurrentAcademicSessionId()));
if (!authorities.isEmpty())
setCurrentAuthority(authorities.get(0));
else
throw new AccessDeniedException("Access denied for " + super.getName().trim() + ": not enough permissions for role " + getCurrentAuthority().getRole() + ".");
}
if (getAuthorities().isEmpty())
throw new AccessDeniedException("Access denied for " + super.getName().trim() + ": no role available.");
}
iOriginalUser = originalUser;
if (iOriginalUser instanceof UserContext.Chameleon)
iOriginalUser = ((UserContext.Chameleon)iOriginalUser).getOriginalUserContext();
if (originalUser.getCurrentAuthority() != null) {
UserAuthority authority = getAuthority(originalUser.getCurrentAuthority().getAuthority());
if (authority != null)
setCurrentAuthority(authority);
}
}
@Override
public UserContext getOriginalUserContext() { return iOriginalUser; }
@Override
public String getName() {
return super.getName() + " (A)";
}
}
|
package com.boniu.ad.reward;
public class DirectCusAdManager {
}
|
/*
* FileName: SystemData.java
* Description:
* Company: 南宁超创信息工程有限公司
* Copyright: ChaoChuang (c) 2005
* History: 2005-1-17 (guig) 1.0 Create
*/
package com.spower.basesystem.common.systemdata;
/**
* 管理应用系统使用的数据常量和数据字典的对象
* @author guig
* @version 1.0 2005-1-17
*/
public abstract class SystemData {
/**
* 单实例对象
*/
private static SystemData me = null;
/**
* @param me The me to set.
*/
protected void setMe(SystemData me) {
SystemData.me = me;
}
/**
* 获取对象实例
* @return SystemData对象的实例
*/
public static SystemData getInstance() {
return me;
}
/**
* 获取系统数据
* @param dataType 要获取的系统数据的数据分类类型
* @param dataKey key数据对象
* @return 返回dataType类型下的dataKey对象对应的值对象
*/
abstract public Object getSystemData(String dataType, Object dataKey);
/**
* 取指定流程起始节点的定义
* @param key 流程逻辑定义名
* @return
public String getFlowBeginDotLogicDefId(String key) {
return getSystemData("flowBeginActionID", key).toString();
}*/
}
|
package com.finki.os.labs.lab1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
/// ---- BAJT PO BAJT ------ ///
public class HW01_2{
public static void main(String[] args) throws IOException {
FileInputStream fis;
try{
fis = new FileInputStream("data/izvor.txt");
} catch(FileNotFoundException e){
System.out.println("Ne e pronajden takov fajl!");
return;
}
ArrayList<Integer> tekst = new ArrayList<Integer>();
int bajt = 0;
while((bajt = fis.read()) != -1){
tekst.add(bajt);
}
fis.close();
FileOutputStream fos;
try{
fos = new FileOutputStream("data/destinacija.txt");
} catch(FileNotFoundException e){
System.out.println("Ne e mozno da se otvori fajlot!");
return;
}
for (int i=tekst.size()-1; i>=0; i--)
fos.write(tekst.get(i));
fos.flush();
fos.close();
}
} |
package com.allen.lightstreamdemo.mvp.login;
/**
* Created by: allen on 16/9/1.
*/
public interface LoginView {
void showProgress(boolean isShow);
void showAlertMsg(String watchList);
void gotoMainActivity();
}
|
package com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.tencent.mm.plugin.sns.i.f;
import com.tencent.mm.plugin.sns.i.g;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.t;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.d;
public final class v extends i {
TextView ePz;
private RelativeLayout nFv;
ImageView nFw;
public v(Context context, t tVar, ViewGroup viewGroup) {
super(context, tVar, viewGroup);
this.nDt = tVar;
}
protected final int getLayout() {
return g.sns_ad_native_landing_pages_item_process_bar;
}
public final void bzz() {
super.bzz();
}
protected final void bzQ() {
this.ePz.setText(((t) this.nDt).label);
this.ePz.setTextSize(0, ((t) this.nDt).azb);
if (((t) this.nDt).fpc != null && ((t) this.nDt).fpc.length() > 0) {
this.nFv.setBackgroundColor(Color.parseColor(((t) this.nDt).fpc));
}
d.a(((t) this.nDt).nBn, ((t) this.nDt).nAX, new 1(this));
}
public final View bzM() {
View view = this.contentView;
view.setBackgroundColor(this.backgroundColor);
this.ePz = (TextView) view.findViewById(f.sns_ad_landingpage_processbar_label);
this.nFv = (RelativeLayout) view.findViewById(f.sns_ad_landingpage_processbar_bg);
this.nFw = (ImageView) view.findViewById(f.sns_ad_landingpage_processbar_front);
return view;
}
public final void bzA() {
super.bzA();
}
public final void bzB() {
super.bzB();
}
}
|
/**
*
*/
package game.menubar;
import game.core.GamePreferences.AppMode;
import game.ui.MainWindow;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
* @author schroeder_jan
*
*/
public class SaveGameAction extends AbstractAction {
public SaveGameAction(String text, ImageIcon icon) {
super(text, icon);
}
/**
*
*/
private static final long serialVersionUID = 1L;
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent pE) {
if (MainWindow.getInstance().getGamePrefs().getAppMode() == AppMode.GAME_MODE
|| MainWindow.getInstance().getGamePrefs().getAppMode() == AppMode.LOAD_GAME_MODE) {
// TODO Speicherdialog aufrufen
JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setMultiSelectionEnabled(false);
jfc.setFileHidingEnabled(true);
FileFilter ff = new FileNameExtensionFilter("Starfield-Spielstand",
"save");
jfc.setFileFilter(ff);
// setzt ausgangspfad und erstellt ordner des ausgangspfads wenn
// nicht vorhanden
File dirfile = new File("Spielstand");
if (dirfile.getAbsoluteFile().exists()) {
jfc.setCurrentDirectory(dirfile.getAbsoluteFile());
} else {
try {
dirfile.mkdir();
jfc.setCurrentDirectory(dirfile.getAbsoluteFile());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// -----------------
int w = 0;
do {
w = 0;
if (jfc.showSaveDialog(jfc) == JFileChooser.APPROVE_OPTION) {
String temppfad = jfc.getSelectedFile().getAbsolutePath();
if (temppfad.endsWith(".save")) {
} else {
temppfad = temppfad + ".save";
}
// prüft ob die datei bereits existiert
File tempfile = new File(temppfad);
if (tempfile.exists()) {
int auswahl = JOptionPane.showConfirmDialog(null,
"Wollen Sie den Spielstand überschreiben?",
"Spielstand existiert",
JOptionPane.YES_NO_CANCEL_OPTION);
switch (auswahl) {
case 0:
try {
File f = new File(temppfad);
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(
fos);
oos.flush();
oos.writeObject(MainWindow.getInstance()
.getCommandStack());
oos.close();
MainWindow.getInstance().getCommandStack()
.setStackChange(false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
w = 0;
break;
case 1:
w = 1;
break;
case 2:
w = 0;
break;
}
} else {
try {
File f = new File(temppfad);
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.flush();
oos.writeObject(MainWindow.getInstance()
.getCommandStack());
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
w = 0;
}
}
} while (w == 1);
}
}
}
|
import java.io.IOException; // checked exception
class SneakyThrow {
static <T extends Throwable> void sneakyThrow(Throwable ex) throws T {
throw (T) ex;
}
static void noCheckedExceptionsDeclared() { // no checked exceptions declared
sneakyThrow(new IOException()); // checked exception will be thrown
}
public static void main(String[] args) {
try {
noCheckedExceptionsDeclared();
} catch (Throwable ex) {
System.out.println(ex); // checked IOException will be logged
}
}
}
|
package net.liuzd.spring.boot.v2.jedis;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import redis.clients.jedis.Jedis;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
/**
* JUnit4使用Java5中的注解(annotation),以下是JUnit4常用的几个annotation:
* @Before:初始化方法 对于每一个测试方法都要执行一次(注意与BeforeClass区别,后者是对于所有方法执行一次)
* @After:释放资源 对于每一个测试方法都要执行一次(注意与AfterClass区别,后者是对于所有方法执行一次)
* @Test:测试方法,在这里可以测试期望异常和超时时间
* @Test(expected=ArithmeticException.class)检查被测方法是否抛出ArithmeticException异常
* :忽略的测试方法
* @BeforeClass:针对所有测试,只执行一次,且必须为static void
* @AfterClass:针对所有测试,只执行一次,且必须为static void 一个JUnit4的单元测试用例执行顺序为:
* @BeforeClass -> @Before -> @Test -> @After -> @AfterClass; 每一个测试方法的调用顺序为:
* @Before -> @Test -> @After;
*/
public class JedisTests {
private static Jedis jedis;
@BeforeClass
public static void start() {
// 连接本地的 Redis 服务
if (null == jedis) {
jedis = new Jedis("localhost");
System.out.println("连接本地的 Redis 服务成功!");
}
}
@AfterClass
public static void end() {
if (null != jedis) {
jedis.close();
}
System.out.println("关闭本地的 Redis 服务成功!");
}
@Test
public void testStr() {
System.out.println("---------------testStr--------------");
// 设置 redis 字符串数据
String key = "souvc";
String url = "http://www.cnblogs.com/liuhongfeng/";
jedis.del(key);
jedis.set(key, url);
// 获取存储的数据并输出
String val = jedis.get(key);
System.out.println("redis存储的字符串是: " + val);
Assert.isTrue(url.equals(val), "not eq");
}
@Test
public void testList() {
System.out.println("---------------testList--------------");
// 存储数据到列表中
String key = "kecheng";
jedis.del(key);
jedis.lpush(key, "java");
jedis.lpush(key, "php");
jedis.lpush(key, "Mysql");
// 获取存储的数据并输出
List<String> list = jedis.lrange(key, 0, 5);
for (int i = 0; i < list.size(); i++) {
System.out.println("redis list里面存储的值是:" + list.get(i));
}
}
@Test
public void testList2() {
System.out.println("---------------testList2--------------");
// 开始前,先移除所有的内容
String key = "java framework";
jedis.del(key);
System.out.println(key + "=" + jedis.lrange(key, 0, -1));
// 先向key java framework中存放三条数据
jedis.lpush(key, "spring");
jedis.lpush(key, "struts");
jedis.lpush(key, "hibernate");
// 再取出所有数据jedis.lrange是按范围取出,
// 第一个是key,第二个是起始位置,第三个是结束位置,jedis.llen获取长度 -1表示取得所有
System.out.println(jedis.lrange(key, 0, -1));
jedis.del(key);
jedis.rpush(key, "spring");
jedis.rpush(key, "struts");
jedis.rpush(key, "hibernate");
System.out.println(jedis.lrange(key, 0, -1));
//
}
@Test
public void testMap() {
System.out.println("---------------testMap--------------");
// -----添加数据----------
Map<String, String> map = new HashMap<>();
map.put("name", "xinxin");
map.put("age", "22");
map.put("qq", "123456");
String key = "user";
jedis.hmset(key, map);
// 取出user中的name,执行结果:[minxr]-->注意结果是一个泛型的List
// 第一个参数是存入redis中map对象的key,后面跟的是放入map中的对象的key,后面的key可以跟多个,是可变参数
List<String> rsmap = jedis.hmget(key, "name", "age", "qq");
System.out.println("list>" + rsmap);
// 删除map中的某个键值
jedis.hdel(key, "age");
System.out.println("age>" + jedis.hmget(key, "age")); // 因为删除了,所以返回的是null
System.out.println(key + "1>" + jedis.hlen(key)); // 返回key为user的键中存放的值的个数2
System.out.println(key + "2>" + jedis.exists(key));// 是否存在key为user的记录
// 返回true
System.out.println(key + "3>" + jedis.hkeys(key));// 返回map对象中的所有key
System.out.println(key + "4>" + jedis.hvals(key));// 返回map对象中的所有value
Iterator<String> iter = jedis.hkeys(key).iterator();
while (iter.hasNext()) {
String mapkey = iter.next();
System.out.println(mapkey + ":" + jedis.hmget(key, mapkey));
}
}
@Test
public void testSet() {
System.out.println("---------------testSet--------------");
// 删除map中的某个键值
String key = "userSet";
if (jedis.exists(key)) {
jedis.del(key);
}
// 添加
jedis.sadd(key, "liuling");
jedis.sadd(key, "xinxin");
jedis.sadd(key, "ling");
jedis.sadd(key, "zhangxinxin");
jedis.sadd(key, "who");
// 移除noname
jedis.srem(key, "who");
System.out.println("smembers>" + jedis.smembers(key));// 获取所有加入的value
System.out.println("sismember>" + jedis.sismember(key, "who"));// 判断who是否是user集合的元素
// 随机返回值
System.out.println("srandmember>" + jedis.srandmember(key));
System.out.println("scard>" + jedis.scard(key));// 返回集合的元素个数
}
@Test
public void testSort() {
System.out.println("---------------testSort--------------");
// jedis 排序
// 注意,此处的rpush和lpush是List的操作。是一个双向链表(但从表现来看的)
String key = "sort";
jedis.del(key);// 先清除数据,再加入数据进行测试
jedis.rpush(key, "1");
jedis.lpush(key, "6");
jedis.lpush(key, "3");
jedis.lpush(key, "9");
System.out.println(jedis.lrange(key, 0, -1));// [9, 3, 6, 1]
System.out.println(jedis.sort(key)); // [1, 3, 6, 9] //输入排序后结果
System.out.println(jedis.lrange(key, 0, -1));
}
} |
package Marketing.OrderEnity;
import Marketing.Promotion.Coupon;
/**
* @Author 王立友
* 该类为订单中金额相关信息,包含原始信息与促销活动信息等相关
*/
public class OrderAmount {
//原始金额;
private double originalAmount;
//促销金额;
private double promotionAmount;
//促销活动
private Coupon coupon;
//运输费用
private double transportationAmount;
public OrderAmount(double originalAmount, Coupon coupon){
this.originalAmount = originalAmount;
this.coupon = coupon;
this. promotionAmount = coupon.getPreferentialPrice(originalAmount);
//运输费用默认为每1元订单的费用为0.0021元
this.transportationAmount = 0.0021 * promotionAmount;
}
public Coupon getCoupon() {
return coupon;
}
public double getOriginalAmount() {
return originalAmount;
}
public double getPromotionAmount() {
return promotionAmount;
}
public double getTransportationAmount() {
return transportationAmount;
}
public void setTransportationAmount(double transportationAmount) {
this.transportationAmount = transportationAmount;
}
}
|
package instructable.server.controllers;
import instructable.server.backend.ExecutionStatus;
import instructable.server.hirarchy.*;
import instructable.server.senseffect.IEmailFetcher;
import java.util.Optional;
/**
* Created by Amos Azaria on 19-May-15.
*/
public class InboxCommandController
{
int currentIncomingEmailIdx;
static public final String emailMessageNameStart = "inbox";
ConceptContainer conceptContainer;
InstanceContainer instanceContainer;
Optional<IEmailFetcher> emailFetcher;
public InboxCommandController(ConceptContainer conceptContainer, InstanceContainer instanceContainer, Optional<IEmailFetcher> emailFetcher)
{
//userId = conceptContainer.getUserId();
this.conceptContainer = conceptContainer;
this.instanceContainer = instanceContainer;
this.emailFetcher = emailFetcher;
if (emailFetcher.isPresent() && emailFetcher.get().shouldUseLastEmail())
currentIncomingEmailIdx = emailFetcher.get().getLastEmailIdx(new ExecutionStatus());
else
currentIncomingEmailIdx = 0;
conceptContainer.defineConcept(new ExecutionStatus(), IncomingEmail.incomingEmailType, IncomingEmail.getFieldDescriptions());
}
/**
* for use only for experiments. In real world will use EmailFetcher
* @param emailMessage
*/
public void addEmailMessageToInbox(EmailInfo emailMessage)
{
new IncomingEmail(instanceContainer, emailMessage, instanceName(inboxSize(new ExecutionStatus())));
}
public boolean isInboxInstanceName(String instanceName)
{
return instanceName.equals(emailMessageNameStart);
}
public String getCurrentEmailName(ExecutionStatus executionStatus)
{
if (currentIncomingEmailIdx == 0 && emailFetcher.isPresent() && emailFetcher.get().shouldUseLastEmail())
setToNewestEmail(new ExecutionStatus());
makeSureEmailIsPresentInDb(executionStatus);
return emailMessageNameStart + currentIncomingEmailIdx;
}
public Optional<GenericInstance> getCurrentIncomingEmail(ExecutionStatus executionStatus)
{
boolean ok = makeSureEmailIsPresentInDb(executionStatus);
if (ok)
return instanceContainer.getInstance(executionStatus, IncomingEmail.incomingEmailType, instanceName(currentIncomingEmailIdx));
executionStatus.add(ExecutionStatus.RetStatus.error, "the email was not found");
return Optional.empty();
}
/**
*
* @return true is ok.
*/
private boolean makeSureEmailIsPresentInDb(ExecutionStatus executionStatus)
{
//TODO: what happens if email was deleted? Maybe current email is different?
if (emailFetcher.isPresent() && !instanceContainer.getInstance(new ExecutionStatus(), IncomingEmail.incomingEmailType, instanceName(currentIncomingEmailIdx)).isPresent())
{
Optional<EmailInfo> emailInfo = emailFetcher.get().getEmailInfo(executionStatus, currentIncomingEmailIdx);
if (emailInfo.isPresent())
{
new IncomingEmail(instanceContainer, emailInfo.get(), instanceName(currentIncomingEmailIdx));
return true;
}
return false;
}
return true;
}
public void setToNextEmail(ExecutionStatus executionStatus)
{
int inboxSize = inboxSize(executionStatus);
if (currentIncomingEmailIdx < inboxSize - 1)
currentIncomingEmailIdx++;
else
executionStatus.add(ExecutionStatus.RetStatus.error, "there are no more emails. You may want to set to a previous email");// You have probably missed some earlier emails. You may want to request a previous email (say \"previous email\")"); //shouldn't be in the production version
}
public void setToPrevEmail(ExecutionStatus executionStatus)
{
if (currentIncomingEmailIdx > 0)
currentIncomingEmailIdx--;
else
executionStatus.add(ExecutionStatus.RetStatus.error, "there is no previous email");
}
/**
* sets to last email, returns index before setting.
* @return
*/
public int setToNewestEmail(ExecutionStatus executionStatus)
{
return setToIndex(inboxSize(executionStatus) - 1);
}
/**
* sets to index, returns index before setting.
* @return
*/
public int setToIndex(int newIdx)
{
int previousIdx = currentIncomingEmailIdx;
currentIncomingEmailIdx = newIdx;
return previousIdx;
}
private String instanceName(int emailIdx)
{
return emailMessageNameStart + emailIdx;
}
private int inboxSize(ExecutionStatus executionStatus)
{
if (emailFetcher.isPresent())
return emailFetcher.get().getLastEmailIdx(executionStatus) + 1;
return instanceContainer.getAllInstances(IncomingEmail.incomingEmailType).size();
}
//TODO: delete?
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pt.mleiria.mlalgo.preprocess;
import junit.framework.TestCase;
import pt.mleiria.mlalgo.core.Transformer;
/**
* @author Manuel Leiria <manuel.leiria at gmail.com>
*/
public class MinMaxScalerTest extends TestCase {
Double[][] data = new Double[4][2];
Transformer t;
@Override
protected void setUp() throws Exception {
data[0][0] = -1.;
data[1][0] = -0.5;
data[2][0] = 0.;
data[3][0] = 1.;
data[0][1] = 2.;
data[1][1] = 6.;
data[2][1] = 10.;
data[3][1] = 18.;
t = new MinMaxScaler();
}
public void testFit() {
t.fit(data);
assertEquals(1., t.getParams(0).getMax());
assertEquals(18., t.getParams(1).getMax());
}
public void testTransform() {
final Double[][] transformed = t.fitTransform(data);
assertEquals(0., transformed[0][0]);
assertEquals(.25, transformed[1][0]);
assertEquals(.5, transformed[2][1]);
assertEquals(1., transformed[3][1]);
}
public void testTransformCustomMinMax() {
((MinMaxScaler) t).setFeaturesRange(10, 20);
final Double[][] transformed = t.fitTransform(data);
assertEquals(10., transformed[0][0]);
assertEquals(12.5, transformed[1][0]);
assertEquals(15., transformed[2][1]);
assertEquals(20., transformed[3][1]);
}
}
|
package net.roto.github.service;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import net.roto.github.model.User;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.github.api.GitHub;
import org.springframework.social.github.api.GitHubUser;
import org.springframework.social.github.api.GitHubUserProfile;
import org.springframework.social.github.api.impl.GitHubTemplate;
import org.springframework.stereotype.Service;
@Service("githubService")
public class GitHubServiceImpl implements GitHubService{
@Inject
ConnectionRepository connectionRepository;
public GitHub getAPI() {
Connection<GitHub> gitHubConnection = connectionRepository.findPrimaryConnection(GitHub.class);
if( gitHubConnection != null ){
return gitHubConnection.getApi();
}
else{
return new GitHubTemplate();
}
}
@Override
public User getUserProfile() {
GitHubUserProfile gitHubUserProfile = getAPI().userOperations().getUserProfile();
if( gitHubUserProfile != null ){
User user = new User();
user.setProfileImageUrl( gitHubUserProfile.getProfileImageUrl() );
user.setId( Long.toString( gitHubUserProfile.getId() ) );
user.setName( gitHubUserProfile.getName() );
user.setEmail( gitHubUserProfile.getEmail() );
user.setFollowerList( getFollowerList());
return user;
}else{
throw new NullPointerException("GitHub 사용자 프로필이 존재하지 않습니다.");
}
}
@Override
public List<User> getFollowerList() {
String username = getAPI().userOperations().getUserProfile().getUsername();
List<GitHubUser> gitHubUserList = getAPI().userOperations().getFollowers(username);
return convertToUserFromGitHubUser (gitHubUserList);
}
@Override
public List<User> getFollowingList() {
String username = getAPI().userOperations().getUserProfile().getUsername();
List<GitHubUser> gitHubUserList = getAPI().userOperations().getFollowing(username);
return convertToUserFromGitHubUser (gitHubUserList);
}
private List<User> convertToUserFromGitHubUser(List<GitHubUser> gitHubUserList){
System.out.println("userList Size : " + gitHubUserList.size());
List<User> userList = new ArrayList<User>();
for(GitHubUser gitHubUser : gitHubUserList){
User user = new User();
user.setId( Long.toString( gitHubUser.getId() ) );
user.setName( gitHubUser.getName() );
user.setProfileImageUrl( gitHubUser.getAvatarUrl() );
userList.add( user );
}
return userList;
}
}
|
package view;
import model.Model;
import javax.swing.*;
import java.awt.*;
import static model.Model.*;
public class WinPanel extends JPanel {
private Model model;
private BaseObjectView background;
WinPanel(Model model) {
this.model = model;
background = new BaseObjectView("space.jpg");
}
@Override
public void paint(Graphics g) {
Graphics2D graphics2D = (Graphics2D)g;
render(graphics2D);
}
private void render(Graphics2D g) {
drawBackground(g);
drawText(g);
}
private void drawBackground(Graphics2D g) {
int windowWidth = (int) model.getWindowDimension().getWidth();
int windowHeight = (int) model.getWindowDimension().getHeight();
g.drawRect(0, 0, windowWidth, windowHeight);
int x = windowWidth - 2 * INDENT;
int y = windowHeight - 2 * INDENT - 25;
g.drawImage(background.getImage(), INDENT, INDENT, x, y, null);
}
private void drawText(Graphics2D g) {
int windowWidth = (int) model.getWindowDimension().getWidth();
int windowHeight = (int) model.getWindowDimension().getHeight();
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 90));
g.setColor(Color.RED);
g.drawString("You win with score = " + model.getScore() + "!", (int)(windowWidth / 6),
(int)(windowHeight / 2.2));
}
}
|
package com.infotec.ses;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Usuario {
private String nombre;
private String paterno;
private String materno;
private String calle;
private String telefono;
private String numero;
private String interior;
private String colonia;
private String municipio;
private String estado;
private String cp;
private int idUsuario;
private int id;
private String usr;
private String email;
public Usuario(){
this.setId(0);
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getPaterno() {
return paterno;
}
public void setPaterno(String paterno) {
this.paterno = paterno;
}
public String getMaterno() {
return materno;
}
public void setMaterno(String materno) {
this.materno = materno;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public int getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(int idUsuario) {
this.idUsuario = idUsuario;
}
public String getCalle() {
return calle;
}
public void setCalle(String calle) {
this.calle = calle;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getInterior() {
return interior;
}
public void setInterior(String interior) {
this.interior = interior;
}
public String getColonia() {
return colonia;
}
public void setColonia(String colonia) {
this.colonia = colonia;
}
public String getMunicipio() {
return municipio;
}
public void setMunicipio(String municipio) {
this.municipio = municipio;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getCp() {
return cp;
}
public void setCp(String cp) {
this.cp = cp;
}
@Override
public String toString() {
return "Usuario [id="+id+",usr="+usr+",idUsruario= "+idUsuario+", nombre= "+nombre+", paterno= "+paterno+", materno= "+materno+", telefono= "+telefono+", email="+ email + ", calle= "+calle+", numero= "+numero+", interior= "+interior+", colonia= "+colonia+", municipio= "+municipio+", estado= "+estado+", cp= "+cp+"]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsr() {
return usr;
}
public void setUsr(String usr) {
this.usr = usr;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
package org.fuserleer.ledger.messages;
public class AtomSubmissionMessage
{
}
|
package pro.eddiecache.ioc.context;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import pro.eddiecache.ioc.context.exception.BeanCreateException;
public class BeanCreatorImpl implements IBeanCreator
{
@Override
public Object createBeanUseDefaultConstruct(String className)
{
try
{
Class<?> clazz = Class.forName(className);
return clazz.newInstance();
}
catch (ClassNotFoundException e)
{
throw new BeanCreateException("class not found " + e.getMessage());
}
catch (Exception e)
{
throw new BeanCreateException(e.getMessage());
}
}
private Constructor<?> getConstructor(Class<?> clazz, Class<?>[] argsClass)
{
try
{
Constructor<?> constructor = clazz.getConstructor(argsClass);
return constructor;
}
catch (NoSuchMethodException e)
{
return null;
}
}
private Constructor<?> findConstructor(Class<?> clazz, Class<?>[] argsClass) throws NoSuchMethodException
{
Constructor<?> constructor = getConstructor(clazz, argsClass);
if (constructor == null)
{
Constructor<?>[] constructors = clazz.getConstructors();
for (Constructor<?> c : constructors)
{
Class<?>[] constructorArgsCLass = c.getParameterTypes();
if (constructorArgsCLass.length == argsClass.length)
{
if (isSameArgs(argsClass, constructorArgsCLass))
{
return c;
}
}
}
}
else
{
return constructor;
}
throw new NoSuchMethodException("could not find any constructor");
}
private boolean isSameArgs(Class<?>[] argsClass, Class<?>[] constructorArgsCLass)
{
for (int i = 0; i < argsClass.length; i++)
{
try
{
argsClass[i].asSubclass(constructorArgsCLass[i]);
if (i == (argsClass.length - 1))
{
return true;
}
}
catch (Exception e)
{
break;
}
}
return false;
}
@Override
public Object createBeanUseDefineConstruce(String className, List<Object> args)
{
Class<?>[] argsClass = getArgsClasses(args);
try
{
Class<?> clazz = Class.forName(className);
Constructor<?> constructor = findConstructor(clazz, argsClass);
return constructor.newInstance(args.toArray());
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
throw new BeanCreateException("class not found " + e.getMessage());
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
throw new BeanCreateException("no such constructor " + e.getMessage());
}
catch (Exception e)
{
e.printStackTrace();
throw new BeanCreateException(e.getMessage());
}
}
private Class<?> getClass(Object obj)
{
if (obj instanceof Integer)
{
return Integer.TYPE;
}
else if (obj instanceof Boolean)
{
return Boolean.TYPE;
}
else if (obj instanceof Long)
{
return Long.TYPE;
}
else if (obj instanceof Short)
{
return Short.TYPE;
}
else if (obj instanceof Double)
{
return Double.TYPE;
}
else if (obj instanceof Float)
{
return Float.TYPE;
}
else if (obj instanceof Character)
{
return Character.TYPE;
}
else if (obj instanceof Byte)
{
return Byte.TYPE;
}
return obj.getClass();
}
private Class<?>[] getArgsClasses(List<Object> args)
{
List<Class<?>> result = new ArrayList<Class<?>>();
for (Object arg : args)
{
result.add(getClass(arg));
}
Class<?>[] a = new Class[result.size()];
return result.toArray(a);
}
}
|
package health.linegym.com.linegym;
/**
* Created by innotree12 on 2017-01-24.
*/
public class LineGymApplication extends android.support.multidex.MultiDexApplication {
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package raytracing3;
/**
*
* @author ianmahoney
*/
public class Normal {
public double x, y, z;
public Normal() {
this.x = 0;
this.y = 0;
this.z = 0;
}
public Normal(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Normal Normalize() {
double magnitude = Math.sqrt(x * x + y * y + z * z);
x /= magnitude;
y /= magnitude;
z /= magnitude;
return this;
}
}
|
package id.ac.ub.ptiik.papps;
import id.ac.ub.ptiik.papps.adapters.NavigationMenuAdapter;
import id.ac.ub.ptiik.papps.base.AppFragment;
import id.ac.ub.ptiik.papps.base.NavMenu;
import id.ac.ub.ptiik.papps.base.User;
import id.ac.ub.ptiik.papps.helpers.SystemHelper;
import id.ac.ub.ptiik.papps.interfaces.AppInterface;
import id.ac.ub.ptiik.papps.interfaces.NavigationInterface;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class HomeActivity extends Activity implements AppInterface, NavigationInterface {
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private ArrayList<NavMenu> menus;
private NavMenu menuHome;
private NavMenu menuNews;
private NavMenu menuSchedule;
private NavMenu menuAgenda;
private NavMenu menuMessages;
private NavigationMenuAdapter navigationMenuAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_home);
mTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
this.initiateNavigationMenu();
// set up the drawer's list view with items and click listener
//mDrawerList.setAdapter(new ArrayAdapter<String>(this,
// R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
//invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
//getActionBar().setTitle(mDrawerTitle);
//invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
/*
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
*/
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
new Bundle();
NavMenu menu = this.menus.get(position);
FragmentManager fragmentManager = getFragmentManager();
Fragment newFragment = getFragmentManager().findFragmentByTag(menu.tag);
switch(menu.id) {
case NavMenu.MENU_SCHEDULE:
if(newFragment == null) {
newFragment = new ScheduleFragment();
}
break;
case NavMenu.MENU_NEWS:
if(newFragment == null) {
newFragment = new NewsFragment();
}
break;
case NavMenu.MENU_AGENDA:
if(newFragment == null) {
User u = SystemHelper.getSystemUser(this);
if(u == null) {
Toast.makeText(this, "You have to login to use this feature",
Toast.LENGTH_SHORT).show();
return;
}
newFragment = new CalendarFragment();
Bundle args = new Bundle();
args.putString("idKaryawan", u.karyawan_id);
newFragment.setArguments(args);
}
break;
case NavMenu.MENU_MESSAGES:
if(newFragment == null) {
MessagesFragment messagesFragment = new MessagesFragment();
messagesFragment.setOnNavigationCallback(this);
newFragment = messagesFragment;
}
break;
default:
if(newFragment == null) {
DashboardFragment fragment = new DashboardFragment();
fragment.setNavigationCallback(this);
newFragment = fragment;
}
}
fragmentManager.beginTransaction()
.replace(R.id.content_frame, newFragment, menu.tag).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
this.setTitle(this.menus.get(position).title);
NavMenu.activate(this.menus, position);
this.navigationMenuAdapter.notifyDataSetChanged();
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
/*
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = "Sapi";//getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
//((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
*/
private void initiateNavigationMenu() {
this.menus = new ArrayList<NavMenu>();
this.menuHome = new NavMenu(NavMenu.MENU_HOME, "Home", "Apps home screen", R.drawable.ic_places_1, AppFragment.FRAGMENT_TAG_HOME);
this.menuNews = new NavMenu(NavMenu.MENU_NEWS, "News", "News and Information", R.drawable.ic_communication_99, AppFragment.FRAGMENT_TAG_NEWS);
this.menuSchedule = new NavMenu(NavMenu.MENU_SCHEDULE, "Schedule", "Lecturing Schedules", R.drawable.ic_time_4, AppFragment.FRAGMENT_TAG_SCHEDULE);
this.menuAgenda = new NavMenu(NavMenu.MENU_AGENDA, "Agenda", "My Agenda", R.drawable.ic_time_3, AppFragment.FRAGMENT_TAG_AGENDA);
this.menuMessages = new NavMenu(NavMenu.MENU_MESSAGES, "Messages", "Incoming messages", R.drawable.ic_communication_61, AppFragment.FRAGMENT_TAG_MESSAGES);
this.menus.add(menuHome);
this.menus.add(menuNews);
this.menus.add(menuSchedule);
this.menus.add(menuAgenda);
this.menus.add(menuMessages);
this.navigationMenuAdapter = new NavigationMenuAdapter(this, this.menus);
this.mDrawerList.setAdapter(this.navigationMenuAdapter);
}
@Override
public void setContentFragment(android.support.v4.app.Fragment fragment,
String tag) {
// TODO Auto-generated method stub
}
@Override
public void setActionBarTitle(String title) {
// TODO Auto-generated method stub
}
@Override
public void OnNavigationMenuSelected(NavMenu menu) {
// TODO Auto-generated method stub
}
}
|
package com.meridal.examples.springbootmysql.mvc;
import com.meridal.examples.springbootmysql.domain.Recording;
import com.meridal.examples.springbootmysql.service.ExamplePublishingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Example Publishing Controller.
*/
@RestController
@RequestMapping("api/publish/{id}")
public class ExamplePublishingController {
@Autowired
public ExamplePublishingService service;
/**
* Publish a message.
* @param string
* @return Status
*/
@PostMapping
public String publishMessage(@PathVariable final String id, @RequestBody final Recording recording) {
this.service.publish(recording);
return "success";
}
}
|
import java.util.Arrays;
import java.util.Random;
import java.util.TreeMap;
public class KTCFRChanceFBRFIX {
public long nodecount = 0;
public int brcount = 0;
public double[][] brex = new double[4][200];
public int itf = 0;
public static final int PASS = 0, BET = 1, NUM_ACTIONS = 2;
public static final Random random = new Random();
public TreeMap<String, Node> nodeMap = new TreeMap<String, Node>();
class Node {
String infoSet;
double[] regretSum = new double[NUM_ACTIONS],
strategy = new double[NUM_ACTIONS],
strategySum = new double[NUM_ACTIONS];
private double[] getStrategy(double realizationWeight) {
double normalizingSum = 0;
for (int a = 0; a < NUM_ACTIONS; a++) {
strategy[a] = regretSum[a] > 0 ? regretSum[a] : 0;
normalizingSum += strategy[a];
}
for (int a = 0; a < NUM_ACTIONS; a++) {
if (normalizingSum > 0)
strategy[a] /= normalizingSum;
else
strategy[a] = 1.0 / NUM_ACTIONS;
strategySum[a] += realizationWeight * strategy[a];
}
return strategy;
}
public double[] getAverageStrategy() {
double[] avgStrategy = new double[NUM_ACTIONS];
double normalizingSum = 0;
for (int a = 0; a < NUM_ACTIONS; a++)
normalizingSum += strategySum[a];
for (int a = 0; a < NUM_ACTIONS; a++)
if (normalizingSum > 0)
avgStrategy[a] = strategySum[a] / normalizingSum;
else
avgStrategy[a] = 1.0 / NUM_ACTIONS;
return avgStrategy;
}
public String toString() {
return String.format("%4s: %s", infoSet, Arrays.toString(getAverageStrategy()));
}
}
public void train(int iterations, int decksize, int buckets) {
int[] cards = new int[decksize];
//int[] card = null;
long starttime = System.currentTimeMillis();
for (int i = 0; i < decksize; i++) {
cards[i]=i;
}
double util1 = 0;
for (int i = 0; i <= iterations; i++) {
for (int c1 = cards.length - 1; c1 > 0; c1--) {
int c2 = random.nextInt(c1 + 1);
int tmp = cards[c1];
cards[c1] = cards[c2];
cards[c2] = tmp;
}
util1 += cfr(cards, "", 1, 1, decksize, starttime, i, buckets, iterations);
}
System.out.println("Average game value: " + util1 / iterations);
long elapsedtime1 = System.currentTimeMillis() - starttime;
System.out.println("Total time: " + elapsedtime1);
for (int i = 0; i < brcount; i++) {
System.out.println("Exploitability: " + brex[0][i] + " at nodecount: " + brex[1][i] + " at time: " + brex[2][i] + " at iteration: " + brex[3][i]);
}
for (Node n : nodeMap.values())
System.out.println(n);
}
private double cfr(int[] cards, String history, double p0, double p1, int decksize, long starttime, int currit, int buckets, int iterations) {
//System.out.println(cards[0]);
//System.out.println(cards[1]);
//System.out.println(cards[2]);
int plays = history.length();
int player = plays % 2;
int opponent = 1 - player;
if (plays > 1) {
boolean terminalPass = history.charAt(plays - 1) == 'p';
boolean doubleBet = history.substring(plays - 2, plays).equals("bb");
boolean isPlayerCardHigher = cards[player] > cards[opponent];
if (terminalPass)
if (history.equals("pp"))
return isPlayerCardHigher ? 1 : -1;
else
return 1;
else if (doubleBet)
return isPlayerCardHigher ? 2 : -2;
}
String infoSet = history;
if (buckets > 0) {
int bucket = 0;
//for (int i = buckets; i => 1; i--){
for (int i = 0; i < buckets; i++){
if (cards[player] < (decksize/buckets)*(i+1)) {
bucket = i;
break;
}
}
infoSet = bucket + history;
}
else {
infoSet = cards[player] + history;
}
//System.out.println(infoSet);
nodecount = nodecount + 1;
if (currit == iterations) {
itf=itf+1;
}
if ((nodecount % 1000000) == 0)
System.out.println("nodecount: " + nodecount);
if ((itf==1) || (nodecount == 32) || (nodecount == 64) || (nodecount == 128) || (nodecount == 256) || (nodecount == 512) || (nodecount == 1024) || (nodecount == 2048) || (nodecount == 4096) || (nodecount == 8192) || (nodecount == 16384) || (nodecount == 32768) || (nodecount == 65536) || (nodecount == 131072) || (nodecount == 262144) || (nodecount == 524288) || (nodecount == 1048576) || (nodecount == 2097152) || (nodecount == 4194304) || (nodecount == 8388608) || (nodecount == 16777216) || (nodecount == 33554432) || (nodecount == 67108864) || (nodecount == 134217728) || (nodecount == 268435456) || (nodecount == 536870912) || (nodecount == 1073741824) || (nodecount == 2147483648l) || (nodecount == 4294967296l) || (nodecount == 8589934592l) || (nodecount == 17179869184l) || (nodecount == 100000) || (nodecount == 1000000) || (nodecount == 10000000) || (nodecount == 100000000) || (nodecount == 1000000000) || (nodecount % 100000000)==0) {//|| (nodecount == 10000000000)) {
double[] oppreach = new double[decksize];
double br0 = 0;
double br1 = 0;
for (int c=0; c < decksize; c++) {
for (int j = 0; j < decksize; j++) {
if (c==j)
oppreach[j] = 0;
else
oppreach[j] = 1./(oppreach.length-1);
}
System.out.println("br iter: " + brf(c, "", 0, oppreach, buckets));
br0 += brf(c, "", 0, oppreach, buckets);
}
for (int c=0; c < decksize; c++) {
for (int j = 0; j < decksize; j++) {
if (c==j)
oppreach[j] = 0;
else
oppreach[j] = 1./(oppreach.length-1);
}
//System.out.println("br iter: " + brf(c, "", 1, oppreach));
br1 += brf(c, "", 1, oppreach, buckets);
}
long elapsedtime = System.currentTimeMillis() - starttime;
System.out.println("br0 " + br0);
System.out.println("br1 " + br1);
//System.out.println("Average game value: " + util0 / currit); //empirical, should also get game value based on average strategy expected value
System.out.println("Exploitability: " + (br0+br1)/(2));
System.out.println("Number of nodes touched: " + nodecount);
System.out.println("Time elapsed in milliseconds: " + elapsedtime);
System.out.println("Iterations: " + currit);
//System.out.println("Iteration player: " + player_iteration);
brex[0][brcount] = (br0+br1)/(2);
brex[1][brcount] = nodecount;
brex[2][brcount] = elapsedtime;
brex[3][brcount] = currit;
brcount = brcount + 1;
}
Node node = nodeMap.get(infoSet);
if (node == null) {
node = new Node();
node.infoSet = infoSet;
nodeMap.put(infoSet, node);
}
double[] strategy = node.getStrategy(player == 0 ? p0 : p1);
double[] util = new double[NUM_ACTIONS];
double nodeUtil = 0;
for (int a = 0; a < NUM_ACTIONS; a++) {
String nextHistory = history + (a == 0 ? "p" : "b");
util[a] = player == 0
? - cfr(cards, nextHistory, p0 * strategy[a], p1, decksize, starttime, currit, buckets, iterations)
: - cfr(cards, nextHistory, p0, p1 * strategy[a], decksize, starttime, currit, buckets, iterations);
nodeUtil += strategy[a] * util[a];
}
for (int a = 0; a < NUM_ACTIONS; a++) {
double regret = util[a] - nodeUtil;
node.regretSum[a] += (player == 0 ? p1 : p0) * regret;
}
return nodeUtil;
}
private double brf(int player_card, String history, int player_iteration, double[] oppreach, int buckets)
{
// System.out.println("oppreach_toploop: " + oppreach[0] + " " + oppreach[1] + " " + oppreach[2]);
// same as in CFR, these evaluate how many plays and whose turn it is
// player is whose turn it is to act at the current action
// we know player based on history.length() since play switches after each action
int plays = history.length();
int player = plays % 2;
// check for terminal pass
// possible sequences in kuhn poker:
// pp (terminalpass), bb (doublebet), bp (terminalpass), pbp (terminalpass), pbb (doublebet)
if (plays > 1) {
double exppayoff = 0;
boolean terminalPass = history.charAt(plays - 1) == 'p'; //check for last action being a pass
boolean doubleBet = history.substring(plays - 2, plays).equals("bb");
if (terminalPass || doubleBet) { //hand is terminal
// System.out.println("opp reach: " + oppreach[0] + " " + oppreach[1] + " " + oppreach[2]);
// oppdist = normalize(oppreach)
double[] oppdist = new double[oppreach.length];
double oppdisttotal = 0;
for (int i = 0; i < oppreach.length; i++) {
oppdisttotal += oppreach[i]; //compute sum of distribution for normalizing later
}
/*if (terminalPass)
System.out.println("terminal pass history: " + history);
if (doubleBet)
System.out.println("terminal doublebet history: " + history); */
for (int i = 0; i < oppreach.length; i++) { //entire opponent distribution
oppdist[i] = oppreach[i]/oppdisttotal; //normalize opponent distribution
double payoff = 0;
boolean isPlayerCardHigher = player_card > i;
// System.out.println("opponent dist pre normalized: " + oppdist[i] + " for card: " + i + " (main card: " + ci + ")");
// System.out.println("current player: " + player);
// System.out.println("main player: " + player_iteration);
if (terminalPass) {
if (history.equals("pp")) {
//if (player == player_iteration)
payoff = isPlayerCardHigher ? 1 : -1;
//else
//payoff = isPlayerCardHigher ? -1 : 1;
}
else {
if (player == player_iteration)
payoff = 1;
else
payoff = -1;
}
//else {
//payoff = 1;
/* if (player == player_iteration)
return 1;
else
return -1;*/
}
//}
else if (doubleBet) {
//if (player == player_iteration)
payoff = isPlayerCardHigher ? 2 : -2;
//else
//payoff = isPlayerCardHigher ? -2 : 2;
}
exppayoff += oppdist[i]*payoff; //adding weighted payoffs
// }
}
//System.out.println("exppayoff: " + exppayoff);
return exppayoff;
}
}
/*
if (plays==0 && player == player_iteration) { //chance node main (i) player
//System.out.println("CHANCE NODE PLAYER i");
double brv = 0;
for (int a = 0; a < NUM_ACTIONS; a++) {
String nextHistory = history + (a == 0 ? "p" : "b");
brv += brf(player_card, nextHistory, player_iteration, oppreach);
}
return brv;
}
if (plays==0 && player != player_iteration) { //chance node opponent (-i) player
//System.out.println("CHANCE NODE PLAYER -i");
String dummyHistory = history + "p";
return brf(player_card, dummyHistory, player_iteration, oppreach); //give opponent player dummy card of 1 that is never used
}*/
//System.out.println("beginning of br iteration, player: " + player);
//System.out.println("beg of iteration oppreach: " + oppreach[0] + " " + oppreach[1] + " " + oppreach[2]);
double[] d = new double[NUM_ACTIONS]; //opponent action dist
d[0] = 0;
d[1] = 0;
//double[] new_oppreach = new double[oppreach.length];
double[] new_oppreach = new double[oppreach.length]; //new opponent card distribution
for (int i = 0; i < oppreach.length; i++) {
new_oppreach[i] = oppreach[i];
}
//System.out.println("new_oppreach_after_define: " + new_oppreach[0] + " " + new_oppreach[1] + " " + new_oppreach[2]);
double v = -100000; //initialize node utility
double[] util = new double[NUM_ACTIONS]; //initialize util value for each action
util[0] = 0;
util[1] = 0;
double[] w = new double[NUM_ACTIONS]; //initialize weights for each action
w[0] = 0;
w[1] = 0;
String infoSet = history;
for (int a = 0; a < NUM_ACTIONS; a++) {
//System.out.println("in loop action: " + a + ", oppreach: " + oppreach[0] + " " + oppreach[1] + " " + oppreach[2]);
if (player != player_iteration) {
//System.out.println("REGULAR NODE PLAYER -i");
for (int i = 0; i < oppreach.length; i++) {
if (buckets > 0) {
int bucket1 = 0;
//for (int j = buckets; j => 1; j--) {
for (int j = 0; j < buckets; j++) {
if (i < (oppreach.length/buckets)*(j+1)) {
bucket1 = j;
break;
}
}
infoSet = bucket1 + history;
}
//System.out.println("oppreach: " + i + " " + oppreach[i]);
//System.out.println("oppreach: " + oppreach.length);
else {
infoSet = i + history; //read info set, which is hand + play history
}
//System.out.println("infoset: " + infoSet);
//for (Node n : nodeMap.values())
//System.out.println(n);
Node node = nodeMap.get(infoSet);
if (node == null) {
node = new Node();
node.infoSet = infoSet;
nodeMap.put(infoSet, node);
System.out.println("infoset: " + infoSet);
}
double[] strategy = node.getAverageStrategy(); //read strategy (same as probability)
//System.out.println("oppreach: " + oppreach[i]);
new_oppreach[i] = oppreach[i]*strategy[a]; //update reach probability
//System.out.println("after newoppreach, original: " + oppreach[0] + " " + oppreach[1] + " " + oppreach[2]);
//System.out.println("strategy[a]: " + strategy[0] + " strategy[b] :" + strategy[1]);
w[a] += new_oppreach[i]; //sum weights over all possibilities of the new reach
//System.out.println("getting strategy and weight: " + w[a]);
}
}
//System.out.println("before brf call oppreach: " + oppreach[0] + " " + oppreach[1] + " " + oppreach[2]);
String nextHistory = history + (a == 0 ? "p" : "b");
//System.out.println("new_oppreach: " + new_oppreach[0] + " " + new_oppreach[1] + " " + new_oppreach[2]);
util[a] = brf(player_card, nextHistory, player_iteration, new_oppreach, buckets); //recurse for each action
if (player == player_iteration && util[a] > v) {
v = util[a]; //this action is better than previously best action
}
}
if (player != player_iteration) {
// D_(-i) = Normalize(w)
// d is action distribution that = normalized w
// System.out.println("weight 0: " + w[0]);
// System.out.println("weight 1: " + w[1]);
d[0] = w[0]/(w[0]+w[1]);
d[1] = w[1]/(w[0]+w[1]);
v = d[0]*util[0] + d[1]*util[1];
}
return v;
}
public static void main(String[] args) {
int iterations = 1000000000;
int decksize = 100;
int buckets = 25; //options: 0, 3, 10, 25
new KTCFRChanceFBRFIX().train(iterations, decksize, buckets);
}
} |
package com.techlab.student;
import static org.junit.Assert.*;
import org.junit.Test;
public class StudentTest {
Student p1 = new Student(101, "Pune", "10/5/97", "IT");
@Test
public void testGetbranch() {
String expected = "IT";
String actual = p1.getbranch();
assertEquals(expected, actual);
}
@Test
public void testGetId() {
int expected = 101;
int actual = p1.getId();
assertEquals(expected, actual);
}
@Test
public void testGetAddress() {
String expected = "Pune";
String actual = p1.getAddress();
assertEquals(expected, actual);
}
@Test
public void testGetDob() {
String expected = "10/5/97";
String actual = p1.getDob();
assertEquals(expected, actual);
}
}
|
package com.zhouyi.business.core.dao;
import com.zhouyi.business.core.model.CollectNodeResult;
import com.zhouyi.business.core.model.LedenCollectNode;
import com.zhouyi.business.core.vo.CollectNodeVo;
import com.zhouyi.business.core.vo.LedenCollectNodeVo;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface LedenCollectNodeMapper extends BuffBaseMapper<LedenCollectNode, LedenCollectNodeVo>{
List<CollectNodeResult> selectCollectNodeListByCategoryOrUnit(CollectNodeVo collectNodeVo);
List<CollectNodeResult> selectCollectNodeByUnitAndCategory(CollectNodeVo collectNodeVo);
Integer selectCollectNodeListCount(CollectNodeVo collectNodeVo);
Integer selectCollectNodeCountByUnitAndCategory(CollectNodeVo collectNodeVo);
} |
package com.bookapp.exception;
public class BookNotFoundException {
public BookNotFoundException(String message) {
super();
}
}
|
package com.gzpy.product.service.impl;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.gzpy.product.dao.ProductDao;
import com.gzpy.product.entity.Product;
import com.gzpy.product.service.ProductService;
@Service
@Transactional
public class ProductServiceImpl implements ProductService{
@Autowired
private ProductDao productDao;
@Override
public Page<Product> findProductBySearch(int currentPage, int pageSize,
final String pTitle, final String dStatus) {
Specification<Product> spec = new Specification<Product>() {
public Predicate toPredicate(Root<Product> root,
CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<String> delStatus = root.get("delStatus");
Path<String> productTitle = root.get("productTitle");
Predicate status = cb.like(delStatus,dStatus);
Predicate title = cb.like(productTitle, pTitle);
query.where(cb.and(status,title));
return query.getRestriction();
}
};
Pageable pb = new PageRequest(currentPage - 1, pageSize,
Sort.Direction.ASC, "productId");
return productDao.findAll(spec, pb);
}
@Override
public Product findProductById(String productId) {
return productDao.findOne(productId);
}
@Override
public List<Product> findProductByStatus(String pTilte, String delStatus) {
return productDao.findProductByStatus(pTilte, delStatus);
}
}
|
package com.ncda.dao.ext;
import com.ncda.entity.ext.ExtAccountBillUploadRecord;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public interface AcBilUploadRecordMapper {
/**
* 保存上传记录
* @param accountBillUploadRecord
* @return
*/
Integer saveUploadRecordData(ExtAccountBillUploadRecord accountBillUploadRecord);
/**
* 根据年月查询数量
* @param year
* @param month
* @return
*/
Integer selectCountByYearMonth(@Param("year") int year, @Param("month") int month);
/**
* 根据年月查询数据
* @param year
* @param month
* @return
*/
ExtAccountBillUploadRecord selectDataByYearMonth(@Param("year") int year, @Param("month") int month);
/**
* 根据年月删除旧数据(逻辑删除)
* @param year
* @param month
* @return
*/
Integer deleteOldDataByYearMonth(@Param("year") int year, @Param("month") int month);
/**
* 获取所有的年月
* @return
*/
List<ExtAccountBillUploadRecord> getAllYearAndMonth();
List<ExtAccountBillUploadRecord> getHistoryFileUploadTimeLine(ExtAccountBillUploadRecord accountBillUploadRecord);
List<ExtAccountBillUploadRecord> getCurrentFileUploadTimeLine();
Integer deletePrimaryData(ExtAccountBillUploadRecord accountBillUploadRecord);
Integer deleteHistoryData(String id);
} |
package vlad.fp.services.synchronous.rpc.client;
import vlad.fp.services.model.InvoiceID;
import vlad.fp.services.model.Report;
import vlad.fp.services.model.ReportID;
import vlad.fp.services.synchronous.api.ReportsService;
import vlad.fp.services.synchronous.rpc.Network;
public class ReportRpcClient implements ReportsService {
private final Network network;
private final ReportsService delegate;
public ReportRpcClient(Network network, ReportsService delegate) {
this.network = network;
this.delegate = delegate;
}
@Override
public ReportID generateBillingReport(InvoiceID invoice) {
return network.execute(() -> delegate.generateBillingReport(invoice));
}
@Override
public Report getReport(ReportID reportID) {
return network.execute(() -> delegate.getReport(reportID));
}
}
|
package workstarter.repository.search;
import workstarter.domain.Portfolio;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Spring Data Elasticsearch repository for the Portfolio entity.
*/
public interface PortfolioSearchRepository extends ElasticsearchRepository<Portfolio, Long> {
}
|
package asset;
import org.newdawn.slick.Music;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.Sound;
public class SoundManager {
public static Music maintheme, deepcavetheme, flairontheme,CrystalCave,jungleboss;
public static Sound pioche,blocbreak;
public SoundManager() {
// TODO Auto-generated constructor stub
}
public static void loadMusic() {
try {
CrystalCave = new Music("sound/CrystalCave.ogg");
maintheme = new Music("sound/Nervous_Bot.ogg");
pioche = new Sound("sound/pioche.ogg");
blocbreak = new Sound("sound/blocbreak.ogg");
deepcavetheme = new Music("sound/Necessary_Step_Back.ogg");
flairontheme = new Music("sound/yaron.ogg");
jungleboss = new Music("sound/Jungle-Boss.ogg");
} catch (SlickException e) {
e.printStackTrace();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.