text stringlengths 10 2.72M |
|---|
/**
* Package for junior.pack1.p4.ch2 Stream API. Переделать задачу #10038 "Банковские переводы" на Stream API.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 2018-12-11
* @since 2017-05-15
*/
package ru.job4j.bank; |
package com.fanfte.algorithm.jz;
/**
* Created by dell on 2018/7/18
**/
public class DeleteNode013 {
public static void main(String[] args) {
}
public ListNode deleteListNode(ListNode head, ListNode toBeDeleted) {
if(head == null || toBeDeleted == null) {
return null;
}
// 删除的是头节点
if(head == toBeDeleted) {
return head.next;
}
// 删除的是最后一个节点
if(toBeDeleted.next == null) {
ListNode temp = head;
while(temp.next != toBeDeleted) {
temp = temp.next;
}
temp.next = null;
} else {
//删除的不是最后一个节点
toBeDeleted.value = toBeDeleted.next.value;
toBeDeleted.next = toBeDeleted.next.next;
}
return head;
}
}
|
package com;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
public class IODemo {
public IODemo() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter file name:");
String fname=br.readLine();
File f =new File(fname);
if(f.exists())
{
BufferedReader fr=new BufferedReader(new FileReader(fname));
String line=null;
while((line=fr.readLine())!=null)
{
System.out.println(line);
}
fr.close();
}
else
{
System.out.println("file doesnot exists");
}
br.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
|
package Defect;
import java.util.*;
import java.util.Calendar;
/**
* Esta clase genera un Usuario
* @author Mauro Galvan
* @version 1.0
*
*/
public class Usuario {
//Campos de la clase
private String nombre;
private String apellido;
private String mail;
private String pais;
private Calendar nacimiento;
private boolean notificacion;
private ArrayList<String> paisesVisitados;
private double kmRecorridos;
private ArrayList<Viaje> misViajes;
private boolean premium;
/**
* Constructor de la clase Usuario
* @param nombre El nombre del usuario
* @param apellido El apellido del usuario
* @param mail El email del usuario
* @param pais Pais de donde se encuentra el usuario
* @param nacimiento Fecha de nacimiento del usuario
* @param notificacion Decicion si el usuario quiere recibir notificaciones
* @param paisesVisitados Lista de los paises que el Usuario visito
* @param kmRecorridos Total de kilometros que recorrio
* @param misViajes Lista de todos los viajes hechos
* @param premium Decisor de si un Usuario es premium o no
*/
public Usuario(String nombre, String apellido, String mail, String pais,Calendar nacimiento,boolean notificacion,boolean premium)
{
this.nombre=nombre;
this.apellido=apellido;
this.mail=mail;
this.pais=pais;
this.nacimiento=nacimiento;
this.notificacion=notificacion;
this.paisesVisitados= new ArrayList <String> ();
this.kmRecorridos=0;
this.misViajes= new ArrayList <Viaje>();
this.premium= premium;
}
/**
* Setea el nombre del Usuario
* @param nombre El nombre del usuario
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* Setea el apellido del usuario
* @param apellido El apellido del usuario
*/
public void setApellido(String apellido) {
this.apellido = apellido;
}
/**
* Setea el email del usuario
* @param mail El email del usuario
*/
public void setMail(String mail) {
this.mail = mail;
}
/**
* Setea el pais de donde se encuentra el usuario
* @param pais El pais de nacimiento del usuario
*/
public void setPais(String pais) {
this.pais = pais;
}
/**
* Setea la fecha de nacimiento del usuario
* @param nacimiento Fecha de nacimiento del usuario
*/
public void setNacimiento(Calendar nacimiento) {
this.nacimiento = nacimiento;
}
/**
* Setea si el usuario quiere recibir notificaciones
* @param notificacion Decicion si el usuario quiere recibir notificaciones
*/
public void setNotificacion(boolean notificacion) {
this.notificacion = notificacion;
}
/**
* Setea si el usuario es premium o no
* @param premium Decisor de si un Usuario es premium o no
*/
public void setPremium(boolean premium) {
this.premium = premium;
}
/**
* Metodo que devulve el nombre del usuario
* @return Nombre del usuario
*/
public String getNombre() {
return nombre;
}
/**
* Metodo que devulve el apellido del usuario
* @return Apellido del usuario
*/
public String getApellido() {
return apellido;
}
/**
* Metodo que devulve el mail del usuario
* @return Mail del usuario
*/
public String getMail() {
return mail;
}
/**
* Metodo que devulve el pais del usuario
* @return pais del usuario
*/
public String getPais() {
return pais;
}
/**
* Metodo que devulve la fecha de nacimiento del usuario
* @return Nacimiento del usuario del tipo Calendar
*/
public Calendar getNacimiento() {
return nacimiento;
}
/**
* Metodo que devulve si el usuario quiere recibir notificaciones
* @return true or false depende que tenga notifiacion
*/
public boolean isNotificacion() {
return notificacion;
}
/**
* Metodo que devulve la lista de los paises visitados del usuario
* @return Lista de los paises visitados
*/
public ArrayList<String> getPaisesVisitados() {
return paisesVisitados;
}
/**
* Metodo que devulve la cantidad de km recorridos por el usuario
* @return double con la cantidad de km
*/
public double getKmRecorridos() {
return kmRecorridos;
}
/**
* Metodo que devulve la lista de viajes del usuario
* @return la lista que contiene los viajes llamada misViajes
*/
public ArrayList<Viaje> getMisViajes() {
return misViajes;
}
/**
* Metodo que devulve si el usuario es premium
* @return true or false depende si el usuario es premium o no
*/
public boolean isPremium() {
return premium;
}
/**
* Agregar un pais visitado a la lista
* @param pais Pais visitado
*/
public void addPaisesVisitados(String pais) {
paisesVisitados.add(pais);
}
/**
* Agregar mas kilometros a los ya recorridos
* @param km Nuevos kilometros generados que se suman a los recorridos
*/
public void addKmRecorridos(double km) {
this.kmRecorridos+=km;
}
/**
* Agrega un nuevo viaje a la lista de misViajes
* @param nuevoViaje Contiene un nuevo viaje
*/
public void addMisViajes(Viaje nuevoViaje) {
misViajes.add(nuevoViaje);
}
/**
* Carga los datos de un viaje
* @param vueloIda contiene un Vuelo de ida
* @param vueloVuelta contiene un vuelo de vuelta
*/
public void cargarDatosViaje (Calendar diaIda, Calendar diaVuelta, String companiaIda, String companiaVuelta,
String numVueloIda, String numVueloVuelta, String ciudadOrigen, String ciudadDestino,String descripcion) {
TrasladoAereo vueloIda= new TrasladoAereo(numVueloIda, companiaIda, diaIda);
TrasladoAereo vueloVuelta= new TrasladoAereo(numVueloVuelta, companiaVuelta, diaVuelta);
String origen= ciudadOrigen;
String destino= ciudadDestino;
Viaje nuevoViaje= new Viaje (origen, destino, vueloIda, vueloVuelta, descripcion);
misViajes.add(nuevoViaje);
}
/**
*
* @param viaje
* @return Mapa, si return Null controlar error.
*/
public Mapa crearMapa(Viaje viaje)
{
if(this.existeViaje(viaje))
{
Mapa m = viaje.crearMapaViaje();
return m;
}
return null;
}
/**
*
* @param viaje
* @return Mapa, si return Null controlar error.
*/
public MapaPremium crearMapaPremium(Viaje viaje)
{
if(premium)
{
if(this.existeViaje(viaje))
{
MapaPremium m = viaje.crearMapaPremium();
return m;
}
}
return null;
}
private boolean existeViaje(Viaje viaje)
{
int i = 0;
while(i < misViajes.size())
{
if(viaje.equals(misViajes.get(i)))
{
return true;
}
}
return false;
}
public String toString() {
String retorno = "Nombre: "+this.nombre+"\nApellido: "+this.apellido+"\nMail: "+this.mail+"\nPais: "+this.pais+
"\nFecha Nacimiento: "+this.nacimiento.get(Calendar.DAY_OF_MONTH)+"/"+this.nacimiento.get(Calendar.MONTH)+"/"+this.nacimiento.get(Calendar.YEAR);
return retorno;
}
} //Cierre de clase
|
package edu.neu.ccs.cs5010;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by wenfei on 11/13/17.
*/
public class SecureBankVerificationSimulatorTest {
SecureBankVerificationSimulator secureBankVerificationSimulator;
@Before
public void setUp() throws Exception {
secureBankVerificationSimulator = new SecureBankVerificationSimulator();
}
@Test
public void simulate() throws Exception {
String[] testLine = {"1000", "500", "0.1", "outputTest.csv"};
secureBankVerificationSimulator.simulate(testLine);
}
@Test
public void main() throws Exception {
}
} |
package fr.maBanque.dao;
import java.io.Serializable;
import org.springframework.data.jpa.repository.JpaRepository;
import fr.maBanque.entities.Client;
public interface ClientRepository extends JpaRepository<Client, Long>{
}
|
package com.aisino.invoice.xtsz.po;
import java.util.List;
/**
* @ClassName: FwkpModCustom
* @Description:
* @author: ZZc
* @date: 2016年10月10日 下午8:05:57
* @Copyright: 2016 航天信息股份有限公司-版权所有
*
*/
public class FwkpModCustom extends FwkpMod {
private List<FwkpModCustomChild> fwkpModCustomChild;
private int fmark;
private boolean fchecked;
private String errCode;
private String errMsg;
public List<FwkpModCustomChild> getFwkpModCustomChild() {
return fwkpModCustomChild;
}
public void setFwkpModCustomChild(List<FwkpModCustomChild> fwkpModCustomChild) {
this.fwkpModCustomChild = fwkpModCustomChild;
}
public int getFmark() {
return fmark;
}
public void setFmark(int fmark) {
this.fmark = fmark;
}
public boolean isFchecked() {
return fchecked;
}
public void setFchecked(boolean fchecked) {
this.fchecked = fchecked;
}
public String getErrCode() {
return errCode;
}
public void setErrCode(String errCode) {
this.errCode = errCode;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
@Override
public String toString() {
return "FwkpModCustom [fwkpModCustomChild=" + fwkpModCustomChild
+ ", fmark=" + fmark + ", fchecked=" + fchecked + "]";
}
} |
/*
* 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 com.csci360.alarmclock;
/**
*
* @author baldy
*/
public class AlarmController {
Alarm alarm = new Alarm();
public String getAlarmTime(){
return alarm.getTimeOfAlarm();
}
public void setAlarmTime(String time){
alarm.setTimeOfAlarm(time);
}
public boolean isStockAlarm(){
return alarm.shouldSoundAlert();
}
public void setStockAlarm(boolean b){
alarm.setStockAlert(b);
}
public void soundAlert(){
alarm.soundAlert();
}
}
|
/*
* Created on 13/10/2008
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.citibank.ods.modules.product.prodassettype.functionality;
import java.math.BigInteger;
import java.util.Date;
import org.apache.struts.action.ActionForm;
import com.citibank.ods.common.functionality.ODSMovementDetailFnc;
import com.citibank.ods.common.functionality.valueobject.BaseFncVO;
import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO;
import com.citibank.ods.common.util.ODSConstraintDecoder;
import com.citibank.ods.entity.pl.TplProdAssetTypeEntity;
import com.citibank.ods.entity.pl.TplProdAssetTypeHistEntity;
import com.citibank.ods.entity.pl.TplProdAssetTypeMovEntity;
import com.citibank.ods.entity.pl.valueobject.BaseTplProdAssetTypeEntityVO;
import com.citibank.ods.entity.pl.valueobject.TplProdAssetTypeMovEntityVO;
import com.citibank.ods.modules.product.prodassettype.form.ProdAssetTypeMovementDetailForm;
import com.citibank.ods.modules.product.prodassettype.functionality.valueobject.ProdAssetTypeMovementDetailFncVO;
import com.citibank.ods.persistence.pl.dao.TplProdAssetTypeDAO;
import com.citibank.ods.persistence.pl.dao.TplProdAssetTypeHistDAO;
import com.citibank.ods.persistence.pl.dao.TplProdAssetTypeMovDAO;
import com.citibank.ods.persistence.pl.dao.TplProductDAO;
import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory;
import com.citibank.ods.persistence.pl.dao.BaseTplProdAssetTypeDAO;
import com.citibank.ods.entity.pl.valueobject.TplProdAssetTypeEntityVO;
/**
* @author lfabiano
* @since 13/10/2008
*/
public class ProdAssetTypeMovementDetailFnc extends
BaseProdAssetTypeDetailFnc implements ODSMovementDetailFnc
{
/**
* Retorna o DAO utilizado pelo método load da super classe
*
* @see com.citibank.ods.modules.product.productfamilyprvt.functionality.BaseProductFamilyPrvtDetailFnc#getDAO()
*/
protected BaseTplProdAssetTypeDAO getDAO()
{
return ODSDAOFactory.getInstance().getTplProdAssetTypeMovDAO();
}
/**
* Retorna uma instância do FncVO
*/
public BaseFncVO createFncVO()
{
return new ProdAssetTypeMovementDetailFncVO();
}
/**
* Realiza a atualização de um registro de movimento
*/
public void update( BaseFncVO fncVO_ )
{
validateUpdate( fncVO_ );
if ( !fncVO_.hasErrors() )
{
ProdAssetTypeMovementDetailFncVO movementDetailFncVO = ( ProdAssetTypeMovementDetailFncVO ) fncVO_;
BaseTplProdAssetTypeEntityVO baseTplProdAssetTypeEntityVO = movementDetailFncVO.getBaseTplProdAssetTypeEntity().getData();
baseTplProdAssetTypeEntityVO.setLastUpdDate( new Date() );
baseTplProdAssetTypeEntityVO.setLastUpdUserId( fncVO_.getLoggedUser() != null
? fncVO_.getLoggedUser().getUserID()
: "" );
TplProdAssetTypeMovDAO prodAssetTypeMovDAO = ODSDAOFactory.getInstance().getTplProdAssetTypeMovDAO();
prodAssetTypeMovDAO.update( ( TplProdAssetTypeMovEntity ) movementDetailFncVO.getBaseTplProdAssetTypeEntity() );
}
}
/**
* Realiza a aprovação de um registro que está pendente de aprovação
*/
public void approve( BaseFncVO fncVO_ )
{
fncVO_.clearErrors();
validateApprove( fncVO_ );
if ( !fncVO_.hasErrors() )
{
// Instancia da Factory
ODSDAOFactory factory = ODSDAOFactory.getInstance();
// Declaracao dos DAOs
TplProdAssetTypeDAO tplProdAssetTypeDAO = factory.getTplProdAssetTypeDAO();
TplProdAssetTypeMovDAO tplProdAssetTypeMovDAO = factory.getTplProdAssetTypeMovDAO();
TplProdAssetTypeHistDAO tplProdAssetTypeHistDAO = factory.getTplProdAssetTypeHistDAO();
// FncVO do movimento
ProdAssetTypeMovementDetailFncVO movementDetailFncVO = ( ProdAssetTypeMovementDetailFncVO ) fncVO_;
super.loadProdAssetType( movementDetailFncVO );
// Entity do movimento
TplProdAssetTypeMovEntity prodAssetTypeMovEntity = ( TplProdAssetTypeMovEntity ) movementDetailFncVO.getBaseTplProdAssetTypeEntity();
// OpernCode
String opernCode = ( ( TplProdAssetTypeMovEntityVO ) prodAssetTypeMovEntity.getData() ).getOpernCode();
TplProdAssetTypeEntity tplProdAssetTypeEntity = new TplProdAssetTypeEntity(prodAssetTypeMovEntity,
new Date(),
fncVO_.getLoggedUser().getUserID(),
TplProdAssetTypeEntity.C_REC_STAT_CODE_ACTIVE );
// Verifica qual operacao está sendo aprovada
if ( TplProdAssetTypeMovEntity.C_OPERN_CODE_DELETE.equals( opernCode ) )
{
//setar estatus como inativo
TplProdAssetTypeEntityVO tplProdutFamilyPrvtEntityVO = ( TplProdAssetTypeEntityVO ) tplProdAssetTypeEntity.getData();
tplProdutFamilyPrvtEntityVO.setRecStatCode( TplProdAssetTypeEntity.C_REC_STAT_CODE_INACTIVE );
}
if ( tplProdAssetTypeDAO.exists( tplProdAssetTypeEntity ) )
{
TplProdAssetTypeEntity tplProdAssetTypeEntityOld = ( TplProdAssetTypeEntity ) tplProdAssetTypeDAO.find( tplProdAssetTypeEntity );
TplProdAssetTypeHistEntity prodAssetTypeHistEntity = new TplProdAssetTypeHistEntity(
tplProdAssetTypeEntityOld,
new Date() );
tplProdAssetTypeHistDAO.insert( prodAssetTypeHistEntity );
tplProdAssetTypeDAO.update( tplProdAssetTypeEntity );
}
else
{
tplProdAssetTypeDAO.insert( tplProdAssetTypeEntity );
}
tplProdAssetTypeMovDAO.delete( prodAssetTypeMovEntity );
}
}
/**
* Rejeita uma ação que está pendente de aprovação
*/
public void reprove( BaseFncVO fncVO_ )
{
fncVO_.clearErrors();
// realiza validação
validateReprove( fncVO_ );
if ( !fncVO_.hasErrors() )
{
ProdAssetTypeMovementDetailFncVO movementDetailFncVO = ( ProdAssetTypeMovementDetailFncVO ) fncVO_;
TplProdAssetTypeMovEntity prodAssetTypeMovEntity = ( TplProdAssetTypeMovEntity ) movementDetailFncVO.getBaseTplProdAssetTypeEntity();
TplProdAssetTypeMovDAO prodAssetTypeMovDAO = ODSDAOFactory.getInstance().getTplProdAssetTypeMovDAO();
prodAssetTypeMovDAO.delete( prodAssetTypeMovEntity );
}
}
/**
* Realiza as Validações - Update
*/
public void validateUpdate( BaseFncVO fncVO_ )
{
ProdAssetTypeMovementDetailFncVO prodAssetTypeMovementDetailFncVO = ( ProdAssetTypeMovementDetailFncVO ) fncVO_;
TplProdAssetTypeMovEntityVO ProdAssetTypeMovEntityVO = ( TplProdAssetTypeMovEntityVO ) prodAssetTypeMovementDetailFncVO.getBaseTplProdAssetTypeEntity().getData();
//testar usuário
if (( !prodAssetTypeMovementDetailFncVO.getLoggedUser().getUserID().equals( ProdAssetTypeMovEntityVO.getLastUpdUserId() ) ) )
{
prodAssetTypeMovementDetailFncVO.addError( BaseODSFncVO.C_ERROR_APPROVAL_UPDATE_USER_NOT_AUTHORIZED );
}
else
{
// testar campos obrigatórios
if ( ProdAssetTypeMovEntityVO.getProdAssetTypeText() == null
|| ProdAssetTypeMovEntityVO.getProdAssetTypeText().equals( "" ) )
{
prodAssetTypeMovementDetailFncVO.addError(BaseODSFncVO.C_ERROR_MANDATORY_FIELD,
C_PROD_ASSETTYPE_TEXT );
}
if ( prodAssetTypeMovementDetailFncVO.getBaseTplProdAssetTypeEntity().getData().getProdSubAssetCode() == null
|| prodAssetTypeMovementDetailFncVO.getBaseTplProdAssetTypeEntity().getData().getProdSubAssetCode().equals("") )
{
fncVO_.addError( BaseODSFncVO.C_ERROR_MANDATORY_FIELD, C_PROD_SUB_ASSET_TEXT );
}
}
// Se opernCode = Delete, adicionar erros
if ( !fncVO_.hasErrors() )
{
TplProdAssetTypeMovDAO tplProdAssetTypeMovDAO = ODSDAOFactory.getInstance().getTplProdAssetTypeMovDAO();
TplProdAssetTypeMovEntity tplProdAssetTypeMovEntity = ( TplProdAssetTypeMovEntity ) tplProdAssetTypeMovDAO.find( prodAssetTypeMovementDetailFncVO.getBaseTplProdAssetTypeEntity() );
String opernCode = ( ( TplProdAssetTypeMovEntityVO ) tplProdAssetTypeMovEntity.getData() ).getOpernCode();
if ( TplProdAssetTypeMovEntity.C_OPERN_CODE_DELETE.equals( opernCode ) )
{
prodAssetTypeMovementDetailFncVO.addError( ProdAssetTypeMovementDetailFncVO.C_ERROR_CANNOT_UPD_DELETE_IN_MOVEMENT );
}
}
}
/**
* Realiza as validações - Approve
*/
public void validateApprove( BaseFncVO fncVO_ )
{
ProdAssetTypeMovementDetailFncVO ProdAssetTypeMovementDetailFncVO = ( ProdAssetTypeMovementDetailFncVO ) fncVO_;
TplProdAssetTypeMovEntityVO ProdAssetTypeMovEntityVO = ( TplProdAssetTypeMovEntityVO ) ProdAssetTypeMovementDetailFncVO.getBaseTplProdAssetTypeEntity().getData();
//testar usuário
if ( ProdAssetTypeMovementDetailFncVO.getLoggedUser().getUserID().equals(
ProdAssetTypeMovEntityVO.getLastUpdUserId() ) )
{
fncVO_.addError( BaseODSFncVO.C_ERROR_APPROVAL_USER_NOT_AUTHORIZED );
}
}
/**
* Realiza as validações - Reprove
*/
public void validateReprove( BaseFncVO fncVO_ )
{
// TODO Auto-generated method stub
}
/**
* Carregamentos iniciais - Update
*/
public void loadForUpdate( BaseFncVO fncVO_ )
{
ProdAssetTypeMovementDetailFncVO movementDetailFncVO = ( ProdAssetTypeMovementDetailFncVO ) fncVO_;
if(movementDetailFncVO.isRefreshAssetCode()){
if(movementDetailFncVO.getBaseTplProdAssetTypeEntity().getData().getProdSubAssetCode()!= null){
super.loadAssetBySubAsset(movementDetailFncVO);
}
else{
movementDetailFncVO.getBaseTplProdAssetTypeEntity().getData().setProdAssetCode(null);
}
}
else{
super.loadProdAssetType( movementDetailFncVO );
super.loadDomains(movementDetailFncVO);
}
}
/**
* Carregamentos iniciais - Approve
*/
public void loadForApprove( BaseFncVO fncVO_ )
{
ProdAssetTypeMovementDetailFncVO movementDetailFncVO = ( ProdAssetTypeMovementDetailFncVO ) fncVO_;
super.loadProdAssetType( movementDetailFncVO );
super.loadDomains(movementDetailFncVO);
}
/**
* Carregamentos iniciais - Detail
*/
public void loadForConsult( BaseFncVO fncVO_ )
{
// TODO Auto-generated method stub
}
/**
* Inserindo as informações no Form a partir do FncVO - Campos específicos
*/
public void updateFormFromFncVO( ActionForm form_, BaseFncVO fncVO_ )
{
super.updateFormFromFncVO( form_, fncVO_ );
//Acertando os Tipos
ProdAssetTypeMovementDetailForm prodAssetTypeForm = ( ProdAssetTypeMovementDetailForm ) form_;
ProdAssetTypeMovementDetailFncVO prodAssetTypeFncVO = ( ProdAssetTypeMovementDetailFncVO ) fncVO_;
//Atualizando os dados: FncVO -> Form
TplProdAssetTypeMovEntityVO prodAssetTypeMovEntityVO = ( TplProdAssetTypeMovEntityVO ) prodAssetTypeFncVO.getBaseTplProdAssetTypeEntity().getData();
String opernCode = prodAssetTypeMovEntityVO.getOpernCode();
if ( opernCode != null && !"".equals( opernCode ) )
{
prodAssetTypeForm.setOpernCode( ODSConstraintDecoder.decodeOpern( opernCode ) );
}
}
} |
import ca.roumani.i2c.MPro;
import ca.roumani.i2c.MPro;
import static org.junit.Assert.*;
public class MCalcPro_ActivityTest {
public static void paymentTest() {
MPro mp = new MPro();
mp.setInterest("2");
mp.setAmortization("20");
mp.setPrinciple("400000");
String monthlyPayment = mp.computePayment("%,.2f");
double mPayment = Double.parseDouble(mp.computePayment(".2f"));
int dollars = (int) (Math.floor(mPayment));
System.out.println(dollars);
}
public static void main(String[] args) {
MPro mp = new MPro();
mp.setInterest("2");
mp.setAmortization("20");
mp.setPrinciple("400000");
String monthlyPayment = mp.computePayment("%,.2f");
double mPayment = Double.parseDouble(mp.computePayment(".2f"));
int dollars = (int) (Math.floor(mPayment));
System.out.println(dollars);
}
} |
package info.datacluster.crawler;
public class PropertyConstant {
public static String ZOOKEEPER_SPLIT = "/";
/**
* 存放提交的任务信息
*/
public static String ZOOKEEPER_TASK_PATH = "/crawler/task";
/**
* 存放每个server的信息
*/
public static String ZOOKEEPER_CRAWLER= "/crawler/meta/server";
/**
* 存放运行的任务信息
*/
public static String ZOOKEEPER_TASK_INFO = "/crawler/meta/task";
/**
* 获取任务的独占锁
*/
public static String ZOOKEEPER_TASK_LOCK = "/crawler/lock/";
}
|
package com.example.todo.test;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.todo.R;
public class AddNewData extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addnewdata);
}
}
|
// https://leetcode.com/problems/product-of-array-except-self/
// #array
class Solution {
/*
product prefix and suffix (first).
*/
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] output = new int[n];
output[n - 1] = 1;
int pre = output[n - 1];
for (int i = n - 2; i >= 0; i--) {
output[i] = nums[i + 1] * pre;
pre = output[i];
}
pre = 1;
for (int i = 0; i < n; i++) {
output[i] *= pre;
pre *= nums[i];
}
return output;
}
}
|
package com.amunga.david.diabeat.common;
/**
* Created by amush on 04-Nov-17.
*/
public class Common {
}
|
package net.mapthinks.repository.search;
import net.mapthinks.domain.CompanyUser;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Spring Data Elasticsearch repository for the CompanyUser entity.
*/
public interface CompanyUserSearchRepository extends ElasticsearchRepository<CompanyUser, Long> {
}
|
module mod.z_bottom {
requires mod.layer;
requires mod.z_middle;
exports pkgz.bottom;
}
|
/*
* 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 com.santana.controller;
import com.santana.model.Alumno;
import com.santana.model.Grupo;
import com.santana.service.AlumnoService;
import com.santana.service.GrupoService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author JASMIN-SOMA
*/
@Controller
@RequestMapping("/")
public class ControllerAlumno {
@Autowired
AlumnoService alumnoService;
@Autowired
GrupoService grupoService;
@RequestMapping(value = {"/", "bienvenido"}, method = RequestMethod.GET)
public String initSistema(ModelMap model) {
return "bienvenido";
}
@RequestMapping(value = "/alumno", method = RequestMethod.GET)
public String alumno(ModelMap model) {
List<Grupo> lGrupo = grupoService.showGrupo();
model.addAttribute("lGrupo", lGrupo);
List<Alumno> lAlumno = alumnoService.showAlumno();
model.addAttribute("lAlumno", lAlumno);
return "alumno";
}
@RequestMapping(value = "/alumno/agregarAlumno", method = RequestMethod.POST)
public @ResponseBody
String agregarAlumno(@RequestParam(value = "datos[]") String datos[]) {
Alumno alumno = new Alumno();
alumno.setCveAlu(datos[0]);
alumno.setNomAlu(datos[1]);
alumno.setEdaAlu(Integer.parseInt(datos[2]));
Grupo lGrupo =grupoService.buscaId(datos[3]);
alumno.setCveGru(lGrupo);
//guarda en arreglo datos
if (alumnoService.save(alumno)) {
return "exito";
} else {
return "error";
}
}
//Metodo para actualizar Delito
@RequestMapping(value = "/alumno/actualizarAlumno", method = RequestMethod.POST)
public @ResponseBody
String actualizarDelito(@RequestParam(value = "datos[]") String datos[]) {
List<Alumno> lAlumno = alumnoService.showAlumno();
if (!lAlumno.isEmpty()) {
for (Alumno alumno : lAlumno) {
//obtiene el nombre del delito
if (alumno.getCveAlu().equals(datos[0])) {
alumno.setNomAlu(datos[1]);
alumno.setEdaAlu(Integer.parseInt(datos[2]));
Grupo lGrupo =grupoService.buscaId(datos[3]);
alumno.setCveGru(lGrupo);
if (alumnoService.update(alumno)) {
return "exito";
} else {
return "error";
}
}
}
}
return "alumno";
}
//Metodo para eliminar un Delito
@RequestMapping(value = "/alumno/eliminarAlumno", method = RequestMethod.POST)
public @ResponseBody
String eliminarAlumno(@RequestParam(value = "datos[]") String datos[]) {
List<Alumno> lAlumno = alumnoService.showAlumno();
if (!lAlumno.isEmpty()) {
for (Alumno alumno : lAlumno) {
//obtiene el id del delitoa a eliminar
String cveAlu = datos[0];
if (alumno.getCveAlu().equals(cveAlu)) {
alumno.setCveAlu(datos[0]);
if (alumnoService.delete(cveAlu)) {
return "exito";
} else {
return "error";
}
}
}//end for
}//si no esta vacia la lista de delitos
return "alumno";
}
@RequestMapping(value = "/grupo", method = RequestMethod.GET)
public String grupo(ModelMap model) {
List<Grupo> lGrupo = grupoService.showGrupo();
model.addAttribute("lGrupo", lGrupo);
return "grupo";
}
@RequestMapping(value = "/grupo/agregarGrupo", method = RequestMethod.POST)
public @ResponseBody
String agregarGrupo(@RequestParam(value = "datos[]") String datos[]) {
Grupo grupo = new Grupo();
grupo.setCveGru(datos[0]);
grupo.setNomGru(datos[1]);
if (grupoService.save(grupo)) {
return "exito";
} else {
return "error";
}
}
//Metodo para actualizar Delito
@RequestMapping(value = "/grupo/actualizarGrupo", method = RequestMethod.POST)
public @ResponseBody
String actualizarGrupo(@RequestParam(value = "datos[]") String datos[]) {
List<Grupo> lGrupo = grupoService.showGrupo();
if (!lGrupo.isEmpty()) {
for (Grupo grupo : lGrupo) {
//obtiene el nombre del delito
if (grupo.getCveGru().equals(datos[0])) {
grupo.setNomGru(datos[1]);
if (grupoService.update(grupo)) {
return "exito";
} else {
return "error";
}
}
}
}
return "grupo";
}
//Metodo para eliminar un Delito
@RequestMapping(value = "/grupo/eliminarGrupo", method = RequestMethod.POST)
public @ResponseBody
String eliminarGrupo(@RequestParam(value = "datos[]") String datos[]) {
List<Grupo> lGrupo = grupoService.showGrupo();
if (!lGrupo.isEmpty()) {
for (Grupo grupo : lGrupo) {
//obtiene el id del delitoa a eliminar
String cveGru = datos[0];
if (grupo.getCveGru().equals(cveGru)) {
grupo.setCveGru(datos[0]);
if (grupoService.delete(cveGru)) {
return "exito";
} else {
return "error";
}
}
}//end for
}//si no esta vacia la lista de delitos
return "grupo";
}
}
|
package com.example.balling;
import java.lang.reflect.Method;
import com.vaadin.util.ReflectTools;
public interface BallerTouchListener {
public static final Method OBJECT_TOUCHED = ReflectTools.findMethod(
BallerTouchListener.class, "objectTouched", BallerTouchEvent.class);
void objectTouched(BallerTouchEvent event);
}
|
package ru.shikhovtsev.driving;
public class Car implements Vehicle {
private int speed;
public Car(int speed) {
this.speed = speed;
}
@Override
public int getSpeed() {
return speed;
}
@Override
public double getFuelCost() {
throw new UnsupportedOperationException();
}
}
|
package com.sinoway.sinowayCrawer.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sinoway.sinowayCrawer.entitys.UserInfo;
import com.sinoway.sinowayCrawer.mapper.UserInfoMapper;
import com.sinoway.sinowayCrawer.service.LoginService;
import com.sinoway.sinowayCrawer.utils.MD5;
@Service("enterService")
public class LoginServiceImpl implements LoginService {
@Autowired
private UserInfoMapper userInfoMapper;
public UserInfo selectUserForLogin(String userName, String userPsw) {
UserInfo user = null;
Map<String, Object> pramMap = new HashMap<String, Object>();
pramMap.put("userName", userName);
List<UserInfo> users = userInfoMapper.selectUserByCondition(pramMap);
// 用户唯一,当用户存在且唯一时才能登陆成功。
if (!users.isEmpty() && users.size() == 1) {
user = users.get(0);
// 验证用户密码是否正确
if (!user.getPassword().equals(MD5.getMD5Str(userPsw))) {
//if (!user.getUserPsw().equals(userPsw)) {
user = null;
}
}
return user;
}
}
|
package com.xinhua.xdcb;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>nbPayerAccountVO complex type�� Java �ࡣ
*
* <p>����ģʽƬ��ָ�������ڴ����е�Ԥ�����ݡ�
*
* <pre>
* <complexType name="nbPayerAccountVO">
* <complexContent>
* <extension base="{http://ws.freshpolicysign.exports.bankpolicy.interfaces.nb.tunan.nci.com/}baseVO">
* <sequence>
* <element name="account" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="accountBank" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="accountId" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="accountName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="customerId" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="listId" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="nextAccount" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="nextAccountBank" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="nextAccountId" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="nextAccountName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="payMode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="payNext" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="payerId" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="policyCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="policyId" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "nbPayerAccountVO", propOrder = {
"account",
"accountBank",
"accountId",
"accountName",
"customerId",
"listId",
"nextAccount",
"nextAccountBank",
"nextAccountId",
"nextAccountName",
"payMode",
"payNext",
"payerId",
"policyCode",
"policyId"
})
public class NbPayerAccountVO
extends BaseVO
{
protected String account;
protected String accountBank;
protected BigDecimal accountId;
protected String accountName;
protected BigDecimal customerId;
protected BigDecimal listId;
protected String nextAccount;
protected String nextAccountBank;
protected BigDecimal nextAccountId;
protected String nextAccountName;
protected String payMode;
protected String payNext;
protected BigDecimal payerId;
protected String policyCode;
protected BigDecimal policyId;
/**
* ��ȡaccount���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getAccount() {
return account;
}
/**
* ����account���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAccount(String value) {
this.account = value;
}
/**
* ��ȡaccountBank���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getAccountBank() {
return accountBank;
}
/**
* ����accountBank���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAccountBank(String value) {
this.accountBank = value;
}
/**
* ��ȡaccountId���Ե�ֵ��
*
* @return
* possible object is
* {@link java.math.BigDecimal }
*
*/
public BigDecimal getAccountId() {
return accountId;
}
/**
* ����accountId���Ե�ֵ��
*
* @param value
* allowed object is
* {@link java.math.BigDecimal }
*
*/
public void setAccountId(BigDecimal value) {
this.accountId = value;
}
/**
* ��ȡaccountName���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getAccountName() {
return accountName;
}
/**
* ����accountName���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAccountName(String value) {
this.accountName = value;
}
/**
* ��ȡcustomerId���Ե�ֵ��
*
* @return
* possible object is
* {@link java.math.BigDecimal }
*
*/
public BigDecimal getCustomerId() {
return customerId;
}
/**
* ����customerId���Ե�ֵ��
*
* @param value
* allowed object is
* {@link java.math.BigDecimal }
*
*/
public void setCustomerId(BigDecimal value) {
this.customerId = value;
}
/**
* ��ȡlistId���Ե�ֵ��
*
* @return
* possible object is
* {@link java.math.BigDecimal }
*
*/
public BigDecimal getListId() {
return listId;
}
/**
* ����listId���Ե�ֵ��
*
* @param value
* allowed object is
* {@link java.math.BigDecimal }
*
*/
public void setListId(BigDecimal value) {
this.listId = value;
}
/**
* ��ȡnextAccount���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getNextAccount() {
return nextAccount;
}
/**
* ����nextAccount���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNextAccount(String value) {
this.nextAccount = value;
}
/**
* ��ȡnextAccountBank���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getNextAccountBank() {
return nextAccountBank;
}
/**
* ����nextAccountBank���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNextAccountBank(String value) {
this.nextAccountBank = value;
}
/**
* ��ȡnextAccountId���Ե�ֵ��
*
* @return
* possible object is
* {@link java.math.BigDecimal }
*
*/
public BigDecimal getNextAccountId() {
return nextAccountId;
}
/**
* ����nextAccountId���Ե�ֵ��
*
* @param value
* allowed object is
* {@link java.math.BigDecimal }
*
*/
public void setNextAccountId(BigDecimal value) {
this.nextAccountId = value;
}
/**
* ��ȡnextAccountName���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getNextAccountName() {
return nextAccountName;
}
/**
* ����nextAccountName���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNextAccountName(String value) {
this.nextAccountName = value;
}
/**
* ��ȡpayMode���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getPayMode() {
return payMode;
}
/**
* ����payMode���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPayMode(String value) {
this.payMode = value;
}
/**
* ��ȡpayNext���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getPayNext() {
return payNext;
}
/**
* ����payNext���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPayNext(String value) {
this.payNext = value;
}
/**
* ��ȡpayerId���Ե�ֵ��
*
* @return
* possible object is
* {@link java.math.BigDecimal }
*
*/
public BigDecimal getPayerId() {
return payerId;
}
/**
* ����payerId���Ե�ֵ��
*
* @param value
* allowed object is
* {@link java.math.BigDecimal }
*
*/
public void setPayerId(BigDecimal value) {
this.payerId = value;
}
/**
* ��ȡpolicyCode���Ե�ֵ��
*
* @return
* possible object is
* {@link String }
*
*/
public String getPolicyCode() {
return policyCode;
}
/**
* ����policyCode���Ե�ֵ��
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPolicyCode(String value) {
this.policyCode = value;
}
/**
* ��ȡpolicyId���Ե�ֵ��
*
* @return
* possible object is
* {@link java.math.BigDecimal }
*
*/
public BigDecimal getPolicyId() {
return policyId;
}
/**
* ����policyId���Ե�ֵ��
*
* @param value
* allowed object is
* {@link java.math.BigDecimal }
*
*/
public void setPolicyId(BigDecimal value) {
this.policyId = value;
}
}
|
package cn.collin.controller;
import cn.collin.service.ConnDB;
import cn.collin.users.Users;
import cn.collin.utils.AnalyseData;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* Created by collin on 17-5-29.
*/
@RestController
@RequestMapping("/analyser")
public class Controller {
@Autowired
private ConnDB connDB;
JSONObject response = new JSONObject();
private String contractID;
private long startTime, endTime;
AnalyseData analyseData = new AnalyseData();
@RequestMapping(value = "/query", method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String set(@RequestBody Users users) {
contractID = users.getContractID();
startTime = users.getStartTime();
endTime = users.getEndTime();
List<Map<String, Object>> list = connDB.createRecord(startTime, endTime, contractID);
if (!list.isEmpty()){
response = analyseData.analyseData(list);
response.put("status","ok");
} else {
response.put("status", "fail");
}
/*for (Map<String, Object> map : list){
System.out.println(map.get("data"));
}*/
// String response = analyseData.analyseData(list);
// System.out.println(response);
return response.toString();
}
}
|
package com.davivienda.utilidades.edc;
/**
* TipoRegistro.java
*
* Fecha : 30/05/2007, 07:26:48 PM
* Descripción : Identificación de los tipos de registro del EDC
*
* @author : jjvargas
* @version : $Id$
*/
public enum DenominacionBillete {
Diez('B',"10000"),
Veinte('C', "20000"),
Cincuenta('E', "50000");
public char codigo;
public String nombre;
/**
* Constructor de <code>TipoRegistro</code>.
*/
DenominacionBillete(char codigo, String nombre) {
this.codigo = codigo;
this.nombre = nombre;
}
public static DenominacionBillete getDenominacionBillete(char unChar) {
DenominacionBillete denominacionBilletes = DenominacionBillete.Diez ;
for (DenominacionBillete elem : DenominacionBillete.values()) {
if (elem.codigo == unChar){
denominacionBilletes = elem;
break;
}
}
return denominacionBilletes;
}
@Override
public String toString() {
return this.nombre;
}
}
|
package servlets;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.*;
import dao.Dao;
import dao.impl.DaoImpl;
import bean.User;
/**
* Servlet implementation class RegisterServlet
*
* @author Windsor
*/
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletContext sc;
private String realAvatarPath;
/**
* @see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
}
public void init(ServletConfig config) {
sc = config.getServletContext();
realAvatarPath = sc.getInitParameter("real_avatar_path");
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
int result = 0;
String message = "";
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = null;
String username = null;
String password = null;
String nickname = null;
try {
items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
if (item.getFieldName().equals("username")) {
username = item.getString("UTF-8");
} else if (item.getFieldName().equals("password")) {
password = item.getString("UTF-8");
} else if (item.getFieldName().equals("nickname")) {
nickname = item.getString("UTF-8");
}
}
}
} catch (FileUploadException e1) {
e1.printStackTrace();
result = 0;
message = "注册失败!服务器出现异常。";
}
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setNickname(nickname);
Dao<User> userDao = new DaoImpl<User>();
try {
List<User> userList = userDao.list("from User u where u.username='"
+ username + "'");
if (userList != null && userList.size() != 0) {
result = 0;
message = "注册失败!此用户名已被注册过了。";
} else {
userDao.create(user);
Iterator<FileItem> itr = items.iterator();
while (itr.hasNext()) {
FileItem item = itr.next();
if (item.isFormField()) {
System.out.println("Post:" + item.getFieldName()
+ ", Value:" + item.getString("UTF-8"));
} else if (item.getName() != null
&& !item.getName().equals("")) {
System.out.println("File Size:" + item.getSize());
System.out
.println("File Type:" + item.getContentType());
System.out.println("File Name:" + item.getName());
File file = new File(realAvatarPath, "u" + user.getId());
item.write(file);
}
}
result = 1;
message = "注册成功!";
}
} catch (FileUploadException e) {
e.printStackTrace();
result = 0;
message = "上传文件失败!";
} catch (Exception e) {
e.printStackTrace();
result = 0;
message = "注册失败!服务器出现异常。";
} finally {
JSONObject json = new JSONObject();
try {
json.put("result", result);
json.put("message", message);
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.write(json.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
|
package com.example.smartphonesensing2.activity_monitoring;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.smartphonesensing2.R;
import com.example.smartphonesensing2.db.TrainingTable;
import com.example.smartphonesensing2.db.TrainingTable.TrainingField;
public class TrainActivity extends FragmentActivity /* implements SensorEventListener */ {
// Flags to keep track the mode the app is running
// private boolean train;
// private String activity = "Stil";
// The rate at which the input is sampled
// private final static int SAMPLE_RATE = 1000;
// Reference to training table
/*private TrainingTable trainingTable;*/
// Variables to hold the values of the accelerometer
/*private float mlastX, mlastY, mlastZ;*/
// rowId of the last inserted data in db
/*private long rowId = 0;*/
// ???
/*private boolean mInitialized;*/
// ???
// private final float NOISE = (float)2.0;
/*private Sensor accelerometer;
private SensorManager sm;*/
@Override
public void onCreate(Bundle savedInstanceState) {
/*mInitialized = false;*/
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_activity_monitoring_train_layout);
/*sm = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
trainingTable = new TrainingTable(getApplicationContext());*/
}
//protected void onResume(){
//
// super.onResume();
// sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
//
//
// }
//
// protected void onPause(){
//
// super.onPause();
// sm.unregisterListener(this);
//
//
// }
//
//
// @Override
// public void onDestroy(){
// super.onDestroy();
// trainingTable.close();
// }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
/*
* This method trains the app for the still activity
public void trainStillActivity(View view){
Button b = (Button) view;
if(b.getText().equals("Start still")) {
// When this button is pressed to start the variable activity
// is set to "still" and the text shown in the button is changed to
// "Stop still"
train = true;
activity = "still";
b.setText("Stop still");
trainApp();
}
else {
// When this button is pressed to stop the variable activity
// is set to "none" and the text shown on the button is changed to
// "Start still"
train = false;
activity = "none";
b.setText("Start still");
}
}*/
/*
* This method trains the app for the walking activity
public void trainWalkActivity(View view) {
Button b = (Button) view;
if(b.getText().equals("Start walking")){
// When this button is pressed to start the variable activity
// is set to "walk" and the text shown on the button is changed to
// "Stop walking"
train = true;
activity = "walk";
b.setText("Stop walking");
trainApp();
}
else {
// When this button is pressed to stop the variable activity
// is set to "none" and the text shown on the button is changed to
// "Start walking"
train = false;
activity = "none";
b.setText("Start walking");
}
}*/
/*
* This method trains the app for the running activity
public void trainRunActivity(View view) {
Button b = (Button) view;
if(b.getText().equals("Start running")){
// When this button is pressed to start the variable activity
// is set to "run" and the text shown in the button is changed to
// "Stop running"
train = true;
activity = "run";
b.setText("Stop running");
trainApp();
}
else {
// When this button is pressed to stop the variable activity
// is set to "none" and the text shown on the button is changed to
// "Start running"
train = false;
activity = "none";
b.setText("Start running");
}
}*/
/*
* This method samples the input and stores them in the database.
private void trainApp() {
// debug.setText("MainActivity.trainApp()");
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
while(train){
storeTrainDataCoordinates();
// showCoordinates();
Thread.sleep(SAMPLE_RATE);
}
}
catch(InterruptedException ie) {
// TextView debug = (TextView) findViewById(R.id.debugView);
// debug.setText("MainActivity.trainApp() "+ ie.getMessage());
}
}
};
new Thread(runnable).start();
}*/
/*public void storeTrainDataCoordinates(){
// debug view
SQLiteDatabase db = null;
// Insert the values into the database
try{
db = trainingTable.getWritableDatabase();
// setup query
ContentValues values = new ContentValues();
values.put(TrainingField.FIELD_X, Float.toString(mlastX));
values.put(TrainingField.FIELD_Y, Float.toString(mlastY));
values.put(TrainingField.FIELD_Z, Float.toString(mlastZ));
values.put(TrainingField.FIELD_ACTIVITY, activity);
// send query to db server
rowId = db.insert(TrainingField.TABLE_NAME, null, values);
db.close();
}
catch(SQLException e){
}
}*/
// Delete all records of the training table
/*public void deleteTrainRecords(View view) {
SQLiteDatabase db = trainingTable.getWritableDatabase();
int n = db.delete(TrainingField.TABLE_NAME,
null,
null);
TextView showStoredCoordinates = (TextView) findViewById(R.id.showStoredCoordinates);
showStoredCoordinates.setText("Deleted " +n+ " records");
}*/
/*@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
TextView tvX = (TextView)findViewById(R.id.x_axis);
TextView tvY = (TextView)findViewById(R.id.y_axis);
TextView tvZ = (TextView)findViewById(R.id.z_axis);
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
if(!mInitialized)
{
mlastX = x ;
mlastY = y ;
mlastZ = z ;
tvX.setText(Float.toString(mlastX));
tvY.setText(Float.toString(mlastY));
tvZ.setText(Float.toString(mlastZ));
// mInitialized = true;
} else {
float deltaX = Math.abs(mlastX - x);
float deltaY = Math.abs(mlastY - y);
float deltaZ = Math.abs(mlastZ - z);
if(deltaX < NOISE) deltaX = (float)0.0;
if(deltaY < NOISE) deltaY = (float)0.0;
if(deltaZ < NOISE) deltaZ = (float)0.0;
mlastX = x ;
mlastY = y ;
mlastZ = z ;
tvX.setText(Float.toString(deltaX));
tvY.setText(Float.toString(deltaY));
tvZ.setText(Float.toString(deltaZ));
}
}*/
/*public void showCoordinates(){
try{
// Read values from database
TextView showStoredCoordinates = (TextView) findViewById(R.id.showStoredCoordinates);
SQLiteDatabase db = null;
db = trainingTable.getReadableDatabase();
String[] data = {
TrainingField.FIELD_ID,
TrainingField.FIELD_X,
TrainingField.FIELD_Y,
TrainingField.FIELD_Z,
TrainingField.FIELD_ACTIVITY
};
String where = TrainingField.FIELD_X +" = "+ mlastX +" AND "+
TrainingField.FIELD_Y +" = "+ mlastY +" AND "+
TrainingField.FIELD_Z +" = "+ mlastZ;
String orderBy = TrainingField.FIELD_ACTIVITY + " ASC";
Cursor c = db.query(TrainingField.TABLE_NAME, // Name of the table
data, // Fields to be fetched
null, // where-clause
null, // arguments for the where-clause
null, // groupBy
null, // having
null // orderBy
);
// Read the values in each field
c.moveToFirst();
String dataX = c.getString(c.getColumnIndex(TrainingField.FIELD_X));
String dataY = c.getString(c.getColumnIndex(TrainingField.FIELD_Y));
String dataZ = c.getString(c.getColumnIndex(TrainingField.FIELD_Z));
String dataActivity = c.getString(c.getColumnIndex(TrainingField.FIELD_ACTIVITY));
db.close();
// show the stored coordinates in db
showStoredCoordinates.setText("X: "+ dataX +
" Y: "+ dataY +
" Z: "+ dataZ +
" Activity "+ dataActivity);
}
catch(Exception e){
}
}*/
/*
* This function shows all records in the train table
*/
/*public void showTrainRecords(View view) {
// This view shows the coordinates stored in db
TextView showStoredCoordinates = (TextView) findViewById(R.id.showStoredCoordinates);
SQLiteDatabase db = trainingTable.getReadableDatabase();
String[] data = {
TrainingField.FIELD_ID,
TrainingField.FIELD_X,
TrainingField.FIELD_Y,
TrainingField.FIELD_Z,
TrainingField.FIELD_ACTIVITY
};
String where = TrainingField.FIELD_X +" = "+ mlastX +" AND "+
TrainingField.FIELD_Y +" = "+ mlastY +" AND "+
TrainingField.FIELD_Z +" = "+ mlastZ;
String orderBy = TrainingField.FIELD_ACTIVITY + " ASC";
Cursor c = db.query(TrainingField.TABLE_NAME, // Name of the table
data, // Fields to be fetched
null, // where-clause
null, // arguments for the where-clause
null, // groupBy
null, // having
null // orderBy
);
// Read the values in each field
String dataID;
String dataX;
String dataY;
String dataZ;
String dataActivity;
if(c.moveToFirst()) {
showStoredCoordinates.setText("");
do {
dataID = c.getString(c.getColumnIndex(TrainingField._ID));
dataX = c.getString(c.getColumnIndex(TrainingField.FIELD_X));
dataY = c.getString(c.getColumnIndex(TrainingField.FIELD_Y));
dataZ = c.getString(c.getColumnIndex(TrainingField.FIELD_Z));
dataActivity = c.getString(c.getColumnIndex(TrainingField.FIELD_ACTIVITY));
showStoredCoordinates.setText(showStoredCoordinates.getText()+
dataID + ":"+
" X: "+ dataX +
" Y: "+ dataY +
" Z: "+ dataZ +
" A: "+ dataActivity +"\n"
);
} while(c.moveToNext());
}
db.close();
}*/
}
|
package nightgames.skills;
import nightgames.characters.Character;
import nightgames.combat.Combat;
import nightgames.combat.Result;
import nightgames.items.Item;
import nightgames.status.Bound;
import nightgames.status.Stsflag;
public class Tie extends Skill {
public Tie(Character self) {
super("Bind", self);
}
@Override
public boolean requirements(Combat c, Character user, Character target) {
return true;
}
@Override
public boolean usable(Combat c, Character target) {
return !target.wary() && getSelf().canAct() && c.getStance().reachTop(getSelf())
&& !c.getStance().reachTop(target)
&& (getSelf().has(Item.ZipTie) || getSelf().has(Item.Handcuffs)) && c.getStance().dom(getSelf())
&& !target.is(Stsflag.bound);
}
@Override
public boolean resolve(Combat c, Character target) {
if (getSelf().has(Item.Handcuffs, 1)) {
getSelf().consume(Item.Handcuffs, 1);
if (getSelf().human()) {
c.write(getSelf(), deal(c, 0, Result.special, target));
} else if (target.human()) {
c.write(getSelf(), receive(c, 0, Result.special, target));
}
target.add(c, new Bound(target, 75, "handcuffs"));
} else {
getSelf().consume(Item.ZipTie, 1);
if (target.roll(this, c, accuracy(c))) {
if (getSelf().human()) {
c.write(getSelf(), deal(c, 0, Result.normal, target));
} else if (target.human()) {
c.write(getSelf(), receive(c, 0, Result.normal, target));
}
target.add(c, new Bound(target, 50, "ziptie"));
} else {
if (getSelf().human()) {
c.write(getSelf(), deal(c, 0, Result.miss, target));
} else if (target.human()) {
c.write(getSelf(), receive(c, 0, Result.miss, target));
}
return false;
}
}
return true;
}
@Override
public Skill copy(Character user) {
return new Tie(user);
}
@Override
public Tactics type(Combat c) {
return Tactics.positioning;
}
@Override
public int speed() {
return 2;
}
@Override
public int accuracy(Combat c) {
return 80;
}
@Override
public String deal(Combat c, int damage, Result modifier, Character target) {
if (modifier == Result.miss) {
return "You try to catch " + target.name() + "'s hands, but she squirms too much to keep your grip on her.";
} else if (modifier == Result.special) {
return "You catch " + target.name() + "'s wrists and slap a pair of cuffs on her.";
} else {
return "You catch both of " + target.name() + " hands and wrap a ziptie around her wrists.";
}
}
@Override
public String receive(Combat c, int damage, Result modifier, Character target) {
if (modifier == Result.miss) {
return getSelf().name() + " tries to tie you down, but you keep your arms free.";
} else if (modifier == Result.special) {
return getSelf().name() + " restrains you with a pair of handcuffs.";
} else {
return getSelf().name() + " secures your hands with a ziptie.";
}
}
@Override
public String describe(Combat c) {
return "Tie up your opponent's hands with a ziptie";
}
@Override
public boolean makesContact() {
return true;
}
}
|
package net.acomputerdog.advplugin.cmd;
import net.acomputerdog.advplugin.AdvancedPlugin;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Cmd {
private final AdvancedPlugin plugin;
private final CommandSender user;
private final Command command;
private final String alias;
private final String[] argsList;
private String argsLine;
public Cmd(AdvancedPlugin plugin, CommandSender user, Command command, String alias, String[] argsList) {
this.plugin = plugin;
this.user = user;
this.command = command;
this.alias = alias;
this.argsList = argsList;
}
public AdvancedPlugin getPlugin() {
return plugin;
}
public CommandSender getUser() {
return user;
}
public Command getCommand() {
return command;
}
public String getAlias() {
return alias;
}
public String getArgsLine() {
if (argsLine == null) {
argsLine = String.join(" ", argsList);
}
return argsLine;
}
public String[] getArgsList() {
return argsList;
}
public Player getPlayerUser() {
return (Player)user;
}
}
|
package com.gaoshin.business;
import java.util.List;
import com.gaoshin.beans.Configuration;
public interface ConfigurationService {
Configuration save(Configuration conf);
Configuration save(String key, String value);
Configuration save(Object obj);
List<Configuration> getList(String key);
Configuration get(String key);
String getString(String key);
String getString(String key, String defaultValue);
Configuration get(String key, Object def);
int getInt(String name, int port);
}
|
// **********************************************************
// 1. 제 목: 평가 결과조회
// 2. 프로그램명: ExamResultBean.java
// 3. 개 요:
// 4. 환 경: JDK 1.3
// 5. 버 젼: 0.1
// 6. 작 성: Administrator 2003-08-29
// 7. 수 정:
//
// **********************************************************
package com.ziaan.exam;
import java.util.ArrayList;
import java.util.Vector;
import com.ziaan.library.DBConnectionManager;
import com.ziaan.library.DataBox;
import com.ziaan.library.ErrorManager;
import com.ziaan.library.ListSet;
import com.ziaan.library.Log;
import com.ziaan.library.RequestBox;
import com.ziaan.library.SQLString;
import com.ziaan.system.ManagerAdminBean;
/**
* @author Administrator
*
* To change the template for this generated type comment go to
* Window > Preferences > Java > Code Generation > Code and Comments
*/
public class ExamResultBean {
public ExamResultBean() { }
/**
평가결과분석
@param box receive from the form object and session
@return ArrayList
*/
public ArrayList SelectReaultList(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ArrayList list = null;
//System.out.println("===============평가결과분석box================ " +box);
String v_action = box.getStringDefault("p_action", "change");
String v_grcode = box.getString("s_grcode");
String v_gyear = box.getString("s_gyear");
String v_grseq = box.getString("s_grseq");
String v_upperclass = box.getStringDefault("s_upperclass", "ALL");
String v_middleclass = box.getStringDefault("s_middleclass","ALL");
String v_lowerclass = box.getStringDefault("s_lowerclass", "ALL");
String v_uclass = box.getString("s_uclass");
String v_subjcourse= box.getString("s_subjcourse");
String v_subjseq = box.getString("s_subjseq");
String v_lesson = box.getString("s_lesson");
String v_papernum = box.getString("s_papernum");
String v_grpcomp = box.getString("s_company");
String v_selgubun = box.getString("s_selgubun");
String v_seltext = box.getString("s_seltext");
String v_seldept = box.getString("s_seldept");
String v_examtype = box.getStringDefault("s_examtype","0");
String s_userid = box.getSession("userid");
String s_gadmin = box.getSession("gadmin");
String v_orderColumn = box.getString("p_orderColumn"); // 정렬할 컬럼명
String v_orderType = box.getString("p_orderType"); // 정렬할 순서
try {
if ( v_action.equals("go") ) {
connMgr = new DBConnectionManager();
list = getResultList(connMgr, v_grcode, v_gyear, v_grseq, v_uclass, v_subjcourse, v_subjseq,
v_grpcomp, v_selgubun, v_seltext, v_seldept, v_lesson, s_userid, s_gadmin, v_papernum, v_examtype,
v_orderColumn, v_orderType);
} else {
list = new ArrayList();
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
} finally {
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return list;
}
/**
평가결과분석
@return ArrayList
*/
public ArrayList getResultList(DBConnectionManager connMgr,
String p_grcode, String p_gyear, String p_grseq, String p_uclass,
String p_subjcourse, String p_subjseq, String p_grpcomp,
String p_selgubun, String p_seltext, String p_seldept, String p_lesson, String p_userid, String p_gadmin, String p_papernum,String p_examtype,
String p_orderColumn, String p_orderType) throws Exception {
ArrayList list = new ArrayList();
ListSet ls = null;
String sql = "";
ExamResultData data = null;
ManagerAdminBean bean = null;
String v_sql_add = "";
try {
//2008.10.23 sql = "select '' jikwi, '' jikwinm, d.userid, '' cono, d.name, ";
sql = "select a.isclosed,'' jikwi, '' jikwinm, d.userid, d.name, ";
//2008.10.23 sql += " d.comp asgn, get_compnm(d.comp,2,2) companynm, '' asgnnm, ";
sql += " d.comp asgn, get_compnm(d.comp) companynm, '' asgnnm, ";
sql += " b.subj, b.year, b.subjseq, b.lesson, b.examtype, b.papernum, ";
sql += " c.exam, c.examcnt, c.exampoint, c.score, ";
sql += " c.answercnt, c.started, c.ended, c.time, ";
sql += " c.answer, c.corrected, a.subjnm, a.subjseqgr,";
sql += " nvl(c.userretry,nvl(b.retrycnt,-1) + 1 ) userretry, ";
// sql += " c.userretry-1 userretry, ";
sql += " b.retrycnt, a.eduend, d.handphone, d.hometel, d.email, c.indate ";
sql += " from vz_scsubjseq a, ";
sql += " (select a.subj, a.year, a.subjseq, b.lesson, b.examtype, b.papernum, a.userid, b.retrycnt ";
sql += " from tz_student a, ";
sql += " tz_exampaper b ";
sql += " where a.subj = b.subj ";
sql += " and a.year = b.year ";
sql += " and a.subjseq = b.subjseq ) b, ";
sql += " tz_examresult c, ";
sql += " tz_member d, ";
sql += " tz_compclass e ";
//sql += " tz_comp e ";
sql += " where a.subj = b.subj ";
sql += " and a.year = b.year ";
sql += " and a.subjseq = b.subjseq ";
sql += " and b.subj = c.subj( +) ";
sql += " and b.year = c.year( +) ";
sql += " and b.subjseq = c.subjseq( +) ";
sql += " and b.lesson = c.lesson( +) ";
sql += " and b.examtype = c.examtype( +) ";
sql += " and b.papernum= c.papernum( +) ";
sql += " and b.userid = c.userid( +) ";
sql += " and b.userid = d.userid ";
sql += " and d.comp = e.comp ";
if ( !p_grcode.equals("ALL") ) {
sql += " and a.grcode = " + SQLString.Format(p_grcode);
}
if ( !p_gyear.equals("ALL") ) {
sql += " and a.gyear = " + SQLString.Format(p_gyear);
}
// if ( !p_grseq.equals("ALL") ) {
// sql += " and a.grseq = " + SQLString.Format(p_grseq);
// }
// if ( !p_uclass.equals("ALL") ) {
// sql += " and a.scupperclass = " + SQLString.Format(p_uclass);
// }
if ( !p_subjcourse.equals("----") && !p_subjcourse.equals("ALL") ) {
sql += " and a.scsubj = " + SQLString.Format(p_subjcourse);
}
if ( !p_subjseq.equals("----") && !p_subjseq.equals("ALL") ) {
sql += " and a.scsubjseq = " + SQLString.Format(p_subjseq);
}
// 부서장일경우
/* if ( p_gadmin.equals("K7") ) {
bean = new ManagerAdminBean();
v_sql_add = bean.getManagerDept(p_userid, p_gadmin);
if ( !v_sql_add.equals("")) sql += " and d.comp in " + v_sql_add; // 관리부서검색조건쿼리
}
if ( p_selgubun.equals("JIKUN") && !p_seltext.equals("ALL")) { // 직군별
sql += " and d.jikun = " +SQLString.Format(p_seltext);
} else if ( p_selgubun.equals("JIKUP") && !p_seltext.equals("ALL") ) { // 직급별
sql += " and d.jikup = " +SQLString.Format(p_seltext);
} else if ( p_selgubun.equals("GPM") && !p_seltext.equals("ALL") ) { // 사업부별
sql += " and d.comp like " +SQLString.Format(GetCodenm.get_compval(p_seltext));
if ( !p_seldept.equals("ALL") ) {
sql += " and e.comp like " +SQLString.Format(GetCodenm.get_compval(p_seldept));
}
}
if ( !p_lesson.equals("ALL") ) {
sql += " and b.lesson = " + SQLString.Format(p_lesson);
}*/
if ( !p_papernum.equals("0") ) {
sql += " and b.papernum = " + SQLString.Format(p_papernum);
}
// sql += " order by a.subj, a.year, a.subjseq, b.userid ";
if ( p_orderColumn.equals("") ) {
sql += " order by a.subj, a.year, a.subjseq, b.userid ";
} else {
sql += " order by " + p_orderColumn + p_orderType;
}
//System.out.println("수료 여부sql=========================" +sql);
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
data = new ExamResultData();
data.setIsclosed ( ls.getString("isclosed"));
data.setSubj ( ls.getString("subj") );
data.setYear ( ls.getString("year") );
data.setSubjseq( ls.getString("subjseq") );
data.setSubjseqgr( ls.getString("subjseqgr") );
data.setLesson( ls.getString("lesson") );
data.setExamtype ( ls.getString("examtype") );
data.setPapernum( ls.getInt("papernum") );
data.setUserid ( ls.getString("userid") );
data.setExam ( ls.getString("exam") );
data.setExamcnt( ls.getInt("examcnt") );
data.setExampoint( ls.getInt("exampoint") );
data.setScore( ls.getInt("score") );
data.setAnswercnt( ls.getInt("answercnt") );
data.setStarted( ls.getString("started") );
data.setEnded ( ls.getString("ended") );
data.setTime ( ls.getDouble("time") );
data.setAnswer ( ls.getString("answer") );
data.setCorrected ( ls.getString("corrected") );
data.setSubjnm ( ls.getString("subjnm") );
data.setCompanynm ( ls.getString("companynm") ); // 회사명
data.setAsgnnm ( ls.getString("asgnnm") );
data.setJikwinm( ls.getString("jikwinm") );
//data.setCono ( ls.getString("cono") );
data.setName ( ls.getString("name") );
data.setUserretry( ls.getInt("userretry") );
data.setRetrycnt( ls.getInt("retrycnt") );
data.setHometel ( ls.getString("hometel") );
data.setHandphone( ls.getString("handphone") );
data.setEmail ( ls.getString("email") );
data.setEduEnd( ls.getString("eduend") );
data.setIndate( ls.getString("indate") );
if ( !(data.getStarted() == null || data.getStarted().equals("")) && (data.getEnded() == null || data.getEnded().equals("")) ) {
data.setStatus("응시(미제출)");
} else if ( data.getAnswer() == null || data.getAnswer().equals("") ) {
data.setStatus("미응시");
} else {
data.setStatus("완료");
}
list.add(data);
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
}
return list;
}
/**
평가자 결과 평균 보기
@param
@return Vector
*/
public Vector SelectResultAverage(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
Vector v_average = null;
String v_grcode = box.getString("s_grcode");
String v_gyear = box.getString("s_gyear");
String v_grseq = box.getString("s_grseq");
String v_upperclass = box.getStringDefault("s_upperclass", "ALL");
String v_middleclass = box.getStringDefault("s_middleclass","ALL");
String v_lowerclass = box.getStringDefault("s_lowerclass", "ALL");
String v_uclass = box.getString("s_uclass");
String v_subjcourse= box.getString("s_subjcourse");
String v_subjseq = box.getString("s_subjseq");
String v_lesson = box.getString("s_lesson");
int v_papernum = box.getInt("s_papernum");
String v_grpcomp = box.getString("s_company");
String v_selgubun = box.getString("s_selgubun");
String v_seltext = box.getString("s_seltext");
String v_seldept = box.getString("s_seldept");
String s_userid = box.getSession("userid");
try {
connMgr = new DBConnectionManager();
v_average = getAverage(connMgr, v_subjcourse, v_gyear, v_subjseq, v_lesson, v_papernum );
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
} finally {
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return v_average;
}
/**
평가자 결과 평균 보기
@param
@return Vector
*/
public Vector SelectResultAverage2(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
Vector v_average = null;
String v_grcode = box.getString("p_grcode");
String v_gyear = box.getString("p_gyear");
String v_grseq = box.getString("p_grseq");
String v_upperclass = box.getStringDefault("s_upperclass", "ALL");
String v_middleclass = box.getStringDefault("s_middleclass","ALL");
String v_lowerclass = box.getStringDefault("s_lowerclass", "ALL");
String v_uclass = box.getString("s_uclass");
String v_subjcourse= box.getString("p_subj");
String v_subjseq = box.getString("p_subjseq");
String v_lesson = box.getString("p_lesson");
int v_papernum = box.getInt("p_papernum");
String v_grpcomp = box.getString("s_company");
String v_selgubun = box.getString("s_selgubun");
String v_seltext = box.getString("s_seltext");
String v_seldept = box.getString("s_seldept");
String s_userid = box.getSession("userid");
try {
connMgr = new DBConnectionManager();
v_average = getAverage(connMgr, v_subjcourse, v_gyear, v_subjseq, v_lesson, v_papernum );
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception(ex.getMessage() );
} finally {
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return v_average;
}
/**
평가자 결과 평균 구하기
@param
@return Vector
*/
public Vector getAverage(DBConnectionManager connMgr, String p_subjcourse, String p_gyear, String p_subjseq, String p_lesson, int p_papernum ) throws Exception {
Vector v_average = null;
String sql = "";
DataBox dbox = null;
ListSet ls = null;
int totalscore =0;
int examcnt = 0;
int usercnt = 0;
double averscore = 0;
int maxscore = 0;
int minscore = 0;
int usercnt1 = 0;
int usercnt2 = 0;
int usercnt3 = 0;
int usercnt4 = 0;
int usercnt5 = 0;
int usercnt6 = 0;
int usercnt7 = 0;
int usercnt8 = 0;
int usercnt9 = 0;
int usercnt10 = 0;
try {
sql += " select k.examcnt, k.score ";
sql += " from tz_examresult k ";
sql += " where k.subj = " + SQLString.Format(p_subjcourse);
sql += " and k.year = " + SQLString.Format(p_gyear);
sql += " and k.subjseq = " + SQLString.Format(p_subjseq);
// sql += " and k.lesson = " + SQLString.Format(p_lesson);
// sql += " and k.papernum = " + SQLString.Format(p_papernum);
sql += " order by k.subj, k.year, k.subjseq, k.userid ";
// System.out.println("평가자 결과 평균 ====="+sql);
ls = connMgr.executeQuery(sql);
v_average = new Vector();
while ( ls.next() ) {
dbox = ls.getDataBox();
totalscore += dbox.getInt("d_score");
examcnt = dbox.getInt("d_examcnt");
usercnt++;
if ( dbox.getInt("d_score") > maxscore) {
maxscore = dbox.getInt("d_score");
}
if ( dbox.getInt("d_score") < minscore) {
minscore = dbox.getInt("d_score");
}
if ( dbox.getInt("d_score") <= 10 ) {
usercnt1++;
} else if ( dbox.getInt("d_score") > 10 && dbox.getInt("d_score") <= 20 ) {
usercnt2++;
} else if ( dbox.getInt("d_score") > 20 && dbox.getInt("d_score") <= 30 ) {
usercnt3++;
} else if ( dbox.getInt("d_score") > 30 && dbox.getInt("d_score") <= 40 ) {
usercnt4++;
} else if ( dbox.getInt("d_score") > 40 && dbox.getInt("d_score") <= 50 ) {
usercnt5++;
} else if ( dbox.getInt("d_score") > 50 && dbox.getInt("d_score") <= 60 ) {
usercnt6++;
} else if ( dbox.getInt("d_score") > 60 && dbox.getInt("d_score") <= 70 ) {
usercnt7++;
} else if ( dbox.getInt("d_score") > 70 && dbox.getInt("d_score") <= 80 ) {
usercnt8++;
} else if ( dbox.getInt("d_score") > 80 && dbox.getInt("d_score") <= 90 ) {
usercnt9++;
} else if ( dbox.getInt("d_score") > 90 && dbox.getInt("d_score") <= 100 ) {
usercnt10++;
}
}
if ( usercnt > 0 ) {
averscore = totalscore / usercnt;
v_average.add(String.valueOf(examcnt));
v_average.add(String.valueOf(usercnt));
v_average.add(String.valueOf(averscore));
v_average.add(String.valueOf(maxscore));
v_average.add(String.valueOf(minscore));
v_average.add(String.valueOf(usercnt1));
v_average.add(String.valueOf(usercnt2));
v_average.add(String.valueOf(usercnt3));
v_average.add(String.valueOf(usercnt4));
v_average.add(String.valueOf(usercnt5));
v_average.add(String.valueOf(usercnt6));
v_average.add(String.valueOf(usercnt7));
v_average.add(String.valueOf(usercnt8));
v_average.add(String.valueOf(usercnt9));
v_average.add(String.valueOf(usercnt10));
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
}
return v_average;
}
/**
평가결과 재응시 리스트
@param
@return ArrayList
*/
public ArrayList SelectUserRetryList(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
ArrayList list = null;
DataBox dbox = null;
String sql = "";
String v_result = "";
try {
String s_userid = box.getSession("userid");
String v_subj = box.getString("p_subj");
String v_year = box.getString("p_year");
String v_subjseq = box.getString("p_subjseq");
connMgr = new DBConnectionManager();
list = new ArrayList();
sql = "select b.subj, a.year, a.subjseq, a.lesson, ";
sql += " a.examtype, a.papernum, a.lessonstart, a.lessonend, a.examtime, a.exampoint, a.examcnt, a.totalscore, ";
sql += " a.cntlevel1, a.cntlevel2, a.cntlevel3, a.isopenanswer, ";
sql += " a.isopenexp, a.retrycnt, b.subjnm, GET_CODENM(" + SQLString.Format(ExamBean.PTYPE) + ", nvl(a.examtype, '')) examtypenm ";
sql += " from tz_exampaper a, ";
sql += " tz_subj b ";
sql += " where a.subj( +) = b.subj ";
sql += " and a.subj = " + SQLString.Format(v_subj);
sql += " and a.year = " + SQLString.Format(v_year);
sql += " and a.subjseq = " + SQLString.Format(v_subjseq);
// sql += " and rownum <= 1 ";
sql += " order by a.subj, a.year, a.subjseq, a.lesson, a.examtype ";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
// System.out.println("retrycnt : " + dbox.getInt("d_retrycnt") );
if ( dbox.getInt("d_retrycnt") != 0 ) {
v_result = String.valueOf(SelectUserRetryList(connMgr, v_subj, v_year, v_subjseq, s_userid, dbox.getString("d_examtype"), dbox.getInt("d_papernum")));
}
else {
v_result = "X"; // 재응시가 없는 평가
}
// System.out.println(dbox.getString("d_examtype") + " : " + v_result);
list.add(String.valueOf(v_result));
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return list;
}
/**
평가자 재응시횟수 구하기
@param
@return int
*/
public int SelectUserRetryList(DBConnectionManager connMgr,
String p_subj, String p_year, String p_subjseq, String p_userid, String p_examtype, int p_papernum) throws Exception {
ArrayList QuestionExampleDataList = null;
int v_result = -1;
ListSet ls = null;
String sql = "";
DataBox dbox = null;
try {
sql = "select userretry ";
sql += " from tz_examresult ";
sql += " where subj = " + SQLString.Format(p_subj);
sql += " and year = " + SQLString.Format(p_year);
sql += " and subjseq = " + SQLString.Format(p_subjseq);
sql += " and examtype = " + SQLString.Format(p_examtype);
sql += " and userid = " + SQLString.Format(p_userid);
sql += " and papernum = " + SQLString.Format(p_papernum);
// System.out.println(sql);
ls = connMgr.executeQuery(sql);
if ( ls.next() ) {
dbox = ls.getDataBox();
v_result = dbox.getInt("d_userretry");
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
}
return v_result;
}
/**
대상자 설문지 셀렉트박스 (RequestBox, 셀렉트박스명,선택값,이벤트명) TZ_SULPAPER 이용
@param
@return String
*/
public static String getPaperSelect (String p_subj, String p_gyear, String p_subjseq, String p_lesson, String name, int selected, String event) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
String result = null;
String sql = "";
DataBox dbox = null;
result = " <SELECT name=" + name + " " + event + " > \n";
result += " <option value='0' > 평가를 선택하세요.</option > \n";
try {
connMgr = new DBConnectionManager();
sql = "select b.subj, a.year, a.subjseq, a.lesson, ";
sql += " a.examtype, a.papernum, a.lessonstart, a.lessonend, a.examtime, a.exampoint, a.examcnt, a.totalscore, ";
sql += " a.cntlevel1, a.cntlevel2, a.cntlevel3, a.isopenanswer, ";
sql += " a.isopenexp, a.retrycnt, b.subjnm, GET_CODENM(" + SQLString.Format(ExamBean.PTYPE) + ", nvl(a.examtype, '')) examtypenm ";
sql += " from tz_exampaper a, ";
sql += " tz_subj b ";
sql += " where a.subj( +) = b.subj ";
sql += " and a.subj = " + SQLString.Format(p_subj);
sql += " and a.year = " + SQLString.Format(p_gyear);
sql += " and a.subjseq = " + SQLString.Format(p_subjseq);
// sql += " and a.lesson = " + SQLString.Format(p_lesson);
sql += " order by a.subj, a.year, a.subjseq, a.lesson, a.examtype, a.papernum asc ";
System.out.println(sql);
ls = connMgr.executeQuery(sql);
String v_null_test = "";
String v_subj_bef = "";
while ( ls.next() ) {
dbox = ls.getDataBox();
result += " <option value=" + dbox.getInt("d_papernum");
if ( selected == dbox.getInt("d_papernum") ) {
result += " selected ";
}
result += " > " + dbox.getString("d_examtypenm") + " [" + dbox.getString("d_papernum") + "]" + "</option > \n";
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
result += " </SELECT > \n";
return result;
}
/**
대상자 설문지 셀렉트박스 (RequestBox, 셀렉트박스명,선택값,이벤트명) TZ_SULPAPER 이용
@param
@return String
*/
public static String getPaperTypeSelect (String p_subj, String p_gyear, String p_subjseq, String p_lesson, String name, String selected, String event) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
String result = null;
String sql = "";
DataBox dbox = null;
result = " <SELECT name=" + name + " " + event + " > \n";
result += " <option value='0' > 평가를 선택하세요.</option > \n";
try {
connMgr = new DBConnectionManager();
sql = "select b.subj, a.year, a.subjseq, a.lesson, ";
sql += " a.examtype, a.papernum, a.lessonstart, a.lessonend, a.examtime, a.exampoint, a.examcnt, a.totalscore, ";
sql += " a.cntlevel1, a.cntlevel2, a.cntlevel3, a.isopenanswer, ";
sql += " a.isopenexp, a.retrycnt, b.subjnm, GET_CODENM(" + SQLString.Format(ExamBean.PTYPE) + ", nvl(a.examtype, '')) examtypenm ";
sql += " from tz_exampaper a, ";
sql += " tz_subj b ";
sql += " where a.subj( +) = b.subj ";
sql += " and a.subj = " + SQLString.Format(p_subj);
sql += " and a.year = " + SQLString.Format(p_gyear);
sql += " and a.subjseq = " + SQLString.Format(p_subjseq);
// sql += " and a.lesson = " + SQLString.Format(p_lesson);
sql += " order by a.subj, a.year, a.subjseq, a.lesson, a.examtype, a.papernum asc ";
System.out.println(sql);
ls = connMgr.executeQuery(sql);
String v_null_test = "";
String v_subj_bef = "";
while ( ls.next() ) {
dbox = ls.getDataBox();
result += " <option value=" + dbox.getString("d_examtype");
if ( selected.equals(dbox.getString("d_examtype"))) {
result += " selected ";
}
result += " > " + dbox.getString("d_examtypenm") + " [" + dbox.getString("d_papernum") + "]" + "</option > \n";
}
} catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
} finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
result += " </SELECT > \n";
return result;
}
} |
package com.invillia.acme.controller;
public enum ResponseType {
SUCCESS, //NORMAL STATUS
REDIRECT, //USEFUL IF WE NEED TO TELL SOME FRONT-END INTERFACE TO REDIRECT INSTEAD OF FORCING IT
UNEXPECTED_ERROR, //USED WHEN PROBLEM HAPPENED SPECIFICALLY WITH PERSISTENCE STORE
VALIDATION_ERROR, //USED ESSENTIALLY FOR INPUT FORMAT VALIDATION
SERVICE_ERROR, //USED BUSINESS LOGIC SPECIFIC ERROR REPORTING
PERSISTENCE_ERROR, //USED WHEN PROBLEM HAPPENED SPECIFICALLY WITH PERSISTENCE STORE
;
}
|
package bd;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class conexao {
private static Connection conexao;
public static Connection getConexao () {
try {
if(conexao == null) {
Class.forName("org.firebirdsql.jdbc.FBDriver");
conexao = DriverManager.getConnection("jdbc:firebirdsql://localhost/" +
System.getProperty("user.dir") + "/BANCO.FDB", "SYSDBA", "masterkey");
}
return conexao;
} catch (ClassNotFoundException cnfe) {
JOptionPane.showMessageDialog(null,"Erro no driver jdbc");
return null;
} catch (SQLException se) {
JOptionPane.showMessageDialog(null,"Erro na conexão com o banco de dados");
se.printStackTrace();
return null;
}
}
}
|
package com.social.server.util;
import com.social.server.dto.UserDto;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TokenUtil {
private final static String SECRET_KEY = "SOCIAL_SECRET_KEY";
private final static String TOKEN_PREFIX = "Bearer";
public static UserDto parseToken(String token) {
try {
log.debug("Parser token={}", token);
Claims body = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody();
UserDto u = new UserDto();
log.debug("Set user data");
u.setId(((Integer)body.get("userId")).longValue());
u.setEmail(body.getSubject());
return u;
} catch (JwtException | ClassCastException e) {
log.error("Parse token was failed", e);
throw e;
}
}
public static String generateToken(UserDto u) {
Claims claims = Jwts.claims().setSubject(u.getEmail());
claims.put("userId", u.getId());
return TOKEN_PREFIX + " " + Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
}
|
package com.svalero.examen.utils;
import javafx.scene.control.Alert;
public class Alerts {
/**
* Muestra una alerta de información
* @param message
*/
public static void showInfoAlert(String message) {
Alert infoAlert = new Alert(Alert.AlertType.INFORMATION);
infoAlert.setTitle("Información");
infoAlert.setContentText(message);
infoAlert.showAndWait();
}
/**
* Muestra una alerta de error
* @param message
*/
public static void showErrorAlert(String message) {
Alert errorAlert = new Alert(Alert.AlertType.ERROR);
errorAlert.setTitle("Error");
errorAlert.setContentText(message);
errorAlert.showAndWait();
}
}
|
package com.designurway.idlidosa.a.utils;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPrefManager {
static SharedPreferences preferences;
public static final String PREF_TOTAL_KEY = "pref_total_key";
public static final String PREF_NAME = "pref_total_key";
Context context;
public SharedPrefManager(Context context) {
this.context = context;
}
public static void SaveTotalKey(Context context, int total) {
preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(PREF_TOTAL_KEY, total);
editor.apply();
}
public static int loadFrompref(Context context) {
SharedPreferences rpref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
return rpref.getInt(PREF_TOTAL_KEY, 0);
}
public static void registerPrif(Context context, SharedPreferences.OnSharedPreferenceChangeListener lisner) {
SharedPreferences rpref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
rpref.registerOnSharedPreferenceChangeListener(lisner);
}
public static void unregisterPref(Context context, SharedPreferences.OnSharedPreferenceChangeListener lisner){
SharedPreferences rpref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
rpref.unregisterOnSharedPreferenceChangeListener(lisner);
}
public static void Clear(Context context){
preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.apply();
}
}
|
package p20;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
public class Service {
DBCon dbCon;
String sql;
Service() {
dbCon = new DBCon();
}
public ArrayList<HashMap<String, Object>> getClassInfo() throws SQLException {
sql = "select * from class_info";
return dbCon.executeQuery(sql, null);
}
public ArrayList<HashMap<String, Object>> getUserInfo() throws SQLException {
sql = "select * from user_info";
return dbCon.executeQuery(sql, null);
}
public int updateClassInfo(LinkedHashMap<String, Object> hm) {
int result = 0;
sql = "update class_info set cidesc=? where cino=?";
try {
result = dbCon.executeUpdate(sql, hm);
dbCon.commit();
} catch (SQLException e) {
try {
dbCon.rollback();
} catch (SQLException e1) {
System.out.println("rollback중 에러발생");
}
e.printStackTrace();
} finally {
try {
dbCon.closeAll();
} catch (SQLException e) {
System.out.println("connection 종료중 에러발생");
}
}
return result;
}
public int deleteClassInfo(LinkedHashMap<String, Object> hm) {
int result = 0;
sql = "delete from user_info where uino=?";
try {
dbCon.executeUpdate(sql, hm);
dbCon.commit();
} catch (SQLException e) {
try {
dbCon.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
try {
dbCon.closeAll();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
public int insertClassInfo(LinkedHashMap<String, Object> hm) {
int result = 0;
sql = "INSERT INTO USER_INFO(UINAME,UIAGE,UIID,UIPWD,CINO,uiregdate,address) " + "VALUES (?,?,?,?,?,Now(),?);";
try {
dbCon.executeUpdate(sql, hm);
dbCon.commit();
} catch (SQLException e) {
try {
dbCon.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
try {
dbCon.closeAll();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
public ArrayList<HashMap<String, Object>> getInfo(LinkedHashMap<String, Object> hm) throws SQLException {
sql = "select "+hm.get("value")+" from "+hm.get("from");
return dbCon.executeQuery(sql, null);
}
public int getExam(LinkedHashMap<String, Object> hm, String sql) {
int result = 0;
try {
dbCon.executeUpdate(sql, hm);
dbCon.commit();
} catch (SQLException e) {
try {
dbCon.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
try {
dbCon.closeAll();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
}
|
package com.jooink.experiments.gwtwebgl.client.tests.cube;
import com.google.gwt.typedarrays.shared.Float32Array;
import com.google.gwt.typedarrays.shared.Uint16Array;
public interface WebGLobject {
public Float32Array getVerticesArray();
public Uint16Array getIndexesArray();
public int getNumIndices();
public Float32Array getTextureCoordinatesArray();
public Float32Array getNormalsArray();
} |
/*
* 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 com.mycompany.serpientesescaleras.principal;
import java.util.*;
import javax.swing.JOptionPane;
/**
*
* @author nroda
*/
public class Dado {
//Atributos
private final Random random = new Random();
private int dado1;
private int dado2;
//Constuctor
public Dado(){
}
//Metodos
public int retornarSuma(){
this.dado1 = random.nextInt(6)+1;
this.dado2 = random.nextInt(6)+1;
int suma = this.dado1 + this.dado2;
JOptionPane.showMessageDialog(null, "El primer dado dio: " + dado1 + " El segundo dado dio: " + dado2 + " Avanzas: " + suma + " casillas");
return suma;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* 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
*
* https://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.springframework.web.servlet.mvc.condition;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.server.PathContainer;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.util.ServletRequestPathUtils;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;
/**
* A logical disjunction (' || ') request condition that matches a request
* against a set of URL path patterns.
*
* <p>In contrast to {@link PatternsRequestCondition}, this condition uses
* parsed {@link PathPattern}s instead of String pattern matching with
* {@link org.springframework.util.AntPathMatcher AntPathMatcher}.
*
* @author Rossen Stoyanchev
* @since 5.3
*/
public final class PathPatternsRequestCondition extends AbstractRequestCondition<PathPatternsRequestCondition> {
private static final SortedSet<PathPattern> EMPTY_PATH_PATTERN =
new TreeSet<>(Collections.singleton(new PathPatternParser().parse("")));
private static final Set<String> EMPTY_PATH = Collections.singleton("");
private static final SortedSet<PathPattern> ROOT_PATH_PATTERNS =
new TreeSet<>(List.of(new PathPatternParser().parse(""), new PathPatternParser().parse("/")));
private final SortedSet<PathPattern> patterns;
/**
* Default constructor resulting in an {@code ""} (empty path) mapping.
*/
public PathPatternsRequestCondition() {
this(EMPTY_PATH_PATTERN);
}
/**
* Constructor with patterns to use.
*/
public PathPatternsRequestCondition(PathPatternParser parser, String... patterns) {
this(parse(parser, patterns));
}
private static SortedSet<PathPattern> parse(PathPatternParser parser, String... patterns) {
if (patterns.length == 0 || (patterns.length == 1 && !StringUtils.hasText(patterns[0]))) {
return EMPTY_PATH_PATTERN;
}
SortedSet<PathPattern> result = new TreeSet<>();
for (String pattern : patterns) {
pattern = parser.initFullPathPattern(pattern);
result.add(parser.parse(pattern));
}
return result;
}
private PathPatternsRequestCondition(SortedSet<PathPattern> patterns) {
this.patterns = patterns;
}
/**
* Return the patterns in this condition. If only the first (top) pattern
* is needed use {@link #getFirstPattern()}.
*/
public Set<PathPattern> getPatterns() {
return this.patterns;
}
@Override
protected Collection<PathPattern> getContent() {
return this.patterns;
}
@Override
protected String getToStringInfix() {
return " || ";
}
/**
* Return the first pattern.
*/
public PathPattern getFirstPattern() {
return this.patterns.first();
}
/**
* Whether the condition is the "" (empty path) mapping.
*/
public boolean isEmptyPathMapping() {
return this.patterns == EMPTY_PATH_PATTERN;
}
/**
* Return the mapping paths that are not patterns.
*/
public Set<String> getDirectPaths() {
if (isEmptyPathMapping()) {
return EMPTY_PATH;
}
Set<String> result = Collections.emptySet();
for (PathPattern pattern : this.patterns) {
if (!pattern.hasPatternSyntax()) {
result = (result.isEmpty() ? new HashSet<>(1) : result);
result.add(pattern.getPatternString());
}
}
return result;
}
/**
* Return the {@link #getPatterns()} mapped to Strings.
*/
public Set<String> getPatternValues() {
return (isEmptyPathMapping() ? EMPTY_PATH :
getPatterns().stream().map(PathPattern::getPatternString).collect(Collectors.toSet()));
}
/**
* Combine the patterns of the current and of the other instances as follows:
* <ul>
* <li>If only one instance has patterns, use those.
* <li>If both have patterns, combine patterns from "this" instance with
* patterns from the other instance via {@link PathPattern#combine(PathPattern)}.
* <li>If neither has patterns, use {@code ""} and {@code "/"} as root path patterns.
* </ul>
*/
@Override
public PathPatternsRequestCondition combine(PathPatternsRequestCondition other) {
if (isEmptyPathMapping() && other.isEmptyPathMapping()) {
return new PathPatternsRequestCondition(ROOT_PATH_PATTERNS);
}
else if (other.isEmptyPathMapping()) {
return this;
}
else if (isEmptyPathMapping()) {
return other;
}
else {
SortedSet<PathPattern> combined = new TreeSet<>();
for (PathPattern pattern1 : this.patterns) {
for (PathPattern pattern2 : other.patterns) {
combined.add(pattern1.combine(pattern2));
}
}
return new PathPatternsRequestCondition(combined);
}
}
/**
* Checks if any of the patterns match the given request and returns an
* instance that is guaranteed to contain matching patterns, sorted.
* @param request the current request
* @return the same instance if the condition contains no patterns;
* or a new condition with sorted matching patterns;
* or {@code null} if no patterns match.
*/
@Override
@Nullable
public PathPatternsRequestCondition getMatchingCondition(HttpServletRequest request) {
PathContainer path = ServletRequestPathUtils.getParsedRequestPath(request).pathWithinApplication();
SortedSet<PathPattern> matches = getMatchingPatterns(path);
return (matches != null ? new PathPatternsRequestCondition(matches) : null);
}
@Nullable
private SortedSet<PathPattern> getMatchingPatterns(PathContainer path) {
TreeSet<PathPattern> result = null;
for (PathPattern pattern : this.patterns) {
if (pattern.matches(path)) {
result = (result != null ? result : new TreeSet<>());
result.add(pattern);
}
}
return result;
}
/**
* Compare the two conditions based on the URL patterns they contain.
* Patterns are compared one at a time, from top to bottom. If all compared
* patterns match equally, but one instance has more patterns, it is
* considered a closer match.
* <p>It is assumed that both instances have been obtained via
* {@link #getMatchingCondition(HttpServletRequest)} to ensure they
* contain only patterns that match the request and are sorted with
* the best matches on top.
*/
@Override
public int compareTo(PathPatternsRequestCondition other, HttpServletRequest request) {
Iterator<PathPattern> iterator = this.patterns.iterator();
Iterator<PathPattern> iteratorOther = other.getPatterns().iterator();
while (iterator.hasNext() && iteratorOther.hasNext()) {
int result = PathPattern.SPECIFICITY_COMPARATOR.compare(iterator.next(), iteratorOther.next());
if (result != 0) {
return result;
}
}
if (iterator.hasNext()) {
return -1;
}
else if (iteratorOther.hasNext()) {
return 1;
}
else {
return 0;
}
}
}
|
package com.example.user.controller;
import com.example.user.entity.User;
import com.example.user.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* @ClassName: UserController
* @Description: 用户信息Controller
* @Author: yongchen
* @Date: 2020/10/21 15:42
**/
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
/**
* @Author: yongchen
* @Description: 获取用户信息
* @Date: 16:12 2020/10/21
* @Param: []
* @return: java.util.List<com.example.user.entity.User>
**/
@GetMapping("getUserList")
public List<User> getUserList(){
return userService.userList();
}
}
|
package com.beta.rulestrategy;
public enum Rule {
// Rule number matters here. DON'T CHANGE THIS ORDER
UNKNOWN, REVERSE, HASH;
}
|
package com.latmod.warp_pads.net;
import com.feed_the_beast.ftbl.lib.net.MessageToServer;
import com.feed_the_beast.ftbl.lib.net.NetworkWrapper;
import com.feed_the_beast.ftbl.lib.util.NetUtils;
import com.latmod.warp_pads.block.TileWarpPad;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.common.network.ByteBufUtils;
/**
* Created by LatvianModder on 31.07.2016.
*/
public class MessageSetName extends MessageToServer<MessageSetName>
{
private BlockPos pos;
private String name;
public MessageSetName()
{
}
public MessageSetName(BlockPos p, String n)
{
pos = p;
name = n;
}
@Override
public NetworkWrapper getWrapper()
{
return WarpPadsNetHandler.NET;
}
@Override
public void toBytes(ByteBuf io)
{
NetUtils.writePos(io, pos);
ByteBufUtils.writeUTF8String(io, name);
}
@Override
public void fromBytes(ByteBuf io)
{
pos = NetUtils.readPos(io);
name = ByteBufUtils.readUTF8String(io);
}
@Override
public void onMessage(MessageSetName m, EntityPlayer player)
{
TileEntity te = player.world.getTileEntity(m.pos);
if(te instanceof TileWarpPad)
{
TileWarpPad teleporter = (TileWarpPad) te;
if(teleporter.isOwner(player.getGameProfile().getId()))
{
teleporter.setName(m.name);
}
}
}
} |
package com.anyuaning.osp.jnimp3lame;
/**
* Created by thom on 14-5-10.
*/
public class SimpleMp3Lame {
}
|
class PingPongThread extends Thread {
final Printer printer;
String message;
public PingPongThread(Printer printer, String message) {
this.printer = printer;
this.message = message;
this.start();
}
@Override
public void run() {
while (true) {
synchronized (printer) {
printer.printMsg(message);
printer.notify();
try {
printer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
} |
package lab.nnverify.platform.verifyplatform.mapper;
import lab.nnverify.platform.verifyplatform.models.Verification;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
import java.util.Map;
@Mapper
public interface VerificationMapper {
@Select("select verify_id,user_id,tool,epsilon,dataset,num_of_image,net_name,status from verification where user_id=#{userId}")
List<Verification> fetchVerificationByUserId(Integer userId);
@Insert("insert into verification(verify_id,user_id,tool,epsilon,dataset,num_of_image,net_name,status) values " +
"(#{verifyId},#{userId},#{tool},#{epsilon},#{dataset},#{numOfImage},#{netName},#{status})")
int insertVerificationRecord(Verification params);
@Update("update verification set status=#{status} where verify_id=#{verifyId}")
int updateVerificationRecordStatus(String verifyId, String status);
@Select("select verify_id,user_id,tool,epsilon,dataset,num_of_image,net_name,status from verification where verify_id=#{verifyId}")
Verification fetchVerificationById(String verifyId);
}
|
package Problem_1245;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int N, M;
static String buf;
static int[][] arr;
static boolean[][] isvisited;
static int cnt;
static int[] dx = {1,1,1,-1,-1,-1,0,0};
static int[] dy = {-1,0,1,-1,0,1,-1,1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
buf = br.readLine();
N = Integer.parseInt(buf.split(" ")[0]);
M = Integer.parseInt(buf.split(" ")[1]);
arr = new int[N][M];
isvisited = new boolean[N][M];
for(int i = 0; i<N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j = 0; j<M; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
for(int i = 0; i<N; i++) {
for(int j = 0; j<M; j++) {
if(arr[i][j] > 0 && !isvisited[i][j]) {
if(bfs(i,j)) cnt++;
}
}
}
System.out.println(cnt);
}
public static boolean isIn(int x, int y) {
return ((x >= 0 && x<N) && (y >= 0 && y<M));
}
public static boolean isTop(int x, int y) {
for(int k = 0; k<8;k++) {
int x_ = x + dx[k];
int y_ = y + dy[k];
if(isIn(x_, y_) && arr[x][y] < arr[x_][y_]) return false;
}
return true;
}
public static boolean bfs(int i, int j) {
Queue<int[]> q = new LinkedList<>();
boolean[][] isvisitedInbfs = new boolean[N][M];
q.add(new int[]{i,j});
isvisitedInbfs[i][j] = true;
isvisited[i][j] = true;
if(!isTop(i,j)) {return false;}
while(!q.isEmpty()) {
int[] data = q.poll();
for(int k = 0; k<8; k++) {
int x_ = data[0] + dx[k];
int y_ = data[1] + dy[k];
if(isIn(x_, y_) && !isvisitedInbfs[x_][y_] && arr[i][j] == arr[x_][y_]) {
if(isTop(x_, y_)){
isvisited[x_][y_] = true;
isvisitedInbfs[x_][y_] = true;
q.add(new int[]{x_,y_});
} else return false;
}
}
}
return true;
}
}
|
package com.example.lanternaverde.retrofit;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.lanternaverde.retrofit.views.atualizarUsuario;
import butterknife.BindView;
import butterknife.ButterKnife;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by Lanterna Verde on 19/08/2017.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private Context context;
private List<jsonConsultaUsuarios> results; //jsonConsultaUsuarios manipula o json vindo do servidor
public RecyclerViewAdapter(Context context, List<jsonConsultaUsuarios> results) {
this.context = context;
this.results = results;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//populando a view com os dados atribuidos
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view_users, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) { //atribui os valores na view
jsonConsultaUsuarios result = results.get(position);
holder.textoID.setText(""+result.getId()); //concatenando com aspas pra forçar a conversão pra string
holder.textoNomeUsuario.setText(""+result.getUsuario());
holder.textoSenha.setText(""+result.getSenha());
}
@Override
public int getItemCount() {
return results.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//instanciando os obj que vao exibir os valores do JSON vindo do servidor
@BindView(R.id.textoID) TextView textoID;
@BindView(R.id.textoNomeUsuario) TextView textoNomeUsuario;
@BindView(R.id.textoSenha) TextView textoSenha;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int id = Integer.parseInt(textoID.getText().toString());
String nome = textoNomeUsuario.getText().toString();
String senha = textoSenha.getText().toString();
Intent i = new Intent(context, atualizarUsuario.class);
i.putExtra("id",id);
i.putExtra("nome",nome);
i.putExtra("senha", senha);
context.startActivity(i);
}
}
}
|
package com.duanc.api;
import java.util.List;
import com.duanc.model.Menu;
import com.duanc.model.SubMenu;
public interface MenuService {
/**
* @Description: 获取系统菜单
* @return List<Menu>
*/
List<Menu> getMenu(Integer userId, Integer menuId, Integer subMenuId);
/**
* @Description: 获取子菜单
* @return List<SubMenu>
*/
List<SubMenu> getSubMenu(Menu menu);
}
|
import javafx.util.Pair;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class DigraphAL extends Graph
{
private ArrayList<LinkedList<Pair<Integer,Integer>>> nodo;
public DigraphAL(int size) {
super(size);
nodo = new ArrayList<>();
for (int i = 0; i < size + 1; i++) {
nodo.add(new LinkedList<>());
}
}
public void addArc(int source, int destination, int weight){
nodo.get(source).add(new Pair<>(destination,weight));
}
public int getWeight(int source, int destination) {
int result = 0;
for (Pair<Integer, Integer> integerIntegerPair : nodo.get(source)) {
if (integerIntegerPair.getKey() == destination)
result = integerIntegerPair.getValue();
}
return result;
}
public ArrayList<Integer> getSuccessors(int vertice){
ArrayList<Integer> n = new ArrayList<>();
nodo.get(vertice).forEach(i -> n.add(i.getKey()));
return n;
}
public static boolean validarBFS(Graph g, int source, int destino){
boolean [] revicion = new boolean [g.getSize()];
return validarBFS(g, source, destino, revicion);
}
private static boolean validarBFS(Graph g, int source, int destino, boolean [] revicion){
ArrayList<Integer> listaVisi = g.getSuccessors(source);
Queue <Integer> lista = new LinkedList <Integer>();
boolean respuesta = false;
revicion[source] = true;
/*for(int proxNode : listaVisi){
lista.add(proxNode);
}
if(listaVisi == null)
return false;*/
if(!listaVisi.isEmpty()){
for(int proxNode : listaVisi){
lista.add(proxNode);
}
}
if(source == destino){
respuesta = true;
}
while(lista.size() != 0){
int org = lista.poll();
return validarBFS(g, org, destino, revicion);
}
return respuesta;
}
public static boolean validarDFS(Graph g, int source, int destino){
boolean [] revicion = new boolean [g.getSize()+1];
return validarDFS(g, source, destino, revicion);
}
private static boolean validarDFS(Graph g, int source, int destino, boolean [] revicion){
ArrayList<Integer> proximo = g.getSuccessors(source);
boolean respuesta = false;
revicion[source] = true;
if(source == destino){
respuesta = true;
}
for(int vecino : proximo){
if(revicion[vecino] == false){
respuesta = respuesta || validarDFS(g, vecino, destino, revicion);
}
}
return respuesta;
}
public static void main(String []ags){
DigraphAL graph = new DigraphAL(5);
graph.addArc(1, 2, 1);
graph.addArc(2, 4, 1);
graph.addArc(1, 5, 1);
System.out.println(validarBFS(graph, 1, 3));
System.out.println(validarBFS(graph, 1, 5));
System.out.println(validarBFS(graph, 2, 4));
graph.addArc(1, 2, 0);
graph.addArc(2, 4, 0);
graph.addArc(1, 5, 0);
System.out.println(validarDFS(graph, 1, 3));
System.out.println(validarDFS(graph, 1, 5));
System.out.println(validarDFS(graph, 2, 4));
}
}
|
package org.maxhoffmann.dev.ProductionAnalysisAnnotation;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.maxhoffmann.dev.util.HibernateUtil;
public class ResourceGroupDAO {
private static final Logger LOGGER = Logger.getLogger(ResourceGroupDAO.class);
@SuppressWarnings("unchecked")
public void listResourceGroups(int whereSourceId) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Query query = session.createQuery("from ResourceGroup where sourceId = :sourceId");
query.setParameter("sourceId", whereSourceId);
List<ResourceGroup> resourceGroups = query.list();
LOGGER.info("\n");
for ( ResourceGroup resourceGroup : resourceGroups ) {
/*
* In order to list the foreign key (Primary Key of "Project" in the ResourceGroups List
* the get method command has to call the getId() method of the class project
*/
int resourceGroupId = resourceGroup.getResourceGroupId();
int sourceId = resourceGroup.getSource().getId();
String label = resourceGroup.getLabel();
String description = resourceGroup.getDescription();
LOGGER.info("ID: " + resourceGroupId
+ "\t Source-ID: " + sourceId
+ " Label: " + label + " Description: " + description);
}
transaction.commit();
} catch ( HibernateException e ) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public void addResourceGroup(String description, String label, Integer soruceId) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Source source = new Source(); // An empty project has to be initialized in order to to
// add the foreign key constraint of the project to the ResourceGroup
ResourceGroup newResourceGroup = new ResourceGroup();
newResourceGroup.setDescription(description);
newResourceGroup.setLabel(label);
newResourceGroup.setSource(source); // Add the project property to ResourceGroup -> ProjectId constraint
// source.setId(sourceId); // assign a certain projectId (type long) to the added project
session.save(newResourceGroup); // save the new data set
transaction.commit(); // commit the transaction execution to the database
} catch (HibernateException e) { // common hibernate procedure to catch errors
transaction.rollback();
e.printStackTrace();
} finally { // close the session in both cases
session.close();
}
}
@SuppressWarnings("unchecked")
public String searchResourceGroupDescription(String label) {
String resourceGroupDescription = null;
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Query query = session.createQuery("from ResourceGroup");
List<ResourceGroup> resourceGroupEntry = query.list();
for (ResourceGroup resourceGroup : resourceGroupEntry) {
if (resourceGroup.getLabel().equals(label)) {
resourceGroupDescription = resourceGroup.getDescription();
}
}
/*
Query query = session.createQuery("select rg.Description from resourcegroup rg where Label := setResourceGroupLabel");
query.setParameter("setResourceGroupLabel", label);
resourceGroupDescription = (String) query.executeUpdate();
*/
} catch ( HibernateException e ) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
if (resourceGroupDescription == null) {
LOGGER.info("\nThe label expression '" + label + "' doesn't exist!");
} else {
LOGGER.info("\nThe label expression '" + label + "' is equivalent to the descpription '" + resourceGroupDescription + "'."); }
return resourceGroupDescription;
}
}
|
package com.mmc.design.pattern.extend;
/**
* @packageName:com.mmc.design.pattern.extend
* @desrciption: 转换成大写
* @author: gaowei
* @date: 2018-10-16 15:34
* @history: (version) author date desc
*/
public class Upcase extends Processor {
@Override
String process(Object input) {
return ((String)input).toUpperCase();
}
}
|
package symap.closeup;
import colordialog.ColorListener;
interface HitDialogInterface extends ColorListener {
public int getNumberOfHits();
public int showIfHits();
}
|
import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.*;
import java.util.stream.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int flatlandSpaceStations(int n, int[] c) {
TreeSet<Integer> stations = IntStream.of(c).boxed().collect(Collectors.toCollection(TreeSet :: new));
int l = stations.pollFirst();
AtomicInteger e = new AtomicInteger(l);
int m = stations.stream().mapToInt(s -> s - e.getAndSet(s)).max().orElse(0);
int h = Optional.ofNullable(stations.pollLast()).map(p -> n - 1 - p).orElse(n - 1 - l);
return (int) Math.max(m % 2 == 0 ? m / 2 : (m - 1) / 2, Math.max(l, h));
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[] c = new int[m];
for(int c_i = 0; c_i < m; c_i++){
c[c_i] = in.nextInt();
}
int result = flatlandSpaceStations(n, c);
System.out.println(result);
in.close();
}
}
|
public class Motorrad extends Fahrzeug
{
private int ps;
public Motorrad(String kennzeichen, int baujahr, int ps) throws AutoException
{
super(kennzeichen, baujahr);
setPs(ps);
}
public Motorrad(String zeile) throws AutoException
{
super(zeile);
try {
String[] eigenschaften=zeile.split(";");
// 0 1 2 3
//Motorrad;WN-345V;2001;50
setPs(Integer.parseInt( eigenschaften[3].trim() ));
}
catch(ArrayIndexOutOfBoundsException e)
{
throw new AutoException("Fehler : ungültiges format");
}
catch(NumberFormatException e)
{
throw new AutoException("Fehler : ungültiges PS!");
}
}
public int getPs()
{
return ps;
}
public void setPs(int ps) throws AutoException
{
if (ps >= 10)
{
this.ps = ps;
}
else
{
throw new AutoException("Fehler: zu wenig ps.");
}
}
public String toStringCSV()
{
return "Motorrad" + super.toStringCSV()+";" + ps;
}
public String toString()
{
return super.toString() + ": " + ps + " PS";
}
public double getGeld()
{
if (ps < 50)
{
return 5;
}
else
{
return 10;
}
}
}
|
package com.cg.healthify.services;
import java.util.List;
import javax.persistence.EntityManager;
import com.cg.healthify.daos.CaloriesLogDAO;
import com.cg.healthify.daos.CaloriesLogDAOImpl;
import com.cg.healthify.exceptions.NegativeIdEntryException;
import com.cg.healthify.pojo.CaloriesLog;
import com.cg.healthify.util.DBUtil;
public class CaloriesLogServiceImpl extends DBUtil implements CaloriesLogService {
public CaloriesLogDAO calorieslogDAO;
public CaloriesLogServiceImpl() {
calorieslogDAO=new CaloriesLogDAOImpl();
}
@Override
public CaloriesLog addCaloriesLog(CaloriesLog calories) {
return calorieslogDAO.addUserCalories(calories);
}
@Override
public CaloriesLog UpdateCaloriesLog(CaloriesLog calories) throws NegativeIdEntryException, NullPointerException{
EntityManager em=DBUtil.emf.createEntityManager();
em.getTransaction().begin();
CaloriesLog log=em.find(CaloriesLog.class, calories.getId());
if(calories.getId()<0) {
throw new NegativeIdEntryException();
}
else if(log!=null) {
calorieslogDAO.updateUserCalories(calories);
return calories;
}
else {
throw new NullPointerException();
}
}
@Override
public CaloriesLog DeleteCaloriesLog(CaloriesLog calories) {
return calorieslogDAO.deleteUserCalories(calories);
}
@Override
public List<CaloriesLog> findAll() {
return calorieslogDAO.findAll();
}
@Override
public CaloriesLog findById(int id) throws NullPointerException, NegativeIdEntryException {
if(id<0) {
throw new NegativeIdEntryException();
}
else {
CaloriesLog log=calorieslogDAO.findById(id);
return log;
}
}
@Override
public void validateId(int id) throws NegativeIdEntryException {
if(id<0) {
throw new NegativeIdEntryException("Id should not be null.");
}
}
}
|
package ua.siemens.dbtool.serializers.WorkPackage;
import com.google.gson.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ua.siemens.dbtool.model.entities.Job;
import ua.siemens.dbtool.model.entities.WorkPackage;
import ua.siemens.dbtool.serializers.Job.BasicJobSerializer;
import java.lang.reflect.Type;
public class BasicWpsSerializer implements JsonSerializer<WorkPackage> {
private static final Logger LOG = LoggerFactory.getLogger(BasicWpsSerializer.class);
private Gson basicJobsSerializer;
public BasicWpsSerializer() {
this.basicJobsSerializer = new GsonBuilder()
.registerTypeAdapter(Job.class, new BasicJobSerializer())
.create();
}
@Override
public JsonElement serialize(WorkPackage wp, Type typeOfSrc, JsonSerializationContext context) {
// LOG.debug(">> serialize()");
JsonObject basicWp = new JsonObject();
basicWp.addProperty("id", wp.getId());
basicWp.addProperty("extensionName", wp.getExtensionName());
basicWp.addProperty("projectId", wp.getProject().getId());
basicWp.addProperty("wpTypeName", wp.getWpType().getName());
basicWp.addProperty("projectName", wp.getProject().getId());
basicWp.addProperty("status", wp.getStatus().getName());
JsonArray jsonJobs = new JsonArray();
for(Job job: wp.getJobs()){
jsonJobs.add(basicJobsSerializer.toJsonTree(job));
}
basicWp.add("basicJobs", jsonJobs);
// LOG.debug("<< serialize()");
return basicWp;
}
}
|
package com.wkrzywiec.spring.library.service;
import java.io.IOException;
import org.springframework.stereotype.Component;
import com.wkrzywiec.spring.library.retrofit.RandomQuoteAPI;
import com.wkrzywiec.spring.library.retrofit.model.RandomQuoteResponse;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
@Component
public class RandomQuoteService {
public RandomQuoteResponse getRandomResponse() {
RandomQuoteResponse randomQuote = null;
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://talaikis.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
RandomQuoteAPI randomQuoteAPI = retrofit.create(RandomQuoteAPI.class);
Call<RandomQuoteResponse> callSync = randomQuoteAPI.getRandomQuote();
try {
Response<RandomQuoteResponse> response = callSync.execute();
randomQuote = response.body();
} catch (IOException e) {
e.printStackTrace();
}
return randomQuote;
}
}
|
package com.example.projet20.ui.home;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.fragment.NavHostFragment;
import com.example.projet20.R;
import com.example.projet20.ui.History;
import com.example.projet20.ui.Match;
public class HomeFragment extends Fragment {
//fragment menu ( ouvert quand l'utilisateur click sur le bouton home)
public HomeFragment(){
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
};
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.New).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// ouvre le fragment match
loadFragment(new Match());
}
});
view.findViewById(R.id.History).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// ouvre le fragment History
loadFragment(new History());
}
});
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) { // même fonction présente dans l'activité principale
HomeFragment.this.getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.commit();
return true;
}
return false;
}
}
|
package com.vkoval.addressbook.controller;
import com.vkoval.addressbook.dao.UserRepository;
import com.vkoval.addressbook.entity.user.Role;
import com.vkoval.addressbook.entity.user.User;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
private UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@PostMapping("/admins")
public String postAdmin(@RequestBody User user) {
if (user == null || StringUtils.isEmpty(user.getLogin())) {
return "Пустой запрос";
}
if (StringUtils.isEmpty(user.getPassword())) {
return "Пароль не может быть пустым";
}
user.setRole(Role.ADMIN);
userRepository.save(user);
return null;
}
}
|
package info.datacluster.crawler.listener;
import info.datacluster.common.zookeeper.ZookeeperClient;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
public class TaskNodeListener implements NodeCacheListener {
private ZookeeperClient zookeeperClient;
//监听zookeeper的任务节点
private NodeCache taskNode;
private String taskPath;
public TaskNodeListener(ZookeeperClient zookeeperClient, String path) {
this.zookeeperClient = zookeeperClient;
this.taskPath = path;
}
@Override
public void nodeChanged() throws Exception {
}
}
|
package com.mabang.android.okhttp.callback;
import com.google.gson.Gson;
import java.lang.reflect.ParameterizedType;
import okhttp3.Response;
/**
* @author View
* @date 2016/11/27 16:34
*/
public abstract class JsonCallback<T> extends Callback<T> {
protected Class<T> clazz;
public JsonCallback() {
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
if (pt != null && pt.getActualTypeArguments().length > 0) {
this.clazz = (Class) pt.getActualTypeArguments()[0];
}
}
@Override
public T parseNetworkResponse(Response response, int id) throws Exception {
String string = response.body().string();
T t = new Gson().fromJson(string, clazz);
return t;
}
}
|
package com.citibank.ods.persistence.pl.dao.rdb.oracle;
import com.citibank.ods.common.persistence.dao.rdb.oracle.BaseOracleDAO;
import com.citibank.ods.persistence.pl.dao.BaseTplProdPlayerRoleDAO;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
*@author acacio.domingos,Apr 10, 2007
*
*/
public abstract class BaseOracleTplProdPlayerRoleDAO extends BaseOracleDAO implements
BaseTplProdPlayerRoleDAO
{
/** Constantes que representam os campos genericos das tabelas
* @see com.citibank.ods.persistence.pl.dao.BaseTplProdPlayerRoleDAO#find(com.citibank.ods.entity.pl.BaseTplProdPlayerRoleEntity)
*/
protected String C_PROD_CODE = "PROD_CODE";
protected String C_SYS_CODE = "SYS_CODE";
protected String C_SYS_SEG_CODE = "SYS_SEG_CODE";
protected String C_PLYR_CNPJ_NBR = "PLYR_CNPJ_NBR";
protected String C_PLYR_ROLE_TYPE_CODE = "PLYR_ROLE_TYPE_CODE";
protected String C_LAST_UPD_USER_ID = "LAST_UPD_USER_ID";
protected String C_LAST_UPD_DATE = "LAST_UPD_DATE";
}
|
package khoapham.ptp.phamtanphat.appluutruthongtin1903.API;
public class DataResponse {
private static final String base_url = "https://servertest12.herokuapp.com/";
public static APICallback sendRequest(){
return Retrofitinit.initRetro(base_url).create(APICallback.class);
}
}
|
package com.nowcoder.community.service;
import com.nowcoder.community.dao.CommentMapper;
import com.nowcoder.community.dao.DiscussionPostMapper;
import com.nowcoder.community.entity.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class CommentService {
@Autowired
private CommentMapper commentMapper;
@Autowired
private DiscussionPostMapper discussionPostMapper;
public List<Comment> getCommentByEntityTypeAndEntityId(int entityType,int entityId,int offset,int limit){
return commentMapper.selectComments(entityType,entityId,offset,limit);
}
public int getCommentCountByEntityTypeAndEntityId(int entityType,int entityId){
return commentMapper.getTotalOfComment(entityType,entityId);
}
@Transactional()
public void addComment(Comment comment){
}
}
|
/**
*/
package iso20022.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import iso20022.Iso20022Package;
import iso20022.MessageDefinition;
import iso20022.SyntaxMessageScheme;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Syntax Message Scheme</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link iso20022.impl.SyntaxMessageSchemeImpl#getMessageDefinitionTrace <em>Message Definition Trace</em>}</li>
* </ul>
*
* @generated
*/
public class SyntaxMessageSchemeImpl extends TopLevelCatalogueEntryImpl implements SyntaxMessageScheme {
/**
* The cached value of the '{@link #getMessageDefinitionTrace() <em>Message Definition Trace</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMessageDefinitionTrace()
* @generated
* @ordered
*/
protected MessageDefinition messageDefinitionTrace;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SyntaxMessageSchemeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Iso20022Package.eINSTANCE.getSyntaxMessageScheme();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MessageDefinition getMessageDefinitionTrace() {
if (messageDefinitionTrace != null && messageDefinitionTrace.eIsProxy()) {
InternalEObject oldMessageDefinitionTrace = (InternalEObject)messageDefinitionTrace;
messageDefinitionTrace = (MessageDefinition)eResolveProxy(oldMessageDefinitionTrace);
if (messageDefinitionTrace != oldMessageDefinitionTrace) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, Iso20022Package.SYNTAX_MESSAGE_SCHEME__MESSAGE_DEFINITION_TRACE, oldMessageDefinitionTrace, messageDefinitionTrace));
}
}
return messageDefinitionTrace;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MessageDefinition basicGetMessageDefinitionTrace() {
return messageDefinitionTrace;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetMessageDefinitionTrace(MessageDefinition newMessageDefinitionTrace, NotificationChain msgs) {
MessageDefinition oldMessageDefinitionTrace = messageDefinitionTrace;
messageDefinitionTrace = newMessageDefinitionTrace;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Iso20022Package.SYNTAX_MESSAGE_SCHEME__MESSAGE_DEFINITION_TRACE, oldMessageDefinitionTrace, newMessageDefinitionTrace);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMessageDefinitionTrace(MessageDefinition newMessageDefinitionTrace) {
if (newMessageDefinitionTrace != messageDefinitionTrace) {
NotificationChain msgs = null;
if (messageDefinitionTrace != null)
msgs = ((InternalEObject)messageDefinitionTrace).eInverseRemove(this, Iso20022Package.MESSAGE_DEFINITION__DERIVATION, MessageDefinition.class, msgs);
if (newMessageDefinitionTrace != null)
msgs = ((InternalEObject)newMessageDefinitionTrace).eInverseAdd(this, Iso20022Package.MESSAGE_DEFINITION__DERIVATION, MessageDefinition.class, msgs);
msgs = basicSetMessageDefinitionTrace(newMessageDefinitionTrace, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.SYNTAX_MESSAGE_SCHEME__MESSAGE_DEFINITION_TRACE, newMessageDefinitionTrace, newMessageDefinitionTrace));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.SYNTAX_MESSAGE_SCHEME__MESSAGE_DEFINITION_TRACE:
if (messageDefinitionTrace != null)
msgs = ((InternalEObject)messageDefinitionTrace).eInverseRemove(this, Iso20022Package.MESSAGE_DEFINITION__DERIVATION, MessageDefinition.class, msgs);
return basicSetMessageDefinitionTrace((MessageDefinition)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.SYNTAX_MESSAGE_SCHEME__MESSAGE_DEFINITION_TRACE:
return basicSetMessageDefinitionTrace(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Iso20022Package.SYNTAX_MESSAGE_SCHEME__MESSAGE_DEFINITION_TRACE:
if (resolve) return getMessageDefinitionTrace();
return basicGetMessageDefinitionTrace();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Iso20022Package.SYNTAX_MESSAGE_SCHEME__MESSAGE_DEFINITION_TRACE:
setMessageDefinitionTrace((MessageDefinition)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Iso20022Package.SYNTAX_MESSAGE_SCHEME__MESSAGE_DEFINITION_TRACE:
setMessageDefinitionTrace((MessageDefinition)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Iso20022Package.SYNTAX_MESSAGE_SCHEME__MESSAGE_DEFINITION_TRACE:
return messageDefinitionTrace != null;
}
return super.eIsSet(featureID);
}
} //SyntaxMessageSchemeImpl
|
package com.reptile.util;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.message.BasicHttpResponse;
import com.reptile.util.constants.ReptileConstants;
/**
* @author LiuEnYuan
* @version 1.1 http utils
**/
public class HttpUtils {
/**
* get raw html
* @param client
* @param url
* @throws IOException
* when http server response failure,can throws {@link IOException}
* **/
public static HttpResponse getRawHtml(HttpClient client, String url) {
HttpGet getMethod = new HttpGet(url);
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, ReptileConstants.OK);
try {
response=client.execute(getMethod);
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}finally {
//getMethod.abort();
}
return response;
}
}
|
package khosbayar.hs.com.droidpheramor.models;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
public class User implements Parcelable {
private String email;
private String password;
private String fullName;
private String zip;
private String feet;
private String inch;
private int gender;
private String dob;
private boolean interestMale;
private boolean interestFemale;
private int ageRangeMin;
private int ageRangeMax;
private int race;
private int religion;
private Uri img;
//write object values to parcel for storage
public void writeToParcel(Parcel dest, int flags) {
//write all properties to the parcle
dest.writeString(email);
dest.writeString(password);
dest.writeString(fullName);
dest.writeString(zip);
dest.writeString(feet);
dest.writeString(inch);
dest.writeInt(gender);
dest.writeString(dob);
dest.writeValue(interestMale);
dest.writeValue(interestFemale);
dest.writeInt(ageRangeMin);
dest.writeInt(ageRangeMax);
dest.writeInt(race);
dest.writeInt(religion);
dest.writeValue(img);
}
//constructor used for parcel
public User(Parcel parcel) {
//read and set saved values from parcel
email = parcel.readString();
password = parcel.readString();
fullName = parcel.readString();
zip = parcel.readString();
feet = parcel.readString();
inch = parcel.readString();
gender = parcel.readInt();
dob = parcel.readString();
interestMale = (Boolean) parcel.readValue(Boolean.class.getClassLoader());
interestFemale = (Boolean) parcel.readValue(Boolean.class.getClassLoader());
ageRangeMin = parcel.readInt();
ageRangeMax = parcel.readInt();
race = parcel.readInt();
religion = parcel.readInt();
img = (Uri) parcel.readValue(Uri.class.getClassLoader());
}
public User(){}
//creator - used when un-parceling our parcle (creating the object)
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
@Override
public User createFromParcel(Parcel parcel) {
return new User(parcel);
}
@Override
public User[] newArray(int size) {
return new User[0];
}
};
//return hashcode of object
public int describeContents() {
return hashCode();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getFeet() {
return feet;
}
public void setFeet(String feet) {
this.feet = feet;
}
public String getInch() {
return inch;
}
public void setInch(String inch) {
this.inch = inch;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public boolean isInterestMale() {
return interestMale;
}
public void setInterestMale(boolean interestMale) {
this.interestMale = interestMale;
}
public boolean isInterestFemale() {
return interestFemale;
}
public void setInterestFemale(boolean interestFemale) {
this.interestFemale = interestFemale;
}
public int getAgeRangeMin() {
return ageRangeMin;
}
public void setAgeRangeMin(int ageRangeMin) {
this.ageRangeMin = ageRangeMin;
}
public int getAgeRangeMax() {
return ageRangeMax;
}
public void setAgeRangeMax(int ageRangeMax) {
this.ageRangeMax = ageRangeMax;
}
public int getRace() {
return race;
}
public void setRace(int race) {
this.race = race;
}
public int getReligion() {
return religion;
}
public void setReligion(int religion) {
this.religion = religion;
}
public Uri getImg() {
return img;
}
public void setImg(Uri img) {
this.img = img;
}
}
|
package picoplaca;
import java.math.BigDecimal;
import java.util.Scanner;
public class PicoPlacaValidator {
private String _plateNumber;
private String _dateCar;
private String _timeCar;
static Scanner scan;
DateValidator objDateValidator;
static String executionControl = "C";
public PicoPlacaValidator(){
validateDate();
validateTime();
validatePlate();
DataMemory.createData();
}
public PicoPlacaValidator(String dummyVal){
}
public PicoPlacaValidator(String inputData, String dummyVal){
String[] inputArray = inputData.split(",");
String dateCar = inputArray[0];
String timeCar = inputArray[1];
String plateNumber = inputArray[2];
objDateValidator = new DateValidator(dateCar);
if(objDateValidator.validate()){
this._timeCar = timeCar;
this._plateNumber = plateNumber;
}
DataMemory.createData();
}
public String getDateCar(){
return this._dateCar;
}
public String getTimeCar(){
return this._timeCar;
}
public String getPlateNumber(){
return this._plateNumber;
}
public static void main(String[] args) {
scan = new Scanner(System.in);
while(executionControl.equals("C")){
PicoPlacaValidator objPico = new PicoPlacaValidator();
objPico.verifyPlate();
executionControl = "";
while(!executionControl.equals("C") && !executionControl.equals("E")){
System.out.println("[Press (C)ontinue or (E)xit]");
executionControl = scan.nextLine().toUpperCase();
}
}
System.out.println("[Program Finished] ********************************");
scan.close();
}
public String verifyPlate(){
String message="";
//get day of week
String dayCompare = objDateValidator.convert();
//get time in decimal format
TimeValidator objTimeValidator = new TimeValidator(this._timeCar);
BigDecimal timeCompare = new BigDecimal(objTimeValidator.convert());
//get last digits of plate numbers authorized
String endingNumbers = DataMemory.get_daysPlate().get(dayCompare);
boolean authorized=false;
String timeRange=null;
if(endingNumbers == null){
//if day if not in hash map then is authorized
authorized = true;
}else{
String minHour="";
String maxHour="";
if(timeCompare.compareTo(new BigDecimal(12)) <= 0){
//search in morning
timeRange = DataMemory.getAllowedHours().get("MORNING");
minHour = timeRange.substring(0,4);
maxHour = timeRange.substring(5);
}else{
//search in afternoon
timeRange = DataMemory.getAllowedHours().get("AFTERNOON");
minHour = timeRange.substring(0,5);
maxHour = timeRange.substring(6);
}
BigDecimal minHourDecimal = new BigDecimal(minHour);
BigDecimal maxHourDecimal = new BigDecimal(maxHour);
//check if the time entered is in the allowed range
if((timeCompare.compareTo(minHourDecimal) >= 0) && (timeCompare.compareTo(maxHourDecimal) <= 0)){
String[] charArray = endingNumbers.split("-");
for(int i=0;i<=charArray.length-1;i++){
//check if the last digit of plate number is authorized
if(this._plateNumber.substring(this._plateNumber.length()-1).equals(String.valueOf(charArray[i]))){
authorized = true;
break;
}
}
}else{
authorized = true;
}
}
//show result message
System.out.println("[[DATA ENTERED]]");
System.out.println("Date: " + this._dateCar);
System.out.println("Time: " + this._timeCar);
System.out.println("Plate Number: " + this._plateNumber);
System.out.println("");
if(authorized){
message = "<< The Car is Authorizad >>";
}else{
message = "<< The Car is Not Authorizad >>";
}
System.out.println(message);
System.out.println("");
return message;
}
public String validatePlate(){
String message="";
while(this._plateNumber == null){
System.out.println("****************************************************");
System.out.println("Please insert your plate number. e.g.: [ABC-123]");
String plateNumber = scan.nextLine();
PlateValidator objPlateValidator = new PlateValidator(plateNumber);
if(objPlateValidator.validate()){
this._plateNumber = plateNumber;
message = "<< The plate number is valid. Ok. >>";
//System.out.println("<< The plate number is valid. Ok. >>");
System.out.println("****************************************************");
//scan.close();
}else{
message = "<< The plate number is invalid. >>";
System.out.println(message);
}
}
return message;
}
public String validateDate(){
String message="";
while(this._dateCar == null){
System.out.println("****************************************************");
System.out.println("Please insert the date. e.g. [20/06/2010]");
String date = scan.nextLine();
objDateValidator = new DateValidator(date);
if(objDateValidator.validate()){
this._dateCar = date;
message = "<< The date is valid. Ok. >>";
//System.out.println("<< The date is valid. Ok. >>");
//scan.close();
}else{
message = "<< The date is invalid. >>";
System.out.println(message);
}
}
return message;
}
public String validateTime(){
String message="";
while(this._timeCar == null){
System.out.println("****************************************************");
System.out.println("Please insert the time. e.g.: [04:45] 24-hrs (hh:mm)");
String time = scan.nextLine();
TimeValidator objTimeValidator = new TimeValidator(time);
if(objTimeValidator.validate()){
this._timeCar = time;
message="<< The time is valid. Ok. >>";
//System.out.println("<< The time is valid. Ok. >>");
//scan.close();
}else{
message = "<< The time is invalid. >>";
System.out.println(message);
}
}
return message;
}
}
|
package com.karya.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.karya.dao.IItemWisePurRegisterDao;
import com.karya.model.ItemWisePurRegister001MB;
import com.karya.model.PaymentEntry001MB;
import com.karya.model.PaymentRequest001MB;
import com.karya.service.IItemWisePurRegisterService;
@Service("itemwisepurregisterService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ItemWisePurRegisterServiceImpl implements IItemWisePurRegisterService{
@Autowired
private IItemWisePurRegisterDao itemwisepuregisterDao;
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void additemwisepurregister(ItemWisePurRegister001MB itemwisepurregiste001mb) {
itemwisepuregisterDao.additemwisepurregister(itemwisepurregiste001mb);
}
public List<ItemWisePurRegister001MB> listitemwisepurregister() {
return itemwisepuregisterDao.listitemwisepurregister();
}
public ItemWisePurRegister001MB getitemwisepurregister(int iwprId) {
return itemwisepuregisterDao.getitemwisepurregister(iwprId);
}
public void deleteitemwisepurregister(int iwprId) {
itemwisepuregisterDao.deleteitemwisepurregister(iwprId);
}
//Payment request
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addpaymentrequest(PaymentRequest001MB paymentrequest001mb) {
itemwisepuregisterDao.addpaymentrequest(paymentrequest001mb);
}
public List<PaymentRequest001MB> listpaymentrequest() {
return itemwisepuregisterDao.listpaymentrequest();
}
public PaymentRequest001MB getpaymentrequest(int payreqId) {
return itemwisepuregisterDao.getpaymentrequest(payreqId);
}
public void deletepaymentrequest(int payreqId) {
itemwisepuregisterDao.deletepaymentrequest(payreqId);
}
//Payment entry
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addpaymententry(PaymentEntry001MB paymententry001mb) {
itemwisepuregisterDao.addpaymententry(paymententry001mb);
}
public List<PaymentEntry001MB> listpaymententry() {
return itemwisepuregisterDao.listpaymententry();
}
public PaymentEntry001MB getpaymententry(int payentId) {
return itemwisepuregisterDao.getpaymententry(payentId);
}
public void deletepaymententry(int payentId) {
itemwisepuregisterDao.deletepaymententry(payentId);
}
}
|
package com.lipnus.gleam.model;
/**
* Created by LIPNUS on 2017-10-29.
*/
public class Mypage {
public String color; //무슨 색 화장품인지
public int count; //몇개인지
}
|
package com.gxtc.huchuan.bean;
import java.io.Serializable;
/**
* 来自 伍玉南 的装逼小尾巴 on 17/8/31.
*/
public class WithdrawRecordBean implements Serializable {
private static final long serialVersionUID = 1L;
/**
* createTime : 1499220490000
* id : 31
* money : 50.00
* openingBank :
* userAccount : 1092723495@qq.com
* userName : ,
* withdrawCashType : 2
* withdrawStatus : 2
*/
private String createTime;
private String id;
private double money;
private String openingBank;
private String userAccount;
private String userName;
private int withdrawCashType;
private int withdrawStatus;
public String getCreateTime() { return createTime;}
public void setCreateTime(String createTime) { this.createTime = createTime;}
public String getId() { return id;}
public void setId(String id) { this.id = id;}
public double getMoney() { return money;}
public void setMoney(double money) { this.money = money;}
public String getOpeningBank() { return openingBank;}
public void setOpeningBank(String openingBank) { this.openingBank = openingBank;}
public String getUserAccount() { return userAccount;}
public void setUserAccount(String userAccount) { this.userAccount = userAccount;}
public String getUserName() { return userName;}
public void setUserName(String userName) { this.userName = userName;}
public int getWithdrawCashType() { return withdrawCashType;}
public void setWithdrawCashType(int withdrawCashType) { this.withdrawCashType = withdrawCashType;}
public int getWithdrawStatus() { return withdrawStatus;}
public void setWithdrawStatus(int withdrawStatus) { this.withdrawStatus = withdrawStatus;}
}
|
package com.example.autopermission.bean;
import java.io.Serializable;
public class ASStepBean implements Serializable {
/**
* 一步需要的延迟时间
*/
public int delay_time;
/**
* 需要找到的文本
*/
public String find_text;
/**
* 行为(点击, 选择)
*/
public String action_type;
/**
* //点击类型,parent 点击这个控件的父容器,child点击指定的控件(reality_node_id 不能为空,findId=true 采用 accessibilityNodeInfosByViewId方式) system,点击系统的返回按键,self 点击自己
*/
public String click_type;
/**
* 精确查找
*/
public boolean findId;
/**
* 禁止滚动
*/
public boolean banScrollable;
/**
* 控件无法点击的提示文案
*/
public String clickFailToast;
public String reality_node_name;
/**
* 查找的ID findId为true 时reality_node_id为全路径ID
*/
public String reality_node_id;
/**
* 指定滚动的控件ID
*/
public String reality_scrollable_node_id;
/**
* 本次任务如果已经完成则移除下一步任务
*/
public boolean checkedRemoveNext;
public int getDelay_time() {
return delay_time;
}
public void setDelay_time(int delay_time) {
this.delay_time = delay_time;
}
public String getFind_text() {
return find_text;
}
public void setFind_text(String find_text) {
this.find_text = find_text;
}
public String getAction_type() {
return action_type;
}
public void setAction_type(String action_type) {
this.action_type = action_type;
}
public String getClick_type() {
return click_type;
}
public void setClick_type(String click_type) {
this.click_type = click_type;
}
public String getReality_node_name() {
return reality_node_name;
}
public void setReality_node_name(String reality_node_name) {
this.reality_node_name = reality_node_name;
}
public String getReality_node_id() {
return reality_node_id;
}
public void setReality_node_id(String reality_node_id) {
this.reality_node_id = reality_node_id;
}
public boolean isFindId() {
return findId;
}
public void setFindId(boolean findId) {
this.findId = findId;
}
public String getReality_scrollable_node_id() {
return reality_scrollable_node_id;
}
public void setReality_scrollable_node_id(String reality_scrollable_node_id) {
this.reality_scrollable_node_id = reality_scrollable_node_id;
}
public boolean isBanScrollable() {
return banScrollable;
}
public void setBanScrollable(boolean banScrollable) {
this.banScrollable = banScrollable;
}
public boolean isCheckedRemoveNext() {
return checkedRemoveNext;
}
public void setCheckedRemoveNext(boolean checkedRemoveNext) {
this.checkedRemoveNext = checkedRemoveNext;
}
public String getClickFailToast() {
return clickFailToast;
}
public void setClickFailToast(String clickFailToast) {
this.clickFailToast = clickFailToast;
}
} |
package web.command.impl;
import classes.util.Resultado;
import dominio.evento.IDominio;
import web.command.AbsCommand;
public class ConsultarCommand extends AbsCommand {
@Override
public Resultado execute(IDominio entidade) {
return fachada.consultar(entidade);
}
}
|
package oops;
import java.util.Scanner;
public class Tariffsingle {
public static void main(String[] args) {
// TODO Auto-generated method stub
Seasonbook ob = new Seasonbook();
ob.roomBooking();
ob.roomBook();
}
}
class Booking {
Scanner s = new Scanner(System.in);
int a,b;
double f;
String c;
void roomBooking() {
System.out.println("Enter the number of Persons");
a = s.nextInt();
System.out.println("Enter the number of days");
b = s.nextInt();
System.out.println("Enter the room type");
c = s.next();
System.out.println("Enter the tariff for single person");
f = s.nextInt();
}
}
class Seasonbook extends Booking{
public void roomBook() {
// TODO Auto-generated method stub
double tot=a*b*f;
System.out.println(tot);
}
}
|
package is.ru.aaad.RemindMe;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.*;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.LatLng;
import is.ru.aaad.RemindMe.Data.LocationsStore;
import is.ru.aaad.RemindMe.Data.RemindersStore;
import is.ru.aaad.RemindMe.Helpers.ErrorDialogFragment;
import is.ru.aaad.RemindMe.Helpers.LocationUtils;
import is.ru.aaad.RemindMe.Helpers.MainPagerAdapter;
import is.ru.aaad.RemindMe.Models.Location;
import is.ru.aaad.RemindMe.Models.Reminder;
/**
* Created by Johannes Gunnar Heidarsson on 15.10.2014.
*/
public class MainActivity extends FragmentActivity implements
LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationsFragment.OnLocationSelectedListener,
RemindersFragment.OnReminderSelectedListener,
ViewPager.OnPageChangeListener{
private MainPagerAdapter mainPagerAdapter;
private LocationsStore locationsStore;
private RemindersStore remindersStore;
private boolean isLarge;
private LocationRequest locationRequest;
private LocationClient locationClient;
private SupportMapFragment mapFragment;
private Location location;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationsStore = LocationsStore.getInstance();
locationsStore.setContext(this);
remindersStore = RemindersStore.getInstance();
remindersStore.setContext(this);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOnPageChangeListener(this);
mainPagerAdapter = new MainPagerAdapter(getSupportFragmentManager(), this);
viewPager.setAdapter(mainPagerAdapter);
isLarge = (getSupportFragmentManager().findFragmentById(R.id.location_fragment) != null);
locationRequest = LocationRequest.create();
locationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
locationClient = new LocationClient(this, this, this);
if(isLarge) {
mapFragment = SupportMapFragment.newInstance();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.map_frame, mapFragment).commit();
}
}
@Override
protected void onStop() {
locationClient.disconnect();
super.onStop();
}
@Override
public void onPause(){
super.onPause();
}
@Override
protected void onStart() {
super.onStart();
locationClient.connect();
}
public void onResume() {
super.onResume();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Choose what to do based on the request code
switch (requestCode) {
// If the request code matches the code sent in onConnectionFailed
case LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST :
switch (resultCode) {
// If Google Play services resolved the problem
case Activity.RESULT_OK:
Log.d(LocationUtils.APPTAG, getString(R.string.resolved));
break;
// If any other result was returned by Google Play services
default:
// Log the result
Log.d(LocationUtils.APPTAG, getString(R.string.no_resolution));
break;
}
default:
// Report that this Activity received an unknown requestCode
Log.d(LocationUtils.APPTAG,
getString(R.string.unknown_activity_request_code, requestCode));
break;
}
}
private boolean servicesConnected(){
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
boolean result;
if(ConnectionResult.SUCCESS == resultCode){
Log.d(LocationUtils.APPTAG, "Google Play services is available");
result = true;
} else {
result = false;
showErrorDialog(resultCode);
}
return result;
}
public void getLocation(View v) {
if (servicesConnected()) {
// Get the current location
android.location.Location currentLocation = locationClient.getLastLocation();
// TODO Display the current location in the UI
}
}
public void addNewLocation(View view){
if(servicesConnected()) {
android.location.Location currentLocation = locationClient.getLastLocation();
Location newLocation = new Location("Location Name");
if(currentLocation == null){
Log.d(LocationUtils.APPTAG, "Could not get current location");
} else {
newLocation.setLatLng(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()));
}
locationsStore.add(newLocation);
ArrayAdapter adapter = (ArrayAdapter) mainPagerAdapter.getLocationsFragment().getListAdapter();
adapter.notifyDataSetChanged();
OnLocationSelected(locationsStore.getPosition(newLocation));
}
}
public void addNewReminder(View view){
remindersStore.add(new Reminder("test", "this is a test", null, false, false, Reminder.Mode.ARRIVING_LEAVING));
ArrayAdapter adapter = (ArrayAdapter<Reminder>) mainPagerAdapter.getRemindersFragment().getListAdapter();
adapter.clear();
adapter.addAll(remindersStore.getAll());
}
@Override
public void OnLocationSelected(int position) {
LocationFragment locationFragment = (LocationFragment) getSupportFragmentManager().findFragmentById(R.id.location_fragment);
if(locationFragment == null){
Log.d("LocationsFragment", "locationFragment does equal null");
Intent intent = new Intent(this, LocationActivity.class);
intent.putExtra("location_position", position);
startActivity(intent);
} else {
Log.d("LocationsFragment", "locationFragment does not equal null");
location = locationsStore.getLocationByPosition(position);
locationFragment.changeLocation(location);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
location.getLatLng(),
16.0f);
mapFragment.getMap().animateCamera(cameraUpdate);
}
}
@Override
public void OnReminderSelected(Reminder reminder) {
Log.d("MainActivity", reminder.getName() + ":" + reminder.getUUID());
Intent intent = new Intent(this, ReminderActivity.class);
intent.putExtra("reminder_uuid", reminder.getUUID());
startActivity(intent);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if(isLarge) {
switch (position) {
case 0:
findViewById(R.id.location_fragment).setVisibility(View.GONE);
findViewById(R.id.reminder_fragment).setVisibility(View.VISIBLE);
break;
case 1:
findViewById(R.id.reminder_fragment).setVisibility(View.GONE);
findViewById(R.id.location_fragment).setVisibility(View.VISIBLE);
break;
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
// Location services
@Override
public void onConnected(Bundle bundle) {
Log.d(LocationUtils.APPTAG, "Location services connected");
}
@Override
public void onDisconnected() {
Log.d(LocationUtils.APPTAG, "Location services disconnected");
}
@Override
public void onLocationChanged(android.location.Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if(connectionResult.hasResolution()){
try{
connectionResult.startResolutionForResult(this, LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e){
e.printStackTrace();
}
} else {
showErrorDialog(connectionResult.getErrorCode());
}
}
private void showErrorDialog(int errorCode){
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(errorCode, this, LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);
if(errorDialog != null){
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(errorDialog);
errorFragment.show(getSupportFragmentManager(), LocationUtils.APPTAG);
}
}
}
|
package cn.edu.zzti.lm.pojo;
/**
* 图书评论信息实体类
* Created by 至尊小涛 on 2018/4/26.
*/
public class Conment {
private String id;
private String userId;
private String bookId;
private String content;
private String conmentTime;
private String remarks;
//用户变量,因为评论要显示发表屏幕的用户的相关信息
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getConmentTime() {
return conmentTime;
}
public void setConmentTime(String conmentTime) {
this.conmentTime = conmentTime;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
}
|
package SeleniumLiveProject1;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
public class validateCreateJobfromBackend {
WebDriver driver;
@BeforeClass
public void beforeClass() {
driver = new FirefoxDriver();
driver.get("https://alchemy.hguy.co/jobs/wp-admin");
}
@Test (priority = 0)
public void Login() {
System.out.println("-----------------------------------------------");
System.out.println("Test case - 'ValidateCreateJobFromBackend' Execution is started");
System.out.println("-----------------------------------------------");
WebElement username = driver.findElement(By.id("user_login"));
WebElement password = driver.findElement(By.id("user_pass"));
username.sendKeys("root");
password.sendKeys("pa$$w0rd");
driver.findElement(By.id("wp-submit")).click();
String Title = driver.getTitle();
System.out.println("Title of the login page is: "+Title);
Assert.assertEquals(Title, "Dashboard ‹ Alchemy Jobs — WordPress");
}
@Test (priority = 1)
public void backendCreateJob() {
String Position = "DineshTesting1";
driver.findElement(By.xpath("/html/body/div[1]/div[1]/div[2]/ul/li[7]/a/div[3]")).click();
driver.findElement(By.xpath("/html/body/div[1]/div[1]/div[2]/ul/li[7]/ul/li[3]/a")).click();
String newTitle = driver.getTitle();
System.out.println("CreateJob page title is: "+newTitle);
Assert.assertEquals(newTitle, "Add Job ‹ Alchemy Jobs — WordPress");
driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[@id=\"post-title-0\"]")).sendKeys(Position);
driver.findElement(By.id("_application")).clear();
driver.findElement(By.id("_application")).sendKeys("dineshbit50@gmail.com");
driver.findElement(By.id("_company_website")).sendKeys("Demo.com");
driver.findElement(By.id("_company_twitter")).sendKeys("1234@DineshDemo");
driver.findElement(By.id("_job_location")).sendKeys("Bangalore");
driver.findElement(By.id("_company_name")).sendKeys("DineshDemo");
WebElement Publish = driver.findElement(By.xpath("/html/body/div[1]/div[2]/div[2]/div[1]/div[3]/div[1]/div/div/div[1]/div/div[1]/div/div[2]/button[2]"));
if (Publish.isEnabled()) {
Publish.click();
}
else {
System.out.println("Publish Button is disabled");
driver.close();
}
driver.findElement(By.xpath("/html/body/div[1]/div[2]/div[2]/div[1]/div[3]/div[1]/div/div/div[1]/div/div[2]/div[3]/div/div/div/div[1]/div/button")).click();
String message = driver.findElement(By.xpath("/html/body/div[1]/div[2]/div[2]/div[1]/div[3]/div[1]/div/div/div[1]/div/div[2]/div[3]/div/div/div/div[2]/div/div[1]")).getText();
System.out.println(message);
Assert.assertEquals(message, Position+ " is now live.");
}
@AfterClass
public void afterClass() {
driver.close();
}
}
|
package com.tech.interview.siply.redbus.repository.contract.users;
import com.tech.interview.siply.redbus.entity.dao.users.Driver;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface DriverRepository extends JpaRepository<Driver, UUID> {
Optional<Driver> findByUserName(String userName);
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* 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
*
* https://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.springframework.jmx.export.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.EmbeddedValueResolver;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotationPredicates;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.annotation.MergedAnnotations.SearchStrategy;
import org.springframework.core.annotation.RepeatableContainers;
import org.springframework.jmx.export.metadata.InvalidMetadataException;
import org.springframework.jmx.export.metadata.JmxAttributeSource;
import org.springframework.lang.Nullable;
import org.springframework.util.StringValueResolver;
/**
* Implementation of the {@link JmxAttributeSource} interface that
* reads annotations and exposes the corresponding attributes.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @author Jennifer Hickey
* @author Stephane Nicoll
* @since 1.2
* @see ManagedResource
* @see ManagedAttribute
* @see ManagedOperation
*/
public class AnnotationJmxAttributeSource implements JmxAttributeSource, BeanFactoryAware {
@Nullable
private StringValueResolver embeddedValueResolver;
@Override
public void setBeanFactory(BeanFactory beanFactory) {
if (beanFactory instanceof ConfigurableBeanFactory cbf) {
this.embeddedValueResolver = new EmbeddedValueResolver(cbf);
}
}
@Override
@Nullable
public org.springframework.jmx.export.metadata.ManagedResource getManagedResource(Class<?> beanClass) throws InvalidMetadataException {
MergedAnnotation<ManagedResource> ann = MergedAnnotations.from(beanClass, SearchStrategy.TYPE_HIERARCHY)
.get(ManagedResource.class).withNonMergedAttributes();
if (!ann.isPresent()) {
return null;
}
Class<?> declaringClass = (Class<?>) ann.getSource();
Class<?> target = (declaringClass != null && !declaringClass.isInterface() ? declaringClass : beanClass);
if (!Modifier.isPublic(target.getModifiers())) {
throw new InvalidMetadataException("@ManagedResource class '" + target.getName() + "' must be public");
}
org.springframework.jmx.export.metadata.ManagedResource bean = new org.springframework.jmx.export.metadata.ManagedResource();
Map<String, Object> map = ann.asMap();
List<PropertyValue> list = new ArrayList<>(map.size());
map.forEach((attrName, attrValue) -> {
if (!"value".equals(attrName)) {
Object value = attrValue;
if (this.embeddedValueResolver != null && value instanceof String text) {
value = this.embeddedValueResolver.resolveStringValue(text);
}
list.add(new PropertyValue(attrName, value));
}
});
PropertyAccessorFactory.forBeanPropertyAccess(bean).setPropertyValues(new MutablePropertyValues(list));
return bean;
}
@Override
@Nullable
public org.springframework.jmx.export.metadata.ManagedAttribute getManagedAttribute(Method method) throws InvalidMetadataException {
MergedAnnotation<ManagedAttribute> ann = MergedAnnotations.from(method, SearchStrategy.TYPE_HIERARCHY)
.get(ManagedAttribute.class).withNonMergedAttributes();
if (!ann.isPresent()) {
return null;
}
org.springframework.jmx.export.metadata.ManagedAttribute bean = new org.springframework.jmx.export.metadata.ManagedAttribute();
Map<String, Object> map = ann.asMap();
MutablePropertyValues pvs = new MutablePropertyValues(map);
pvs.removePropertyValue("defaultValue");
PropertyAccessorFactory.forBeanPropertyAccess(bean).setPropertyValues(pvs);
String defaultValue = (String) map.get("defaultValue");
if (defaultValue.length() > 0) {
bean.setDefaultValue(defaultValue);
}
return bean;
}
@Override
@Nullable
public org.springframework.jmx.export.metadata.ManagedMetric getManagedMetric(Method method) throws InvalidMetadataException {
MergedAnnotation<ManagedMetric> ann = MergedAnnotations.from(method, SearchStrategy.TYPE_HIERARCHY)
.get(ManagedMetric.class).withNonMergedAttributes();
return copyPropertiesToBean(ann, org.springframework.jmx.export.metadata.ManagedMetric.class);
}
@Override
@Nullable
public org.springframework.jmx.export.metadata.ManagedOperation getManagedOperation(Method method) throws InvalidMetadataException {
MergedAnnotation<ManagedOperation> ann = MergedAnnotations.from(method, SearchStrategy.TYPE_HIERARCHY)
.get(ManagedOperation.class).withNonMergedAttributes();
return copyPropertiesToBean(ann, org.springframework.jmx.export.metadata.ManagedOperation.class);
}
@Override
public org.springframework.jmx.export.metadata.ManagedOperationParameter[] getManagedOperationParameters(Method method)
throws InvalidMetadataException {
List<MergedAnnotation<? extends Annotation>> anns = getRepeatableAnnotations(
method, ManagedOperationParameter.class, ManagedOperationParameters.class);
return copyPropertiesToBeanArray(anns, org.springframework.jmx.export.metadata.ManagedOperationParameter.class);
}
@Override
public org.springframework.jmx.export.metadata.ManagedNotification[] getManagedNotifications(Class<?> clazz)
throws InvalidMetadataException {
List<MergedAnnotation<? extends Annotation>> anns = getRepeatableAnnotations(
clazz, ManagedNotification.class, ManagedNotifications.class);
return copyPropertiesToBeanArray(anns, org.springframework.jmx.export.metadata.ManagedNotification.class);
}
private static List<MergedAnnotation<? extends Annotation>> getRepeatableAnnotations(
AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType,
Class<? extends Annotation> containerAnnotationType) {
return MergedAnnotations.from(annotatedElement, SearchStrategy.TYPE_HIERARCHY,
RepeatableContainers.of(annotationType, containerAnnotationType))
.stream(annotationType)
.filter(MergedAnnotationPredicates.firstRunOf(MergedAnnotation::getAggregateIndex))
.map(MergedAnnotation::withNonMergedAttributes)
.collect(Collectors.toList());
}
@SuppressWarnings("unchecked")
private static <T> T[] copyPropertiesToBeanArray(
List<MergedAnnotation<? extends Annotation>> anns, Class<T> beanClass) {
T[] beans = (T[]) Array.newInstance(beanClass, anns.size());
int i = 0;
for (MergedAnnotation<? extends Annotation> ann : anns) {
beans[i++] = copyPropertiesToBean(ann, beanClass);
}
return beans;
}
@Nullable
private static <T> T copyPropertiesToBean(MergedAnnotation<? extends Annotation> ann, Class<T> beanClass) {
if (!ann.isPresent()) {
return null;
}
T bean = BeanUtils.instantiateClass(beanClass);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
bw.setPropertyValues(new MutablePropertyValues(ann.asMap()));
return bean;
}
}
|
package courierserviceapp.domain;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class DateTime {
private static DateFormat df = new SimpleDateFormat("dd/MM/yy");
private static Date date;
private String dateToday;
public DateTime(){
date = new Date();
dateToday = df.format(date);
}
public String getDate(){
return dateToday;
}
}
|
/**
* This class reads Common.cfg and records the variables.
*/
import java.io.BufferedReader;
import java.io.FileReader;
public class CommonCfg {
private int numberOfPreferredNeighbors;
private int unchokingInterval;
private int optimisticUnchokingInterval;
private String fileName;
private int fileSize;
private int pieceSize;
/**
* Constructor. Reads the file and stores the variables.
*/
public CommonCfg() {
try {
FileReader fr = new FileReader("Common.cfg");
BufferedReader br = new BufferedReader(fr);
String currentLine;
String[] words;
int lineNumber = 0;
while((currentLine = br.readLine()) != null) {
words = currentLine.split("\\s+");
switch(lineNumber) {
case 0: numberOfPreferredNeighbors = Integer.parseInt(words[1]);
break;
case 1: unchokingInterval = Integer.parseInt(words[1]);
break;
case 2: optimisticUnchokingInterval = Integer.parseInt(words[1]);
break;
case 3: fileName = words[1];
break;
case 4: fileSize = Integer.parseInt(words[1]);
break;
case 5: pieceSize = Integer.parseInt(words[1]);
break;
}
lineNumber++;
}
}
catch (Exception e){
System.out.println(e);
}
}
/**
* Prints out the recorded variables. Used for testing.
*/
public void printSettingsForTesting() {
System.out.println(numberOfPreferredNeighbors);
System.out.println(unchokingInterval);
System.out.println(optimisticUnchokingInterval);
System.out.println(fileName);
System.out.println(fileSize);
System.out.println(pieceSize);
}
/**
* Getter for numberOfPreferredNeighbors.
* @return int: the numberOfPreferredNeighbors.
*/
public int getNumberOfPreferredNeighbors() {
return numberOfPreferredNeighbors;
}
/**
* Getter for unchokingInterval.
* @return int: the unchokingInterval.
*/
public int getUnchokingInterval() {
return unchokingInterval;
}
/**
* Getter for optimisticUnchokingInterval.
* @return int: the optimisticUnchokingInterval.
*/
public int getOptimisticUnchokingInterval() {
return optimisticUnchokingInterval;
}
/**
* Getter for fileName.
* @return String: the fileName.
*/
public String getFileName() {
return fileName;
}
/**
* Getter for fileSize.
* @return int: the fileSize.
*/
public int getFileSize() {
return fileSize;
}
/**
* Getter for pieceSize.
* @return int: the pieceSize.
*/
public int getPieceSize() {
return pieceSize;
}
}
|
package com.mobile.mobilehardware.exceptions;
/**
* exception
*/
public class MobException extends Exception {
public MobException(String error) {
super(error);
}
public MobException(Throwable throwable) {
super(throwable);
}
}
|
package unidade3;
import java.sql.CallableStatement;
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.Scanner;
public class ClienteApp {
public static String usuario = "curso_java";
public static String senha = "schema";
public static String url = "jdbc:oracle:thin:@192.168.237.89:1521:XE";
public static Connection conexao;
public static void conectaBancoOracle() throws SQLException {
conexao = DriverManager.getConnection(url, usuario, senha);
conexao.setAutoCommit(false); // Realiza todas as operacoes para depois confirmar.
}
public static void desconectaBancoOracle() throws SQLException {
conexao.close();
}
public static void insereCliente(long cpf, String nome, String email) throws SQLException {
String sql = "insert into cliente values ("+ cpf + ", ' "+ nome + " ', ' " + email + " ')";
Statement statement = conexao.createStatement();
statement.execute(sql);
conexao.commit();
}
public static void insereClientePs(long cpf, String nome, String email) throws SQLException {
String sql = "insert into cliente values (?, ?, ?)";
PreparedStatement statement = conexao.prepareStatement(sql);
statement.setLong(1, cpf);
statement.setString(2, nome);
statement.setString(3, email);
statement.executeUpdate();
conexao.commit();
}
public static void insereClienteSp(long cpf, String nome, String email) throws SQLException {
String sql = "{call sp_inserir_cliente(?, ?, ?)}";
CallableStatement cstmt = conexao.prepareCall(sql);
cstmt.setLong(1, cpf);
cstmt.setString(2, nome);
cstmt.setString(3, email);
cstmt.execute();
conexao.commit();
}
public static void consultaCliente(long cpf) throws SQLException {
String sql = "select nome, cpf, email from cliente where cpf = " + cpf + " ";
Statement statement = conexao.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
System.out.println("CPF:" + rs.getLong("cpf") + " Nome:" + rs.getString("nome") + " Email:" + rs.getString("email"));
}
}
public static void consultaTodosClientes() throws SQLException {
String sql = "select nome, cpf, email from cliente";
Statement statement = conexao.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
System.out.println("CPF:" + rs.getLong("cpf") + " Nome:" + rs.getString("nome") + " Email:" + rs.getString("email"));
System.out.println("-----------------------------------------");
}
System.out.println("Numero de clientes listados: " + rs.getRow() + "\n");
}
public static void alteraCliente(long cpf, String nome, String email) throws SQLException {
String sql = "update cliente set nome = ' "+ nome + " ', email= ' " + email + " ' where cpf = " + cpf;
Statement statement = conexao.createStatement();
statement.executeUpdate(sql);
conexao.commit();
}
public static void excluiCliente(long cpf) throws SQLException {
String sql = "delete from cliente where cpf = " + cpf;
Statement statement = conexao.createStatement();
statement.executeUpdate(sql);
conexao.commit();
}
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
int opcao = 0;
long cpf = 0;
String nome, email;
try {
conectaBancoOracle();
while (opcao != 6) {
System.out.println("Sistema de gerenciamento de clientes");
System.out.println("====================================");
System.out.println("Digite [1] para consultar todos os clientes");
System.out.println("Digite [2] para consultar um cliente especifico");
System.out.println("Digite [3] para cadastrar um novo cliente");
System.out.println("Digite [4] para alterar um cliente");
System.out.println("Digite [5] para excluir um cliente");
System.out.println("Digite [6] para sair do sistema");
System.out.println("====================================");
opcao = entrada.nextInt();
switch (opcao) {
case 1:
System.out.println("[1] Consultar todos os clientes");
System.out.println("====================================");
consultaTodosClientes();
break;
case 2:
System.out.println("[2] Consultar um cliente especifico");
System.out.println("Favor informar o CPF");
cpf = entrada.nextLong();
consultaCliente(cpf);
break;
case 3:
System.out.println("[3] Cadastrar um novo cliente");
System.out.println("Favor informar o CPF");
cpf = entrada.nextLong();
entrada.nextLine(); // Para esvaziar o buffer do teclado.
System.out.println("Favor informar o nome");
nome = entrada.nextLine();
System.out.println("Favor informar o e-mail");
email = entrada.nextLine();
// insereCliente(cpf, nome, email);
// insereClientePs(cpf, nome, email);
insereClienteSp(cpf, nome, email);
break;
case 4:
System.out.println("[4] Alterar um cliente");
System.out.println("Favor informar o CPF");
cpf = entrada.nextLong();
entrada.nextLine(); // Para esvaziar o buffer do teclado.
System.out.println("Favor informar o nome");
nome = entrada.nextLine();
System.out.println("Favor informar o e-mail");
email = entrada.nextLine();
alteraCliente(cpf, nome, email);
break;
case 5:
System.out.println("[5] Excluir um cliente");
System.out.println("Favor informar o CPF");
cpf = entrada.nextLong();
entrada.nextLine(); // Para esvaziar o buffer do teclado.
excluiCliente(cpf);
break;
case 6:
System.out.println("Encerrando o sistema...");
break;
default:
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
entrada.close();
}
}
|
package com.example.bootcamp.service;
import com.example.bootcamp.model.ResetPasswordModel;
public interface UserPasswordTokenService {
String sendPasswordResetLink(String emailorPhone);
String verifyPasswordResetLink(String resetLink);
String updatePassword(ResetPasswordModel resetPasswordModel, String link);
}
|
package cartas;
public class DragonDefinitivo extends CartaRequiereSacrificios {
public DragonDefinitivo() {
super();
this.sacrificiosRequeridos = 3;
this.puntosDeAtaque = new Puntos(4500);
this.puntosDeDefensa = new Puntos(3800);
this.nivel = 12;
this.nombre = "Dragon Blanco de Ojos Azules Definitivo";
this.colocarImagenEnCartaDesdeArchivoDeRuta("resources/images/carta_DragonDefinitivo.png");
}
}
|
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.oauth.as;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Date;
import java.util.Locale;
import javax.ws.rs.core.Response;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;
import org.junit.Test;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.oauth.as.OAuthSystemAttributesProvider.GrantFlow;
import pl.edu.icm.unity.oauth.as.token.AccessTokenResource;
import pl.edu.icm.unity.server.api.internal.LoginSession;
import pl.edu.icm.unity.server.api.internal.TokensManagement;
import pl.edu.icm.unity.server.api.internal.TransactionalRunner;
import pl.edu.icm.unity.server.authn.InvocationContext;
import pl.edu.icm.unity.types.authn.AuthenticationRealm;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.oauth2.sdk.AuthorizationSuccessResponse;
import com.nimbusds.oauth2.sdk.GrantType;
import com.nimbusds.oauth2.sdk.ResponseType;
import com.nimbusds.oauth2.sdk.http.HTTPResponse;
import com.nimbusds.openid.connect.sdk.OIDCTokenResponse;
public class AccessTokenResourceTest
{
private TransactionalRunner tx = new TransactionalRunner()
{
@Override
public <T> T runInTransactionRet(TxRunnableRet<T> code) throws EngineException
{
return code.run();
}
@Override
public void runInTransaction(TxRunnable code) throws EngineException
{
code.run();
}
};
@Test
public void userInfoFailsWithWrongClient() throws Exception
{
TokensManagement tokensManagement = new MockTokensMan();
OAuthASProperties config = OAuthTestUtils.getConfig();
AccessTokenResource tested = new AccessTokenResource(tokensManagement, config, null, null, tx);
setupInvocationContext(111);
OAuthAuthzContext ctx = OAuthTestUtils.createContext(config, new ResponseType(ResponseType.Value.CODE),
GrantFlow.authorizationCode, 100);
AuthorizationSuccessResponse step1Resp = OAuthTestUtils.initOAuthFlowAccessCode(tokensManagement,
ctx);
Response r = tested.getToken(GrantType.AUTHORIZATION_CODE.getValue(),
step1Resp.getAuthorizationCode().getValue(),
null,
"https://return.host.com/foo");
assertEquals(HTTPResponse.SC_BAD_REQUEST, r.getStatus());
}
@Test
public void userInfoFailsWithWrongRedirect() throws Exception
{
TokensManagement tokensManagement = new MockTokensMan();
OAuthASProperties config = OAuthTestUtils.getConfig();
AccessTokenResource tested = new AccessTokenResource(tokensManagement, config, null, null, tx);
setupInvocationContext(100);
OAuthAuthzContext ctx = OAuthTestUtils.createContext(config, new ResponseType(ResponseType.Value.CODE),
GrantFlow.authorizationCode, 100);
AuthorizationSuccessResponse step1Resp = OAuthTestUtils.initOAuthFlowAccessCode(tokensManagement,
ctx);
Response r = tested.getToken(GrantType.AUTHORIZATION_CODE.getValue(),
step1Resp.getAuthorizationCode().getValue(),
null,
"https://wrong.com");
assertEquals(HTTPResponse.SC_BAD_REQUEST, r.getStatus());
}
@Test
public void userInfoFailsOnInvalidToken() throws Exception
{
TokensManagement tokensManagement = new MockTokensMan();
OAuthASProperties config = OAuthTestUtils.getConfig();
AccessTokenResource tested = new AccessTokenResource(tokensManagement, config, null, null, tx);
setupInvocationContext(100);
Response resp = tested.getToken(GrantType.AUTHORIZATION_CODE.getValue(),
"1234", null, "https://return.host.com/foo");
assertEquals(400, resp.getStatus());
JSONObject ret = (JSONObject) JSONValue.parse(resp.getEntity().toString());
assertEquals("invalid_grant", ret.get("error"));
}
@Test
public void userInfoWorksWithValidToken() throws Exception
{
TokensManagement tokensManagement = new MockTokensMan();
OAuthASProperties config = OAuthTestUtils.getConfig();
AccessTokenResource tested = new AccessTokenResource(tokensManagement, config, null, null, tx);
setupInvocationContext(100);
OAuthAuthzContext ctx = OAuthTestUtils.createOIDCContext(config,
new ResponseType(ResponseType.Value.CODE),
GrantFlow.authorizationCode, 100, "nonce");
AuthorizationSuccessResponse step1Resp = OAuthTestUtils.initOAuthFlowAccessCode(tokensManagement,
ctx);
Response resp = tested.getToken(GrantType.AUTHORIZATION_CODE.getValue(),
step1Resp.getAuthorizationCode().getValue(), null, "https://return.host.com/foo");
HTTPResponse httpResp = new HTTPResponse(resp.getStatus());
httpResp.setContent(resp.getEntity().toString());
httpResp.setContentType("application/json");
OIDCTokenResponse parsed = OIDCTokenResponse.parse(httpResp);
assertNotNull(parsed.getOIDCTokens().getAccessToken());
assertNotNull(parsed.getOIDCTokens().getIDToken());
JWTClaimsSet idToken = parsed.getOIDCTokens().getIDToken().getJWTClaimsSet();
assertEquals("userA", idToken.getSubject());
assertTrue(idToken.getAudience().contains("clientC"));
assertEquals(OAuthTestUtils.ISSUER, idToken.getIssuer());
}
private void setupInvocationContext(long entityId)
{
AuthenticationRealm realm = new AuthenticationRealm("foo", "", 5, 10, -1, 1000);
InvocationContext virtualAdmin = new InvocationContext(null, realm);
LoginSession loginSession = new LoginSession("sid", new Date(), 1000, entityId, "foo");
virtualAdmin.setLoginSession(loginSession);
virtualAdmin.setLocale(Locale.ENGLISH);
InvocationContext.setCurrent(virtualAdmin);
}
}
|
package com.octave.mapper;
import com.octave.entity.PostOrder;
import org.springframework.stereotype.Component;
import java.util.List;
@Component("orderMapper")
public interface OrderMapper {
int deleteByPrimaryKey(Integer orderId);
int insert(PostOrder record);
int insertSelective(PostOrder record);
PostOrder selectByPrimaryKey(Integer orderId);
int updateByPrimaryKeySelective(PostOrder record);
int updateByPrimaryKey(PostOrder record);
/**
* 通过用户id获取
*
* @param uid
* @return
*/
List<PostOrder> listByUserId(Integer uid);
/**
* 通过订单号数组获取
*
* @param ids
* @return
*/
List<PostOrder> listByIds(Integer[] ids);
/**
* 通过寄件方或收件方电话获取
*
* @param tel
* @return
*/
List<PostOrder> listByTel(String tel);
} |
package compiler.nodes;
import java.util.ArrayList;
import compiler.virtualMachine.Visitor.NodeVisitor;
public class FunctionCall extends AbstractFunctionCall{
public FunctionCall(){
parameters = new ArrayList<String>();
}
@Override
public void Accept(NodeVisitor visitor) {
visitor.visit(this);
}
}
|
package com.mvalho.study.pattern.factory.model;
public enum ShapeType {
CIRCLE, RECTANGLE, SQUARE;
}
|
package br.com.oliversys.mmnsimplify.domainmodel.aggregate.entity;
import org.hibernate.validator.constraints.br.CPF;
import br.com.oliversys.mmnsimplify.domainmodel.aggregate.root.ProspectoAggRoot;
import br.com.oliversys.mmnsimplify.domainmodel.valueobject.DadosFormularioCadastroEmpresaMMN;
public class Consultor {
@CPF
private String cpf;
private ProspectoAggRoot prospecto;
private DadosFormularioCadastroEmpresaMMN cadastro;
private boolean isDireto;
}
|
package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Scaling;
import com.mygdx.assets.AssetHandler;
import com.mygdx.extras.PermanetPlayer;
import com.mygdx.renderable.Player;
import com.mygdx.shop.Shop;
import java.util.List;
/**
* Shop Screen to allow player to get more items.
* @author Inder, Vanessa
*/
public class ShopScreen implements Screen {
/** If the Screen is Paused */
private boolean isPaused = false;
/** An instance of main */
private Main main;
/** An instance of shop */
private Shop shop;
/** A table to store the UI element */
private Table t;
/** Used to scale items by window size */
private float scaleItem;
/** The pause window. */
private Window pause;
/** The ui skin. */
private Skin skin;
/** List of label items */
private List<Label> items;
/** The labelstyle for any labels which are unclicked */
private LabelStyle unClicked;
/** The labelstyle for any labels which are clicked */
private LabelStyle clicked;
/** The Label to hold the item information */
private Label information;
/** The Label to hold the item description */
private Label description;
/** The Label to hold the item amount */
private Label amount;
/** The Label to hold the item amount on player */
private Label amountOnPlayer;
/** The Label title cost */
private Label titleCost;
/** The label holds the total cost */
private Label cost;
/** The label which holds the amount of burn fluids */
private Label burnFluid;
/** The label which holds the amount of cure fluids */
private Label cureFluid;
/** The label which holds the amount of player masks*/
private Label playerMasks;
/** The label which holds the amount of player food */
private Label playerGold;
/** The Image button to leave */
private Image Leave;
/** The Image button to buy */
private Image Buy;
/** The String to hold current equipment clicked*/
private String clickedEquipment;
public ShopScreen(final Main main, final Shop shop, final MapScreen mapScreen) {
this.main = main;
this.shop = shop;
this.t = new Table();
clickedEquipment = "";
unClicked = AssetHandler.FONT_SIZE_60_SUBTITLES_WHITE;
clicked = AssetHandler.FONT_SIZE_60_SUBTITLES_CYAN;
this.skin = AssetHandler.SKIN_UI;
this.t = new Table();
this.t.setFillParent(true);
scaleItem = 1080f/(float)Gdx.graphics.getWidth();
if(scaleItem < 1) {
scaleItem = 1;
}
final Image Title = new Image(new TextureRegionDrawable(new TextureRegion(AssetHandler.MANAGER.get("shop/screen/SHOP.png", Texture.class))));
Title.setScaling(Scaling.fit);
Title.setPosition(50f, main.ui.getHeight()- Title.getHeight() - 50f);
Title.setSize(Title.getWidth(), Title.getHeight());
t.addActor(Title);
playerGold = new Label("PLAYER FOOD: " + Player.getInstance().getFood(), unClicked);
playerGold .setPosition(50f, Title.getY() - 100f);
main.ui.addActor(playerGold);
setCatagories();
Leave = new Image(new TextureRegionDrawable(new TextureRegion(new TextureRegion(AssetHandler.MANAGER.get("shop/screen/LEAVE.png", Texture.class)))));
Leave.setScaling(Scaling.fit);
Leave.setPosition((main.ui.getWidth())-40f-Leave.getWidth(),40f);
Leave.setSize(Leave.getWidth(), Leave.getHeight());
Leave.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
if(!isPaused) {
dispose();
main.ui.clear();
mapScreen.createUI();
mapScreen.pauseGame();
mapScreen.inventory();
main.setScreen(mapScreen);
}
}
public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
if(!isPaused) {
TextureRegionDrawable t = new TextureRegionDrawable((new TextureRegion(AssetHandler.MANAGER.get("shop/screen/LEAVEMOUSE.png", Texture.class))));
Leave.setDrawable(t);
}
}
public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) {
if(!isPaused) {
TextureRegionDrawable t = new TextureRegionDrawable((new TextureRegion(AssetHandler.MANAGER.get("shop/screen/LEAVE.png", Texture.class))));
Leave.setDrawable(t);
}
}
});
t.addActor(Leave);
Buy = new Image(new TextureRegionDrawable((new TextureRegion(AssetHandler.MANAGER.get("shop/screen/BUY.png", Texture.class)))));
Buy.setScaling(Scaling.fit);
Buy.setPosition((main.ui.getWidth())-40f-Buy.getWidth(),40f*2f + Leave.getHeight());
Buy.setSize(Buy.getWidth(), Buy.getHeight());
Buy.setVisible(false);
Buy.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
if(clickedEquipment.equals("PLAYER MASKS") && Player.getInstance().getFood() >= shop.COST_PER_MASK) {
Player.getInstance().setFood(Player.getInstance().getFood()-shop.COST_PER_MASK);
PermanetPlayer.getPermanentPlayerInstance().reduceNumberOfMasks(-shop.MASK_PER_PURCHASE);
setLabels(new String[] {
clickedEquipment,
"AMOUNT OF MASKS.",
PermanetPlayer.getPermanentPlayerInstance().getNumberOfMasks()+"",
shop.COST_PER_MASK+"",
});
}
else if(clickedEquipment.equals("BURN FLUID") && Player.getInstance().getFood() >= shop.COST_PER_FLUID) {
Player.getInstance().setFood(Player.getInstance().getFood()-shop.COST_PER_FLUID);
PermanetPlayer.getPermanentPlayerInstance().reduceBurnSpray( (int) -shop.FLUID_PER_PURCHASE);
setLabels(new String[] {
clickedEquipment,
"AMOUNT OF BURN FLUID.",
PermanetPlayer.getPermanentPlayerInstance().getBurningFluid()+"",
shop.COST_PER_FLUID+"",
});
}
else if(clickedEquipment.equals("CURE FLUID") && Player.getInstance().getFood() >= shop.COST_PER_FLUID) {
Player.getInstance().setFood(Player.getInstance().getFood()-shop.COST_PER_FLUID);
PermanetPlayer.getPermanentPlayerInstance().reduceCureSpray( (int) -shop.FLUID_PER_PURCHASE);
setLabels(new String[] {
clickedEquipment,
"AMOUNT OF CURE FLUID.",
PermanetPlayer.getPermanentPlayerInstance().getHealingFluid()+"",
shop.COST_PER_FLUID+"",
});
}
playerGold.setText("PLAYER FOOD: " + Player.getInstance().getFood());
}
public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
if(!isPaused) {
TextureRegionDrawable t = new TextureRegionDrawable((new TextureRegion(AssetHandler.MANAGER.get("shop/screen/BUYMOUSE.png", Texture.class))));
Buy.setDrawable(t);
}
}
public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) {
if(!isPaused) {
TextureRegionDrawable t = new TextureRegionDrawable((new TextureRegion(AssetHandler.MANAGER.get("shop/screen/BUY.png", Texture.class))));
Buy.setDrawable(t);
}
}
});
t.addActor(Buy);
information = new Label("DESCRIPTION:", unClicked);
information.setPosition((main.ui.getWidth())-40f-Leave.getWidth(), Title.getY());
information.setVisible(false);
main.ui.addActor(information);
description = new Label("VOID", unClicked);
description.setFontScale(0.5f);
description.setPosition((main.ui.getWidth())-40f-Leave.getWidth(), information.getY() - 60f);
description.setVisible(false);
main.ui.addActor(description);
amountOnPlayer = new Label("AMOUNT ON PLAYER:", unClicked);
amountOnPlayer.setPosition((main.ui.getWidth())-40f-Leave.getWidth(), description.getY() - 100f);
amountOnPlayer.setVisible(false);
main.ui.addActor(amountOnPlayer);
amount = new Label("VOID", unClicked);
amount.setFontScale(0.5f);
amount.setPosition((main.ui.getWidth())-40f-Leave.getWidth(), amountOnPlayer.getY() - 60f);
amount.setVisible(false);
main.ui.addActor(amount);
titleCost = new Label("COST OF ITEM:", unClicked);
titleCost .setPosition((main.ui.getWidth())-40f-Leave.getWidth(), amount.getY() - 100f);
titleCost .setVisible(false);
main.ui.addActor(titleCost);
cost= new Label("VOID", unClicked);
cost.setFontScale(0.5f);
cost.setPosition((main.ui.getWidth())-40f-Leave.getWidth(), titleCost.getY() - 60f);
cost.setVisible(false);
main.ui.addActor(cost);
Gdx.input.setInputProcessor(main.ui);
main.ui.addActor(t);
pauseGame();
}
/**
* Set the categories of each of the potential items in the shop.
*/
public void setCatagories() {
float spacing = 80f;
burnFluid = new Label("BURN FLUID", unClicked);
burnFluid.setPosition(50, playerGold.getY() - 200);
burnFluid.setWidth(burnFluid.getWidth() + burnFluid.getWidth());
cureFluid = new Label("CURE FLUID", unClicked);
cureFluid.setPosition(50, burnFluid.getY() - spacing);
cureFluid.setWidth(cureFluid.getWidth() + cureFluid.getWidth());
playerMasks = new Label("PLAYER MASKS", unClicked);
playerMasks.setWidth(playerMasks.getWidth() + playerMasks.getWidth());
playerMasks.setPosition(50, cureFluid.getY() - spacing);
burnFluid.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
if(!isPaused) {
if(burnFluid.getStyle().equals(unClicked)) {
resetLabel();
burnFluid.setStyle(clicked);
setLabels(new String[] {
burnFluid.getText().toString(),
"AMOUNT OF BURN FLUID.",
PermanetPlayer.getPermanentPlayerInstance().getBurningFluid()+"",
shop.COST_PER_FLUID+"",
});
}
else {
burnFluid.setStyle(unClicked);
updateUI(false);
}
}
}
});
cureFluid.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
if(!isPaused) {
if(cureFluid.getStyle().equals(unClicked)) {
resetLabel();
cureFluid.setStyle(clicked);
setLabels(new String[] {
cureFluid.getText().toString(),
"AMOUNT OF CURE FLUID.",
PermanetPlayer.getPermanentPlayerInstance().getHealingFluid()+"",
shop.COST_PER_FLUID+"",
});
}
else {
cureFluid.setStyle(unClicked);
updateUI(false);
}
}
}
});
playerMasks.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
if(!isPaused) {
if(playerMasks.getStyle().equals(unClicked)) {
resetLabel();
playerMasks.setStyle(clicked);
setLabels(new String[] {
playerMasks.getText().toString(),
"AMOUNT OF MASKS.",
PermanetPlayer.getPermanentPlayerInstance().getNumberOfMasks()+"",
shop.COST_PER_MASK+"",
});
}
else {
playerMasks.setStyle(unClicked);
updateUI(false);
}
}
}
});
main.ui.addActor(burnFluid);
main.ui.addActor(cureFluid);
main.ui.addActor(playerMasks);
}
/**
* Reset the labels and make them invisible
*/
public void resetLabel() {
burnFluid.setStyle(unClicked);
cureFluid.setStyle(unClicked);
playerMasks.setStyle(unClicked);
updateUI(false);
clickedEquipment = "";
}
/**
* Set the labels of the menu.
* @param values an array of string values
*/
public void setLabels(String[] values) {
clickedEquipment = values[0];
description.setText(values[1]);
amount.setText("AMOUNT: " + values[2]);
cost.setText(values[3]+" FOOD");
updateUI(true);
}
@Override
public void show() {
// TODO Auto-generated method stub
}
@Override
public void render(float delta) {
inputHandler();
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(0, 0, 0, 1);
main.ui.act(delta);
main.ui.draw();
}
/**
* InputHandler for the shop screen to allow exit.
*/
public void inputHandler() {
if(Gdx.input.isKeyJustPressed(Keys.ESCAPE)) {
togglePaused();
pause.setVisible(isPaused);
}
}
@Override
public void resize(int width, int height) {
main.ui.getViewport().update(width, height);
main.ui.getViewport().apply();
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void hide() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
/**
* The window for the pause game.
*/
public void pauseGame() {
/*
* This method is used to create the window elements for the pause menu
*
* Creates a window and then has two different text buttons within
*
* - RESUME (hides window when clicked and allows movement)
* - EXIT (exits the game)
*
* This is done through add listeners to each of the the buttons
*
* The window containing all the values is called pause
*/
float windowWidth = 200*scaleItem, windowHeight = 200*scaleItem;
pause = new Window("", skin);
pause.setMovable(false); //So the user can't move the window
//final TextButton button1 = new TextButton("Resume", skin);
final Label button1 = new Label("RESUME", AssetHandler.FONT_SIZE_60_SUBTITLES_WHITE);
button1.setFontScale(24f/60f);
button1.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
togglePaused();
pause.setVisible(false);
}
});
Label button2 = new Label("EXIT", AssetHandler.FONT_SIZE_60_SUBTITLES_WHITE);
button2.setFontScale(24f/60f);
button2.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
System.exit(0);
}
});
pause.add(button1).row();
pause.row();
pause.add(button2).row();
pause.pack(); //Important! Correctly scales the window after adding new elements
//Centre window on screen.
pause.setBounds(((main.ui.getWidth() - windowWidth*scaleItem ) / 2),
(main.ui.getHeight() - windowHeight*scaleItem) / 2, windowWidth , windowHeight );
//Sets the menu as invisible
isPaused = false;
pause.setVisible(false);
pause.setSize(pause.getWidth()*scaleItem, pause.getHeight()*scaleItem);
//Adds it to the UI Screen.
main.ui.addActor(pause);
}
/**
* Toggle isPaused variable.
*/
private void togglePaused() {
isPaused = !isPaused;
}
/**
* Update all the UI elements
* @param hit if a ui element has been hit.
*/
public void updateUI(Boolean hit) {
information.setVisible(hit);
description.setVisible(hit);
amount.setVisible(hit);
amountOnPlayer.setVisible(hit);
Buy.setVisible(hit);
titleCost.setVisible(hit);
cost.setVisible(hit);
}
} |
package com.soa.ws;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.9-b130926.1035
* Generated source version: 2.2
*
*/
@WebServiceClient(name = "VacationImplService", targetNamespace = "http://ws.soa.com/", wsdlLocation = "http://localhost:8080/vacation?wsdl")
public class VacationImplService
extends Service
{
private final static URL VACATIONIMPLSERVICE_WSDL_LOCATION;
private final static WebServiceException VACATIONIMPLSERVICE_EXCEPTION;
private final static QName VACATIONIMPLSERVICE_QNAME = new QName("http://ws.soa.com/", "VacationImplService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("http://localhost:8080/vacation?wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
VACATIONIMPLSERVICE_WSDL_LOCATION = url;
VACATIONIMPLSERVICE_EXCEPTION = e;
}
public VacationImplService() {
super(__getWsdlLocation(), VACATIONIMPLSERVICE_QNAME);
}
public VacationImplService(WebServiceFeature... features) {
super(__getWsdlLocation(), VACATIONIMPLSERVICE_QNAME, features);
}
public VacationImplService(URL wsdlLocation) {
super(wsdlLocation, VACATIONIMPLSERVICE_QNAME);
}
public VacationImplService(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, VACATIONIMPLSERVICE_QNAME, features);
}
public VacationImplService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public VacationImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
* @return
* returns Vacation
*/
@WebEndpoint(name = "VacationImplPort")
public Vacation getVacationImplPort() {
return super.getPort(new QName("http://ws.soa.com/", "VacationImplPort"), Vacation.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns Vacation
*/
@WebEndpoint(name = "VacationImplPort")
public Vacation getVacationImplPort(WebServiceFeature... features) {
return super.getPort(new QName("http://ws.soa.com/", "VacationImplPort"), Vacation.class, features);
}
private static URL __getWsdlLocation() {
if (VACATIONIMPLSERVICE_EXCEPTION!= null) {
throw VACATIONIMPLSERVICE_EXCEPTION;
}
return VACATIONIMPLSERVICE_WSDL_LOCATION;
}
}
|
/**
*
*/
package com.oriaxx77.javaplay.gof.flyweight;
import java.util.HashMap;
import java.util.Map;
import com.oriaxx77.javaplay.gof.GofExample;
/**
* Factory to create and store models. It should be the only point to
* get {@link Model} objects.
* @author BagyuraI
*/
@GofExample(pattern="Flyweight", stereotype="FlyweightFactory")
public class ModelFactory
{
/**
* Model repo
*/
private Map<String,Model> models = new HashMap<String,Model>();
/**
* Creates a model factory with the available models.
*/
public ModelFactory( )
{
models.put( "halberd" , new WeaponModel( "halberd") );
models.put( "scimitar" , new WeaponModel( "scimitar") );
}
/**
* Get a model from the repo.
* @param modelKey Key of the model
* @return Model or null if there is no model under the provided key.
*/
public Model getModel( String modelKey )
{
return models.get( modelKey );
}
}
|
package demo.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int stuNo;
private String stuName;
private int stuAge;
private String graName;
private boolean stuSex;
}
|
package com.Premium.entity;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import lombok.Data;
import lombok.NonNull;
@Entity
@Table(name = "Task")
@Data
public class TaskEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long taskId;
@ManyToOne
@JoinColumn(name = "statusFlowId")
private StatusFlowEntity currentStatus;
@Column
@NonNull
private String taskDescription;
@Column
private Date taskCreated_at;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "projectId", nullable = false)
private ProjectEntity project;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "employeeId", nullable = false)
private EmployeeEntity assignedTo;
@OneToMany
private List<FilesEntity> filesAttached;
@OneToMany
private List<UpdatesEntity> updates;
@OneToMany
private List<CommentsEntity> comments;
}
|
package lettieri.masstexter.activities;
import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import lettieri.masstexter.models.Contact;
import lettieri.masstexter.R;
public class SendMessage extends AppCompatActivity {
public static final String EXTRA_GROUP_IDS = "EXTRA_GROUP_IDS";
public static final String EXTRA_GROUP_NAME = "EXTRA_GROUP_NAME";
// arbitrary number to determine which permission was granted
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 466;
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 467;
private ArrayList<Contact> contacts = new ArrayList<>();
private ArrayAdapter<Contact> adapter;
private ListView lstContacts;
private Button btnSend;
private EditText etMessage;
private TextView txtCount;
private TextView txtName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_message);
findViews();
txtName.setText(getIntent().getStringExtra(EXTRA_GROUP_NAME));
// this will only be called if the user is on this screen and then manually goes in and revokes permission to the read contacts (because they granted it on the previous screen
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
} else {
addContactsByGroups();
}
setUp();
}
/***
* Find the views that are associated with this layout
*/
private void findViews() {
lstContacts = (ListView)findViewById(R.id.lstContacts);
btnSend = (Button)findViewById(R.id.btnSend);
etMessage = (EditText)findViewById(R.id.etMessage);
txtCount = (TextView)findViewById(R.id.txtCount);
txtName = (TextView)findViewById(R.id.txtName);
}
/***
* Setup the list adapter and click listeners
*/
private void setUp() {
adapter = new ArrayAdapter<Contact>(this, android.R.layout.simple_list_item_1, contacts);
lstContacts.setAdapter(adapter);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
}
/***
* Grab the text from teh edit text and
* send the message to all contacts in the group
* it then clears the edit text
*/
private void sendMessage() {
// this will only be called if the user is on this screen and then manually goes in and revokes permission to the read contacts (because they granted it on the previous screen
if(ContextCompat.checkSelfPermission(SendMessage.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(SendMessage.this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
} else {
String message = etMessage.getText().toString();
sendMessage(message);
etMessage.getText().clear();
}
}
/***
* send the message to all contacts in the group
* @param message is the message to send to everyone
*/
private void sendMessage(String message) {
if(message == null || message.isEmpty()) {
Toast.makeText(this, "Cannot send empty or null message", Toast.LENGTH_LONG).show();
} else {
for(Contact c: contacts) {
c.sendMessage(message);
}
}
}
/***
* Uses the group id of the intent
*/
private void addContactsByGroups() {
ArrayList<String> ids = getIntent().getStringArrayListExtra(EXTRA_GROUP_IDS);
for(String id: ids) {
addContactsByGroup(id);
}
}
/***
* Given a group id it will query for the contact ids in that group
* From that result it will query for users by id and add them to the objects contacts variable
* @param groupId is the id of the group to add the users by
*/
private void addContactsByGroup(String groupId) {
Cursor contactInGroupCursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID},
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "= ?" + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'",
new String[] {groupId}, null);
if(contactInGroupCursor!=null){
while(contactInGroupCursor.moveToNext()){
String contactId = contactInGroupCursor.getString(0);
addContactsById(contactId);
}
updateCount();
contactInGroupCursor.close();
}
}
/***
* Adds all the contacts associated with the given contact id to the objects contacts array
* @param contactId is the id of thed contact
*/
private void addContactsById(String contactId) {
Cursor contactCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[] { contactId }, null);
if(contactCursor != null) {
while(contactCursor.moveToNext()) {
contacts.add(new Contact(contactId, contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)), contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))));
}
contactCursor.close();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch(requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
addContactsByGroups();
adapter.notifyDataSetInvalidated();
} else {
Toast.makeText(this, "This app requires contact permission, close the app and reopen to allow", Toast.LENGTH_LONG).show();
}
return;
case MY_PERMISSIONS_REQUEST_SEND_SMS:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
sendMessage();
} else {
Toast.makeText(this, "This app requires permission to send the message, try sending the message again and grant permission", Toast.LENGTH_LONG).show();
}
return;
}
}
/***
* Sets the count to the size of the list of contacts surrounded by ()
*/
private void updateCount() {
txtCount.setText("(" + contacts.size() + ")");
}
}
|
package com.app.myapplication.remote;
import android.app.Person;
import com.app.myapplication.pojo.Empleado;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
public interface PersonaService {
@GET("/employees")
Call<List<Empleado>> getEmpleados();
@GET("/employees/{id}")
Call<List<Empleado>> getEmpleadosById(@Path("id") Long id);
@POST("/employees")
Call<Empleado> addEmpleado (@Body Empleado empleado);
@PUT("/employees")
Call<Empleado> updateEmpleado(@Body Empleado empleado);
@DELETE("/employees/{id}")
Call<Empleado> deleteEmpleado(@Path("id") Long id);
}
|
package com.jpa.servises;
import com.jpa.entity.Station;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import java.util.List;
/**
* Created by Дарья on 05.03.2015.
*/
public class StationServices {
public EntityManager em = Persistence.createEntityManagerFactory("COLIBRI").createEntityManager();
public Station add(Station station){
em.getTransaction().begin();
Station stationFromDB = em.merge(station);
em.getTransaction().commit();
return stationFromDB;
}
public void delete(long id){
em.getTransaction().begin();
em.remove(get(id));
em.getTransaction().commit();
}
public Station get(long id){
return em.find(Station.class, id);
}
public void update(Station station){
em.getTransaction().begin();
em.merge(station);
em.getTransaction().commit();
}
public List<Station> getAll(){
TypedQuery<Station> namedQuery = em.createNamedQuery("Station.getAll", Station.class);
return namedQuery.getResultList();
}
}
|
//package eric.keys;
//
//public class FirebaseUIAdapter {
// FirebaseRecyclerOptions<Chat> options =
// new FirebaseRecyclerOptions.Builder<Chat>()
// .setQuery(query, Chat.class)
// .build();
//}
|
package com.sunny.netty.chat.codec;
import com.sunny.netty.chat.protocol.PacketCodec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
/**
* <Description> <br>
*
* @author Sunny<br>
* @version 1.0<br>
* @taskId: <br>
* @createDate 2018/10/26 16:41 <br>
* @see com.sunny.netty.chat.codec <br>
*/
public class Spliter extends LengthFieldBasedFrameDecoder {
private static final int LENGTH_FIELD_OFFSET = 7;
private static final int LENGTH_FIELD_LENGTH = 4;
public Spliter() {
super(Integer.MAX_VALUE, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH);
}
@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
if (in.getInt(in.readerIndex()) != PacketCodec.MAGIC_NUMBER) {
ctx.channel().close();
return null;
}
return super.decode(ctx, in);
}
}
|
package app.akeorcist.deviceinformation.application;
import android.app.Application;
import app.akeorcist.deviceinformation.network.NetworkManager;
import app.akeorcist.deviceinformation.utility.SnackBar;
/**
* Created by Ake on 2/25/2015.
*/
public class DDIApplication extends Application {
private static SnackBar snackBar = new SnackBar();
private static NetworkManager networkManager = new NetworkManager();
@Override
public void onCreate() {
super.onCreate();
}
public static NetworkManager getNetworkInstance() {
return networkManager;
}
public static SnackBar getSnackBar() {
return snackBar;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.